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/type/component.rb
lib/puppet/type/component.rb
# frozen_string_literal: true require_relative '../../puppet' require_relative '../../puppet/type' require_relative '../../puppet/transaction' Puppet::Type.newtype(:component) do include Enumerable newparam(:name) do desc "The name of the component. Generally optional." isnamevar end # Override how parameters are handled so that we support the extra # parameters that are used with defined resource types. def [](param) if self.class.valid_parameter?(param) super else @extra_parameters[param.to_sym] end end # Override how parameters are handled so that we support the extra # parameters that are used with defined resource types. def []=(param, value) if self.class.valid_parameter?(param) super else @extra_parameters[param.to_sym] = value end end # Initialize a new component def initialize(*args) @extra_parameters = {} super end # Component paths are special because they function as containers. def pathbuilder if reference.type == "Class" myname = reference.title else myname = reference.to_s end p = parent if p [p.pathbuilder, myname] else [myname] end end def ref reference.to_s end # We want our title to just be the whole reference, rather than @title. def title ref end def title=(str) @reference = Puppet::Resource.new(str) end def refresh catalog.adjacent(self).each do |child| if child.respond_to?(:refresh) child.refresh child.log "triggering refresh" end end end def to_s reference.to_s end # Overrides the default implementation to do nothing. # This type contains data from class/define parameters, but does # not have actual parameters or properties at the Type level. We can # simply ignore anything flagged as sensitive here, since any # contained resources will handle that sensitivity themselves. There # is no risk of this information leaking into reports, since no # Component instances survive the graph transmutation. # def set_sensitive_parameters(sensitive_parameters) end private attr_reader :reference end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/group.rb
lib/puppet/type/group.rb
# frozen_string_literal: true require 'etc' require_relative '../../puppet/property/keyvalue' require_relative '../../puppet/parameter/boolean' module Puppet Type.newtype(:group) do @doc = "Manage groups. On most platforms this can only create groups. Group membership must be managed on individual users. On some platforms such as OS X, group membership is managed as an attribute of the group, not the user record. Providers must have the feature 'manages_members' to manage the 'members' property of a group record." feature :manages_members, "For directories where membership is an attribute of groups not users." feature :manages_aix_lam, "The provider can manage AIX Loadable Authentication Module (LAM) system." feature :system_groups, "The provider allows you to create system groups with lower GIDs." feature :manages_local_users_and_groups, "Allows local groups to be managed on systems that also use some other remote Name Switch Service (NSS) method of managing accounts." ensurable do desc "Create or remove the group." newvalue(:present) do provider.create end newvalue(:absent) do provider.delete end defaultto :present end newproperty(:gid) do desc "The group ID. Must be specified numerically. If no group ID is specified when creating a new group, then one will be chosen automatically according to local system standards. This will likely result in the same group having different GIDs on different systems, which is not recommended. On Windows, this property is read-only and will return the group's security identifier (SID)." def retrieve provider.gid end def sync if should == :absent raise Puppet::DevError, _("GID cannot be deleted") else provider.gid = should end end munge do |gid| case gid when String if gid =~ /^[-0-9]+$/ gid = Integer(gid) else self.fail _("Invalid GID %{gid}") % { gid: gid } end when Symbol unless gid == :absent devfail "Invalid GID #{gid}" end end return gid end end newproperty(:members, :array_matching => :all, :required_features => :manages_members) do desc "The members of the group. For platforms or directory services where group membership is stored in the group objects, not the users. This parameter's behavior can be configured with `auth_membership`." def change_to_s(currentvalue, newvalue) newvalue = actual_should(currentvalue, newvalue) currentvalue = currentvalue.join(",") if currentvalue != :absent newvalue = newvalue.join(",") super(currentvalue, newvalue) end def insync?(current) if provider.respond_to?(:members_insync?) return provider.members_insync?(current, @should) end super(current) end def is_to_s(currentvalue) # rubocop:disable Naming/PredicateName if provider.respond_to?(:members_to_s) currentvalue = '' if currentvalue.nil? currentvalue = currentvalue.is_a?(Array) ? currentvalue : currentvalue.split(',') return provider.members_to_s(currentvalue) end super(currentvalue) end def should_to_s(newvalue) is_to_s(actual_should(retrieve, newvalue)) end # Calculates the actual should value given the current and # new values. This is only used in should_to_s and change_to_s # to fix the change notification issue reported in PUP-6542. def actual_should(currentvalue, newvalue) currentvalue = munge_members_value(currentvalue) newvalue = munge_members_value(newvalue) if @resource[:auth_membership] newvalue.uniq.sort else (currentvalue + newvalue).uniq.sort end end # Useful helper to handle the possible property value types that we can # both pass-in and return. It munges the value into an array def munge_members_value(value) return [] if value == :absent return value.split(',') if value.is_a?(String) value end validate do |value| if provider.respond_to?(:member_valid?) return provider.member_valid?(value) end end end newparam(:auth_membership, :boolean => true, :parent => Puppet::Parameter::Boolean) do desc "Configures the behavior of the `members` parameter. * `false` (default) --- The provided list of group members is partial, and Puppet **ignores** any members that aren't listed there. * `true` --- The provided list of of group members is comprehensive, and Puppet **purges** any members that aren't listed there." defaultto false end newparam(:name) do desc "The group name. While naming limitations vary by operating system, it is advisable to restrict names to the lowest common denominator, which is a maximum of 8 characters beginning with a letter. Note that Puppet considers group names to be case-sensitive, regardless of the platform's own rules; be sure to always use the same case when referring to a given group." isnamevar end newparam(:allowdupe, :boolean => true, :parent => Puppet::Parameter::Boolean) do desc "Whether to allow duplicate GIDs." defaultto false end newparam(:ia_load_module, :required_features => :manages_aix_lam) do desc "The name of the I&A module to use to manage this group. This should be set to `files` if managing local groups." end newproperty(:attributes, :parent => Puppet::Property::KeyValue, :required_features => :manages_aix_lam) do desc "Specify group AIX attributes, as an array of `'key=value'` strings. This parameter's behavior can be configured with `attribute_membership`." self.log_only_changed_or_new_keys = true def membership :attribute_membership end def delimiter " " end end newparam(:attribute_membership) do desc "AIX only. Configures the behavior of the `attributes` parameter. * `minimum` (default) --- The provided list of attributes is partial, and Puppet **ignores** any attributes that aren't listed there. * `inclusive` --- The provided list of attributes is comprehensive, and Puppet **purges** any attributes that aren't listed there." newvalues(:inclusive, :minimum) defaultto :minimum end newparam(:system, :boolean => true, :parent => Puppet::Parameter::Boolean) do desc "Whether the group is a system group with lower GID." defaultto false end newparam(:forcelocal, :boolean => true, :required_features => :manages_local_users_and_groups, :parent => Puppet::Parameter::Boolean) do desc "Forces the management of local accounts when accounts are also being managed by some other Name Switch Service (NSS). For AIX, refer to the `ia_load_module` parameter. This option relies on your operating system's implementation of `luser*` commands, such as `luseradd` , `lgroupadd`, and `lusermod`. The `forcelocal` option could behave unpredictably in some circumstances. If the tools it depends on are not available, it might have no effect at all." defaultto false end # This method has been exposed for puppet to manage users and groups of # files in its settings and should not be considered available outside of # puppet. # # (see Puppet::Settings#service_group_available?) # # @return [Boolean] if the group exists on the system # @api private def exists? provider.exists? end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/stage.rb
lib/puppet/type/stage.rb
# frozen_string_literal: true Puppet::Type.newtype(:stage) do desc "A resource type for creating new run stages. Once a stage is available, classes can be assigned to it by declaring them with the resource-like syntax and using [the `stage` metaparameter](https://puppet.com/docs/puppet/latest/metaparameter.html#stage). Note that new stages are not useful unless you also declare their order in relation to the default `main` stage. A complete run stage example: stage { 'pre': before => Stage['main'], } class { 'apt-updates': stage => 'pre', } Individual resources cannot be assigned to run stages; you can only set stages for classes." newparam :name do desc "The name of the stage. Use this as the value for the `stage` metaparameter when assigning classes to this stage." end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/package.rb
lib/puppet/type/package.rb
# coding: utf-8 # frozen_string_literal: true # Define the different packaging systems. Each package system is implemented # in a module, which then gets used to individually extend each package object. # This allows packages to exist on the same machine using different packaging # systems. require_relative '../../puppet/parameter/package_options' require_relative '../../puppet/parameter/boolean' module Puppet Type.newtype(:package) do @doc = "Manage packages. There is a basic dichotomy in package support right now: Some package types (such as yum and apt) can retrieve their own package files, while others (such as rpm and sun) cannot. For those package formats that cannot retrieve their own files, you can use the `source` parameter to point to the correct file. Puppet will automatically guess the packaging format that you are using based on the platform you are on, but you can override it using the `provider` parameter; each provider defines what it requires in order to function, and you must meet those requirements to use a given provider. You can declare multiple package resources with the same `name` as long as they have unique titles, and specify different providers and commands. Note that you must use the _title_ to make a reference to a package resource; `Package[<NAME>]` is not a synonym for `Package[<TITLE>]` like it is for many other resource types. **Autorequires:** If Puppet is managing the files specified as a package's `adminfile`, `responsefile`, or `source`, the package resource will autorequire those files." feature :reinstallable, "The provider can reinstall packages.", :methods => [:reinstall] feature :installable, "The provider can install packages.", :methods => [:install] feature :uninstallable, "The provider can uninstall packages.", :methods => [:uninstall] feature :upgradeable, "The provider can upgrade to the latest version of a package. This feature is used by specifying `latest` as the desired value for the package.", :methods => [:update, :latest] feature :purgeable, "The provider can purge packages. This generally means that all traces of the package are removed, including existing configuration files. This feature is thus destructive and should be used with the utmost care.", :methods => [:purge] feature :versionable, "The provider is capable of interrogating the package database for installed version(s), and can select which out of a set of available versions of a package to install if asked." feature :version_ranges, "The provider can ensure version ranges." feature :holdable, "The provider is capable of placing packages on hold such that they are not automatically upgraded as a result of other package dependencies unless explicit action is taken by a user or another package.", :methods => [:hold, :unhold] feature :install_only, "The provider accepts options to only install packages never update (kernels, etc.)" feature :install_options, "The provider accepts options to be passed to the installer command." feature :uninstall_options, "The provider accepts options to be passed to the uninstaller command." feature :disableable, "The provider can disable packages. This feature is used by specifying `disabled` as the desired value for the package.", :methods => [:disable] feature :supports_flavors, "The provider accepts flavors, which are specific variants of packages." feature :package_settings, "The provider accepts package_settings to be ensured for the given package. The meaning and format of these settings is provider-specific.", :methods => [:package_settings_insync?, :package_settings, :package_settings=] feature :virtual_packages, "The provider accepts virtual package names for install and uninstall." feature :targetable, "The provider accepts a targeted package management command." ensurable do desc <<-EOT What state the package should be in. On packaging systems that can retrieve new packages on their own, you can choose which package to retrieve by specifying a version number or `latest` as the ensure value. On packaging systems that manage configuration files separately from "normal" system files, you can uninstall config files by specifying `purged` as the ensure value. This defaults to `installed`. Version numbers must match the full version to install, including release if the provider uses a release moniker. For example, to install the bash package from the rpm `bash-4.1.2-29.el6.x86_64.rpm`, use the string `'4.1.2-29.el6'`. On supported providers, version ranges can also be ensured. For example, inequalities: `<2.0.0`, or intersections: `>1.0.0 <2.0.0`. EOT attr_accessor :latest newvalue(:present, :event => :package_installed) do provider.install end newvalue(:absent, :event => :package_removed) do provider.uninstall end newvalue(:purged, :event => :package_purged, :required_features => :purgeable) do provider.purge end newvalue(:disabled, :required_features => :disableable) do provider.disable end # Alias the 'present' value. aliasvalue(:installed, :present) newvalue(:latest, :required_features => :upgradeable) do # Because yum always exits with a 0 exit code, there's a retrieve # in the "install" method. So, check the current state now, # to compare against later. current = retrieve begin provider.update rescue => detail self.fail Puppet::Error, _("Could not update: %{detail}") % { detail: detail }, detail end if current == :absent :package_installed else :package_changed end end newvalue(/./, :required_features => :versionable) do begin provider.install rescue => detail self.fail Puppet::Error, _("Could not update: %{detail}") % { detail: detail }, detail end if retrieve == :absent :package_installed else :package_changed end end defaultto :installed # Override the parent method, because we've got all kinds of # funky definitions of 'in sync'. def insync?(is) @lateststamp ||= (Time.now.to_i - 1000) # Iterate across all of the should values, and see how they # turn out. @should.each { |should| case should when :present return true unless [:absent, :purged, :disabled].include?(is) when :latest # Short-circuit packages that are not present return false if is == :absent || is == :purged # Don't run 'latest' more than about every 5 minutes if @latest and ((Time.now.to_i - @lateststamp) / 60) < 5 # self.debug "Skipping latest check" else begin @latest = provider.latest @lateststamp = Time.now.to_i rescue => detail error = Puppet::Error.new(_("Could not get latest version: %{detail}") % { detail: detail }) error.set_backtrace(detail.backtrace) raise error end end case when is.is_a?(Array) && is.include?(@latest) return true when is == @latest return true when is == :present # This will only happen on packaging systems # that can't query versions. return true else debug "#{@resource.name} #{is.inspect} is installed, latest is #{@latest.inspect}" end when :absent return true if is == :absent || is == :purged when :purged return true if is == :purged # this handles version number matches and # supports providers that can have multiple versions installed when *Array(is) return true else # We have version numbers, and no match. If the provider has # additional logic, run it here. return provider.insync?(is) if provider.respond_to?(:insync?) end } false end # This retrieves the current state. LAK: I think this method is unused. def retrieve provider.properties[:ensure] end # Provide a bit more information when logging upgrades. def should_to_s(newvalue = @should) if @latest super(@latest) else super(newvalue) end end def change_to_s(currentvalue, newvalue) # Handle transitioning from any previous state to 'purged' return 'purged' if newvalue == :purged # Check for transitions from nil/purged/absent to 'created' (any state that is not absent and not purged) return 'created' if (currentvalue.nil? || currentvalue == :absent || currentvalue == :purged) && (newvalue != :absent && newvalue != :purged) # The base should handle the normal property transitions super(currentvalue, newvalue) end end newparam(:name) do desc "The package name. This is the name that the packaging system uses internally, which is sometimes (especially on Solaris) a name that is basically useless to humans. If a package goes by several names, you can use a single title and then set the name conditionally: # In the 'openssl' class $ssl = $os['name'] ? { solaris => SMCossl, default => openssl } package { 'openssl': ensure => installed, name => $ssl, } ... $ssh = $os['name'] ? { solaris => SMCossh, default => openssh } package { 'openssh': ensure => installed, name => $ssh, require => Package['openssl'], } " isnamevar validate do |value| unless value.is_a?(String) raise ArgumentError, _("Name must be a String not %{klass}") % { klass: value.class } end end end # We call providify here so that we can set provider as a namevar. # Normally this method is called after newtype finishes constructing this # Type class. providify paramclass(:provider).isnamevar def self.parameters_to_include [:provider] end # Specify a targeted package management command. newparam(:command, :required_features => :targetable) do desc <<-EOT The targeted command to use when managing a package: package { 'mysql': provider => gem, } package { 'mysql-opt': name => 'mysql', provider => gem, command => '/opt/ruby/bin/gem', } Each provider defines a package management command and uses the first instance of the command found in the PATH. Providers supporting the targetable feature allow you to specify the absolute path of the package management command. Specifying the absolute path is useful when multiple instances of the command are installed, or the command is not in the PATH. EOT isnamevar defaultto :default end # We have more than one namevar, so we need title_patterns. # However, we cheat and set the patterns to map to name only # and completely ignore provider (and command, for targetable providers). # So far, the logic that determines uniqueness appears to just # "Do The Right Thing™" when provider (and command) are explicitly set. # # The following resources will be seen as unique by puppet: # # # Uniqueness Key: ['mysql', nil] # package {'mysql': } # # # Uniqueness Key: ['mysql', 'gem', nil] # package {'gem-mysql': # name => 'mysql, # provider => gem, # } # # # Uniqueness Key: ['mysql', 'gem', '/opt/ruby/bin/gem'] # package {'gem-mysql-opt': # name => 'mysql, # provider => gem # command => '/opt/ruby/bin/gem', # } # # This does not handle the case where providers like 'yum' and 'rpm' should # clash. Also, declarations that implicitly use the default provider will # clash with those that explicitly use the default. def self.title_patterns # This is the default title pattern for all types, except hard-wired to # set only name. [[/(.*)/m, [[:name]]]] end newproperty(:package_settings, :required_features => :package_settings) do desc "Settings that can change the contents or configuration of a package. The formatting and effects of package_settings are provider-specific; any provider that implements them must explain how to use them in its documentation. (Our general expectation is that if a package is installed but its settings are out of sync, the provider should re-install that package with the desired settings.) An example of how package_settings could be used is FreeBSD's port build options --- a future version of the provider could accept a hash of options, and would reinstall the port if the installed version lacked the correct settings. package { 'www/apache22': package_settings => { 'SUEXEC' => false } } Again, check the documentation of your platform's package provider to see the actual usage." validate do |value| if provider.respond_to?(:package_settings_validate) provider.package_settings_validate(value) else super(value) end end munge do |value| if provider.respond_to?(:package_settings_munge) provider.package_settings_munge(value) else super(value) end end def insync?(is) provider.package_settings_insync?(should, is) end def should_to_s(newvalue) if provider.respond_to?(:package_settings_should_to_s) provider.package_settings_should_to_s(should, newvalue) else super(newvalue) end end def is_to_s(currentvalue) # rubocop:disable Naming/PredicateName if provider.respond_to?(:package_settings_is_to_s) provider.package_settings_is_to_s(should, currentvalue) else super(currentvalue) end end def change_to_s(currentvalue, newvalue) if provider.respond_to?(:package_settings_change_to_s) provider.package_settings_change_to_s(currentvalue, newvalue) else super(currentvalue, newvalue) end end end newproperty(:flavor, :required_features => :supports_flavors) do desc "OpenBSD and DNF modules support 'flavors', which are further specifications for which type of package you want." validate do |value| if [:disabled, "disabled"].include?(@resource[:ensure]) && value raise ArgumentError, _('Cannot have both `ensure => disabled` and `flavor`') end end end newparam(:source) do desc "Where to find the package file. This is mostly used by providers that don't automatically download packages from a central repository. (For example: the `yum` provider ignores this attribute, `apt` provider uses it if present and the `rpm` and `dpkg` providers require it.) Different providers accept different values for `source`. Most providers accept paths to local files stored on the target system. Some providers may also accept URLs or network drive paths. Puppet will not automatically retrieve source files for you, and usually just passes the value of `source` to the package installation command. You can use a `file` resource if you need to manually copy package files to the target system." validate do |value| provider.validate_source(value) end end newparam(:instance) do desc "A read-only parameter set by the package." end newparam(:status) do desc "A read-only parameter set by the package." end newparam(:adminfile) do desc "A file containing package defaults for installing packages. This attribute is only used on Solaris. Its value should be a path to a local file stored on the target system. Solaris's package tools expect either an absolute file path or a relative path to a file in `/var/sadm/install/admin`. The value of `adminfile` will be passed directly to the `pkgadd` or `pkgrm` command with the `-a <ADMINFILE>` option." end newparam(:responsefile) do desc "A file containing any necessary answers to questions asked by the package. This is currently used on Solaris and Debian. The value will be validated according to system rules, but it should generally be a fully qualified path." end newparam(:configfiles) do desc "Whether to keep or replace modified config files when installing or upgrading a package. This only affects the `apt` and `dpkg` providers." defaultto :keep newvalues(:keep, :replace) end newparam(:category) do desc "A read-only parameter set by the package." end newparam(:platform) do desc "A read-only parameter set by the package." end newparam(:root) do desc "A read-only parameter set by the package." end newparam(:vendor) do desc "A read-only parameter set by the package." end newparam(:description) do desc "A read-only parameter set by the package." end newparam(:allowcdrom) do desc "Tells apt to allow cdrom sources in the sources.list file. Normally apt will bail if you try this." newvalues(:true, :false) end newparam(:enable_only, :boolean => false, :parent => Puppet::Parameter::Boolean) do desc <<-EOT Tells `dnf module` to only enable a specific module, instead of installing its default profile. Modules with no default profile will be enabled automatically without the use of this parameter. Conflicts with the `flavor` property, which selects a profile to install. EOT defaultto false validate do |value| if [true, :true, "true"].include?(value) && @resource[:flavor] raise ArgumentError, _('Cannot have both `enable_only => true` and `flavor`') end if [:disabled, "disabled"].include?(@resource[:ensure]) raise ArgumentError, _('Cannot have both `ensure => disabled` and `enable_only => true`') end end end newparam(:install_only, :boolean => false, :parent => Puppet::Parameter::Boolean, :required_features => :install_only) do desc <<-EOT It should be set for packages that should only ever be installed, never updated. Kernels in particular fall into this category. EOT defaultto false end newparam(:install_options, :parent => Puppet::Parameter::PackageOptions, :required_features => :install_options) do desc <<-EOT An array of additional options to pass when installing a package. These options are package-specific, and should be documented by the software vendor. One commonly implemented option is `INSTALLDIR`: package { 'mysql': ensure => installed, source => 'N:/packages/mysql-5.5.16-winx64.msi', install_options => [ '/S', { 'INSTALLDIR' => 'C:\\mysql-5.5' } ], } Each option in the array can either be a string or a hash, where each key and value pair are interpreted in a provider specific way. Each option will automatically be quoted when passed to the install command. With Windows packages, note that file paths in an install option must use backslashes. (Since install options are passed directly to the installation command, forward slashes won't be automatically converted like they are in `file` resources.) Note also that backslashes in double-quoted strings _must_ be escaped and backslashes in single-quoted strings _can_ be escaped. EOT end newparam(:uninstall_options, :parent => Puppet::Parameter::PackageOptions, :required_features => :uninstall_options) do desc <<-EOT An array of additional options to pass when uninstalling a package. These options are package-specific, and should be documented by the software vendor. For example: package { 'VMware Tools': ensure => absent, uninstall_options => [ { 'REMOVE' => 'Sync,VSS' } ], } Each option in the array can either be a string or a hash, where each key and value pair are interpreted in a provider specific way. Each option will automatically be quoted when passed to the uninstall command. On Windows, this is the **only** place in Puppet where backslash separators should be used. Note that backslashes in double-quoted strings _must_ be double-escaped and backslashes in single-quoted strings _may_ be double-escaped. EOT end newparam(:allow_virtual, :boolean => true, :parent => Puppet::Parameter::Boolean, :required_features => :virtual_packages) do desc 'Specifies if virtual package names are allowed for install and uninstall.' defaultto do provider_class = provider.class if provider_class.respond_to?(:defaultto_allow_virtual) provider_class.defaultto_allow_virtual else true end end end autorequire(:file) do autos = [] [:responsefile, :adminfile].each { |param| val = self[param] if val autos << val end } source = self[:source] if source && absolute_path?(source) autos << source end autos end # This only exists for testing. def clear obj = @parameters[:ensure] if obj obj.latest = nil end end # The 'query' method returns a hash of info if the package # exists and returns nil if it does not. def exists? @provider.get(:ensure) != :absent end def present?(current_values) super && current_values[:ensure] != :purged end # This parameter exists to ensure backwards compatibility is preserved. # See https://github.com/puppetlabs/puppet/pull/2614 for discussion. # If/when a metaparameter for controlling how arbitrary resources respond # to refreshing is created, that will supersede this, and this will be # deprecated. newparam(:reinstall_on_refresh) do desc "Whether this resource should respond to refresh events (via `subscribe`, `notify`, or the `~>` arrow) by reinstalling the package. Only works for providers that support the `reinstallable` feature. This is useful for source-based distributions, where you may want to recompile a package if the build options change. If you use this, be careful of notifying classes when you want to restart services. If the class also contains a refreshable package, doing so could cause unnecessary re-installs." newvalues(:true, :false) defaultto :false end # When a refresh event is triggered, calls reinstall on providers # that support the reinstall_on_refresh parameter. def refresh if provider.reinstallable? && @parameters[:reinstall_on_refresh].value == :true && @parameters[:ensure].value != :purged && @parameters[:ensure].value != :absent provider.reinstall end end newproperty(:mark, :required_features => :holdable) do mark_doc = 'Valid values are: hold/none' desc <<-EOT Set to hold to tell Debian apt/Solaris pkg to hold the package version #{mark_doc} Default is "none". Mark can be specified with or without `ensure`, if `ensure` is missing will default to "present". Mark cannot be specified together with "purged", or "absent" values for `ensure`. EOT newvalues(:hold, :none) munge do |value| case value when "hold", :hold :hold when "none", :none :none else raise ArgumentError, _('Invalid hold value %{value}. %{doc}') % { value: value.inspect, doc: mark_doc } end end def insync?(is) @should[0] == is end def should @should[0] if @should && @should.is_a?(Array) && @should.size == 1 end def retrieve provider.properties[:mark] end def sync if @should[0] == :hold provider.hold else provider.unhold end end end validate do if @parameters[:mark] && [:absent, :purged].include?(@parameters[:ensure].should) raise ArgumentError, _('You cannot use "mark" property while "ensure" is one of ["absent", "purged"]') end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/resources.rb
lib/puppet/type/resources.rb
# frozen_string_literal: true require_relative '../../puppet' require_relative '../../puppet/parameter/boolean' Puppet::Type.newtype(:resources) do @doc = "This is a metatype that can manage other resource types. Any metaparams specified here will be passed on to any generated resources, so you can purge unmanaged resources but set `noop` to true so the purging is only logged and does not actually happen." apply_to_all newparam(:name) do desc "The name of the type to be managed." validate do |name| raise ArgumentError, _("Could not find resource type '%{name}'") % { name: name } unless Puppet::Type.type(name) end munge(&:to_s) end newparam(:purge, :boolean => true, :parent => Puppet::Parameter::Boolean) do desc "Whether to purge unmanaged resources. When set to `true`, this will delete any resource that is not specified in your configuration and is not autorequired by any managed resources. **Note:** The `ssh_authorized_key` resource type can't be purged this way; instead, see the `purge_ssh_keys` attribute of the `user` type." defaultto :false validate do |value| if munge(value) unless @resource.resource_type.respond_to?(:instances) raise ArgumentError, _("Purging resources of type %{res_type} is not supported, since they cannot be queried from the system") % { res_type: @resource[:name] } end raise ArgumentError, _("Purging is only supported on types that accept 'ensure'") unless @resource.resource_type.validproperty?(:ensure) end end end newparam(:unless_system_user) do desc "This keeps system users from being purged. By default, it does not purge users whose UIDs are less than the minimum UID for the system (typically 500 or 1000), but you can specify a different UID as the inclusive limit." newvalues(:true, :false, /^\d+$/) munge do |value| case value when /^\d+/ Integer(value) when :true, true @resource.class.system_users_max_uid when :false, false false when Integer; value else raise ArgumentError, _("Invalid value %{value}") % { value: value.inspect } end end defaultto { if @resource[:name] == "user" @resource.class.system_users_max_uid else nil end } end newparam(:unless_uid) do desc 'This keeps specific uids or ranges of uids from being purged when purge is true. Accepts integers, integer strings, and arrays of integers or integer strings. To specify a range of uids, consider using the range() function from stdlib.' munge do |value| value = [value] unless value.is_a? Array value.flatten.collect do |v| case v when Integer v when String Integer(v) else raise ArgumentError, _("Invalid value %{value}.") % { value: v.inspect } end end end end WINDOWS_SYSTEM_SID_REGEXES = # Administrator, Guest, Domain Admins, Schema Admins, Enterprise Admins. # https://support.microsoft.com/en-us/help/243330/well-known-security-identifiers-in-windows-operating-systems [/S-1-5-21.+-500/, /S-1-5-21.+-501/, /S-1-5-21.+-512/, /S-1-5-21.+-518/, /S-1-5-21.+-519/] def check(resource) @checkmethod ||= "#{self[:name]}_check" @hascheck ||= respond_to?(@checkmethod) if @hascheck send(@checkmethod, resource) else true end end def able_to_ensure_absent?(resource) resource[:ensure] = :absent rescue ArgumentError, Puppet::Error err _("The 'ensure' attribute on %{name} resources does not accept 'absent' as a value") % { name: self[:name] } false end # Generate any new resources we need to manage. This is pretty hackish # right now, because it only supports purging. def generate return [] unless purge? resource_type.instances .reject { |r| catalog.resource_refs.include? r.ref } .select { |r| check(r) } .select { |r| r.class.validproperty?(:ensure) } .select { |r| able_to_ensure_absent?(r) } .each { |resource| resource.copy_metaparams(@parameters) resource.purging } end def resource_type unless defined?(@resource_type) type = Puppet::Type.type(self[:name]) unless type raise Puppet::DevError, _("Could not find resource type") end @resource_type = type end @resource_type end # Make sure we don't purge users with specific uids def user_check(resource) return true unless self[:name] == "user" return true unless self[:unless_system_user] resource[:audit] = :uid current_values = resource.retrieve_resource current_uid = current_values[resource.property(:uid)] unless_uids = self[:unless_uid] return false if system_users.include?(resource[:name]) return false if unless_uids && unless_uids.include?(current_uid) if current_uid.is_a?(String) # Windows user; is a system user if any regex matches. WINDOWS_SYSTEM_SID_REGEXES.none? { |regex| current_uid =~ regex } else current_uid > self[:unless_system_user] end end def system_users %w[root nobody bin noaccess daemon sys] end def self.system_users_max_uid return @system_users_max_uid if @system_users_max_uid # First try to read the minimum user id from login.defs if Puppet::FileSystem.exist?('/etc/login.defs') @system_users_max_uid = Puppet::FileSystem.each_line '/etc/login.defs' do |line| break Regexp.last_match(1).to_i - 1 if line =~ /^\s*UID_MIN\s+(\d+)(\s*#.*)?$/ end end # Otherwise, use a sensible default based on the OS family @system_users_max_uid ||= case Puppet.runtime[:facter].value('os.family') when 'OpenBSD', 'FreeBSD' then 999 else 499 end @system_users_max_uid end def self.reset_system_users_max_uid! @system_users_max_uid = nil end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/file.rb
lib/puppet/type/file.rb
# coding: utf-8 # frozen_string_literal: true require 'digest/md5' require 'cgi' require 'etc' require 'uri' require 'fileutils' require 'pathname' require_relative '../../puppet/parameter/boolean' require_relative '../../puppet/util/diff' require_relative '../../puppet/util/checksums' require_relative '../../puppet/util/backups' require_relative '../../puppet/util/symbolic_file_mode' Puppet::Type.newtype(:file) do include Puppet::Util::Checksums include Puppet::Util::Backups include Puppet::Util::SymbolicFileMode @doc = "Manages files, including their content, ownership, and permissions. The `file` type can manage normal files, directories, and symlinks; the type should be specified in the `ensure` attribute. File contents can be managed directly with the `content` attribute, or downloaded from a remote source using the `source` attribute; the latter can also be used to recursively serve directories (when the `recurse` attribute is set to `true` or `local`). On Windows, note that file contents are managed in binary mode; Puppet never automatically translates line endings. **Autorequires:** If Puppet is managing the user or group that owns a file, the file resource will autorequire them. If Puppet is managing any parent directories of a file, the file resource autorequires them. Warning: Enabling `recurse` on directories containing large numbers of files slows agent runs. To manage file attributes for many files, consider using alternative methods such as the `chmod_r`, `chown_r`, or `recursive_file_permissions` modules from the Forge." feature :manages_symlinks, "The provider can manage symbolic links." def self.title_patterns # strip trailing slashes from path but allow the root directory, including # for example "/" or "C:/" [[%r{^(/|.+:/|.*[^/])/*\Z}m, [[:path]]]] end newparam(:path) do desc <<-'EOT' The path to the file to manage. Must be fully qualified. On Windows, the path should include the drive letter and should use `/` as the separator character (rather than `\\`). EOT isnamevar validate do |value| unless Puppet::Util.absolute_path?(value) fail Puppet::Error, _("File paths must be fully qualified, not '%{path}'") % { path: value } end end munge do |value| if value.start_with?('//') and ::File.basename(value) == "/" # This is a UNC path pointing to a share, so don't add a trailing slash ::File.expand_path(value) else ::File.join(::File.split(::File.expand_path(value))) end end end newparam(:backup) do desc <<-EOT Whether (and how) file content should be backed up before being replaced. This attribute works best as a resource default in the site manifest (`File { backup => main }`), so it can affect all file resources. * If set to `false`, file content won't be backed up. * If set to a string beginning with `.`, such as `.puppet-bak`, Puppet will use copy the file in the same directory with that value as the extension of the backup. (A value of `true` is a synonym for `.puppet-bak`.) * If set to any other string, Puppet will try to back up to a filebucket with that title. Puppet automatically creates a **local** filebucket named `puppet` if one doesn't already exist. See the `filebucket` resource type for more details. Default value: `false` Backing up to a local filebucket isn't particularly useful. If you want to make organized use of backups, you will generally want to use the primary Puppet server's filebucket service. This requires declaring a filebucket resource and a resource default for the `backup` attribute in site.pp: # /etc/puppetlabs/puppet/manifests/site.pp filebucket { 'main': path => false, # This is required for remote filebuckets. server => 'puppet.example.com', # Optional; defaults to the configured primary Puppet server. } File { backup => main, } If you are using multiple primary servers, you will want to centralize the contents of the filebucket. Either configure your load balancer to direct all filebucket traffic to a single primary server, or use something like an out-of-band rsync task to synchronize the content on all primary servers. > **Note**: Enabling and using the backup option, and by extension the filebucket resource, requires appropriate planning and management to ensure that sufficient disk space is available for the file backups. Generally, you can implement this using one of the following two options: - Use a `find` command and `crontab` entry to retain only the last X days of file backups. For example: ``` find /opt/puppetlabs/server/data/puppetserver/bucket -type f -mtime +45 -atime +45 -print0 | xargs -0 rm ``` - Restrict the directory to a maximum size after which the oldest items are removed. EOT defaultto false munge do |value| # I don't really know how this is happening. value = value.shift if value.is_a?(Array) case value when false, "false", :false false when true, "true", ".puppet-bak", :true ".puppet-bak" when String value else self.fail _("Invalid backup type %{value}") % { value: value.inspect } end end end newparam(:recurse) do desc "Whether to recursively manage the _contents_ of a directory. This attribute is only used when `ensure => directory` is set. The allowed values are: * `false` --- The default behavior. The contents of the directory will not be automatically managed. * `remote` --- If the `source` attribute is set, Puppet will automatically manage the contents of the source directory (or directories), ensuring that equivalent files and directories exist on the target system and that their contents match. Using `remote` will disable the `purge` attribute, but results in faster catalog application than `recurse => true`. The `source` attribute is mandatory when `recurse => remote`. * `true` --- If the `source` attribute is set, this behaves similarly to `recurse => remote`, automatically managing files from the source directory. This also enables the `purge` attribute, which can delete unmanaged files from a directory. See the description of `purge` for more details. The `source` attribute is not mandatory when using `recurse => true`, so you can enable purging in directories where all files are managed individually. By default, setting recurse to `remote` or `true` will manage _all_ subdirectories. You can use the `recurselimit` attribute to limit the recursion depth. " newvalues(:true, :false, :remote) validate { |arg| } munge do |value| newval = super(value) case newval when :true; true when :false; false when :remote; :remote else self.fail _("Invalid recurse value %{value}") % { value: value.inspect } end end end newparam(:recurselimit) do desc "How far Puppet should descend into subdirectories, when using `ensure => directory` and either `recurse => true` or `recurse => remote`. The recursion limit affects which files will be copied from the `source` directory, as well as which files can be purged when `purge => true`. Setting `recurselimit => 0` is the same as setting `recurse => false` --- Puppet will manage the directory, but all of its contents will be treated as unmanaged. Setting `recurselimit => 1` will manage files and directories that are directly inside the directory, but will not manage the contents of any subdirectories. Setting `recurselimit => 2` will manage the direct contents of the directory, as well as the contents of the _first_ level of subdirectories. This pattern continues for each incremental value of `recurselimit`." newvalues(/^[0-9]+$/) munge do |value| newval = super(value) case newval when Integer; value when /^\d+$/; Integer(value) else self.fail _("Invalid recurselimit value %{value}") % { value: value.inspect } end end end newparam(:max_files) do desc "In case the resource is a directory and the recursion is enabled, puppet will generate a new resource for each file file found, possible leading to an excessive number of resources generated without any control. Setting `max_files` will check the number of file resources that will eventually be created and will raise a resource argument error if the limit will be exceeded. Use value `0` to log a warning instead of raising an error. Use value `-1` to disable errors and warnings due to max files." defaultto 0 newvalues(/^[0-9]+$/, /^-1$/) end newparam(:replace, :boolean => true, :parent => Puppet::Parameter::Boolean) do desc "Whether to replace a file or symlink that already exists on the local system but whose content doesn't match what the `source` or `content` attribute specifies. Setting this to false allows file resources to initialize files without overwriting future changes. Note that this only affects content; Puppet will still manage ownership and permissions." defaultto :true end newparam(:force, :boolean => true, :parent => Puppet::Parameter::Boolean) do desc "Perform the file operation even if it will destroy one or more directories. You must use `force` in order to: * `purge` subdirectories * Replace directories with files or links * Remove a directory when `ensure => absent`" defaultto false end newparam(:ignore) do desc "A parameter which omits action on files matching specified patterns during recursion. Uses Ruby's builtin globbing engine, so shell metacharacters such as `[a-z]*` are fully supported. Matches that would descend into the directory structure are ignored, such as `*/*`." validate do |value| unless value.is_a?(Array) or value.is_a?(String) or value == false devfail "Ignore must be a string or an Array" end end end newparam(:links) do desc "How to handle links during file actions. During file copying, `follow` will copy the target file instead of the link and `manage` will copy the link itself. When not copying, `manage` will manage the link, and `follow` will manage the file to which the link points." newvalues(:follow, :manage) defaultto :manage end newparam(:purge, :boolean => true, :parent => Puppet::Parameter::Boolean) do desc "Whether unmanaged files should be purged. This option only makes sense when `ensure => directory` and `recurse => true`. * When recursively duplicating an entire directory with the `source` attribute, `purge => true` will automatically purge any files that are not in the source directory. * When managing files in a directory as individual resources, setting `purge => true` will purge any files that aren't being specifically managed. If you have a filebucket configured, the purged files will be uploaded, but if you do not, this will destroy data. Unless `force => true` is set, purging will **not** delete directories, although it will delete the files they contain. If `recurselimit` is set and you aren't using `force => true`, purging will obey the recursion limit; files in any subdirectories deeper than the limit will be treated as unmanaged and left alone." defaultto :false end newparam(:sourceselect) do desc "Whether to copy all valid sources, or just the first one. This parameter only affects recursive directory copies; by default, the first valid source is the only one used, but if this parameter is set to `all`, then all valid sources will have all of their contents copied to the local system. If a given file exists in more than one source, the version from the earliest source in the list will be used." defaultto :first newvalues(:first, :all) end newparam(:show_diff, :boolean => true, :parent => Puppet::Parameter::Boolean) do desc "Whether to display differences when the file changes, defaulting to true. This parameter is useful for files that may contain passwords or other secret data, which might otherwise be included in Puppet reports or other insecure outputs. If the global `show_diff` setting is false, then no diffs will be shown even if this parameter is true." defaultto :true end newparam(:staging_location) do desc "When rendering a file first render it to this location. The default location is the same path as the desired location with a unique filename. This parameter is useful in conjuction with validate_cmd to test a file before moving the file to it's final location. WARNING: File replacement is only guaranteed to be atomic if the staging location is on the same filesystem as the final location." validate do |value| unless Puppet::Util.absolute_path?(value) fail Puppet::Error, "File paths must be fully qualified, not '#{value}'" end end munge do |value| if value.start_with?('//') and ::File.basename(value) == "/" # This is a UNC path pointing to a share, so don't add a trailing slash ::File.expand_path(value) else ::File.join(::File.split(::File.expand_path(value))) end end end newparam(:validate_cmd) do desc "A command for validating the file's syntax before replacing it. If Puppet would need to rewrite a file due to new `source` or `content`, it will check the new content's validity first. If validation fails, the file resource will fail. This command must have a fully qualified path, and should contain a percent (`%`) token where it would expect an input file. It must exit `0` if the syntax is correct, and non-zero otherwise. The command will be run on the target system while applying the catalog, not on the primary Puppet server. Example: file { '/etc/apache2/apache2.conf': content => 'example', validate_cmd => '/usr/sbin/apache2 -t -f %', } This would replace apache2.conf only if the test returned true. Note that if a validation command requires a `%` as part of its text, you can specify a different placeholder token with the `validate_replacement` attribute." end newparam(:validate_replacement) do desc "The replacement string in a `validate_cmd` that will be replaced with an input file name." defaultto '%' end # Autorequire the nearest ancestor directory found in the catalog. autorequire(:file) do req = [] path = Pathname.new(self[:path]) unless path.root? # Start at our parent, to avoid autorequiring ourself parents = path.parent.enum_for(:ascend) found = parents.find { |p| catalog.resource(:file, p.to_s) } if found req << found.to_s end end # if the resource is a link, make sure the target is created first req << self[:target] if self[:target] req end # Autorequire the owner and group of the file. { :user => :owner, :group => :group }.each do |type, property| autorequire(type) do if @parameters.include?(property) # The user/group property automatically converts to IDs should = @parameters[property].shouldorig next unless should val = should[0] if val.is_a?(Integer) or val =~ /^\d+$/ nil else val end end end end # mutually exclusive ways to create files CREATORS = [:content, :source, :target].freeze # This is both "checksum types that can't be used with the content property" # and "checksum types that are not digest based" SOURCE_ONLY_CHECKSUMS = [:none, :ctime, :mtime].freeze validate do creator_count = 0 CREATORS.each do |param| creator_count += 1 if self.should(param) end creator_count += 1 if @parameters.include?(:source) self.fail _("You cannot specify more than one of %{creators}") % { creators: CREATORS.collect(&:to_s).join(", ") } if creator_count > 1 self.fail _("You cannot specify a remote recursion without a source") if !self[:source] && self[:recurse] == :remote self.fail _("You cannot specify source when using checksum 'none'") if self[:checksum] == :none && !self[:source].nil? SOURCE_ONLY_CHECKSUMS.each do |checksum_type| self.fail _("You cannot specify content when using checksum '%{checksum_type}'") % { checksum_type: checksum_type } if self[:checksum] == checksum_type && !self[:content].nil? end warning _("Possible error: recurselimit is set but not recurse, no recursion will happen") if !self[:recurse] && self[:recurselimit] if @parameters[:content] && @parameters[:content].actual_content # Now that we know the checksum, update content (in case it was created before checksum was known). @parameters[:content].value = @parameters[:checksum].sum(@parameters[:content].actual_content) end if self[:checksum] && self[:checksum_value] && !valid_checksum?(self[:checksum], self[:checksum_value]) self.fail _("Checksum value '%{value}' is not a valid checksum type %{checksum}") % { value: self[:checksum_value], checksum: self[:checksum] } end warning _("Checksum value is ignored unless content or source are specified") if self[:checksum_value] && !self[:content] && !self[:source] provider.validate if provider.respond_to?(:validate) end def self.[](path) return nil unless path super(path.gsub(%r{/+}, '/').sub(%r{/$}, '')) end def self.instances [] end # Determine the user to write files as. def asuser if self.should(:owner) && !self.should(:owner).is_a?(Symbol) writeable = Puppet::Util::SUIDManager.asuser(self.should(:owner)) { FileTest.writable?(::File.dirname(self[:path])) } # If the parent directory is writeable, then we execute # as the user in question. Otherwise we'll rely on # the 'owner' property to do things. asuser = self.should(:owner) if writeable end asuser end def bucket return @bucket if @bucket backup = self[:backup] return nil unless backup return nil if backup =~ /^\./ unless catalog or backup == "puppet" fail _("Can not find filebucket for backups without a catalog") end filebucket = catalog.resource(:filebucket, backup) if catalog if !catalog || (!filebucket && backup != 'puppet') fail _("Could not find filebucket %{backup} specified in backup") % { backup: backup } end return default_bucket unless filebucket @bucket = filebucket.bucket @bucket end def default_bucket Puppet::Type.type(:filebucket).mkdefaultbucket.bucket end # Does the file currently exist? Just checks for whether # we have a stat def exist? stat ? true : false end def present?(current_values) super && current_values[:ensure] != :false end # We have to do some extra finishing, to retrieve our bucket if # there is one. def finish # Look up our bucket, if there is one bucket super end # Create any children via recursion or whatever. def eval_generate return [] unless recurse? recurse end def ancestors ancestors = Pathname.new(self[:path]).enum_for(:ascend).map(&:to_s) ancestors.delete(self[:path]) ancestors end def flush # We want to make sure we retrieve metadata anew on each transaction. @parameters.each do |_name, param| param.flush if param.respond_to?(:flush) end @stat = :needs_stat end def initialize(hash) # Used for caching clients @clients = {} super # If they've specified a source, we get our 'should' values # from it. unless self[:ensure] if self[:target] self[:ensure] = :link elsif self[:content] self[:ensure] = :file end end @stat = :needs_stat end # Configure discovered resources to be purged. def mark_children_for_purging(children) children.each do |_name, child| next if child[:source] child[:ensure] = :absent end end # Create a new file or directory object as a child to the current # object. def newchild(path) full_path = ::File.join(self[:path], path) # Add some new values to our original arguments -- these are the ones # set at initialization. We specifically want to exclude any param # values set by the :source property or any default values. # LAK:NOTE This is kind of silly, because the whole point here is that # the values set at initialization should live as long as the resource # but values set by default or by :source should only live for the transaction # or so. Unfortunately, we don't have a straightforward way to manage # the different lifetimes of this data, so we kludge it like this. # The right-side hash wins in the merge. options = @original_parameters.merge(:path => full_path).compact # These should never be passed to our children. [:parent, :ensure, :recurse, :recurselimit, :max_files, :target, :alias, :source].each do |param| options.delete(param) if options.include?(param) end self.class.new(options) end # Files handle paths specially, because they just lengthen their # path names, rather than including the full parent's title each # time. def pathbuilder # We specifically need to call the method here, so it looks # up our parent in the catalog graph. parent = parent() if parent # We only need to behave specially when our parent is also # a file if parent.is_a?(self.class) # Remove the parent file name list = parent.pathbuilder list.pop # remove the parent's path info list << ref else super end else [ref] end end # Recursively generate a list of file resources, which will # be used to copy remote files, manage local files, and/or make links # to map to another directory. def recurse children = (self[:recurse] == :remote) ? {} : recurse_local if self[:target] recurse_link(children) elsif self[:source] recurse_remote(children) end # If we're purging resources, then delete any resource that isn't on the # remote system. mark_children_for_purging(children) if purge? result = children.values.sort_by { |a| a[:path] } remove_less_specific_files(result) end def remove_less_specific_files(files) existing_files = catalog.vertices.select { |r| r.is_a?(self.class) } self.class.remove_less_specific_files(files, self[:path], existing_files) do |file| file[:path] end end # This is to fix bug #2296, where two files recurse over the same # set of files. It's a rare case, and when it does happen you're # not likely to have many actual conflicts, which is good, because # this is a pretty inefficient implementation. def self.remove_less_specific_files(files, parent_path, existing_files, &block) # REVISIT: is this Windows safe? AltSeparator? mypath = parent_path.split(::File::Separator) other_paths = existing_files .select { |r| (yield r) != parent_path } .collect { |r| (yield r).split(::File::Separator) } .select { |p| p[0, mypath.length] == mypath } return files if other_paths.empty? files.reject { |file| path = (yield file).split(::File::Separator) other_paths.any? { |p| path[0, p.length] == p } } end # A simple method for determining whether we should be recursing. def recurse? self[:recurse] == true or self[:recurse] == :remote end # Recurse the target of the link. def recurse_link(children) perform_recursion(self[:target]).each do |meta| if meta.relative_path == "." self[:ensure] = :directory next end children[meta.relative_path] ||= newchild(meta.relative_path) if meta.ftype == "directory" children[meta.relative_path][:ensure] = :directory else children[meta.relative_path][:ensure] = :link children[meta.relative_path][:target] = meta.full_path end end children end # Recurse the file itself, returning a Metadata instance for every found file. def recurse_local result = perform_recursion(self[:path]) return {} unless result result.each_with_object({}) do |meta, hash| next hash if meta.relative_path == "." hash[meta.relative_path] = newchild(meta.relative_path) end end # Recurse against our remote file. def recurse_remote(children) recurse_remote_metadata.each do |meta| if meta.relative_path == "." self[:checksum] = meta.checksum_type parameter(:source).metadata = meta next end children[meta.relative_path] ||= newchild(meta.relative_path) children[meta.relative_path][:source] = meta.source children[meta.relative_path][:checksum] = meta.checksum_type children[meta.relative_path].parameter(:source).metadata = meta end children end def recurse_remote_metadata sourceselect = self[:sourceselect] total = self[:source].collect do |source| # For each inlined file resource, the catalog contains a hash mapping # source path to lists of metadata returned by a server-side search. recursive_metadata = catalog.recursive_metadata[title] if recursive_metadata result = recursive_metadata[source] else result = perform_recursion(source) end next unless result top = result.find { |r| r.relative_path == "." } return [] if top && top.ftype != "directory" result.each do |data| if data.relative_path == '.' data.source = source else # REMIND: appending file paths to URL may not be safe, e.g. foo+bar data.source = "#{source}/#{data.relative_path}" end end break result if result and !result.empty? and sourceselect == :first result end.flatten.compact # This only happens if we have sourceselect == :all unless sourceselect == :first found = [] total.reject! do |data| result = found.include?(data.relative_path) found << data.relative_path unless result result end end total end def perform_recursion(path) Puppet::FileServing::Metadata.indirection.search( path, :links => self[:links], :recurse => (self[:recurse] == :remote ? true : self[:recurse]), :recurselimit => self[:recurselimit], :max_files => self[:max_files], :source_permissions => self[:source_permissions], :ignore => self[:ignore], :checksum_type => (self[:source] || self[:content]) ? self[:checksum] : :none, :environment => catalog.environment_instance ) end # Back up and remove the file or directory at `self[:path]`. # # @param [Symbol] should The file type replacing the current content. # @return [Boolean] True if the file was removed, else False # @raises [fail???] If the file could not be backed up or could not be removed. def remove_existing(should) wanted_type = should.to_s current_type = read_current_type if current_type.nil? return false end if self[:backup] if can_backup?(current_type) backup_existing else warning _("Could not back up file of type %{current_type}") % { current_type: current_type } end end if wanted_type != "link" and current_type == wanted_type return false end case current_type when "directory" remove_directory(wanted_type) when "link", "file", "fifo", "socket" remove_file(current_type, wanted_type) else # Including: “blockSpecial”, “characterSpecial”, “unknown” self.fail _("Could not remove files of type %{current_type}") % { current_type: current_type } end end def retrieve # This check is done in retrieve to ensure it happens before we try to use # metadata in `copy_source_values`, but so it only fails the resource and not # catalog validation (because that would be a breaking change from Puppet 4). if Puppet::Util::Platform.windows? && parameter(:source) && [:use, :use_when_creating].include?(self[:source_permissions]) # TRANSLATORS "source_permissions => ignore" should not be translated err_msg = _("Copying owner/mode/group from the source file on Windows is not supported; use source_permissions => ignore.") if self[:owner].nil? || self[:group].nil? || self[:mode].nil? # Fail on Windows if source permissions are being used and the file resource # does not have mode owner, group, and mode all set (which would take precedence). self.fail err_msg else # Warn if use source permissions is specified on Windows warning err_msg end end # `checksum_value` implies explicit management of all metadata, so skip metadata # retrieval. Otherwise, if source is set, retrieve metadata for source. if (source = parameter(:source)) && property(:checksum_value).nil? source.copy_source_values end super end # Set the checksum, from another property. There are multiple # properties that modify the contents of a file, and they need the # ability to make sure that the checksum value is in sync. def setchecksum(sum = nil) if @parameters.include? :checksum if sum @parameters[:checksum].checksum = sum else # If they didn't pass in a sum, then tell checksum to # figure it out. currentvalue = @parameters[:checksum].retrieve @parameters[:checksum].checksum = currentvalue end end end # Should this thing be a normal file? This is a relatively complex # way of determining whether we're trying to create a normal file, # and it's here so that the logic isn't visible in the content property. def should_be_file? return true if self[:ensure] == :file # I.e., it's set to something like "directory" return false if self[:ensure] && self[:ensure] != :present # The user doesn't really care, apparently if self[:ensure] == :present return true unless stat return(stat.ftype == "file") end # If we've gotten here, then :ensure isn't set return true if self[:content] return true if stat and stat.ftype == "file" false end # Stat our file. Depending on the value of the 'links' attribute, we # use either 'stat' or 'lstat', and we expect the properties to use the # resulting stat object accordingly (mostly by testing the 'ftype' # value). # # We use the initial value :needs_stat to ensure we only stat the file once, # but can also keep track of a failed stat (@stat == nil). This also allows # us to re-stat on demand by setting @stat = :needs_stat. def stat return @stat unless @stat == :needs_stat method = :stat # Files are the only types that support links if instance_of?(Puppet::Type::File) and self[:links] != :follow method = :lstat end @stat = begin Puppet::FileSystem.send(method, self[:path]) rescue Errno::ENOENT nil rescue Errno::ENOTDIR nil rescue Errno::EACCES warning _("Could not stat; permission denied") nil rescue Errno::EINVAL warning _("Could not stat; invalid pathname") nil end end def to_resource resource = super resource.delete(:target) if resource[:target] == :notlink resource end # Write out the file. To write content, pass the property as an argument # to delegate writing to; must implement a #write method that takes the file # as an argument. def write(property = nil) remove_existing(:file) mode = self.should(:mode) # might be nil
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
true
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/notify.rb
lib/puppet/type/notify.rb
# frozen_string_literal: true # # Simple module for logging messages on the client-side module Puppet Type.newtype(:notify) do @doc = "Sends an arbitrary message, specified as a string, to the agent run-time log. It's important to note that the notify resource type is not idempotent. As a result, notifications are shown as a change on every Puppet run." apply_to_all newproperty(:message, :idempotent => false) do desc "The message to be sent to the log. Note that the value specified must be a string." def sync message = @sensitive ? 'Sensitive [value redacted]' : should case @resource["withpath"] when :true send(@resource[:loglevel], message) else Puppet.send(@resource[:loglevel], message) end nil end def retrieve :absent end def insync?(is) false end defaultto { @resource[:name] } end newparam(:withpath) do desc "Whether to show the full object path." defaultto :false newvalues(:true, :false) end newparam(:name) do desc "An arbitrary tag for your own reference; the name of the message." isnamevar end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/exec.rb
lib/puppet/type/exec.rb
# frozen_string_literal: true module Puppet Type.newtype(:exec) do include Puppet::Util::Execution require 'timeout' @doc = "Executes external commands. Any command in an `exec` resource **must** be able to run multiple times without causing harm --- that is, it must be *idempotent*. There are three main ways for an exec to be idempotent: * The command itself is already idempotent. (For example, `apt-get update`.) * The exec has an `onlyif`, `unless`, or `creates` attribute, which prevents Puppet from running the command unless some condition is met. The `onlyif` and `unless` commands of an `exec` are used in the process of determining whether the `exec` is already in sync, therefore they must be run during a noop Puppet run. * The exec has `refreshonly => true`, which allows Puppet to run the command only when some other resource is changed. (See the notes on refreshing below.) The state managed by an `exec` resource represents whether the specified command _needs to be_ executed during the catalog run. The target state is always that the command does not need to be executed. If the initial state is that the command _does_ need to be executed, then successfully executing the command transitions it to the target state. The `unless`, `onlyif`, and `creates` properties check the initial state of the resource. If one or more of these properties is specified, the exec might not need to run. If the exec does not need to run, then the system is already in the target state. In such cases, the exec is considered successful without actually executing its command. A caution: There's a widespread tendency to use collections of execs to manage resources that aren't covered by an existing resource type. This works fine for simple tasks, but once your exec pile gets complex enough that you really have to think to understand what's happening, you should consider developing a custom resource type instead, as it is much more predictable and maintainable. **Duplication:** Even though `command` is the namevar, Puppet allows multiple `exec` resources with the same `command` value. **Refresh:** `exec` resources can respond to refresh events (via `notify`, `subscribe`, or the `~>` arrow). The refresh behavior of execs is non-standard, and can be affected by the `refresh` and `refreshonly` attributes: * If `refreshonly` is set to true, the exec runs _only_ when it receives an event. This is the most reliable way to use refresh with execs. * If the exec has already run and then receives an event, it runs its command **up to two times.** If an `onlyif`, `unless`, or `creates` condition is no longer met after the first run, the second run does not occur. * If the exec has already run, has a `refresh` command, and receives an event, it runs its normal command. Then, if any `onlyif`, `unless`, or `creates` conditions are still met, the exec runs its `refresh` command. * If the exec has an `onlyif`, `unless`, or `creates` attribute that prevents it from running, and it then receives an event, it still will not run. * If the exec has `noop => true`, would otherwise have run, and receives an event from a non-noop resource, it runs once. However, if it has a `refresh` command, it runs that instead of its normal command. In short: If there's a possibility of your exec receiving refresh events, it is extremely important to make sure the run conditions are restricted. **Autorequires:** If Puppet is managing an exec's cwd or the executable file used in an exec's command, the exec resource autorequires those files. If Puppet is managing the user that an exec should run as, the exec resource autorequires that user." # Create a new check mechanism. It's basically a parameter that # provides one extra 'check' method. def self.newcheck(name, options = {}, &block) @checks ||= {} check = newparam(name, options, &block) @checks[name] = check end def self.checks @checks.keys end newproperty(:returns, :array_matching => :all, :event => :executed_command) do |_property| include Puppet::Util::Execution munge(&:to_s) def event_name :executed_command end defaultto "0" attr_reader :output desc "The expected exit code(s). An error will be returned if the executed command has some other exit code. Can be specified as an array of acceptable exit codes or a single value. On POSIX systems, exit codes are always integers between 0 and 255. On Windows, **most** exit codes should be integers between 0 and 2147483647. Larger exit codes on Windows can behave inconsistently across different tools. The Win32 APIs define exit codes as 32-bit unsigned integers, but both the cmd.exe shell and the .NET runtime cast them to signed integers. This means some tools will report negative numbers for exit codes above 2147483647. (For example, cmd.exe reports 4294967295 as -1.) Since Puppet uses the plain Win32 APIs, it will report the very large number instead of the negative number, which might not be what you expect if you got the exit code from a cmd.exe session. Microsoft recommends against using negative/very large exit codes, and you should avoid them when possible. To convert a negative exit code to the positive one Puppet will use, add it to 4294967296." # Make output a bit prettier def change_to_s(currentvalue, newvalue) _("executed successfully") end # First verify that all of our checks pass. def retrieve # We need to return :notrun to trigger evaluation; when that isn't # true, we *LIE* about what happened and return a "success" for the # value, which causes us to be treated as in_sync?, which means we # don't actually execute anything. I think. --daniel 2011-03-10 if @resource.check_all_attributes :notrun else should end end # Actually execute the command. def sync event = :executed_command tries = resource[:tries] try_sleep = resource[:try_sleep] begin tries.times do |try| # Only add debug messages for tries > 1 to reduce log spam. debug("Exec try #{try + 1}/#{tries}") if tries > 1 @output, @status = provider.run(resource[:command]) break if should.include?(@status.exitstatus.to_s) if try_sleep > 0 and tries > 1 debug("Sleeping for #{try_sleep} seconds between tries") sleep try_sleep end end rescue Timeout::Error => e self.fail Puppet::Error, _("Command exceeded timeout"), e end log = @resource[:logoutput] if log case log when :true log = @resource[:loglevel] when :on_failure if should.include?(@status.exitstatus.to_s) log = :false else log = @resource[:loglevel] end end unless log == :false if @resource.parameter(:command).sensitive send(log, "[output redacted]") else @output.split(/\n/).each { |line| send(log, line) } end end end unless should.include?(@status.exitstatus.to_s) if @resource.parameter(:command).sensitive # Don't print sensitive commands in the clear self.fail(_("[command redacted] returned %{status} instead of one of [%{expected}]") % { status: @status.exitstatus, expected: should.join(",") }) else self.fail(_("'%{cmd}' returned %{status} instead of one of [%{expected}]") % { cmd: resource[:command], status: @status.exitstatus, expected: should.join(",") }) end end event end end newparam(:command) do isnamevar desc "The actual command to execute. Must either be fully qualified or a search path for the command must be provided. If the command succeeds, any output produced will be logged at the instance's normal log level (usually `notice`), but if the command fails (meaning its return code does not match the specified code) then any output is logged at the `err` log level. Multiple `exec` resources can use the same `command` value; Puppet only uses the resource title to ensure `exec`s are unique. On *nix platforms, the command can be specified as an array of strings and Puppet will invoke it using the more secure method of parameterized system calls. For example, rather than executing the malicious injected code, this command will echo it out: command => ['/bin/echo', 'hello world; rm -rf /'] " validate do |command| unless command.is_a?(String) || command.is_a?(Array) raise ArgumentError, _("Command must be a String or Array<String>, got value of class %{klass}") % { klass: command.class } end end end newparam(:path) do desc "The search path used for command execution. Commands must be fully qualified if no path is specified. Paths can be specified as an array or as a '#{File::PATH_SEPARATOR}' separated list." # Support both arrays and colon-separated fields. def value=(*values) @value = values.flatten.collect { |val| val.split(File::PATH_SEPARATOR) }.flatten end end newparam(:user) do desc "The user to run the command as. > **Note:** Puppet cannot execute commands as other users on Windows. Note that if you use this attribute, any error output is not captured due to a bug within Ruby. If you use Puppet to create this user, the exec automatically requires the user, as long as it is specified by name. The $HOME environment variable is not automatically set when using this attribute." validate do |user| if Puppet::Util::Platform.windows? self.fail _("Unable to execute commands as other users on Windows") elsif !Puppet.features.root? && resource.current_username() != user self.fail _("Only root can execute commands as other users") end end end newparam(:group) do desc "The group to run the command as. This seems to work quite haphazardly on different platforms -- it is a platform issue not a Ruby or Puppet one, since the same variety exists when running commands as different users in the shell." # Validation is handled by the SUIDManager class. end newparam(:cwd, :parent => Puppet::Parameter::Path) do desc "The directory from which to run the command. If this directory does not exist, the command will fail." end newparam(:logoutput) do desc "Whether to log command output in addition to logging the exit code. Defaults to `on_failure`, which only logs the output when the command has an exit code that does not match any value specified by the `returns` attribute. As with any resource type, the log level can be controlled with the `loglevel` metaparameter." defaultto :on_failure newvalues(:true, :false, :on_failure) end newparam(:refresh) do desc "An alternate command to run when the `exec` receives a refresh event from another resource. By default, Puppet runs the main command again. For more details, see the notes about refresh behavior above, in the description for this resource type. Note that this alternate command runs with the same `provider`, `path`, `user`, and `group` as the main command. If the `path` isn't set, you must fully qualify the command's name." validate do |command| provider.validatecmd(command) end end newparam(:environment) do desc "An array of any additional environment variables you want to set for a command, such as `[ 'HOME=/root', 'MAIL=root@example.com']`. Note that if you use this to set PATH, it will override the `path` attribute. Multiple environment variables should be specified as an array." validate do |values| values = [values] unless values.is_a? Array values.each do |value| unless value =~ /\w+=/ raise ArgumentError, _("Invalid environment setting '%{value}'") % { value: value } end end end end newparam(:umask, :required_feature => :umask) do desc "Sets the umask to be used while executing this command" munge do |value| if value =~ /^0?[0-7]{1,4}$/ return value.to_i(8) else raise Puppet::Error, _("The umask specification is invalid: %{value}") % { value: value.inspect } end end end newparam(:timeout) do desc "The maximum time the command should take. If the command takes longer than the timeout, the command is considered to have failed and will be stopped. The timeout is specified in seconds. The default timeout is 300 seconds and you can set it to 0 to disable the timeout." munge do |value| value = value.shift if value.is_a?(Array) begin value = Float(value) rescue ArgumentError => e raise ArgumentError, _("The timeout must be a number."), e.backtrace end [value, 0.0].max end defaultto 300 end newparam(:tries) do desc "The number of times execution of the command should be tried. This many attempts will be made to execute the command until an acceptable return code is returned. Note that the timeout parameter applies to each try rather than to the complete set of tries." munge do |value| if value.is_a?(String) unless value =~ /^\d+$/ raise ArgumentError, _("Tries must be an integer") end value = Integer(value) end raise ArgumentError, _("Tries must be an integer >= 1") if value < 1 value end defaultto 1 end newparam(:try_sleep) do desc "The time to sleep in seconds between 'tries'." munge do |value| if value.is_a?(String) unless value =~ /^[-\d.]+$/ raise ArgumentError, _("try_sleep must be a number") end value = Float(value) end raise ArgumentError, _("try_sleep cannot be a negative number") if value < 0 value end defaultto 0 end newcheck(:refreshonly) do desc <<-'EOT' The command should only be run as a refresh mechanism for when a dependent object is changed. It only makes sense to use this option when this command depends on some other object; it is useful for triggering an action: # Pull down the main aliases file file { '/etc/aliases': source => 'puppet://server/module/aliases', } # Rebuild the database, but only when the file changes exec { newaliases: path => ['/usr/bin', '/usr/sbin'], subscribe => File['/etc/aliases'], refreshonly => true, } Note that only `subscribe` and `notify` can trigger actions, not `require`, so it only makes sense to use `refreshonly` with `subscribe` or `notify`. EOT newvalues(:true, :false) # We always fail this test, because we're only supposed to run # on refresh. def check(value) # We have to invert the values. value != :true end end newcheck(:creates, :parent => Puppet::Parameter::Path) do desc <<-'EOT' A file to look for before running the command. The command will only run if the file **doesn't exist.** This parameter doesn't cause Puppet to create a file; it is only useful if **the command itself** creates a file. exec { 'tar -xf /Volumes/nfs02/important.tar': cwd => '/var/tmp', creates => '/var/tmp/myfile', path => ['/usr/bin', '/usr/sbin',], } In this example, `myfile` is assumed to be a file inside `important.tar`. If it is ever deleted, the exec will bring it back by re-extracting the tarball. If `important.tar` does **not** actually contain `myfile`, the exec will keep running every time Puppet runs. This parameter can also take an array of files, and the command will not run if **any** of these files exist. Consider this example: creates => ['/tmp/file1', '/tmp/file2'], The command is only run if both files don't exist. EOT accept_arrays # If the file exists, return false (i.e., don't run the command), # else return true def check(value) # TRANSLATORS 'creates' is a parameter name and should not be translated debug(_("Checking that 'creates' path '%{creates_path}' exists") % { creates_path: value }) !Puppet::FileSystem.exist?(value) end end newcheck(:unless) do desc <<-'EOT' A test command that checks the state of the target system and restricts when the `exec` can run. If present, Puppet runs this test command first, then runs the main command unless the test has an exit code of 0 (success). For example: exec { '/bin/echo root >> /usr/lib/cron/cron.allow': path => '/usr/bin:/usr/sbin:/bin', unless => 'grep ^root$ /usr/lib/cron/cron.allow 2>/dev/null', } This would add `root` to the cron.allow file (on Solaris) unless `grep` determines it's already there. Note that this test command runs with the same `provider`, `path`, `user`, `cwd`, and `group` as the main command. If the `path` isn't set, you must fully qualify the command's name. Since this command is used in the process of determining whether the `exec` is already in sync, it must be run during a noop Puppet run. This parameter can also take an array of commands. For example: unless => ['test -f /tmp/file1', 'test -f /tmp/file2'], or an array of arrays. For example: unless => [['test', '-f', '/tmp/file1'], 'test -f /tmp/file2'] This `exec` would only run if every command in the array has a non-zero exit code. EOT validate do |cmds| cmds = [cmds] unless cmds.is_a? Array cmds.each do |command| provider.validatecmd(command) end end # Return true if the command does not return 0. def check(value) begin output, status = provider.run(value, true) rescue Timeout::Error err _("Check %{value} exceeded timeout") % { value: value.inspect } return false end if sensitive debug("[output redacted]") else output.split(/\n/).each { |line| debug(line) } end status.exitstatus != 0 end end newcheck(:onlyif) do desc <<-'EOT' A test command that checks the state of the target system and restricts when the `exec` can run. If present, Puppet runs this test command first, and only runs the main command if the test has an exit code of 0 (success). For example: exec { 'logrotate': path => '/usr/bin:/usr/sbin:/bin', provider => shell, onlyif => 'test `du /var/log/messages | cut -f1` -gt 100000', } This would run `logrotate` only if that test returns true. Note that this test command runs with the same `provider`, `path`, `user`, `cwd`, and `group` as the main command. If the `path` isn't set, you must fully qualify the command's name. Since this command is used in the process of determining whether the `exec` is already in sync, it must be run during a noop Puppet run. This parameter can also take an array of commands. For example: onlyif => ['test -f /tmp/file1', 'test -f /tmp/file2'], or an array of arrays. For example: onlyif => [['test', '-f', '/tmp/file1'], 'test -f /tmp/file2'] This `exec` would only run if every command in the array has an exit code of 0 (success). EOT validate do |cmds| cmds = [cmds] unless cmds.is_a? Array cmds.each do |command| provider.validatecmd(command) end end # Return true if the command returns 0. def check(value) begin output, status = provider.run(value, true) rescue Timeout::Error err _("Check %{value} exceeded timeout") % { value: value.inspect } return false end if sensitive debug("[output redacted]") else output.split(/\n/).each { |line| debug(line) } end status.exitstatus == 0 end end # Exec names are not isomorphic with the objects. @isomorphic = false validate do provider.validatecmd(self[:command]) end # FIXME exec should autorequire any exec that 'creates' our cwd autorequire(:file) do reqs = [] # Stick the cwd in there if we have it reqs << self[:cwd] if self[:cwd] file_regex = Puppet::Util::Platform.windows? ? %r{^([a-zA-Z]:[\\/]\S+)} : %r{^(/\S+)} cmd = self[:command] cmd = cmd[0] if cmd.is_a? Array if cmd.is_a?(Puppet::Pops::Evaluator::DeferredValue) debug("The 'command' parameter is deferred and cannot be autorequired") else cmd.scan(file_regex) { |str| reqs << str } cmd.scan(/^"([^"]+)"/) { |str| reqs << str } end [:onlyif, :unless].each { |param| tmp = self[param] next unless tmp tmp = [tmp] unless tmp.is_a? Array tmp.each do |line| # And search the command line for files, adding any we # find. This will also catch the command itself if it's # fully qualified. It might not be a bad idea to add # unqualified files, but, well, that's a bit more annoying # to do. line = line[0] if line.is_a? Array if line.is_a?(Puppet::Pops::Evaluator::DeferredValue) debug("The '#{param}' parameter is deferred and cannot be autorequired") else reqs += line.scan(file_regex) end end } # For some reason, the += isn't causing a flattening reqs.flatten! reqs end autorequire(:user) do # Autorequire users if they are specified by name user = self[:user] if user && user !~ /^\d+$/ user end end def self.instances [] end # Verify that we pass all of the checks. The argument determines whether # we skip the :refreshonly check, which is necessary because we now check # within refresh def check_all_attributes(refreshing = false) self.class.checks.each { |check| next if refreshing and check == :refreshonly next unless @parameters.include?(check) val = @parameters[check].value val = [val] unless val.is_a? Array val.each do |value| next if @parameters[check].check(value) # Give a debug message so users can figure out what command would have been # but don't print sensitive commands or parameters in the clear cmdstring = @parameters[:command].sensitive ? "[command redacted]" : @parameters[:command].value debug(_("'%{cmd}' won't be executed because of failed check '%{check}'") % { cmd: cmdstring, check: check }) return false end } true end def output if property(:returns).nil? nil else property(:returns).output end end # Run the command, or optionally run a separately-specified command. def refresh if check_all_attributes(true) cmd = self[:refresh] if cmd provider.run(cmd) else property(:returns).sync end end end def current_username Etc.getpwuid(Process.uid).name end private def set_sensitive_parameters(sensitive_parameters) # If any are sensitive, mark all as sensitive sensitive = false parameters_to_check = [:command, :unless, :onlyif] parameters_to_check.each do |p| if sensitive_parameters.include?(p) sensitive_parameters.delete(p) sensitive = true end end if sensitive parameters_to_check.each do |p| if parameters.include?(p) parameter(p).sensitive = true end end end super(sensitive_parameters) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/filebucket.rb
lib/puppet/type/filebucket.rb
# frozen_string_literal: true module Puppet require_relative '../../puppet/file_bucket/dipper' Type.newtype(:filebucket) do @doc = <<-EOT A repository for storing and retrieving file content by cryptographic checksum. Can be local to each agent node, or centralized on a primary Puppet server. All puppet servers provide a filebucket service that agent nodes can access via HTTP, but you must declare a filebucket resource before any agents will do so. Filebuckets are used for the following features: - **Content backups.** If the `file` type's `backup` attribute is set to the name of a filebucket, Puppet will back up the _old_ content whenever it rewrites a file; see the documentation for the `file` type for more details. These backups can be used for manual recovery of content, but are more commonly used to display changes and differences in a tool like Puppet Dashboard. To use a central filebucket for backups, you will usually want to declare a filebucket resource and a resource default for the `backup` attribute in site.pp: # /etc/puppetlabs/puppet/manifests/site.pp filebucket { 'main': path => false, # This is required for remote filebuckets. server => 'puppet.example.com', # Optional; defaults to the configured primary server. } File { backup => main, } Puppet Servers automatically provide the filebucket service, so this will work in a default configuration. If you have a heavily restricted Puppet Server `auth.conf` file, you may need to allow access to the `file_bucket_file` endpoint. EOT newparam(:name) do desc "The name of the filebucket." isnamevar end newparam(:server) do desc "The server providing the remote filebucket service. This setting is _only_ consulted if the `path` attribute is set to `false`. If this attribute is not specified, the first entry in the `server_list` configuration setting is used, followed by the value of the `server` setting if `server_list` is not set." end newparam(:port) do desc "The port on which the remote server is listening. This setting is _only_ consulted if the `path` attribute is set to `false`. If this attribute is not specified, the first entry in the `server_list` configuration setting is used, followed by the value of the `serverport` setting if `server_list` is not set." end newparam(:path) do desc "The path to the _local_ filebucket; defaults to the value of the `clientbucketdir` setting. To use a remote filebucket, you _must_ set this attribute to `false`." defaultto { Puppet[:clientbucketdir] } validate do |value| if value.is_a? Array raise ArgumentError, _("You can only have one filebucket path") end if value.is_a? String and !Puppet::Util.absolute_path?(value) raise ArgumentError, _("Filebucket paths must be absolute") end true end end # Create a default filebucket. def self.mkdefaultbucket new(:name => "puppet", :path => Puppet[:clientbucketdir]) end def bucket mkbucket unless defined?(@bucket) @bucket end private def mkbucket # Default is a local filebucket, if no server is given. # If the default path has been removed, too, then # the puppetmaster is used as default server type = "local" args = {} if self[:path] args[:Path] = self[:path] else args[:Server] = self[:server] args[:Port] = self[:port] end begin @bucket = Puppet::FileBucket::Dipper.new(args) rescue => detail message = _("Could not create %{type} filebucket: %{detail}") % { type: type, detail: detail } log_exception(detail, message) self.fail(message) end @bucket.name = name end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/service.rb
lib/puppet/type/service.rb
# frozen_string_literal: true # This is our main way of managing processes right now. # # a service is distinct from a process in that services # can only be managed through the interface of an init script # which is why they have a search path for initscripts and such module Puppet Type.newtype(:service) do @doc = "Manage running services. Service support unfortunately varies widely by platform --- some platforms have very little if any concept of a running service, and some have a very codified and powerful concept. Puppet's service support is usually capable of doing the right thing, but the more information you can provide, the better behaviour you will get. Puppet 2.7 and newer expect init scripts to have a working status command. If this isn't the case for any of your services' init scripts, you will need to set `hasstatus` to false and possibly specify a custom status command in the `status` attribute. As a last resort, Puppet will attempt to search the process table by calling whatever command is listed in the `ps` fact. The default search pattern is the name of the service, but you can specify it with the `pattern` attribute. **Refresh:** `service` resources can respond to refresh events (via `notify`, `subscribe`, or the `~>` arrow). If a `service` receives an event from another resource, Puppet will restart the service it manages. The actual command used to restart the service depends on the platform and can be configured: * If you set `hasrestart` to true, Puppet will use the init script's restart command. * You can provide an explicit command for restarting with the `restart` attribute. * If you do neither, the service's stop and start commands will be used." feature :refreshable, "The provider can restart the service.", :methods => [:restart] feature :enableable, "The provider can enable and disable the service.", :methods => [:disable, :enable, :enabled?] feature :delayed_startable, "The provider can set service to delayed start", :methods => [:delayed_start] feature :manual_startable, "The provider can set service to manual start", :methods => [:manual_start] feature :controllable, "The provider uses a control variable." feature :flaggable, "The provider can pass flags to the service." feature :maskable, "The provider can 'mask' the service.", :methods => [:mask] feature :configurable_timeout, "The provider can specify a minumum timeout for syncing service properties" feature :manages_logon_credentials, "The provider can specify the logon credentials used for a service" newproperty(:enable, :required_features => :enableable) do desc "Whether a service should be enabled to start at boot. This property behaves differently depending on the platform; wherever possible, it relies on local tools to enable or disable a given service. Default values depend on the platform. If you don't specify a value for the `enable` attribute, Puppet leaves that aspect of the service alone and your operating system determines the behavior." newvalue(:true, :event => :service_enabled) do provider.enable end newvalue(:false, :event => :service_disabled) do provider.disable end newvalue(:manual, :event => :service_manual_start, :required_features => :manual_startable) do provider.manual_start end # This only makes sense on systemd systems. Otherwise, it just defaults # to disable. newvalue(:mask, :event => :service_disabled, :required_features => :maskable) do provider.mask end def retrieve provider.enabled? end newvalue(:delayed, :event => :service_delayed_start, :required_features => :delayed_startable) do provider.delayed_start end def insync?(current) return provider.enabled_insync?(current) if provider.respond_to?(:enabled_insync?) super(current) end end # Handle whether the service should actually be running right now. newproperty(:ensure) do desc "Whether a service should be running. Default values depend on the platform." newvalue(:stopped, :event => :service_stopped) do provider.stop end newvalue(:running, :event => :service_started, :invalidate_refreshes => true) do provider.start end aliasvalue(:false, :stopped) aliasvalue(:true, :running) def retrieve provider.status end def sync property = @resource.property(:logonaccount) if property val = property.retrieve property.sync unless property.safe_insync?(val) end event = super() property = @resource.property(:enable) if property val = property.retrieve property.sync unless property.safe_insync?(val) end event end end newproperty(:logonaccount, :required_features => :manages_logon_credentials) do desc "Specify an account for service logon" def insync?(current) return provider.logonaccount_insync?(current) if provider.respond_to?(:logonaccount_insync?) super(current) end end newparam(:logonpassword, :required_features => :manages_logon_credentials) do desc "Specify a password for service logon. Default value is an empty string (when logonaccount is specified)." validate do |value| raise ArgumentError, _("Passwords cannot include ':'") if value.is_a?(String) && value.include?(":") end sensitive true defaultto { @resource[:logonaccount] ? "" : nil } end newproperty(:flags, :required_features => :flaggable) do desc "Specify a string of flags to pass to the startup script." end newparam(:binary) do desc "The path to the daemon. This is only used for systems that do not support init scripts. This binary will be used to start the service if no `start` parameter is provided." end newparam(:hasstatus) do desc "Declare whether the service's init script has a functional status command. This attribute's default value changed in Puppet 2.7.0. The init script's status command must return 0 if the service is running and a nonzero value otherwise. Ideally, these exit codes should conform to [the LSB's specification][lsb-exit-codes] for init script status actions, but Puppet only considers the difference between 0 and nonzero to be relevant. If a service's init script does not support any kind of status command, you should set `hasstatus` to false and either provide a specific command using the `status` attribute or expect that Puppet will look for the service name in the process table. Be aware that 'virtual' init scripts (like 'network' under Red Hat systems) will respond poorly to refresh events from other resources if you override the default behavior without providing a status command." newvalues(:true, :false) defaultto :true end newparam(:name) do desc <<-EOT The name of the service to run. This name is used to find the service; on platforms where services have short system names and long display names, this should be the short name. (To take an example from Windows, you would use "wuauserv" rather than "Automatic Updates.") EOT isnamevar end newparam(:path) do desc "The search path for finding init scripts. Multiple values should be separated by colons or provided as an array." munge do |value| value = [value] unless value.is_a?(Array) value.flatten.collect { |p| p.split(File::PATH_SEPARATOR) }.flatten end defaultto { provider.class.defpath if provider.class.respond_to?(:defpath) } end newparam(:pattern) do desc "The pattern to search for in the process table. This is used for stopping services on platforms that do not support init scripts, and is also used for determining service status on those service whose init scripts do not include a status command. Defaults to the name of the service. The pattern can be a simple string or any legal Ruby pattern, including regular expressions (which should be quoted without enclosing slashes)." defaultto { @resource[:binary] || @resource[:name] } end newparam(:restart) do desc "Specify a *restart* command manually. If left unspecified, the service will be stopped and then started." end newparam(:start) do desc "Specify a *start* command manually. Most service subsystems support a `start` command, so this will not need to be specified." end newparam(:status) do desc "Specify a *status* command manually. This command must return 0 if the service is running and a nonzero value otherwise. Ideally, these exit codes should conform to [the LSB's specification][lsb-exit-codes] for init script status actions, but Puppet only considers the difference between 0 and nonzero to be relevant. If left unspecified, the status of the service will be determined automatically, usually by looking for the service in the process table. [lsb-exit-codes]: http://refspecs.linuxfoundation.org/LSB_4.1.0/LSB-Core-generic/LSB-Core-generic/iniscrptact.html" end newparam(:stop) do desc "Specify a *stop* command manually." end newparam(:control) do desc "The control variable used to manage services (originally for HP-UX). Defaults to the upcased service name plus `START` replacing dots with underscores, for those providers that support the `controllable` feature." defaultto { resource.name.tr(".", "_").upcase + "_START" if resource.provider.controllable? } end newparam :hasrestart do desc "Specify that an init script has a `restart` command. If this is false and you do not specify a command in the `restart` attribute, the init script's `stop` and `start` commands will be used." newvalues(:true, :false) end newparam(:manifest) do desc "Specify a command to config a service, or a path to a manifest to do so." end newparam(:timeout, :required_features => :configurable_timeout) do desc "Specify an optional minimum timeout (in seconds) for puppet to wait when syncing service properties" defaultto { provider.respond_to?(:default_timeout) ? provider.default_timeout : 10 } munge do |value| value = value.to_i raise if value < 1 value rescue raise Puppet::Error, _("\"%{value}\" is not a positive integer: the timeout parameter must be specified as a positive integer") % { value: value } end end # Basically just a synonym for restarting. Used to respond # to events. def refresh # Only restart if we're actually running if (@parameters[:ensure] || newattr(:ensure)).retrieve == :running provider.restart else debug "Skipping restart; service is not running" end end def self.needs_ensure_retrieved false end validate do if @parameters[:logonpassword] && @parameters[:logonaccount].nil? raise Puppet::Error, _("The 'logonaccount' parameter is mandatory when setting 'logonpassword'.") end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/whit.rb
lib/puppet/type/whit.rb
# frozen_string_literal: true Puppet::Type.newtype(:whit) do desc "Whits are internal artifacts of Puppet's current implementation, and Puppet suppresses their appearance in all logs. We make no guarantee of the whit's continued existence, and it should never be used in an actual manifest. Use the `anchor` type from the puppetlabs-stdlib module if you need arbitrary whit-like no-op resources." newparam :name do desc "The name of the whit, because it must have one." end # Hide the fact that we're a whit from logs. # # I hate you, milkman whit. You are so painful, so often. # # In this case the memoized version means we generate a new string about 1.9 # percent of the time, and we allocate about 1.6MB less memory, and generate # a whole lot less GC churn. # # That number probably goes up at least O(n) with the complexity of your # catalog, and I suspect beyond that, because that is, like, 10,000 calls # for 200 distinct objects. Even with just linear, that is a constant # factor of, like, 50n. --daniel 2012-07-17 def to_s @to_s ||= name.sub(/^completed_|^admissible_/, "") end alias path to_s def refresh # We don't do anything with them, but we need this to show that we are # "refresh aware" and not break the chain of propagation. end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/tidy.rb
lib/puppet/type/tidy.rb
# frozen_string_literal: true require_relative '../../puppet/parameter/boolean' Puppet::Type.newtype(:tidy) do require_relative '../../puppet/file_serving/fileset' require_relative '../../puppet/file_bucket/dipper' @doc = "Remove unwanted files based on specific criteria. Multiple criteria are OR'd together, so a file that is too large but is not old enough will still get tidied. Ignores managed resources. If you don't specify either `age` or `size`, then all files will be removed. This resource type works by generating a file resource for every file that should be deleted and then letting that resource perform the actual deletion. " # Tidy names are not isomorphic with the objects. @isomorphic = false newparam(:path) do desc "The path to the file or directory to manage. Must be fully qualified." isnamevar munge do |value| File.expand_path(value) end end newparam(:recurse) do desc "If target is a directory, recursively descend into the directory looking for files to tidy. Numeric values specify a limit for the recursion depth, `true` means unrestricted recursion." newvalues(:true, :false, :inf, /^[0-9]+$/) # Replace the validation so that we allow numbers in # addition to string representations of them. validate { |arg| } munge do |value| newval = super(value) case newval when :true, :inf; true when :false; false when Integer; value when /^\d+$/; Integer(value) else raise ArgumentError, _("Invalid recurse value %{value}") % { value: value.inspect } end end end newparam(:max_files) do desc "In case the resource is a directory and the recursion is enabled, puppet will generate a new resource for each file file found, possible leading to an excessive number of resources generated without any control. Setting `max_files` will check the number of file resources that will eventually be created and will raise a resource argument error if the limit will be exceeded. Use value `0` to disable the check. In this case, a warning is logged if the number of files exceeds 1000." defaultto 0 newvalues(/^[0-9]+$/) end newparam(:matches) do desc <<-'EOT' One or more (shell type) file glob patterns, which restrict the list of files to be tidied to those whose basenames match at least one of the patterns specified. Multiple patterns can be specified using an array. Example: tidy { '/tmp': age => '1w', recurse => 1, matches => [ '[0-9]pub*.tmp', '*.temp', 'tmpfile?' ], } This removes files from `/tmp` if they are one week old or older, are not in a subdirectory and match one of the shell globs given. Note that the patterns are matched against the basename of each file -- that is, your glob patterns should not have any '/' characters in them, since you are only specifying against the last bit of the file. Finally, note that you must now specify a non-zero/non-false value for recurse if matches is used, as matches only apply to files found by recursion (there's no reason to use static patterns match against a statically determined path). Requiring explicit recursion clears up a common source of confusion. EOT # Make sure we convert to an array. munge do |value| fail _("Tidy can't use matches with recurse 0, false, or undef") if (@resource[:recurse]).to_s =~ /^(0|false|)$/ [value].flatten end # Does a given path match our glob patterns, if any? Return true # if no patterns have been provided. def tidy?(path, stat) basename = File.basename(path) flags = File::FNM_DOTMATCH | File::FNM_PATHNAME (value.find { |pattern| File.fnmatch(pattern, basename, flags) } ? true : false) end end newparam(:backup) do desc "Whether tidied files should be backed up. Any values are passed directly to the file resources used for actual file deletion, so consult the `file` type's backup documentation to determine valid values." end newparam(:age) do desc "Tidy files whose age is equal to or greater than the specified time. You can choose seconds, minutes, hours, days, or weeks by specifying the first letter of any of those words (for example, '1w' represents one week). Specifying 0 will remove all files." AgeConvertors = { :s => 1, :m => 60, :h => 60 * 60, :d => 60 * 60 * 24, :w => 60 * 60 * 24 * 7, } def convert(unit, multi) num = AgeConvertors[unit] if num num * multi else self.fail _("Invalid age unit '%{unit}'") % { unit: unit } end end def tidy?(path, stat) # If the file's older than we allow, we should get rid of it. (Time.now.to_i - stat.send(resource[:type]).to_i) >= value end munge do |age| unit = multi = nil case age when /^([0-9]+)(\w)\w*$/ multi = Integer(Regexp.last_match(1)) unit = Regexp.last_match(2).downcase.intern when /^([0-9]+)$/ multi = Integer(Regexp.last_match(1)) unit = :d else # TRANSLATORS tidy is the name of a program and should not be translated self.fail _("Invalid tidy age %{age}") % { age: age } end convert(unit, multi) end end newparam(:size) do desc "Tidy files whose size is equal to or greater than the specified size. Unqualified values are in kilobytes, but *b*, *k*, *m*, *g*, and *t* can be appended to specify *bytes*, *kilobytes*, *megabytes*, *gigabytes*, and *terabytes*, respectively. Only the first character is significant, so the full word can also be used." def convert(unit, multi) num = { :b => 0, :k => 1, :m => 2, :g => 3, :t => 4 }[unit] if num result = multi num.times do result *= 1024 end result else self.fail _("Invalid size unit '%{unit}'") % { unit: unit } end end def tidy?(path, stat) stat.size >= value end munge do |size| case size when /^([0-9]+)(\w)\w*$/ multi = Integer(Regexp.last_match(1)) unit = Regexp.last_match(2).downcase.intern when /^([0-9]+)$/ multi = Integer(Regexp.last_match(1)) unit = :k else # TRANSLATORS tidy is the name of a program and should not be translated self.fail _("Invalid tidy size %{age}") % { age: age } end convert(unit, multi) end end newparam(:type) do desc "Set the mechanism for determining age." newvalues(:atime, :mtime, :ctime) defaultto :atime end newparam(:rmdirs, :boolean => true, :parent => Puppet::Parameter::Boolean) do desc "Tidy directories in addition to files; that is, remove directories whose age is older than the specified criteria. This will only remove empty directories, so all contained files must also be tidied before a directory gets removed." end # Erase PFile's validate method validate do end def self.instances [] end def depthfirst? true end def initialize(hash) super # only allow backing up into filebuckets self[:backup] = false unless self[:backup].is_a? Puppet::FileBucket::Dipper end # Make a file resource to remove a given file. def mkfile(path) # Force deletion, so directories actually get deleted. parameters = { :path => path, :backup => self[:backup], :ensure => :absent, :force => true } new_file = Puppet::Type.type(:file).new(parameters) new_file.copy_metaparams(@parameters) new_file end def retrieve # Our ensure property knows how to retrieve everything for us. obj = @parameters[:ensure] if obj obj.retrieve else {} end end # Hack things a bit so we only ever check the ensure property. def properties [] end def generate return [] unless stat(self[:path]) case self[:recurse] when Integer, /^\d+$/ parameter = { :max_files => self[:max_files], :recurse => true, :recurselimit => self[:recurse] } when true, :true, :inf parameter = { :max_files => self[:max_files], :recurse => true } end if parameter files = Puppet::FileServing::Fileset.new(self[:path], parameter).files.collect do |f| f == "." ? self[:path] : ::File.join(self[:path], f) end else files = [self[:path]] end found_files = files.find_all { |path| tidy?(path) }.collect { |path| mkfile(path) } result = found_files.each { |file| debug "Tidying #{file.ref}" }.sort { |a, b| b[:path] <=> a[:path] } if found_files.size > 0 # TRANSLATORS "Tidy" is a program name and should not be translated notice _("Tidying %{count} files") % { count: found_files.size } end # No need to worry about relationships if we don't have rmdirs; there won't be # any directories. return result unless rmdirs? # Now make sure that all directories require the files they contain, if all are available, # so that a directory is emptied before we try to remove it. files_by_name = result.each_with_object({}) { |file, hash| hash[file[:path]] = file; } files_by_name.keys.sort { |a, b| b <=> a }.each do |path| dir = ::File.dirname(path) resource = files_by_name[dir] next unless resource if resource[:require] resource[:require] << Puppet::Resource.new(:file, path) else resource[:require] = [Puppet::Resource.new(:file, path)] end end result end # Does a given path match our glob patterns, if any? Return true # if no patterns have been provided. def matches?(path) return true unless self[:matches] basename = File.basename(path) flags = File::FNM_DOTMATCH | File::FNM_PATHNAME if self[:matches].find { |pattern| File.fnmatch(pattern, basename, flags) } true else debug "No specified patterns match #{path}, not tidying" false end end # Should we remove the specified file? def tidy?(path) # ignore files that are already managed, since we can't tidy # those files anyway return false if catalog.resource(:file, path) stat = self.stat(path) return false unless stat return false if stat.ftype == "directory" and !rmdirs? # The 'matches' parameter isn't OR'ed with the other tests -- # it's just used to reduce the list of files we can match. param = parameter(:matches) return false if param && !param.tidy?(path, stat) tested = false [:age, :size].each do |name| param = parameter(name) next unless param tested = true return true if param.tidy?(path, stat) end # If they don't specify either, then the file should always be removed. return true unless tested false end def stat(path) Puppet::FileSystem.lstat(path) rescue Errno::ENOENT debug _("File does not exist") nil rescue Errno::EACCES # TRANSLATORS "stat" is a program name and should not be translated warning _("Could not stat; permission denied") nil end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/schedule.rb
lib/puppet/type/schedule.rb
# frozen_string_literal: true module Puppet Type.newtype(:schedule) do @doc = <<-'EOT' Define schedules for Puppet. Resources can be limited to a schedule by using the [`schedule`](https://puppet.com/docs/puppet/latest/metaparameter.html#schedule) metaparameter. Currently, **schedules can only be used to stop a resource from being applied;** they cannot cause a resource to be applied when it otherwise wouldn't be, and they cannot accurately specify a time when a resource should run. Every time Puppet applies its configuration, it will apply the set of resources whose schedule does not eliminate them from running right then, but there is currently no system in place to guarantee that a given resource runs at a given time. If you specify a very restrictive schedule and Puppet happens to run at a time within that schedule, then the resources will get applied; otherwise, that work may never get done. Thus, it is advisable to use wider scheduling (for example, over a couple of hours) combined with periods and repetitions. For instance, if you wanted to restrict certain resources to only running once, between the hours of two and 4 AM, then you would use this schedule: schedule { 'maint': range => '2 - 4', period => daily, repeat => 1, } With this schedule, the first time that Puppet runs between 2 and 4 AM, all resources with this schedule will get applied, but they won't get applied again between 2 and 4 because they will have already run once that day, and they won't get applied outside that schedule because they will be outside the scheduled range. Puppet automatically creates a schedule for each of the valid periods with the same name as that period (such as hourly and daily). Additionally, a schedule named `puppet` is created and used as the default, with the following attributes: schedule { 'puppet': period => hourly, repeat => 2, } This will cause resources to be applied every 30 minutes by default. The `statettl` setting on the agent affects the ability of a schedule to determine if a resource has already been checked. If the `statettl` is set lower than the span of the associated schedule resource, then a resource could be checked & applied multiple times in the schedule as the information about when the resource was last checked will have expired from the cache. EOT apply_to_all newparam(:name) do desc <<-EOT The name of the schedule. This name is used when assigning the schedule to a resource with the `schedule` metaparameter: schedule { 'everyday': period => daily, range => '2 - 4', } exec { '/usr/bin/apt-get update': schedule => 'everyday', } EOT isnamevar end newparam(:range) do desc <<-EOT The earliest and latest that a resource can be applied. This is always a hyphen-separated range within a 24 hour period, and hours must be specified in numbers between 0 and 23, inclusive. Minutes and seconds can optionally be provided, using the normal colon as a separator. For instance: schedule { 'maintenance': range => '1:30 - 4:30', } This is mostly useful for restricting certain resources to being applied in maintenance windows or during off-peak hours. Multiple ranges can be applied in array context. As a convenience when specifying ranges, you can cross midnight (for example, `range => "22:00 - 04:00"`). EOT # This is lame; properties all use arrays as values, but parameters don't. # That's going to hurt eventually. validate do |values| values = [values] unless values.is_a?(Array) values.each { |value| unless value.is_a?(String) and value =~ /\d+(:\d+){0,2}\s*-\s*\d+(:\d+){0,2}/ self.fail _("Invalid range value '%{value}'") % { value: value } end } end munge do |values| values = [values] unless values.is_a?(Array) ret = [] values.each { |value| range = [] # Split each range value into a hour, minute, second triad value.split(/\s*-\s*/).each { |val| # Add the values as an array. range << val.split(":").collect(&:to_i) } self.fail _("Invalid range %{value}") % { value: value } if range.length != 2 # Fill out 0s for unspecified minutes and seconds range.each do |time_array| (3 - time_array.length).times { |_| time_array << 0 } end # Make sure the hours are valid [range[0][0], range[1][0]].each do |n| raise ArgumentError, _("Invalid hour '%{n}'") % { n: n } if n < 0 or n > 23 end [range[0][1], range[1][1]].each do |n| raise ArgumentError, _("Invalid minute '%{n}'") % { n: n } if n and (n < 0 or n > 59) end ret << range } # Now our array of arrays ret end def weekday_match?(day) if @resource[:weekday] @resource[:weekday].has_key?(day) else true end end def match?(previous, now) # The lowest-level array is of the hour, minute, second triad # then it's an array of two of those, to present the limits # then it's an array of those ranges @value = [@value] unless @value[0][0].is_a?(Array) @value.any? do |range| limit_start = Time.local(now.year, now.month, now.day, *range[0]) limit_end = Time.local(now.year, now.month, now.day, *range[1]) if limit_start < limit_end # The whole range is in one day, simple case now.between?(limit_start, limit_end) && weekday_match?(now.wday) else # The range spans days. We have to test against a range starting # today, and a range that started yesterday. today = Date.new(now.year, now.month, now.day) tomorrow = today.next_day yesterday = today.prev_day # First check a range starting today if now.between?(limit_start, Time.local(tomorrow.year, tomorrow.month, tomorrow.day, *range[1])) weekday_match?(today.wday) else # Then check a range starting yesterday now.between?(Time.local(yesterday.year, yesterday.month, yesterday.day, *range[0]), limit_end) && weekday_match?(yesterday.wday) end end end end end newparam(:periodmatch) do desc "Whether periods should be matched by a numeric value (for instance, whether two times are in the same hour) or by their chronological distance apart (whether two times are 60 minutes apart)." newvalues(:number, :distance) defaultto :distance end newparam(:period) do desc <<-EOT The period of repetition for resources on this schedule. The default is for resources to get applied every time Puppet runs. Note that the period defines how often a given resource will get applied but not when; if you would like to restrict the hours that a given resource can be applied (for instance, only at night during a maintenance window), then use the `range` attribute. If the provided periods are not sufficient, you can provide a value to the *repeat* attribute, which will cause Puppet to schedule the affected resources evenly in the period the specified number of times. Take this schedule: schedule { 'veryoften': period => hourly, repeat => 6, } This can cause Puppet to apply that resource up to every 10 minutes. At the moment, Puppet cannot guarantee that level of repetition; that is, the resource can applied _up to_ every 10 minutes, but internal factors might prevent it from actually running that often (for instance, if a Puppet run is still in progress when the next run is scheduled to start, that next run will be suppressed). See the `periodmatch` attribute for tuning whether to match times by their distance apart or by their specific value. > **Tip**: You can use `period => never,` to prevent a resource from being applied in the given `range`. This is useful if you need to create a blackout window to perform sensitive operations without interruption. EOT newvalues(:hourly, :daily, :weekly, :monthly, :never) ScheduleScales = { :hourly => 3600, :daily => 86_400, :weekly => 604_800, :monthly => 2_592_000 } ScheduleMethods = { :hourly => :hour, :daily => :day, :monthly => :month, :weekly => proc do |prev, now| # Run the resource if the previous day was after this weekday (e.g., prev is wed, current is tue) # or if it's been more than a week since we ran prev.wday > now.wday or (now - prev) > (24 * 3600 * 7) end } def match?(previous, now) return false if value == :never value = self.value case @resource[:periodmatch] when :number method = ScheduleMethods[value] if method.is_a?(Proc) method.call(previous, now) else # We negate it, because if they're equal we don't run now.send(method) != previous.send(method) end when :distance scale = ScheduleScales[value] # If the number of seconds between the two times is greater # than the unit of time, we match. We divide the scale # by the repeat, so that we'll repeat that often within # the scale. (now.to_i - previous.to_i) >= (scale / @resource[:repeat]) end end end newparam(:repeat) do desc "How often a given resource may be applied in this schedule's `period`. Must be an integer." defaultto 1 validate do |value| unless value.is_a?(Integer) or value =~ /^\d+$/ raise Puppet::Error, _("Repeat must be a number") end # This implicitly assumes that 'periodmatch' is distance -- that # is, if there's no value, we assume it's a valid value. return unless @resource[:periodmatch] if value != 1 and @resource[:periodmatch] != :distance raise Puppet::Error, _("Repeat must be 1 unless periodmatch is 'distance', not '%{period}'") % { period: @resource[:periodmatch] } end end munge do |value| value = Integer(value) unless value.is_a?(Integer) value end def match?(previous, now) true end end newparam(:weekday) do desc <<-EOT The days of the week in which the schedule should be valid. You may specify the full day name 'Tuesday', the three character abbreviation 'Tue', or a number (as a string or as an integer) corresponding to the day of the week where 0 is Sunday, 1 is Monday, and so on. Multiple days can be specified as an array. If not specified, the day of the week will not be considered in the schedule. If you are also using a range match that spans across midnight then this parameter will match the day that it was at the start of the range, not necessarily the day that it is when it matches. For example, consider this schedule: schedule { 'maintenance_window': range => '22:00 - 04:00', weekday => 'Saturday', } This will match at 11 PM on Saturday and 2 AM on Sunday, but not at 2 AM on Saturday. EOT validate do |values| values = [values] unless values.is_a?(Array) values.each { |value| if weekday_integer?(value) || weekday_string?(value) value else raise ArgumentError, _("%{value} is not a valid day of the week") % { value: value } end } end def weekday_integer?(value) value.is_a?(Integer) && (0..6).cover?(value) end def weekday_string?(value) value.is_a?(String) && (value =~ /^[0-6]$/ || value =~ /^(Mon|Tues?|Wed(?:nes)?|Thu(?:rs)?|Fri|Sat(?:ur)?|Sun)(day)?$/i) end weekdays = { 'sun' => 0, 'mon' => 1, 'tue' => 2, 'wed' => 3, 'thu' => 4, 'fri' => 5, 'sat' => 6, } munge do |values| values = [values] unless values.is_a?(Array) ret = {} values.each do |value| case value when /^[0-6]$/ index = value.to_i when 0..6 index = value else index = weekdays[value[0, 3].downcase] end ret[index] = true end ret end def match?(previous, now) # Special case weekday matching with ranges to a no-op here. # If the ranges span days then we can't simply match the current # weekday, as we want to match the weekday as it was when the range # started. As a result, all of that logic is in range, not here. return true if @resource[:range] return true if value.has_key?(now.wday) false end end def self.instances [] end def self.mkdefaultschedules result = [] unless Puppet[:default_schedules] Puppet.debug "Not creating default schedules: default_schedules is false" return result end Puppet.debug "Creating default schedules" result << new( :name => "puppet", :period => :hourly, :repeat => "2" ) # And then one for every period @parameters.find { |p| p.name == :period }.value_collection.values.each { |value| result << new( :name => value.to_s, :period => value ) } result end def match?(previous = nil, now = nil) # If we've got a value, then convert it to a Time instance previous &&= Time.at(previous) now ||= Time.now # Pull them in order self.class.allattrs.each { |param| if @parameters.include?(param) and @parameters[param].respond_to?(:match?) return false unless @parameters[param].match?(previous, now) end } # If we haven't returned false, then return true; in other words, # any provided schedules need to all match true end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/user.rb
lib/puppet/type/user.rb
# frozen_string_literal: true require 'etc' require_relative '../../puppet/parameter/boolean' require_relative '../../puppet/property/list' require_relative '../../puppet/property/ordered_list' require_relative '../../puppet/property/keyvalue' module Puppet Type.newtype(:user) do @doc = "Manage users. This type is mostly built to manage system users, so it is lacking some features useful for managing normal users. This resource type uses the prescribed native tools for creating groups and generally uses POSIX APIs for retrieving information about them. It does not directly modify `/etc/passwd` or anything. **Autorequires:** If Puppet is managing the user's primary group (as provided in the `gid` attribute) or any group listed in the `groups` attribute then the user resource will autorequire that group. If Puppet is managing any role accounts corresponding to the user's roles, the user resource will autorequire those role accounts." feature :allows_duplicates, "The provider supports duplicate users with the same UID." feature :manages_homedir, "The provider can create and remove home directories." feature :manages_passwords, "The provider can modify user passwords, by accepting a password hash." feature :manages_password_age, "The provider can set age requirements and restrictions for passwords." feature :manages_password_salt, "The provider can set a password salt. This is for providers that implement PBKDF2 passwords with salt properties." feature :manages_solaris_rbac, "The provider can manage normal users" feature :manages_roles, "The provider can manage roles" feature :manages_expiry, "The provider can manage the expiry date for a user." feature :system_users, "The provider allows you to create system users with lower UIDs." feature :manages_aix_lam, "The provider can manage AIX Loadable Authentication Module (LAM) system." feature :manages_local_users_and_groups, "Allows local users to be managed on systems that also use some other remote Name Service Switch (NSS) method of managing accounts." feature :manages_shell, "The provider allows for setting shell and validates if possible" feature :manages_loginclass, "The provider can manage the login class for a user." newproperty(:ensure, :parent => Puppet::Property::Ensure) do newvalue(:present, :event => :user_created) do provider.create end newvalue(:absent, :event => :user_removed) do provider.delete end newvalue(:role, :event => :role_created, :required_features => :manages_solaris_rbac) do provider.create_role end desc "The basic state that the object should be in." # If they're talking about the thing at all, they generally want to # say it should exist. defaultto do if @resource.managed? :present else nil end end def retrieve if provider.exists? if provider.respond_to?(:is_role?) and provider.is_role? :role else :present end else :absent end end def sync event = super property = @resource.property(:roles) if property val = property.retrieve property.sync unless property.safe_insync?(val) end event end end newproperty(:home) do desc "The home directory of the user. The directory must be created separately and is not currently checked for existence." end newproperty(:uid) do desc "The user ID; must be specified numerically. If no user ID is specified when creating a new user, then one will be chosen automatically. This will likely result in the same user having different UIDs on different systems, which is not recommended. This is especially noteworthy when managing the same user on both Darwin and other platforms, since Puppet does UID generation on Darwin, but the underlying tools do so on other platforms. On Windows, this property is read-only and will return the user's security identifier (SID)." munge do |value| case value when String if value =~ /^[-0-9]+$/ value = Integer(value) end end return value end end newproperty(:gid) do desc "The user's primary group. Can be specified numerically or by name. This attribute is not supported on Windows systems; use the `groups` attribute instead. (On Windows, designating a primary group is only meaningful for domain accounts, which Puppet does not currently manage.)" munge do |value| if value.is_a?(String) and value =~ /^[-0-9]+$/ Integer(value) else value end end def insync?(is) # We know the 'is' is a number, so we need to convert the 'should' to a number, # too. @should.each do |value| return true if is == Puppet::Util.gid(value) end false end def sync found = false @should.each do |value| number = Puppet::Util.gid(value) next unless number provider.gid = number found = true break end fail _("Could not find group(s) %{groups}") % { groups: @should.join(",") } unless found # Use the default event. end end newproperty(:comment) do desc "A description of the user. Generally the user's full name." def insync?(is) # nameservice provider requires special attention to encoding # Overrides Puppet::Property#insync? if !@should.empty? && provider.respond_to?(:comments_insync?) return provider.comments_insync?(is, @should) end super(is) end # In the case that our comments have incompatible encodings, set external # encoding to support concatenation for display. # overrides Puppet::Property#change_to_s def change_to_s(currentvalue, newvalue) if newvalue.is_a?(String) && !Encoding.compatible?(currentvalue, newvalue) return super(currentvalue, newvalue.dup.force_encoding(currentvalue.encoding)) end super(currentvalue, newvalue) end end newproperty(:shell, :required_features => :manages_shell) do desc "The user's login shell. The shell must exist and be executable. This attribute cannot be managed on Windows systems." end newproperty(:password, :required_features => :manages_passwords) do desc %q{The user's password, in whatever encrypted format the local system requires. Consult your operating system's documentation for acceptable password encryption formats and requirements. * Mac OS X 10.5 and 10.6, and some older Linux distributions, use salted SHA1 hashes. You can use Puppet's built-in `sha1` function to generate a salted SHA1 hash from a password. * Mac OS X 10.7 (Lion), and many recent Linux distributions, use salted SHA512 hashes. The Puppet Labs [stdlib][] module contains a `str2saltedsha512` function which can generate password hashes for these operating systems. * OS X 10.8 and higher use salted SHA512 PBKDF2 hashes. When managing passwords on these systems, the `salt` and `iterations` attributes need to be specified as well as the password. * macOS 10.15 and later require the salt to be 32 bytes. Because Puppet's user resource requires the value to be hex encoded, the length of the salt's string must be 64. * Windows passwords can be managed only in cleartext, because there is no Windows API for setting the password hash. [stdlib]: https://github.com/puppetlabs/puppetlabs-stdlib/ Enclose any value that includes a dollar sign ($) in single quotes (') to avoid accidental variable interpolation. To redact passwords from reports to PuppetDB, use the `Sensitive` data type. For example, this resource protects the password: ```puppet user { 'foo': ensure => present, password => Sensitive("my secret password") } ``` This results in the password being redacted from the report, as in the `previous_value`, `desired_value`, and `message` fields below. ```yaml events: - !ruby/object:Puppet::Transaction::Event audited: false property: password previous_value: "[redacted]" desired_value: "[redacted]" historical_value: message: changed [redacted] to [redacted] name: :password_changed status: success time: 2017-05-17 16:06:02.934398293 -07:00 redacted: true corrective_change: false corrective_change: false ``` } validate do |value| raise ArgumentError, _("Passwords cannot include ':'") if value.is_a?(String) and value.include?(":") end sensitive true end newproperty(:password_min_age, :required_features => :manages_password_age) do desc "The minimum number of days a password must be used before it may be changed." munge do |value| case value when String Integer(value) else value end end validate do |value| if value.to_s !~ /^-?\d+$/ raise ArgumentError, _("Password minimum age must be provided as a number.") end end end newproperty(:password_max_age, :required_features => :manages_password_age) do desc "The maximum number of days a password may be used before it must be changed." munge do |value| case value when String Integer(value) else value end end validate do |value| if value.to_s !~ /^-?\d+$/ raise ArgumentError, _("Password maximum age must be provided as a number.") end end end newproperty(:password_warn_days, :required_features => :manages_password_age) do desc "The number of days before a password is going to expire (see the maximum password age) during which the user should be warned." munge do |value| case value when String Integer(value) else value end end validate do |value| if value.to_s !~ /^-?\d+$/ raise ArgumentError, "Password warning days must be provided as a number." end end end newproperty(:groups, :parent => Puppet::Property::List) do desc "The groups to which the user belongs. The primary group should not be listed, and groups should be identified by name rather than by GID. Multiple groups should be specified as an array." validate do |value| if value =~ /^\d+$/ raise ArgumentError, _("Group names must be provided, not GID numbers.") end raise ArgumentError, _("Group names must be provided as an array, not a comma-separated list.") if value.include?(",") raise ArgumentError, _("Group names must not be empty. If you want to specify \"no groups\" pass an empty array") if value.empty? end def change_to_s(currentvalue, newvalue) newvalue = newvalue.split(",") if newvalue != :absent if provider.respond_to?(:groups_to_s) # for Windows ADSI # de-dupe the "newvalue" when the sync event message is generated, # due to final retrieve called after the resource has been modified newvalue = provider.groups_to_s(newvalue).split(',').uniq end super(currentvalue, newvalue) end # override Puppet::Property::List#retrieve def retrieve if provider.respond_to?(:groups_to_s) # Windows ADSI groups returns SIDs, but retrieve needs names # must return qualified names for SIDs for "is" value and puppet resource return provider.groups_to_s(provider.groups).split(',') end super end def insync?(current) if provider.respond_to?(:groups_insync?) return provider.groups_insync?(current, @should) end super(current) end end newparam(:name) do desc "The user name. While naming limitations vary by operating system, it is advisable to restrict names to the lowest common denominator, which is a maximum of 8 characters beginning with a letter. Note that Puppet considers user names to be case-sensitive, regardless of the platform's own rules; be sure to always use the same case when referring to a given user." isnamevar end newparam(:membership) do desc "If `minimum` is specified, Puppet will ensure that the user is a member of all specified groups, but will not remove any other groups that the user is a part of. If `inclusive` is specified, Puppet will ensure that the user is a member of **only** specified groups." newvalues(:inclusive, :minimum) defaultto :minimum end newparam(:system, :boolean => true, :parent => Puppet::Parameter::Boolean) do desc "Whether the user is a system user, according to the OS's criteria; on most platforms, a UID less than or equal to 500 indicates a system user. This parameter is only used when the resource is created and will not affect the UID when the user is present." defaultto false end newparam(:allowdupe, :boolean => true, :parent => Puppet::Parameter::Boolean) do desc "Whether to allow duplicate UIDs." defaultto false end newparam(:managehome, :boolean => true, :parent => Puppet::Parameter::Boolean) do desc "Whether to manage the home directory when Puppet creates or removes the user. This creates the home directory if Puppet also creates the user account, and deletes the home directory if Puppet also removes the user account. This parameter has no effect unless Puppet is also creating or removing the user in the resource at the same time. For instance, Puppet creates a home directory for a managed user if `ensure => present` and the user does not exist at the time of the Puppet run. If the home directory is then deleted manually, Puppet will not recreate it on the next run. Note that on Windows, this manages creation/deletion of the user profile instead of the home directory. The user profile is stored in the `C:\\Users\\<username>` directory." defaultto false validate do |val| if munge(val) raise ArgumentError, _("User provider %{name} can not manage home directories") % { name: provider.class.name } if provider and !provider.class.manages_homedir? end end end newproperty(:expiry, :required_features => :manages_expiry) do desc "The expiry date for this user. Provide as either the special value `absent` to ensure that the account never expires, or as a zero-padded YYYY-MM-DD format -- for example, 2010-02-19." newvalues :absent newvalues(/^\d{4}-\d{2}-\d{2}$/) validate do |value| if value.intern != :absent and value !~ /^\d{4}-\d{2}-\d{2}$/ # TRANSLATORS YYYY-MM-DD represents a date with a four-digit year, a two-digit month, and a two-digit day, # TRANSLATORS separated by dashes. raise ArgumentError, _("Expiry dates must be YYYY-MM-DD or the string \"absent\"") end end end # Autorequire the group, if it's around autorequire(:group) do autos = [] # autorequire primary group, if managed obj = @parameters[:gid] groups = obj.shouldorig if obj if groups groups = groups.collect { |group| if group.is_a?(String) && group =~ /^\d+$/ Integer(group) else group end } groups.each { |group| case group when Integer resource = catalog.resources.find { |r| r.is_a?(Puppet::Type.type(:group)) && r.should(:gid) == group } if resource autos << resource end else autos << group end } end # autorequire groups, excluding primary group, if managed obj = @parameters[:groups] if obj groups = obj.should if groups autos += groups.split(",") end end autos end # This method has been exposed for puppet to manage users and groups of # files in its settings and should not be considered available outside of # puppet. # # (see Puppet::Settings#service_user_available?) # # @return [Boolean] if the user exists on the system # @api private def exists? provider.exists? end newproperty(:roles, :parent => Puppet::Property::List, :required_features => :manages_roles) do desc "The roles the user has. Multiple roles should be specified as an array." def membership :role_membership end validate do |value| if value =~ /^\d+$/ raise ArgumentError, _("Role names must be provided, not numbers") end raise ArgumentError, _("Role names must be provided as an array, not a comma-separated list") if value.include?(",") end end # autorequire the roles that the user has autorequire(:user) do reqs = [] roles_property = @parameters[:roles] roles = roles_property.should if roles_property if roles reqs += roles.split(',') end reqs end unless Puppet::Util::Platform.windows? newparam(:role_membership) do desc "Whether specified roles should be considered the **complete list** (`inclusive`) or the **minimum list** (`minimum`) of roles the user has." newvalues(:inclusive, :minimum) defaultto :minimum end newproperty(:auths, :parent => Puppet::Property::List, :required_features => :manages_solaris_rbac) do desc "The auths the user has. Multiple auths should be specified as an array." def membership :auth_membership end validate do |value| if value =~ /^\d+$/ raise ArgumentError, _("Auth names must be provided, not numbers") end raise ArgumentError, _("Auth names must be provided as an array, not a comma-separated list") if value.include?(",") end end newparam(:auth_membership) do desc "Whether specified auths should be considered the **complete list** (`inclusive`) or the **minimum list** (`minimum`) of auths the user has. This setting is specific to managing Solaris authorizations." newvalues(:inclusive, :minimum) defaultto :minimum end newproperty(:profiles, :parent => Puppet::Property::OrderedList, :required_features => :manages_solaris_rbac) do desc "The profiles the user has. Multiple profiles should be specified as an array." def membership :profile_membership end validate do |value| if value =~ /^\d+$/ raise ArgumentError, _("Profile names must be provided, not numbers") end raise ArgumentError, _("Profile names must be provided as an array, not a comma-separated list") if value.include?(",") end end newparam(:profile_membership) do desc "Whether specified roles should be treated as the **complete list** (`inclusive`) or the **minimum list** (`minimum`) of roles of which the user is a member." newvalues(:inclusive, :minimum) defaultto :minimum end newproperty(:keys, :parent => Puppet::Property::KeyValue, :required_features => :manages_solaris_rbac) do desc "Specify user attributes in an array of key = value pairs." def membership :key_membership end end newparam(:key_membership) do desc "Whether specified key/value pairs should be considered the **complete list** (`inclusive`) or the **minimum list** (`minimum`) of the user's attributes." newvalues(:inclusive, :minimum) defaultto :minimum end newproperty(:project, :required_features => :manages_solaris_rbac) do desc "The name of the project associated with a user." end newparam(:ia_load_module, :required_features => :manages_aix_lam) do desc "The name of the I&A module to use to manage this user. This should be set to `files` if managing local users." end newproperty(:attributes, :parent => Puppet::Property::KeyValue, :required_features => :manages_aix_lam) do desc "Specify AIX attributes for the user in an array or hash of attribute = value pairs. For example: ``` ['minage=0', 'maxage=5', 'SYSTEM=compat'] ``` or ``` attributes => { 'minage' => '0', 'maxage' => '5', 'SYSTEM' => 'compat' } ``` " self.log_only_changed_or_new_keys = true def membership :attribute_membership end def delimiter " " end end newparam(:attribute_membership) do desc "Whether specified attribute value pairs should be treated as the **complete list** (`inclusive`) or the **minimum list** (`minimum`) of attribute/value pairs for the user." newvalues(:inclusive, :minimum) defaultto :minimum end newproperty(:salt, :required_features => :manages_password_salt) do desc "This is the 32-byte salt used to generate the PBKDF2 password used in OS X. This field is required for managing passwords on OS X >= 10.8." end newproperty(:iterations, :required_features => :manages_password_salt) do desc "This is the number of iterations of a chained computation of the [PBKDF2 password hash](https://en.wikipedia.org/wiki/PBKDF2). This parameter is used in OS X, and is required for managing passwords on OS X 10.8 and newer." munge do |value| if value.is_a?(String) and value =~ /^[-0-9]+$/ Integer(value) else value end end end newparam(:forcelocal, :boolean => true, :required_features => :manages_local_users_and_groups, :parent => Puppet::Parameter::Boolean) do desc "Forces the management of local accounts when accounts are also being managed by some other Name Service Switch (NSS). For AIX, refer to the `ia_load_module` parameter. This option relies on your operating system's implementation of `luser*` commands, such as `luseradd` , and `lgroupadd`, `lusermod`. The `forcelocal` option could behave unpredictably in some circumstances. If the tools it depends on are not available, it might have no effect at all." defaultto false end def generate unless self[:purge_ssh_keys].empty? if Puppet::Type.type(:ssh_authorized_key).nil? warning _("Ssh_authorized_key type is not available. Cannot purge SSH keys.") else return find_unmanaged_keys end end [] end newparam(:purge_ssh_keys) do desc "Whether to purge authorized SSH keys for this user if they are not managed with the `ssh_authorized_key` resource type. This parameter is a noop if the ssh_authorized_key type is not available. Allowed values are: * `false` (default) --- don't purge SSH keys for this user. * `true` --- look for keys in the `.ssh/authorized_keys` file in the user's home directory. Purge any keys that aren't managed as `ssh_authorized_key` resources. * An array of file paths --- look for keys in all of the files listed. Purge any keys that aren't managed as `ssh_authorized_key` resources. If any of these paths starts with `~` or `%h`, that token will be replaced with the user's home directory." defaultto :false # Use Symbols instead of booleans until PUP-1967 is resolved. newvalues(:true, :false) validate do |value| if [:true, :false].include? value.to_s.intern return end value = [value] if value.is_a?(String) if value.is_a?(Array) value.each do |entry| raise ArgumentError, _("Each entry for purge_ssh_keys must be a string, not a %{klass}") % { klass: entry.class } unless entry.is_a?(String) valid_home = Puppet::Util.absolute_path?(entry) || entry =~ %r{^~/|^%h/} raise ArgumentError, _("Paths to keyfiles must be absolute, not %{entry}") % { entry: entry } unless valid_home end return end raise ArgumentError, _("purge_ssh_keys must be true, false, or an array of file names, not %{value}") % { value: value.inspect } end munge do |value| # Resolve string, boolean and symbol forms of true and false to a # single representation. case value when :false, false, "false" [] when :true, true, "true" home = homedir home ? ["#{home}/.ssh/authorized_keys"] : [] else # value can be a string or array - munge each value [value].flatten.filter_map do |entry| authorized_keys_path(entry) end end end private def homedir resource[:home] || Dir.home(resource[:name]) rescue ArgumentError Puppet.debug("User '#{resource[:name]}' does not exist") nil end def authorized_keys_path(entry) return entry unless entry.match?(%r{^(?:~|%h)/}) # if user doesn't exist (yet), ignore nonexistent homedir home = homedir return nil unless home # compiler freezes "value" so duplicate using a gsub, second mutating gsub! is then ok entry = entry.gsub(%r{^~/}, "#{home}/") entry.gsub!(%r{^%h/}, "#{home}/") entry end end newproperty(:loginclass, :required_features => :manages_loginclass) do desc "The name of login class to which the user belongs." validate do |value| if value =~ /^\d+$/ raise ArgumentError, _("Class name must be provided.") end end end # Generate ssh_authorized_keys resources for purging. The key files are # taken from the purge_ssh_keys parameter. The generated resources inherit # all metaparameters from the parent user resource. # # @return [Array<Puppet::Type::Ssh_authorized_key] a list of resources # representing the found keys # @see generate # @api private def find_unmanaged_keys self[:purge_ssh_keys] .select { |f| File.readable?(f) } .map { |f| unknown_keys_in_file(f) } .flatten.each do |res| res[:ensure] = :absent res[:user] = self[:name] res.copy_metaparams(@parameters) end end # Parse an ssh authorized keys file superficially, extract the comments # on the keys. These are considered names of possible ssh_authorized_keys # resources. Keys that are managed by the present catalog are ignored. # # @see generate # @api private # @return [Array<Puppet::Type::Ssh_authorized_key] a list of resources # representing the found keys def unknown_keys_in_file(keyfile) # The ssh_authorized_key type is distributed as a module on the Forge, # so we shouldn't rely on it being available. return [] unless Puppet::Type.type(:ssh_authorized_key) names = [] name_index = 0 # RFC 4716 specifies UTF-8 allowed in public key files per https://www.ietf.org/rfc/rfc4716.txt # the authorized_keys file may contain UTF-8 comments Puppet::FileSystem.open(keyfile, nil, 'r:UTF-8').each do |line| next unless line =~ Puppet::Type.type(:ssh_authorized_key).keyline_regex # the name is stored in the 4th capture of the regex name = ::Regexp.last_match(4) if name.empty? ::Regexp.last_match(3).delete("\n") # If no comment is specified for this key, generate a unique internal # name. This uses the same rules as # provider/ssh_authorized_key/parsed (PUP-3357) name = "#{keyfile}:unnamed-#{name_index += 1}" end names << name Puppet.debug "#{ref} parsed for purging Ssh_authorized_key[#{name}]" end names.map { |keyname| Puppet::Type.type(:ssh_authorized_key).new( :name => keyname, :target => keyfile ) }.reject { |res| catalog.resource_refs.include? res.ref } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/file/ctime.rb
lib/puppet/type/file/ctime.rb
# frozen_string_literal: true module Puppet Puppet::Type.type(:file).newproperty(:ctime) do desc "A read-only state to check the file ctime. On most modern \*nix-like systems, this is the time of the most recent change to the owner, group, permissions, or content of the file." def retrieve current_value = :absent stat = @resource.stat if stat current_value = stat.ctime end current_value.to_s end validate do |_val| fail "ctime is read-only" end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/file/target.rb
lib/puppet/type/file/target.rb
# frozen_string_literal: true module Puppet Puppet::Type.type(:file).newproperty(:target) do desc "The target for creating a link. Currently, symlinks are the only type supported. This attribute is mutually exclusive with `source` and `content`. Symlink targets can be relative, as well as absolute: # (Useful on Solaris) file { '/etc/inetd.conf': ensure => link, target => 'inet/inetd.conf', } Directories of symlinks can be served recursively by instead using the `source` attribute, setting `ensure` to `directory`, and setting the `links` attribute to `manage`." newvalue(:notlink) do # We do nothing if the value is absent return :nochange end # Anything else, basically newvalue(/./) do @resource[:ensure] = :link unless @resource.should(:ensure) # Only call mklink if ensure didn't call us in the first place. currentensure = @resource.property(:ensure).retrieve mklink if @resource.property(:ensure).safe_insync?(currentensure) end # Create our link. def mklink raise Puppet::Error, "Cannot symlink on this platform version" unless provider.feature?(:manages_symlinks) target = should # Clean up any existing objects. The argument is just for logging, # it doesn't determine what's removed. @resource.remove_existing(target) raise Puppet::Error, "Could not remove existing file" if Puppet::FileSystem.exist?(@resource[:path]) Puppet::Util::SUIDManager.asuser(@resource.asuser) do mode = @resource.should(:mode) if mode Puppet::Util.withumask(0o00) do Puppet::FileSystem.symlink(target, @resource[:path]) end else Puppet::FileSystem.symlink(target, @resource[:path]) end end @resource.send(:property_fix) :link_created end def insync?(currentvalue) if [:nochange, :notlink].include?(should) or @resource.recurse? true elsif !@resource.replace? and Puppet::FileSystem.exist?(@resource[:path]) true else super(currentvalue) end end def retrieve stat = @resource.stat if stat if stat.ftype == "link" Puppet::FileSystem.readlink(@resource[:path]) else :notlink end else :absent end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/file/source.rb
lib/puppet/type/file/source.rb
# frozen_string_literal: true require_relative '../../../puppet/file_serving/content' require_relative '../../../puppet/file_serving/metadata' require_relative '../../../puppet/file_serving/terminus_helper' require_relative '../../../puppet/http' module Puppet # Copy files from a local or remote source. This state *only* does any work # when the remote file is an actual file; in that case, this state copies # the file down. If the remote file is a dir or a link or whatever, then # this state, during retrieval, modifies the appropriate other states # so that things get taken care of appropriately. Puppet::Type.type(:file).newparam(:source) do attr_accessor :source, :local desc <<-'EOT' A source file, which will be copied into place on the local system. This attribute is mutually exclusive with `content` and `target`. Allowed values are: * `puppet:` URIs, which point to files in modules or Puppet file server mount points. * Fully qualified paths to locally available files (including files on NFS shares or Windows mapped drives). * `file:` URIs, which behave the same as local file paths. * `http(s):` URIs, which point to files served by common web servers. The normal form of a `puppet:` URI is: `puppet:///modules/<MODULE NAME>/<FILE PATH>` This will fetch a file from a module on the Puppet master (or from a local module when using Puppet apply). Given a `modulepath` of `/etc/puppetlabs/code/modules`, the example above would resolve to `/etc/puppetlabs/code/modules/<MODULE NAME>/files/<FILE PATH>`. Unlike `content`, the `source` attribute can be used to recursively copy directories if the `recurse` attribute is set to `true` or `remote`. If a source directory contains symlinks, use the `links` attribute to specify whether to recreate links or follow them. _HTTP_ URIs cannot be used to recursively synchronize whole directory trees. You cannot use `source_permissions` values other than `ignore` because HTTP servers do not transfer any metadata that translates to ownership or permission details. Puppet determines if file content is synchronized by computing a checksum for the local file and comparing it against the `checksum_value` parameter. If the `checksum_value` parameter is not specified for `puppet` and `file` sources, Puppet computes a checksum based on its `Puppet[:digest_algorithm]`. For `http(s)` sources, Puppet uses the first HTTP header it recognizes out of the following list: `X-Checksum-Sha256`, `X-Checksum-Sha1`, `X-Checksum-Md5` or `Content-MD5`. If the server response does not include one of these headers, Puppet defaults to using the `Last-Modified` header. Puppet updates the local file if the header is newer than the modified time (mtime) of the local file. _HTTP_ URIs can include a user information component so that Puppet can retrieve file metadata and content from HTTP servers that require HTTP Basic authentication. For example `https://<user>:<pass>@<server>:<port>/path/to/file.` When connecting to _HTTPS_ servers, Puppet trusts CA certificates in the puppet-agent certificate bundle and the Puppet CA. You can configure Puppet to trust additional CA certificates using the `Puppet[:ssl_trust_store]` setting. Multiple `source` values can be specified as an array, and Puppet will use the first source that exists. This can be used to serve different files to different system types: file { '/etc/nfs.conf': source => [ "puppet:///modules/nfs/conf.${host}", "puppet:///modules/nfs/conf.${os['name']}", 'puppet:///modules/nfs/conf' ] } Alternately, when serving directories recursively, multiple sources can be combined by setting the `sourceselect` attribute to `all`. EOT validate do |sources| sources = [sources] unless sources.is_a?(Array) sources.each do |source| next if Puppet::Util.absolute_path?(source) begin uri = URI.parse(Puppet::Util.uri_encode(source)) rescue => detail self.fail Puppet::Error, "Could not understand source #{source}: #{detail}", detail end self.fail "Cannot use relative URLs '#{source}'" unless uri.absolute? self.fail "Cannot use opaque URLs '#{source}'" unless uri.hierarchical? unless %w[file puppet http https].include?(uri.scheme) self.fail "Cannot use URLs of type '#{uri.scheme}' as source for fileserving" end end end SEPARATOR_REGEX = [Regexp.escape(File::SEPARATOR.to_s), Regexp.escape(File::ALT_SEPARATOR.to_s)].join munge do |sources| sources = [sources] unless sources.is_a?(Array) sources.map do |source| source = self.class.normalize(source) if Puppet::Util.absolute_path?(source) # CGI.unescape will butcher properly escaped URIs uri_string = Puppet::Util.path_to_uri(source).to_s # Ruby 1.9.3 and earlier have a URI bug in URI # to_s returns an ASCII string despite UTF-8 fragments # since its escaped its safe to universally call encode # Puppet::Util.uri_unescape always returns strings in the original encoding Puppet::Util.uri_unescape(uri_string.encode(Encoding::UTF_8)) else source end end end def self.normalize(source) source.sub(/[#{SEPARATOR_REGEX}]+$/, '') end def change_to_s(currentvalue, newvalue) # newvalue = "{md5}#{@metadata.checksum}" if resource.property(:ensure).retrieve == :absent "creating from source #{metadata.source} with contents #{metadata.checksum}" else "replacing from source #{metadata.source} with contents #{metadata.checksum}" end end def checksum metadata && metadata.checksum end # Copy the values from the source to the resource. Yay. def copy_source_values devfail "Somehow got asked to copy source values without any metadata" unless metadata # conditionally copy :checksum if metadata.ftype != "directory" && !(metadata.ftype == "link" && metadata.links == :manage) copy_source_value(:checksum) end # Take each of the stats and set them as states on the local file # if a value has not already been provided. [:owner, :mode, :group].each do |metadata_method| next if metadata_method == :owner and !Puppet.features.root? next if metadata_method == :group and !Puppet.features.root? case resource[:source_permissions] when :ignore, nil next when :use_when_creating next if Puppet::FileSystem.exist?(resource[:path]) end copy_source_value(metadata_method) end if resource[:ensure] == :absent # We know all we need to elsif metadata.ftype != "link" resource[:ensure] = metadata.ftype elsif resource[:links] == :follow resource[:ensure] = :present else resource[:ensure] = "link" resource[:target] = metadata.destination end end attr_writer :metadata # Provide, and retrieve if necessary, the metadata for this file. Fail # if we can't find data about this host, and fail if there are any # problems in our query. def metadata @metadata ||= resource.catalog.metadata[resource.title] return @metadata if @metadata return nil unless value value.each do |source| options = { :environment => resource.catalog.environment_instance, :links => resource[:links], :checksum_type => resource[:checksum], :source_permissions => resource[:source_permissions] } data = Puppet::FileServing::Metadata.indirection.find(source, options) if data @metadata = data @metadata.source = source break end rescue => detail self.fail Puppet::Error, "Could not retrieve file metadata for #{source}: #{detail}", detail end self.fail "Could not retrieve information from environment #{resource.catalog.environment} source(s) #{value.join(', ')}" unless @metadata @metadata end def local? found? and scheme == "file" end def full_path Puppet::Util.uri_to_path(uri) if found? end def server? uri && uri.host && !uri.host.empty? end def server server? ? uri.host : Puppet.settings[:server] end def port (uri and uri.port) or Puppet.settings[:serverport] end def uri @uri ||= URI.parse(Puppet::Util.uri_encode(metadata.source)) end def write(file) resource.parameter(:checksum).sum_stream { |sum| each_chunk_from { |chunk| sum << chunk file.print chunk } } end private def scheme (uri and uri.scheme) end def found? !(metadata.nil? or metadata.ftype.nil?) end def copy_source_value(metadata_method) param_name = (metadata_method == :checksum) ? :content : metadata_method if resource[param_name].nil? or resource[param_name] == :absent if Puppet::Util::Platform.windows? && [:owner, :group, :mode].include?(metadata_method) devfail "Should not have tried to use source owner/mode/group on Windows" end value = metadata.send(metadata_method) # Force the mode value in file resources to be a string containing octal. value = value.to_s(8) if param_name == :mode && value.is_a?(Numeric) resource[param_name] = value if metadata_method == :checksum # If copying checksum, also copy checksum_type resource[:checksum] = metadata.checksum_type end end end def each_chunk_from(&block) if Puppet[:default_file_terminus] == :file_server && scheme == 'puppet' && (uri.host.nil? || uri.host.empty?) chunk_file_from_disk(metadata.full_path, &block) elsif local? chunk_file_from_disk(full_path, &block) else chunk_file_from_source(&block) end end def chunk_file_from_disk(local_path) File.open(local_path, "rb") do |src| while chunk = src.read(8192) # rubocop:disable Lint/AssignmentInCondition yield chunk end end end def get_from_content_uri_source(url, &block) session = Puppet.lookup(:http_session) api = session.route_to(:fileserver, url: url) api.get_static_file_content( path: Puppet::Util.uri_unescape(url.path), environment: resource.catalog.environment_instance.to_s, code_id: resource.catalog.code_id, &block ) end def get_from_source_uri_source(url, &block) session = Puppet.lookup(:http_session) api = session.route_to(:fileserver, url: url) api.get_file_content( path: Puppet::Util.uri_unescape(url.path), environment: resource.catalog.environment_instance.to_s, &block ) end def get_from_http_source(url, &block) client = Puppet.runtime[:http] client.get(url, options: { include_system_store: true }) do |response| raise Puppet::HTTP::ResponseError, response unless response.success? response.read_body(&block) end end def chunk_file_from_source(&block) if uri.scheme =~ /^https?/ # Historically puppet has not encoded the http(s) source URL before parsing # it, for example, if the path contains spaces, then it must be URL encoded # as %20 in the manifest. Puppet behaves the same when retrieving file # metadata via http(s), see Puppet::Indirector::FileMetadata::Http#find. url = URI.parse(metadata.source) get_from_http_source(url, &block) elsif metadata.content_uri content_url = URI.parse(Puppet::Util.uri_encode(metadata.content_uri)) get_from_content_uri_source(content_url, &block) else get_from_source_uri_source(uri, &block) end rescue Puppet::HTTP::ResponseError => e handle_response_error(e.response) end def handle_response_error(response) message = "Error #{response.code} on SERVER: #{response.body.empty? ? response.reason : response.body}" raise Net::HTTPError.new(message, Puppet::HTTP::ResponseConverter.to_ruby_response(response)) end end Puppet::Type.type(:file).newparam(:source_permissions) do desc <<-'EOT' Whether (and how) Puppet should copy owner, group, and mode permissions from the `source` to `file` resources when the permissions are not explicitly specified. (In all cases, explicit permissions will take precedence.) Valid values are `use`, `use_when_creating`, and `ignore`: * `ignore` (the default) will never apply the owner, group, or mode from the `source` when managing a file. When creating new files without explicit permissions, the permissions they receive will depend on platform-specific behavior. On POSIX, Puppet will use the umask of the user it is running as. On Windows, Puppet will use the default DACL associated with the user it is running as. * `use` will cause Puppet to apply the owner, group, and mode from the `source` to any files it is managing. * `use_when_creating` will only apply the owner, group, and mode from the `source` when creating a file; existing files will not have their permissions overwritten. EOT defaultto :ignore newvalues(:use, :use_when_creating, :ignore) munge do |value| value = value ? value.to_sym : :ignore if @resource.file && @resource.line && value != :ignore # TRANSLATORS "source_permissions" is a parameter name and should not be translated Puppet.puppet_deprecation_warning(_("The `source_permissions` parameter is deprecated. Explicitly set `owner`, `group`, and `mode`."), file: @resource.file, line: @resource.line) end value end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/file/content.rb
lib/puppet/type/file/content.rb
# frozen_string_literal: true require 'net/http' require 'uri' require 'tempfile' require_relative '../../../puppet/util/checksums' require_relative '../../../puppet/type/file/data_sync' module Puppet Puppet::Type.type(:file).newproperty(:content) do include Puppet::Util::Checksums include Puppet::DataSync attr_reader :actual_content desc <<-'EOT' The desired contents of a file, as a string. This attribute is mutually exclusive with `source` and `target`. Newlines and tabs can be specified in double-quoted strings using standard escaped syntax --- \n for a newline, and \t for a tab. With very small files, you can construct content strings directly in the manifest... define resolve($nameserver1, $nameserver2, $domain, $search) { $str = "search ${search} domain ${domain} nameserver ${nameserver1} nameserver ${nameserver2} " file { '/etc/resolv.conf': content => $str, } } ...but for larger files, this attribute is more useful when combined with the [template](https://puppet.com/docs/puppet/latest/function.html#template) or [file](https://puppet.com/docs/puppet/latest/function.html#file) function. EOT # Store a checksum as the value, rather than the actual content. # Simplifies everything. munge do |value| if value == :absent value elsif value.is_a?(String) && checksum?(value) # XXX This is potentially dangerous because it means users can't write a file whose # entire contents are a plain checksum unless it is a Binary content. Puppet.puppet_deprecation_warning([ # TRANSLATORS "content" is an attribute and should not be translated _('Using a checksum in a file\'s "content" property is deprecated.'), # TRANSLATORS "filebucket" is a resource type and should not be translated. The quoted occurrence of "content" is an attribute and should not be translated. _('The ability to use a checksum to retrieve content from the filebucket using the "content" property will be removed in a future release.'), # TRANSLATORS "content" is an attribute and should not be translated. _('The literal value of the "content" property will be written to the file.'), # TRANSLATORS "static catalogs" should not be translated. _('The checksum retrieval functionality is being replaced by the use of static catalogs.'), _('See https://puppet.com/docs/puppet/latest/static_catalogs.html for more information.') ].join(" "), :file => @resource.file, :line => @resource.line) if !@actual_content && !resource.parameter(:source) value else @actual_content = value.is_a?(Puppet::Pops::Types::PBinaryType::Binary) ? value.binary_buffer : value resource.parameter(:checksum).sum(@actual_content) end end # Checksums need to invert how changes are printed. def change_to_s(currentvalue, newvalue) # Our "new" checksum value is provided by the source. source = resource.parameter(:source) tmp = source.checksum if source if tmp newvalue = tmp end if currentvalue == :absent "defined content as '#{newvalue}'" elsif newvalue == :absent "undefined content from '#{currentvalue}'" else "content changed '#{currentvalue}' to '#{newvalue}'" end end def length (actual_content and actual_content.length) || 0 end def content should end # Override this method to provide diffs if asked for. # Also, fix #872: when content is used, and replace is true, the file # should be insync when it exists def insync?(is) if resource[:source] && resource[:checksum_value] # Asserts that nothing has changed since validate ran. devfail "content property should not exist if source and checksum_value are specified" end contents_prop = resource.parameter(:source) || self checksum_insync?(contents_prop, is, !resource[:content].nil?) { |inner| super(inner) } end def property_matches?(current, desired) # If checksum_value is specified, it overrides comparing the content field. checksum_type = resource.parameter(:checksum).value checksum_value = resource.parameter(:checksum_value) if checksum_value desired = "{#{checksum_type}}#{checksum_value.value}" end # The inherited equality is always accepted, so use it if valid. return true if super(current, desired) date_matches?(checksum_type, current, desired) end def retrieve retrieve_checksum(resource) end # Make sure we're also managing the checksum property. def should=(value) # treat the value as a bytestring value = value.b if value.is_a?(String) @resource.newattr(:checksum) unless @resource.parameter(:checksum) super end # Just write our content out to disk. def sync contents_sync(resource.parameter(:source) || self) end def write(file) resource.parameter(:checksum).sum_stream { |sum| each_chunk_from { |chunk| sum << chunk file.print chunk } } end private # the content is munged so if it's a checksum source_or_content is nil # unless the checksum indirectly comes from source def each_chunk_from if actual_content.is_a?(String) yield actual_content elsif content_is_really_a_checksum? && actual_content.nil? yield read_file_from_filebucket elsif actual_content.nil? yield '' end end def content_is_really_a_checksum? checksum?(should) end def read_file_from_filebucket dipper = resource.bucket raise "Could not get filebucket from file" unless dipper sum = should.sub(/\{\w+\}/, '') dipper.getfile(sum) rescue => detail self.fail Puppet::Error, "Could not retrieve content for #{should} from filebucket: #{detail}", detail end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/file/group.rb
lib/puppet/type/file/group.rb
# frozen_string_literal: true require_relative '../../../puppet/util/posix' module Puppet # Manage file group ownership. Puppet::Type.type(:file).newproperty(:group) do desc <<-EOT Which group should own the file. Argument can be either a group name or a group ID. On Windows, a user (such as "Administrator") can be set as a file's group and a group (such as "Administrators") can be set as a file's owner; however, a file's owner and group shouldn't be the same. (If the owner is also the group, files with modes like `"0640"` will cause log churn, as they will always appear out of sync.) EOT validate do |group| raise(Puppet::Error, "Invalid group name '#{group.inspect}'") unless group and group != "" end def insync?(current) # We don't want to validate/munge groups until we actually start to # evaluate this property, because they might be added during the catalog # apply. @should.map! do |val| gid = provider.name2gid(val) if gid gid elsif provider.resource.noop? return false else raise "Could not find group #{val}" end end @should.include?(current) end # We want to print names, not numbers def is_to_s(currentvalue) # rubocop:disable Naming/PredicateName super(provider.gid2name(currentvalue) || currentvalue) end def should_to_s(newvalue) super(provider.gid2name(newvalue) || newvalue) 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/type/file/checksum.rb
lib/puppet/type/file/checksum.rb
# frozen_string_literal: true require_relative '../../../puppet/util/checksums' # Specify which checksum algorithm to use when checksumming # files. Puppet::Type.type(:file).newparam(:checksum) do include Puppet::Util::Checksums # The default is defined in Puppet.default_digest_algorithm desc "The checksum type to use when determining whether to replace a file's contents. The default checksum type is sha256." # The values are defined in Puppet::Util::Checksums.known_checksum_types newvalues(:sha256, :sha256lite, :md5, :md5lite, :sha1, :sha1lite, :sha512, :sha384, :sha224, :mtime, :ctime, :none) defaultto do Puppet[:digest_algorithm].to_sym end validate do |value| if Puppet::Util::Platform.fips_enabled? && (value == :md5 || value == :md5lite) raise ArgumentError, _("MD5 is not supported in FIPS mode") end end def sum(content) content = content.is_a?(Puppet::Pops::Types::PBinaryType::Binary) ? content.binary_buffer : content type = digest_algorithm "{#{type}}" + send(type, content) end def sum_file(path) type = digest_algorithm method = type.to_s + "_file" "{#{type}}" + send(method, path).to_s end def sum_stream(&block) type = digest_algorithm method = type.to_s + "_stream" checksum = send(method, &block) "{#{type}}#{checksum}" end private # Return the appropriate digest algorithm with fallbacks in case puppet defaults have not # been initialized. def digest_algorithm value || Puppet[:digest_algorithm].to_sym end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/file/mode.rb
lib/puppet/type/file/mode.rb
# frozen_string_literal: true # Manage file modes. This state should support different formats # for specification (e.g., u+rwx, or -0011), but for now only supports # specifying the full mode. module Puppet Puppet::Type.type(:file).newproperty(:mode) do require_relative '../../../puppet/util/symbolic_file_mode' include Puppet::Util::SymbolicFileMode desc <<-'EOT' The desired permissions mode for the file, in symbolic or numeric notation. This value **must** be specified as a string; do not use un-quoted numbers to represent file modes. If the mode is omitted (or explicitly set to `undef`), Puppet does not enforce permissions on existing files and creates new files with permissions of `0644`. The `file` type uses traditional Unix permission schemes and translates them to equivalent permissions for systems which represent permissions differently, including Windows. For detailed ACL controls on Windows, you can leave `mode` unmanaged and use [the puppetlabs/acl module.](https://forge.puppetlabs.com/puppetlabs/acl) Numeric modes should use the standard octal notation of `<SETUID/SETGID/STICKY><OWNER><GROUP><OTHER>` (for example, "0644"). * Each of the "owner," "group," and "other" digits should be a sum of the permissions for that class of users, where read = 4, write = 2, and execute/search = 1. * The setuid/setgid/sticky digit is also a sum, where setuid = 4, setgid = 2, and sticky = 1. * The setuid/setgid/sticky digit is optional. If it is absent, Puppet will clear any existing setuid/setgid/sticky permissions. (So to make your intent clear, you should use at least four digits for numeric modes.) * When specifying numeric permissions for directories, Puppet sets the search permission wherever the read permission is set. Symbolic modes should be represented as a string of comma-separated permission clauses, in the form `<WHO><OP><PERM>`: * "Who" should be any combination of u (user), g (group), and o (other), or a (all) * "Op" should be = (set exact permissions), + (add select permissions), or - (remove select permissions) * "Perm" should be one or more of: * r (read) * w (write) * x (execute/search) * t (sticky) * s (setuid/setgid) * X (execute/search if directory or if any one user can execute) * u (user's current permissions) * g (group's current permissions) * o (other's current permissions) Thus, mode `"0664"` could be represented symbolically as either `a=r,ug+w` or `ug=rw,o=r`. However, symbolic modes are more expressive than numeric modes: a mode only affects the specified bits, so `mode => 'ug+w'` will set the user and group write bits, without affecting any other bits. See the manual page for GNU or BSD `chmod` for more details on numeric and symbolic modes. On Windows, permissions are translated as follows: * Owner and group names are mapped to Windows SIDs * The "other" class of users maps to the "Everyone" SID * The read/write/execute permissions map to the `FILE_GENERIC_READ`, `FILE_GENERIC_WRITE`, and `FILE_GENERIC_EXECUTE` access rights; a file's owner always has the `FULL_CONTROL` right * "Other" users can't have any permissions a file's group lacks, and its group can't have any permissions its owner lacks; that is, "0644" is an acceptable mode, but "0464" is not. EOT validate do |value| unless value.is_a?(String) raise Puppet::Error, "The file mode specification must be a string, not '#{value.class.name}'" end unless value.nil? or valid_symbolic_mode?(value) raise Puppet::Error, "The file mode specification is invalid: #{value.inspect}" end end munge do |value| return nil if value.nil? unless valid_symbolic_mode?(value) raise Puppet::Error, "The file mode specification is invalid: #{value.inspect}" end # normalizes to symbolic form, e.g. u+a, an octal string without leading 0 normalize_symbolic_mode(value) end unmunge do |value| # return symbolic form or octal string *with* leading 0's display_mode(value) if value end def desired_mode_from_current(desired, current) current = current.to_i(8) if current.is_a? String is_a_directory = @resource.stat && @resource.stat.directory? symbolic_mode_to_int(desired, current, is_a_directory) end # If we're a directory, we need to be executable for all cases # that are readable. This should probably be selectable, but eh. def dirmask(value) if FileTest.directory?(resource[:path]) and value =~ /^\d+$/ then value = value.to_i(8) value |= 0o100 if value & 0o400 != 0 value |= 0o10 if value & 0o40 != 0 value |= 0o1 if value & 0o4 != 0 value = value.to_s(8) end value end # If we're not following links and we're a link, then we just turn # off mode management entirely. def insync?(currentvalue) if provider.respond_to?(:munge_windows_system_group) munged_mode = provider.munge_windows_system_group(currentvalue, @should) return false if munged_mode.nil? currentvalue = munged_mode end stat = @resource.stat if stat && stat.ftype == "link" && @resource[:links] != :follow debug _("Not managing symlink mode") true else super(currentvalue) end end def property_matches?(current, desired) return false unless current current_bits = normalize_symbolic_mode(current) desired_bits = desired_mode_from_current(desired, current).to_s(8) current_bits == desired_bits end # Ideally, dirmask'ing could be done at munge time, but we don't know if 'ensure' # will eventually be a directory or something else. And unfortunately, that logic # depends on the ensure, source, and target properties. So rather than duplicate # that logic, and get it wrong, we do dirmask during retrieve, after 'ensure' has # been synced. def retrieve if @resource.stat @should &&= @should.collect { |s| dirmask(s) } end super end # Finally, when we sync the mode out we need to transform it; since we # don't have access to the calculated "desired" value here, or the # "current" value, only the "should" value we need to retrieve again. def sync current = @resource.stat ? @resource.stat.mode : 0o644 set(desired_mode_from_current(@should[0], current).to_s(8)) end def change_to_s(old_value, desired) return super if desired =~ /^\d+$/ old_bits = normalize_symbolic_mode(old_value) new_bits = normalize_symbolic_mode(desired_mode_from_current(desired, old_bits)) super(old_bits, new_bits) + " (#{desired})" end def should_to_s(should_value) "'#{should_value.rjust(4, '0')}'" end def is_to_s(currentvalue) # rubocop:disable Naming/PredicateName if currentvalue == :absent # This can occur during audits---if a file is transitioning from # present to absent the mode will have a value of `:absent`. super else "'#{currentvalue.rjust(4, '0')}'" end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/file/type.rb
lib/puppet/type/file/type.rb
# frozen_string_literal: true module Puppet Puppet::Type.type(:file).newproperty(:type) do require 'etc' desc "A read-only state to check the file type." def retrieve current_value = :absent stat = @resource.stat if stat current_value = stat.ftype end current_value end validate do |_val| fail "type is read-only" end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/file/checksum_value.rb
lib/puppet/type/file/checksum_value.rb
# frozen_string_literal: true require_relative '../../../puppet/util/checksums' require_relative '../../../puppet/type/file/data_sync' module Puppet Puppet::Type.type(:file).newproperty(:checksum_value) do include Puppet::Util::Checksums include Puppet::DataSync desc "The checksum of the source contents. Only md5, sha256, sha224, sha384 and sha512 are supported when specifying this parameter. If this parameter is set, source_permissions will be assumed to be false, and ownership and permissions will not be read from source." def insync?(is) # If checksum_value and source are specified, manage the file contents. # Otherwise the content property will manage syncing. if resource.parameter(:source).nil? return true end checksum_insync?(resource.parameter(:source), is, true) { |inner| super(inner) } end def property_matches?(current, desired) return true if super(current, desired) date_matches?(resource.parameter(:checksum).value, current, desired) end def retrieve # If checksum_value and source are specified, manage the file contents. # Otherwise the content property will manage syncing. Don't compute the checksum twice. if resource.parameter(:source).nil? return nil end result = retrieve_checksum(resource) # If the returned type matches the util/checksums format (prefixed with the type), # strip the checksum type. result = sumdata(result) if checksum?(result) result end def sync if resource.parameter(:source).nil? devfail "checksum_value#sync should not be called without a source parameter" end # insync? only returns false if it expects to manage the file content, # so instruct the resource to write its contents. contents_sync(resource.parameter(:source)) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/file/owner.rb
lib/puppet/type/file/owner.rb
# frozen_string_literal: true module Puppet Puppet::Type.type(:file).newproperty(:owner) do include Puppet::Util::Warnings desc <<-EOT The user to whom the file should belong. Argument can be a user name or a user ID. On Windows, a group (such as "Administrators") can be set as a file's owner and a user (such as "Administrator") can be set as a file's group; however, a file's owner and group shouldn't be the same. (If the owner is also the group, files with modes like `"0640"` will cause log churn, as they will always appear out of sync.) EOT def insync?(current) # We don't want to validate/munge users until we actually start to # evaluate this property, because they might be added during the catalog # apply. @should.map! do |val| uid = provider.name2uid(val) if uid uid elsif provider.resource.noop? return false else raise "Could not find user #{val}" end end return true if @should.include?(current) unless Puppet.features.root? warnonce "Cannot manage ownership unless running as root" return true end false end # We want to print names, not numbers def is_to_s(currentvalue) # rubocop:disable Naming/PredicateName super(provider.uid2name(currentvalue) || currentvalue) end def should_to_s(newvalue) super(provider.uid2name(newvalue) || newvalue) 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/type/file/selcontext.rb
lib/puppet/type/file/selcontext.rb
# frozen_string_literal: true # Manage SELinux context of files. # # This code actually manages three pieces of data in the context. # # [root@delenn files]# ls -dZ / # drwxr-xr-x root root system_u:object_r:root_t / # # The context of '/' here is 'system_u:object_r:root_t'. This is # three separate fields: # # system_u is the user context # object_r is the role context # root_t is the type context # # All three of these fields are returned in a single string by the # output of the stat command, but set individually with the chcon # command. This allows the user to specify a subset of the three # values while leaving the others alone. # # See https://www.nsa.gov/selinux/ for complete docs on SELinux. module Puppet require_relative '../../../puppet/util/selinux' class SELFileContext < Puppet::Property include Puppet::Util::SELinux def retrieve return :absent unless @resource.stat context = get_selinux_current_context(@resource[:path]) is = parse_selinux_context(name, context) if name == :selrange and selinux_support? selinux_category_to_label(is) else is end end def retrieve_default_context(property) return nil if Puppet::Util::Platform.windows? if @resource[:selinux_ignore_defaults] == :true return nil end context = get_selinux_default_context_with_handle(@resource[:path], provider.class.selinux_handle, @resource[:ensure]) unless context return nil end property_default = parse_selinux_context(property, context) debug "Found #{property} default '#{property_default}' for #{@resource[:path]}" unless property_default.nil? property_default end def insync?(value) if !selinux_support? debug("SELinux bindings not found. Ignoring parameter.") true elsif !selinux_label_support?(@resource[:path]) debug("SELinux not available for this filesystem. Ignoring parameter.") true else super end end def unsafe_munge(should) unless selinux_support? return should end if name == :selrange selinux_category_to_label(should) else should end end def sync set_selinux_context(@resource[:path], @should, name) :file_changed end end Puppet::Type.type(:file).newparam(:selinux_ignore_defaults) do desc "If this is set, Puppet will not call the SELinux function selabel_lookup to supply defaults for the SELinux attributes (seluser, selrole, seltype, and selrange). In general, you should leave this set at its default and only set it to true when you need Puppet to not try to fix SELinux labels automatically." newvalues(:true, :false) defaultto :false end Puppet::Type.type(:file).newproperty(:seluser, :parent => Puppet::SELFileContext) do desc "What the SELinux user component of the context of the file should be. Any valid SELinux user component is accepted. For example `user_u`. If not specified, it defaults to the value returned by selabel_lookup for the file, if any exists. Only valid on systems with SELinux support enabled." @event = :file_changed defaultto { retrieve_default_context(:seluser) } end Puppet::Type.type(:file).newproperty(:selrole, :parent => Puppet::SELFileContext) do desc "What the SELinux role component of the context of the file should be. Any valid SELinux role component is accepted. For example `role_r`. If not specified, it defaults to the value returned by selabel_lookup for the file, if any exists. Only valid on systems with SELinux support enabled." @event = :file_changed defaultto { retrieve_default_context(:selrole) } end Puppet::Type.type(:file).newproperty(:seltype, :parent => Puppet::SELFileContext) do desc "What the SELinux type component of the context of the file should be. Any valid SELinux type component is accepted. For example `tmp_t`. If not specified, it defaults to the value returned by selabel_lookup for the file, if any exists. Only valid on systems with SELinux support enabled." @event = :file_changed defaultto { retrieve_default_context(:seltype) } end Puppet::Type.type(:file).newproperty(:selrange, :parent => Puppet::SELFileContext) do desc "What the SELinux range component of the context of the file should be. Any valid SELinux range component is accepted. For example `s0` or `SystemHigh`. If not specified, it defaults to the value returned by selabel_lookup for the file, if any exists. Only valid on systems with SELinux support enabled and that have support for MCS (Multi-Category Security)." @event = :file_changed defaultto { retrieve_default_context(:selrange) } end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/file/ensure.rb
lib/puppet/type/file/ensure.rb
# frozen_string_literal: true module Puppet Puppet::Type.type(:file).ensurable do require 'etc' require_relative '../../../puppet/util/symbolic_file_mode' include Puppet::Util::SymbolicFileMode desc <<-EOT Whether the file should exist, and if so what kind of file it should be. Possible values are `present`, `absent`, `file`, `directory`, and `link`. * `present` accepts any form of file existence, and creates a normal file if the file is missing. (The file will have no content unless the `content` or `source` attribute is used.) * `absent` ensures the file doesn't exist, and deletes it if necessary. * `file` ensures it's a normal file, and enables use of the `content` or `source` attribute. * `directory` ensures it's a directory, and enables use of the `source`, `recurse`, `recurselimit`, `ignore`, and `purge` attributes. * `link` ensures the file is a symlink, and **requires** that you also set the `target` attribute. Symlinks are supported on all Posix systems and on Windows Vista / 2008 and higher. On Windows, managing symlinks requires Puppet agent's user account to have the "Create Symbolic Links" privilege; this can be configured in the "User Rights Assignment" section in the Windows policy editor. By default, Puppet agent runs as the Administrator account, which has this privilege. Puppet avoids destroying directories unless the `force` attribute is set to `true`. This means that if a file is currently a directory, setting `ensure` to anything but `directory` or `present` will cause Puppet to skip managing the resource and log either a notice or an error. There is one other non-standard value for `ensure`. If you specify the path to another file as the ensure value, it is equivalent to specifying `link` and using that path as the `target`: # Equivalent resources: file { '/etc/inetd.conf': ensure => '/etc/inet/inetd.conf', } file { '/etc/inetd.conf': ensure => link, target => '/etc/inet/inetd.conf', } However, we recommend using `link` and `target` explicitly, since this behavior can be harder to read and is [deprecated](https://docs.puppet.com/puppet/4.3/deprecated_language.html) as of Puppet 4.3.0. EOT # Most 'ensure' properties have a default, but with files we, um, don't. nodefault newvalue(:absent) do Puppet::FileSystem.unlink(@resource[:path]) end aliasvalue(:false, :absent) newvalue(:file, :event => :file_created) do # Make sure we're not managing the content some other way property = @resource.property(:content) || @resource.property(:checksum_value) if property property.sync else @resource.write @resource.should(:mode) end end # aliasvalue(:present, :file) newvalue(:present, :event => :file_created) do # Make a file if they want something, but this will match almost # anything. set_file end newvalue(:directory, :event => :directory_created) do mode = @resource.should(:mode) parent = File.dirname(@resource[:path]) unless Puppet::FileSystem.exist? parent raise Puppet::Error, "Cannot create #{@resource[:path]}; parent directory #{parent} does not exist" end if mode Puppet::Util.withumask(0o00) do Dir.mkdir(@resource[:path], symbolic_mode_to_int(mode, 0o755, true)) end else Dir.mkdir(@resource[:path]) end @resource.send(:property_fix) return :directory_created end newvalue(:link, :event => :link_created, :required_features => :manages_symlinks) do property = resource.property(:target) fail "Cannot create a symlink without a target" unless property property.retrieve property.mklink end # Symlinks. newvalue(/./) do # This code never gets executed. We need the regex to support # specifying it, but the work is done in the 'symlink' code block. end munge do |value| value = super(value) unless value.is_a? Symbol resource[:target] = value value = :link end resource[:links] = :manage if value == :link and resource[:links] != :follow value end def change_to_s(currentvalue, newvalue) return super unless [:file, :present].include?(newvalue) property = @resource.property(:content) return super unless property # We know that content is out of sync if we're here, because # it's essentially equivalent to 'ensure' in the transaction. source = @resource.parameter(:source) if source should = source.checksum else should = property.should end if should == :absent is = property.retrieve else is = :absent end property.change_to_s(is, should) end # Check that we can actually create anything def check basedir = File.dirname(@resource[:path]) if !Puppet::FileSystem.exist?(basedir) raise Puppet::Error, "Can not create #{@resource.title}; parent directory does not exist" elsif !FileTest.directory?(basedir) raise Puppet::Error, "Can not create #{@resource.title}; #{dirname} is not a directory" end end # We have to treat :present specially, because it works with any # type of file. def insync?(currentvalue) unless currentvalue == :absent or resource.replace? return true end if should == :present !(currentvalue.nil? or currentvalue == :absent) else super(currentvalue) end end def retrieve stat = @resource.stat if stat stat.ftype.intern elsif should == :false :false else :absent end end def sync @resource.remove_existing(should) if should == :absent return :file_removed end super end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/file/data_sync.rb
lib/puppet/type/file/data_sync.rb
# frozen_string_literal: true require_relative '../../../puppet/util/checksums' require_relative '../../../puppet/util/diff' require 'date' require 'tempfile' module Puppet module DataSync include Puppet::Util::Checksums include Puppet::Util::Diff def write_temporarily(param) tempfile = Tempfile.new("puppet-file") tempfile.open param.write(tempfile) tempfile.close yield tempfile.path ensure tempfile.delete if tempfile end def checksum_insync?(param, is, has_contents, &block) resource = param.resource if resource.should_be_file? return false if is == :absent else if resource[:ensure] == :present && has_contents && (s = resource.stat) # TRANSLATORS 'Ensure' is an attribute and ':present' is a value and should not be translated resource.warning _("Ensure set to :present but file type is %{file_type} so no content will be synced") % { file_type: s.ftype } end return true end return true unless resource.replace? is_insync = yield(is) if show_diff?(!is_insync) if param.sensitive send resource[:loglevel], "[diff redacted]" else write_temporarily(param) do |path| diff_output = diff(resource[:path], path) if diff_output.encoding == Encoding::BINARY || !diff_output.valid_encoding? diff_output = "Binary files #{resource[:path]} and #{path} differ" end send resource[:loglevel], "\n" + diff_output end end end is_insync end def show_diff?(has_changes) has_changes && Puppet[:show_diff] && resource.show_diff? end def date_matches?(checksum_type, current, desired) time_types = [:mtime, :ctime] return false unless time_types.include?(checksum_type) return false unless current && desired begin if checksum?(current) || checksum?(desired) raise if !time_types.include?(sumtype(current).to_sym) || !time_types.include?(sumtype(desired).to_sym) current = sumdata(current) desired = sumdata(desired) end DateTime.parse(current) >= DateTime.parse(desired) rescue => detail self.fail Puppet::Error, "Resource with checksum_type #{checksum_type} didn't contain a date in #{current} or #{desired}", detail.backtrace end end def retrieve_checksum(resource) stat = resource.stat return :absent unless stat ftype = stat.ftype # Don't even try to manage the content on directories or links return nil if %w[directory link fifo socket].include?(ftype) begin resource.parameter(:checksum).sum_file(resource[:path]) rescue => detail raise Puppet::Error, "Could not read #{ftype} #{resource.title}: #{detail}", detail.backtrace end end def contents_sync(param) return_event = param.resource.stat ? :file_changed : :file_created resource.write(param) return_event end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/type/file/mtime.rb
lib/puppet/type/file/mtime.rb
# frozen_string_literal: true module Puppet Puppet::Type.type(:file).newproperty(:mtime) do desc "A read-only state to check the file mtime. On \*nix-like systems, this is the time of the most recent change to the content of the file." def retrieve current_value = :absent stat = @resource.stat if stat current_value = stat.mtime end current_value.to_s end validate do |_val| fail "mtime is read-only" end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/generate/type.rb
lib/puppet/generate/type.rb
# frozen_string_literal: true require 'erb' require 'fileutils' require_relative '../../puppet/util/autoload' require_relative '../../puppet/generate/models/type/type' module Puppet module Generate # Responsible for generating type definitions in Puppet class Type # Represents an input to the type generator class Input # Gets the path to the input. attr_reader :path # Gets the format to use for generating the output file. attr_reader :format # Initializes an input. # @param base [String] The base path where the input is located. # @param path [String] The path to the input file. # @param format [Symbol] The format to use for generation. # @return [void] def initialize(base, path, format) @base = base @path = path self.format = format end # Gets the expected resource type name for the input. # @return [Symbol] Returns the expected resource type name for the input. def type_name File.basename(@path, '.rb').to_sym end # Sets the format to use for this input. # @param format [Symbol] The format to use for generation. # @return [Symbol] Returns the new format. def format=(format) format = format.to_sym raise _("unsupported format '%{format}'.") % { format: format } unless self.class.supported_format?(format) @format = format end # Determines if the output file is up-to-date with respect to the input file. # @param [String, nil] The path to output to, or nil if determined by input # @return [Boolean] Returns true if the output is up-to-date or false if not. def up_to_date?(outputdir) f = effective_output_path(outputdir) Puppet::FileSystem.exist?(f) && (Puppet::FileSystem.stat(@path) <=> Puppet::FileSystem.stat(f)) <= 0 end # Gets the filename of the output file. # @return [String] Returns the name to the output file. def output_name @output_name ||= case @format when :pcore "#{File.basename(@path, '.rb')}.pp" else raise _("unsupported format '%{format}'.") % { format: @format } end end # Gets the path to the output file. # @return [String] Returns the path to the output file. def output_path @output_path ||= case @format when :pcore File.join(@base, 'pcore', 'types', output_name) else raise _("unsupported format '%{format}'.") % { format: @format } end end # Sets the path to the output file. # @param path [String] The new path to the output file. # @return [String] Returns the new path to the output file. def output_path=(path) @output_path = path end # Returns the outputpath to use given an outputdir that may be nil # If outputdir is not nil, the returned path is relative to that outpudir # otherwise determined by this input. # @param [String, nil] The outputdirectory to use, or nil if to be determined by this Input def effective_output_path(outputdir) outputdir ? File.join(outputdir, output_name) : output_path end # Gets the path to the template to use for this input. # @return [String] Returns the path to the template. def template_path File.join(File.dirname(__FILE__), 'templates', 'type', "#{@format}.erb") end # Gets the string representation of the input. # @return [String] Returns the string representation of the input. def to_s @path end # Determines if the given format is supported # @param format [Symbol] The format to use for generation. # @return [Boolean] Returns true if the format is supported or false if not. def self.supported_format?(format) [:pcore].include?(format) end end # Finds the inputs for the generator. # @param format [Symbol] The format to use. # @param environment [Puppet::Node::Environment] The environment to search for inputs. Defaults to the current environment. # @return [Array<Input>] Returns the array of inputs. def self.find_inputs(format = :pcore, environment = Puppet.lookup(:current_environment)) Puppet.debug "Searching environment '#{environment.name}' for custom types." inputs = [] environment.modules.each do |mod| directory = File.join(Puppet::Util::Autoload.cleanpath(mod.plugin_directory), 'puppet', 'type') unless Puppet::FileSystem.exist?(directory) Puppet.debug "Skipping '#{mod.name}' module because it contains no custom types." next end Puppet.debug "Searching '#{mod.name}' module for custom types." Dir.glob("#{directory}/*.rb") do |file| next unless Puppet::FileSystem.file?(file) Puppet.debug "Found custom type source file '#{file}'." inputs << Input.new(mod.path, file, format) end end # Sort the inputs by path inputs.sort_by!(&:path) end def self.bad_input? @bad_input end # Generates files for the given inputs. # If a file is up to date (newer than input) it is kept. # If a file is out of date it is regenerated. # If there is a file for a non existing output in a given output directory it is removed. # If using input specific output removal must be made by hand if input is removed. # # @param inputs [Array<Input>] The inputs to generate files for. # @param outputdir [String, nil] the outputdir where all output should be generated, or nil if next to input # @param force [Boolean] True to force the generation of the output files (skip up-to-date checks) or false if not. # @return [void] def self.generate(inputs, outputdir = nil, force = false) # remove files for non existing inputs unless outputdir.nil? filenames_to_keep = inputs.map(&:output_name) existing_files = Puppet::FileSystem.children(outputdir).map { |f| Puppet::FileSystem.basename(f) } files_to_remove = existing_files - filenames_to_keep files_to_remove.each do |f| Puppet::FileSystem.unlink(File.join(outputdir, f)) end Puppet.notice(_("Removed output '%{files_to_remove}' for non existing inputs") % { files_to_remove: files_to_remove }) unless files_to_remove.empty? end if inputs.empty? Puppet.notice _('No custom types were found.') return nil end templates = {} templates.default_proc = lambda { |_hash, key| raise _("template was not found at '%{key}'.") % { key: key } unless Puppet::FileSystem.file?(key) template = Puppet::Util.create_erb(File.read(key)) template.filename = key template } up_to_date = true @bad_input = false Puppet.notice _('Generating Puppet resource types.') inputs.each do |input| if !force && input.up_to_date?(outputdir) Puppet.debug "Skipping '#{input}' because it is up-to-date." next end up_to_date = false type_name = input.type_name Puppet.debug "Loading custom type '#{type_name}' in '#{input}'." begin require input.path rescue SystemExit raise rescue Exception => e # Log the exception and move on to the next input @bad_input = true Puppet.log_exception(e, _("Failed to load custom type '%{type_name}' from '%{input}': %{message}") % { type_name: type_name, input: input, message: e.message }) next end # HACK: there's no way to get a type without loading it (sigh); for now, just get the types hash directly types ||= Puppet::Type.instance_variable_get('@types') # Assume the type follows the naming convention type = types[type_name] unless type Puppet.err _("Custom type '%{type_name}' was not defined in '%{input}'.") % { type_name: type_name, input: input } next end # Create the model begin model = Models::Type::Type.new(type) rescue Exception => e @bad_input = true # Move on to the next input Puppet.log_exception(e, "#{input}: #{e.message}") next end # Render the template begin result = model.render(templates[input.template_path]) rescue Exception => e @bad_input = true Puppet.log_exception(e) raise end # Write the output file begin effective_output_path = input.effective_output_path(outputdir) Puppet.notice _("Generating '%{effective_output_path}' using '%{format}' format.") % { effective_output_path: effective_output_path, format: input.format } FileUtils.mkdir_p(File.dirname(effective_output_path)) Puppet::FileSystem.open(effective_output_path, nil, 'w:UTF-8') do |file| file.write(result) end rescue Exception => e @bad_input = true Puppet.log_exception(e, _("Failed to generate '%{effective_output_path}': %{message}") % { effective_output_path: effective_output_path, message: e.message }) # Move on to the next input next end end Puppet.notice _('No files were generated because all inputs were up-to-date.') if up_to_date end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/generate/models/type/type.rb
lib/puppet/generate/models/type/type.rb
# frozen_string_literal: true require_relative '../../../../puppet/generate/models/type/property' module Puppet module Generate module Models module Type # A model for Puppet resource types. class Type # Gets the name of the type as a Puppet string literal. attr_reader :name # Gets the doc string of the type. attr_reader :doc # Gets the properties of the type. attr_reader :properties # Gets the parameters of the type. attr_reader :parameters # Gets the title patterns of the type attr_reader :title_patterns # Gets the isomorphic member attribute of the type attr_reader :isomorphic # Gets the capability member attribute of the type attr_reader :capability # Initializes a type model. # @param type [Puppet::Type] The Puppet type to model. # @return [void] def initialize(type) @name = Puppet::Pops::Types::StringConverter.convert(type.name.to_s, '%p') @doc = type.doc.strip @properties = type.properties.map { |p| Property.new(p) } @parameters = type.parameters.map do |name| Property.new(type.paramclass(name)) end sc = Puppet::Pops::Types::StringConverter.singleton @title_patterns = type.title_patterns.to_h do |mapping| [ sc.convert(mapping[0], '%p'), sc.convert(mapping[1].map do |names| next if names.empty? raise Puppet::Error, _('title patterns that use procs are not supported.') unless names.size == 1 names[0].to_s end, '%p') ] end @isomorphic = type.isomorphic? # continue to emit capability as false when rendering the ERB # template, so that pcore modules generated prior to puppet7 can be # read by puppet7 and vice-versa. @capability = false end def render(template) template.result(binding) end end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/generate/models/type/property.rb
lib/puppet/generate/models/type/property.rb
# frozen_string_literal: true module Puppet module Generate module Models module Type # A model for resource type properties and parameters. class Property # Gets the name of the property as a Puppet string literal. attr_reader :name # Gets the Puppet type of the property. attr_reader :type # Gets the doc string of the property. attr_reader :doc # Initializes a property model. # @param property [Puppet::Property] The Puppet property to model. # @return [void] def initialize(property) @name = Puppet::Pops::Types::StringConverter.convert(property.name.to_s, '%p') @type = self.class.get_puppet_type(property) @doc = property.doc.strip @is_namevar = property.isnamevar? end # Determines if this property is a namevar. # @return [Boolean] Returns true if the property is a namevar or false if not. def is_namevar? @is_namevar end # Gets the Puppet type for a property. # @param property [Puppet::Property] The Puppet property to get the Puppet type for. # @return [String] Returns the string representing the Puppet type. def self.get_puppet_type(property) # HACK: the value collection does not expose the underlying value information at all # thus this horribleness to get the underlying values hash regexes = [] strings = [] values = property.value_collection.instance_variable_get('@values') || {} values.each do |_, value| if value.regex? regexes << Puppet::Pops::Types::StringConverter.convert(value.name, '%p') next end strings << Puppet::Pops::Types::StringConverter.convert(value.name.to_s, '%p') value.aliases.each do |a| strings << Puppet::Pops::Types::StringConverter.convert(a.to_s, '%p') end end # If no string or regexes, default to Any type return 'Any' if strings.empty? && regexes.empty? # Calculate a variant of supported values # Note that boolean strings are mapped to Variant[Boolean, Enum['true', 'false']] # because of tech debt... enum = strings.empty? ? nil : "Enum[#{strings.join(', ')}]" pattern = regexes.empty? ? nil : "Pattern[#{regexes.join(', ')}]" boolean = strings.include?('\'true\'') || strings.include?('\'false\'') ? 'Boolean' : nil variant = [boolean, enum, pattern].compact return variant[0] if variant.size == 1 "Variant[#{variant.join(', ')}]" end end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/resource/type.rb
lib/puppet/resource/type.rb
# frozen_string_literal: true require_relative '../../puppet/parser' require_relative '../../puppet/util/warnings' require_relative '../../puppet/util/errors' require_relative '../../puppet/parser/ast/leaf' # Puppet::Resource::Type represents nodes, classes and defined types. # # @api public class Puppet::Resource::Type Puppet::ResourceType = self include Puppet::Util::Warnings include Puppet::Util::Errors RESOURCE_KINDS = [:hostclass, :node, :definition] # Map the names used in our documentation to the names used internally RESOURCE_KINDS_TO_EXTERNAL_NAMES = { :hostclass => "class", :node => "node", :definition => "defined_type" } RESOURCE_EXTERNAL_NAMES_TO_KINDS = RESOURCE_KINDS_TO_EXTERNAL_NAMES.invert NAME = 'name' TITLE = 'title' MODULE_NAME = 'module_name' CALLER_MODULE_NAME = 'caller_module_name' PARAMETERS = 'parameters' KIND = 'kind' NODES = 'nodes' DOUBLE_COLON = '::' EMPTY_ARRAY = [].freeze LOOKAROUND_OPERATORS = { "(" => 'LP', "?" => "QU", "<" => "LT", ">" => "GT", "!" => "EX", "=" => "EQ", ")" => 'RP' }.freeze attr_accessor :file, :line, :doc, :code, :parent, :resource_type_collection, :override attr_reader :namespace, :arguments, :behaves_like, :module_name # Map from argument (aka parameter) names to Puppet Type # @return [Hash<Symbol, Puppet::Pops::Types::PAnyType] map from name to type # attr_reader :argument_types # This should probably be renamed to 'kind' eventually, in accordance with the changes # made for serialization and API usability (#14137). At the moment that seems like # it would touch a whole lot of places in the code, though. --cprice 2012-04-23 attr_reader :type RESOURCE_KINDS.each do |t| define_method("#{t}?") { type == t } end # Are we a child of the passed class? Do a recursive search up our # parentage tree to figure it out. def child_of?(klass) return true if override return false unless parent (klass == parent_type ? true : parent_type.child_of?(klass)) end # Now evaluate the code associated with this class or definition. def evaluate_code(resource) static_parent = evaluate_parent_type(resource) scope = static_parent || resource.scope scope = scope.newscope(:source => self, :resource => resource) unless resource.title == :main scope.compiler.add_class(name) unless definition? set_resource_parameters(resource, scope) resource.add_edge_to_stage if code if @match # Only bother setting up the ephemeral scope if there are match variables to add into it scope.with_guarded_scope do scope.ephemeral_from(@match, file, line) code.safeevaluate(scope) end else code.safeevaluate(scope) end end end def initialize(type, name, options = {}) @type = type.to_s.downcase.to_sym raise ArgumentError, _("Invalid resource supertype '%{type}'") % { type: type } unless RESOURCE_KINDS.include?(@type) name = convert_from_ast(name) if name.is_a?(Puppet::Parser::AST::HostName) set_name_and_namespace(name) [:code, :doc, :line, :file, :parent].each do |param| value = options[param] next unless value send(param.to_s + '=', value) end set_arguments(options[:arguments]) set_argument_types(options[:argument_types]) @match = nil @module_name = options[:module_name] end # This is only used for node names, and really only when the node name # is a regexp. def match(string) return string.to_s.downcase == name unless name_is_regex? @match = @name.match(string) end # Add code from a new instance to our code. def merge(other) fail _("%{name} is not a class; cannot add code to it") % { name: name } unless type == :hostclass fail _("%{name} is not a class; cannot add code from it") % { name: other.name } unless other.type == :hostclass if name == "" && Puppet.settings[:freeze_main] # It is ok to merge definitions into main even if freeze is on (definitions are nodes, classes, defines, functions, and types) unless other.code.is_definitions_only? fail _("Cannot have code outside of a class/node/define because 'freeze_main' is enabled") end end if parent and other.parent and parent != other.parent fail _("Cannot merge classes with different parent classes (%{name} => %{parent} vs. %{other_name} => %{other_parent})") % { name: name, parent: parent, other_name: other.name, other_parent: other.parent } end # We know they're either equal or only one is set, so keep whichever parent is specified. self.parent ||= other.parent if other.doc self.doc ||= "" self.doc += other.doc end # This might just be an empty, stub class. return unless other.code unless code self.code = other.code return end self.code = Puppet::Parser::ParserFactory.code_merger.concatenate([self, other]) end # Make an instance of the resource type, and place it in the catalog # if it isn't in the catalog already. This is only possible for # classes and nodes. No parameters are be supplied--if this is a # parameterized class, then all parameters take on their default # values. def ensure_in_catalog(scope, parameters = nil) resource_type = case type when :definition raise ArgumentError, _('Cannot create resources for defined resource types') when :hostclass :class when :node :node end # Do nothing if the resource already exists; this makes sure we don't # get multiple copies of the class resource, which helps provide the # singleton nature of classes. # we should not do this for classes with parameters # if parameters are passed, we should still try to create the resource # even if it exists so that we can fail # this prevents us from being able to combine param classes with include if parameters.nil? resource = scope.catalog.resource(resource_type, name) return resource unless resource.nil? elsif parameters.is_a?(Hash) parameters = parameters.map { |k, v| Puppet::Parser::Resource::Param.new(:name => k, :value => v, :source => self) } end resource = Puppet::Parser::Resource.new(resource_type, name, :scope => scope, :source => self, :parameters => parameters) instantiate_resource(scope, resource) scope.compiler.add_resource(scope, resource) resource end def instantiate_resource(scope, resource) # Make sure our parent class has been evaluated, if we have one. if parent && !scope.catalog.resource(resource.type, parent) parent_type(scope).ensure_in_catalog(scope) end if %w[Class Node].include? resource.type scope.catalog.merge_tags_from(resource) end end def name if type == :node && name_is_regex? # Normalize lookarround regex patthern internal_name = @name.source.downcase.gsub(/\(\?[^)]*\)/) do |str| str.gsub(/./) { |ch| LOOKAROUND_OPERATORS[ch] || ch } end "__node_regexp__#{internal_name.gsub(/[^-\w:.]/, '').sub(/^\.+/, '')}" else @name end end def name_is_regex? @name.is_a?(Regexp) end def parent_type(scope = nil) return nil unless parent @parent_type ||= scope.environment.known_resource_types.send("find_#{type}", parent) || fail(Puppet::ParseError, _("Could not find parent resource type '%{parent}' of type %{parent_type} in %{env}") % { parent: parent, parent_type: type, env: scope.environment }) end # Validate and set any arguments passed by the resource as variables in the scope. # # This method is known to only be used on the server/compile side. # # @param resource [Puppet::Parser::Resource] the resource # @param scope [Puppet::Parser::Scope] the scope # # @api private def set_resource_parameters(resource, scope) # Inject parameters from using external lookup modname = resource[:module_name] || module_name scope[MODULE_NAME] = modname unless modname.nil? caller_name = resource[:caller_module_name] || scope.parent_module_name scope[CALLER_MODULE_NAME] = caller_name unless caller_name.nil? inject_external_parameters(resource, scope) if @type == :hostclass scope[TITLE] = resource.title.to_s.downcase scope[NAME] = resource.name.to_s.downcase else scope[TITLE] = resource.title scope[NAME] = resource.name end scope.class_set(name, scope) if hostclass? || node? param_hash = scope.with_parameter_scope(resource.to_s, arguments.keys) do |param_scope| # Assign directly to the parameter scope to avoid scope parameter validation at this point. It # will happen anyway when the values are assigned to the scope after the parameter scoped has # been popped. resource.each { |k, v| param_scope[k.to_s] = v.value unless k == :name || k == :title } assign_defaults(resource, param_scope, scope) param_scope.to_hash end validate_resource_hash(resource, param_hash) # Assign parameter values to current scope param_hash.each { |param, value| exceptwrap { scope[param] = value } } end # Lookup and inject parameters from external scope # @param resource [Puppet::Parser::Resource] the resource # @param scope [Puppet::Parser::Scope] the scope def inject_external_parameters(resource, scope) # Only lookup parameters for host classes return unless type == :hostclass parameters = resource.parameters arguments.each do |param_name, default| sym_name = param_name.to_sym param = parameters[sym_name] next unless param.nil? || param.value.nil? catch(:no_such_key) do bound_value = Puppet::Pops::Lookup.search_and_merge("#{name}::#{param_name}", Puppet::Pops::Lookup::Invocation.new(scope), nil) # Assign bound value but don't let an undef trump a default expression resource[sym_name] = bound_value unless bound_value.nil? && !default.nil? end end end private :inject_external_parameters def assign_defaults(resource, param_scope, scope) return unless resource.is_a?(Puppet::Parser::Resource) parameters = resource.parameters arguments.each do |param_name, default| next if default.nil? name = param_name.to_sym param = parameters[name] next unless param.nil? || param.value.nil? value = exceptwrap { param_scope.evaluate3x(param_name, default, scope) } resource[name] = value param_scope[param_name] = value end end private :assign_defaults def validate_resource_hash(resource, resource_hash) Puppet::Pops::Types::TypeMismatchDescriber.validate_parameters(resource.to_s, parameter_struct, resource_hash, false) end private :validate_resource_hash # Validate that all parameters given to the resource are correct # @param resource [Puppet::Resource] the resource to validate def validate_resource(resource) # Since Sensitive values have special encoding (in a separate parameter) an unwrapped sensitive value must be # recreated as a Sensitive in order to perform correct type checking. sensitives = Set.new(resource.sensitive_parameters) validate_resource_hash(resource, resource.parameters.to_h do |name, value| value_to_validate = sensitives.include?(name) ? Puppet::Pops::Types::PSensitiveType::Sensitive.new(value.value) : value.value [name.to_s, value_to_validate] end) end # Check whether a given argument is valid. def valid_parameter?(param) parameter_struct.hashed_elements.include?(param.to_s) end def set_arguments(arguments) @arguments = {} @parameter_struct = nil return if arguments.nil? arguments.each do |arg, default| arg = arg.to_s warn_if_metaparam(arg, default) @arguments[arg] = default end end # Sets the argument name to Puppet Type hash used for type checking. # Names must correspond to available arguments (they must be defined first). # Arguments not mentioned will not be type-checked. # def set_argument_types(name_to_type_hash) @argument_types = {} @parameter_struct = nil return unless name_to_type_hash name_to_type_hash.each do |name, t| # catch internal errors unless @arguments.include?(name) raise Puppet::DevError, _("Parameter '%{name}' is given a type, but is not a valid parameter.") % { name: name } end unless t.is_a? Puppet::Pops::Types::PAnyType raise Puppet::DevError, _("Parameter '%{name}' is given a type that is not a Puppet Type, got %{class_name}") % { name: name, class_name: t.class } end @argument_types[name] = t end end private def convert_from_ast(name) value = name.value if value.is_a?(Puppet::Parser::AST::Regex) value.value else value end end def evaluate_parent_type(resource) klass = parent_type(resource.scope) parent_resource = resource.scope.compiler.catalog.resource(:class, klass.name) || resource.scope.compiler.catalog.resource(:node, klass.name) if klass return unless klass && parent_resource parent_resource.evaluate unless parent_resource.evaluated? parent_scope(resource.scope, klass) end # Split an fq name into a namespace and name def namesplit(fullname) ary = fullname.split(DOUBLE_COLON) n = ary.pop || "" ns = ary.join(DOUBLE_COLON) [ns, n] end def parent_scope(scope, klass) scope.class_scope(klass) || raise(Puppet::DevError, _("Could not find scope for %{class_name}") % { class_name: klass.name }) end def set_name_and_namespace(name) if name.is_a?(Regexp) @name = name @namespace = "" else @name = name.to_s.downcase # Note we're doing something somewhat weird here -- we're setting # the class's namespace to its fully qualified name. This means # anything inside that class starts looking in that namespace first. @namespace, _ = @type == :hostclass ? [@name, ''] : namesplit(@name) end end def warn_if_metaparam(param, default) return unless Puppet::Type.metaparamclass(param) if default warnonce _("%{param} is a metaparam; this value will inherit to all contained resources in the %{name} definition") % { param: param, name: name } else raise Puppet::ParseError, _("%{param} is a metaparameter; please choose another parameter name in the %{name} definition") % { param: param, name: name } end end def parameter_struct @parameter_struct ||= create_params_struct end def create_params_struct arg_types = argument_types type_factory = Puppet::Pops::Types::TypeFactory members = { type_factory.optional(type_factory.string(NAME)) => type_factory.any } Puppet::Type.eachmetaparam do |name| # TODO: Once meta parameters are typed, this should change to reflect that type members[name.to_s] = type_factory.any end arguments.each_pair do |name, default| key_type = type_factory.string(name.to_s) key_type = type_factory.optional(key_type) unless default.nil? arg_type = arg_types[name] arg_type = type_factory.any if arg_type.nil? members[key_type] = arg_type end type_factory.struct(members) end private :create_params_struct end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/resource/catalog.rb
lib/puppet/resource/catalog.rb
# frozen_string_literal: true require_relative '../../puppet/node' require_relative '../../puppet/indirector' require_relative '../../puppet/transaction' require_relative '../../puppet/util/tagging' require_relative '../../puppet/graph' require 'securerandom' # This class models a node catalog. It is the thing meant to be passed # from server to client, and it contains all of the information in the # catalog, including the resources and the relationships between them. # # @api public class Puppet::Resource::Catalog < Puppet::Graph::SimpleGraph class DuplicateResourceError < Puppet::Error include Puppet::ExternalFileError end extend Puppet::Indirector indirects :catalog, :terminus_setting => :catalog_terminus include Puppet::Util::Tagging # The host name this is a catalog for. attr_accessor :name # The catalog version. Used for testing whether a catalog # is up to date. attr_accessor :version # The id of the code input to the compiler. attr_accessor :code_id # The UUID of the catalog attr_accessor :catalog_uuid # @return [Integer] catalog format version number. This value is constant # for a given version of Puppet; it is incremented when a new release of # Puppet changes the API for the various objects that make up the catalog. attr_accessor :catalog_format # Inlined file metadata for non-recursive find # A hash of title => metadata attr_accessor :metadata # Inlined file metadata for recursive search # A hash of title => { source => [metadata, ...] } attr_accessor :recursive_metadata # How long this catalog took to retrieve. Used for reporting stats. attr_accessor :retrieval_duration # Whether this is a host catalog, which behaves very differently. # In particular, reports are sent, graphs are made, and state is # stored in the state database. If this is set incorrectly, then you often # end up in infinite loops, because catalogs are used to make things # that the host catalog needs. attr_accessor :host_config # Whether this catalog was retrieved from the cache, which affects # whether it is written back out again. attr_accessor :from_cache # Some metadata to help us compile and generally respond to the current state. attr_accessor :client_version, :server_version # A String representing the environment for this catalog attr_accessor :environment # The actual environment instance that was used during compilation attr_accessor :environment_instance # Add classes to our class list. def add_class(*classes) classes.each do |klass| @classes << klass end # Add the class names as tags, too. tag(*classes) end # Returns [typename, title] when given a String with "Type[title]". # Returns [nil, nil] if '[' ']' not detected. # def title_key_for_ref(ref) s = ref.index('[') e = ref.rindex(']') if s && e && e > s a = [ref[0, s], ref[s + 1, e - s - 1]] else a = [nil, nil] end a end def add_resource_before(other, *resources) resources.each do |resource| other_title_key = title_key_for_ref(other.ref) idx = @resources.index(other_title_key) if idx.nil? raise ArgumentError, _("Cannot add resource %{resource_1} before %{resource_2} because %{resource_2} is not yet in the catalog") % { resource_1: resource.ref, resource_2: other.ref } end add_one_resource(resource, idx) end end # Add `resources` to the catalog after `other`. WARNING: adding # multiple resources will produce the reverse ordering, e.g. calling # `add_resource_after(A, [B,C])` will result in `[A,C,B]`. def add_resource_after(other, *resources) resources.each do |resource| other_title_key = title_key_for_ref(other.ref) idx = @resources.index(other_title_key) if idx.nil? raise ArgumentError, _("Cannot add resource %{resource_1} after %{resource_2} because %{resource_2} is not yet in the catalog") % { resource_1: resource.ref, resource_2: other.ref } end add_one_resource(resource, idx + 1) end end def add_resource(*resources) resources.each do |resource| add_one_resource(resource) end end # @param resource [A Resource] a resource in the catalog # @return [A Resource, nil] the resource that contains the given resource # @api public def container_of(resource) adjacent(resource, :direction => :in)[0] end def add_one_resource(resource, idx = -1) title_key = title_key_for_ref(resource.ref) if @resource_table[title_key] fail_on_duplicate_type_and_title(resource, title_key) end add_resource_to_table(resource, title_key, idx) create_resource_aliases(resource) resource.catalog = self if resource.respond_to?(:catalog=) add_resource_to_graph(resource) end private :add_one_resource def add_resource_to_table(resource, title_key, idx) @resource_table[title_key] = resource @resources.insert(idx, title_key) end private :add_resource_to_table def add_resource_to_graph(resource) add_vertex(resource) @relationship_graph.add_vertex(resource) if @relationship_graph end private :add_resource_to_graph def create_resource_aliases(resource) # Explicit aliases must always be processed # The alias setting logic checks, and does not error if the alias is set to an already set alias # for the same resource (i.e. it is ok if alias == title explicit_aliases = [resource[:alias]].flatten.compact explicit_aliases.each { |given_alias| self.alias(resource, given_alias) } # Skip creating uniqueness key alias and checking collisions for non-isomorphic resources. return unless resource.respond_to?(:isomorphic?) and resource.isomorphic? # Add an alias if the uniqueness key is valid and not the title, which has already been checked. ukey = resource.uniqueness_key if ukey.any? and ukey != [resource.title] self.alias(resource, ukey) end end private :create_resource_aliases # Create an alias for a resource. def alias(resource, key) ref = resource.ref ref =~ /^(.+)\[/ class_name = ::Regexp.last_match(1) || resource.class.name newref = [class_name, key].flatten if key.is_a? String ref_string = "#{class_name}[#{key}]" return if ref_string == ref end # LAK:NOTE It's important that we directly compare the references, # because sometimes an alias is created before the resource is # added to the catalog, so comparing inside the below if block # isn't sufficient. existing = @resource_table[newref] if existing return if existing == resource resource_declaration = Puppet::Util::Errors.error_location(resource.file, resource.line) msg = if resource_declaration.empty? # TRANSLATORS 'alias' should not be translated _("Cannot alias %{resource} to %{key}; resource %{newref} already declared") % { resource: ref, key: key.inspect, newref: newref.inspect } else # TRANSLATORS 'alias' should not be translated _("Cannot alias %{resource} to %{key} at %{resource_declaration}; resource %{newref} already declared") % { resource: ref, key: key.inspect, resource_declaration: resource_declaration, newref: newref.inspect } end msg += Puppet::Util::Errors.error_location_with_space(existing.file, existing.line) raise ArgumentError, msg end @resource_table[newref] = resource @aliases[ref] ||= [] @aliases[ref] << newref end # Apply our catalog to the local host. # @param options [Hash{Symbol => Object}] a hash of options # @option options [Puppet::Transaction::Report] :report # The report object to log this transaction to. This is optional, # and the resulting transaction will create a report if not # supplied. # # @return [Puppet::Transaction] the transaction created for this # application # # @api public def apply(options = {}) Puppet::Util::Storage.load if host_config? transaction = create_transaction(options) begin transaction.report.as_logging_destination do transaction_evaluate_time = Puppet::Util.thinmark do transaction.evaluate end transaction.report.add_times(:transaction_evaluation, transaction_evaluate_time) end ensure # Don't try to store state unless we're a host config # too recursive. Puppet::Util::Storage.store if host_config? end yield transaction if block_given? transaction end # The relationship_graph form of the catalog. This contains all of the # dependency edges that are used for determining order. # # @param given_prioritizer [Puppet::Graph::Prioritizer] The prioritization # strategy to use when constructing the relationship graph. Defaults the # being determined by the `ordering` setting. # @return [Puppet::Graph::RelationshipGraph] # @api public def relationship_graph(given_prioritizer = nil) if @relationship_graph.nil? @relationship_graph = Puppet::Graph::RelationshipGraph.new(given_prioritizer || prioritizer) @relationship_graph.populate_from(self) end @relationship_graph end def clear(remove_resources = true) super() # We have to do this so that the resources clean themselves up. @resource_table.values.each(&:remove) if remove_resources @resource_table.clear @resources = [] if @relationship_graph @relationship_graph.clear @relationship_graph = nil end end def classes @classes.dup end # Create a new resource and register it in the catalog. def create_resource(type, options) klass = Puppet::Type.type(type) unless klass raise ArgumentError, _("Unknown resource type %{type}") % { type: type } end resource = klass.new(options) return unless resource add_resource(resource) resource end # Make sure all of our resources are "finished". def finalize make_default_resources @resource_table.values.each(&:finish) write_graph(:resources) end def host_config? host_config end def initialize(name = nil, environment = Puppet::Node::Environment::NONE, code_id = nil) super() @name = name @catalog_uuid = SecureRandom.uuid @catalog_format = 2 @metadata = {} @recursive_metadata = {} @classes = [] @resource_table = {} @resources = [] @relationship_graph = nil @host_config = true @environment_instance = environment @environment = environment.to_s @code_id = code_id @aliases = {} if block_given? yield(self) finalize end end # Make the default objects necessary for function. def make_default_resources # We have to add the resources to the catalog, or else they won't get cleaned up after # the transaction. # First create the default scheduling objects Puppet::Type.type(:schedule).mkdefaultschedules.each { |res| add_resource(res) unless resource(res.ref) } # And filebuckets bucket = Puppet::Type.type(:filebucket).mkdefaultbucket if bucket add_resource(bucket) unless resource(bucket.ref) end end # Remove the resource from our catalog. Notice that we also call # 'remove' on the resource, at least until resource classes no longer maintain # references to the resource instances. def remove_resource(*resources) resources.each do |resource| ref = resource.ref title_key = title_key_for_ref(ref) @resource_table.delete(title_key) aliases = @aliases[ref] if aliases aliases.each { |res_alias| @resource_table.delete(res_alias) } @aliases.delete(ref) end remove_vertex!(resource) if vertex?(resource) @relationship_graph.remove_vertex!(resource) if @relationship_graph and @relationship_graph.vertex?(resource) @resources.delete(title_key) # Only Puppet::Type kind of resources respond to :remove, not Puppet::Resource resource.remove if resource.respond_to?(:remove) end end # Look a resource up by its reference (e.g., File[/etc/passwd]). def resource(type, title = nil) # Retain type if it's a type type_name = type.is_a?(Puppet::CompilableResourceType) || type.is_a?(Puppet::Resource::Type) ? type.name : type type_name, title = Puppet::Resource.type_and_title(type_name, title) type = type_name if type.is_a?(String) title_key = [type_name, title.to_s] result = @resource_table[title_key] if result.nil? # an instance has to be created in order to construct the unique key used when # searching for aliases res = Puppet::Resource.new(type, title, { :environment => @environment_instance }) # Must check with uniqueness key because of aliases or if resource transforms title in title # to attribute mappings. result = @resource_table[[type_name, res.uniqueness_key].flatten] end result end def resource_refs resource_keys.filter_map { |type, name| name.is_a?(String) ? "#{type}[#{name}]" : nil } end def resource_keys @resource_table.keys end def resources @resources.collect do |key| @resource_table[key] end end def self.from_data_hash(data) result = new(data['name'], Puppet::Node::Environment::NONE) result.tag(*data['tags']) if data['tags'] result.version = data['version'] if data['version'] result.code_id = data['code_id'] if data['code_id'] result.catalog_uuid = data['catalog_uuid'] if data['catalog_uuid'] result.catalog_format = data['catalog_format'] || 0 environment = data['environment'] if environment result.environment = environment result.environment_instance = Puppet::Node::Environment.remote(environment.to_sym) end result.add_resource( *data['resources'].collect do |res| Puppet::Resource.from_data_hash(res) end ) if data['resources'] if data['edges'] data['edges'].each do |edge_hash| edge = Puppet::Relationship.from_data_hash(edge_hash) source = result.resource(edge.source) unless source raise ArgumentError, _("Could not intern from data: Could not find relationship source %{source} for %{target}") % { source: edge.source.inspect, target: edge.target.to_s } end edge.source = source target = result.resource(edge.target) unless target raise ArgumentError, _("Could not intern from data: Could not find relationship target %{target} for %{source}") % { target: edge.target.inspect, source: edge.source.to_s } end edge.target = target result.add_edge(edge) end end result.add_class(*data['classes']) if data['classes'] result.metadata = data['metadata'].transform_values { |v| Puppet::FileServing::Metadata.from_data_hash(v); } if data['metadata'] recursive_metadata = data['recursive_metadata'] if recursive_metadata result.recursive_metadata = recursive_metadata.transform_values do |source_to_meta_hash| source_to_meta_hash.transform_values do |metas| metas.map { |meta| Puppet::FileServing::Metadata.from_data_hash(meta) } end end end result end def to_data_hash metadata_hash = metadata.transform_values(&:to_data_hash) recursive_metadata_hash = recursive_metadata.transform_values do |source_to_meta_hash| source_to_meta_hash.transform_values do |metas| metas.map(&:to_data_hash) end end { 'tags' => tags.to_a, 'name' => name, 'version' => version, 'code_id' => code_id, 'catalog_uuid' => catalog_uuid, 'catalog_format' => catalog_format, 'environment' => environment.to_s, 'resources' => @resources.map { |v| @resource_table[v].to_data_hash }, 'edges' => edges.map(&:to_data_hash), 'classes' => classes, }.merge(metadata_hash.empty? ? {} : { 'metadata' => metadata_hash }).merge(recursive_metadata_hash.empty? ? {} : { 'recursive_metadata' => recursive_metadata_hash }) end # Convert our catalog into a RAL catalog. def to_ral to_catalog :to_ral end # Convert our catalog into a catalog of Puppet::Resource instances. def to_resource to_catalog :to_resource end # filter out the catalog, applying +block+ to each resource. # If the block result is false, the resource will # be kept otherwise it will be skipped def filter(&block) # to_catalog must take place in a context where current_environment is set to the same env as the # environment set in the catalog (if it is set) # See PUP-3755 if environment_instance Puppet.override({ :current_environment => environment_instance }) do to_catalog :to_resource, &block end else # If catalog has no environment_instance, hope that the caller has made sure the context has the # correct current_environment to_catalog :to_resource, &block end end # Store the classes in the classfile. def write_class_file # classfile paths may contain UTF-8 # https://puppet.com/docs/puppet/latest/configuration.html#classfile classfile = Puppet.settings.setting(:classfile) Puppet::FileSystem.open(classfile.value, classfile.mode.to_i(8), "w:UTF-8") do |f| f.puts classes.join("\n") end rescue => detail Puppet.err _("Could not create class file %{file}: %{detail}") % { file: Puppet[:classfile], detail: detail } end # Store the list of resources we manage def write_resource_file # resourcefile contains resources that may be UTF-8 names # https://puppet.com/docs/puppet/latest/configuration.html#resourcefile resourcefile = Puppet.settings.setting(:resourcefile) Puppet::FileSystem.open(resourcefile.value, resourcefile.mode.to_i(8), "w:UTF-8") do |f| to_print = resources.filter_map do |resource| next unless resource.managed? resource.ref.downcase.to_s end f.puts to_print.join("\n") end rescue => detail Puppet.err _("Could not create resource file %{file}: %{detail}") % { file: Puppet[:resourcefile], detail: detail } end # Produce the graph files if requested. def write_graph(name) # We only want to graph the main host catalog. return unless host_config? super end private def prioritizer @prioritizer = Puppet::Graph::SequentialPrioritizer.new end def create_transaction(options) transaction = Puppet::Transaction.new(self, options[:report], prioritizer) transaction.tags = options[:tags] if options[:tags] transaction.ignoreschedules = true if options[:ignoreschedules] transaction.for_network_device = Puppet.lookup(:network_device) { nil } || options[:network_device] transaction end # Verify that the given resource isn't declared elsewhere. def fail_on_duplicate_type_and_title(resource, title_key) # Short-circuit the common case, existing_resource = @resource_table[title_key] return unless existing_resource # If we've gotten this far, it's a real conflict error_location_str = Puppet::Util::Errors.error_location(existing_resource.file, existing_resource.line) msg = if error_location_str.empty? _("Duplicate declaration: %{resource} is already declared; cannot redeclare") % { resource: resource.ref } else _("Duplicate declaration: %{resource} is already declared at %{error_location}; cannot redeclare") % { resource: resource.ref, error_location: error_location_str } end raise DuplicateResourceError.new(msg, resource.file, resource.line) end # An abstracted method for converting one catalog into another type of catalog. # This pretty much just converts all of the resources from one class to another, using # a conversion method. def to_catalog(convert) result = self.class.new(name, environment_instance) result.version = version result.code_id = code_id result.catalog_uuid = catalog_uuid result.catalog_format = catalog_format result.metadata = metadata result.recursive_metadata = recursive_metadata map = {} resources.each do |resource| next if virtual_not_exported?(resource) next if block_given? and yield resource newres = resource.copy_as_resource newres.catalog = result if convert != :to_resource newres = newres.to_ral end # We can't guarantee that resources don't munge their names # (like files do with trailing slashes), so we have to keep track # of what a resource got converted to. map[resource.ref] = newres result.add_resource newres end message = convert.to_s.tr "_", " " edges.each do |edge| # Skip edges between virtual resources. next if virtual_not_exported?(edge.source) next if block_given? and yield edge.source next if virtual_not_exported?(edge.target) next if block_given? and yield edge.target source = map[edge.source.ref] unless source raise Puppet::DevError, _("Could not find resource %{resource} when converting %{message} resources") % { resource: edge.source.ref, message: message } end target = map[edge.target.ref] unless target raise Puppet::DevError, _("Could not find resource %{resource} when converting %{message} resources") % { resource: edge.target.ref, message: message } end result.add_edge(source, target, edge.label) end map.clear result.add_class(*classes) result.merge_tags_from(self) result end def virtual_not_exported?(resource) resource.virtual && !resource.exported end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/resource/type_collection.rb
lib/puppet/resource/type_collection.rb
# frozen_string_literal: true require_relative '../../puppet/parser/type_loader' require_relative '../../puppet/util/file_watcher' require_relative '../../puppet/util/warnings' require_relative '../../puppet/concurrent/lock' # @api private class Puppet::Resource::TypeCollection attr_reader :environment attr_accessor :parse_failed include Puppet::Util::Warnings def clear @hostclasses.clear @definitions.clear @nodes.clear @notfound.clear end def initialize(env) @environment = env @hostclasses = {} @definitions = {} @nodes = {} @notfound = {} # always lock the environment before acquiring this lock @lock = Puppet::Concurrent::Lock.new # So we can keep a list and match the first-defined regex @node_list = [] end def import_ast(ast, modname) ast.instantiate(modname).each do |instance| add(instance) end end def inspect "TypeCollection" + { :hostclasses => @hostclasses.keys, :definitions => @definitions.keys, :nodes => @nodes.keys }.inspect end # @api private def <<(thing) add(thing) self end def add(instance) # return a merged instance, or the given catch(:merged) { send("add_#{instance.type}", instance) instance.resource_type_collection = self instance } end def add_hostclass(instance) handle_hostclass_merge(instance) dupe_check(instance, @hostclasses) { |dupe| _("Class '%{klass}' is already defined%{error}; cannot redefine") % { klass: instance.name, error: dupe.error_context } } dupe_check(instance, @nodes) { |dupe| _("Node '%{klass}' is already defined%{error}; cannot be redefined as a class") % { klass: instance.name, error: dupe.error_context } } dupe_check(instance, @definitions) { |dupe| _("Definition '%{klass}' is already defined%{error}; cannot be redefined as a class") % { klass: instance.name, error: dupe.error_context } } @hostclasses[instance.name] = instance instance end def handle_hostclass_merge(instance) # Only main class (named '') can be merged (for purpose of merging top-scopes). return instance unless instance.name == '' if instance.type == :hostclass && (other = @hostclasses[instance.name]) && other.type == :hostclass other.merge(instance) # throw is used to signal merge - avoids dupe checks and adding it to hostclasses throw :merged, other end end # Replaces the known settings with a new instance (that must be named 'settings'). # This is primarily needed for testing purposes. Also see PUP-5954 as it makes # it illegal to merge classes other than the '' (main) class. Prior to this change # settings where always merged rather than being defined from scratch for many testing scenarios # not having a complete side effect free setup for compilation. # def replace_settings(instance) @hostclasses['settings'] = instance end def hostclass(name) @hostclasses[munge_name(name)] end def add_node(instance) dupe_check(instance, @nodes) { |dupe| _("Node '%{name}' is already defined%{error}; cannot redefine") % { name: instance.name, error: dupe.error_context } } dupe_check(instance, @hostclasses) { |dupe| _("Class '%{klass}' is already defined%{error}; cannot be redefined as a node") % { klass: instance.name, error: dupe.error_context } } @node_list << instance @nodes[instance.name] = instance instance end def loader @loader ||= Puppet::Parser::TypeLoader.new(environment) end def node(name) name = munge_name(name) node = @nodes[name] if node return node end @node_list.each do |n| next unless n.name_is_regex? return n if n.match(name) end nil end def node_exists?(name) @nodes[munge_name(name)] end def nodes? @nodes.length > 0 end def add_definition(instance) dupe_check(instance, @hostclasses) { |dupe| _("'%{name}' is already defined%{error} as a class; cannot redefine as a definition") % { name: instance.name, error: dupe.error_context } } dupe_check(instance, @definitions) { |dupe| _("Definition '%{name}' is already defined%{error}; cannot be redefined") % { name: instance.name, error: dupe.error_context } } @definitions[instance.name] = instance end def definition(name) @definitions[munge_name(name)] end def find_node(name) @nodes[munge_name(name)] end def find_hostclass(name) find_or_load(name, :hostclass) end def find_definition(name) find_or_load(name, :definition) end # TODO: This implementation is wasteful as it creates a copy on each request # [:hostclasses, :nodes, :definitions].each do |m| define_method(m) do instance_variable_get("@#{m}").dup end end def parse_failed? @parse_failed end def version unless defined?(@version) if environment.config_version.nil? || environment.config_version == "" @version = Time.now.to_i else @version = Puppet::Util::Execution.execute([environment.config_version]).to_s.strip end end @version rescue Puppet::ExecutionFailure => e raise Puppet::ParseError, _("Execution of config_version command `%{cmd}` failed: %{message}") % { cmd: environment.config_version, message: e.message }, e.backtrace end private COLON_COLON = "::" # Resolve namespaces and find the given object. Autoload it if # necessary. def find_or_load(name, type) # always lock the environment before locking the type collection @environment.lock.synchronize do @lock.synchronize do # Name is always absolute, but may start with :: which must be removed fqname = (name[0, 2] == COLON_COLON ? name[2..] : name) result = send(type, fqname) unless result if @notfound[fqname] && Puppet[:ignoremissingtypes] # do not try to autoload if we already tried and it wasn't conclusive # as this is a time consuming operation. Warn the user. # Check first if debugging is on since the call to debug_once is expensive if Puppet[:debug] debug_once _("Not attempting to load %{type} %{fqname} as this object was missing during a prior compilation") % { type: type, fqname: fqname } end else fqname = munge_name(fqname) result = loader.try_load_fqname(type, fqname) @notfound[fqname] = result.nil? end end result end end end def munge_name(name) name.to_s.downcase end def dupe_check(instance, hash) dupe = hash[instance.name] return unless dupe message = yield dupe instance.fail Puppet::ParseError, message end def dupe_check_singleton(instance, set) return if set.empty? message = yield set[0] instance.fail Puppet::ParseError, message end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/resource/status.rb
lib/puppet/resource/status.rb
# frozen_string_literal: true require 'time' require_relative '../../puppet/network/format_support' require_relative '../../puppet/util/psych_support' module Puppet class Resource # This class represents the result of evaluating a given resource. It # contains file and line information about the source, events generated # while evaluating the resource, timing information, and the status of the # resource evaluation. # # @api private class Status include Puppet::Util::PsychSupport include Puppet::Util::Tagging include Puppet::Network::FormatSupport # @!attribute [rw] file # @return [String] The file where `@real_resource` was defined. attr_accessor :file # @!attribute [rw] line # @return [Integer] The line number in the file where `@real_resource` was defined. attr_accessor :line # @!attribute [rw] evaluation_time # @return [Float] The time elapsed in sections while evaluating `@real_resource`. # measured in seconds. attr_accessor :evaluation_time # Boolean status types set while evaluating `@real_resource`. STATES = [:skipped, :failed, :failed_to_restart, :restarted, :changed, :out_of_sync, :scheduled, :corrective_change] attr_accessor(*STATES) # @!attribute [r] source_description # @return [String] The textual description of the path to `@real_resource` # based on the containing structures. This is in contrast to # `@containment_path` which is a list of containment path components. # @example # status.source_description #=> "/Stage[main]/Myclass/Exec[date]" attr_reader :source_description # @!attribute [r] containment_path # @return [Array<String>] A list of resource references that contain # `@real_resource`. # @example A normal contained type # status.containment_path #=> ["Stage[main]", "Myclass", "Exec[date]"] # @example A whit associated with a class # status.containment_path #=> ["Whit[Admissible_class[Main]]"] attr_reader :containment_path # @!attribute [r] time # @return [Time] The time that this status object was created attr_reader :time # @!attribute [r] resource # @return [String] The resource reference for `@real_resource` attr_reader :resource # @!attribute [r] change_count # @return [Integer] A count of the successful changes made while # evaluating `@real_resource`. attr_reader :change_count # @!attribute [r] out_of_sync_count # @return [Integer] A count of the audited changes made while # evaluating `@real_resource`. attr_reader :out_of_sync_count # @!attribute [r] resource_type # @example # status.resource_type #=> 'Notify' # @return [String] The class name of `@real_resource` attr_reader :resource_type # @!attribute [rw] provider_used # @return [String] The class name of the provider used for the resource attr_accessor :provider_used # @!attribute [r] title # @return [String] The title of `@real_resource` attr_reader :title # @!attribute [r] events # @return [Array<Puppet::Transaction::Event>] A list of events generated # while evaluating `@real_resource`. attr_reader :events # @!attribute [r] corrective_change # @return [Boolean] true if the resource contained a corrective change. attr_reader :corrective_change # @!attribute [rw] failed_dependencies # @return [Array<Puppet::Resource>] A cache of all # dependencies of this resource that failed to apply. attr_accessor :failed_dependencies def dependency_failed? failed_dependencies && !failed_dependencies.empty? end def self.from_data_hash(data) obj = allocate obj.initialize_from_hash(data) obj end # Provide a boolean method for each of the states. STATES.each do |attr| define_method("#{attr}?") do !!send(attr) end end def <<(event) add_event(event) self end def add_event(event) @events << event case event.status when 'failure' self.failed = true when 'success' @change_count += 1 @changed = true end if event.status != 'audit' @out_of_sync_count += 1 @out_of_sync = true end if event.corrective_change @corrective_change = true end end def failed_because(detail) @real_resource.log_exception(detail, _("Could not evaluate: %{detail}") % { detail: detail }) # There's a contract (implicit unfortunately) that a status of failed # will always be accompanied by an event with some explanatory power. This # is useful for reporting/diagnostics/etc. So synthesize an event here # with the exception detail as the message. fail_with_event(detail.to_s) end # Both set the status state to failed and generate a corresponding # Puppet::Transaction::Event failure with the given message. # @param message [String] the reason for a status failure def fail_with_event(message) add_event(@real_resource.event(:name => :resource_error, :status => "failure", :message => message)) end def initialize(resource) @real_resource = resource @source_description = resource.path @containment_path = resource.pathbuilder @resource = resource.to_s @change_count = 0 @out_of_sync_count = 0 @changed = false @out_of_sync = false @skipped = false @failed = false @corrective_change = false @file = resource.file @line = resource.line merge_tags_from(resource) @time = Time.now @events = [] @resource_type = resource.type.to_s.capitalize @provider_used = resource.provider.class.name.to_s unless resource.provider.nil? @title = resource.title end def initialize_from_hash(data) @resource_type = data['resource_type'] @provider_used = data['provider_used'] @title = data['title'] @resource = data['resource'] @containment_path = data['containment_path'] @file = data['file'] @line = data['line'] @evaluation_time = data['evaluation_time'] @change_count = data['change_count'] @out_of_sync_count = data['out_of_sync_count'] @tags = Puppet::Util::TagSet.new(data['tags']) @time = data['time'] @time = Time.parse(@time) if @time.is_a? String @out_of_sync = data['out_of_sync'] @changed = data['changed'] @skipped = data['skipped'] @failed = data['failed'] @failed_to_restart = data['failed_to_restart'] @corrective_change = data['corrective_change'] @events = data['events'].map do |event| # Older versions contain tags that causes Psych to create instances directly event.is_a?(Puppet::Transaction::Event) ? event : Puppet::Transaction::Event.from_data_hash(event) end end def to_data_hash { 'title' => @title, 'file' => @file, 'line' => @line, 'resource' => @resource, 'resource_type' => @resource_type, 'provider_used' => @provider_used, 'containment_path' => @containment_path, 'evaluation_time' => @evaluation_time, 'tags' => @tags.to_a, 'time' => @time.iso8601(9), 'failed' => @failed, 'failed_to_restart' => failed_to_restart?, 'changed' => @changed, 'out_of_sync' => @out_of_sync, 'skipped' => @skipped, 'change_count' => @change_count, 'out_of_sync_count' => @out_of_sync_count, 'events' => @events.map(&:to_data_hash), 'corrective_change' => @corrective_change, } end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/vendor/require_vendored.rb
lib/puppet/vendor/require_vendored.rb
# This adds upfront requirements on vendored code found under lib/vendor/x # Add one requirement per vendored package (or a comment if it is loaded on demand). # The vendored library 'rgen' is loaded on demand.
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/node/environment.rb
lib/puppet/node/environment.rb
# frozen_string_literal: true require_relative '../../puppet/util' require 'monitor' require_relative '../../puppet/parser/parser_factory' require_relative '../../puppet/concurrent/lock' # Just define it, so this class has fewer load dependencies. class Puppet::Node end # Puppet::Node::Environment acts as a container for all configuration # that is expected to vary between environments. # # ## The root environment # # In addition to normal environments that are defined by the user,there is a # special 'root' environment. It is defined as an instance variable on the # Puppet::Node::Environment metaclass. The environment name is `*root*` and can # be accessed by looking up the `:root_environment` using {Puppet.lookup}. # # The primary purpose of the root environment is to contain parser functions # that are not bound to a specific environment. The main case for this is for # logging functions. Logging functions are attached to the 'root' environment # when {Puppet::Parser::Functions.reset} is called. class Puppet::Node::Environment NO_MANIFEST = :no_manifest # The create() factory method should be used instead. private_class_method :new # Create a new environment with the given name # # @param name [Symbol] the name of the environment # @param modulepath [Array<String>] the list of paths from which to load modules # @param manifest [String] the path to the manifest for the environment or # the constant Puppet::Node::Environment::NO_MANIFEST if there is none. # @param config_version [String] path to a script whose output will be added # to report logs (optional) # @return [Puppet::Node::Environment] # # @api public def self.create(name, modulepath, manifest = NO_MANIFEST, config_version = nil) new(name, modulepath, manifest, config_version) end # A remote subclass to make it easier to trace instances when debugging. # @api private class Remote < Puppet::Node::Environment; end # A "reference" to a remote environment. The created environment instance # isn't expected to exist on the local system, but is instead a reference to # environment information on a remote system. For instance when a catalog is # being applied, this will be used on the agent. # # @note This does not provide access to the information of the remote # environment's modules, manifest, or anything else. It is simply a value # object to pass around and use as an environment. # # @param name [Symbol] The name of the remote environment # def self.remote(name) Remote.create(name, [], NO_MANIFEST) end # Instantiate a new environment # # @note {Puppet::Node::Environment.new} is private for historical reasons, as # previously it had been overridden to return memoized objects and was # replaced with {Puppet::Node::Environment.create}, so this will not be # invoked with the normal Ruby initialization semantics. # # @param name [Symbol] The environment name def initialize(name, modulepath, manifest, config_version) @lock = Puppet::Concurrent::Lock.new @name = name.intern @modulepath = self.class.expand_dirs(self.class.extralibs() + modulepath) @manifest = manifest == NO_MANIFEST ? manifest : Puppet::FileSystem.expand_path(manifest) @config_version = config_version end # Creates a new Puppet::Node::Environment instance, overriding any of the passed # parameters. # # @param env_params [Hash<{Symbol => String,Array<String>}>] new environment # parameters (:modulepath, :manifest, :config_version) # @return [Puppet::Node::Environment] def override_with(env_params) self.class.create(name, env_params[:modulepath] || modulepath, env_params[:manifest] || manifest, env_params[:config_version] || config_version) end # Creates a new Puppet::Node::Environment instance, overriding :manifest, # :modulepath, or :config_version from the passed settings if they were # originally set from the commandline, or returns self if there is nothing to # override. # # @param settings [Puppet::Settings] an initialized puppet settings instance # @return [Puppet::Node::Environment] new overridden environment or self if # there are no commandline changes from settings. def override_from_commandline(settings) overrides = {} if settings.set_by_cli?(:modulepath) overrides[:modulepath] = self.class.split_path(settings.value(:modulepath)) end if settings.set_by_cli?(:config_version) overrides[:config_version] = settings.value(:config_version) end if settings.set_by_cli?(:manifest) overrides[:manifest] = settings.value(:manifest) end overrides.empty? ? self : override_with(overrides) end # @param [String] name Environment name to check for valid syntax. # @return [Boolean] true if name is valid # @api public def self.valid_name?(name) !!name.match(/\A\w+\Z/) end # @!attribute [r] name # @api public # @return [Symbol] the human readable environment name that serves as the # environment identifier attr_reader :name # @api public # @return [Array<String>] All directories present on disk in the modulepath def modulepath @modulepath.find_all do |p| Puppet::FileSystem.directory?(p) end end # @api public # @return [Array<String>] All directories in the modulepath (even if they are not present on disk) def full_modulepath @modulepath end # @!attribute [r] manifest # @api public # @return [String] path to the manifest file or directory. attr_reader :manifest # @!attribute [r] config_version # @api public # @return [String] path to a script whose output will be added to report logs # (optional) attr_reader :config_version # Cached loaders - management of value handled by Puppet::Pops::Loaders # @api private attr_accessor :loaders # Lock for compilation that needs exclusive access to the environment # @api private attr_reader :lock # For use with versioned dirs # our environment path may contain symlinks, while we want to resolve the # path while reading the manifests we may want to report the resources as # coming from the configured path. attr_accessor :configured_path # See :configured_path above attr_accessor :resolved_path # Ensure the path given is of the format we want in the catalog/report. # # Intended for use with versioned symlinked environments. If this # environment is configured with "/etc/puppetlabs/code/environments/production" # but the resolved path is # # "/opt/puppetlabs/server/puppetserver/filesync/client/puppet-code/production_abcdef1234" # # this changes the filepath # # "/opt/puppetlabs/server/puppetserver/filesync/client/puppet-code/production_abcdef1234/modules/foo/manifests/init.pp" # # to # # "/etc/puppetlabs/code/environments/production/modules/foo/manifests/init.pp" def externalize_path(filepath) paths_set = configured_path && resolved_path munging_possible = paths_set && configured_path != resolved_path munging_desired = munging_possible && Puppet[:report_configured_environmentpath] && filepath.to_s.start_with?(resolved_path) if munging_desired File.join(configured_path, filepath.delete_prefix(resolved_path)) else filepath end end # Checks to make sure that this environment did not have a manifest set in # its original environment.conf if Puppet is configured with # +disable_per_environment_manifest+ set true. If it did, the environment's # modules may not function as intended by the original authors, and we may # seek to halt a puppet compilation for a node in this environment. # # The only exception to this would be if the environment.conf manifest is an exact, # uninterpolated match for the current +default_manifest+ setting. # # @return [Boolean] true if using directory environments, and # Puppet[:disable_per_environment_manifest] is true, and this environment's # original environment.conf had a manifest setting that is not the # Puppet[:default_manifest]. # @api private def conflicting_manifest_settings? return false unless Puppet[:disable_per_environment_manifest] original_manifest = configuration.raw_setting(:manifest) !original_manifest.nil? && !original_manifest.empty? && original_manifest != Puppet[:default_manifest] end # @api private def static_catalogs? if @static_catalogs.nil? environment_conf = Puppet.lookup(:environments).get_conf(name) @static_catalogs = (environment_conf.nil? ? Puppet[:static_catalogs] : environment_conf.static_catalogs) end @static_catalogs end # Return the environment configuration # @return [Puppet::Settings::EnvironmentConf] The configuration # # @api private def configuration Puppet.lookup(:environments).get_conf(name) end # Checks the environment and settings for any conflicts # @return [Array<String>] an array of validation errors # @api public def validation_errors errors = [] if conflicting_manifest_settings? errors << _("The 'disable_per_environment_manifest' setting is true, and the '%{env_name}' environment has an environment.conf manifest that conflicts with the 'default_manifest' setting.") % { env_name: name } end errors end def rich_data_from_env_conf unless @checked_conf_for_rich_data environment_conf = Puppet.lookup(:environments).get_conf(name) @rich_data_from_conf = environment_conf&.rich_data @checked_conf_for_rich_data = true end @rich_data_from_conf end # Checks if this environment permits use of rich data types in the catalog # Checks the environment conf for an override on first query, then going forward # either uses that, or if unset, uses the current value of the `rich_data` setting. # @return [Boolean] `true` if rich data is permitted. # @api private def rich_data? @rich_data = rich_data_from_env_conf.nil? ? Puppet[:rich_data] : rich_data_from_env_conf end # Return an environment-specific Puppet setting. # # @api public # # @param param [String, Symbol] The environment setting to look up # @return [Object] The resolved setting value def [](param) Puppet.settings.value(param, name) end # @api public # @return [Puppet::Resource::TypeCollection] The current global TypeCollection def known_resource_types @lock.synchronize do if @known_resource_types.nil? @known_resource_types = Puppet::Resource::TypeCollection.new(self) @known_resource_types.import_ast(perform_initial_import(), '') end @known_resource_types end end # Yields each modules' plugin directory if the plugin directory (modulename/lib) # is present on the filesystem. # # @yield [String] Yields the plugin directory from each module to the block. # @api public def each_plugin_directory(&block) modules.map(&:plugin_directory).each do |lib| lib = Puppet::Util::Autoload.cleanpath(lib) yield lib if File.directory?(lib) end end # Locate a module instance by the module name alone. # # @api public # # @param name [String] The module name # @return [Puppet::Module, nil] The module if found, else nil def module(name) modules_by_name[name] end # Locate a module instance by the full forge name (EG authorname/module) # # @api public # # @param forge_name [String] The module name # @return [Puppet::Module, nil] The module if found, else nil def module_by_forge_name(forge_name) _, modname = forge_name.split('/') found_mod = self.module(modname) found_mod and found_mod.forge_name == forge_name ? found_mod : nil end # Return all modules for this environment in the order they appear in the # modulepath. # @note If multiple modules with the same name are present they will # both be added, but methods like {#module} and {#module_by_forge_name} # will return the first matching entry in this list. # @note This value is cached so that the filesystem doesn't have to be # re-enumerated every time this method is invoked, since that # enumeration could be a costly operation and this method is called # frequently. The cache expiry is determined by `Puppet[:filetimeout]`. # @api public # @return [Array<Puppet::Module>] All modules for this environment def modules if @modules.nil? module_references = [] project = Puppet.lookup(:bolt_project) { nil } seen_modules = if project && project.load_as_module? module_references << project.to_h { project.name => true } else {} end modulepath.each do |path| Puppet::FileSystem.children(path).map do |p| Puppet::FileSystem.basename_string(p) end.each do |name| next unless Puppet::Module.is_module_directory?(name, path) warn_about_mistaken_path(path, name) unless seen_modules[name] module_references << { :name => name, :path => File.join(path, name) } seen_modules[name] = true end end end @modules = module_references.filter_map do |reference| Puppet::Module.new(reference[:name], reference[:path], self) rescue Puppet::Module::Error => e Puppet.log_exception(e) nil end end @modules end # @api private def modules_by_name @modules_by_name ||= modules.to_h { |mod| [mod.name, mod] } end private :modules_by_name # Generate a warning if the given directory in a module path entry is named `lib`. # # @api private # # @param path [String] The module directory containing the given directory # @param name [String] The directory name def warn_about_mistaken_path(path, name) if name == "lib" Puppet.debug { "Warning: Found directory named 'lib' in module path ('#{path}/lib'); unless you \ are expecting to load a module named 'lib', your module path may be set incorrectly." } end end # Modules broken out by directory in the modulepath # # @api public # # @return [Hash<String, Array<Puppet::Module>>] A hash whose keys are file # paths, and whose values is an array of Puppet Modules for that path def modules_by_path modules_by_path = {} modulepath.each do |path| if Puppet::FileSystem.exist?(path) module_names = Puppet::FileSystem.children(path).map do |p| Puppet::FileSystem.basename_string(p) end.select do |name| Puppet::Module.is_module_directory?(name, path) end modules_by_path[path] = module_names.sort.map do |name| Puppet::Module.new(name, File.join(path, name), self) end else modules_by_path[path] = [] end end modules_by_path end # All module requirements for all modules in the environment modulepath # # @api public # # @comment This has nothing to do with an environment. It seems like it was # stuffed into the first convenient class that vaguely involved modules. # # @example # environment.module_requirements # # => { # # 'username/amodule' => [ # # { # # 'name' => 'username/moduledep', # # 'version' => '1.2.3', # # 'version_requirement' => '>= 1.0.0', # # }, # # { # # 'name' => 'username/anotherdep', # # 'version' => '4.5.6', # # 'version_requirement' => '>= 3.0.0', # # } # # ] # # } # # # # @return [Hash<String, Array<Hash<String, String>>>] See the method example # for an explanation of the return value. def module_requirements deps = {} modules.each do |mod| next unless mod.forge_name deps[mod.forge_name] ||= [] mod.dependencies and mod.dependencies.each do |mod_dep| dep_name = mod_dep['name'].tr('-', '/') (deps[dep_name] ||= []) << { 'name' => mod.forge_name, 'version' => mod.version, 'version_requirement' => mod_dep['version_requirement'] } end end deps.each do |mod, mod_deps| deps[mod] = mod_deps.sort_by { |d| d['name'] } end deps end # Loads module translations for the current environment once for # the lifetime of the environment. Execute a block in the context # of that translation domain. def with_text_domain return yield if Puppet[:disable_i18n] if @text_domain.nil? @text_domain = @name Puppet::GettextConfig.reset_text_domain(@text_domain) Puppet::ModuleTranslations.load_from_modulepath(modules) else Puppet::GettextConfig.use_text_domain(@text_domain) end yield ensure # Is a noop if disable_i18n is true Puppet::GettextConfig.clear_text_domain end # Checks if a reparse is required (cache of files is stale). # def check_for_reparse @lock.synchronize do if Puppet[:code] != @parsed_code || @known_resource_types.parse_failed? @parsed_code = nil @known_resource_types = nil end end end # @return [String] The YAML interpretation of the object # Return the name of the environment as a string interpretation of the object def to_yaml to_s.to_yaml end # @return [String] The stringified value of the `name` instance variable # @api public def to_s name.to_s end # @api public def inspect %Q(<#{self.class}:#{object_id} @name="#{name}" @manifest="#{manifest}" @modulepath="#{full_modulepath.join(':')}" >) end # @return [Symbol] The `name` value, cast to a string, then cast to a symbol. # # @api public # # @note the `name` instance variable is a Symbol, but this casts the value # to a String and then converts it back into a Symbol which will needlessly # create an object that needs to be garbage collected def to_sym to_s.to_sym end def self.split_path(path_string) path_string.split(File::PATH_SEPARATOR) end def ==(other) true if other.is_a?(Puppet::Node::Environment) && name == other.name && full_modulepath == other.full_modulepath && manifest == other.manifest end alias eql? == def hash [self.class, name, full_modulepath, manifest].hash end # not private so it can be called in tests def self.extralibs if ENV['PUPPETLIB'] split_path(ENV.fetch('PUPPETLIB', nil)) else [] end end # not private so it can be called in initialize def self.expand_dirs(dirs) dirs.collect do |dir| Puppet::FileSystem.expand_path(dir) end end private # Reparse the manifests for the given environment # # There are two sources that can be used for the initial parse: # # 1. The value of `Puppet[:code]`: Puppet can take a string from # its settings and parse that as a manifest. This is used by various # Puppet applications to read in a manifest and pass it to the # environment as a side effect. This is attempted first. # 2. The contents of this environment's +manifest+ attribute: Puppet will # try to load the environment manifest. # # @return [Puppet::Parser::AST::Hostclass] The AST hostclass object # representing the 'main' hostclass def perform_initial_import parser = Puppet::Parser::ParserFactory.parser @parsed_code = Puppet[:code] if @parsed_code != "" parser.string = @parsed_code parser.parse else file = manifest # if the manifest file is a reference to a directory, parse and combine # all .pp files in that directory if file == NO_MANIFEST empty_parse_result elsif File.directory?(file) # JRuby does not properly perform Dir.glob operations with wildcards, (see PUP-11788 and https://github.com/jruby/jruby/issues/7836). # We sort the results because Dir.glob order is inconsistent in Ruby < 3 (see PUP-10115). parse_results = Puppet::FileSystem::PathPattern.absolute(File.join(file, '**/*')).glob.select { |globbed_file| globbed_file.end_with?('.pp') }.sort.map do |file_to_parse| parser.file = file_to_parse parser.parse end # Use a parser type specific merger to concatenate the results Puppet::Parser::AST::Hostclass.new('', :code => Puppet::Parser::ParserFactory.code_merger.concatenate(parse_results)) else parser.file = file parser.parse end end rescue Puppet::ParseErrorWithIssue => detail @known_resource_types.parse_failed = true detail.environment = name raise rescue => detail @known_resource_types.parse_failed = true msg = _("Could not parse for environment %{env}: %{detail}") % { env: self, detail: detail } error = Puppet::Error.new(msg) error.set_backtrace(detail.backtrace) raise error end # Return an empty top-level hostclass to indicate that no file was loaded # # @return [Puppet::Parser::AST::Hostclass] def empty_parse_result Puppet::Parser::AST::Hostclass.new('') end # A None subclass to make it easier to trace the NONE environment when debugging. # @api private class None < Puppet::Node::Environment; end # A special "null" environment # # This environment should be used when there is no specific environment in # effect. NONE = None.create(:none, []) end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/node/server_facts.rb
lib/puppet/node/server_facts.rb
# frozen_string_literal: true class Puppet::Node::ServerFacts def self.load server_facts = {} # Add our server Puppet Enterprise version, if available. pe_version_file = '/opt/puppetlabs/server/pe_version' if File.readable?(pe_version_file) and !File.zero?(pe_version_file) server_facts['pe_serverversion'] = File.read(pe_version_file).chomp end # Add our server version to the fact list server_facts["serverversion"] = Puppet.version.to_s # And then add the server name and IP { "servername" => "networking.fqdn", "serverip" => "networking.ip", "serverip6" => "networking.ip6" }.each do |var, fact| value = Puppet.runtime[:facter].value(fact) unless value.nil? server_facts[var] = value end end if server_facts["servername"].nil? host = Puppet.runtime[:facter].value('networking.hostname') if host.nil? Puppet.warning _("Could not retrieve fact servername") elsif domain = Puppet.runtime[:facter].value('networking.domain') # rubocop:disable Lint/AssignmentInCondition server_facts["servername"] = [host, domain].join(".") else server_facts["servername"] = host end end if server_facts["serverip"].nil? && server_facts["serverip6"].nil? Puppet.warning _("Could not retrieve either serverip or serverip6 fact") end server_facts end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/node/facts.rb
lib/puppet/node/facts.rb
# frozen_string_literal: true require 'time' require_relative '../../puppet/node' require_relative '../../puppet/indirector' require_relative '../../puppet/util/psych_support' # Manage a given node's facts. This either accepts facts and stores them, or # returns facts for a given node. class Puppet::Node::Facts include Puppet::Util::PsychSupport # Set up indirection, so that nodes can be looked for in # the node sources. extend Puppet::Indirector # We want to expire any cached nodes if the facts are saved. module NodeExpirer def save(instance, key = nil, options = {}) Puppet::Node.indirection.expire(instance.name, options) super end end indirects :facts, :terminus_setting => :facts_terminus, :extend => NodeExpirer attr_accessor :name, :values, :timestamp def add_local_facts values["clientcert"] = Puppet.settings[:certname] values["clientversion"] = Puppet.version.to_s values["clientnoop"] = Puppet.settings[:noop] end def initialize(name, values = {}) @name = name @values = values add_timestamp end def initialize_from_hash(data) @name = data['name'] @values = data['values'] # Timestamp will be here in YAML, e.g. when reading old reports timestamp = @values.delete('_timestamp') # Timestamp will be here in JSON timestamp ||= data['timestamp'] if timestamp.is_a? String @timestamp = Time.parse(timestamp) else @timestamp = timestamp end self.expiration = data['expiration'] if expiration.is_a? String self.expiration = Time.parse(expiration) end end # Add extra values, such as facts given to lookup on the command line. The # extra values will override existing values. # @param extra_values [Hash{String=>Object}] the values to add # @api private def add_extra_values(extra_values) @values.merge!(extra_values) nil end # Sanitize fact values by converting everything not a string, Boolean # numeric, array or hash into strings. def sanitize values.each do |fact, value| values[fact] = sanitize_fact value end end def ==(other) return false unless name == other.name values == other.values end def self.from_data_hash(data) new_facts = allocate new_facts.initialize_from_hash(data) new_facts end def to_data_hash result = { 'name' => name, 'values' => values } if @timestamp if @timestamp.is_a? Time result['timestamp'] = @timestamp.iso8601(9) else result['timestamp'] = @timestamp end end if expiration if expiration.is_a? Time result['expiration'] = expiration.iso8601(9) else result['expiration'] = expiration end end result end def add_timestamp @timestamp = Time.now end def to_yaml facts_to_display = Psych.parse_stream(YAML.dump(self)) quote_special_strings(facts_to_display) end private def quote_special_strings(fact_hash) fact_hash.grep(Psych::Nodes::Scalar).each do |node| next unless node.value =~ /:/ node.plain = false node.quoted = true node.style = Psych::Nodes::Scalar::DOUBLE_QUOTED end fact_hash.yaml end def sanitize_fact(fact) case fact when Hash ret = {} fact.each_pair { |k, v| ret[sanitize_fact k] = sanitize_fact v } ret when Array fact.collect { |i| sanitize_fact i } when Numeric, TrueClass, FalseClass, String fact else result = fact.to_s # The result may be ascii-8bit encoded without being a binary (low level object.inspect returns ascii-8bit string) if result.encoding == Encoding::ASCII_8BIT begin result = result.encode(Encoding::UTF_8) rescue # return the ascii-8bit - it will be taken as a binary result end end result end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/transaction/report.rb
lib/puppet/transaction/report.rb
# frozen_string_literal: true require_relative '../../puppet' require_relative '../../puppet/indirector' # This class is used to report what happens on a client. # There are two types of data in a report; _Logs_ and _Metrics_. # # * **Logs** - are the output that each change produces. # * **Metrics** - are all of the numerical data involved in the transaction. # # Use {Puppet::Reports} class to create a new custom report type. This class is indirectly used # as a source of data to report in such a registered report. # # ##Metrics # There are three types of metrics in each report, and each type of metric has one or more values. # # * Time: Keeps track of how long things took. # * Total: Total time for the configuration run # * File: # * Exec: # * User: # * Group: # * Config Retrieval: How long the configuration took to retrieve # * Service: # * Package: # * Resources: Keeps track of the following stats: # * Total: The total number of resources being managed # * Skipped: How many resources were skipped, because of either tagging or scheduling restrictions # * Scheduled: How many resources met any scheduling restrictions # * Out of Sync: How many resources were out of sync # * Applied: How many resources were attempted to be fixed # * Failed: How many resources were not successfully fixed # * Restarted: How many resources were restarted because their dependencies changed # * Failed Restarts: How many resources could not be restarted # * Changes: The total number of changes in the transaction. # # @api public class Puppet::Transaction::Report include Puppet::Util::PsychSupport extend Puppet::Indirector STATES_FOR_EXCLUSION_FROM_REPORT = [:failed, :failed_to_restart, :out_of_sync, :skipped].freeze indirects :report, :terminus_class => :processor # The version of the configuration # @todo Uncertain what this is? # @return [???] the configuration version attr_accessor :configuration_version # An agent generated transaction uuid, useful for connecting catalog and report # @return [String] uuid attr_accessor :transaction_uuid # The id of the code input to the compiler. attr_accessor :code_id # The id of the job responsible for this run. attr_accessor :job_id # A master generated catalog uuid, useful for connecting a single catalog to multiple reports. attr_accessor :catalog_uuid # Whether a cached catalog was used in the run, and if so, the reason that it was used. # @return [String] One of the values: 'not_used', 'explicitly_requested', # or 'on_failure' attr_accessor :cached_catalog_status # Contains the name and port of the server that was successfully contacted # @return [String] a string of the format 'servername:port' attr_accessor :server_used # The host name for which the report is generated # @return [String] the host name attr_accessor :host # The name of the environment the host is in # @return [String] the environment name attr_accessor :environment # The name of the environment the agent initially started in # @return [String] the environment name attr_accessor :initial_environment # Whether there are changes that we decided not to apply because of noop # @return [Boolean] # attr_accessor :noop_pending # A hash with a map from resource to status # @return [Hash{String => Puppet::Resource::Status}] Resource name to status. attr_reader :resource_statuses # A list of log messages. # @return [Array<Puppet::Util::Log>] logged messages attr_reader :logs # A hash of metric name to metric value. # @return [Hash<{String => Object}>] A map of metric name to value. # @todo Uncertain if all values are numbers - now marked as Object. # attr_reader :metrics # The time when the report data was generated. # @return [Time] A time object indicating when the report data was generated # attr_reader :time # The status of the client run is an enumeration: 'failed', 'changed' or 'unchanged' # @return [String] the status of the run - one of the values 'failed', 'changed', or 'unchanged' # attr_reader :status # @return [String] The Puppet version in String form. # @see Puppet::version() # attr_reader :puppet_version # @return [Integer] report format version number. This value is constant for # a given version of Puppet; it is incremented when a new release of Puppet # changes the API for the various objects that make up a report. # attr_reader :report_format # Whether the puppet run was started in noop mode # @return [Boolean] # attr_reader :noop # @!attribute [r] corrective_change # @return [Boolean] true if the report contains any events and resources that had # corrective changes, including noop corrective changes. attr_reader :corrective_change # @return [Boolean] true if one or more resources attempted to generate # resources and failed # attr_accessor :resources_failed_to_generate # @return [Boolean] true if the transaction completed it's evaluate # attr_accessor :transaction_completed TOTAL = "total" def self.from_data_hash(data) obj = allocate obj.initialize_from_hash(data) obj end def as_logging_destination(&block) Puppet::Util::Log.with_destination(self, &block) end # @api private def <<(msg) @logs << msg self end # @api private def add_times(name, value, accumulate = true) if @external_times[name] && accumulate @external_times[name] += value else @external_times[name] = value end end # @api private def add_metric(name, hash) metric = Puppet::Util::Metric.new(name) hash.each do |metric_name, value| metric.newvalue(metric_name, value) end @metrics[metric.name] = metric metric end # @api private def add_resource_status(status) @resource_statuses[status.resource] = status end # @api private def compute_status(resource_metrics, change_metric) if resources_failed_to_generate || !transaction_completed || (resource_metrics["failed"] || 0) > 0 || (resource_metrics["failed_to_restart"] || 0) > 0 'failed' elsif change_metric > 0 'changed' else 'unchanged' end end # @api private def has_noop_events?(resource) resource.events.any? { |event| event.status == 'noop' } end # @api private def prune_internal_data resource_statuses.delete_if { |_name, res| res.resource_type == 'Whit' } end # @api private def finalize_report prune_internal_data calculate_report_corrective_change resource_metrics = add_metric(:resources, calculate_resource_metrics) add_metric(:time, calculate_time_metrics) change_metric = calculate_change_metric add_metric(:changes, { TOTAL => change_metric }) add_metric(:events, calculate_event_metrics) @status = compute_status(resource_metrics, change_metric) @noop_pending = @resource_statuses.any? { |_name, res| has_noop_events?(res) } end # @api private def initialize(configuration_version = nil, environment = nil, transaction_uuid = nil, job_id = nil, start_time = Time.now) @metrics = {} @logs = [] @resource_statuses = {} @external_times ||= {} @host = Puppet[:node_name_value] @time = start_time @report_format = 12 @puppet_version = Puppet.version @configuration_version = configuration_version @transaction_uuid = transaction_uuid @code_id = nil @job_id = job_id @catalog_uuid = nil @cached_catalog_status = nil @server_used = nil @environment = environment @status = 'failed' # assume failed until the report is finalized @noop = Puppet[:noop] @noop_pending = false @corrective_change = false @transaction_completed = false end # @api private def initialize_from_hash(data) @puppet_version = data['puppet_version'] @report_format = data['report_format'] @configuration_version = data['configuration_version'] @transaction_uuid = data['transaction_uuid'] @environment = data['environment'] @status = data['status'] @transaction_completed = data['transaction_completed'] @noop = data['noop'] @noop_pending = data['noop_pending'] @host = data['host'] @time = data['time'] @corrective_change = data['corrective_change'] if data['server_used'] @server_used = data['server_used'] elsif data['master_used'] @server_used = data['master_used'] end if data['catalog_uuid'] @catalog_uuid = data['catalog_uuid'] end if data['job_id'] @job_id = data['job_id'] end if data['code_id'] @code_id = data['code_id'] end if data['cached_catalog_status'] @cached_catalog_status = data['cached_catalog_status'] end if @time.is_a? String @time = Time.parse(@time) end @metrics = {} data['metrics'].each do |name, hash| # Older versions contain tags that causes Psych to create instances directly @metrics[name] = hash.is_a?(Puppet::Util::Metric) ? hash : Puppet::Util::Metric.from_data_hash(hash) end @logs = data['logs'].map do |record| # Older versions contain tags that causes Psych to create instances directly record.is_a?(Puppet::Util::Log) ? record : Puppet::Util::Log.from_data_hash(record) end @resource_statuses = {} data['resource_statuses'].map do |key, rs| @resource_statuses[key] = if rs == Puppet::Resource::EMPTY_HASH nil elsif rs.is_a?(Puppet::Resource::Status) # Older versions contain tags that causes Psych to create instances # directly rs else Puppet::Resource::Status.from_data_hash(rs) end end end def resource_unchanged?(rs) STATES_FOR_EXCLUSION_FROM_REPORT.each do |state| return false if rs.send(state) end true end def calculate_resource_statuses resource_statuses = if Puppet[:exclude_unchanged_resources] @resource_statuses.reject { |_key, rs| resource_unchanged?(rs) } else @resource_statuses end resource_statuses.transform_values { |rs| rs.nil? ? nil : rs.to_data_hash } end def to_data_hash hash = { 'host' => @host, 'time' => @time.iso8601(9), 'configuration_version' => @configuration_version, 'transaction_uuid' => @transaction_uuid, 'report_format' => @report_format, 'puppet_version' => @puppet_version, 'status' => @status, 'transaction_completed' => @transaction_completed, 'noop' => @noop, 'noop_pending' => @noop_pending, 'environment' => @environment, 'logs' => @logs.map(&:to_data_hash), 'metrics' => @metrics.transform_values(&:to_data_hash), 'resource_statuses' => calculate_resource_statuses, 'corrective_change' => @corrective_change, } # The following is include only when set hash['server_used'] = @server_used unless @server_used.nil? hash['catalog_uuid'] = @catalog_uuid unless @catalog_uuid.nil? hash['code_id'] = @code_id unless @code_id.nil? hash['job_id'] = @job_id unless @job_id.nil? hash['cached_catalog_status'] = @cached_catalog_status unless @cached_catalog_status.nil? hash end # @return [String] the host name # @api public # def name host end # Provide a human readable textual summary of this report. # @note This is intended for debugging purposes # @return [String] A string with a textual summary of this report. # @api public # def summary report = raw_summary ret = ''.dup report.keys.sort_by(&:to_s).each do |key| ret += "#{Puppet::Util::Metric.labelize(key)}:\n" report[key].keys.sort { |a, b| # sort by label if a == TOTAL 1 elsif b == TOTAL -1 else report[key][a].to_s <=> report[key][b].to_s end }.each do |label| value = report[key][label] next if value == 0 value = "%0.2f" % value if value.is_a?(Float) ret += " %15s %s\n" % [Puppet::Util::Metric.labelize(label) + ":", value] end end ret end # Provides a raw hash summary of this report. # @return [Hash<{String => Object}>] A hash with metrics key to value map # @api public # def raw_summary report = { "version" => { "config" => configuration_version, "puppet" => Puppet.version }, "application" => { "run_mode" => Puppet.run_mode.name.to_s, "initial_environment" => initial_environment, "converged_environment" => environment } } @metrics.each do |_name, metric| key = metric.name.to_s report[key] = {} metric.values.each do |metric_name, _label, value| report[key][metric_name.to_s] = value end report[key][TOTAL] = 0 unless key == "time" or report[key].include?(TOTAL) end (report["time"] ||= {})["last_run"] = Time.now.tv_sec report end # Computes a single number that represents the report's status. # The computation is based on the contents of this report's metrics. # The resulting number is a bitmask where # individual bits represent the presence of different metrics. # # * 0x2 set if there are changes # * 0x4 set if there are resource failures or resources that failed to restart # @return [Integer] A bitmask where 0x2 is set if there are changes, and 0x4 is set of there are failures. # @api public # def exit_status status = 0 if @metrics["changes"] && @metrics["changes"][TOTAL] && @metrics["resources"] && @metrics["resources"]["failed"] && @metrics["resources"]["failed_to_restart"] status |= 2 if @metrics["changes"][TOTAL] > 0 status |= 4 if @metrics["resources"]["failed"] > 0 status |= 4 if @metrics["resources"]["failed_to_restart"] > 0 else status = -1 end status end private # Mark the report as corrective, if there are any resource_status marked corrective. def calculate_report_corrective_change @corrective_change = resource_statuses.any? do |_name, status| status.corrective_change end end def calculate_change_metric resource_statuses.map { |_name, status| status.change_count || 0 }.inject(0) { |a, b| a + b } end def calculate_event_metrics metrics = Hash.new(0) %w[total failure success].each { |m| metrics[m] = 0 } resource_statuses.each do |_name, status| metrics[TOTAL] += status.events.length status.events.each do |event| metrics[event.status] += 1 end end metrics end def calculate_resource_metrics metrics = {} metrics[TOTAL] = resource_statuses.length # force every resource key in the report to be present # even if no resources is in this given state Puppet::Resource::Status::STATES.each do |state| metrics[state.to_s] = 0 end resource_statuses.each do |_name, status| Puppet::Resource::Status::STATES.each do |state| metrics[state.to_s] += 1 if status.send(state) end end metrics end def calculate_time_metrics metrics = Hash.new(0) resource_statuses.each do |_name, status| metrics[status.resource_type.downcase] += status.evaluation_time if status.evaluation_time end @external_times.each do |name, value| metrics[name.to_s.downcase] = value end metrics end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/transaction/persistence.rb
lib/puppet/transaction/persistence.rb
# frozen_string_literal: true require 'yaml' require_relative '../../puppet/util/yaml' # A persistence store implementation for storing information between # transaction runs for the purposes of information inference (such # as calculating corrective_change). # @api private class Puppet::Transaction::Persistence def self.allowed_classes @allowed_classes ||= [ Symbol, Time, Regexp, # URI is excluded, because it serializes all instance variables including the # URI parser. Better to serialize the URL encoded representation. SemanticPuppet::Version, # SemanticPuppet::VersionRange has many nested classes and is unlikely to be # used directly, so ignore it Puppet::Pops::Time::Timestamp, Puppet::Pops::Time::TimeData, Puppet::Pops::Time::Timespan, Puppet::Pops::Types::PBinaryType::Binary # Puppet::Pops::Types::PSensitiveType::Sensitive values are excluded from # the persistence store, ignore it. ].freeze end def initialize @old_data = {} @new_data = { "resources" => {} } end # Obtain the full raw data from the persistence store. # @return [Hash] hash of data stored in persistence store def data @old_data end # Retrieve the system value using the resource and parameter name # @param [String] resource_name name of resource # @param [String] param_name name of the parameter # @return [Object,nil] the system_value def get_system_value(resource_name, param_name) if !@old_data["resources"].nil? && !@old_data["resources"][resource_name].nil? && !@old_data["resources"][resource_name]["parameters"].nil? && !@old_data["resources"][resource_name]["parameters"][param_name].nil? @old_data["resources"][resource_name]["parameters"][param_name]["system_value"] else nil end end def set_system_value(resource_name, param_name, value) @new_data["resources"] ||= {} @new_data["resources"][resource_name] ||= {} @new_data["resources"][resource_name]["parameters"] ||= {} @new_data["resources"][resource_name]["parameters"][param_name] ||= {} @new_data["resources"][resource_name]["parameters"][param_name]["system_value"] = value end def copy_skipped(resource_name) @old_data["resources"] ||= {} old_value = @old_data["resources"][resource_name] unless old_value.nil? @new_data["resources"][resource_name] = old_value end end # Load data from the persistence store on disk. def load filename = Puppet[:transactionstorefile] unless Puppet::FileSystem.exist?(filename) return end unless File.file?(filename) Puppet.warning(_("Transaction store file %{filename} is not a file, ignoring") % { filename: filename }) return end result = nil Puppet::Util.benchmark(:debug, _("Loaded transaction store file in %{seconds} seconds")) do result = Puppet::Util::Yaml.safe_load_file(filename, self.class.allowed_classes) rescue Puppet::Util::Yaml::YamlLoadError => detail Puppet.log_exception(detail, _("Transaction store file %{filename} is corrupt (%{detail}); replacing") % { filename: filename, detail: detail }) begin File.rename(filename, filename + ".bad") rescue => detail Puppet.log_exception(detail, _("Unable to rename corrupt transaction store file: %{detail}") % { detail: detail }) raise Puppet::Error, _("Could not rename corrupt transaction store file %{filename}; remove manually") % { filename: filename }, detail.backtrace end result = {} end unless result.is_a?(Hash) Puppet.err _("Transaction store file %{filename} is valid YAML but not returning a hash. Check the file for corruption, or remove it before continuing.") % { filename: filename } return end @old_data = result end # Save data from internal class to persistence store on disk. def save Puppet::Util::Yaml.dump(@new_data, Puppet[:transactionstorefile]) end # Use the catalog and run_mode to determine if persistence should be enabled or not # @param [Puppet::Resource::Catalog] catalog catalog being processed # @return [boolean] true if persistence is enabled def enabled?(catalog) catalog.host_config? && Puppet.run_mode.name == :agent end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/transaction/event.rb
lib/puppet/transaction/event.rb
# frozen_string_literal: true require_relative '../../puppet/transaction' require_relative '../../puppet/util/tagging' require_relative '../../puppet/util/logging' require_relative '../../puppet/network/format_support' # A simple struct for storing what happens on the system. class Puppet::Transaction::Event include Puppet::Util::Tagging include Puppet::Util::Logging include Puppet::Network::FormatSupport ATTRIBUTES = [:name, :resource, :property, :previous_value, :desired_value, :historical_value, :status, :message, :file, :line, :source_description, :audited, :invalidate_refreshes, :redacted, :corrective_change] attr_accessor(*ATTRIBUTES) attr_accessor :time attr_reader :default_log_level EVENT_STATUSES = %w[noop success failure audit] def self.from_data_hash(data) obj = allocate obj.initialize_from_hash(data) obj end def initialize(audited: false, corrective_change: false, desired_value: nil, file: nil, historical_value: nil, invalidate_refreshes: nil, line: nil, message: nil, name: nil, previous_value: nil, property: nil, redacted: false, resource: nil, source_description: nil, status: nil, tags: nil) @audited = audited @corrective_change = corrective_change @desired_value = desired_value @file = file @historical_value = historical_value @invalidate_refreshes = invalidate_refreshes @line = line @message = message @name = name @previous_value = previous_value @redacted = redacted @source_description = source_description @tags = tags self.property = property if property self.resource = resource if resource self.status = status if status @time = Time.now end def eql?(event) self.class == event.class && ATTRIBUTES.all? { |attr| send(attr).eql?(event.send(attr)) } end alias == eql? def initialize_from_hash(data) data = Puppet::Pops::Serialization::FromDataConverter.convert(data, { :allow_unresolved => true, :loader => Puppet::Pops::Loaders.static_loader }) @audited = data['audited'] @property = data['property'] @previous_value = data['previous_value'] @desired_value = data['desired_value'] @historical_value = data['historical_value'] @message = data['message'] @name = data['name'].intern if data['name'] @status = data['status'] @time = data['time'] @time = Time.parse(@time) if @time.is_a? String @redacted = data.fetch('redacted', false) @corrective_change = data['corrective_change'] end def to_data_hash hash = { 'audited' => @audited, 'property' => @property, 'previous_value' => @previous_value, 'desired_value' => @desired_value, 'historical_value' => @historical_value, 'message' => @message, 'name' => @name.nil? ? nil : @name.to_s, 'status' => @status, 'time' => @time.iso8601(9), 'redacted' => @redacted, 'corrective_change' => @corrective_change, } # Use the stringifying converter since rich data is not possible downstream. # (This will destroy some data type information, but this is expected). Puppet::Pops::Serialization::ToStringifiedConverter.convert(hash, :message_prefix => 'Event') end def property=(prop) @property_instance = prop @property = prop.to_s end def resource=(res) level = res[:loglevel] if res.respond_to?(:[]) if level @default_log_level = level end @resource = res.to_s end def send_log super(log_level, message) end def status=(value) raise ArgumentError, _("Event status can only be %{statuses}") % { statuses: EVENT_STATUSES.join(', ') } unless EVENT_STATUSES.include?(value) @status = value end def to_s message end def inspect %Q(#<#{self.class.name} @name="#{@name.inspect}" @message="#{@message.inspect}">) end # Calculate and set the corrective_change parameter, based on the old_system_value of the property. # @param [Object] old_system_value system_value from last transaction # @return [bool] true if this is a corrective_change def calculate_corrective_change(old_system_value) # Only idempotent properties, and cases where we have an old system_value # are corrective_changes. if @property_instance.idempotent? && !@property_instance.sensitive && !old_system_value.nil? # If the values aren't insync, we have confirmed a corrective_change insync = @property_instance.insync_values?(old_system_value, previous_value) # Preserve the nil state, but flip true/false @corrective_change = insync.nil? ? nil : !insync else @corrective_change = false end end private # If it's a failure, use 'err', else use either the resource's log level (if available) # or 'notice'. def log_level status == "failure" ? :err : (@default_log_level || :notice) end # Used by the Logging module def log_source source_description || property || resource end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/transaction/additional_resource_generator.rb
lib/puppet/transaction/additional_resource_generator.rb
# frozen_string_literal: true # Adds additional resources to the catalog and relationship graph that are # generated by existing resources. There are two ways that a resource can # generate additional resources, either through the #generate method or the # #eval_generate method. # # @api private class Puppet::Transaction::AdditionalResourceGenerator attr_writer :relationship_graph # [boolean] true if any resource has attempted and failed to generate resources attr_reader :resources_failed_to_generate def initialize(catalog, relationship_graph, prioritizer) @catalog = catalog @relationship_graph = relationship_graph @prioritizer = prioritizer @resources_failed_to_generate = false end def generate_additional_resources(resource) return unless resource.respond_to?(:generate) begin generated = resource.generate rescue => detail @resources_failed_to_generate = true resource.log_exception(detail, _("Failed to generate additional resources using 'generate': %{detail}") % { detail: detail }) end return unless generated generated = [generated] unless generated.is_a?(Array) generated.collect! do |res| @catalog.resource(res.ref) || res end unless resource.depthfirst? # This is reversed because PUP-1963 changed how generated # resources were added to the catalog. It exists for backwards # compatibility only, and can probably be removed in Puppet 5 # # Previously, resources were given sequential priorities in the # relationship graph. Post-1963, resources are added to the # catalog one by one adjacent to the parent resource. This # causes an implicit reversal of their application order from # the old code. The reverse makes it all work like it did. generated.reverse! end generated.each do |res| add_resource(res, resource) add_generated_directed_dependency(resource, res) generate_additional_resources(res) end end def eval_generate(resource) return false unless resource.respond_to?(:eval_generate) raise Puppet::DevError, _("Depthfirst resources are not supported by eval_generate") if resource.depthfirst? begin generated = replace_duplicates_with_catalog_resources(resource.eval_generate) return false if generated.empty? rescue => detail @resources_failed_to_generate = true # TRANSLATORS eval_generate is a method name and should be left untranslated resource.log_exception(detail, _("Failed to generate additional resources using 'eval_generate': %{detail}") % { detail: detail }) return false end add_resources(generated, resource) made = generated.map(&:name).zip(generated).to_h contain_generated_resources_in(resource, made) connect_resources_to_ancestors(resource, made) true end private def replace_duplicates_with_catalog_resources(generated) generated.collect do |generated_resource| @catalog.resource(generated_resource.ref) || generated_resource end end def contain_generated_resources_in(resource, made) sentinel = Puppet::Type.type(:whit).new(:name => "completed_#{resource.title}", :catalog => resource.catalog) # Tag the completed whit with all of the tags of the generating resource # except the type name to allow event propogation to succeed beyond the whit # "boundary" when filtering resources with tags. We include auto-generated # tags such as the type name to support implicit filtering as well as # explicit. Note that resource#tags returns a duplicate of the resource's # tags. sentinel.merge_tags_from(resource) priority = @prioritizer.generate_priority_contained_in(resource, sentinel) @relationship_graph.add_vertex(sentinel, priority) redirect_edges_to_sentinel(resource, sentinel, made) made.values.each do |res| # This resource isn't 'completed' until each child has run add_conditional_directed_dependency(res, sentinel, Puppet::Graph::RelationshipGraph::Default_label) end # This edge allows the resource's events to propagate, though it isn't # strictly necessary for ordering purposes add_conditional_directed_dependency(resource, sentinel, Puppet::Graph::RelationshipGraph::Default_label) end def redirect_edges_to_sentinel(resource, sentinel, made) @relationship_graph.adjacent(resource, :direction => :out, :type => :edges).each do |e| next if made[e.target.name] @relationship_graph.add_relationship(sentinel, e.target, e.label) @relationship_graph.remove_edge! e end end def connect_resources_to_ancestors(resource, made) made.values.each do |res| # Depend on the nearest ancestor we generated, falling back to the # resource if we have none parent_name = res.ancestors.find { |a| made[a] and made[a] != res } parent = made[parent_name] || resource add_conditional_directed_dependency(parent, res) end end def add_resources(generated, resource) generated.each do |res| priority = @prioritizer.generate_priority_contained_in(resource, res) add_resource(res, resource, priority) end end def add_resource(res, parent_resource, priority = nil) if @catalog.resource(res.ref).nil? res.merge_tags_from(parent_resource) if parent_resource.depthfirst? @catalog.add_resource_before(parent_resource, res) else @catalog.add_resource_after(parent_resource, res) end @catalog.add_edge(@catalog.container_of(parent_resource), res) if @catalog.container_of(parent_resource) if @relationship_graph && priority # If we have a relationship_graph we should add the resource # to it (this is an eval_generate). If we don't, then the # relationship_graph has not yet been created and we can skip # adding it. @relationship_graph.add_vertex(res, priority) end res.finish end end # add correct edge for depth- or breadth- first traversal of # generated resource. Skip generating the edge if there is already # some sort of edge between the two resources. def add_generated_directed_dependency(parent, child, label = nil) if parent.depthfirst? source = child target = parent else source = parent target = child end # For each potential relationship metaparam, check if parent or # child references the other. If there are none, we should add our # edge. edge_exists = Puppet::Type.relationship_params.any? { |param| param_sym = param.name.to_sym if parent[param_sym] parent_contains = parent[param_sym].any? { |res| res.ref == child.ref } else parent_contains = false end if child[param_sym] child_contains = child[param_sym].any? { |res| res.ref == parent.ref } else child_contains = false end parent_contains || child_contains } unless edge_exists # We *cannot* use target.to_resource here! # # For reasons that are beyond my (and, perhaps, human) # comprehension, to_resource will call retrieve. This is # problematic if a generated resource needs the system to be # changed by a previous resource (think a file on a path # controlled by a mount resource). # # Instead of using to_resource, we just construct a resource as # if the arguments to the Type instance had been passed to a # Resource instead. resource = ::Puppet::Resource.new(target.class, target.title, :parameters => target.original_parameters) source[:before] ||= [] source[:before] << resource end end # Copy an important relationships from the parent to the newly-generated # child resource. def add_conditional_directed_dependency(parent, child, label = nil) @relationship_graph.add_vertex(child) edge = parent.depthfirst? ? [child, parent] : [parent, child] if @relationship_graph.edge?(*edge.reverse) parent.debug "Skipping automatic relationship to #{child}" else @relationship_graph.add_relationship(edge[0], edge[1], label) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/transaction/event_manager.rb
lib/puppet/transaction/event_manager.rb
# frozen_string_literal: true require_relative '../../puppet/transaction' # This class stores, routes, and responds to events generated while evaluating # a transaction. # # @api private class Puppet::Transaction::EventManager # @!attribute [r] transaction # @return [Puppet::Transaction] The transaction associated with this event manager. attr_reader :transaction # @!attribute [r] events # @todo Determine if this instance variable is used for anything aside from testing. # @return [Array<Puppet::Transaction::Events>] A list of events that can be # handled by the target resource. Events that cannot be handled by the # target resource will be discarded. attr_reader :events def initialize(transaction) @transaction = transaction @event_queues = {} @events = [] end def relationship_graph transaction.relationship_graph end # Respond to any queued events for this resource. def process_events(resource) restarted = false queued_events(resource) do |callback, events| r = process_callback(resource, callback, events) restarted ||= r end if restarted queue_events(resource, [resource.event(:name => :restarted, :status => "success")]) transaction.resource_status(resource).restarted = true end end # Queues events for other resources to respond to. All of these events have # to be from the same resource. # # @param resource [Puppet::Type] The resource generating the given events # @param events [Array<Puppet::Transaction::Event>] All events generated by this resource # @return [void] def queue_events(resource, events) # @events += events # Do some basic normalization so we're not doing so many # graph queries for large sets of events. events.each_with_object({}) do |event, collection| collection[event.name] ||= [] collection[event.name] << event end.collect do |_name, list| # It doesn't matter which event we use - they all have the same source # and name here. event = list[0] # Collect the targets of any subscriptions to those events. We pass # the parent resource in so it will override the source in the events, # since eval_generated children can't have direct relationships. received = (event.name != :restarted) relationship_graph.matching_edges(event, resource).each do |edge| received ||= true unless edge.target.is_a?(Puppet::Type.type(:whit)) method = edge.callback next unless method next unless edge.target.respond_to?(method) queue_events_for_resource(resource, edge.target, method, list) end @events << event if received queue_events_for_resource(resource, resource, :refresh, [event]) if resource.self_refresh? and !resource.deleting? end dequeue_events_for_resource(resource, :refresh) if events.detect(&:invalidate_refreshes) end def dequeue_all_events_for_resource(target) callbacks = @event_queues[target] if callbacks && !callbacks.empty? target.info _("Unscheduling all events on %{target}") % { target: target } @event_queues[target] = {} end end def dequeue_events_for_resource(target, callback) target.info _("Unscheduling %{callback} on %{target}") % { callback: callback, target: target } @event_queues[target][callback] = [] if @event_queues[target] end def queue_events_for_resource(source, target, callback, events) whit = Puppet::Type.type(:whit) # The message that a resource is refreshing the completed-whit for its own class # is extremely counter-intuitive. Basically everything else is easy to understand, # if you suppress the whit-lookingness of the whit resources refreshing_c_whit = target.is_a?(whit) && target.name =~ /^completed_/ if refreshing_c_whit source.debug "The container #{target} will propagate my #{callback} event" else source.info _("Scheduling %{callback} of %{target}") % { callback: callback, target: target } end @event_queues[target] ||= {} @event_queues[target][callback] ||= [] @event_queues[target][callback].concat(events) end def queued_events(resource) callbacks = @event_queues[resource] return unless callbacks callbacks.each do |callback, events| yield callback, events unless events.empty? end end private # Should the callback for this resource be invoked? # @param resource [Puppet::Type] The resource to be refreshed # @param events [Array<Puppet::Transaction::Event>] A list of events # associated with this callback and resource. # @return [true, false] Whether the callback should be run. def process_callback?(resource, events) !(events.all? { |e| e.status == "noop" } || resource.noop?) end # Processes callbacks for a given resource. # # @param resource [Puppet::Type] The resource receiving the callback. # @param callback [Symbol] The name of the callback method that will be invoked. # @param events [Array<Puppet::Transaction::Event>] A list of events # associated with this callback and resource. # @return [true, false] Whether the callback was successfully run. def process_callback(resource, callback, events) unless process_callback?(resource, events) process_noop_events(resource, callback, events) return false end resource.send(callback) unless resource.is_a?(Puppet::Type.type(:whit)) message = n_("Triggered '%{callback}' from %{count} event", "Triggered '%{callback}' from %{count} events", events.length) % { count: events.length, callback: callback } resource.notice message add_callback_status_event(resource, callback, message, "success") end true rescue => detail resource_error_message = _("Failed to call %{callback}: %{detail}") % { callback: callback, detail: detail } resource.err(resource_error_message) transaction.resource_status(resource).failed_to_restart = true transaction.resource_status(resource).fail_with_event(resource_error_message) resource.log_exception(detail) false end def add_callback_status_event(resource, callback, message, status) options = { message: message, status: status, name: callback.to_s } event = resource.event options transaction.resource_status(resource) << event if event end def process_noop_events(resource, callback, events) resource.notice n_("Would have triggered '%{callback}' from %{count} event", "Would have triggered '%{callback}' from %{count} events", events.length) % { count: events.length, callback: callback } # And then add an event for it. queue_events(resource, [resource.event(:status => "noop", :name => :noop_restart)]) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/transaction/resource_harness.rb
lib/puppet/transaction/resource_harness.rb
# frozen_string_literal: true require_relative '../../puppet/resource/status' class Puppet::Transaction::ResourceHarness NO_ACTION = Object.new extend Forwardable def_delegators :@transaction, :relationship_graph attr_reader :transaction def initialize(transaction) @transaction = transaction @persistence = transaction.persistence end def evaluate(resource) status = Puppet::Resource::Status.new(resource) begin context = ResourceApplicationContext.from_resource(resource, status) perform_changes(resource, context) if status.changed? && !resource.noop? cache(resource, :synced, Time.now) resource.flush if resource.respond_to?(:flush) end rescue => detail status.failed_because(detail) ensure status.evaluation_time = Time.now - status.time end status end def scheduled?(resource) return true if Puppet[:ignoreschedules] schedule = schedule(resource) return true unless schedule # We use 'checked' here instead of 'synced' because otherwise we'll # end up checking most resources most times, because they will generally # have been synced a long time ago (e.g., a file only gets updated # once a month on the server and its schedule is daily; the last sync time # will have been a month ago, so we'd end up checking every run). schedule.match?(cached(resource, :checked).to_i) end def schedule(resource) unless resource.catalog resource.warning _("Cannot schedule without a schedule-containing catalog") return nil end name = resource[:schedule] return nil unless name resource.catalog.resource(:schedule, name) || resource.fail(_("Could not find schedule %{name}") % { name: name }) end # Used mostly for scheduling and auditing at this point. def cached(resource, name) Puppet::Util::Storage.cache(resource)[name] end # Used mostly for scheduling and auditing at this point. def cache(resource, name, value) Puppet::Util::Storage.cache(resource)[name] = value end private def perform_changes(resource, context) cache(resource, :checked, Time.now) # Record the current state in state.yml. context.audited_params.each do |param| cache(resource, param, context.current_values[param]) end ensure_param = resource.parameter(:ensure) if ensure_param && ensure_param.should ensure_event = sync_if_needed(ensure_param, context) else ensure_event = NO_ACTION end if ensure_event == NO_ACTION if context.resource_present? resource.properties.each do |param| sync_if_needed(param, context) end else resource.debug("Nothing to manage: no ensure and the resource doesn't exist") end end capture_audit_events(resource, context) persist_system_values(resource, context) end # We persist the last known values for the properties of a resource after resource # application. # @param [Puppet::Type] resource resource whose values we are to persist. # @param [ResourceApplicationContext] context the application context to operate on. def persist_system_values(resource, context) param_to_event = {} context.status.events.each do |ev| param_to_event[ev.property] = ev end context.system_value_params.each do |pname, param| @persistence.set_system_value(resource.ref, pname.to_s, new_system_value(param, param_to_event[pname.to_s], @persistence.get_system_value(resource.ref, pname.to_s))) end end def sync_if_needed(param, context) historical_value = context.historical_values[param.name] current_value = context.current_values[param.name] do_audit = context.audited_params.include?(param.name) begin if param.should && !param.safe_insync?(current_value) event = create_change_event(param, current_value, historical_value) if do_audit event = audit_event(event, param, context) end brief_audit_message = audit_message(param, do_audit, historical_value, current_value) if param.noop noop(event, param, current_value, brief_audit_message) else sync(event, param, current_value, brief_audit_message) end event else NO_ACTION end rescue => detail # Execution will continue on StandardErrors, just store the event Puppet.log_exception(detail) event = create_change_event(param, current_value, historical_value) event.status = "failure" event.message = param.format(_("change from %s to %s failed: "), param.is_to_s(current_value), param.should_to_s(param.should)) + detail.to_s event rescue Exception => detail # Execution will halt on Exceptions, they get raised to the application event = create_change_event(param, current_value, historical_value) event.status = "failure" event.message = param.format(_("change from %s to %s failed: "), param.is_to_s(current_value), param.should_to_s(param.should)) + detail.to_s raise ensure if event name = param.name.to_s event.message ||= _("could not create change error message for %{name}") % { name: name } event.calculate_corrective_change(@persistence.get_system_value(context.resource.ref, name)) event.message << ' (corrective)' if event.corrective_change context.record(event) event.send_log context.synced_params << param.name end end end def create_change_event(property, current_value, historical_value) options = {} should = property.should if property.sensitive options[:previous_value] = current_value.nil? ? nil : '[redacted]' options[:desired_value] = should.nil? ? nil : '[redacted]' options[:historical_value] = historical_value.nil? ? nil : '[redacted]' else options[:previous_value] = current_value options[:desired_value] = should options[:historical_value] = historical_value end property.event(options) end # This method is an ugly hack because, given a Time object with nanosecond # resolution, roundtripped through YAML serialization, the Time object will # be truncated to microseconds. # For audit purposes, this code special cases this comparison, and compares # the two objects by their second and microsecond components. tv_sec is the # number of seconds since the epoch, and tv_usec is only the microsecond # portion of time. def are_audited_values_equal(a, b) a == b || (a.is_a?(Time) && b.is_a?(Time) && a.tv_sec == b.tv_sec && a.tv_usec == b.tv_usec) end private :are_audited_values_equal # Populate an existing event with audit information. # # @param event [Puppet::Transaction::Event] The event to be populated. # @param property [Puppet::Property] The property being audited. # @param context [ResourceApplicationContext] # # @return [Puppet::Transaction::Event] The given event, populated with the audit information. def audit_event(event, property, context) event.audited = true event.status = "audit" # The event we've been provided might have been redacted so we need to use the state stored within # the resource application context to see if an event was actually generated. unless are_audited_values_equal(context.historical_values[property.name], context.current_values[property.name]) event.message = property.format(_("audit change: previously recorded value %s has been changed to %s"), property.is_to_s(event.historical_value), property.is_to_s(event.previous_value)) end event end def audit_message(param, do_audit, historical_value, current_value) if do_audit && historical_value && !are_audited_values_equal(historical_value, current_value) param.format(_(" (previously recorded value was %s)"), param.is_to_s(historical_value)) else "" end end def noop(event, param, current_value, audit_message) if param.sensitive event.message = param.format(_("current_value %s, should be %s (noop)"), param.is_to_s(current_value), param.should_to_s(param.should)) + audit_message.to_s else event.message = "#{param.change_to_s(current_value, param.should)} (noop)#{audit_message}" end event.status = "noop" end def sync(event, param, current_value, audit_message) param.sync if param.sensitive event.message = param.format(_("changed %s to %s"), param.is_to_s(current_value), param.should_to_s(param.should)) + audit_message.to_s else event.message = "#{param.change_to_s(current_value, param.should)}#{audit_message}" end event.status = "success" end def capture_audit_events(resource, context) context.audited_params.each do |param_name| if context.historical_values.include?(param_name) if !are_audited_values_equal(context.historical_values[param_name], context.current_values[param_name]) && !context.synced_params.include?(param_name) parameter = resource.parameter(param_name) event = audit_event(create_change_event(parameter, context.current_values[param_name], context.historical_values[param_name]), parameter, context) event.send_log context.record(event) end else property = resource.property(param_name) property.notice(property.format(_("audit change: newly-recorded value %s"), context.current_values[param_name])) end end end # Given an event and its property, calculate the system_value to persist # for future calculations. # @param [Puppet::Transaction::Event] event event to use for processing # @param [Puppet::Property] property correlating property # @param [Object] old_system_value system_value from last transaction # @return [Object] system_value to be used for next transaction def new_system_value(property, event, old_system_value) if event && event.status != "success" # For non-success events, we persist the old_system_value if it is defined, # or use the event previous_value. # If we're using the event previous_value, we ensure that it's # an array. This is needed because properties assume that their # `should` value is an array, and we will use this value later # on in property insync? logic. event_value = [event.previous_value] unless event.previous_value.is_a?(Array) old_system_value.nil? ? event_value : old_system_value else # For non events, or for success cases, we just want to store # the parameters agent value. # We use instance_variable_get here because we want this process to bypass any # munging/unmunging or validation that the property might try to do, since those # operations may not be correctly implemented for custom types. property.instance_variable_get(:@should) end end # @api private ResourceApplicationContext = Struct.new(:resource, :current_values, :historical_values, :audited_params, :synced_params, :status, :system_value_params) do def self.from_resource(resource, status) ResourceApplicationContext.new(resource, resource.retrieve_resource.to_hash, Puppet::Util::Storage.cache(resource).dup, (resource[:audit] || []).map(&:to_sym), [], status, resource.parameters.select { |_n, p| p.is_a?(Puppet::Property) && !p.sensitive }) end def resource_present? resource.present?(current_values) end def record(event) status << event end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/interface/action_manager.rb
lib/puppet/interface/action_manager.rb
# frozen_string_literal: true # This class is not actually public API, but the method # {Puppet::Interface::ActionManager#action action} is public when used # as part of the Faces DSL (i.e. from within a # {Puppet::Interface.define define} block). # @api public module Puppet::Interface::ActionManager # Declare that this app can take a specific action, and provide # the code to do so. # Defines a new action. This takes a block to build the action using # the methods on {Puppet::Interface::ActionBuilder}. # @param name [Symbol] The name that will be used to invoke the # action # @overload action(name, { block }) # @return [void] # @api public # @dsl Faces def action(name, &block) @actions ||= {} Puppet.debug _("Redefining action %{name} for %{self}") % { name: name, self: self } if action?(name) action = Puppet::Interface::ActionBuilder.build(self, name, &block) # REVISIT: (#18042) doesn't this mean we can't redefine the default action? -- josh current = get_default_action if action.default if current raise "Actions #{current.name} and #{name} cannot both be default" end @actions[action.name] = action end # Returns the list of available actions for this face. # @return [Array<Symbol>] The names of the actions for this face # @api private def actions @actions ||= {} result = @actions.keys if is_a?(Class) and superclass.respond_to?(:actions) result += superclass.actions elsif self.class.respond_to?(:actions) result += self.class.actions end # We need to uniq the result, because we duplicate actions when they are # fetched to ensure that they have the correct bindings; they shadow the # parent, and uniq implements that. --daniel 2011-06-01 (result - @deactivated_actions.to_a).uniq.sort end # Retrieves a named action # @param name [Symbol] The name of the action # @return [Puppet::Interface::Action] The action object # @api private def get_action(name) @actions ||= {} result = @actions[name.to_sym] if result.nil? if is_a?(Class) and superclass.respond_to?(:get_action) found = superclass.get_action(name) elsif self.class.respond_to?(:get_action) found = self.class.get_action(name) end if found then # This is not the nicest way to make action equivalent to the Ruby # Method object, rather than UnboundMethod, but it will do for now, # and we only have to make this change in *one* place. --daniel 2011-04-12 result = @actions[name.to_sym] = found.__dup_and_rebind_to(self) end end result end # Retrieves the default action for the face # @return [Puppet::Interface::Action] # @api private def get_default_action default = actions.map { |x| get_action(x) }.select(&:default) if default.length > 1 raise "The actions #{default.map(&:name).join(', ')} cannot all be default" end default.first end # Deactivate a named action # @return [Puppet::Interface::Action] # @api public def deactivate_action(name) @deactivated_actions ||= Set.new @deactivated_actions.add name.to_sym end # @api private def action?(name) actions.include?(name.to_sym) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/interface/option_builder.rb
lib/puppet/interface/option_builder.rb
# frozen_string_literal: true # @api public class Puppet::Interface::OptionBuilder # The option under construction # @return [Puppet::Interface::Option] # @api private attr_reader :option # Build an option # @return [Puppet::Interface::Option] # @api private def self.build(face, *declaration, &block) new(face, *declaration, &block).option end def initialize(face, *declaration, &block) @face = face @option = Puppet::Interface::Option.new(face, *declaration) instance_eval(&block) if block_given? end # Metaprogram the simple DSL from the option class. Puppet::Interface::Option.instance_methods.grep(/=$/).each do |setter| next if setter =~ /^=/ dsl = setter.to_s.chomp('=') unless private_method_defined? dsl define_method(dsl) do |value| @option.send(setter, value) end end end # Override some methods that deal in blocks, not objects. # Sets a block to be executed when an action is invoked before the # main action code. This is most commonly used to validate an option. # @yieldparam action [Puppet::Interface::Action] The action being # invoked # @yieldparam args [Array] The arguments given to the action # @yieldparam options [Hash<Symbol=>Object>] Any options set # @api public # @dsl Faces def before_action(&block) unless block # TRANSLATORS 'before_action' is a method name and should not be translated raise ArgumentError, _("%{option} before_action requires a block") % { option: @option } end if @option.before_action # TRANSLATORS 'before_action' is a method name and should not be translated raise ArgumentError, _("%{option} already has a before_action set") % { option: @option } end unless block.arity == 3 then # TRANSLATORS 'before_action' is a method name and should not be translated raise ArgumentError, _("before_action takes three arguments, action, args, and options") end @option.before_action = block end # Sets a block to be executed after an action is invoked. # !(see before_action) # @api public # @dsl Faces def after_action(&block) unless block # TRANSLATORS 'after_action' is a method name and should not be translated raise ArgumentError, _("%{option} after_action requires a block") % { option: @option } end if @option.after_action # TRANSLATORS 'after_action' is a method name and should not be translated raise ArgumentError, _("%{option} already has an after_action set") % { option: @option } end unless block.arity == 3 then # TRANSLATORS 'after_action' is a method name and should not be translated raise ArgumentError, _("after_action takes three arguments, action, args, and options") end @option.after_action = block end # Sets whether the option is required. If no argument is given it # defaults to setting it as a required option. # @api public # @dsl Faces def required(value = true) @option.required = value end # Sets a block that will be used to compute the default value for this # option. It will be evaluated when the action is invoked. The block # should take no arguments. # @api public # @dsl Faces def default_to(&block) unless block # TRANSLATORS 'default_to' is a method name and should not be translated raise ArgumentError, _("%{option} default_to requires a block") % { option: @option } end if @option.has_default? raise ArgumentError, _("%{option} already has a default value") % { option: @option } end unless block.arity == 0 # TRANSLATORS 'default_to' is a method name and should not be translated raise ArgumentError, _("%{option} default_to block should not take any arguments") % { option: @option } end @option.default = block end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/interface/face_collection.rb
lib/puppet/interface/face_collection.rb
# frozen_string_literal: true module Puppet::Interface::FaceCollection @faces = Hash.new { |hash, key| hash[key] = {} } @loader = Puppet::Util::Autoload.new(:application, 'puppet/face') def self.faces unless @loaded @loaded = true names = @loader.files_to_load(Puppet.lookup(:current_environment)).map do |fn| ::File.basename(fn, '.rb') end.uniq names.each { |name| self[name, :current] } end @faces.keys.select { |name| @faces[name].length > 0 } end def self.[](name, version) name = underscorize(name) get_face(name, version) or load_face(name, version) end def self.get_action_for_face(name, action_name, version) name = underscorize(name) # If the version they request specifically doesn't exist, don't search # elsewhere. Usually this will start from :current and all... face = self[name, version] return nil unless face action = face.get_action(action_name) unless action # ...we need to search for it bound to an o{lder,ther} version. Since # we load all actions when the face is first references, this will be in # memory in the known set of versions of the face. (@faces[name].keys - [:current]).sort.reverse_each do |vers| action = @faces[name][vers].get_action(action_name) break if action end end action end # get face from memory, without loading. def self.get_face(name, pattern) return nil unless @faces.has_key? name return @faces[name][:current] if pattern == :current versions = @faces[name].keys - [:current] range = pattern.is_a?(SemanticPuppet::Version) ? SemanticPuppet::VersionRange.new(pattern, pattern) : SemanticPuppet::VersionRange.parse(pattern) found = find_matching(range, versions) @faces[name][found] end def self.find_matching(range, versions) versions.select { |v| range === v }.max end # try to load the face, and return it. def self.load_face(name, version) # We always load the current version file; the common case is that we have # the expected version and any compatibility versions in the same file, # the default. Which means that this is almost always the case. # # We use require to avoid executing the code multiple times, like any # other Ruby library that we might want to use. --daniel 2011-04-06 if safely_require name then # If we wanted :current, we need to index to find that; direct version # requests just work as they go. --daniel 2011-04-06 if version == :current then # We need to find current out of this. This is the largest version # number that doesn't have a dedicated on-disk file present; those # represent "experimental" versions of faces, which we don't fully # support yet. # # We walk the versions from highest to lowest and take the first version # that is not defined in an explicitly versioned file on disk as the # current version. # # This constrains us to only ship experimental versions with *one* # version in the file, not multiple, but given you can't reliably load # them except by side-effect when you ignore that rule this seems safe # enough... # # Given those constraints, and that we are not going to ship a versioned # interface that is not :current in this release, we are going to leave # these thoughts in place, and just punt on the actual versioning. # # When we upgrade the core to support multiple versions we can solve the # problems then; as lazy as possible. # # We do support multiple versions in the same file, though, so we sort # versions here and return the last item in that set. # # --daniel 2011-04-06 latest_ver = @faces[name].keys.max @faces[name][:current] = @faces[name][latest_ver] end end unless version == :current or get_face(name, version) # Try an obsolete version of the face, if needed, to see if that helps? safely_require name, version end get_face(name, version) end def self.safely_require(name, version = nil) path = @loader.expand(version ? ::File.join(version.to_s, name.to_s) : name) require path true rescue LoadError => e raise unless e.message =~ /-- #{path}$/ # ...guess we didn't find the file; return a much better problem. nil rescue SyntaxError => e raise unless e.message =~ /#{path}\.rb:\d+: / Puppet.err _("Failed to load face %{name}:\n%{detail}") % { name: name, detail: e } # ...but we just carry on after complaining. nil end def self.register(face) @faces[underscorize(face.name)][face.version] = face end def self.underscorize(name) unless name.to_s =~ /^[-_a-z][-_a-z0-9]*$/i then # TRANSLATORS 'face' refers to a programming API in Puppet raise ArgumentError, _("%{name} (%{class_name}) is not a valid face name") % { name: name.inspect, class_name: name.class } end name.to_s.downcase.split(/[-_]/).join('_').to_sym end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/interface/documentation.rb
lib/puppet/interface/documentation.rb
# frozen_string_literal: true class Puppet::Interface # @api private module DocGen require_relative '../../puppet/util/docs' # @api private def self.strip_whitespace(text) # I don't want no... Puppet::Util::Docs.scrub(text) end # The documentation attributes all have some common behaviours; previously # we open-coded them across the set of six things, but that seemed # wasteful - especially given that they were literally the same, and had # the same bug hidden in them. # # This feels a bit like overkill, but at least the common code is common # now. --daniel 2011-04-29 # @api private def attr_doc(name, &validate) # Now, which form of the setter do we want, validated or not? get_arg = "value.to_s" if validate define_method(:"_validate_#{name}", validate) get_arg = "_validate_#{name}(#{get_arg})" end # We use module_eval, which I don't like much, because we can't have an # argument to a block with a default value in Ruby 1.8, and I don't like # the side-effects (eg: no argument count validation) of using blocks # without as methods. When we are 1.9 only (hah!) you can totally # replace this with some up-and-up define_method. --daniel 2011-04-29 module_eval(<<-EOT, __FILE__, __LINE__ + 1) def #{name}(value = nil) # def attribute(value=nil) self.#{name} = value unless value.nil? # self.attribute = value unless value.nil? @#{name} # @value end # end def #{name}=(value) # def attribute=(value) @#{name} = Puppet::Interface::DocGen.strip_whitespace(#{get_arg}) # @value = Puppet::Interface::DocGen.strip_whitespace(#{get_arg}) end # end EOT end end # This module can be mixed in to provide a minimal set of # documentation attributes. # @api public module TinyDocs extend Puppet::Interface::DocGen # @!method summary(summary) # Sets a summary of this object. # @api public # @dsl Faces attr_doc :summary do |value| value =~ /\n/ and # TRANSLATORS 'Face' refers to a programming API in Puppet, 'summary' and 'description' are specifc attribute names and should not be translated raise ArgumentError, _("Face summary should be a single line; put the long text in 'description' instead.") value end # @!method description(description) # Sets the long description of this object. # @param description [String] The description of this object. # @api public # @dsl Faces attr_doc :description # @api private def build_synopsis(face, action = nil, arguments = nil) PrettyPrint.format do |s| s.text("puppet #{face}") s.text(" #{action}") unless action.nil? s.text(" ") options.each do |option| option = get_option(option) wrap = option.required? ? %w[< >] : %w{[ ]} s.group(0, *wrap) do option.optparse.each do |item| unless s.current_group.first? s.breakable s.text '|' s.breakable end s.text item end end s.breakable end display_global_options.sort.each do |option| wrap = %w{[ ]} s.group(0, *wrap) do type = Puppet.settings.setting(option).default type ||= Puppet.settings.setting(option).type.to_s.upcase s.text "--#{option} #{type}" s.breakable end s.breakable end if arguments then s.text arguments.to_s end end end end # This module can be mixed in to provide a full set of documentation # attributes. It is intended to be used for {Puppet::Interface}. # @api public module FullDocs extend Puppet::Interface::DocGen include TinyDocs # @!method examples # @overload examples(text) # Sets examples. # @param text [String] Example text # @api public # @return [void] # @dsl Faces # @overload examples # Returns documentation of examples # @return [String] The examples # @api private attr_doc :examples # @!method notes(text) # @overload notes(text) # Sets optional notes. # @param text [String] The notes # @api public # @return [void] # @dsl Faces # @overload notes # Returns any optional notes # @return [String] The notes # @api private attr_doc :notes # @!method license(text) # @overload license(text) # Sets the license text # @param text [String] the license text # @api public # @return [void] # @dsl Faces # @overload license # Returns the license # @return [String] The license # @api private attr_doc :license attr_doc :short_description # @overload short_description(value) # Sets a short description for this object. # @param value [String, nil] A short description (about a paragraph) # of this component. If `value` is `nil` the short_description # will be set to the shorter of the first paragraph or the first # five lines of {description}. # @return [void] # @api public # @dsl Faces # @overload short_description # Get the short description for this object # @return [String, nil] The short description of this object. If none is # set it will be derived from {description}. Returns `nil` if # {description} is `nil`. # @api private def short_description(value = nil) self.short_description = value unless value.nil? if @short_description.nil? then return nil if @description.nil? lines = @description.split("\n") first_paragraph_break = lines.index('') || 5 grab = [5, first_paragraph_break].min @short_description = lines[0, grab].join("\n") @short_description += ' [...]' if grab < lines.length and first_paragraph_break >= 5 end @short_description end # @overload author(value) # Adds an author to the documentation for this object. To set # multiple authors, call this once for each author. # @param value [String] the name of the author # @api public # @dsl Faces # @overload author # Returns a list of authors # @return [String, nil] The names of all authors separated by # newlines, or `nil` if no authors have been set. # @api private def author(value = nil) unless value.nil? then unless value.is_a? String # TRANSLATORS 'author' is an attribute name and should not be translated raise ArgumentError, _('author must be a string; use multiple statements for multiple authors') end if value =~ /\n/ then # TRANSLATORS 'author' is an attribute name and should not be translated raise ArgumentError, _('author should be a single line; use multiple statements for multiple authors') end @authors.push(Puppet::Interface::DocGen.strip_whitespace(value)) end @authors.empty? ? nil : @authors.join("\n") end # Returns a list of authors. See {author}. # @return [String] The list of authors, separated by newlines. # @api private def authors @authors end # @api private def author=(value) # I think it's a bug that this ends up being the exposed # version of `author` on ActionBuilder if Array(value).any? { |x| x =~ /\n/ } then # TRANSLATORS 'author' is an attribute name and should not be translated raise ArgumentError, _('author should be a single line; use multiple statements') end @authors = Array(value).map { |x| Puppet::Interface::DocGen.strip_whitespace(x) } end alias :authors= :author= # Sets the copyright owner and year. This returns the copyright # string, so it can be called with no arguments retrieve that string # without side effects. # @param owner [String, Array<String>] The copyright owner or an # array of owners # @param years [Integer, Range<Integer>, Array<Integer,Range<Integer>>] # The copyright year or years. Years can be specified with integers, # a range of integers, or an array of integers and ranges of # integers. # @return [String] A string describing the copyright on this object. # @api public # @dsl Faces def copyright(owner = nil, years = nil) if years.nil? and !owner.nil? then # TRANSLATORS 'copyright' is an attribute name and should not be translated raise ArgumentError, _('copyright takes the owners names, then the years covered') end self.copyright_owner = owner unless owner.nil? self.copyright_years = years unless years.nil? if copyright_years or copyright_owner then "Copyright #{copyright_years} by #{copyright_owner}" else "Unknown copyright owner and years." end end # Sets the copyright owner # @param value [String, Array<String>] The copyright owner or # owners. # @return [String] Comma-separated list of copyright owners # @api private attr_reader :copyright_owner def copyright_owner=(value) case value when String then @copyright_owner = value when Array then @copyright_owner = value.join(", ") else # TRANSLATORS 'copyright' is an attribute name and should not be translated raise ArgumentError, _("copyright owner must be a string or an array of strings") end end # Sets the copyright year # @param value [Integer, Range<Integer>, Array<Integer, Range>] The # copyright year or years. # @return [String] # @api private attr_reader :copyright_years def copyright_years=(value) years = munge_copyright_year value years = (years.is_a?(Array) ? years : [years]) .sort_by do |x| x.is_a?(Range) ? x.first : x end @copyright_years = years.map do |year| if year.is_a? Range then "#{year.first}-#{year.last}" else year end end.join(", ") end # @api private def munge_copyright_year(input) case input when Range then input when Integer then if input < 1970 then fault = "before 1970" elsif input > (future = Time.now.year + 2) then fault = "after #{future}" end if fault then # TRANSLATORS 'copyright' is an attribute name and should not be translated raise ArgumentError, _("copyright with a year %{value} is very strange; did you accidentally add or subtract two years?") % { value: fault } end input when String then input.strip.split(/,/).map do |part| part = part.strip if part =~ /^\d+$/ part.to_i else found = part.split(/-/) if found unless found.length == 2 and found.all? { |x| x.strip =~ /^\d+$/ } # TRANSLATORS 'copyright' is an attribute name and should not be translated raise ArgumentError, _("%{value} is not a good copyright year or range") % { value: part.inspect } end Range.new(found[0].to_i, found[1].to_i) else # TRANSLATORS 'copyright' is an attribute name and should not be translated raise ArgumentError, _("%{value} is not a good copyright year or range") % { value: part.inspect } end end end when Array then result = [] input.each do |item| item = munge_copyright_year item if item.is_a? Array result.concat item else result << item end end result else # TRANSLATORS 'copyright' is an attribute name and should not be translated raise ArgumentError, _("%{value} is not a good copyright year, set, or range") % { value: input.inspect } end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/interface/option.rb
lib/puppet/interface/option.rb
# frozen_string_literal: true # This represents an option on an action or face (to be globally applied # to its actions). Options should be constructed by calling # {Puppet::Interface::OptionManager#option}, which is available on # {Puppet::Interface}, and then calling methods of # {Puppet::Interface::OptionBuilder} in the supplied block. # @api public class Puppet::Interface::Option include Puppet::Interface::TinyDocs # @api private def initialize(parent, *declaration, &block) @parent = parent @optparse = [] @default = nil # Collect and sort the arguments in the declaration. dups = {} declaration.each do |item| if item.is_a? String and item.to_s =~ /^-/ then unless item =~ /^-[a-z]\b/ or item =~ /^--[^-]/ then raise ArgumentError, _("%{option}: long options need two dashes (--)") % { option: item.inspect } end @optparse << item # Duplicate checking... # for our duplicate checking purpose, we don't make a check with the # translated '-' -> '_'. Right now, we do that on purpose because of # a duplicated option made publicly available on certificate and ca # faces for dns alt names. Puppet defines 'dns_alt_names', those # faces include 'dns-alt-names'. We can't get rid of 'dns-alt-names' # yet, so we need to do our duplicate checking on the untranslated # version of the option. # jeffweiss 17 april 2012 name = optparse_to_optionname(item) if Puppet.settings.include? name then raise ArgumentError, _("%{option}: already defined in puppet") % { option: item.inspect } end dup = dups[name] if dup raise ArgumentError, _("%{option}: duplicates existing alias %{duplicate} in %{parent}") % { option: item.inspect, duplicate: dup.inspect, parent: @parent } else dups[name] = item end else raise ArgumentError, _("%{option} is not valid for an option argument") % { option: item.inspect } end end if @optparse.empty? then raise ArgumentError, _("No option declarations found while building") end # Now, infer the name from the options; we prefer the first long option as # the name, rather than just the first option. @name = optparse_to_name(@optparse.find do |a| a =~ /^--/ end || @optparse.first) @aliases = @optparse.map { |o| optparse_to_name(o) } # Do we take an argument? If so, are we consistent about it, because # incoherence here makes our life super-difficult, and we can more easily # relax this rule later if we find a valid use case for it. --daniel 2011-03-30 @argument = @optparse.any? { |o| o =~ /[ =]/ } if @argument and !@optparse.all? { |o| o =~ /[ =]/ } then raise ArgumentError, _("Option %{name} is inconsistent about taking an argument") % { name: @name } end # Is our argument optional? The rules about consistency apply here, also, # just like they do to taking arguments at all. --daniel 2011-03-30 @optional_argument = @optparse.any? { |o| o =~ /[ =]\[/ } if @optional_argument raise ArgumentError, _("Options with optional arguments are not supported") end if @optional_argument and !@optparse.all? { |o| o =~ /[ =]\[/ } then raise ArgumentError, _("Option %{name} is inconsistent about the argument being optional") % { name: @name } end end # to_s and optparse_to_name are roughly mirrored, because they are used to # transform options to name symbols, and vice-versa. This isn't a full # bidirectional transformation though. --daniel 2011-04-07 def to_s @name.to_s.tr('_', '-') end # @api private def optparse_to_optionname(declaration) found = declaration.match(/^-+(?:\[no-\])?([^ =]+)/) unless found raise ArgumentError, _("Can't find a name in the declaration %{declaration}") % { declaration: declaration.inspect } end found.captures.first end # @api private def optparse_to_name(declaration) name = optparse_to_optionname(declaration).tr('-', '_') unless name.to_s =~ /^[a-z]\w*$/ raise _("%{name} is an invalid option name") % { name: name.inspect } end name.to_sym end def takes_argument? !!@argument end def optional_argument? !!@optional_argument end def required? !!@required end def has_default? !!@default end def default=(proc) if required raise ArgumentError, _("%{name} can't be optional and have a default value") % { name: self } end unless proc.is_a? Proc # TRANSLATORS 'proc' is a Ruby block of code raise ArgumentError, _("default value for %{name} is a %{class_name}, not a proc") % { name: self, class_name: proc.class.name.inspect } end @default = proc end def default @default and @default.call end attr_reader :parent, :name, :aliases, :optparse, :required def required=(value) if has_default? raise ArgumentError, _("%{name} can't be optional and have a default value") % { name: self } end @required = value end attr_reader :before_action def before_action=(proc) unless proc.is_a? Proc # TRANSLATORS 'proc' is a Ruby block of code raise ArgumentError, _("before action hook for %{name} is a %{class_name}, not a proc") % { name: self, class_name: proc.class.name.inspect } end @before_action = @parent.__send__(:__add_method, __decoration_name(:before), proc) end attr_reader :after_action def after_action=(proc) unless proc.is_a? Proc # TRANSLATORS 'proc' is a Ruby block of code raise ArgumentError, _("after action hook for %{name} is a %{class_name}, not a proc") % { name: self, class_name: proc.class.name.inspect } end @after_action = @parent.__send__(:__add_method, __decoration_name(:after), proc) end def __decoration_name(type) if @parent.is_a? Puppet::Interface::Action then :"option #{name} from #{parent.name} #{type} decoration" else :"option #{name} #{type} decoration" end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/interface/option_manager.rb
lib/puppet/interface/option_manager.rb
# frozen_string_literal: true # This class is not actually public API, but the method # {Puppet::Interface::OptionManager#option option} is public when used # as part of the Faces DSL (i.e. from within a # {Puppet::Interface.define define} block). # @api public module Puppet::Interface::OptionManager # @api private def display_global_options(*args) @display_global_options ||= [] [args].flatten.each do |refopt| unless Puppet.settings.include?(refopt) # TRANSLATORS 'Puppet.settings' references to the Puppet settings options and should not be translated raise ArgumentError, _("Global option %{option} does not exist in Puppet.settings") % { option: refopt } end @display_global_options << refopt if refopt end @display_global_options.uniq! @display_global_options end alias :display_global_option :display_global_options def all_display_global_options walk_inheritance_tree(@display_global_options, :all_display_global_options) end # @api private def walk_inheritance_tree(start, sym) result = start || [] if is_a?(Class) and superclass.respond_to?(sym) result = superclass.send(sym) + result elsif self.class.respond_to?(sym) result = self.class.send(sym) + result end result end # Declare that this app can take a specific option, and provide the # code to do so. See {Puppet::Interface::ActionBuilder#option} for # details. # # @api public # @dsl Faces def option(*declaration, &block) add_option Puppet::Interface::OptionBuilder.build(self, *declaration, &block) end # @api private def add_option(option) # @options collects the added options in the order they're declared. # @options_hash collects the options keyed by alias for quick lookups. @options ||= [] @options_hash ||= {} option.aliases.each do |name| conflict = get_option(name) if conflict raise ArgumentError, _("Option %{option} conflicts with existing option %{conflict}") % { option: option, conflict: conflict } end actions.each do |action| action = get_action(action) conflict = action.get_option(name) if conflict raise ArgumentError, _("Option %{option} conflicts with existing option %{conflict} on %{action}") % { option: option, conflict: conflict, action: action } end end end @options << option.name option.aliases.each do |name| @options_hash[name] = option end option end # @api private def options walk_inheritance_tree(@options, :options) end # @api private def get_option(name, with_inherited_options = true) @options_hash ||= {} result = @options_hash[name.to_sym] if result.nil? and with_inherited_options then if is_a?(Class) and superclass.respond_to?(:get_option) result = superclass.get_option(name) elsif self.class.respond_to?(:get_option) result = self.class.get_option(name) end end result end # @api private def option?(name) options.include? name.to_sym end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/interface/action_builder.rb
lib/puppet/interface/action_builder.rb
# frozen_string_literal: true # This class is used to build {Puppet::Interface::Action actions}. # When an action is defined with # {Puppet::Interface::ActionManager#action} the block is evaluated # within the context of a new instance of this class. # @api public class Puppet::Interface::ActionBuilder extend Forwardable # The action under construction # @return [Puppet::Interface::Action] # @api private attr_reader :action # Builds a new action. # @return [Puppet::Interface::Action] # @api private def self.build(face, name, &block) raise "Action #{name.inspect} must specify a block" unless block new(face, name, &block).action end # Deprecates the action # @return [void] # @api private # @dsl Faces def deprecate @action.deprecate end # Ideally the method we're defining here would be added to the action, and a # method on the face would defer to it, but we can't get scope correct, so # we stick with this. --daniel 2011-03-24 # Sets what the action does when it is invoked. This takes a block # which will be called when the action is invoked. The action will # accept arguments based on the arity of the block. It should always # take at least one argument for options. Options will be the last # argument. # # @overload when_invoked({|options| ... }) # An action with no arguments # @overload when_invoked({|arg1, arg2, options| ... }) # An action with two arguments # @return [void] # @api public # @dsl Faces def when_invoked(&block) @action.when_invoked = block end # Sets a block to be run at the rendering stage, for a specific # rendering type (eg JSON, YAML, console), after the block for # when_invoked gets run. This manipulates the value returned by the # action. It makes it possible to work around limitations in the # underlying object returned, and should be avoided in favor of # returning a more capable object. # @api private # @todo this needs more # @dsl Faces def when_rendering(type = nil, &block) if type.nil? then # the default error message sucks --daniel 2011-04-18 # TRANSLATORS 'when_rendering' is a method name and should not be translated raise ArgumentError, _('You must give a rendering format to when_rendering') end if block.nil? then # TRANSLATORS 'when_rendering' is a method name and should not be translated raise ArgumentError, _('You must give a block to when_rendering') end @action.set_rendering_method_for(type, block) end # Declare that this action can take a specific option, and provide the # code to do so. One or more strings are given, in the style of # OptionParser (see example). These strings are parsed to derive a # name for the option. Any `-` characters within the option name (ie # excluding the initial `-` or `--` for an option) will be translated # to `_`.The first long option will be used as the name, and the rest # are retained as aliases. The original form of the option is used # when invoking the face, the translated form is used internally. # # When the action is invoked the value of the option is available in # a hash passed to the {Puppet::Interface::ActionBuilder#when_invoked # when_invoked} block, using the option name in symbol form as the # hash key. # # The block to this method is used to set attributes for the option # (see {Puppet::Interface::OptionBuilder}). # # @param declaration [String] Option declarations, as described above # and in the example. # # @example Say hi # action :say_hi do # option "-u USER", "--user-name USER" do # summary "Who to say hi to" # end # # when_invoked do |options| # "Hi, #{options[:user_name]}" # end # end # @api public # @dsl Faces def option(*declaration, &block) option = Puppet::Interface::OptionBuilder.build(@action, *declaration, &block) @action.add_option(option) end # Set this as the default action for the face. # @api public # @dsl Faces # @return [void] def default(value = true) @action.default = !!value end # @api private def display_global_options(*args) @action.add_display_global_options args end alias :display_global_option :display_global_options # Sets the default rendering format # @api private def render_as(value = nil) if value.nil? # TRANSLATORS 'render_as' is a method name and should not be translated raise ArgumentError, _("You must give a rendering format to render_as") end formats = Puppet::Network::FormatHandler.formats unless formats.include? value raise ArgumentError, _("%{value} is not a valid rendering format: %{formats_list}") % { value: value.inspect, formats_list: formats.sort.join(", ") } end @action.render_as = value end # Metaprogram the simple DSL from the target class. Puppet::Interface::Action.instance_methods.grep(/=$/).each do |setter| next if setter =~ /^=/ property = setter.to_s.chomp('=') unless method_defined? property # ActionBuilder#<property> delegates to Action#<setter> def_delegator :@action, setter, property end end private def initialize(face, name, &block) @face = face @action = Puppet::Interface::Action.new(face, name) instance_eval(&block) unless @action.when_invoked # TRANSLATORS 'when_invoked' is a method name and should not be translated and 'block' is a Ruby code block raise ArgumentError, _("actions need to know what to do when_invoked; please add the block") end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/interface/action.rb
lib/puppet/interface/action.rb
# coding: utf-8 # frozen_string_literal: true require 'prettyprint' # This represents an action that is attached to a face. Actions should # be constructed by calling {Puppet::Interface::ActionManager#action}, # which is available on {Puppet::Interface}, and then calling methods of # {Puppet::Interface::ActionBuilder} in the supplied block. # @api private class Puppet::Interface::Action extend Puppet::Interface::DocGen include Puppet::Interface::FullDocs # @api private def initialize(face, name) raise "#{name.inspect} is an invalid action name" unless name.to_s =~ /^[a-z]\w*$/ @face = face @name = name.to_sym # The few bits of documentation we actually demand. The default license # is a favour to our end users; if you happen to get that in a core face # report it as a bug, please. --daniel 2011-04-26 @authors = [] @license = 'All Rights Reserved' # @options collects the added options in the order they're declared. # @options_hash collects the options keyed by alias for quick lookups. @options = [] @display_global_options = [] @options_hash = {} @when_rendering = {} end # This is not nice, but it is the easiest way to make us behave like the # Ruby Method object rather than UnboundMethod. Duplication is vaguely # annoying, but at least we are a shallow clone. --daniel 2011-04-12 # @return [void] # @api private def __dup_and_rebind_to(to) bound_version = dup bound_version.instance_variable_set(:@face, to) bound_version end def to_s() "#{@face}##{@name}" end # The name of this action # @return [Symbol] attr_reader :name # The face this action is attached to # @return [Puppet::Interface] attr_reader :face # Whether this is the default action for the face # @return [Boolean] # @api private attr_accessor :default def default? !!@default end ######################################################################## # Documentation... attr_doc :returns attr_doc :arguments def synopsis build_synopsis(@face.name, default? ? nil : name, arguments) end ######################################################################## # Support for rendering formats and all. # @api private def when_rendering(type) unless type.is_a? Symbol raise ArgumentError, _("The rendering format must be a symbol, not %{class_name}") % { class_name: type.class.name } end # Do we have a rendering hook for this name? return @when_rendering[type].bind(@face) if @when_rendering.has_key? type # How about by another name? alt = type.to_s.sub(/^to_/, '').to_sym return @when_rendering[alt].bind(@face) if @when_rendering.has_key? alt # Guess not, nothing to run. nil end # @api private def set_rendering_method_for(type, proc) unless proc.is_a? Proc msg = if proc.nil? # TRANSLATORS 'set_rendering_method_for' and 'Proc' should not be translated _("The second argument to set_rendering_method_for must be a Proc") else # TRANSLATORS 'set_rendering_method_for' and 'Proc' should not be translated _("The second argument to set_rendering_method_for must be a Proc, not %{class_name}") % { class_name: proc.class.name } end raise ArgumentError, msg end if proc.arity != 1 and proc.arity != (@positional_arg_count + 1) msg = if proc.arity < 0 then # TRANSLATORS 'when_rendering', 'when_invoked' are method names and should not be translated _("The when_rendering method for the %{face} face %{name} action takes either just one argument,"\ " the result of when_invoked, or the result plus the %{arg_count} arguments passed to the"\ " when_invoked block, not a variable number") % { face: @face.name, name: name, arg_count: @positional_arg_count } else # TRANSLATORS 'when_rendering', 'when_invoked' are method names and should not be translated _("The when_rendering method for the %{face} face %{name} action takes either just one argument,"\ " the result of when_invoked, or the result plus the %{arg_count} arguments passed to the"\ " when_invoked block, not %{string}") % { face: @face.name, name: name, arg_count: @positional_arg_count, string: proc.arity.to_s } end raise ArgumentError, msg end unless type.is_a? Symbol raise ArgumentError, _("The rendering format must be a symbol, not %{class_name}") % { class_name: type.class.name } end if @when_rendering.has_key? type then raise ArgumentError, _("You can't define a rendering method for %{type} twice") % { type: type } end # Now, the ugly bit. We add the method to our interface object, and # retrieve it, to rotate through the dance of getting a suitable method # object out of the whole process. --daniel 2011-04-18 @when_rendering[type] = @face.__send__(:__add_method, __render_method_name_for(type), proc) end # @return [void] # @api private def __render_method_name_for(type) :"#{name}_when_rendering_#{type}" end private :__render_method_name_for # @api private # @return [Symbol] attr_reader :render_as def render_as=(value) @render_as = value.to_sym end # @api private # @return [void] def deprecate @deprecated = true end # @api private # @return [Boolean] def deprecated? @deprecated end ######################################################################## # Initially, this was defined to allow the @action.invoke pattern, which is # a very natural way to invoke behaviour given our introspection # capabilities. Heck, our initial plan was to have the faces delegate to # the action object for invocation and all. # # It turns out that we have a binding problem to solve: @face was bound to # the parent class, not the subclass instance, and we don't pass the # appropriate context or change the binding enough to make this work. # # We could hack around it, by either mandating that you pass the context in # to invoke, or try to get the binding right, but that has probably got # subtleties that we don't instantly think of – especially around threads. # # So, we are pulling this method for now, and will return it to life when we # have the time to resolve the problem. For now, you should replace... # # @action = @face.get_action(name) # @action.invoke(arg1, arg2, arg3) # # ...with... # # @action = @face.get_action(name) # @face.send(@action.name, arg1, arg2, arg3) # # I understand that is somewhat cumbersome, but it functions as desired. # --daniel 2011-03-31 # # PS: This code is left present, but commented, to support this chunk of # documentation, for the benefit of the reader. # # def invoke(*args, &block) # @face.send(name, *args, &block) # end # We need to build an instance method as a wrapper, using normal code, to be # able to expose argument defaulting between the caller and definer in the # Ruby API. An extra method is, sadly, required for Ruby 1.8 to work since # it doesn't expose bind on a block. # # Hopefully we can improve this when we finally shuffle off the last of Ruby # 1.8 support, but that looks to be a few "enterprise" release eras away, so # we are pretty stuck with this for now. # # Patches to make this work more nicely with Ruby 1.9 using runtime version # checking and all are welcome, provided that they don't change anything # outside this little ol' bit of code and all. # # Incidentally, we though about vendoring evil-ruby and actually adjusting # the internal C structure implementation details under the hood to make # this stuff work, because it would have been cleaner. Which gives you an # idea how motivated we were to make this cleaner. Sorry. # --daniel 2011-03-31 # The arity of the action # @return [Integer] attr_reader :positional_arg_count # The block that is executed when the action is invoked # @return [block] attr_reader :when_invoked def when_invoked=(block) internal_name = "#{@name} implementation, required on Ruby 1.8".to_sym arity = @positional_arg_count = block.arity if arity == 0 then # This will never fire on 1.8.7, which treats no arguments as "*args", # but will on 1.9.2, which treats it as "no arguments". Which bites, # because this just begs for us to wind up in the horrible situation # where a 1.8 vs 1.9 error bites our end users. --daniel 2011-04-19 # TRANSLATORS 'when_invoked' should not be translated raise ArgumentError, _("when_invoked requires at least one argument (options) for action %{name}") % { name: @name } elsif arity > 0 then range = Range.new(1, arity - 1) decl = range.map { |x| "arg#{x}" } << "options = {}" optn = "" args = "[" + (range.map { |x| "arg#{x}" } << "options").join(", ") + "]" else range = Range.new(1, arity.abs - 1) decl = range.map { |x| "arg#{x}" } << "*rest" optn = "rest << {} unless rest.last.is_a?(Hash)" if arity == -1 then args = "rest" else args = "[" + range.map { |x| "arg#{x}" }.join(", ") + "] + rest" end end file = __FILE__ + "+eval[wrapper]" line = __LINE__ + 2 # <== points to the same line as 'def' in the wrapper. wrapper = <<~WRAPPER def #{@name}(#{decl.join(', ')}) #{optn} args = #{args} action = get_action(#{name.inspect}) args << action.validate_and_clean(args.pop) __invoke_decorations(:before, action, args, args.last) rval = self.__send__(#{internal_name.inspect}, *args) __invoke_decorations(:after, action, args, args.last) return rval end WRAPPER # It should be possible to rewrite this code to use `define_method` # instead of `class/instance_eval` since Ruby 1.8 is long dead. if @face.is_a?(Class) @face.class_eval do eval wrapper, nil, file, line end # rubocop:disable Security/Eval @face.send(:define_method, internal_name, &block) @when_invoked = @face.instance_method(name) else @face.instance_eval do eval wrapper, nil, file, line end # rubocop:disable Security/Eval @face.meta_def(internal_name, &block) @when_invoked = @face.method(name).unbind end end def add_option(option) option.aliases.each do |name| conflict = get_option(name) if conflict raise ArgumentError, _("Option %{option} conflicts with existing option %{conflict}") % { option: option, conflict: conflict } else conflict = @face.get_option(name) if conflict raise ArgumentError, _("Option %{option} conflicts with existing option %{conflict} on %{face}") % { option: option, conflict: conflict, face: @face } end end end @options << option.name option.aliases.each do |name| @options_hash[name] = option end option end def option?(name) @options_hash.include? name.to_sym end def options @face.options + @options end def add_display_global_options(*args) @display_global_options ||= [] [args].flatten.each do |refopt| unless Puppet.settings.include? refopt # TRANSLATORS 'Puppet.settings' should not be translated raise ArgumentError, _("Global option %{option} does not exist in Puppet.settings") % { option: refopt } end @display_global_options << refopt end @display_global_options.uniq! @display_global_options end def display_global_options(*args) args ? add_display_global_options(args) : @display_global_options + @face.display_global_options end alias :display_global_option :display_global_options def get_option(name, with_inherited_options = true) option = @options_hash[name.to_sym] if option.nil? and with_inherited_options option = @face.get_option(name) end option end def validate_and_clean(original) # The final set of arguments; effectively a hand-rolled shallow copy of # the original, which protects the caller from the surprises they might # get if they passed us a hash and we mutated it... result = {} # Check for multiple aliases for the same option, and canonicalize the # name of the argument while we are about it. overlap = Hash.new do |h, k| h[k] = [] end unknown = [] original.keys.each do |name| option = get_option(name) if option canonical = option.name if result.has_key? canonical overlap[canonical] << name else result[canonical] = original[name] end elsif Puppet.settings.include? name result[name] = original[name] else unknown << name end end unless overlap.empty? overlap_list = overlap.map { |k, v| "(#{k}, #{v.sort.join(', ')})" }.join(", ") raise ArgumentError, _("Multiple aliases for the same option passed: %{overlap_list}") % { overlap_list: overlap_list } end unless unknown.empty? unknown_list = unknown.sort.join(", ") raise ArgumentError, _("Unknown options passed: %{unknown_list}") % { unknown_list: unknown_list } end # Inject default arguments and check for missing mandating options. missing = [] options.map { |x| get_option(x) }.each do |option| name = option.name next if result.has_key? name if option.has_default? result[name] = option.default elsif option.required? missing << name end end unless missing.empty? missing_list = missing.sort.join(', ') raise ArgumentError, _("The following options are required: %{missing_list}") % { missing_list: missing_list } end # All done. result end ######################################################################## # Support code for action decoration; see puppet/interface.rb for the gory # details of why this is hidden away behind private. --daniel 2011-04-15 private # @return [void] # @api private def __add_method(name, proc) @face.__send__ :__add_method, name, proc end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/graph/sequential_prioritizer.rb
lib/puppet/graph/sequential_prioritizer.rb
# frozen_string_literal: true # This implements a priority in which keys are given values that will keep them # in the same priority in which they priorities are requested. Nested # structures (those in which a key is contained within another key) are # preserved in such a way that child keys are after the parent and before the # key after the parent. # # @api private class Puppet::Graph::SequentialPrioritizer < Puppet::Graph::Prioritizer def initialize super @container = {} @count = Puppet::Graph::Key.new end def generate_priority_for(key) if priority_of(key).nil? @count = @count.next record_priority_for(key, @count) else priority_of(key) end end def generate_priority_contained_in(container, key) @container[container] ||= priority_of(container).down priority = @container[container].next record_priority_for(key, priority) @container[container] = priority priority end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/graph/rb_tree_map.rb
lib/puppet/graph/rb_tree_map.rb
# frozen_string_literal: true # Algorithms and Containers project is Copyright (c) 2009 Kanwei Li # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the 'Software'), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. # # A RbTreeMap is a map that is stored in sorted order based on the order of its keys. This ordering is # determined by applying the function <=> to compare the keys. No duplicate values for keys are allowed, # so duplicate values are overwritten. # # A major advantage of RBTreeMap over a Hash is the fact that keys are stored in order and can thus be # iterated over in order. This is useful for many datasets. # # The implementation is adapted from Robert Sedgewick's Left Leaning Red-Black Tree implementation, # which can be found at https://www.cs.princeton.edu/~rs/talks/LLRB/Java/RedBlackBST.java # # Most methods have O(log n) complexity. class Puppet::Graph::RbTreeMap include Enumerable attr_reader :size alias_method :length, :size # Create and initialize a new empty TreeMap. def initialize @root = nil @size = 0 end # Insert an item with an associated key into the TreeMap, and returns the item inserted # # Complexity: O(log n) # # map = Containers::TreeMap.new # map.push("MA", "Massachusetts") #=> "Massachusetts" # map.get("MA") #=> "Massachusetts" def push(key, value) @root = insert(@root, key, value) @root.color = :black value end alias_method :[]=, :push # Return true if key is found in the TreeMap, false otherwise # # Complexity: O(log n) # # map = Containers::TreeMap.new # map.push("MA", "Massachusetts") # map.push("GA", "Georgia") # map.has_key?("GA") #=> true # map.has_key?("DE") #=> false def has_key?(key) !get_recursive(@root, key).nil? end # Return the item associated with the key, or nil if none found. # # Complexity: O(log n) # # map = Containers::TreeMap.new # map.push("MA", "Massachusetts") # map.push("GA", "Georgia") # map.get("GA") #=> "Georgia" def get(key) node = get_recursive(@root, key) node ? node.value : nil node.value if node end alias_method :[], :get # Return the smallest key in the map. # # Complexity: O(log n) # # map = Containers::TreeMap.new # map.push("MA", "Massachusetts") # map.push("GA", "Georgia") # map.min_key #=> "GA" def min_key @root.nil? ? nil : min_recursive(@root).key end # Return the largest key in the map. # # Complexity: O(log n) # # map = Containers::TreeMap.new # map.push("MA", "Massachusetts") # map.push("GA", "Georgia") # map.max_key #=> "MA" def max_key @root.nil? ? nil : max_recursive(@root).key end # Deletes the item and key if it's found, and returns the item. Returns nil # if key is not present. # # Complexity: O(log n) # # map = Containers::TreeMap.new # map.push("MA", "Massachusetts") # map.push("GA", "Georgia") # map.delete("MA") #=> "Massachusetts" def delete(key) result = nil if @root return unless has_key? key @root, result = delete_recursive(@root, key) @root.color = :black if @root @size -= 1 end result end # Returns true if the tree is empty, false otherwise def empty? @root.nil? end # Deletes the item with the smallest key and returns the item. Returns nil # if key is not present. # # Complexity: O(log n) # # map = Containers::TreeMap.new # map.push("MA", "Massachusetts") # map.push("GA", "Georgia") # map.delete_min #=> "Massachusetts" # map.size #=> 1 def delete_min result = nil if @root @root, result = delete_min_recursive(@root) @root.color = :black if @root @size -= 1 end result end # Deletes the item with the largest key and returns the item. Returns nil # if key is not present. # # Complexity: O(log n) # # map = Containers::TreeMap.new # map.push("MA", "Massachusetts") # map.push("GA", "Georgia") # map.delete_max #=> "Georgia" # map.size #=> 1 def delete_max result = nil if @root @root, result = delete_max_recursive(@root) @root.color = :black if @root @size -= 1 end result end # Yields [key, value] pairs in order by key. def each(&blk) recursive_yield(@root, &blk) end def first return nil unless @root node = min_recursive(@root) [node.key, node.value] end def last return nil unless @root node = max_recursive(@root) [node.key, node.value] end def to_hash @root ? @root.to_hash : {} end class Node # :nodoc: all attr_accessor :color, :key, :value, :left, :right def initialize(key, value) @key = key @value = value @color = :red @left = nil @right = nil end def to_hash h = { :node => { :key => @key, :value => @value, :color => @color, } } h[:left] = left.to_hash if @left h[:right] = right.to_hash if @right h end def red? @color == :red end def colorflip @color = @color == :red ? :black : :red @left.color = @left.color == :red ? :black : :red @right.color = @right.color == :red ? :black : :red end def rotate_left r = @right r_key = r.key r_value = r.value b = r.left r.left = @left @left = r @right = r.right r.right = b r.color = :red r.key = @key r.value = @value @key = r_key @value = r_value self end def rotate_right l = @left l_key = l.key l_value = l.value b = l.right l.right = @right @right = l @left = l.left l.left = b l.color = :red l.key = @key l.value = @value @key = l_key @value = l_value self end def move_red_left colorflip if @right.left && @right.left.red? @right.rotate_right rotate_left colorflip end self end def move_red_right colorflip if @left.left && @left.left.red? rotate_right colorflip end self end def fixup rotate_left if @right && @right.red? rotate_right if (@left && @left.red?) && (@left.left && @left.left.red?) colorflip if (@left && @left.red?) && (@right && @right.red?) self end end private def recursive_yield(node, &blk) return unless node recursive_yield(node.left, &blk) yield node.key, node.value recursive_yield(node.right, &blk) end def delete_recursive(node, key) if (key <=> node.key) == -1 node.move_red_left if !isred(node.left) && !isred(node.left.left) node.left, result = delete_recursive(node.left, key) else node.rotate_right if isred(node.left) if ((key <=> node.key) == 0) && node.right.nil? return nil, node.value end if !isred(node.right) && !isred(node.right.left) node.move_red_right end if (key <=> node.key) == 0 result = node.value min_child = min_recursive(node.right) node.value = min_child.value node.key = min_child.key node.right = delete_min_recursive(node.right).first else node.right, result = delete_recursive(node.right, key) end end [node.fixup, result] end def delete_min_recursive(node) if node.left.nil? return nil, node.value end if !isred(node.left) && !isred(node.left.left) node.move_red_left end node.left, result = delete_min_recursive(node.left) [node.fixup, result] end def delete_max_recursive(node) if isred(node.left) node = node.rotate_right end return nil, node.value if node.right.nil? if !isred(node.right) && !isred(node.right.left) node.move_red_right end node.right, result = delete_max_recursive(node.right) [node.fixup, result] end def get_recursive(node, key) return nil if node.nil? case key <=> node.key when 0 then node when -1 then get_recursive(node.left, key) when 1 then get_recursive(node.right, key) end end def min_recursive(node) return node if node.left.nil? min_recursive(node.left) end def max_recursive(node) return node if node.right.nil? max_recursive(node.right) end def insert(node, key, value) unless node @size += 1 return Node.new(key, value) end case key <=> node.key when 0 then node.value = value when -1 then node.left = insert(node.left, key, value) when 1 then node.right = insert(node.right, key, value) end node.rotate_left if node.right && node.right.red? node.rotate_right if node.left && node.left.red? && node.left.left && node.left.left.red? node.colorflip if node.left && node.left.red? && node.right && node.right.red? node end def isred(node) return false if node.nil? node.color == :red end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/graph/simple_graph.rb
lib/puppet/graph/simple_graph.rb
# frozen_string_literal: true require_relative '../../puppet/external/dot' require_relative '../../puppet/relationship' require 'set' # A hopefully-faster graph class to replace the use of GRATR. class Puppet::Graph::SimpleGraph include Puppet::Util::PsychSupport # # All public methods of this class must maintain (assume ^ ensure) the following invariants, where "=~=" means # equiv. up to order: # # @in_to.keys =~= @out_to.keys =~= all vertices # @in_to.values.collect { |x| x.values }.flatten =~= @out_from.values.collect { |x| x.values }.flatten =~= all edges # @in_to[v1][v2] =~= @out_from[v2][v1] =~= all edges from v1 to v2 # @in_to [v].keys =~= vertices with edges leading to v # @out_from[v].keys =~= vertices with edges leading from v # no operation may shed reference loops (for gc) # recursive operation must scale with the depth of the spanning trees, or better (e.g. no recursion over the set # of all vertices, etc.) # # This class is intended to be used with DAGs. However, if the # graph has a cycle, it will not cause non-termination of any of the # algorithms. # def initialize @in_to = {} @out_from = {} @upstream_from = {} @downstream_from = {} end # Clear our graph. def clear @in_to.clear @out_from.clear @upstream_from.clear @downstream_from.clear end # Which resources the given resource depends on. def dependencies(resource) vertex?(resource) ? upstream_from_vertex(resource).keys : [] end # Which resources depend upon the given resource. def dependents(resource) vertex?(resource) ? downstream_from_vertex(resource).keys : [] end # Whether our graph is directed. Always true. Used to produce dot files. def directed? true end # Determine all of the leaf nodes below a given vertex. def leaves(vertex, direction = :out) tree_from_vertex(vertex, direction).keys.find_all { |c| adjacent(c, :direction => direction).empty? } end # Collect all of the edges that the passed events match. Returns # an array of edges. def matching_edges(event, base = nil) source = base || event.resource unless vertex?(source) Puppet.warning _("Got an event from invalid vertex %{source}") % { source: source.ref } return [] end # Get all of the edges that this vertex should forward events # to, which is the same thing as saying all edges directly below # This vertex in the graph. @out_from[source].values.flatten.find_all { |edge| edge.match?(event.name) } end # Return a reversed version of this graph. def reversal result = self.class.new vertices.each { |vertex| result.add_vertex(vertex) } edges.each do |edge| result.add_edge edge.class.new(edge.target, edge.source, edge.label) end result end # Return the size of the graph. def size vertices.size end def to_a vertices end # This is a simple implementation of Tarjan's algorithm to find strongly # connected components in the graph; this is a fairly ugly implementation, # because I can't just decorate the vertices themselves. # # This method has an unhealthy relationship with the find_cycles_in_graph # method below, which contains the knowledge of how the state object is # maintained. def tarjan(root, s) # initialize the recursion stack we use to work around the nasty lack of a # decent Ruby stack. recur = [{ :node => root }] until recur.empty? frame = recur.last vertex = frame[:node] case frame[:step] when nil then s[:index][vertex] = s[:number] s[:lowlink][vertex] = s[:number] s[:number] = s[:number] + 1 s[:stack].push(vertex) s[:seen][vertex] = true frame[:children] = adjacent(vertex) frame[:step] = :children when :children then if frame[:children].length > 0 then child = frame[:children].shift if !s[:index][child] then # Never seen, need to recurse. frame[:step] = :after_recursion frame[:child] = child recur.push({ :node => child }) elsif s[:seen][child] then s[:lowlink][vertex] = [s[:lowlink][vertex], s[:index][child]].min end else if s[:lowlink][vertex] == s[:index][vertex] then this_scc = [] loop do top = s[:stack].pop s[:seen][top] = false this_scc << top break if top == vertex end s[:scc] << this_scc end recur.pop # done with this node, finally. end when :after_recursion then s[:lowlink][vertex] = [s[:lowlink][vertex], s[:lowlink][frame[:child]]].min frame[:step] = :children else fail "#{frame[:step]} is an unknown step" end end end # Find all cycles in the graph by detecting all the strongly connected # components, then eliminating everything with a size of one as # uninteresting - which it is, because it can't be a cycle. :) # # This has an unhealthy relationship with the 'tarjan' method above, which # it uses to implement the detection of strongly connected components. def find_cycles_in_graph state = { :number => 0, :index => {}, :lowlink => {}, :scc => [], :stack => [], :seen => {} } # we usually have a disconnected graph, must walk all possible roots vertices.each do |vertex| unless state[:index][vertex] then tarjan vertex, state end end # To provide consistent results to the user, given that a hash is never # assured to return the same order, and given our graph processing is # based on hash tables, we need to sort the cycles internally, as well as # the set of cycles. # # Given we are in a failure state here, any extra cost is more or less # irrelevant compared to the cost of a fix - which is on a human # time-scale. state[:scc].select do |component| multi_vertex_component?(component) || single_vertex_referring_to_self?(component) end.map(&:sort).sort end # Perform a BFS on the sub graph representing the cycle, with a view to # generating a sufficient set of paths to report the cycle meaningfully, and # ideally usefully, for the end user. # # BFS is preferred because it will generally report the shortest paths # through the graph first, which are more likely to be interesting to the # user. I think; it would be interesting to verify that. --daniel 2011-01-23 def paths_in_cycle(cycle, max_paths = 1) # TRANSLATORS "negative or zero" refers to the count of paths raise ArgumentError, _("negative or zero max_paths") if max_paths < 1 # Calculate our filtered outbound vertex lists... adj = {} cycle.each do |vertex| adj[vertex] = adjacent(vertex).select { |s| cycle.member? s } end found = [] # frame struct is vertex, [path] stack = [[cycle.first, []]] while frame = stack.shift # rubocop:disable Lint/AssignmentInCondition if frame[1].member?(frame[0]) then found << frame[1] + [frame[0]] break if found.length >= max_paths else adj[frame[0]].each do |to| stack.push [to, frame[1] + [frame[0]]] end end end found.sort end # @return [Array] array of dependency cycles (arrays) def report_cycles_in_graph cycles = find_cycles_in_graph number_of_cycles = cycles.length return if number_of_cycles == 0 message = n_("Found %{num} dependency cycle:\n", "Found %{num} dependency cycles:\n", number_of_cycles) % { num: number_of_cycles } cycles.each do |cycle| paths = paths_in_cycle(cycle) message += paths.map { |path| '(' + path.join(' => ') + ')' }.join('\n') + '\n' end if Puppet[:graph] then filename = write_cycles_to_graph(cycles) message += _("Cycle graph written to %{filename}.") % { filename: filename } else # TRANSLATORS '--graph' refers to a command line option and OmniGraffle and GraphViz are program names and should not be translated message += _("Try the '--graph' option and opening the resulting '.dot' file in OmniGraffle or GraphViz") end Puppet.err(message) cycles end def write_cycles_to_graph(cycles) # This does not use the DOT graph library, just writes the content # directly. Given the complexity of this, there didn't seem much point # using a heavy library to generate exactly the same content. --daniel 2011-01-27 graph = ["digraph Resource_Cycles {"] graph << ' label = "Resource Cycles"' cycles.each do |cycle| paths_in_cycle(cycle, 10).each do |path| graph << path.map { |v| '"' + v.to_s.gsub(/"/, '\\"') + '"' }.join(" -> ") end end graph << '}' filename = File.join(Puppet[:graphdir], "cycles.dot") # DOT files are assumed to be UTF-8 by default - http://www.graphviz.org/doc/info/lang.html File.open(filename, "w:UTF-8") { |f| f.puts graph } filename end # Add a new vertex to the graph. def add_vertex(vertex) @in_to[vertex] ||= {} @out_from[vertex] ||= {} end # Remove a vertex from the graph. def remove_vertex!(v) return unless vertex?(v) @upstream_from.clear @downstream_from.clear (@in_to[v].values + @out_from[v].values).flatten.each { |e| remove_edge!(e) } @in_to.delete(v) @out_from.delete(v) end # Test whether a given vertex is in the graph. def vertex?(v) @in_to.include?(v) end # Return a list of all vertices. def vertices @in_to.keys end # Add a new edge. The graph user has to create the edge instance, # since they have to specify what kind of edge it is. def add_edge(e, *a) return add_relationship(e, *a) unless a.empty? e = Puppet::Relationship.from_data_hash(e) if e.is_a?(Hash) @upstream_from.clear @downstream_from.clear add_vertex(e.source) add_vertex(e.target) # Avoid multiple lookups here. This code is performance critical arr = (@in_to[e.target][e.source] ||= []) arr << e unless arr.include?(e) arr = (@out_from[e.source][e.target] ||= []) arr << e unless arr.include?(e) end def add_relationship(source, target, label = nil) add_edge Puppet::Relationship.new(source, target, label) end # Find all matching edges. def edges_between(source, target) (@out_from[source] || {})[target] || [] end # Is there an edge between the two vertices? def edge?(source, target) vertex?(source) and vertex?(target) and @out_from[source][target] end def edges @in_to.values.collect(&:values).flatten end def each_edge @in_to.each { |_t, ns| ns.each { |_s, es| es.each { |e| yield e } } } end # Remove an edge from our graph. def remove_edge!(e) if edge?(e.source, e.target) @upstream_from.clear @downstream_from.clear @in_to[e.target].delete e.source if (@in_to[e.target][e.source] -= [e]).empty? @out_from[e.source].delete e.target if (@out_from[e.source][e.target] -= [e]).empty? end end # Find adjacent edges. def adjacent(v, options = {}) ns = (options[:direction] == :in) ? @in_to[v] : @out_from[v] return [] unless ns (options[:type] == :edges) ? ns.values.flatten : ns.keys end # Just walk the tree and pass each edge. def walk(source, direction) # Use an iterative, breadth-first traversal of the graph. One could do # this recursively, but Ruby's slow function calls and even slower # recursion make the shorter, recursive algorithm cost-prohibitive. stack = [source] seen = Set.new until stack.empty? node = stack.shift next if seen.member? node connected = adjacent(node, :direction => direction) connected.each do |target| yield node, target end stack.concat(connected) seen << node end end # A different way of walking a tree, and a much faster way than the # one that comes with GRATR. def tree_from_vertex(start, direction = :out) predecessor = {} walk(start, direction) do |parent, child| predecessor[child] = parent end predecessor end def downstream_from_vertex(v) return @downstream_from[v] if @downstream_from[v] result = @downstream_from[v] = {} @out_from[v].keys.each do |node| result[node] = 1 result.update(downstream_from_vertex(node)) end result end def direct_dependents_of(v) (@out_from[v] || {}).keys end def upstream_from_vertex(v) return @upstream_from[v] if @upstream_from[v] result = @upstream_from[v] = {} @in_to[v].keys.each do |node| result[node] = 1 result.update(upstream_from_vertex(node)) end result end def direct_dependencies_of(v) (@in_to[v] || {}).keys end # Return an array of the edge-sets between a series of n+1 vertices (f=v0,v1,v2...t=vn) # connecting the two given vertices. The ith edge set is an array containing all the # edges between v(i) and v(i+1); these are (by definition) never empty. # # * if f == t, the list is empty # * if they are adjacent the result is an array consisting of # a single array (the edges from f to t) # * and so on by induction on a vertex m between them # * if there is no path from f to t, the result is nil # # This implementation is not particularly efficient; it's used in testing where clarity # is more important than last-mile efficiency. # def path_between(f, t) if f == t [] elsif direct_dependents_of(f).include?(t) [edges_between(f, t)] elsif dependents(f).include?(t) m = (dependents(f) & direct_dependencies_of(t)).first path_between(f, m) + path_between(m, t) else nil end end # LAK:FIXME This is just a paste of the GRATR code with slight modifications. # Return a DOT::DOTDigraph for directed graphs or a DOT::DOTSubgraph for an # undirected Graph. _params_ can contain any graph property specified in # rdot.rb. If an edge or vertex label is a kind of Hash then the keys # which match +dot+ properties will be used as well. def to_dot_graph(params = {}) params['name'] ||= self.class.name.tr(':', '_') fontsize = params['fontsize'] || '8' graph = (directed? ? DOT::DOTDigraph : DOT::DOTSubgraph).new(params) edge_klass = directed? ? DOT::DOTDirectedEdge : DOT::DOTEdge vertices.each do |v| name = v.ref params = { 'name' => stringify(name), 'fontsize' => fontsize, 'label' => name } v_label = v.ref params.merge!(v_label) if v_label and v_label.is_a? Hash graph << DOT::DOTNode.new(params) end edges.each do |e| params = { 'from' => stringify(e.source.ref), 'to' => stringify(e.target.ref), 'fontsize' => fontsize } e_label = e.ref params.merge!(e_label) if e_label and e_label.is_a? Hash graph << edge_klass.new(params) end graph end def stringify(s) %("#{s.gsub('"', '\\"')}") end # Output the dot format as a string def to_dot(params = {}) to_dot_graph(params).to_s; end # Produce the graph files if requested. def write_graph(name) return unless Puppet[:graph] file = File.join(Puppet[:graphdir], "#{name}.dot") # DOT files are assumed to be UTF-8 by default - http://www.graphviz.org/doc/info/lang.html File.open(file, "w:UTF-8") { |f| f.puts to_dot("name" => name.to_s.capitalize) } end # This flag may be set to true to use the new YAML serialization # format (where @vertices is a simple list of vertices rather than a # list of VertexWrapper objects). Deserialization supports both # formats regardless of the setting of this flag. class << self attr_accessor :use_new_yaml_format end self.use_new_yaml_format = false def initialize_from_hash(hash) initialize vertices = hash['vertices'] edges = hash['edges'] if vertices.is_a?(Hash) # Support old (2.6) format vertices = vertices.keys end vertices.each { |v| add_vertex(v) } unless vertices.nil? edges.each { |e| add_edge(e) } unless edges.nil? end def to_data_hash hash = { 'edges' => edges.map(&:to_data_hash) } hash['vertices'] = if self.class.use_new_yaml_format vertices else # Represented in YAML using the old (version 2.6) format. result = {} vertices.each do |vertex| adjacencies = {} [:in, :out].each do |direction| direction_hash = {} adjacencies[direction.to_s] = direction_hash adjacent(vertex, :direction => direction, :type => :edges).each do |edge| other_vertex = direction == :in ? edge.source : edge.target (direction_hash[other_vertex.to_s] ||= []) << edge end direction_hash.each_pair { |key, edges| direction_hash[key] = edges.uniq.map(&:to_data_hash) } end vname = vertex.to_s result[vname] = { 'adjacencies' => adjacencies, 'vertex' => vname } end result end hash end def multi_vertex_component?(component) component.length > 1 end private :multi_vertex_component? def single_vertex_referring_to_self?(component) if component.length == 1 vertex = component[0] adjacent(vertex).include?(vertex) else false end end private :single_vertex_referring_to_self? end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/graph/relationship_graph.rb
lib/puppet/graph/relationship_graph.rb
# frozen_string_literal: true # The relationship graph is the final form of a puppet catalog in # which all dependency edges are explicitly in the graph. This form of the # catalog is used to traverse the graph in the order in which resources are # managed. # # @api private class Puppet::Graph::RelationshipGraph < Puppet::Graph::SimpleGraph attr_reader :blockers def initialize(prioritizer) super() @prioritizer = prioritizer @ready = Puppet::Graph::RbTreeMap.new @generated = {} @done = {} @blockers = {} @providerless_types = [] end def populate_from(catalog) add_all_resources_as_vertices(catalog) build_manual_dependencies build_autorelation_dependencies(catalog) write_graph(:relationships) if catalog.host_config? replace_containers_with_anchors(catalog) write_graph(:expanded_relationships) if catalog.host_config? end def add_vertex(vertex, priority = nil) super(vertex) if priority @prioritizer.record_priority_for(vertex, priority) else @prioritizer.generate_priority_for(vertex) end end def add_relationship(f, t, label = nil) super(f, t, label) @ready.delete(@prioritizer.priority_of(t)) end def remove_vertex!(vertex) super @prioritizer.forget(vertex) end def resource_priority(resource) @prioritizer.priority_of(resource) end # Enqueue the initial set of resources, those with no dependencies. def enqueue_roots vertices.each do |v| @blockers[v] = direct_dependencies_of(v).length enqueue(v) if @blockers[v] == 0 end end # Decrement the blocker count for the resource by 1. If the number of # blockers is unknown, count them and THEN decrement by 1. def unblock(resource) @blockers[resource] ||= direct_dependencies_of(resource).select { |r2| !@done[r2] }.length if @blockers[resource] > 0 @blockers[resource] -= 1 else resource.warning _("appears to have a negative number of dependencies") end @blockers[resource] <= 0 end def clear_blockers @blockers.clear end def enqueue(*resources) resources.each do |resource| @ready[@prioritizer.priority_of(resource)] = resource end end def finish(resource) direct_dependents_of(resource).each do |v| enqueue(v) if unblock(v) end @done[resource] = true end def next_resource @ready.delete_min end def traverse(options = {}, &block) continue_while = options[:while] || -> { true } pre_process = options[:pre_process] || ->(resource) {} overly_deferred_resource_handler = options[:overly_deferred_resource_handler] || ->(resource) {} canceled_resource_handler = options[:canceled_resource_handler] || ->(resource) {} teardown = options[:teardown] || -> {} graph_cycle_handler = options[:graph_cycle_handler] || -> { [] } cycles = report_cycles_in_graph if cycles graph_cycle_handler.call(cycles) end enqueue_roots deferred_resources = [] while continue_while.call() && (resource = next_resource) if resource.suitable? made_progress = true pre_process.call(resource) yield resource finish(resource) else deferred_resources << resource end next unless @ready.empty? and deferred_resources.any? if made_progress enqueue(*deferred_resources) else deferred_resources.each do |res| overly_deferred_resource_handler.call(res) finish(res) end end made_progress = false deferred_resources = [] end unless continue_while.call() while (resource = next_resource) canceled_resource_handler.call(resource) finish(resource) end end teardown.call() end private def add_all_resources_as_vertices(catalog) catalog.resources.each do |vertex| add_vertex(vertex) end end def build_manual_dependencies vertices.each do |vertex| vertex.builddepends.each do |edge| add_edge(edge) end end end def build_autorelation_dependencies(catalog) vertices.each do |vertex| [:require, :subscribe].each do |rel_type| vertex.send("auto#{rel_type}".to_sym, catalog).each do |edge| # don't let automatic relationships conflict with manual ones. next if edge?(edge.source, edge.target) if edge?(edge.target, edge.source) vertex.debug "Skipping automatic relationship with #{edge.source}" else vertex.debug "Adding auto#{rel_type} relationship with #{edge.source}" if rel_type == :require edge.event = :NONE else edge.callback = :refresh edge.event = :ALL_EVENTS end add_edge(edge) end end end [:before, :notify].each do |rel_type| vertex.send("auto#{rel_type}".to_sym, catalog).each do |edge| # don't let automatic relationships conflict with manual ones. next if edge?(edge.target, edge.source) if edge?(edge.source, edge.target) vertex.debug "Skipping automatic relationship with #{edge.target}" else vertex.debug "Adding auto#{rel_type} relationship with #{edge.target}" if rel_type == :before edge.event = :NONE else edge.callback = :refresh edge.event = :ALL_EVENTS end add_edge(edge) end end end end end # Impose our container information on another graph by using it # to replace any container vertices X with a pair of vertices # { admissible_X and completed_X } such that # # 0) completed_X depends on admissible_X # 1) contents of X each depend on admissible_X # 2) completed_X depends on each on the contents of X # 3) everything which depended on X depends on completed_X # 4) admissible_X depends on everything X depended on # 5) the containers and their edges must be removed # # Note that this requires attention to the possible case of containers # which contain or depend on other containers, but has the advantage # that the number of new edges created scales linearly with the number # of contained vertices regardless of how containers are related; # alternatives such as replacing container-edges with content-edges # scale as the product of the number of external dependencies, which is # to say geometrically in the case of nested / chained containers. # Default_label = { :callback => :refresh, :event => :ALL_EVENTS } def replace_containers_with_anchors(catalog) stage_class = Puppet::Type.type(:stage) whit_class = Puppet::Type.type(:whit) component_class = Puppet::Type.type(:component) containers = catalog.resources.find_all { |v| (v.is_a?(component_class) or v.is_a?(stage_class)) and vertex?(v) } # # These two hashes comprise the aforementioned attention to the possible # case of containers that contain / depend on other containers; they map # containers to their sentinels but pass other vertices through. Thus we # can "do the right thing" for references to other vertices that may or # may not be containers. # admissible = Hash.new { |_h, k| k } completed = Hash.new { |_h, k| k } containers.each { |x| admissible[x] = whit_class.new(:name => "admissible_#{x.ref}", :catalog => catalog) completed[x] = whit_class.new(:name => "completed_#{x.ref}", :catalog => catalog) # This copies the original container's tags over to the two anchor whits. # Without this, tags are not propagated to the container's resources. admissible[x].set_tags(x) completed[x].set_tags(x) priority = @prioritizer.priority_of(x) add_vertex(admissible[x], priority) add_vertex(completed[x], priority) } # # Implement the six requirements listed above # containers.each { |x| contents = catalog.adjacent(x, :direction => :out) add_edge(admissible[x], completed[x]) if contents.empty? # (0) contents.each { |v| add_edge(admissible[x], admissible[v], Default_label) # (1) add_edge(completed[v], completed[x], Default_label) # (2) } # (3) & (5) adjacent(x, :direction => :in, :type => :edges).each { |e| add_edge(completed[e.source], admissible[x], e.label) remove_edge! e } # (4) & (5) adjacent(x, :direction => :out, :type => :edges).each { |e| add_edge(completed[x], admissible[e.target], e.label) remove_edge! e } } containers.each { |x| remove_vertex! x } # (5) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/graph/prioritizer.rb
lib/puppet/graph/prioritizer.rb
# frozen_string_literal: true # Base, template method, class for Prioritizers. This provides the basic # tracking facilities used. # # @api private class Puppet::Graph::Prioritizer def initialize @priority = {} end def forget(key) @priority.delete(key) end def record_priority_for(key, priority) @priority[key] = priority end def generate_priority_for(key) raise NotImplementedError end def generate_priority_contained_in(container, key) raise NotImplementedError end def priority_of(key) @priority[key] end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/graph/key.rb
lib/puppet/graph/key.rb
# frozen_string_literal: true # Sequential, nestable keys for tracking order of insertion in "the graph" # @api private class Puppet::Graph::Key include Comparable attr_reader :value protected :value def initialize(value = [0]) @value = value end def next next_values = @value.clone next_values[-1] += 1 Puppet::Graph::Key.new(next_values) end def down Puppet::Graph::Key.new(@value + [0]) end def <=>(other) @value <=> other.value end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/enum_setting.rb
lib/puppet/settings/enum_setting.rb
# frozen_string_literal: true class Puppet::Settings::EnumSetting < Puppet::Settings::BaseSetting attr_accessor :values def type :enum end def munge(value) if values.include?(value) value else raise Puppet::Settings::ValidationError, _("Invalid value '%{value}' for parameter %{name}. Allowed values are '%{allowed_values}'") % { value: value, name: @name, allowed_values: values.join("', '") } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/priority_setting.rb
lib/puppet/settings/priority_setting.rb
# frozen_string_literal: true require_relative '../../puppet/settings/base_setting' # A setting that represents a scheduling priority, and evaluates to an # OS-specific priority level. class Puppet::Settings::PrioritySetting < Puppet::Settings::BaseSetting PRIORITY_MAP = if Puppet::Util::Platform.windows? require_relative '../../puppet/util/windows/process' require_relative '../../puppet/ffi/windows/constants' { :high => Puppet::FFI::Windows::Constants::HIGH_PRIORITY_CLASS, :normal => Puppet::FFI::Windows::Constants::NORMAL_PRIORITY_CLASS, :low => Puppet::FFI::Windows::Constants::BELOW_NORMAL_PRIORITY_CLASS, :idle => Puppet::FFI::Windows::Constants::IDLE_PRIORITY_CLASS } else { :high => -10, :normal => 0, :low => 10, :idle => 19 } end def type :priority end def munge(value) return unless value if value.is_a?(Integer) value elsif value.is_a?(String) and value =~ /\d+/ value.to_i elsif value.is_a?(String) and PRIORITY_MAP[value.to_sym] PRIORITY_MAP[value.to_sym] else raise Puppet::Settings::ValidationError, _("Invalid priority format '%{value}' for parameter: %{name}") % { value: value.inspect, name: @name } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/base_setting.rb
lib/puppet/settings/base_setting.rb
# frozen_string_literal: true require 'set' require_relative '../../puppet/settings/errors' # The base setting type class Puppet::Settings::BaseSetting attr_writer :default attr_accessor :name, :desc, :section attr_reader :short, :deprecated, :call_hook # Hooks are called during different parts of the settings lifecycle: # # * :on_write_only - This is the default hook type. The hook will be called # if its value is set in `main` or programmatically. If its value is set in # a section that doesn't match the application's run mode, it will be # ignored entirely. If the section does match the run mode, the value will # be used, but the hook will not be called! # # * :on_define_and_write - The hook behaves the same as above, except it is # also called immediately when the setting is defined in # {Puppet::Settings.define_settings}. In that case, the hook receives the # default value as specified. # # * :on_initialize_and_write - The hook will be called if the value is set in # `main`, the section that matches the run mode, or programmatically. # HOOK_TYPES = Set.new([:on_define_and_write, :on_initialize_and_write, :on_write_only]).freeze def self.available_call_hook_values HOOK_TYPES.to_a end # Registers a hook to be called later based on the type of hook specified in `value`. # # @param value [Symbol] One of {HOOK_TYPES} def call_hook=(value) if value.nil? # TRANSLATORS ':%{name}', ':call_hook', and ':on_write_only' should not be translated Puppet.warning _("Setting :%{name} :call_hook is nil, defaulting to :on_write_only") % { name: name } value = :on_write_only end unless HOOK_TYPES.include?(value) # TRANSLATORS 'call_hook' is a Puppet option name and should not be translated raise ArgumentError, _("Invalid option %{value} for call_hook") % { value: value } end @call_hook = value end # @see {HOOK_TYPES} def call_hook_on_define? call_hook == :on_define_and_write end # @see {HOOK_TYPES} def call_hook_on_initialize? call_hook == :on_initialize_and_write end # get the arguments in getopt format def getopt_args if short [["--#{name}", "-#{short}", GetoptLong::REQUIRED_ARGUMENT]] else [["--#{name}", GetoptLong::REQUIRED_ARGUMENT]] end end # get the arguments in OptionParser format def optparse_args if short ["--#{name}", "-#{short}", desc, :REQUIRED] else ["--#{name}", desc, :REQUIRED] end end def hook=(block) @has_hook = true meta_def :handle, &block end def has_hook? @has_hook end # Create the new element. Pretty much just sets the name. def initialize(args = {}) @settings = args.delete(:settings) unless @settings raise ArgumentError, "You must refer to a settings object" end # explicitly set name prior to calling other param= methods to provide meaningful feedback during # other warnings @name = args[:name] if args.include? :name # set the default value for call_hook @call_hook = :on_write_only if args[:hook] and !(args[:call_hook]) @has_hook = false if args[:call_hook] and !(args[:hook]) # TRANSLATORS ':call_hook' and ':hook' are specific setting names and should not be translated raise ArgumentError, _("Cannot reference :call_hook for :%{name} if no :hook is defined") % { name: @name } end args.each do |param, value| method = param.to_s + "=" unless respond_to? method raise ArgumentError, _("%{class_name} (setting '%{setting}') does not accept %{parameter}") % { class_name: self.class, setting: args[:name], parameter: param } end send(method, value) end unless desc raise ArgumentError, _("You must provide a description for the %{class_name} config option") % { class_name: name } end end def iscreated @iscreated = true end def iscreated? @iscreated end # short name for the element def short=(value) raise ArgumentError, _("Short names can only be one character.") if value.to_s.length != 1 @short = value.to_s end def default(check_application_defaults_first = false) if @default.is_a? Proc # Give unit tests a chance to reevaluate the call by removing the instance variable unless instance_variable_defined?(:@evaluated_default) @evaluated_default = @default.call end default_value = @evaluated_default else default_value = @default end return default_value unless check_application_defaults_first @settings.value(name, :application_defaults, true) || default_value end # Convert the object to a config statement. def to_config require_relative '../../puppet/util/docs' # Scrub any funky indentation; comment out description. str = Puppet::Util::Docs.scrub(@desc).gsub(/^/, "# ") + "\n" # Add in a statement about the default. str << "# The default value is '#{default(true)}'.\n" if default(true) # If the value has not been overridden, then print it out commented # and unconverted, so it's clear that that's the default and how it # works. value = @settings.value(name) if value != @default line = "#{@name} = #{value}" else line = "# #{@name} = #{@default}" end str << (line + "\n") # Indent str.gsub(/^/, " ") end # @param bypass_interpolation [Boolean] Set this true to skip the # interpolation step, returning the raw setting value. Defaults to false. # @return [String] Retrieves the value, or if it's not set, retrieves the default. # @api public def value(bypass_interpolation = false) @settings.value(name, nil, bypass_interpolation) end # Modify the value when it is first evaluated def munge(value) value end # Print the value for the user in a config compatible format def print(value) munge(value) end def set_meta(meta) Puppet.notice("#{name} does not support meta data. Ignoring.") end def deprecated=(deprecation) unless [:completely, :allowed_on_commandline].include?(deprecation) # TRANSLATORS 'deprecated' is a Puppet setting and ':completely' and ':allowed_on_commandline' are possible values and should not be translated raise ArgumentError, _("Unsupported deprecated value '%{deprecation}'.") % { deprecation: deprecation } + ' ' + _("Supported values for deprecated are ':completely' or ':allowed_on_commandline'") end @deprecated = deprecation end def deprecated? !!@deprecated end # True if we should raise a deprecation_warning if the setting is submitted # on the commandline or is set in puppet.conf. def completely_deprecated? @deprecated == :completely end # True if we should raise a deprecation_warning if the setting is found in # puppet.conf, but not if the user sets it on the commandline def allowed_on_commandline? @deprecated == :allowed_on_commandline end def inspect %Q(<#{self.class}:#{object_id} @name="#{@name}" @section="#{@section}" @default="#{@default}" @call_hook="#{@call_hook}">) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/file_or_directory_setting.rb
lib/puppet/settings/file_or_directory_setting.rb
# frozen_string_literal: true class Puppet::Settings::FileOrDirectorySetting < Puppet::Settings::FileSetting def type if Puppet::FileSystem.directory?(value) || @path_ends_with_slash :directory else :file end end # Overrides munge to be able to read the un-munged value (the FileSetting.munch removes trailing slash) # def munge(value) if value.is_a?(String) && value =~ %r{[\\/]$} @path_ends_with_slash = true end super end # @api private # # @param option [String] Extra file operation mode information to use # (defaults to read-only mode 'r') # This is the standard mechanism Ruby uses in the IO class, and therefore # encoding may be explicitly like fmode : encoding or fmode : "BOM|UTF-*" # for example, a:ASCII or w+:UTF-8 def open_file(filename, option = 'r', &block) if type == :file super else controlled_access do |mode| Puppet::FileSystem.open(filename, mode, option, &block) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/array_setting.rb
lib/puppet/settings/array_setting.rb
# frozen_string_literal: true class Puppet::Settings::ArraySetting < Puppet::Settings::BaseSetting def type :array end def munge(value) case value when String value.split(/\s*,\s*/) when Array value else raise ArgumentError, _("Expected an Array or String, got a %{klass}") % { klass: value.class } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/environment_conf.rb
lib/puppet/settings/environment_conf.rb
# frozen_string_literal: true # Configuration settings for a single directory Environment. # @api private class Puppet::Settings::EnvironmentConf ENVIRONMENT_CONF_ONLY_SETTINGS = [:modulepath, :manifest, :config_version].freeze VALID_SETTINGS = (ENVIRONMENT_CONF_ONLY_SETTINGS + [:environment_timeout, :environment_data_provider, :static_catalogs, :rich_data]).freeze # Given a path to a directory environment, attempts to load and parse an # environment.conf in ini format, and return an EnvironmentConf instance. # # An environment.conf is optional, so if the file itself is missing, or # empty, an EnvironmentConf with default values will be returned. # # @note logs warnings if the environment.conf contains any ini sections, # or has settings other than the three handled for directory environments # (:manifest, :modulepath, :config_version) # # @param path_to_env [String] path to the directory environment # @param global_module_path [Array<String>] the installation's base modulepath # setting, appended to default environment modulepaths # @return [EnvironmentConf] the parsed EnvironmentConf object def self.load_from(path_to_env, global_module_path) path_to_env = File.expand_path(path_to_env) conf_file = File.join(path_to_env, 'environment.conf') begin config = Puppet.settings.parse_file(conf_file) validate(conf_file, config) section = config.sections[:main] rescue Errno::ENOENT # environment.conf is an optional file Puppet.debug { "Path to #{path_to_env} does not exist, using default environment.conf" } end new(path_to_env, section, global_module_path) end # Provides a configuration object tied directly to the passed environment. # Configuration values are exactly those returned by the environment object, # without interpolation. This is a special case for the default configured # environment returned by the Puppet::Environments::StaticPrivate loader. def self.static_for(environment, environment_timeout = 0, static_catalogs = false, rich_data = false) Static.new(environment, environment_timeout, static_catalogs, nil, rich_data) end attr_reader :section, :path_to_env, :global_modulepath # Create through EnvironmentConf.load_from() def initialize(path_to_env, section, global_module_path) @path_to_env = path_to_env @section = section @global_module_path = global_module_path end def manifest puppet_conf_manifest = Pathname.new(Puppet.settings.value(:default_manifest)) disable_per_environment_manifest = Puppet.settings.value(:disable_per_environment_manifest) fallback_manifest_directory = if puppet_conf_manifest.absolute? puppet_conf_manifest.to_s else File.join(@path_to_env, puppet_conf_manifest.to_s) end if disable_per_environment_manifest environment_conf_manifest = absolute(raw_setting(:manifest)) if environment_conf_manifest && fallback_manifest_directory != environment_conf_manifest # TRANSLATORS 'disable_per_environment_manifest' is a setting and 'environment.conf' is a file name and should not be translated message = _("The 'disable_per_environment_manifest' setting is true, but the environment located at %{path_to_env} has a manifest setting in its environment.conf of '%{environment_conf}' which does not match the default_manifest setting '%{puppet_conf}'.") % { path_to_env: @path_to_env, environment_conf: environment_conf_manifest, puppet_conf: puppet_conf_manifest } message += ' ' + _("If this environment is expecting to find modules in '%{environment_conf}', they will not be available!") % { environment_conf: environment_conf_manifest } Puppet.err(message) end fallback_manifest_directory.to_s else get_setting(:manifest, fallback_manifest_directory) do |manifest| absolute(manifest) end end end def environment_timeout # gen env specific config or use the default value get_setting(:environment_timeout, Puppet.settings.value(:environment_timeout)) do |ttl| # munges the string form statically without really needed the settings system, only # its ability to munge "4s, 3m, 5d, and 'unlimited' into seconds - if already munged into # numeric form, the TTLSetting handles that. Puppet::Settings::TTLSetting.munge(ttl, 'environment_timeout') end end def environment_data_provider get_setting(:environment_data_provider, Puppet.settings.value(:environment_data_provider)) do |value| value end end def modulepath default_modulepath = [File.join(@path_to_env, "modules")] + @global_module_path get_setting(:modulepath, default_modulepath) do |modulepath| path = modulepath.is_a?(String) ? modulepath.split(File::PATH_SEPARATOR) : modulepath path.map { |p| expand_glob(absolute(p)) }.flatten.join(File::PATH_SEPARATOR) end end def rich_data get_setting(:rich_data, Puppet.settings.value(:rich_data)) do |value| value end end def static_catalogs get_setting(:static_catalogs, Puppet.settings.value(:static_catalogs)) do |value| value end end def config_version get_setting(:config_version) do |config_version| absolute(config_version) end end def raw_setting(setting_name) setting = section.setting(setting_name) if section setting.value if setting end private def self.validate(path_to_conf_file, config) valid = true section_keys = config.sections.keys main = config.sections[:main] if section_keys.size > 1 # warn once per config file path Puppet.warn_once( :invalid_settings_section, "EnvironmentConf-section:#{path_to_conf_file}", _("Invalid sections in environment.conf at '%{path_to_conf_file}'. Environment conf may not have sections. The following sections are being ignored: '%{sections}'") % { path_to_conf_file: path_to_conf_file, sections: (section_keys - [:main]).join(',') } ) valid = false end extraneous_settings = main.settings.map(&:name) - VALID_SETTINGS unless extraneous_settings.empty? # warn once per config file path Puppet.warn_once( :invalid_settings, "EnvironmentConf-settings:#{path_to_conf_file}", _("Invalid settings in environment.conf at '%{path_to_conf_file}'. The following unknown setting(s) are being ignored: %{ignored_settings}") % { path_to_conf_file: path_to_conf_file, ignored_settings: extraneous_settings.join(', ') } ) valid = false end valid end private_class_method :validate def get_setting(setting_name, default = nil) value = raw_setting(setting_name) value = default if value.nil? yield value end def expand_glob(path) return nil if path.nil? if path =~ /[*?\[{]/ Dir.glob(path) else path end end def absolute(path) return nil if path.nil? if path =~ /^\$/ # Path begins with $something interpolatable path else Puppet::FileSystem.expand_path(path, @path_to_env) end end # Models configuration for an environment that is not loaded from a directory. # # @api private class Static attr_reader :environment_timeout attr_reader :environment_data_provider attr_reader :rich_data attr_reader :static_catalogs def initialize(environment, environment_timeout, static_catalogs, environment_data_provider = nil, rich_data = false) @environment = environment @environment_timeout = environment_timeout @static_catalogs = static_catalogs @environment_data_provider = environment_data_provider @rich_data = rich_data end def path_to_env nil end def manifest @environment.manifest end def modulepath @environment.modulepath.join(File::PATH_SEPARATOR) end def config_version @environment.config_version end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/config_file.rb
lib/puppet/settings/config_file.rb
# frozen_string_literal: true require_relative '../../puppet/settings/ini_file' ## # @api private # # Parses puppet configuration files # class Puppet::Settings::ConfigFile ## # @param value_converter [Proc] a function that will convert strings into ruby types def initialize(value_converter) @value_converter = value_converter end # @param file [String, File] pointer to the file whose text we are parsing # @param text [String] the actual text of the inifile to be parsed # @param allowed_section_names [Array] an optional array of accepted section # names; if this list is non-empty, sections outside of it will raise an # error. # @return A Struct with a +sections+ array representing each configuration section def parse_file(file, text, allowed_section_names = []) result = Conf.new unless allowed_section_names.empty? allowed_section_names << 'main' unless allowed_section_names.include?('main') end ini = Puppet::Settings::IniFile.parse(text.encode(Encoding::UTF_8)) unique_sections_in(ini, file, allowed_section_names).each do |section_name| section = Section.new(section_name.to_sym) result.with_section(section) ini.lines_in(section_name).each do |line| if line.is_a?(Puppet::Settings::IniFile::SettingLine) parse_setting(line, section) elsif line.text !~ /^\s*#|^\s*$/ raise Puppet::Settings::ParseError.new(_("Could not match line %{text}") % { text: line.text }, file, line.line_number) end end end result end Conf = Struct.new(:sections) do def initialize super({}) end def with_section(section) sections[section.name] = section self end end Section = Struct.new(:name, :settings) do def initialize(name) super(name, []) end def with_setting(name, value, meta) settings << Setting.new(name, value, meta) self end def setting(name) settings.find { |setting| setting.name == name } end end Setting = Struct.new(:name, :value, :meta) do def has_metadata? meta != NO_META end end Meta = Struct.new(:owner, :group, :mode) NO_META = Meta.new(nil, nil, nil) private def unique_sections_in(ini, file, allowed_section_names) ini.section_lines.collect do |section| if !allowed_section_names.empty? && !allowed_section_names.include?(section.name) error_location_str = Puppet::Util::Errors.error_location(file, section.line_number) message = _("Illegal section '%{name}' in config file at %{error_location}.") % { name: section.name, error_location: error_location_str } # TRANSLATORS 'puppet.conf' is the name of the puppet configuration file and should not be translated. message += ' ' + _("The only valid puppet.conf sections are: [%{allowed_sections_list}].") % { allowed_sections_list: allowed_section_names.join(", ") } message += ' ' + _("Please use the directory environments feature to specify environments.") message += ' ' + _("(See https://puppet.com/docs/puppet/latest/environments_about.html)") raise(Puppet::Error, message) end section.name end.uniq end def parse_setting(setting, section) var = setting.name.intern value = @value_converter[setting.value] # Check to see if this is a file argument and it has extra options begin options = extract_fileinfo(value) if value.is_a?(String) if options section.with_setting(var, options[:value], Meta.new(options[:owner], options[:group], options[:mode])) else section.with_setting(var, value, NO_META) end rescue Puppet::Error => detail raise Puppet::Settings::ParseError.new(detail.message, file, setting.line_number, detail) end end def empty_section { :_meta => {} } end def extract_fileinfo(string) result = {} value = string.sub(/\{\s*([^}]+)\s*\}/) do params = ::Regexp.last_match(1) params.split(/\s*,\s*/).each do |str| if str =~ /^\s*(\w+)\s*=\s*(\w+)\s*$/ param = ::Regexp.last_match(1).intern value = ::Regexp.last_match(2) result[param] = value unless [:owner, :mode, :group].include?(param) raise ArgumentError, _("Invalid file option '%{parameter}'") % { parameter: param } end if param == :mode and value !~ /^\d+$/ raise ArgumentError, _("File modes must be numbers") end else raise ArgumentError, _("Could not parse '%{string}'") % { string: string } end end '' end result[:value] = value.sub(/\s*$/, '') result end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/errors.rb
lib/puppet/settings/errors.rb
# frozen_string_literal: true # Exceptions for the settings module require_relative '../../puppet/error' class Puppet::Settings class SettingsError < Puppet::Error; end class ValidationError < SettingsError; end class InterpolationError < SettingsError; end class ParseError < SettingsError include Puppet::ExternalFileError end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/directory_setting.rb
lib/puppet/settings/directory_setting.rb
# frozen_string_literal: true class Puppet::Settings::DirectorySetting < Puppet::Settings::FileSetting def type :directory end # @api private # # @param option [String] Extra file operation mode information to use # (defaults to read-only mode 'r') # This is the standard mechanism Ruby uses in the IO class, and therefore # encoding may be explicitly like fmode : encoding or fmode : "BOM|UTF-*" # for example, a:ASCII or w+:UTF-8 def open_file(filename, option = 'r', &block) controlled_access do |mode| Puppet::FileSystem.open(filename, mode, option, &block) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/terminus_setting.rb
lib/puppet/settings/terminus_setting.rb
# frozen_string_literal: true class Puppet::Settings::TerminusSetting < Puppet::Settings::BaseSetting def munge(value) case value when '', nil nil when String value.intern when Symbol value else raise Puppet::Settings::ValidationError, _("Invalid terminus setting: %{value}") % { value: value } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/boolean_setting.rb
lib/puppet/settings/boolean_setting.rb
# frozen_string_literal: true # A simple boolean. class Puppet::Settings::BooleanSetting < Puppet::Settings::BaseSetting # get the arguments in getopt format def getopt_args if short [["--#{name}", "-#{short}", GetoptLong::NO_ARGUMENT], ["--no-#{name}", GetoptLong::NO_ARGUMENT]] else [["--#{name}", GetoptLong::NO_ARGUMENT], ["--no-#{name}", GetoptLong::NO_ARGUMENT]] end end def optparse_args if short ["--[no-]#{name}", "-#{short}", desc, :NONE] else ["--[no-]#{name}", desc, :NONE] end end def munge(value) case value when true, "true"; true when false, "false"; false else raise Puppet::Settings::ValidationError, _("Invalid value '%{value}' for boolean parameter: %{name}") % { value: value.inspect, name: @name } end end def type :boolean end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/integer_setting.rb
lib/puppet/settings/integer_setting.rb
# frozen_string_literal: true class Puppet::Settings::IntegerSetting < Puppet::Settings::BaseSetting def munge(value) return value if value.is_a?(Integer) begin value = Integer(value) rescue ArgumentError, TypeError raise Puppet::Settings::ValidationError, _("Cannot convert '%{value}' to an integer for parameter: %{name}") % { value: value.inspect, name: @name } end value end def type :integer end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/string_setting.rb
lib/puppet/settings/string_setting.rb
# frozen_string_literal: true class Puppet::Settings::StringSetting < Puppet::Settings::BaseSetting def type :string end def validate(value) value.nil? or value.is_a?(String) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/http_extra_headers_setting.rb
lib/puppet/settings/http_extra_headers_setting.rb
# frozen_string_literal: true class Puppet::Settings::HttpExtraHeadersSetting < Puppet::Settings::BaseSetting def type :http_extra_headers end def munge(headers) return headers if headers.is_a?(Hash) headers = headers.split(/\s*,\s*/) if headers.is_a?(String) raise ArgumentError, _("Expected an Array, String, or Hash, got a %{klass}") % { klass: headers.class } unless headers.is_a?(Array) headers.map! { |header| case header when String header.split(':') when Array header else raise ArgumentError, _("Expected an Array or String, got a %{klass}") % { klass: header.class } end } end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/duration_setting.rb
lib/puppet/settings/duration_setting.rb
# frozen_string_literal: true # A setting that represents a span of time, and evaluates to an integer # number of seconds after being parsed class Puppet::Settings::DurationSetting < Puppet::Settings::BaseSetting # How we convert from various units to seconds. UNITMAP = { # 365 days isn't technically a year, but is sufficient for most purposes "y" => 365 * 24 * 60 * 60, "d" => 24 * 60 * 60, "h" => 60 * 60, "m" => 60, "s" => 1 } # A regex describing valid formats with groups for capturing the value and units FORMAT = /^(\d+)(y|d|h|m|s)?$/ def type :duration end # Convert the value to an integer, parsing numeric string with units if necessary. def munge(value) if value.is_a?(Integer) || value.nil? value elsif value.is_a?(String) and value =~ FORMAT ::Regexp.last_match(1).to_i * UNITMAP[::Regexp.last_match(2) || 's'] else raise Puppet::Settings::ValidationError, _("Invalid duration format '%{value}' for parameter: %{name}") % { value: value.inspect, name: @name } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/port_setting.rb
lib/puppet/settings/port_setting.rb
# frozen_string_literal: true class Puppet::Settings::PortSetting < Puppet::Settings::IntegerSetting def munge(value) value = super(value) if value < 0 || value > 65_535 raise Puppet::Settings::ValidationError, _("Value '%{value}' is not a valid port number for parameter: %{name}") % { value: value.inspect, name: @name } end value end def type :port end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/alias_setting.rb
lib/puppet/settings/alias_setting.rb
# frozen_string_literal: true class Puppet::Settings::AliasSetting attr_reader :name, :alias_name def initialize(args = {}) @name = args[:name] @alias_name = args[:alias_for] @alias_for = Puppet.settings.setting(alias_name) end def optparse_args args = @alias_for.optparse_args args[0].gsub!(alias_name.to_s, name.to_s) args end def getopt_args args = @alias_for.getopt_args args[0].gsub!(alias_name.to_s, name.to_s) args end def type :alias end def method_missing(method, *args) alias_for.send(method, *args) rescue => e Puppet.log_exception(self.class, e.message) end private attr_reader :alias_for end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/ini_file.rb
lib/puppet/settings/ini_file.rb
# frozen_string_literal: true # @api private class Puppet::Settings::IniFile DEFAULT_SECTION_NAME = "main" def self.update(config_fh, &block) config = parse(config_fh) manipulator = Manipulator.new(config) yield manipulator config.write(config_fh) end def self.parse(config_fh) config = new([DefaultSection.new]) config_fh.each_line do |line| case line.chomp when /^(\s*)\[([[:word:]]+)\](\s*)$/ config.append(SectionLine.new(::Regexp.last_match(1), ::Regexp.last_match(2), ::Regexp.last_match(3))) when /^(\s*)([[:word:]]+)(\s*=\s*)(.*?)(\s*)$/ config.append(SettingLine.new(::Regexp.last_match(1), ::Regexp.last_match(2), ::Regexp.last_match(3), ::Regexp.last_match(4), ::Regexp.last_match(5))) else config.append(Line.new(line)) end end config end def initialize(lines = []) @lines = lines end def append(line) line.previous = @lines.last @lines << line end def delete(section, name) delete_offset = @lines.index(setting(section, name)) next_offset = delete_offset + 1 if next_offset < @lines.length @lines[next_offset].previous = @lines[delete_offset].previous end @lines.delete_at(delete_offset) end def insert_after(line, new_line) new_line.previous = line insertion_point = @lines.index(line) @lines.insert(insertion_point + 1, new_line) if @lines.length > insertion_point + 2 @lines[insertion_point + 2].previous = new_line end end def section_lines @lines.select { |line| line.is_a?(SectionLine) } end def section_line(name) section_lines.find { |section| section.name == name } end def setting(section, name) settings_in(lines_in(section)).find do |line| line.name == name end end def lines_in(section_name) section_lines = [] current_section_name = DEFAULT_SECTION_NAME @lines.each do |line| if line.is_a?(SectionLine) current_section_name = line.name elsif current_section_name == section_name section_lines << line end end section_lines end def settings_in(lines) lines.select { |line| line.is_a?(SettingLine) } end def settings_exist_in_default_section? lines_in(DEFAULT_SECTION_NAME).any? { |line| line.is_a?(SettingLine) } end def section_exists_with_default_section_name? section_lines.any? do |section| !section.is_a?(DefaultSection) && section.name == DEFAULT_SECTION_NAME end end def set_default_section_write_sectionline(value) index = @lines.find_index { |line| line.is_a?(DefaultSection) } if index @lines[index].write_sectionline = true end end def write(fh) # If no real section line for the default section exists, configure the # DefaultSection object to write its section line. (DefaultSection objects # don't write the section line unless explicitly configured to do so) if settings_exist_in_default_section? && !section_exists_with_default_section_name? set_default_section_write_sectionline(true) end fh.truncate(0) fh.rewind @lines.each do |line| line.write(fh) end fh.flush end class Manipulator def initialize(config) @config = config end def set(section, name, value) setting = @config.setting(section, name) if setting setting.value = value else add_setting(section, name, value) end end def delete(section_name, name) setting = @config.setting(section_name, name) if setting @config.delete(section_name, name) setting.to_s.chomp end end private def add_setting(section_name, name, value) section = @config.section_line(section_name) if section.nil? previous_line = SectionLine.new("", section_name, "") @config.append(previous_line) else previous_line = @config.settings_in(@config.lines_in(section_name)).last || section end @config.insert_after(previous_line, SettingLine.new("", name, " = ", value, "")) end end module LineNumber attr_accessor :previous def line_number line = 0 previous_line = previous while previous_line line += 1 previous_line = previous_line.previous end line end end Line = Struct.new(:text) do include LineNumber def to_s text end def write(fh) fh.puts(to_s) end end SettingLine = Struct.new(:prefix, :name, :infix, :value, :suffix) do include LineNumber def to_s "#{prefix}#{name}#{infix}#{value}#{suffix}" end def write(fh) fh.puts(to_s) end def ==(other) super(other) && line_number == other.line_number end end SectionLine = Struct.new(:prefix, :name, :suffix) do include LineNumber def to_s "#{prefix}[#{name}]#{suffix}" end def write(fh) fh.puts(to_s) end end class DefaultSection < SectionLine attr_accessor :write_sectionline def initialize @write_sectionline = false super("", DEFAULT_SECTION_NAME, "") end def write(fh) if @write_sectionline super(fh) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/ttl_setting.rb
lib/puppet/settings/ttl_setting.rb
# frozen_string_literal: true # A setting that represents a span of time to live, and evaluates to Numeric # seconds to live where 0 means shortest possible time to live, a positive numeric value means time # to live in seconds, and the symbolic entry 'unlimited' is an infinite amount of time. # class Puppet::Settings::TTLSetting < Puppet::Settings::BaseSetting # How we convert from various units to seconds. UNITMAP = { # 365 days isn't technically a year, but is sufficient for most purposes "y" => 365 * 24 * 60 * 60, "d" => 24 * 60 * 60, "h" => 60 * 60, "m" => 60, "s" => 1 } # A regex describing valid formats with groups for capturing the value and units FORMAT = /^(\d+)(y|d|h|m|s)?$/ def type :ttl end # Convert the value to Numeric, parsing numeric string with units if necessary. def munge(value) self.class.munge(value, @name) end def print(value) val = munge(value) val == Float::INFINITY ? 'unlimited' : val end # Convert the value to Numeric, parsing numeric string with units if necessary. def self.munge(value, param_name) if value.is_a?(Numeric) if value < 0 raise Puppet::Settings::ValidationError, _("Invalid negative 'time to live' %{value} - did you mean 'unlimited'?") % { value: value.inspect } end value elsif value == 'unlimited' Float::INFINITY elsif value.is_a?(String) and value =~ FORMAT ::Regexp.last_match(1).to_i * UNITMAP[::Regexp.last_match(2) || 's'] else raise Puppet::Settings::ValidationError, _("Invalid 'time to live' format '%{value}' for parameter: %{param_name}") % { value: value.inspect, param_name: param_name } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/value_translator.rb
lib/puppet/settings/value_translator.rb
# frozen_string_literal: true # Convert arguments into booleans, integers, or whatever. class Puppet::Settings::ValueTranslator def [](value) # Handle different data types correctly case value when /^false$/i; false when /^true$/i; true when true; true when false; false else value.gsub(/^["']|["']$/, '').sub(/\s+$/, '') end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/symbolic_enum_setting.rb
lib/puppet/settings/symbolic_enum_setting.rb
# frozen_string_literal: true class Puppet::Settings::SymbolicEnumSetting < Puppet::Settings::BaseSetting attr_accessor :values def type :symbolic_enum end def munge(value) sym = value.to_sym if values.include?(sym) sym else raise Puppet::Settings::ValidationError, _("Invalid value '%{value}' for parameter %{name}. Allowed values are '%{allowed_values}'") % { value: value, name: @name, allowed_values: values.join("', '") } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/certificate_revocation_setting.rb
lib/puppet/settings/certificate_revocation_setting.rb
# frozen_string_literal: true require_relative '../../puppet/settings/base_setting' class Puppet::Settings::CertificateRevocationSetting < Puppet::Settings::BaseSetting def type :certificate_revocation end def munge(value) case value when 'chain', 'true', TrueClass :chain when 'leaf' :leaf when 'false', FalseClass, NilClass false else raise Puppet::Settings::ValidationError, _("Invalid certificate revocation value %{value}: must be one of 'true', 'chain', 'leaf', or 'false'") % { value: value } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/server_list_setting.rb
lib/puppet/settings/server_list_setting.rb
# frozen_string_literal: true class Puppet::Settings::ServerListSetting < Puppet::Settings::ArraySetting def type :server_list end def print(value) if value.is_a?(Array) # turn into a string value.map { |item| item.join(":") }.join(",") else value end end def munge(value) servers = super servers.map! { |server| case server when String server.split(':') when Array server else raise ArgumentError, _("Expected an Array of String, got a %{klass}") % { klass: value.class } end } end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/path_setting.rb
lib/puppet/settings/path_setting.rb
# frozen_string_literal: true class Puppet::Settings::PathSetting < Puppet::Settings::StringSetting def munge(value) if value.is_a?(String) value = value.split(File::PATH_SEPARATOR).map { |d| File.expand_path(d) }.join(File::PATH_SEPARATOR) end value end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/autosign_setting.rb
lib/puppet/settings/autosign_setting.rb
# frozen_string_literal: true require_relative '../../puppet/settings/base_setting' # A specialization of the file setting to allow boolean values. # # The autosign value can be either a boolean or a file path, and if the setting # is a file path then it may have a owner/group/mode specified. # # @api private class Puppet::Settings::AutosignSetting < Puppet::Settings::FileSetting def munge(value) if ['true', true].include? value true elsif ['false', false, nil].include? value false elsif Puppet::Util.absolute_path?(value) value else raise Puppet::Settings::ValidationError, _("Invalid autosign value %{value}: must be 'true'/'false' or an absolute path") % { value: value } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/settings/file_setting.rb
lib/puppet/settings/file_setting.rb
# frozen_string_literal: true # A file. class Puppet::Settings::FileSetting < Puppet::Settings::StringSetting class SettingError < StandardError; end # An unspecified user or group # # @api private class Unspecified def value nil end end # A "root" user or group # # @api private class Root def value "root" end end # A "service" user or group that picks up values from settings when the # referenced user or group is safe to use (it exists or will be created), and # uses the given fallback value when not safe. # # @api private class Service # @param name [Symbol] the name of the setting to use as the service value # @param fallback [String, nil] the value to use when the service value cannot be used # @param settings [Puppet::Settings] the puppet settings object # @param available_method [Symbol] the name of the method to call on # settings to determine if the value in settings is available on the system # def initialize(name, fallback, settings, available_method) @settings = settings @available_method = available_method @name = name @fallback = fallback end def value if safe_to_use_settings_value? @settings[@name] else @fallback end end private def safe_to_use_settings_value? @settings[:mkusers] or @settings.send(@available_method) end end attr_accessor :mode def initialize(args) @group = Unspecified.new @owner = Unspecified.new super(args) end # @param value [String] the group to use on the created file (can only be "root" or "service") # @api public def group=(value) @group = case value when "root" Root.new when "service" # Group falls back to `nil` because we cannot assume that a "root" group exists. # Some systems have root group, others have wheel, others have something else. Service.new(:group, nil, @settings, :service_group_available?) else unknown_value(':group', value) end end # @param value [String] the owner to use on the created file (can only be "root" or "service") # @api public def owner=(value) @owner = case value when "root" Root.new when "service" Service.new(:user, "root", @settings, :service_user_available?) else unknown_value(':owner', value) end end # @return [String, nil] the name of the group to use for the file or nil if the group should not be managed # @api public def group @group.value end # @return [String, nil] the name of the user to use for the file or nil if the user should not be managed # @api public def owner @owner.value end def set_meta(meta) self.owner = meta.owner if meta.owner self.group = meta.group if meta.group self.mode = meta.mode if meta.mode end def munge(value) if value.is_a?(String) and value != ':memory:' # for sqlite3 in-memory tests value = File.expand_path(value) end value end def type :file end # Turn our setting thing into a Puppet::Resource instance. def to_resource type = self.type return nil unless type path = value return nil unless path.is_a?(String) # Make sure the paths are fully qualified. path = File.expand_path(path) return nil unless type == :directory || Puppet::FileSystem.exist?(path) return nil if path =~ %r{^/dev} || path =~ %r{^[A-Z]:/dev}i resource = Puppet::Resource.new(:file, path) if Puppet[:manage_internal_file_permissions] if mode # This ends up mimicking the munge method of the mode # parameter to make sure that we're always passing the string # version of the octal number. If we were setting the # 'should' value for mode rather than the 'is', then the munge # method would be called for us automatically. Normally, one # wouldn't need to call the munge method manually, since # 'should' gets set by the provider and it should be able to # provide the data in the appropriate format. mode = self.mode mode = mode.to_i(8) if mode.is_a?(String) mode = mode.to_s(8) resource[:mode] = mode end # REMIND fails on Windows because chown/chgrp functionality not supported yet if Puppet.features.root? and !Puppet::Util::Platform.windows? resource[:owner] = owner if owner resource[:group] = group if group end end resource[:ensure] = type resource[:loglevel] = :debug resource[:links] = :follow resource[:backup] = false resource.tag(section, name, "settings") resource end # @api private # @param option [String] Extra file operation mode information to use # (defaults to read-only mode 'r') # This is the standard mechanism Ruby uses in the IO class, and therefore # encoding may be explicitly like fmode : encoding or fmode : "BOM|UTF-*" # for example, a:ASCII or w+:UTF-8 def exclusive_open(option = 'r', &block) controlled_access do |mode| Puppet::FileSystem.exclusive_open(file(), mode, option, &block) end end # @api private # @param option [String] Extra file operation mode information to use # (defaults to read-only mode 'r') # This is the standard mechanism Ruby uses in the IO class, and therefore # encoding may be explicitly like fmode : encoding or fmode : "BOM|UTF-*" # for example, a:ASCII or w+:UTF-8 def open(option = 'r', &block) controlled_access do |mode| Puppet::FileSystem.open(file, mode, option, &block) end end private def file Puppet::FileSystem.pathname(value) end def unknown_value(parameter, value) raise SettingError, _("The %{parameter} parameter for the setting '%{name}' must be either 'root' or 'service', not '%{value}'") % { parameter: parameter, name: name, value: value } end def controlled_access(&block) chown = nil if Puppet.features.root? chown = [owner, group] else chown = [nil, nil] end Puppet::Util::SUIDManager.asuser(*chown) do # Update the umask to make non-executable files Puppet::Util.withumask(File.umask ^ 0o111) do yielded_value = case mode when String mode.to_i(8) when NilClass 0o640 else mode end yield yielded_value end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/forge/repository.rb
lib/puppet/forge/repository.rb
# frozen_string_literal: true require_relative '../../puppet/ssl/openssl_loader' require 'digest/sha1' require 'uri' require_relative '../../puppet/forge' require_relative '../../puppet/forge/errors' require_relative '../../puppet/network/http' class Puppet::Forge # = Repository # # This class is a file for accessing remote repositories with modules. class Repository include Puppet::Forge::Errors attr_reader :uri, :cache # Instantiate a new repository instance rooted at the +url+. # The library will report +for_agent+ in the User-Agent to the repository. def initialize(host, for_agent) @host = host @agent = for_agent @cache = Cache.new(self) @uri = URI.parse(host) ssl_provider = Puppet::SSL::SSLProvider.new @ssl_context = ssl_provider.create_system_context(cacerts: []) end # Return a Net::HTTPResponse read for this +path+. def make_http_request(path, io = nil) raise ArgumentError, "Path must start with forward slash" unless path.start_with?('/') begin str = @uri.to_s str.chomp!('/') str += Puppet::Util.uri_encode(path) uri = URI(str) headers = { "User-Agent" => user_agent } if forge_authorization uri.user = nil uri.password = nil headers["Authorization"] = forge_authorization end http = Puppet.runtime[:http] response = http.get(uri, headers: headers, options: { ssl_context: @ssl_context }) io.write(response.body) if io.respond_to?(:write) response rescue Puppet::SSL::CertVerifyError => e raise SSLVerifyError.new(:uri => @uri.to_s, :original => e.cause) rescue => e raise CommunicationError.new(:uri => @uri.to_s, :original => e) end end def forge_authorization if Puppet[:forge_authorization] Puppet[:forge_authorization] elsif Puppet.features.pe_license? PELicense.load_license_key.authorization_token end end # Return the local file name containing the data downloaded from the # repository at +release+ (e.g. "myuser-mymodule"). def retrieve(release) path = @host.chomp('/') + release cache.retrieve(path) end # Return the URI string for this repository. def to_s "#<#{self.class} #{@host}>" end # Return the cache key for this repository, this a hashed string based on # the URI. def cache_key @cache_key ||= [ @host.to_s.gsub(/[^[:alnum:]]+/, '_').sub(/_$/, ''), Digest::SHA1.hexdigest(@host.to_s) ].join('-').freeze end private def user_agent @user_agent ||= [ @agent, Puppet[:http_user_agent] ].join(' ').freeze end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/forge/errors.rb
lib/puppet/forge/errors.rb
# frozen_string_literal: true require_relative '../../puppet/util/json' require_relative '../../puppet/error' require_relative '../../puppet/forge' # Puppet::Forge specific exceptions module Puppet::Forge::Errors # This exception is the parent for all Forge API errors class ForgeError < Puppet::Error # This is normally set by the child class, but if it is not this will # fall back to displaying the message as a multiline. # # @return [String] the multiline version of the error message def multiline message end end # This exception is raised when there is an SSL verification error when # communicating with the forge. class SSLVerifyError < ForgeError # @option options [String] :uri The URI that failed # @option options [String] :original the original exception def initialize(options) @uri = options[:uri] original = options[:original] super(_("Unable to verify the SSL certificate at %{uri}") % { uri: @uri }, original) end # Return a multiline version of the error message # # @return [String] the multiline version of the error message def multiline message = [] message << _('Could not connect via HTTPS to %{uri}') % { uri: @uri } message << _(' Unable to verify the SSL certificate') message << _(' The certificate may not be signed by a valid CA') message << _(' The CA bundle included with OpenSSL may not be valid or up to date') message.join("\n") end end # This exception is raised when there is a communication error when connecting # to the forge class CommunicationError < ForgeError # @option options [String] :uri The URI that failed # @option options [String] :original the original exception def initialize(options) @uri = options[:uri] original = options[:original] @detail = original.message message = _("Unable to connect to the server at %{uri}. Detail: %{detail}.") % { uri: @uri, detail: @detail } super(message, original) end # Return a multiline version of the error message # # @return [String] the multiline version of the error message def multiline message = [] message << _('Could not connect to %{uri}') % { uri: @uri } message << _(' There was a network communications problem') message << _(" The error we caught said '%{detail}'") % { detail: @detail } message << _(' Check your network connection and try again') message.join("\n") end end # This exception is raised when there is a bad HTTP response from the forge # and optionally a message in the response. class ResponseError < ForgeError # @option options [String] :uri The URI that failed # @option options [String] :input The user's input (e.g. module name) # @option options [String] :message Error from the API response (optional) # @option options [Puppet::HTTP::Response] :response The original HTTP response def initialize(options) @uri = options[:uri] @message = options[:message] response = options[:response] @response = "#{response.code} #{response.reason.strip}" begin body = Puppet::Util::Json.load(response.body) if body['message'] @message ||= body['message'].strip end rescue Puppet::Util::Json::ParseError end message = if @message _("Request to Puppet Forge failed.") + ' ' + _("Detail: %{detail}.") % { detail: "#{@message} / #{@response}" } else _("Request to Puppet Forge failed.") + ' ' + _("Detail: %{detail}.") % { detail: @response } end super(message, original) end # Return a multiline version of the error message # # @return [String] the multiline version of the error message def multiline message = [] message << _('Request to Puppet Forge failed.') message << _(' The server being queried was %{uri}') % { uri: @uri } message << _(" The HTTP response we received was '%{response}'") % { response: @response } message << _(" The message we received said '%{message}'") % { message: @message } if @message message.join("\n") end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/forge/cache.rb
lib/puppet/forge/cache.rb
# frozen_string_literal: true require 'uri' require_relative '../../puppet/forge' class Puppet::Forge # = Cache # # Provides methods for reading files from local cache, filesystem or network. class Cache # Instantiate new cache for the +repository+ instance. def initialize(repository, options = {}) @repository = repository @options = options end # Return filename retrieved from +uri+ instance. Will download this file and # cache it if needed. # # TODO: Add checksum support. # TODO: Add error checking. def retrieve(url) (path + File.basename(url.to_s)).tap do |cached_file| uri = url.is_a?(::URI) ? url : ::URI.parse(url) unless cached_file.file? if uri.scheme == 'file' # CGI.unescape butchers Uris that are escaped properly FileUtils.cp(Puppet::Util.uri_unescape(uri.path), cached_file) else # TODO: Handle HTTPS; probably should use repository.contact data = read_retrieve(uri) cached_file.open('wb') { |f| f.write data } end end end end # Return contents of file at the given URI's +uri+. def read_retrieve(uri) uri.read end # Return Pathname for repository's cache directory, create it if needed. def path (self.class.base_path + @repository.cache_key).tap(&:mkpath) end # Return the base Pathname for all the caches. def self.base_path (Pathname(Puppet.settings[:module_working_dir]) + 'cache').cleanpath.tap do |o| o.mkpath unless o.exist? end end # Clean out all the caches. def self.clean base_path.rmtree if base_path.exist? end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/info_service/plan_information_service.rb
lib/puppet/info_service/plan_information_service.rb
# frozen_string_literal: true class Puppet::InfoService::PlanInformationService require_relative '../../puppet/module' def self.plans_per_environment(environment_name) # get the actual environment object, raise error if the named env doesn't exist env = Puppet.lookup(:environments).get!(environment_name) env.modules.map do |mod| mod.plans.map do |plan| { :module => { :name => plan.module.name }, :name => plan.name } end end.flatten end def self.plan_data(environment_name, module_name, plan_name) # raise EnvironmentNotFound if applicable Puppet.lookup(:environments).get!(environment_name) pup_module = Puppet::Module.find(module_name, environment_name) if pup_module.nil? raise Puppet::Module::MissingModule, _("Module %{module_name} not found in environment %{environment_name}.") % { module_name: module_name, environment_name: environment_name } end plan = pup_module.plans.find { |t| t.name == plan_name } if plan.nil? raise Puppet::Module::Plan::PlanNotFound.new(plan_name, module_name) end begin plan.validate { :metadata => plan.metadata, :files => plan.files } rescue Puppet::Module::Plan::Error => err { :metadata => nil, :files => [], :error => err.to_h } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/info_service/class_information_service.rb
lib/puppet/info_service/class_information_service.rb
# frozen_string_literal: true require_relative '../../puppet' require_relative '../../puppet/pops' require_relative '../../puppet/pops/evaluator/json_strict_literal_evaluator' class Puppet::InfoService::ClassInformationService def initialize @file_to_result = {} @parser = Puppet::Pops::Parser::EvaluatingParser.new() end def classes_per_environment(env_file_hash) # In this version of puppet there is only one way to parse manifests, as feature switches per environment # are added or removed, this logic needs to change to compute the result per environment with the correct # feature flags in effect. unless env_file_hash.is_a?(Hash) raise ArgumentError, _('Given argument must be a Hash') end result = {} # for each environment # for each file # if file already processed, use last result or error # env_file_hash.each do |env, files| env_result = result[env] = {} files.each do |f| env_result[f] = result_of(f) end end result end private def type_parser Puppet::Pops::Types::TypeParser.singleton end def literal_evaluator @@literal_evaluator ||= Puppet::Pops::Evaluator::JsonStrictLiteralEvaluator.new end def result_of(f) entry = @file_to_result[f] if entry.nil? @file_to_result[f] = entry = parse_file(f) end entry end def parse_file(f) return { :error => _("The file %{f} does not exist") % { f: f } } unless Puppet::FileSystem.exist?(f) begin parse_result = @parser.parse_file(f) { :classes => parse_result.definitions.select { |d| d.is_a?(Puppet::Pops::Model::HostClassDefinition) }.map do |d| { :name => d.name, :params => d.parameters.map { |p| extract_param(p) } } end } rescue StandardError => e { :error => e.message } end end def extract_param(p) extract_default(extract_type({ :name => p.name }, p), p) end def extract_type(structure, p) return structure if p.type_expr.nil? structure[:type] = typeexpr_to_string(p.name, p.type_expr) structure end def extract_default(structure, p) value_expr = p.value return structure if value_expr.nil? default_value = value_as_literal(value_expr) structure[:default_literal] = default_value unless default_value.nil? structure[:default_source] = extract_value_source(value_expr) structure end def typeexpr_to_string(name, type_expr) type_parser.interpret_any(type_expr, nil).to_s rescue Puppet::ParseError => e raise Puppet::Error, "The parameter '$#{name}' is invalid: #{e.message}", e.backtrace end def value_as_literal(value_expr) catch(:not_literal) do return literal_evaluator.literal(value_expr) end nil end # Extracts the source for the expression def extract_value_source(value_expr) value_expr.locator.extract_tree_text(value_expr) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/info_service/task_information_service.rb
lib/puppet/info_service/task_information_service.rb
# frozen_string_literal: true class Puppet::InfoService::TaskInformationService require_relative '../../puppet/module' def self.tasks_per_environment(environment_name) # get the actual environment object, raise error if the named env doesn't exist env = Puppet.lookup(:environments).get!(environment_name) env.modules.map do |mod| mod.tasks.map do |task| # If any task is malformed continue to list other tasks in module task.validate { :module => { :name => task.module.name }, :name => task.name, :metadata => task.metadata } rescue Puppet::Module::Task::Error => err Puppet.log_exception(err) nil end end.flatten.compact end def self.task_data(environment_name, module_name, task_name) # raise EnvironmentNotFound if applicable Puppet.lookup(:environments).get!(environment_name) pup_module = Puppet::Module.find(module_name, environment_name) if pup_module.nil? raise Puppet::Module::MissingModule, _("Module %{module_name} not found in environment %{environment_name}.") % { module_name: module_name, environment_name: environment_name } end task = pup_module.tasks.find { |t| t.name == task_name } if task.nil? raise Puppet::Module::Task::TaskNotFound.new(task_name, module_name) end begin task.validate { :metadata => task.metadata, :files => task.files } rescue Puppet::Module::Task::Error => err { :metadata => nil, :files => [], :error => err.to_h } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/metatype/manager.rb
lib/puppet/metatype/manager.rb
# frozen_string_literal: true require_relative '../../puppet' require_relative '../../puppet/util/classgen' require_relative '../../puppet/node/environment' # This module defines methods dealing with Type management. # This module gets included into the Puppet::Type class, it's just split out here for clarity. # @api public # module Puppet::MetaType module Manager include Puppet::Util::ClassGen # An implementation specific method that removes all type instances during testing. # @note Only use this method for testing purposes. # @api private # def allclear @types.each { |_name, type| type.clear } end # Clears any types that were used but absent when types were last loaded. # @note Used after each catalog compile when always_retry_plugins is false # @api private # def clear_misses unless @types.nil? @types.compact end end # Iterates over all already loaded Type subclasses. # @yield [t] a block receiving each type # @yieldparam t [Puppet::Type] each defined type # @yieldreturn [Object] the last returned object is also returned from this method # @return [Object] the last returned value from the block. def eachtype @types.each do |_name, type| # Only consider types that have names # if ! type.parameters.empty? or ! type.validproperties.empty? yield type # end end end # Loads all types. # @note Should only be used for purposes such as generating documentation as this is potentially a very # expensive operation. # @return [void] # def loadall typeloader.loadall(Puppet.lookup(:current_environment)) end # Defines a new type or redefines an existing type with the given name. # A convenience method on the form `new<name>` where name is the name of the type is also created. # (If this generated method happens to clash with an existing method, a warning is issued and the original # method is kept). # # @param name [String] the name of the type to create or redefine. # @param options [Hash] options passed on to {Puppet::Util::ClassGen#genclass} as the option `:attributes`. # @option options [Puppet::Type] # Puppet::Type. This option is not passed on as an attribute to genclass. # @yield [ ] a block evaluated in the context of the created class, thus allowing further detailing of # that class. # @return [Class<inherits Puppet::Type>] the created subclass # @see Puppet::Util::ClassGen.genclass # # @dsl type # @api public def newtype(name, options = {}, &block) @manager_lock.synchronize do # Handle backward compatibility unless options.is_a?(Hash) # TRANSLATORS 'Puppet::Type.newtype' should not be translated Puppet.warning(_("Puppet::Type.newtype(%{name}) now expects a hash as the second argument, not %{argument}") % { name: name, argument: options.inspect }) end # First make sure we don't have a method sitting around name = name.intern newmethod = "new#{name}" # Used for method manipulation. selfobj = singleton_class if @types.include?(name) if respond_to?(newmethod) # Remove the old newmethod selfobj.send(:remove_method, newmethod) end end # Then create the class. klass = genclass( name, :parent => Puppet::Type, :overwrite => true, :hash => @types, :attributes => options, &block ) # Now define a "new<type>" method for convenience. if respond_to? newmethod # Refuse to overwrite existing methods like 'newparam' or 'newtype'. # TRANSLATORS 'new%{method}' will become a method name, do not translate this string Puppet.warning(_("'new%{method}' method already exists; skipping") % { method: name.to_s }) else selfobj.send(:define_method, newmethod) do |*args| klass.new(*args) end end # If they've got all the necessary methods defined and they haven't # already added the property, then do so now. klass.ensurable if klass.ensurable? and !klass.validproperty?(:ensure) # Now set up autoload any providers that might exist for this type. klass.providerloader = Puppet::Util::Autoload.new(klass, "puppet/provider/#{klass.name}") # We have to load everything so that we can figure out the default provider. klass.providerloader.loadall(Puppet.lookup(:current_environment)) klass.providify unless klass.providers.empty? loc = block_given? ? block.source_location : nil uri = loc.nil? ? nil : URI("#{Puppet::Util.path_to_uri(loc[0])}?line=#{loc[1]}") Puppet::Pops::Loaders.register_runtime3_type(name, uri) klass end end # Removes an existing type. # @note Only use this for testing. # @api private def rmtype(name) # Then create the class. rmclass(name, :hash => @types) singleton_class.send(:remove_method, "new#{name}") if respond_to?("new#{name}") end # Returns a Type instance by name. # This will load the type if not already defined. # @param [String, Symbol] name of the wanted Type # @return [Puppet::Type, nil] the type or nil if the type was not defined and could not be loaded # def type(name) @manager_lock.synchronize do # Avoid loading if name obviously is not a type name if name.to_s.include?(':') return nil end # We are overwhelmingly symbols here, which usually match, so it is worth # having this special-case to return quickly. Like, 25K symbols vs. 300 # strings in this method. --daniel 2012-07-17 return @types[name] if @types.include? name # Try mangling the name, if it is a string. if name.is_a? String name = name.downcase.intern return @types[name] if @types.include? name end # Try loading the type. if typeloader.load(name, Puppet.lookup(:current_environment)) # TRANSLATORS 'puppet/type/%{name}' should not be translated Puppet.warning(_("Loaded puppet/type/%{name} but no class was created") % { name: name }) unless @types.include? name elsif !Puppet[:always_retry_plugins] # PUP-5482 - Only look for a type once if plugin retry is disabled @types[name] = nil end # ...and I guess that is that, eh. return @types[name] end end # Creates a loader for Puppet types. # Defaults to an instance of {Puppet::Util::Autoload} if no other auto loader has been set. # @return [Puppet::Util::Autoload] the loader to use. # @api private def typeloader unless defined?(@typeloader) @typeloader = Puppet::Util::Autoload.new(self, "puppet/type") end @typeloader end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parameter/path.rb
lib/puppet/parameter/path.rb
# frozen_string_literal: true require_relative '../../puppet/parameter' # This specialized {Puppet::Parameter} handles validation and munging of paths. # By default, a single path is accepted, and by calling {accept_arrays} it is possible to # allow an array of paths. # class Puppet::Parameter::Path < Puppet::Parameter # Specifies whether multiple paths are accepted or not. # @dsl type # def self.accept_arrays(bool = true) @accept_arrays = !!bool end def self.arrays? @accept_arrays end # Performs validation of the given paths. # If the concrete parameter defines a validation method, it may call this method to perform # path validation. # @raise [Puppet::Error] if this property is configured for single paths and an array is given # @raise [Puppet::Error] if a path is not an absolute path # @return [Array<String>] the given paths # def validate_path(paths) if paths.is_a?(Array) and !self.class.arrays? then fail _("%{name} only accepts a single path, not an array of paths") % { name: name } end fail(_("%{name} must be a fully qualified path") % { name: name }) unless Array(paths).all? { |path| absolute_path?(path) } paths end # This is the default implementation of the `validate` method. # It will be overridden if the validate option is used when defining the parameter. # @return [void] # def unsafe_validate(paths) validate_path(paths) end # This is the default implementation of `munge`. # If the concrete parameter defines a `munge` method, this default implementation will be overridden. # This default implementation does not perform any munging, it just checks the one/many paths # constraints. A derived implementation can perform this check as: # `paths.is_a?(Array) and ! self.class.arrays?` and raise a {Puppet::Error}. # @param paths [String, Array<String>] one of multiple paths # @return [String, Array<String>] the given paths # @raise [Puppet::Error] if the given paths does not comply with the on/many paths rule. def unsafe_munge(paths) if paths.is_a?(Array) and !self.class.arrays? then fail _("%{name} only accepts a single path, not an array of paths") % { name: name } end paths end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parameter/value.rb
lib/puppet/parameter/value.rb
# frozen_string_literal: true require_relative '../../puppet/parameter/value_collection' # Describes an acceptable value for a parameter or property. # An acceptable value is either specified as a literal value or a regular expression. # @note this class should be used via the api methods in {Puppet::Parameter} and {Puppet::Property} # @api private # class Puppet::Parameter::Value attr_reader :name, :options, :event attr_accessor :block, :method, :required_features, :invalidate_refreshes # Adds an alias for this value. # Makes the given _name_ be an alias for this acceptable value. # @param name [Symbol] the additional alias this value should be known as # @api private # def alias(name) @aliases << convert(name) end # @return [Array<Symbol>] Returns all aliases (or an empty array). # @api private # def aliases @aliases.dup end # Stores the event that our value generates, if it does so. # @api private # def event=(value) @event = convert(value) end # Initializes the instance with a literal accepted value, or a regular expression. # If anything else is passed, it is turned into a String, and then made into a Symbol. # @param name [Symbol, Regexp, Object] the value to accept, Symbol, a regular expression, or object to convert. # @api private # def initialize(name) if name.is_a?(Regexp) @name = name else # Convert to a string and then a symbol, so things like true/false # still show up as symbols. @name = convert(name) end @aliases = [] end # Checks if the given value matches the acceptance rules (literal value, regular expression, or one # of the aliases. # @api private # def match?(value) if regex? true if name =~ value.to_s else (name == convert(value) ? true : @aliases.include?(convert(value))) end end # @return [Boolean] whether the accepted value is a regular expression or not. # @api private # def regex? @name.is_a?(Regexp) end private # A standard way of converting all of our values, so we're always # comparing apples to apples. # @api private # def convert(value) case value when Symbol, '' # can't intern an empty string value when String value.intern when true :true when false :false else value.to_s.intern end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parameter/boolean.rb
lib/puppet/parameter/boolean.rb
# frozen_string_literal: true require_relative '../../puppet/coercion' # This specialized {Puppet::Parameter} handles Boolean options, accepting lots # of strings and symbols for both truth and falsehood. # class Puppet::Parameter::Boolean < Puppet::Parameter def unsafe_munge(value) Puppet::Coercion.boolean(value) end def self.initvars super @value_collection.newvalues(*Puppet::Coercion.boolean_values) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parameter/package_options.rb
lib/puppet/parameter/package_options.rb
# frozen_string_literal: true require_relative '../../puppet/parameter' # This specialized {Puppet::Parameter} handles munging of package options. # Package options are passed as an array of key value pairs. Special munging is # required as the keys and values needs to be quoted in a safe way. # class Puppet::Parameter::PackageOptions < Puppet::Parameter def unsafe_munge(values) values = [values] unless values.is_a? Array values.collect do |val| case val when Hash safe_hash = {} val.each_pair do |k, v| safe_hash[quote(k)] = quote(v) end safe_hash when String quote(val) else fail(_("Expected either a string or hash of options")) end end end # @api private def quote(value) value.include?(' ') ? %Q("#{value.gsub(/"/, '\"')}") : value end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/parameter/value_collection.rb
lib/puppet/parameter/value_collection.rb
# frozen_string_literal: true require_relative '../../puppet/parameter/value' # A collection of values and regular expressions, used for specifying allowed values # in a given parameter. # @note This class is considered part of the internal implementation of {Puppet::Parameter}, and # {Puppet::Property} and the functionality provided by this class should be used via their interfaces. # @comment This class probably have several problems when trying to use it with a combination of # regular expressions and aliases as it finds an acceptable value holder vi "name" which may be # a regular expression... # # @api private # class Puppet::Parameter::ValueCollection # Aliases the given existing _other_ value with the additional given _name_. # @return [void] # @api private # def aliasvalue(name, other) other = other.to_sym value = match?(other) raise Puppet::DevError, _("Cannot alias nonexistent value %{value}") % { value: other } unless value value.alias(name) end # Returns a doc string (enumerating the acceptable values) for all of the values in this parameter/property. # @return [String] a documentation string. # @api private # def doc unless defined?(@doc) @doc = ''.dup unless values.empty? @doc << "Valid values are " @doc << @strings.collect do |value| aliases = value.aliases if aliases && !aliases.empty? "`#{value.name}` (also called `#{aliases.join(', ')}`)" else "`#{value.name}`" end end.join(", ") << ". " end unless regexes.empty? @doc << "Values can match `#{regexes.join('`, `')}`." end end @doc end # @return [Boolean] Returns whether the set of allowed values is empty or not. # @api private # def empty? @values.empty? end # @api private # def initialize # We often look values up by name, so a hash makes more sense. @values = {} # However, we want to retain the ability to match values in order, # but we always prefer directly equality (i.e., strings) over regex matches. @regexes = [] @strings = [] end # Checks if the given value is acceptable (matches one of the literal values or patterns) and returns # the "matcher" that matched. # Literal string matchers are tested first, if both a literal and a regexp match would match, the literal # match wins. # # @param test_value [Object] the value to test if it complies with the configured rules # @return [Puppet::Parameter::Value, nil] The instance of Puppet::Parameter::Value that matched the given value, or nil if there was no match. # @api private # def match?(test_value) # First look for normal values value = @strings.find { |v| v.match?(test_value) } return value if value # Then look for a regex match @regexes.find { |v| v.match?(test_value) } end # Munges the value if it is valid, else produces the same value. # @param value [Object] the value to munge # @return [Object] the munged value, or the given value # @todo This method does not seem to do any munging. It just returns the value if it matches the # regexp, or the (most likely Symbolic) allowed value if it matches (which is more of a replacement # of one instance with an equal one. Is the intent that this method should be specialized? # @api private # def munge(value) return value if empty? instance = match?(value) if instance if instance.regex? value else instance.name end else value end end # Defines a new valid value for a {Puppet::Property}. # A valid value is specified as a literal (typically a Symbol), but can also be # specified with a regexp. # # @param name [Symbol, Regexp] a valid literal value, or a regexp that matches a value # @param options [Hash] a hash with options # @option options [Symbol] :event The event that should be emitted when this value is set. # @todo Option :event original comment says "event should be returned...", is "returned" the correct word # to use? # @option options [Symbol] :invalidate_refreshes True if a change on this property should invalidate and # remove any scheduled refreshes (from notify or subscribe) targeted at the same resource. For example, if # a change in this property takes into account any changes that a scheduled refresh would have performed, # then the scheduled refresh would be deleted. # @option options [Object] _any_ Any other option is treated as a call to a setter having the given # option name (e.g. `:required_features` calls `required_features=` with the option's value as an # argument). # @api private # def newvalue(name, options = {}, &block) call_opt = options[:call] unless call_opt.nil? devfail "Cannot use obsolete :call value '#{call_opt}' for property '#{self.class.name}'" unless call_opt == :none || call_opt == :instead # TRANSLATORS ':call' is a property and should not be translated message = _("Property option :call is deprecated and no longer used.") message += ' ' + _("Please remove it.") Puppet.deprecation_warning(message) options = options.reject { |k, _v| k == :call } end value = Puppet::Parameter::Value.new(name) @values[value.name] = value if value.regex? @regexes << value else @strings << value end options.each { |opt, arg| value.send(opt.to_s + "=", arg) } if block_given? devfail "Cannot use :call value ':none' in combination with a block for property '#{self.class.name}'" if call_opt == :none value.block = block value.method ||= "set_#{value.name}" unless value.regex? elsif call_opt == :instead devfail "Cannot use :call value ':instead' without a block for property '#{self.class.name}'" end value end # Defines one or more valid values (literal or regexp) for a parameter or property. # @return [void] # @dsl type # @api private # def newvalues(*names) names.each { |name| newvalue(name) } end # @return [Array<String>] An array of the regular expressions in string form, configured as matching valid values. # @api private # def regexes @regexes.collect { |r| r.name.inspect } end # Validates the given value against the set of valid literal values and regular expressions. # @raise [ArgumentError] if the value is not accepted # @return [void] # @api private # def validate(value) return if empty? unless @values.detect { |_name, v| v.match?(value) } str = _("Invalid value %{value}.") % { value: value.inspect } str += " " + _("Valid values are %{value_list}.") % { value_list: values.join(", ") } unless values.empty? str += " " + _("Valid values match %{pattern}.") % { pattern: regexes.join(", ") } unless regexes.empty? raise ArgumentError, str end end # Returns a valid value matcher (a literal or regular expression) # @todo This looks odd, asking for an instance that matches a symbol, or an instance that has # a regexp. What is the intention here? Marking as api private... # # @return [Puppet::Parameter::Value] a valid value matcher # @api private # def value(name) @values[name] end # @return [Array<Symbol>] Returns a list of valid literal values. # @see regexes # @api private # def values @strings.collect(&:name) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/test/test_helper.rb
lib/puppet/test/test_helper.rb
# frozen_string_literal: true require 'tmpdir' require 'fileutils' module Puppet::Test # This class is intended to provide an API to be used by external projects # when they are running tests that depend on puppet core. This should # allow us to vary the implementation details of managing puppet's state # for testing, from one version of puppet to the next--without forcing # the external projects to do any of that state management or be aware of # the implementation details. # # For now, this consists of a few very simple signatures. The plan is # that it should be the responsibility of the puppetlabs_spec_helper # to broker between external projects and this API; thus, if any # hacks are required (e.g. to determine whether or not a particular) # version of puppet supports this API, those hacks will be consolidated in # one place and won't need to be duplicated in every external project. # # This should also alleviate the anti-pattern that we've been following, # wherein each external project starts off with a copy of puppet core's # test_helper.rb and is exposed to risk of that code getting out of # sync with core. # # Since this class will be "library code" that ships with puppet, it does # not use API from any existing test framework such as rspec. This should # theoretically allow it to be used with other unit test frameworks in the # future, if desired. # # Note that in the future this API could potentially be expanded to handle # other features such as "around_test", but we didn't see a compelling # reason to deal with that right now. class TestHelper # Call this method once, as early as possible, such as before loading tests # that call Puppet. # @return nil def self.initialize # This meta class instance variable is used as a guard to ensure that # before_each, and after_each are only called once. This problem occurs # when there are more than one puppet test infrastructure orchestrator in use. # The use of both puppetabs-spec_helper, and rodjek-rspec_puppet will cause # two resets of the puppet environment, and will cause problem rolling back to # a known point as there is no way to differentiate where the calls are coming # from. See more information in #before_each_test, and #after_each_test # Note that the variable is only initialized to 0 if nil. This is important # as more than one orchestrator will call initialize. A second call can not # simply set it to 0 since that would potentially destroy an active guard. # @@reentry_count ||= 0 @environmentpath = Dir.mktmpdir('environments') Dir.mkdir("#{@environmentpath}/production") owner = Process.pid Puppet.push_context(Puppet.base_context({ :environmentpath => @environmentpath, :basemodulepath => "", }), "Initial for specs") Puppet::Parser::Functions.reset ObjectSpace.define_finalizer(Puppet.lookup(:environments), proc { if Process.pid == owner FileUtils.rm_rf(@environmentpath) end }) Puppet::SSL::Oids.register_puppet_oids end # Call this method once, when beginning a test run--prior to running # any individual tests. # @return nil def self.before_all_tests # The process environment is a shared, persistent resource. $old_env = ENV.to_hash end # Call this method once, at the end of a test run, when no more tests # will be run. # @return nil def self.after_all_tests end # The name of the rollback mark used in the Puppet.context. This is what # the test infrastructure returns to for each test. # ROLLBACK_MARK = "initial testing state" # Call this method once per test, prior to execution of each individual test. # @return nil def self.before_each_test # When using both rspec-puppet and puppet-rspec-helper, there are two packages trying # to be helpful and orchestrate the callback sequence. We let only the first win, the # second callback results in a no-op. # Likewise when entering after_each_test(), a check is made to make tear down happen # only once. # return unless @@reentry_count == 0 @@reentry_count = 1 Puppet.mark_context(ROLLBACK_MARK) # We need to preserve the current state of all our indirection cache and # terminus classes. This is pretty important, because changes to these # are global and lead to order dependencies in our testing. # # We go direct to the implementation because there is no safe, sane public # API to manage restoration of these to their default values. This # should, once the value is proved, be moved to a standard API on the # indirector. # # To make things worse, a number of the tests stub parts of the # indirector. These stubs have very specific expectations that what # little of the public API we could use is, well, likely to explode # randomly in some tests. So, direct access. --daniel 2011-08-30 $saved_indirection_state = {} indirections = Puppet::Indirector::Indirection.send(:class_variable_get, :@@indirections) indirections.each do |indirector| $saved_indirection_state[indirector.name] = { :@terminus_class => indirector.instance_variable_get(:@terminus_class).value, :@cache_class => indirector.instance_variable_get(:@cache_class).value, # dup the termini hash so termini created and registered during # the test aren't stored in our saved_indirection_state :@termini => indirector.instance_variable_get(:@termini).dup } end # So is the load_path $old_load_path = $LOAD_PATH.dup initialize_settings_before_each() Puppet.push_context( { trusted_information: Puppet::Context::TrustedInformation.new('local', 'testing', {}, { "trusted_testhelper" => true }), ssl_context: Puppet::SSL::SSLContext.new(cacerts: []).freeze, http_session: proc { Puppet.runtime[:http].create_session } }, "Context for specs" ) # trigger `require 'facter'` Puppet.runtime[:facter] Puppet::Parser::Functions.reset Puppet::Application.clear! Puppet::Util::Profiler.clear Puppet::Node::Facts.indirection.terminus_class = :memory facts = Puppet::Node::Facts.new(Puppet[:node_name_value]) Puppet::Node::Facts.indirection.save(facts) Puppet.clear_deprecation_warnings end # Call this method once per test, after execution of each individual test. # @return nil def self.after_each_test # Ensure that a matching tear down only happens once per completed setup # (see #before_each_test). return unless @@reentry_count == 1 @@reentry_count = 0 Puppet.settings.send(:clear_everything_for_tests) Puppet::Util::Storage.clear Puppet::Util::ExecutionStub.reset Puppet.runtime.clear Puppet.clear_deprecation_warnings # uncommenting and manipulating this can be useful when tracking down calls to deprecated code # Puppet.log_deprecations_to_file("deprecations.txt", /^Puppet::Util.exec/) # Restore the indirector configuration. See before hook. indirections = Puppet::Indirector::Indirection.send(:class_variable_get, :@@indirections) indirections.each do |indirector| $saved_indirection_state.fetch(indirector.name, {}).each do |variable, value| if variable == :@termini indirector.instance_variable_set(variable, value) else indirector.instance_variable_get(variable).value = value end end end $saved_indirection_state = nil # Restore the global process environment. ENV.replace($old_env) # Clear all environments Puppet.lookup(:environments).clear_all # Restore the load_path late, to avoid messing with stubs from the test. $LOAD_PATH.clear $old_load_path.each { |x| $LOAD_PATH << x } Puppet.rollback_context(ROLLBACK_MARK) end ######################################################################################### # PRIVATE METHODS (not part of the public TestHelper API--do not call these from outside # of this class!) ######################################################################################### def self.app_defaults_for_tests { :logdir => "/dev/null", :confdir => "/dev/null", :publicdir => "/dev/null", :codedir => "/dev/null", :vardir => "/dev/null", :rundir => "/dev/null", :hiera_config => "/dev/null", } end private_class_method :app_defaults_for_tests def self.initialize_settings_before_each Puppet.settings.preferred_run_mode = "user" # Initialize "app defaults" settings to a good set of test values Puppet.settings.initialize_app_defaults(app_defaults_for_tests) # We don't want to depend upon the reported domain name of the # machine running the tests, nor upon the DNS setup of that # domain. Puppet.settings[:use_srv_records] = false # Longer keys are secure, but they sure make for some slow testing - both # in terms of generating keys, and in terms of anything the next step down # the line doing validation or whatever. Most tests don't care how long # or secure it is, just that it exists, so these are better and faster # defaults, in testing only. # # I would make these even shorter, but OpenSSL doesn't support anything # below 512 bits. Sad, really, because a 0 bit key would be just fine. Puppet[:keylength] = 512 # Although we setup a testing context during initialization, some tests # will end up creating their own context using the real context objects # and use the setting for the environments. In order to avoid those tests # having to deal with a missing environmentpath we can just set it right # here. Puppet[:environmentpath] = @environmentpath Puppet[:environment_timeout] = 0 end private_class_method :initialize_settings_before_each end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/store_configs.rb
lib/puppet/indirector/store_configs.rb
# frozen_string_literal: true class Puppet::Indirector::StoreConfigs < Puppet::Indirector::Terminus def initialize super # This will raise if the indirection can't be found, so we can assume it # is always set to a valid instance from here on in. @target = indirection.terminus Puppet[:storeconfigs_backend] end attr_reader :target def head(request) target.head request end def find(request) target.find request end def search(request) target.search request end def save(request) target.save request end def destroy(request) target.save request end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/indirector/direct_file_server.rb
lib/puppet/indirector/direct_file_server.rb
# frozen_string_literal: true require_relative '../../puppet/file_serving/terminus_helper' require_relative '../../puppet/indirector/terminus' class Puppet::Indirector::DirectFileServer < Puppet::Indirector::Terminus include Puppet::FileServing::TerminusHelper def find(request) return nil unless Puppet::FileSystem.exist?(request.key) path2instance(request, request.key) end def search(request) return nil unless Puppet::FileSystem.exist?(request.key) path2instances(request, request.key) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false