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/functions/map.rb | lib/puppet/functions/map.rb | # frozen_string_literal: true
# Applies a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html)
# to every value in a data structure and returns an array containing the results.
#
# This function takes two mandatory arguments, in this order:
#
# 1. An array, hash, or other iterable object that the function will iterate over.
# 2. A lambda, which the function calls for each element in the first argument. It can
# request one or two parameters.
#
# @example Using the `map` function
#
# `$transformed_data = $data.map |$parameter| { <PUPPET CODE BLOCK> }`
#
# or
#
# `$transformed_data = map($data) |$parameter| { <PUPPET CODE BLOCK> }`
#
# When the first argument (`$data` in the above example) is an array, Puppet passes each
# value in turn to the lambda.
#
# @example Using the `map` function with an array and a one-parameter lambda
#
# ```puppet
# # For the array $data, return an array containing each value multiplied by 10
# $data = [1,2,3]
# $transformed_data = $data.map |$items| { $items * 10 }
# # $transformed_data contains [10,20,30]
# ```
#
# When the first argument is a hash, Puppet passes each key and value pair to the lambda
# as an array in the form `[key, value]`.
#
# @example Using the `map` function with a hash and a one-parameter lambda
#
# ```puppet
# # For the hash $data, return an array containing the keys
# $data = {'a'=>1,'b'=>2,'c'=>3}
# $transformed_data = $data.map |$items| { $items[0] }
# # $transformed_data contains ['a','b','c']
# ```
#
# When the first argument is an array and the lambda has two parameters, Puppet passes the
# array's indexes (enumerated from 0) in the first parameter and its values in the second
# parameter.
#
# @example Using the `map` function with an array and a two-parameter lambda
#
# ```puppet
# # For the array $data, return an array containing the indexes
# $data = [1,2,3]
# $transformed_data = $data.map |$index,$value| { $index }
# # $transformed_data contains [0,1,2]
# ```
#
# When the first argument is a hash, Puppet passes its keys to the first parameter and its
# values to the second parameter.
#
# @example Using the `map` function with a hash and a two-parameter lambda
#
# ```puppet
# # For the hash $data, return an array containing each value
# $data = {'a'=>1,'b'=>2,'c'=>3}
# $transformed_data = $data.map |$key,$value| { $value }
# # $transformed_data contains [1,2,3]
# ```
#
# @since 4.0.0
#
Puppet::Functions.create_function(:map) do
dispatch :map_Hash_2 do
param 'Hash[Any, Any]', :hash
block_param 'Callable[2,2]', :block
end
dispatch :map_Hash_1 do
param 'Hash[Any, Any]', :hash
block_param 'Callable[1,1]', :block
end
dispatch :map_Enumerable_2 do
param 'Iterable', :enumerable
block_param 'Callable[2,2]', :block
end
dispatch :map_Enumerable_1 do
param 'Iterable', :enumerable
block_param 'Callable[1,1]', :block
end
def map_Hash_1(hash)
result = []
begin
hash.each { |x, y| result << yield([x, y]) }
rescue StopIteration
end
result
end
def map_Hash_2(hash)
result = []
begin
hash.each { |x, y| result << yield(x, y) }
rescue StopIteration
end
result
end
def map_Enumerable_1(enumerable)
result = []
enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable)
begin
enum.each do |val|
result << yield(val)
end
rescue StopIteration
end
result
end
def map_Enumerable_2(enumerable)
enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable)
if enum.hash_style?
enum.map { |entry| yield(*entry) }
else
result = []
begin
enum.each_with_index do |val, index|
result << yield(index, val)
end
rescue StopIteration
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/functions/import.rb | lib/puppet/functions/import.rb | # frozen_string_literal: true
# The import function raises an error when called to inform the user that import is no longer supported.
#
Puppet::Functions.create_function(:import) do
def import(*args)
raise Puppet::Pops::SemanticError, Puppet::Pops::Issues::DISCONTINUED_IMPORT
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/functions/return.rb | lib/puppet/functions/return.rb | # frozen_string_literal: true
# Makes iteration continue with the next value, optionally with a given value for this iteration.
# If a value is not given it defaults to `undef`
#
# @since 4.7.0
#
Puppet::Functions.create_function(:return, Puppet::Functions::InternalFunction) do
dispatch :return_impl do
optional_param 'Any', :value
end
def return_impl(value = nil)
file, line = Puppet::Pops::PuppetStack.top_of_stack
raise Puppet::Pops::Evaluator::Return.new(value, file, line)
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/functions/min.rb | lib/puppet/functions/min.rb | # frozen_string_literal: true
# Returns the lowest value among a variable number of arguments.
# Takes at least one argument.
#
# This function is (with one exception) compatible with the stdlib function
# with the same name and performs deprecated type conversion before
# comparison as follows:
#
# * If a value converted to String is an optionally '-' prefixed,
# string of digits, one optional decimal point, followed by optional
# decimal digits - then the comparison is performed on the values
# converted to floating point.
# * If a value is not considered convertible to float, it is converted
# to a `String` and the comparison is a lexical compare where min is
# the lexicographical earlier value.
# * A lexicographical compare is performed in a system locale - international
# characters may therefore not appear in what a user thinks is the correct order.
# * The conversion rules apply to values in pairs - the rule must hold for both
# values - a value may therefore be compared using different rules depending
# on the "other value".
# * The returned result found to be the "lowest" is the original unconverted value.
#
# The above rules have been deprecated in Puppet 6.0.0 as they produce strange results when
# given values of mixed data types. In general, either convert values to be
# all `String` or all `Numeric` values before calling the function, or call the
# function with a lambda that performs type conversion and comparison. This because one
# simply cannot compare `Boolean` with `Regexp` and with any arbitrary `Array`, `Hash` or
# `Object` and getting a meaningful result.
#
# The one change in the function's behavior is when the function is given a single
# array argument. The stdlib implementation would return that array as the result where
# it now instead returns the max value from that array.
#
# @example 'min of values - stdlib compatible'
#
# ```puppet
# notice(min(1)) # would notice 1
# notice(min(1,2)) # would notice 1
# notice(min("1", 2)) # would notice 1
# notice(min("0777", 512)) # would notice 512, since "0777" is not converted from octal form
# notice(min(0777, 512)) # would notice 511, since 0777 is decimal 511
# notice(min('aa', 'ab')) # would notice 'aa'
# notice(min(['a'], ['b'])) # would notice ['a'], since "['a']" is before "['b']"
# ```
#
# @example find 'min' value in an array
#
# ```puppet
# $x = [1,2,3,4]
# notice(min(*$x)) # would notice 1
# ```
#
# @example find 'min' value in an array directly - since Puppet 6.0.0
#
# ```puppet
# $x = [1,2,3,4]
# notice(min($x)) # would notice 1
# notice($x.min) # would notice 1
# ```
# This example shows that a single array argument is used as the set of values
# as opposed to being a single returned value.
#
# When calling with a lambda, it must accept two variables and it must return
# one of -1, 0, or 1 depending on if first argument is before/lower than, equal to,
# or higher/after the second argument.
#
# @example 'min of values using a lambda'
#
# ```puppet
# notice(min("2", "10", "100") |$a, $b| { compare($a, $b) })
# ```
#
# Would notice "10" as lower since it is lexicographically lower/before the other values. Without the
# lambda the stdlib compatible (deprecated) behavior would have been to return "2" since number conversion kicks in.
#
Puppet::Functions.create_function(:min) do
dispatch :on_numeric do
repeated_param 'Numeric', :values
end
dispatch :on_string do
repeated_param 'String', :values
end
dispatch :on_semver do
repeated_param 'Semver', :values
end
dispatch :on_timespan do
repeated_param 'Timespan', :values
end
dispatch :on_timestamp do
repeated_param 'Timestamp', :values
end
dispatch :on_single_numeric_array do
param 'Array[Numeric]', :values
optional_block_param 'Callable[2,2]', :block
end
dispatch :on_single_semver_array do
param 'Array[Semver]', :values
optional_block_param 'Callable[2,2]', :block
end
dispatch :on_single_timespan_array do
param 'Array[Timespan]', :values
optional_block_param 'Callable[2,2]', :block
end
dispatch :on_single_timestamp_array do
param 'Array[Timestamp]', :values
optional_block_param 'Callable[2,2]', :block
end
dispatch :on_single_string_array do
param 'Array[String]', :values
optional_block_param 'Callable[2,2]', :block
end
dispatch :on_single_any_array do
param 'Array', :values
optional_block_param 'Callable[2,2]', :block
end
dispatch :on_any_with_block do
repeated_param 'Any', :values
block_param 'Callable[2,2]', :block
end
dispatch :on_any do
repeated_param 'Any', :values
end
# All are Numeric - ok now, will be ok later
def on_numeric(*args)
assert_arg_count(args)
args.min
end
# All are String, may convert to numeric (which is deprecated)
def on_string(*args)
assert_arg_count(args)
args.min do |a, b|
if a.to_s =~ /\A^-?\d+([._eE]\d+)?\z/ && b.to_s =~ /\A-?\d+([._eE]\d+)?\z/
Puppet.warn_once('deprecations', 'min_function_numeric_coerce_string',
_("The min() function's auto conversion of String to Numeric is deprecated - change to convert input before calling, or use lambda"))
a.to_f <=> b.to_f
else
# case sensitive as in the stdlib function
a <=> b
end
end
end
def on_semver(*args)
assert_arg_count(args)
args.min
end
def on_timespan(*args)
assert_arg_count(args)
args.min
end
def on_timestamp(*args)
assert_arg_count(args)
args.min
end
def on_any_with_block(*args, &block)
args.min { |x, y| block.call(x, y) }
end
def on_single_numeric_array(array, &block)
if block_given?
on_any_with_block(*array, &block)
else
on_numeric(*array)
end
end
def on_single_string_array(array, &block)
if block_given?
on_any_with_block(*array, &block)
else
on_string(*array)
end
end
def on_single_semver_array(array, &block)
if block_given?
on_any_with_block(*array, &block)
else
on_semver(*array)
end
end
def on_single_timespan_array(array, &block)
if block_given?
on_any_with_block(*array, &block)
else
on_timespan(*array)
end
end
def on_single_timestamp_array(array, &block)
if block_given?
on_any_with_block(*array, &block)
else
on_timestamp(*array)
end
end
def on_single_any_array(array, &block)
if block_given?
on_any_with_block(*array, &block)
else
on_any(*array)
end
end
# Mix of data types - while only some compares are actually bad it will deprecate
# the entire call
#
def on_any(*args)
assert_arg_count(args)
args.min do |a, b|
as = a.to_s
bs = b.to_s
if as =~ /\A^-?\d+([._eE]\d+)?\z/ && bs =~ /\A-?\d+([._eE]\d+)?\z/
Puppet.warn_once('deprecations', 'min_function_numeric_coerce_string',
_("The min() function's auto conversion of String to Numeric is deprecated - change to convert input before calling, or use lambda"))
a.to_f <=> b.to_f
else
Puppet.warn_once('deprecations', 'min_function_string_coerce_any',
_("The min() function's auto conversion of Any to String is deprecated - change to convert input before calling, or use lambda"))
as <=> bs
end
end
end
def assert_arg_count(args)
raise(ArgumentError, 'min(): Wrong number of arguments need at least one') if args.empty?
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/functions/err.rb | lib/puppet/functions/err.rb | # frozen_string_literal: true
# Logs a message on the server at level `err`.
Puppet::Functions.create_function(:err, Puppet::Functions::InternalFunction) do
# @param values The values to log.
# @return [Undef]
dispatch :err do
scope_param
repeated_param 'Any', :values
return_type 'Undef'
end
def err(scope, *values)
Puppet::Util::Log.log_func(scope, :err, 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/functions/downcase.rb | lib/puppet/functions/downcase.rb | # frozen_string_literal: true
# Converts a String, Array or Hash (recursively) into lower case.
#
# This function is compatible with the stdlib function with the same name.
#
# The function does the following:
# * For a `String`, its lower case version is returned. This is done using Ruby system locale which handles some, but not all
# special international up-casing rules (for example German double-s ß is upcased to "SS", whereas upper case double-s
# is downcased to ß).
# * For `Array` and `Hash` the conversion to lower case is recursive and each key and value must be convertible by
# this function.
# * When a `Hash` is converted, some keys could result in the same key - in those cases, the
# latest key-value wins. For example if keys "aBC", and "abC" where both present, after downcase there would only be one
# key "abc".
# * If the value is `Numeric` it is simply returned (this is for backwards compatibility).
# * An error is raised for all other data types.
#
# Please note: This function relies directly on Ruby's String implementation and as such may not be entirely UTF8 compatible.
# To ensure best compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085.
#
# @example Converting a String to lower case
# ```puppet
# 'HELLO'.downcase()
# downcase('HEllO')
# ```
# Would both result in `"hello"`
#
# @example Converting an Array to lower case
# ```puppet
# ['A', 'B'].downcase()
# downcase(['A', 'B'])
# ```
# Would both result in `['a', 'b']`
#
# @example Converting a Hash to lower case
# ```puppet
# {'A' => 'HEllO', 'B' => 'GOODBYE'}.downcase()
# ```
# Would result in `{'a' => 'hello', 'b' => 'goodbye'}`
#
# @example Converting a recursive structure
# ```puppet
# ['A', 'B', ['C', ['D']], {'X' => 'Y'}].downcase
# ```
# Would result in `['a', 'b', ['c', ['d']], {'x' => 'y'}]`
#
Puppet::Functions.create_function(:downcase) do
local_types do
type 'StringData = Variant[String, Numeric, Array[StringData], Hash[StringData, StringData]]'
end
dispatch :on_numeric do
param 'Numeric', :arg
end
dispatch :on_string do
param 'String', :arg
end
dispatch :on_array do
param 'Array[StringData]', :arg
end
dispatch :on_hash do
param 'Hash[StringData, StringData]', :arg
end
# unit function - since the old implementation skipped Numeric values
def on_numeric(n)
n
end
def on_string(s)
s.downcase
end
def on_array(a)
a.map { |x| do_downcase(x) }
end
def on_hash(h)
result = {}
h.each_pair { |k, v| result[do_downcase(k)] = do_downcase(v) }
result
end
def do_downcase(x)
x.is_a?(String) ? x.downcase : call_function('downcase', x)
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/functions/each.rb | lib/puppet/functions/each.rb | # frozen_string_literal: true
# Runs a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html)
# repeatedly using each value in a data structure, then returns the values unchanged.
#
# This function takes two mandatory arguments, in this order:
#
# 1. An array, hash, or other iterable object that the function will iterate over.
# 2. A lambda, which the function calls for each element in the first argument. It can
# request one or two parameters.
#
# @example Using the `each` function
#
# `$data.each |$parameter| { <PUPPET CODE BLOCK> }`
#
# or
#
# `each($data) |$parameter| { <PUPPET CODE BLOCK> }`
#
# When the first argument (`$data` in the above example) is an array, Puppet passes each
# value in turn to the lambda, then returns the original values.
#
# @example Using the `each` function with an array and a one-parameter lambda
#
# ```puppet
# # For the array $data, run a lambda that creates a resource for each item.
# $data = ["routers", "servers", "workstations"]
# $data.each |$item| {
# notify { $item:
# message => $item
# }
# }
# # Puppet creates one resource for each of the three items in $data. Each resource is
# # named after the item's value and uses the item's value in a parameter.
# ```
#
# When the first argument is a hash, Puppet passes each key and value pair to the lambda
# as an array in the form `[key, value]` and returns the original hash.
#
# @example Using the `each` function with a hash and a one-parameter lambda
#
# ```puppet
# # For the hash $data, run a lambda using each item as a key-value array that creates a
# # resource for each item.
# $data = {"rtr" => "Router", "svr" => "Server", "wks" => "Workstation"}
# $data.each |$items| {
# notify { $items[0]:
# message => $items[1]
# }
# }
# # Puppet creates one resource for each of the three items in $data, each named after the
# # item's key and containing a parameter using the item's value.
# ```
#
# When the first argument is an array and the lambda has two parameters, Puppet passes the
# array's indexes (enumerated from 0) in the first parameter and its values in the second
# parameter.
#
# @example Using the `each` function with an array and a two-parameter lambda
#
# ```puppet
# # For the array $data, run a lambda using each item's index and value that creates a
# # resource for each item.
# $data = ["routers", "servers", "workstations"]
# $data.each |$index, $value| {
# notify { $value:
# message => $index
# }
# }
# # Puppet creates one resource for each of the three items in $data, each named after the
# # item's value and containing a parameter using the item's index.
# ```
#
# When the first argument is a hash, Puppet passes its keys to the first parameter and its
# values to the second parameter.
#
# @example Using the `each` function with a hash and a two-parameter lambda
#
# ```puppet
# # For the hash $data, run a lambda using each item's key and value to create a resource
# # for each item.
# $data = {"rtr" => "Router", "svr" => "Server", "wks" => "Workstation"}
# $data.each |$key, $value| {
# notify { $key:
# message => $value
# }
# }
# # Puppet creates one resource for each of the three items in $data, each named after the
# # item's key and containing a parameter using the item's value.
# ```
#
# For an example that demonstrates how to create multiple `file` resources using `each`,
# see the Puppet
# [iteration](https://puppet.com/docs/puppet/latest/lang_iteration.html)
# documentation.
#
# @since 4.0.0
#
Puppet::Functions.create_function(:each) do
dispatch :foreach_Hash_2 do
param 'Hash[Any, Any]', :hash
block_param 'Callable[2,2]', :block
end
dispatch :foreach_Hash_1 do
param 'Hash[Any, Any]', :hash
block_param 'Callable[1,1]', :block
end
dispatch :foreach_Enumerable_2 do
param 'Iterable', :enumerable
block_param 'Callable[2,2]', :block
end
dispatch :foreach_Enumerable_1 do
param 'Iterable', :enumerable
block_param 'Callable[1,1]', :block
end
def foreach_Hash_1(hash)
begin
hash.each_pair do |pair|
yield(pair)
end
rescue StopIteration
end
# produces the receiver
hash
end
def foreach_Hash_2(hash)
begin
hash.each_pair do |pair|
yield(*pair)
end
rescue StopIteration
end
# produces the receiver
hash
end
def foreach_Enumerable_1(enumerable)
enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable)
begin
enum.each do |value|
yield value
end
rescue StopIteration
end
# produces the receiver
enumerable
end
def foreach_Enumerable_2(enumerable)
enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable)
if enum.hash_style?
enum.each { |entry| yield(*entry) }
else
begin
enum.each_with_index do |value, index|
yield(index, value)
end
rescue StopIteration
end
end
# produces the receiver
enumerable
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/functions/lookup.rb | lib/puppet/functions/lookup.rb | # frozen_string_literal: true
# Uses the Puppet lookup system to retrieve a value for a given key. By default,
# this returns the first value found (and fails compilation if no values are
# available), but you can configure it to merge multiple values into one, fail
# gracefully, and more.
#
# When looking up a key, Puppet will search up to three tiers of data, in the
# following order:
#
# 1. Hiera.
# 2. The current environment's data provider.
# 3. The indicated module's data provider, if the key is of the form
# `<MODULE NAME>::<SOMETHING>`.
#
# #### Arguments
#
# You must provide the name of a key to look up, and can optionally provide other
# arguments. You can combine these arguments in the following ways:
#
# * `lookup( <NAME>, [<VALUE TYPE>], [<MERGE BEHAVIOR>], [<DEFAULT VALUE>] )`
# * `lookup( [<NAME>], <OPTIONS HASH> )`
# * `lookup( as above ) |$key| { # lambda returns a default value }`
#
# Arguments in `[square brackets]` are optional.
#
# The arguments accepted by `lookup` are as follows:
#
# 1. `<NAME>` (string or array) --- The name of the key to look up.
# * This can also be an array of keys. If Puppet doesn't find anything for the
# first key, it will try again with the subsequent ones, only resorting to a
# default value if none of them succeed.
# 2. `<VALUE TYPE>` (data type) --- A
# [data type](https://puppet.com/docs/puppet/latest/lang_data_type.html)
# that must match the retrieved value; if not, the lookup (and catalog
# compilation) will fail. Defaults to `Data` (accepts any normal value).
# 3. `<MERGE BEHAVIOR>` (string or hash; see **"Merge Behaviors"** below) ---
# Whether (and how) to combine multiple values. If present, this overrides any
# merge behavior specified in the data sources. Defaults to no value; Puppet will
# use merge behavior from the data sources if present, and will otherwise do a
# first-found lookup.
# 4. `<DEFAULT VALUE>` (any normal value) --- If present, `lookup` returns this
# when it can't find a normal value. Default values are never merged with found
# values. Like a normal value, the default must match the value type. Defaults to
# no value; if Puppet can't find a normal value, the lookup (and compilation) will
# fail.
# 5. `<OPTIONS HASH>` (hash) --- Alternate way to set the arguments above, plus
# some less-common extra options. If you pass an options hash, you can't combine
# it with any regular arguments (except `<NAME>`). An options hash can have the
# following keys:
# * `'name'` --- Same as `<NAME>` (argument 1). You can pass this as an
# argument or in the hash, but not both.
# * `'value_type'` --- Same as `<VALUE TYPE>` (argument 2).
# * `'merge'` --- Same as `<MERGE BEHAVIOR>` (argument 3).
# * `'default_value'` --- Same as `<DEFAULT VALUE>` (argument 4).
# * `'default_values_hash'` (hash) --- A hash of lookup keys and default
# values. If Puppet can't find a normal value, it will check this hash for the
# requested key before giving up. You can combine this with `default_value` or
# a lambda, which will be used if the key isn't present in this hash. Defaults
# to an empty hash.
# * `'override'` (hash) --- A hash of lookup keys and override values. Puppet
# will check for the requested key in the overrides hash _first;_ if found, it
# returns that value as the _final_ value, ignoring merge behavior. Defaults
# to an empty hash.
#
# Finally, `lookup` can take a lambda, which must accept a single parameter.
# This is yet another way to set a default value for the lookup; if no results are
# found, Puppet will pass the requested key to the lambda and use its result as
# the default value.
#
# #### Merge Behaviors
#
# Puppet lookup uses a hierarchy of data sources, and a given key might have
# values in multiple sources. By default, Puppet returns the first value it finds,
# but it can also continue searching and merge all the values together.
#
# > **Note:** Data sources can use the special `lookup_options` metadata key to
# request a specific merge behavior for a key. The `lookup` function will use that
# requested behavior unless you explicitly specify one.
#
# The valid merge behaviors are:
#
# * `'first'` --- Returns the first value found, with no merging. Puppet lookup's
# default behavior.
# * `'unique'` (called "array merge" in classic Hiera) --- Combines any number of
# arrays and scalar values to return a merged, flattened array with all duplicate
# values removed. The lookup will fail if any hash values are found.
# * `'hash'` --- Combines the keys and values of any number of hashes to return a
# merged hash. If the same key exists in multiple source hashes, Puppet will use
# the value from the highest-priority data source; it won't recursively merge the
# values.
# * `'deep'` --- Combines the keys and values of any number of hashes to return a
# merged hash. If the same key exists in multiple source hashes, Puppet will
# recursively merge hash or array values (with duplicate values removed from
# arrays). For conflicting scalar values, the highest-priority value will win.
# * `{'strategy' => 'first'}`, `{'strategy' => 'unique'}`,
# or `{'strategy' => 'hash'}` --- Same as the string versions of these merge behaviors.
# * `{'strategy' => 'deep', <DEEP OPTION> => <VALUE>, ...}` --- Same as `'deep'`,
# but can adjust the merge with additional options. The available options are:
# * `'knockout_prefix'` (string) --- A string prefix to indicate a
# value should be _removed_ from the final result. If a value is exactly equal
# to the prefix, it will knockout the entire element. Defaults to `undef`, which
# disables this feature.
# * `'sort_merged_arrays'` (boolean) --- Whether to sort all arrays that are
# merged together. Defaults to `false`.
# * `'merge_hash_arrays'` (boolean) --- Whether to merge hashes within arrays.
# Defaults to `false`.
#
# @example Look up a key and return the first value found
#
# lookup('ntp::service_name')
#
# @example Do a unique merge lookup of class names, then add all of those classes to the catalog (like `hiera_include`)
#
# lookup('classes', Array[String], 'unique').include
#
# @example Do a deep hash merge lookup of user data, but let higher priority sources remove values by prefixing them with `--`
#
# lookup( { 'name' => 'users',
# 'merge' => {
# 'strategy' => 'deep',
# 'knockout_prefix' => '--',
# },
# })
#
# @since 4.0.0
Puppet::Functions.create_function(:lookup, Puppet::Functions::InternalFunction) do
local_types do
type 'NameType = Variant[String, Array[String]]'
type 'ValueType = Type'
type 'DefaultValueType = Any'
type 'MergeType = Variant[String[1], Hash[String, Scalar]]'
type 'BlockType = Callable[NameType]'
type "OptionsWithName = Struct[{\
name => NameType,\
value_type => Optional[ValueType],\
default_value => Optional[DefaultValueType],\
override => Optional[Hash[String,Any]],\
default_values_hash => Optional[Hash[String,Any]],\
merge => Optional[MergeType]\
}]"
type "OptionsWithoutName = Struct[{\
value_type => Optional[ValueType],\
default_value => Optional[DefaultValueType],\
override => Optional[Hash[String,Any]],\
default_values_hash => Optional[Hash[String,Any]],\
merge => Optional[MergeType]\
}]"
end
dispatch :lookup_1 do
scope_param
param 'NameType', :name
optional_param 'ValueType', :value_type
optional_param 'MergeType', :merge
end
dispatch :lookup_2 do
scope_param
param 'NameType', :name
param 'Optional[ValueType]', :value_type
param 'Optional[MergeType]', :merge
param 'DefaultValueType', :default_value
end
dispatch :lookup_3 do
scope_param
param 'NameType', :name
optional_param 'ValueType', :value_type
optional_param 'MergeType', :merge
required_block_param 'BlockType', :block
end
# Lookup without name. Name then becomes a required entry in the options hash
dispatch :lookup_4 do
scope_param
param 'OptionsWithName', :options_hash
optional_block_param 'BlockType', :block
end
# Lookup using name and options hash.
dispatch :lookup_5 do
scope_param
param 'Variant[String,Array[String]]', :name
param 'OptionsWithoutName', :options_hash
optional_block_param 'BlockType', :block
end
def lookup_1(scope, name, value_type = nil, merge = nil)
do_lookup(scope, name, value_type, nil, false, {}, {}, merge)
end
def lookup_2(scope, name, value_type, merge, default_value)
do_lookup(scope, name, value_type, default_value, true, {}, {}, merge)
end
def lookup_3(scope, name, value_type = nil, merge = nil, &block)
do_lookup(scope, name, value_type, nil, false, {}, {}, merge, &block)
end
def lookup_4(scope, options_hash, &block)
do_lookup(scope, options_hash['name'], *hash_args(options_hash), &block)
end
def lookup_5(scope, name, options_hash, &block)
do_lookup(scope, name, *hash_args(options_hash), &block)
end
def do_lookup(scope, name, value_type, default_value, has_default, override, default_values_hash, merge, &block)
Puppet::Pops::Lookup.lookup(name, value_type, default_value, has_default, merge,
Puppet::Pops::Lookup::Invocation.new(scope, override, default_values_hash), &block)
end
def hash_args(options_hash)
[
options_hash['value_type'],
options_hash['default_value'],
options_hash.include?('default_value'),
options_hash['override'] || {},
options_hash['default_values_hash'] || {},
options_hash['merge']
]
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/functions/lstrip.rb | lib/puppet/functions/lstrip.rb | # frozen_string_literal: true
# Strips leading spaces from a String
#
# This function is compatible with the stdlib function with the same name.
#
# The function does the following:
# * For a `String` the conversion removes all leading ASCII white space characters such as space, tab, newline, and return.
# It does not remove other space-like characters like hard space (Unicode U+00A0). (Tip, `/^[[:space:]]/` regular expression
# matches all space-like characters).
# * For an `Iterable[Variant[String, Numeric]]` (for example an `Array`) each value is processed and the conversion is not recursive.
# * If the value is `Numeric` it is simply returned (this is for backwards compatibility).
# * An error is raised for all other data types.
#
# @example Removing leading space from a String
# ```puppet
# "\n\thello ".lstrip()
# lstrip("\n\thello ")
# ```
# Would both result in `"hello"`
#
# @example Removing leading space from strings in an Array
# ```puppet
# ["\n\thello ", "\n\thi "].lstrip()
# lstrip(["\n\thello ", "\n\thi "])
# ```
# Would both result in `['hello', 'hi']`
#
Puppet::Functions.create_function(:lstrip) do
dispatch :on_numeric do
param 'Numeric', :arg
end
dispatch :on_string do
param 'String', :arg
end
dispatch :on_iterable do
param 'Iterable[Variant[String, Numeric]]', :arg
end
# unit function - since the old implementation skipped Numeric values
def on_numeric(n)
n
end
def on_string(s)
s.lstrip
end
def on_iterable(a)
a.map { |x| do_lstrip(x) }
end
def do_lstrip(x)
# x can only be a String or Numeric because type constraints have been automatically applied
x.is_a?(String) ? x.lstrip : x
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/functions/capitalize.rb | lib/puppet/functions/capitalize.rb | # frozen_string_literal: true
# Capitalizes the first character of a String, or the first character of every String in an Iterable value (such as an Array).
#
# This function is compatible with the stdlib function with the same name.
#
# The function does the following:
# * For a `String`, a string is returned in which the first character is uppercase.
# This is done using Ruby system locale which handles some, but not all
# special international up-casing rules (for example German double-s ß is capitalized to "Ss").
# * For an `Iterable[Variant[String, Numeric]]` (for example an `Array`) each value is capitalized and the conversion is not recursive.
# * If the value is `Numeric` it is simply returned (this is for backwards compatibility).
# * An error is raised for all other data types.
#
# Please note: This function relies directly on Ruby's String implementation and as such may not be entirely UTF8 compatible.
# To ensure best compatibility please use this function with Ruby 2.4.0 or greater - https://bugs.ruby-lang.org/issues/10085.
#
# @example Capitalizing a String
# ```puppet
# 'hello'.capitalize()
# capitalize('hello')
# ```
# Would both result in `"Hello"`
#
# @example Capitalizing strings in an Array
# ```puppet
# ['abc', 'bcd'].capitalize()
# capitalize(['abc', 'bcd'])
# ```
# Would both result in `['Abc', 'Bcd']`
#
Puppet::Functions.create_function(:capitalize) do
dispatch :on_numeric do
param 'Numeric', :arg
end
dispatch :on_string do
param 'String', :arg
end
dispatch :on_iterable do
param 'Iterable[Variant[String, Numeric]]', :arg
end
# unit function - since the old implementation skipped Numeric values
def on_numeric(n)
n
end
def on_string(s)
s.capitalize
end
def on_iterable(a)
a.map { |x| do_capitalize(x) }
end
def do_capitalize(x)
# x can only be a String or Numeric because type constraints have been automatically applied
x.is_a?(String) ? x.capitalize : x
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/functions/versioncmp.rb | lib/puppet/functions/versioncmp.rb | # frozen_string_literal: true
require_relative '../../puppet/util/package'
# Compares two version numbers.
#
# Prototype:
#
# $result = versioncmp(a, b)
#
# Where a and b are arbitrary version strings.
#
# Optional parameter ignore_trailing_zeroes is used to ignore unnecessary
# trailing version numbers like .0 or .0.00
#
# This function returns:
#
# * `1` if version a is greater than version b
# * `0` if the versions are equal
# * `-1` if version a is less than version b
#
# @example Using versioncmp
#
# if versioncmp('2.6-1', '2.4.5') > 0 {
# notice('2.6-1 is > than 2.4.5')
# }
#
# This function uses the same version comparison algorithm used by Puppet's
# `package` type.
#
Puppet::Functions.create_function(:versioncmp) do
dispatch :versioncmp do
param 'String', :a
param 'String', :b
optional_param 'Boolean', :ignore_trailing_zeroes
end
def versioncmp(a, b, ignore_trailing_zeroes = false)
Puppet::Util::Package.versioncmp(a, b, ignore_trailing_zeroes)
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/functions/find_template.rb | lib/puppet/functions/find_template.rb | # frozen_string_literal: true
# Finds an existing template from a module and returns its path.
#
# This function accepts an argument that is a String as a `<MODULE NAME>/<TEMPLATE>`
# reference, which searches for `<TEMPLATE>` relative to a module's `templates`
# directory on the primary server. (For example, the reference `mymod/secret.conf.epp`
# will search for the file `<MODULES DIRECTORY>/mymod/templates/secret.conf.epp`.)
#
# The primary use case is for agent-side template rendering with late-bound variables
# resolved, such as from secret stores inaccessible to the primary server, such as
#
# ```
# $variables = {
# 'password' => Deferred('vault_lookup::lookup',
# ['secret/mymod', 'https://vault.example.com:8200']),
# }
#
# # compile the template source into the catalog
# file { '/etc/secrets.conf':
# ensure => file,
# content => Deferred('inline_epp',
# [find_template('mymod/secret.conf.epp').file, $variables]),
# }
# ```
#
#
#
# This function can also accept:
#
# * An absolute String path, which checks for the existence of a template from anywhere on disk.
# * Multiple String arguments, which returns the path of the **first** template
# found, skipping nonexistent files.
# * An array of string paths, which returns the path of the **first** template
# found from the given paths in the array, skipping nonexistent files.
#
# The function returns `undef` if none of the given paths were found.
#
# @since 6.x
#
Puppet::Functions.create_function(:find_template, Puppet::Functions::InternalFunction) do
dispatch :find_template do
scope_param
repeated_param 'String', :paths
end
dispatch :find_template_array do
scope_param
repeated_param 'Array[String]', :paths_array
end
def find_template_array(scope, array)
find_template(scope, *array)
end
def find_template(scope, *args)
args.each do |file|
found = Puppet::Parser::Files.find_template(file, scope.compiler.environment)
if found && Puppet::FileSystem.exist?(found)
return found
end
end
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/functions/inline_epp.rb | lib/puppet/functions/inline_epp.rb | # frozen_string_literal: true
# Evaluates an Embedded Puppet (EPP) template string and returns the rendered
# text result as a String.
#
# `inline_epp('<EPP TEMPLATE STRING>', <PARAMETER HASH>)`
#
# The first argument to this function should be a string containing an EPP
# template. In most cases, the last argument is optional; if used, it should be a
# [hash](https://puppet.com/docs/puppet/latest/lang_data_hash.html) that contains parameters to
# pass to the template.
#
# - See the [template](https://puppet.com/docs/puppet/latest/lang_template.html)
# documentation for general template usage information.
# - See the [EPP syntax](https://puppet.com/docs/puppet/latest/lang_template_epp.html)
# documentation for examples of EPP.
#
# For example, to evaluate an inline EPP template and pass it the `docroot` and
# `virtual_docroot` parameters, call the `inline_epp` function like this:
#
# `inline_epp('docroot: <%= $docroot %> Virtual docroot: <%= $virtual_docroot %>',
# { 'docroot' => '/var/www/html', 'virtual_docroot' => '/var/www/example' })`
#
# Puppet produces a syntax error if you pass more parameters than are declared in
# the template's parameter tag. When passing parameters to a template that
# contains a parameter tag, use the same names as the tag's declared parameters.
#
# Parameters are required only if they are declared in the called template's
# parameter tag without default values. Puppet produces an error if the
# `inline_epp` function fails to pass any required parameter.
#
# An inline EPP template should be written as a single-quoted string or
# [heredoc](https://puppet.com/docs/puppet/latest/lang_data_string.html#heredocs).
# A double-quoted string is subject to expression interpolation before the string
# is parsed as an EPP template.
#
# For example, to evaluate an inline EPP template using a heredoc, call the
# `inline_epp` function like this:
#
# ```puppet
# # Outputs 'Hello given argument planet!'
# inline_epp(@(END), { x => 'given argument' })
# <%- | $x, $y = planet | -%>
# Hello <%= $x %> <%= $y %>!
# END
# ```
#
# @since 4.0.0
#
Puppet::Functions.create_function(:inline_epp, Puppet::Functions::InternalFunction) do
dispatch :inline_epp do
scope_param()
param 'String', :template
optional_param 'Hash[Pattern[/^\w+$/], Any]', :parameters
return_type 'Variant[String, Sensitive[String]]'
end
def inline_epp(scope, template, parameters = nil)
Puppet::Pops::Evaluator::EppEvaluator.inline_epp(scope, template, parameters)
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/functions/regsubst.rb | lib/puppet/functions/regsubst.rb | # frozen_string_literal: true
# Performs regexp replacement on a string or array of strings.
Puppet::Functions.create_function(:regsubst) do
# @param target [String]
# The string or array of strings to operate on. If an array, the replacement will be
# performed on each of the elements in the array, and the return value will be an array.
# @param pattern [String, Regexp, Type[Regexp]]
# The regular expression matching the target string. If you want it anchored at the start
# and or end of the string, you must do that with ^ and $ yourself.
# @param replacement [String, Hash[String, String]]
# Replacement string. Can contain backreferences to what was matched using \\0 (whole match),
# \\1 (first set of parentheses), and so on.
# If the second argument is a Hash, and the matched text is one of its keys, the corresponding value is the replacement string.
# @param flags [Optional[Pattern[/^[GEIM]*$/]], Pattern[/^G?$/]]
# Optional. String of single letter flags for how the regexp is interpreted (E, I, and M cannot be used
# if pattern is a precompiled regexp):
# - *E* Extended regexps
# - *I* Ignore case in regexps
# - *M* Multiline regexps
# - *G* Global replacement; all occurrences of the regexp in each target string will be replaced. Without this, only the first occurrence will be replaced.
# @param encoding [Enum['N','E','S','U']]
# Deprecated and ignored parameter, included only for compatibility.
# @return [Array[String], String] The result of the substitution. Result type is the same as for the target parameter.
# @deprecated
# This method has the optional encoding parameter, which is ignored.
# @example Get the third octet from the node's IP address:
# ```puppet
# $i3 = regsubst($ipaddress,'^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$','\\3')
# ```
dispatch :regsubst_string do
param 'Variant[Array[Variant[String,Sensitive[String]]],Sensitive[Array[Variant[String,Sensitive[String]]]],Variant[String,Sensitive[String]]]', :target
param 'String', :pattern
param 'Variant[String,Hash[String,String]]', :replacement
optional_param 'Optional[Pattern[/^[GEIM]*$/]]', :flags
optional_param "Enum['N','E','S','U']", :encoding
end
# @param target [String, Array[String]]
# The string or array of strings to operate on. If an array, the replacement will be
# performed on each of the elements in the array, and the return value will be an array.
# @param pattern [Regexp, Type[Regexp]]
# The regular expression matching the target string. If you want it anchored at the start
# and or end of the string, you must do that with ^ and $ yourself.
# @param replacement [String, Hash[String, String]]
# Replacement string. Can contain backreferences to what was matched using \\0 (whole match),
# \\1 (first set of parentheses), and so on.
# If the second argument is a Hash, and the matched text is one of its keys, the corresponding value is the replacement string.
# @param flags [Optional[Pattern[/^[GEIM]*$/]], Pattern[/^G?$/]]
# Optional. String of single letter flags for how the regexp is interpreted (E, I, and M cannot be used
# if pattern is a precompiled regexp):
# - *E* Extended regexps
# - *I* Ignore case in regexps
# - *M* Multiline regexps
# - *G* Global replacement; all occurrences of the regexp in each target string will be replaced. Without this, only the first occurrence will be replaced.
# @return [Array[String], String] The result of the substitution. Result type is the same as for the target parameter.
# @example Put angle brackets around each octet in the node's IP address:
# ```puppet
# $x = regsubst($ipaddress, /([0-9]+)/, '<\\1>', 'G')
# ```
dispatch :regsubst_regexp do
param 'Variant[Array[Variant[String,Sensitive[String]]],Sensitive[Array[Variant[String,Sensitive[String]]]],Variant[String,Sensitive[String]]]', :target
param 'Variant[Regexp,Type[Regexp]]', :pattern
param 'Variant[String,Hash[String,String]]', :replacement
optional_param 'Pattern[/^G?$/]', :flags
end
def regsubst_string(target, pattern, replacement, flags = nil, encoding = nil)
if encoding
Puppet.warn_once(
'deprecations', 'regsubst_function_encoding',
_("The regsubst() function's encoding argument has been ignored since Ruby 1.9 and will be removed in a future release")
)
end
re_flags = 0
operation = :sub
unless flags.nil?
flags.split(//).each do |f|
case f
when 'G' then operation = :gsub
when 'E' then re_flags |= Regexp::EXTENDED
when 'I' then re_flags |= Regexp::IGNORECASE
when 'M' then re_flags |= Regexp::MULTILINE
end
end
end
inner_regsubst(target, Regexp.compile(pattern, re_flags), replacement, operation)
end
def regsubst_regexp(target, pattern, replacement, flags = nil)
pattern = pattern.pattern || '' if pattern.is_a?(Puppet::Pops::Types::PRegexpType)
inner_regsubst(target, pattern, replacement, flags == 'G' ? :gsub : :sub)
end
def inner_regsubst(target, re, replacement, op)
if target.is_a?(Puppet::Pops::Types::PSensitiveType::Sensitive) && target.unwrap.is_a?(Array)
# this is a Sensitive Array
target = target.unwrap
target.map do |item|
inner_regsubst(item, re, replacement, op)
end
elsif target.is_a?(Array)
# this is an Array
target.map do |item|
inner_regsubst(item, re, replacement, op)
end
elsif target.is_a?(Puppet::Pops::Types::PSensitiveType::Sensitive)
# this is a Sensitive
target = target.unwrap
target = target.respond_to?(op) ? target.send(op, re, replacement) : target.map { |e| e.send(op, re, replacement) }
Puppet::Pops::Types::PSensitiveType::Sensitive.new(target)
else
# this should be a String
target.respond_to?(op) ? target.send(op, re, replacement) : target.map { |e| e.send(op, re, replacement) }
end
end
private :inner_regsubst
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/functions/group_by.rb | lib/puppet/functions/group_by.rb | # frozen_string_literal: true
# Groups the collection by result of the block. Returns a hash where the keys are the evaluated result from the block
# and the values are arrays of elements in the collection that correspond to the key.
Puppet::Functions.create_function(:group_by) do
# @param collection A collection of things to group.
# @example Group array of strings by length, results in e.g. `{ 1 => [a, b], 2 => [ab] }`
# ```puppet
# [a, b, ab].group_by |$s| { $s.length }
# ```
# @example Group array of strings by length and index, results in e.g. `{1 => ['a'], 2 => ['b', 'ab']}`
# ```puppet
# [a, b, ab].group_by |$i, $s| { $i%2 + $s.length }
# ```
# @example Group hash iterating by key-value pair, results in e.g. `{ 2 => [['a', [1, 2]]], 1 => [['b', [1]]] }`
# ```puppet
# { a => [1, 2], b => [1] }.group_by |$kv| { $kv[1].length }
# ```
# @example Group hash iterating by key and value, results in e.g. `{ 2 => [['a', [1, 2]]], 1 => [['b', [1]]] }`
# ```puppet
# { a => [1, 2], b => [1] }.group_by |$k, $v| { $v.length }
# ```
dispatch :group_by_1 do
required_param 'Collection', :collection
block_param 'Callable[1,1]', :block
return_type 'Hash'
end
dispatch :group_by_2a do
required_param 'Array', :array
block_param 'Callable[2,2]', :block
return_type 'Hash'
end
dispatch :group_by_2 do
required_param 'Collection', :collection
block_param 'Callable[2,2]', :block
return_type 'Hash'
end
def group_by_1(collection)
collection.group_by do |item|
yield(item)
end.freeze
end
def group_by_2a(array)
grouped = array.size.times.zip(array).group_by do |k, v|
yield(k, v)
end
grouped.transform_values do |v|
v.map { |item| item[1] }
end.freeze
end
def group_by_2(collection)
collection.group_by do |k, v|
yield(k, v)
end.freeze
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/functions/break.rb | lib/puppet/functions/break.rb | # frozen_string_literal: true
# Breaks an innermost iteration as if it encountered an end of input.
# This function does not return to the caller.
#
# The signal produced to stop the iteration bubbles up through
# the call stack until either terminating the innermost iteration or
# raising an error if the end of the call stack is reached.
#
# The break() function does not accept an argument.
#
# @example Using `break`
#
# ```puppet
# $data = [1,2,3]
# notice $data.map |$x| { if $x == 3 { break() } $x*10 }
# ```
#
# Would notice the value `[10, 20]`
#
# @example Using a nested `break`
#
# ```puppet
# function break_if_even($x) {
# if $x % 2 == 0 { break() }
# }
# $data = [1,2,3]
# notice $data.map |$x| { break_if_even($x); $x*10 }
# ```
# Would notice the value `[10]`
#
# * Also see functions `next` and `return`
#
# @since 4.8.0
#
Puppet::Functions.create_function(:break) do
dispatch :break_impl do
end
def break_impl
# get file, line if available, else they are set to nil
file, line = Puppet::Pops::PuppetStack.top_of_stack
# PuppetStopIteration contains file and line and is a StopIteration exception
# so it can break a Ruby Kernel#loop or enumeration
#
raise Puppet::Pops::Evaluator::PuppetStopIteration.new(file, line)
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/functions/dig.rb | lib/puppet/functions/dig.rb | # frozen_string_literal: true
# Returns a value for a sequence of given keys/indexes into a structure, such as
# an array or hash.
#
# This function is used to "dig into" a complex data structure by
# using a sequence of keys / indexes to access a value from which
# the next key/index is accessed recursively.
#
# The first encountered `undef` value or key stops the "dig" and `undef` is returned.
#
# An error is raised if an attempt is made to "dig" into
# something other than an `undef` (which immediately returns `undef`), an `Array` or a `Hash`.
#
# @example Using `dig`
#
# ```puppet
# $data = {a => { b => [{x => 10, y => 20}, {x => 100, y => 200}]}}
# notice $data.dig('a', 'b', 1, 'x')
# ```
#
# Would notice the value 100.
#
# This is roughly equivalent to `$data['a']['b'][1]['x']`. However, a standard
# index will return an error and cause catalog compilation failure if any parent
# of the final key (`'x'`) is `undef`. The `dig` function will return `undef`,
# rather than failing catalog compilation. This allows you to check if data
# exists in a structure without mandating that it always exists.
#
# @since 4.5.0
#
Puppet::Functions.create_function(:dig) do
dispatch :dig do
param 'Optional[Collection]', :data
repeated_param 'Any', :arg
end
def dig(data, *args)
walked_path = []
args.reduce(data) do |d, k|
return nil if d.nil? || k.nil?
unless d.is_a?(Array) || d.is_a?(Hash)
t = Puppet::Pops::Types::TypeCalculator.infer(d)
msg = _("The given data does not contain a Collection at %{walked_path}, got '%{type}'") % { walked_path: walked_path, type: t }
error_data = Puppet::DataTypes::Error.new(
msg,
'SLICE_ERROR',
{ 'walked_path' => walked_path, 'value_type' => t },
'EXPECTED_COLLECTION'
)
raise Puppet::ErrorWithData.new(error_data, msg)
end
walked_path << k
if d.is_a?(Array) && !k.is_a?(Integer)
t = Puppet::Pops::Types::TypeCalculator.infer(k)
msg = _("The given data requires an Integer index at %{walked_path}, got '%{type}'") % { walked_path: walked_path, type: t }
error_data = Puppet::DataTypes::Error.new(
msg,
'SLICE_ERROR',
{ 'walked_path' => walked_path, 'index_type' => t },
'EXPECTED_INTEGER_INDEX'
)
raise Puppet::ErrorWithData.new(error_data, msg)
end
d[k]
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/functions/hocon_data.rb | lib/puppet/functions/hocon_data.rb | # frozen_string_literal: true
# The `hocon_data` is a hiera 5 `data_hash` data provider function.
# See [the configuration guide documentation](https://puppet.com/docs/puppet/latest/hiera_config_yaml_5.html#configuring-a-hierarchy-level-built-in-backends) for
# how to use this function.
#
# Note that this function is not supported without a hocon library being present.
#
# @since 4.9.0
#
Puppet::Functions.create_function(:hocon_data) do
unless Puppet.features.hocon?
raise Puppet::DataBinding::LookupError, _('Lookup using Hocon data_hash function is not supported without hocon library')
end
require 'hocon'
require 'hocon/config_error'
dispatch :hocon_data do
param 'Struct[{path=>String[1]}]', :options
param 'Puppet::LookupContext', :context
end
argument_mismatch :missing_path do
param 'Hash', :options
param 'Puppet::LookupContext', :context
end
def hocon_data(options, context)
path = options['path']
context.cached_file_data(path) do |content|
Hocon.parse(content)
rescue Hocon::ConfigError => ex
raise Puppet::DataBinding::LookupError, _("Unable to parse (%{path}): %{message}") % { path: path, message: ex.message }
end
end
def missing_path(options, context)
"one of 'path', 'paths' 'glob', 'globs' or 'mapped_paths' must be declared in hiera.yaml when using this data_hash function"
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/functions/alert.rb | lib/puppet/functions/alert.rb | # frozen_string_literal: true
# Logs a message on the server at level `alert`.
Puppet::Functions.create_function(:alert, Puppet::Functions::InternalFunction) do
# @param values The values to log.
# @return [Undef]
dispatch :alert do
scope_param
repeated_param 'Any', :values
return_type 'Undef'
end
def alert(scope, *values)
Puppet::Util::Log.log_func(scope, :alert, 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/functions/then.rb | lib/puppet/functions/then.rb | # frozen_string_literal: true
# Calls a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html)
# with the given argument unless the argument is `undef`.
# Returns `undef` if the argument is `undef`, and otherwise the result of giving the
# argument to the lambda.
#
# This is useful to process a sequence of operations where an intermediate
# result may be `undef` (which makes the entire sequence `undef`).
# The `then` function is especially useful with the function `dig` which
# performs in a similar way "digging out" a value in a complex structure.
#
# @example Using `dig` and `then`
#
# ```puppet
# $data = {a => { b => [{x => 10, y => 20}, {x => 100, y => 200}]}}
# notice $data.dig(a, b, 1, x).then |$x| { $x * 2 }
# ```
#
# Would notice the value 200
#
# Contrast this with:
#
# ```puppet
# $data = {a => { b => [{x => 10, y => 20}, {not_x => 100, why => 200}]}}
# notice $data.dig(a, b, 1, x).then |$x| { $x * 2 }
# ```
#
# Which would notice `undef` since the last lookup of 'x' results in `undef` which
# is returned (without calling the lambda given to the `then` function).
#
# As a result there is no need for conditional logic or a temporary (non local)
# variable as the result is now either the wanted value (`x`) multiplied
# by 2 or `undef`.
#
# Calls to `then` can be chained. In the next example, a structure is using an offset based on
# using 1 as the index to the first element (instead of 0 which is used in the language).
# We are not sure if user input actually contains an index at all, or if it is
# outside the range of available names.args.
#
# @example Chaining calls to the `then` function
#
# ```puppet
# # Names to choose from
# $names = ['Ringo', 'Paul', 'George', 'John']
#
# # Structure where 'beatle 2' is wanted (but where the number refers
# # to 'Paul' because input comes from a source using 1 for the first
# # element).
#
# $data = ['singer', { beatle => 2 }]
# $picked = assert_type(String,
# # the data we are interested in is the second in the array,
# # a hash, where we want the value of the key 'beatle'
# $data.dig(1, 'beatle')
# # and we want the index in $names before the given index
# .then |$x| { $names[$x-1] }
# # so we can construct a string with that beatle's name
# .then |$x| { "Picked Beatle '${x}'" }
# )
# notice $picked
# ```
#
# Would notice "Picked Beatle 'Paul'", and would raise an error if the result
# was not a String.
#
# * Since 4.5.0
#
Puppet::Functions.create_function(:then) do
dispatch :then do
param 'Any', :arg
block_param 'Callable[1,1]', :block
end
def then(arg)
return nil if arg.nil?
yield(arg)
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/functions/reverse_each.rb | lib/puppet/functions/reverse_each.rb | # frozen_string_literal: true
# Reverses the order of the elements of something that is iterable and optionally runs a
# [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) for each
# element.
#
# This function takes one to two arguments:
#
# 1. An `Iterable` that the function will iterate over.
# 2. An optional lambda, which the function calls for each element in the first argument. It must
# request one parameter.
#
# @example Using the `reverse_each` function
#
# ```puppet
# $data.reverse_each |$parameter| { <PUPPET CODE BLOCK> }
# ```
#
# or
#
# ```puppet
# $reverse_data = $data.reverse_each
# ```
#
# or
#
# ```puppet
# reverse_each($data) |$parameter| { <PUPPET CODE BLOCK> }
# ```
#
# or
#
# ```puppet
# $reverse_data = reverse_each($data)
# ```
#
# When no second argument is present, Puppet returns an `Iterable` that represents the reverse
# order of its first argument. This allows methods on `Iterable` to be chained.
#
# When a lambda is given as the second argument, Puppet iterates the first argument in reverse
# order and passes each value in turn to the lambda, then returns `undef`.
#
# @example Using the `reverse_each` function with an array and a one-parameter lambda
#
# ```puppet
# # Puppet will log a notice for each of the three items
# # in $data in reverse order.
# $data = [1,2,3]
# $data.reverse_each |$item| { notice($item) }
# ```
#
# When no second argument is present, Puppet returns a new `Iterable` which allows it to
# be directly chained into another function that takes an `Iterable` as an argument.
#
# @example Using the `reverse_each` function chained with a `map` function.
#
# ```puppet
# # For the array $data, return an array containing each
# # value multiplied by 10 in reverse order
# $data = [1,2,3]
# $transformed_data = $data.reverse_each.map |$item| { $item * 10 }
# # $transformed_data is set to [30,20,10]
# ```
#
# @example Using `reverse_each` function chained with a `map` in alternative syntax
#
# ```puppet
# # For the array $data, return an array containing each
# # value multiplied by 10 in reverse order
# $data = [1,2,3]
# $transformed_data = map(reverse_each($data)) |$item| { $item * 10 }
# # $transformed_data is set to [30,20,10]
# ```
#
# @since 4.4.0
#
Puppet::Functions.create_function(:reverse_each) do
dispatch :reverse_each do
param 'Iterable', :iterable
end
dispatch :reverse_each_block do
param 'Iterable', :iterable
block_param 'Callable[1,1]', :block
end
def reverse_each(iterable)
# produces an Iterable
Puppet::Pops::Types::Iterable.asserted_iterable(self, iterable, true).reverse_each
end
def reverse_each_block(iterable, &block)
Puppet::Pops::Types::Iterable.asserted_iterable(self, iterable).reverse_each(&block)
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/functions/call.rb | lib/puppet/functions/call.rb | # frozen_string_literal: true
# Calls an arbitrary Puppet function by name.
#
# This function takes one mandatory argument and one or more optional arguments:
#
# 1. A string corresponding to a function name.
# 2. Any number of arguments to be passed to the called function.
# 3. An optional lambda, if the function being called supports it.
#
# This function can also be used to resolve a `Deferred` given as
# the only argument to the function (does not accept arguments nor
# a block).
#
# @example Using the `call` function
#
# ```puppet
# $a = 'notice'
# call($a, 'message')
# ```
#
# @example Using the `call` function with a lambda
#
# ```puppet
# $a = 'each'
# $b = [1,2,3]
# call($a, $b) |$item| {
# notify { $item: }
# }
# ```
#
# The `call` function can be used to call either Ruby functions or Puppet language
# functions.
#
# When used with `Deferred` values, the deferred value can either describe
# a function call, or a dig into a variable.
#
# @example Resolving a deferred function call
#
# ```puppet
# $d = Deferred('join', [[1,2,3], ':']) # A future call to join that joins the arguments 1,2,3 with ':'
# notice($d.call())
# ```
#
# Would notice the string "1:2:3".
#
# @example Resolving a deferred variable value with optional dig into its structure
#
# ```puppet
# $d = Deferred('$facts', ['processors', 'count'])
# notice($d.call())
# ```
#
# Would notice the value of `$facts['processors']['count']` at the time when the `call` is made.
#
# * Deferred values supported since Puppet 6.0
#
# @since 5.0.0
#
Puppet::Functions.create_function(:call, Puppet::Functions::InternalFunction) do
dispatch :call_impl_block do
scope_param
param 'String', :function_name
repeated_param 'Any', :arguments
optional_block_param
end
dispatch :call_deferred do
scope_param
param 'Deferred', :deferred
end
def call_impl_block(scope, function_name, *args, &block)
# The call function must be able to call functions loaded by any loader visible from the calling scope.
Puppet::Pops::Parser::EvaluatingParser.new.evaluator.external_call_function(function_name, args, scope, &block)
end
def call_deferred(scope, deferred)
Puppet::Pops::Evaluator::DeferredResolver.resolve(deferred, scope.compiler)
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/functions/flatten.rb | lib/puppet/functions/flatten.rb | # frozen_string_literal: true
# Returns a flat Array produced from its possibly deeply nested given arguments.
#
# One or more arguments of any data type can be given to this function.
# The result is always a flat array representation where any nested arrays are recursively flattened.
#
# @example Typical use of `flatten()`
#
# ```puppet
# flatten(['a', ['b', ['c']]])
# # Would return: ['a','b','c']
# ```
#
# To flatten other kinds of iterables (for example hashes, or intermediate results like from a `reverse_each`)
# first convert the result to an array using `Array($x)`, or `$x.convert_to(Array)`. See the `new` function
# for details and options when performing a conversion.
#
# @example Flattening a Hash
#
# ```puppet
# $hsh = { a => 1, b => 2}
#
# # -- without conversion
# $hsh.flatten()
# # Would return [{a => 1, b => 2}]
#
# # -- with conversion
# $hsh.convert_to(Array).flatten()
# # Would return [a,1,b,2]
#
# flatten(Array($hsh))
# # Would also return [a,1,b,2]
# ```
#
# @example Flattening and concatenating at the same time
#
# ```puppet
# $a1 = [1, [2, 3]]
# $a2 = [[4,[5,6]]
# $x = 7
# flatten($a1, $a2, $x)
# # would return [1,2,3,4,5,6,7]
# ```
#
# @example Transforming to Array if not already an Array
#
# ```puppet
# flatten(42)
# # Would return [42]
#
# flatten([42])
# # Would also return [42]
# ```
#
# @since 5.5.0 support for flattening and concatenating at the same time
#
Puppet::Functions.create_function(:flatten) do
dispatch :flatten_args do
repeated_param 'Any', :args
end
def flatten_args(*args)
args.flatten()
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/functions/with.rb | lib/puppet/functions/with.rb | # frozen_string_literal: true
# Calls a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html)
# with the given arguments and returns the result.
#
# Since a lambda's scope is
# [local](https://puppet.com/docs/puppet/latest/lang_lambdas.html#lambda-scope)
# to the lambda, you can use the `with` function to create private blocks of code within a
# class using variables whose values cannot be accessed outside of the lambda.
#
# @example Using `with`
#
# ```puppet
# # Concatenate three strings into a single string formatted as a list.
# $fruit = with("apples", "oranges", "bananas") |$x, $y, $z| {
# "${x}, ${y}, and ${z}"
# }
# $check_var = $x
# # $fruit contains "apples, oranges, and bananas"
# # $check_var is undefined, as the value of $x is local to the lambda.
# ```
#
# @since 4.0.0
#
Puppet::Functions.create_function(:with) do
dispatch :with do
repeated_param 'Any', :arg
block_param
end
def with(*args)
yield(*args)
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/functions/round.rb | lib/puppet/functions/round.rb | # frozen_string_literal: true
# Returns an `Integer` value rounded to the nearest value.
# Takes a single `Numeric` value as an argument.
#
# @example 'rounding a value'
#
# ```puppet
# notice(round(2.9)) # would notice 3
# notice(round(2.1)) # would notice 2
# notice(round(-2.9)) # would notice -3
# ```
#
Puppet::Functions.create_function(:round) do
dispatch :on_numeric do
param 'Numeric', :val
end
def on_numeric(x)
if x > 0
Integer(x + 0.5)
else
Integer(x - 0.5)
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/functions/all.rb | lib/puppet/functions/all.rb | # frozen_string_literal: true
# Runs a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html)
# repeatedly using each value in a data structure until the lambda returns a non "truthy" value which
# makes the function return `false`, or if the end of the iteration is reached, `true` is returned.
#
# This function takes two mandatory arguments, in this order:
#
# 1. An array, hash, or other iterable object that the function will iterate over.
# 2. A lambda, which the function calls for each element in the first argument. It can
# request one or two parameters.
#
# @example Using the `all` function
#
# `$data.all |$parameter| { <PUPPET CODE BLOCK> }`
#
# or
#
# `all($data) |$parameter| { <PUPPET CODE BLOCK> }`
#
# @example Using the `all` function with an Array and a one-parameter lambda
#
# ```puppet
# # For the array $data, run a lambda that checks that all values are multiples of 10
# $data = [10, 20, 30]
# notice $data.all |$item| { $item % 10 == 0 }
# ```
#
# Would notice `true`.
#
# When the first argument is a `Hash`, Puppet passes each key and value pair to the lambda
# as an array in the form `[key, value]`.
#
# @example Using the `all` function with a `Hash` and a one-parameter lambda
#
# ```puppet
# # For the hash $data, run a lambda using each item as a key-value array
# $data = { 'a_0'=> 10, 'b_1' => 20 }
# notice $data.all |$item| { $item[1] % 10 == 0 }
# ```
#
# Would notice `true` if all values in the hash are multiples of 10.
#
# When the lambda accepts two arguments, the first argument gets the index in an array
# or the key from a hash, and the second argument the value.
#
#
# @example Using the `all` function with a hash and a two-parameter lambda
#
# ```puppet
# # Check that all values are a multiple of 10 and keys start with 'abc'
# $data = {abc_123 => 10, abc_42 => 20, abc_blue => 30}
# notice $data.all |$key, $value| { $value % 10 == 0 and $key =~ /^abc/ }
# ```
#
# Would notice `true`.
#
# For an general examples that demonstrates iteration, see the Puppet
# [iteration](https://puppet.com/docs/puppet/latest/lang_iteration.html)
# documentation.
#
# @since 5.2.0
#
Puppet::Functions.create_function(:all) do
dispatch :all_Hash_2 do
param 'Hash[Any, Any]', :hash
block_param 'Callable[2,2]', :block
end
dispatch :all_Hash_1 do
param 'Hash[Any, Any]', :hash
block_param 'Callable[1,1]', :block
end
dispatch :all_Enumerable_2 do
param 'Iterable', :enumerable
block_param 'Callable[2,2]', :block
end
dispatch :all_Enumerable_1 do
param 'Iterable', :enumerable
block_param 'Callable[1,1]', :block
end
def all_Hash_1(hash)
hash.each_pair.all? { |x| yield(x) }
end
def all_Hash_2(hash)
hash.each_pair.all? { |x, y| yield(x, y) }
end
def all_Enumerable_1(enumerable)
Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable).all? { |e| yield(e) }
end
def all_Enumerable_2(enumerable)
enum = Puppet::Pops::Types::Iterable.asserted_iterable(self, enumerable)
if enum.hash_style?
enum.all? { |entry| yield(*entry) }
else
enum.each_with_index { |e, i| return false unless yield(i, e) }
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/network/authconfig.rb | lib/puppet/network/authconfig.rb | # frozen_string_literal: true
module Puppet
class Network::AuthConfig
def self.authprovider_class=(_)
# legacy auth is not supported, ignore
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/network/format.rb | lib/puppet/network/format.rb | # frozen_string_literal: true
require_relative '../../puppet/confiner'
# A simple class for modeling encoding formats for moving
# instances around the network.
class Puppet::Network::Format
include Puppet::Confiner
attr_reader :name, :mime
attr_accessor :intern_method, :render_method, :intern_multiple_method, :render_multiple_method, :weight, :required_methods, :extension, :charset
def init_attribute(name, default)
value = @options.delete(name)
value = default if value.nil?
send(name.to_s + "=", value)
end
def initialize(name, options = {}, &block)
@name = name.to_s.downcase.intern
@options = options
# This must be done early the values can be used to set required_methods
define_method_names
method_list = {
:intern_method => "from_#{name}",
:intern_multiple_method => "from_multiple_#{name}",
:render_multiple_method => "to_multiple_#{name}",
:render_method => "to_#{name}"
}
init_attribute(:mime, "text/#{name}")
init_attribute(:weight, 5)
init_attribute(:required_methods, method_list.keys)
init_attribute(:extension, name.to_s)
init_attribute(:charset, nil)
method_list.each do |method, value|
init_attribute(method, value)
end
raise ArgumentError, _("Unsupported option(s) %{options_list}") % { options_list: @options.keys } unless @options.empty?
@options = nil
instance_eval(&block) if block_given?
end
def intern(klass, text)
return klass.send(intern_method, text) if klass.respond_to?(intern_method)
raise NotImplementedError, "#{klass} does not respond to #{intern_method}; can not intern instances from #{mime}"
end
def intern_multiple(klass, text)
return klass.send(intern_multiple_method, text) if klass.respond_to?(intern_multiple_method)
raise NotImplementedError, "#{klass} does not respond to #{intern_multiple_method}; can not intern multiple instances from #{mime}"
end
def mime=(mime)
@mime = mime.to_s.downcase
end
def render(instance)
return instance.send(render_method) if instance.respond_to?(render_method)
raise NotImplementedError, "#{instance.class} does not respond to #{render_method}; can not render instances to #{mime}"
end
def render_multiple(instances)
# This method implicitly assumes that all instances are of the same type.
return instances[0].class.send(render_multiple_method, instances) if instances[0].class.respond_to?(render_multiple_method)
raise NotImplementedError, _("%{klass} does not respond to %{method}; can not render multiple instances to %{mime}") %
{ klass: instances[0].class, method: render_multiple_method, mime: mime }
end
def required_methods_present?(klass)
[:intern_method, :intern_multiple_method, :render_multiple_method].each do |name|
return false unless required_method_present?(name, klass, :class)
end
return false unless required_method_present?(:render_method, klass, :instance)
true
end
def supported?(klass)
suitable? and required_methods_present?(klass)
end
def to_s
"Puppet::Network::Format[#{name}]"
end
private
def define_method_names
@intern_method = "from_#{name}"
@render_method = "to_#{name}"
@intern_multiple_method = "from_multiple_#{name}"
@render_multiple_method = "to_multiple_#{name}"
end
def required_method_present?(name, klass, type)
return true unless required_methods.include?(name)
method = send(name)
(type == :class ? klass.respond_to?(method) : klass.method_defined?(method))
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/network/format_support.rb | lib/puppet/network/format_support.rb | # frozen_string_literal: true
require_relative '../../puppet/network/format_handler'
# Provides network serialization support when included
# @api public
module Puppet::Network::FormatSupport
def self.included(klass)
klass.extend(ClassMethods)
end
module ClassMethods
def convert_from(format, data)
get_format(format).intern(self, data)
rescue => err
# TRANSLATORS "intern" is a function name and should not be translated
raise Puppet::Network::FormatHandler::FormatError, _("Could not intern from %{format}: %{err}") % { format: format, err: err }, err.backtrace
end
def convert_from_multiple(format, data)
get_format(format).intern_multiple(self, data)
rescue => err
# TRANSLATORS "intern_multiple" is a function name and should not be translated
raise Puppet::Network::FormatHandler::FormatError, _("Could not intern_multiple from %{format}: %{err}") % { format: format, err: err }, err.backtrace
end
def render_multiple(format, instances)
get_format(format).render_multiple(instances)
rescue => err
# TRANSLATORS "render_multiple" is a function name and should not be translated
raise Puppet::Network::FormatHandler::FormatError, _("Could not render_multiple to %{format}: %{err}") % { format: format, err: err }, err.backtrace
end
def default_format
supported_formats[0]
end
def support_format?(name)
Puppet::Network::FormatHandler.format(name).supported?(self)
end
def supported_formats
result = format_handler.formats.collect do |f|
format_handler.format(f)
end.find_all do |f|
f.supported?(self)
end.sort do |a, b|
# It's an inverse sort -- higher weight formats go first.
b.weight <=> a.weight
end
result = put_preferred_format_first(result).map(&:name)
Puppet.debug { "#{friendly_name} supports formats: #{result.join(' ')}" }
result
end
# @api private
def get_format(format_name)
format_handler.format_for(format_name)
end
private
def format_handler
Puppet::Network::FormatHandler
end
def friendly_name
if respond_to? :indirection
indirection.name
else
self
end
end
def put_preferred_format_first(list)
preferred_format = Puppet.settings[:preferred_serialization_format].to_s
preferred = list.select { |format|
format.mime.end_with?(preferred_format)
}
if preferred.empty?
Puppet.debug { "Value of 'preferred_serialization_format' (#{preferred_format}) is invalid for #{friendly_name}, using default (#{list.first.name})" }
else
list = preferred + list.reject { |format|
format.mime.end_with?(preferred_format)
}
end
list
end
end
def to_msgpack(*args)
to_data_hash.to_msgpack(*args)
end
# @deprecated, use to_json
def to_pson(*args)
to_data_hash.to_pson(*args)
end
def to_json(*args)
Puppet::Util::Json.dump(to_data_hash, *args)
end
def render(format = nil)
format ||= self.class.default_format
self.class.get_format(format).render(self)
rescue => err
# TRANSLATORS "render" is a function name and should not be translated
raise Puppet::Network::FormatHandler::FormatError, _("Could not render to %{format}: %{err}") % { format: format, err: err }, err.backtrace
end
def mime(format = nil)
format ||= self.class.default_format
self.class.get_format(format).mime
rescue => err
# TRANSLATORS "mime" is a function name and should not be translated
raise Puppet::Network::FormatHandler::FormatError, _("Could not mime to %{format}: %{err}") % { format: format, err: err }, err.backtrace
end
def support_format?(name)
self.class.support_format?(name)
end
# @comment Document to_data_hash here as it is called as a hook from to_msgpack if it exists
# @!method to_data_hash(*args)
# @api public
# @abstract
# This method may be implemented to return a hash object that is used for serializing.
# The object returned by this method should contain all the info needed to instantiate it again.
# If the method exists it will be called from to_msgpack and other serialization methods.
# @return [Hash]
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/network/http.rb | lib/puppet/network/http.rb | # frozen_string_literal: true
# This module is used to handle puppet REST requests in puppetserver.
module Puppet::Network::HTTP
HEADER_ENABLE_PROFILING = "X-Puppet-Profiling"
HEADER_PUPPET_VERSION = "X-Puppet-Version"
SERVER_URL_PREFIX = "/puppet"
SERVER_URL_VERSIONS = "v3"
MASTER_URL_PREFIX = SERVER_URL_PREFIX
MASTER_URL_VERSIONS = SERVER_URL_VERSIONS
CA_URL_PREFIX = "/puppet-ca"
CA_URL_VERSIONS = "v1"
require_relative '../../puppet/network/authconfig'
require_relative '../../puppet/network/authorization'
require_relative 'http/issues'
require_relative 'http/error'
require_relative 'http/route'
require_relative 'http/api'
require_relative 'http/api/master'
require_relative 'http/api/master/v3'
require_relative 'http/handler'
require_relative 'http/response'
require_relative 'http/request'
require_relative 'http/memory_response'
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/network/uri.rb | lib/puppet/network/uri.rb | # frozen_string_literal: true
# This module holds funtions for network URI's
module Puppet::Network::Uri
# Mask credentials in given URI or address as string. Resulting string will
# contain '***' in place of password. It will only be replaced if actual
# password is given.
#
# @param uri [URI|String] an uri or address to be masked
# @return [String] a masked url
def mask_credentials(uri)
if uri.is_a? URI
uri = uri.dup
else
uri = URI.parse(uri)
end
uri.password = '***' unless uri.password.nil?
uri.to_s
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/network/http_pool.rb | lib/puppet/network/http_pool.rb | # frozen_string_literal: true
require_relative '../../puppet/network/http/connection'
module Puppet::Network; end
# This module is deprecated.
#
# @api public
# @deprecated Use {Puppet::HTTP::Client} instead.
#
module Puppet::Network::HttpPool
@http_client_class = Puppet::Network::HTTP::Connection
def self.http_client_class
@http_client_class
end
def self.http_client_class=(klass)
@http_client_class = klass
end
# Retrieve a connection for the given host and port.
#
# @param host [String] The hostname to connect to
# @param port [Integer] The port on the host to connect to
# @param use_ssl [Boolean] Whether to use an SSL connection
# @param verify_peer [Boolean] Whether to verify the peer credentials, if possible. Verification will not take place if the CA certificate is missing.
# @return [Puppet::Network::HTTP::Connection]
#
# @deprecated Use {Puppet.runtime[:http]} instead.
# @api public
#
def self.http_instance(host, port, use_ssl = true, verify_peer = true)
Puppet.warn_once('deprecations', self, "The method 'Puppet::Network::HttpPool.http_instance' is deprecated. Use Puppet.runtime[:http] instead")
if verify_peer
verifier = Puppet::SSL::Verifier.new(host, nil)
else
ssl = Puppet::SSL::SSLProvider.new
verifier = Puppet::SSL::Verifier.new(host, ssl.create_insecure_context)
end
http_client_class.new(host, port, use_ssl: use_ssl, verifier: verifier)
end
# Retrieve a connection for the given host and port.
#
# @param host [String] The host to connect to
# @param port [Integer] The port to connect to
# @param use_ssl [Boolean] Whether to use SSL, defaults to `true`.
# @param ssl_context [Puppet::SSL:SSLContext, nil] The ssl context to use
# when making HTTPS connections. Required when `use_ssl` is `true`.
# @return [Puppet::Network::HTTP::Connection]
#
# @deprecated Use {Puppet.runtime[:http]} instead.
# @api public
#
def self.connection(host, port, use_ssl: true, ssl_context: nil)
Puppet.warn_once('deprecations', self, "The method 'Puppet::Network::HttpPool.connection' is deprecated. Use Puppet.runtime[:http] instead")
if use_ssl
unless ssl_context
# TRANSLATORS 'ssl_context' is an argument and should not be translated
raise ArgumentError, _("An ssl_context is required when connecting to 'https://%{host}:%{port}'") % { host: host, port: port }
end
verifier = Puppet::SSL::Verifier.new(host, ssl_context)
http_client_class.new(host, port, use_ssl: true, verifier: verifier)
else
if ssl_context
# TRANSLATORS 'ssl_context' is an argument and should not be translated
Puppet.warning(_("An ssl_context is unnecessary when connecting to 'http://%{host}:%{port}' and will be ignored") % { host: host, port: port })
end
http_client_class.new(host, port, use_ssl: false)
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/network/client_request.rb | lib/puppet/network/client_request.rb | # frozen_string_literal: true
module Puppet::Network # :nodoc:
# A struct-like class for passing around a client request. It's mostly
# just used for validation and authorization.
class ClientRequest
attr_accessor :name, :ip, :authenticated, :handler, :method
def authenticated?
authenticated
end
# A common way of talking about the full call. Individual servers
# are responsible for setting the values correctly, but this common
# format makes it possible to check rights.
def call
raise ArgumentError, _("Request is not set up; cannot build call") unless handler and method
[handler, method].join(".")
end
def initialize(name, ip, authenticated)
@name = name
@ip = ip
@authenticated = authenticated
end
def to_s
"#{name}(#{ip})"
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/network/authorization.rb | lib/puppet/network/authorization.rb | # frozen_string_literal: true
module Puppet::Network
module Authorization
class << self
# This method is deprecated and will be removed in a future release.
def authconfigloader_class=(klass)
@authconfigloader_class = klass
end
# Verify something external to puppet is authorizing REST requests, so
# we don't fail insecurely due to misconfiguration.
def check_external_authorization(method, path)
if @authconfigloader_class.nil?
message = "Forbidden request: #{path} (method #{method})"
raise Puppet::Network::HTTP::Error::HTTPNotAuthorizedError.new(message, Puppet::Network::HTTP::Issues::FAILED_AUTHORIZATION)
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/network/format_handler.rb | lib/puppet/network/format_handler.rb | # frozen_string_literal: true
require 'yaml'
require_relative '../../puppet/network'
require_relative '../../puppet/network/format'
module Puppet::Network::FormatHandler
class FormatError < Puppet::Error; end
ALL_MEDIA_TYPES = '*/*'
@formats = {}
def self.create(*args, &block)
instance = Puppet::Network::Format.new(*args, &block)
@formats[instance.name] = instance
instance
end
def self.create_serialized_formats(name, options = {}, &block)
["application/x-#{name}", "application/#{name}", "text/x-#{name}", "text/#{name}"].each { |mime_type|
create name, { :mime => mime_type }.update(options), &block
}
end
def self.format(name)
@formats[name.to_s.downcase.intern]
end
def self.format_for(name)
name = format_to_canonical_name(name)
format(name)
end
def self.format_by_extension(ext)
@formats.each do |_name, format|
return format if format.extension == ext
end
nil
end
# Provide a list of all formats.
def self.formats
@formats.keys
end
# Return a format capable of handling the provided mime type.
def self.mime(mimetype)
mimetype = mimetype.to_s.downcase
@formats.values.find { |format| format.mime == mimetype }
end
# Return a format name given:
# * a format name
# * a mime-type
# * a format instance
def self.format_to_canonical_name(format)
case format
when Puppet::Network::Format
out = format
when %r{\w+/\w+}
out = mime(format)
else
out = format(format)
end
if out.nil?
raise ArgumentError, _("No format matches the given format name or mime-type (%{format})") % { format: format }
end
out.name
end
# Determine which of the accepted formats should be used given what is supported.
#
# @param accepted [Array<String, Symbol>] the accepted formats in a form a
# that generally conforms to an HTTP Accept header. Any quality specifiers
# are ignored and instead the formats are simply in strict preference order
# (most preferred is first)
# @param supported [Array<Symbol>] the names of the supported formats (the
# most preferred format is first)
# @return [Array<Puppet::Network::Format>] the most suitable formats that
# are both accepted and supported
# @api private
def self.most_suitable_formats_for(accepted, supported)
accepted.collect do |format|
format.to_s.sub(/;q=.*$/, '')
end.filter_map do |format|
if format == ALL_MEDIA_TYPES
supported.first
else
format_to_canonical_name_or_nil(format)
end
end.find_all do |format|
supported.include?(format)
end.collect do |format|
format_for(format)
end
end
# @api private
def self.format_to_canonical_name_or_nil(format)
format_to_canonical_name(format)
rescue ArgumentError
nil
end
end
require_relative '../../puppet/network/formats'
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/network/formats.rb | lib/puppet/network/formats.rb | # frozen_string_literal: true
require_relative '../../puppet/network/format_handler'
require_relative '../../puppet/util/json'
Puppet::Network::FormatHandler.create_serialized_formats(:msgpack, :weight => 20, :mime => "application/x-msgpack", :required_methods => [:render_method, :intern_method], :intern_method => :from_data_hash) do
confine :feature => :msgpack
def intern(klass, text)
data = MessagePack.unpack(text)
return data if data.is_a?(klass)
klass.from_data_hash(data)
end
def intern_multiple(klass, text)
MessagePack.unpack(text).collect do |data|
klass.from_data_hash(data)
end
end
def render_multiple(instances)
instances.to_msgpack
end
end
Puppet::Network::FormatHandler.create_serialized_formats(:yaml) do
def allowed_yaml_classes
@allowed_yaml_classes ||= [
Puppet::Node::Facts,
Puppet::Node,
Puppet::Transaction::Report,
Puppet::Resource,
Puppet::Resource::Catalog
]
end
def intern(klass, text)
data = Puppet::Util::Yaml.safe_load(text, allowed_yaml_classes)
data_to_instance(klass, data)
rescue Puppet::Util::Yaml::YamlLoadError => e
raise Puppet::Network::FormatHandler::FormatError, _("Serialized YAML did not contain a valid instance of %{klass}: %{message}") % { klass: klass, message: e.message }
end
def intern_multiple(klass, text)
data = Puppet::Util::Yaml.safe_load(text, allowed_yaml_classes)
unless data.respond_to?(:collect)
raise Puppet::Network::FormatHandler::FormatError, _("Serialized YAML did not contain a collection of instances when calling intern_multiple")
end
data.collect do |datum|
data_to_instance(klass, datum)
end
rescue Puppet::Util::Yaml::YamlLoadError => e
raise Puppet::Network::FormatHandler::FormatError, _("Serialized YAML did not contain a valid instance of %{klass}: %{message}") % { klass: klass, message: e.message }
end
def data_to_instance(klass, data)
return data if data.is_a?(klass)
unless data.is_a? Hash
raise Puppet::Network::FormatHandler::FormatError, _("Serialized YAML did not contain a valid instance of %{klass}") % { klass: klass }
end
klass.from_data_hash(data)
end
def render(instance)
instance.to_yaml
end
# Yaml monkey-patches Array, so this works.
def render_multiple(instances)
instances.to_yaml
end
def supported?(klass)
true
end
end
Puppet::Network::FormatHandler.create(:s, :mime => "text/plain", :charset => Encoding::UTF_8, :extension => "txt")
# By default, to_binary is called to render and from_binary called to intern. Note unlike
# text-based formats (json, yaml, etc), we don't use to_data_hash for binary.
Puppet::Network::FormatHandler.create(:binary, :mime => "application/octet-stream", :weight => 1,
:required_methods => [:render_method, :intern_method]) do
end
# PSON is deprecated
Puppet::Network::FormatHandler.create_serialized_formats(:pson, :weight => 10, :required_methods => [:render_method, :intern_method], :intern_method => :from_data_hash) do
confine :feature => :pson
def intern(klass, text)
data_to_instance(klass, PSON.parse(text))
end
def intern_multiple(klass, text)
PSON.parse(text).collect do |data|
data_to_instance(klass, data)
end
end
# PSON monkey-patches Array, so this works.
def render_multiple(instances)
instances.to_pson
end
# If they pass class information, we want to ignore it.
# This is required for compatibility with Puppet 3.x
def data_to_instance(klass, data)
d = data['data'] if data.is_a?(Hash)
if d
data = d
end
return data if data.is_a?(klass)
klass.from_data_hash(data)
end
end
Puppet::Network::FormatHandler.create_serialized_formats(:json, :mime => 'application/json', :charset => Encoding::UTF_8, :weight => 15, :required_methods => [:render_method, :intern_method], :intern_method => :from_data_hash) do
def intern(klass, text)
data_to_instance(klass, Puppet::Util::Json.load(text))
end
def intern_multiple(klass, text)
Puppet::Util::Json.load(text).collect do |data|
data_to_instance(klass, data)
end
end
def render_multiple(instances)
Puppet::Util::Json.dump(instances)
end
# Unlike PSON, we do not need to unwrap the data envelope, because legacy 3.x agents
# have never supported JSON
def data_to_instance(klass, data)
return data if data.is_a?(klass)
klass.from_data_hash(data)
end
end
# This is really only ever going to be used for Catalogs.
Puppet::Network::FormatHandler.create_serialized_formats(:dot, :required_methods => [:render_method])
Puppet::Network::FormatHandler.create(:console,
:mime => 'text/x-console-text',
:weight => 0) do
def json
@json ||= Puppet::Network::FormatHandler.format(:json)
end
def render(datum)
return datum if datum.is_a?(String) || datum.is_a?(Numeric)
# Simple hash to table
if datum.is_a?(Hash) && datum.keys.all? { |x| x.is_a?(String) || x.is_a?(Numeric) }
output = ''.dup
column_a = datum.empty? ? 2 : datum.map { |k, _v| k.to_s.length }.max + 2
datum.sort_by { |k, _v| k.to_s }.each do |key, value|
output << key.to_s.ljust(column_a)
output << json.render(value)
.chomp.gsub(/\n */) { |x| x + (' ' * column_a) }
output << "\n"
end
return output
end
# Print one item per line for arrays
if datum.is_a? Array
output = ''.dup
datum.each do |item|
output << item.to_s
output << "\n"
end
return output
end
# ...or pretty-print the inspect outcome.
Puppet::Util::Json.dump(datum, :pretty => true, :quirks_mode => true)
end
def render_multiple(data)
data.collect(&:render).join("\n")
end
end
Puppet::Network::FormatHandler.create(:flat,
:mime => 'text/x-flat-text',
:weight => 0) do
def flatten_hash(hash)
hash.each_with_object({}) do |(k, v), h|
case v
when Hash
flatten_hash(v).map do |h_k, h_v|
h["#{k}.#{h_k}"] = h_v
end
when Array
v.each_with_index do |el, i|
if el.is_a? Hash
flatten_hash(el).map do |el_k, el_v|
h["#{k}.#{i}.#{el_k}"] = el_v
end
else
h["#{k}.#{i}"] = el
end
end
else
h[k] = v
end
end
end
def flatten_array(array)
a = {}
array.each_with_index do |el, i|
if el.is_a? Hash
flatten_hash(el).map do |el_k, el_v|
a["#{i}.#{el_k}"] = el_v
end
else
a[i.to_s] = el
end
end
a
end
def construct_output(data)
output = ''.dup
data.each do |key, value|
output << "#{key}=#{value}"
output << "\n"
end
output
end
def render(datum)
return datum if datum.is_a?(String) || datum.is_a?(Numeric)
# Simple hash
case datum
when Hash
data = flatten_hash(datum)
return construct_output(data)
when Array
data = flatten_array(datum)
return construct_output(data)
end
Puppet::Util::Json.dump(datum, :pretty => true, :quirks_mode => true)
end
def render_multiple(data)
data.collect(&:render).join("\n")
end
end
Puppet::Network::FormatHandler.create(:rich_data_json, mime: 'application/vnd.puppet.rich+json', charset: Encoding::UTF_8, weight: 30) do
def intern(klass, text)
Puppet.override({ :rich_data => true }) do
data_to_instance(klass, Puppet::Util::Json.load(text))
end
end
def intern_multiple(klass, text)
Puppet.override({ :rich_data => true }) do
Puppet::Util::Json.load(text).collect do |data|
data_to_instance(klass, data)
end
end
end
def render(instance)
Puppet.override({ :rich_data => true }) do
instance.to_json
end
end
def render_multiple(instances)
Puppet.override({ :rich_data => true }) do
Puppet::Util::Json.dump(instances)
end
end
def data_to_instance(klass, data)
Puppet.override({ :rich_data => true }) do
return data if data.is_a?(klass)
klass.from_data_hash(data)
end
end
def supported?(klass)
klass == Puppet::Resource::Catalog &&
Puppet.lookup(:current_environment).rich_data?
end
end
Puppet::Network::FormatHandler.create_serialized_formats(:rich_data_msgpack, mime: "application/vnd.puppet.rich+msgpack", weight: 35) do
confine :feature => :msgpack
def intern(klass, text)
Puppet.override(rich_data: true) do
data = MessagePack.unpack(text)
return data if data.is_a?(klass)
klass.from_data_hash(data)
end
end
def intern_multiple(klass, text)
Puppet.override(rich_data: true) do
MessagePack.unpack(text).collect do |data|
klass.from_data_hash(data)
end
end
end
def render_multiple(instances)
Puppet.override(rich_data: true) do
instances.to_msgpack
end
end
def render(instance)
Puppet.override(rich_data: true) do
instance.to_msgpack
end
end
def supported?(klass)
suitable? &&
klass == Puppet::Resource::Catalog &&
Puppet.lookup(:current_environment).rich_data?
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/network/http/issues.rb | lib/puppet/network/http/issues.rb | # frozen_string_literal: true
module Puppet::Network::HTTP::Issues
NO_INDIRECTION_REMOTE_REQUESTS = :NO_INDIRECTION_REMOTE_REQUESTS
HANDLER_NOT_FOUND = :HANDLER_NOT_FOUND
RESOURCE_NOT_FOUND = :RESOURCE_NOT_FOUND
ENVIRONMENT_NOT_FOUND = :ENVIRONMENT_NOT_FOUND
RUNTIME_ERROR = :RUNTIME_ERROR
MISSING_HEADER_FIELD = :MISSING_HEADER_FIELD
UNSUPPORTED_FORMAT = :UNSUPPORTED_FORMAT
UNSUPPORTED_METHOD = :UNSUPPORTED_METHOD
FAILED_AUTHORIZATION = :FAILED_AUTHORIZATION
UNSUPPORTED_MEDIA_TYPE = :UNSUPPORTED_MEDIA_TYPE
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/network/http/response.rb | lib/puppet/network/http/response.rb | # frozen_string_literal: true
class Puppet::Network::HTTP::Response
def initialize(handler, response)
@handler = handler
@response = response
end
def respond_with(code, type, body)
format = Puppet::Network::FormatHandler.format_for(type)
mime = format.mime
charset = format.charset
if charset
if body.is_a?(String) && body.encoding != charset
body.encode!(charset)
end
mime += "; charset=#{charset.name.downcase}"
end
@handler.set_content_type(@response, mime)
@handler.set_response(@response, body, code)
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/network/http/route.rb | lib/puppet/network/http/route.rb | # frozen_string_literal: true
class Puppet::Network::HTTP::Route
MethodNotAllowedHandler = lambda do |req, _res|
raise Puppet::Network::HTTP::Error::HTTPMethodNotAllowedError.new("method #{req.method} not allowed for route #{req.path}", Puppet::Network::HTTP::Issues::UNSUPPORTED_METHOD)
end
NO_HANDLERS = [MethodNotAllowedHandler]
attr_reader :path_matcher
def self.path(path_matcher)
new(path_matcher)
end
def initialize(path_matcher)
@path_matcher = path_matcher
@method_handlers = {
:GET => NO_HANDLERS,
:HEAD => NO_HANDLERS,
:OPTIONS => NO_HANDLERS,
:POST => NO_HANDLERS,
:PUT => NO_HANDLERS,
:DELETE => NO_HANDLERS
}
@chained = []
end
def get(*handlers)
@method_handlers[:GET] = handlers
self
end
def head(*handlers)
@method_handlers[:HEAD] = handlers
self
end
def options(*handlers)
@method_handlers[:OPTIONS] = handlers
self
end
def post(*handlers)
@method_handlers[:POST] = handlers
self
end
def put(*handlers)
@method_handlers[:PUT] = handlers
self
end
def delete(*handlers)
@method_handlers[:DELETE] = handlers
self
end
def any(*handlers)
@method_handlers.each do |method, _registered_handlers|
@method_handlers[method] = handlers
end
self
end
def chain(*routes)
@chained = routes
self
end
def matches?(request)
Puppet.debug { "Evaluating match for #{inspect}" }
if match(request.routing_path)
return true
else
Puppet.debug { "Did not match path (#{request.routing_path.inspect})" }
end
false
end
def process(request, response)
handlers = @method_handlers[request.method.upcase.intern] || NO_HANDLERS
handlers.each do |handler|
handler.call(request, response)
end
subrequest = request.route_into(match(request.routing_path).to_s)
chained_route = @chained.find { |route| route.matches?(subrequest) }
if chained_route
chained_route.process(subrequest, response)
end
end
def inspect
"Route #{@path_matcher.inspect}"
end
private
def match(path)
@path_matcher.match(path)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/network/http/api.rb | lib/puppet/network/http/api.rb | # frozen_string_literal: true
class Puppet::Network::HTTP::API
require_relative '../../../puppet/version'
def self.not_found
Puppet::Network::HTTP::Route
.path(/.*/)
.any(lambda do |req, _res|
raise Puppet::Network::HTTP::Error::HTTPNotFoundError.new("No route for #{req.method} #{req.path}", Puppet::Network::HTTP::Issues::HANDLER_NOT_FOUND)
end)
end
def self.not_found_upgrade
Puppet::Network::HTTP::Route
.path(/.*/)
.any(lambda do |_req, _res|
raise Puppet::Network::HTTP::Error::HTTPNotFoundError.new("Error: Invalid URL - Puppet expects requests that conform to the " \
"/puppet and /puppet-ca APIs.\n\n" \
"Note that Puppet 3 agents aren't compatible with this version; if you're " \
"running Puppet 3, you must either upgrade your agents to match the server " \
"or point them to a server running Puppet 3.\n\n" \
"Server Info:\n" \
" Puppet version: #{Puppet.version}\n" \
" Supported /puppet API versions: #{Puppet::Network::HTTP::SERVER_URL_VERSIONS}\n",
Puppet::Network::HTTP::Issues::HANDLER_NOT_FOUND)
end)
end
def self.server_routes
server_prefix = Regexp.new("^#{Puppet::Network::HTTP::SERVER_URL_PREFIX}/")
Puppet::Network::HTTP::Route.path(server_prefix)
.any
.chain(Puppet::Network::HTTP::API::Server::V3.routes,
Puppet::Network::HTTP::API.not_found)
end
def self.master_routes
server_routes
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/network/http/handler.rb | lib/puppet/network/http/handler.rb | # frozen_string_literal: true
module Puppet::Network::HTTP
end
require_relative '../../../puppet/network/http'
require_relative '../../../puppet/util/profiler'
require_relative '../../../puppet/util/profiler/aggregate'
require 'resolv'
module Puppet::Network::HTTP::Handler
include Puppet::Network::HTTP::Issues
# These shouldn't be allowed to be set by clients
# in the query string, for security reasons.
DISALLOWED_KEYS = %w[node ip]
def register(routes)
# There's got to be a simpler way to do this, right?
dupes = {}
routes.each { |r| dupes[r.path_matcher] = (dupes[r.path_matcher] || 0) + 1 }
dupes = dupes.filter_map { |pm, count| pm if count > 1 }
if dupes.count > 0
raise ArgumentError, _("Given multiple routes with identical path regexes: %{regexes}") % { regexes: dupes.map(&:inspect).join(', ') }
end
@routes = routes
Puppet.debug("Routes Registered:")
@routes.each do |route|
Puppet.debug(route.inspect)
end
end
# Retrieve all headers from the http request, as a hash with the header names
# (lower-cased) as the keys
def headers(request)
raise NotImplementedError
end
# The mime type is always passed to the `set_content_type` method, so
# it is no longer necessary to retrieve the Format's mime type.
#
# @deprecated
def format_to_mime(format)
format.is_a?(Puppet::Network::Format) ? format.mime : format
end
# Create a generic puppet request from the implementation-specific request
# created by the web server
def make_generic_request(request)
request_path = path(request)
Puppet::Network::HTTP::Request.new(
headers(request),
params(request),
http_method(request),
request_path, # path
request_path, # routing_path
client_cert(request),
body(request)
)
end
def with_request_profiling(request)
profiler = configure_profiler(request.headers, request.params)
Puppet::Util::Profiler.profile(
_("Processed request %{request_method} %{request_path}") % { request_method: request.method, request_path: request.path },
[:http, request.method, request.path]
) do
yield
end
ensure
remove_profiler(profiler) if profiler
end
# handle an HTTP request
def process(external_request, response)
# The response_wrapper stores the response and modifies it as a side effect.
# The caller will use the original response
response_wrapper = Puppet::Network::HTTP::Response.new(self, response)
request = make_generic_request(external_request)
set_puppet_version_header(response)
respond_to_errors(response_wrapper) do
with_request_profiling(request) do
find_route_or_raise(request).process(request, response_wrapper)
end
end
end
def respond_to_errors(response)
yield
rescue Puppet::Network::HTTP::Error::HTTPError => e
Puppet.info(e.message)
respond_with_http_error(response, e)
rescue StandardError => e
http_e = Puppet::Network::HTTP::Error::HTTPServerError.new(e)
Puppet.err([http_e.message, *e.backtrace].join("\n"))
respond_with_http_error(response, http_e)
end
def respond_with_http_error(response, exception)
response.respond_with(exception.status, "application/json", exception.to_json)
end
def find_route_or_raise(request)
route = @routes.find { |r| r.matches?(request) }
route || raise(Puppet::Network::HTTP::Error::HTTPNotFoundError.new(
_("No route for %{request} %{path}") % { request: request.method, path: request.path },
HANDLER_NOT_FOUND
))
end
def set_puppet_version_header(response)
response[Puppet::Network::HTTP::HEADER_PUPPET_VERSION] = Puppet.version
end
# Set the response up, with the body and status.
def set_response(response, body, status = 200)
raise NotImplementedError
end
# Set the specified format as the content type of the response.
def set_content_type(response, format)
raise NotImplementedError
end
# resolve node name from peer's ip address
# this is used when the request is unauthenticated
def resolve_node(result)
begin
return Resolv.getname(result[:ip])
rescue => detail
Puppet.err _("Could not resolve %{ip}: %{detail}") % { ip: result[:ip], detail: detail }
end
result[:ip]
end
private
# methods to be overridden by the including web server class
def http_method(request)
raise NotImplementedError
end
def path(request)
raise NotImplementedError
end
def request_key(request)
raise NotImplementedError
end
def body(request)
raise NotImplementedError
end
def params(request)
raise NotImplementedError
end
def client_cert(request)
raise NotImplementedError
end
def decode_params(params)
params.select { |key, _| allowed_parameter?(key) }.each_with_object({}) do |ary, result|
param, value = ary
result[param.to_sym] = parse_parameter_value(param, value)
end
end
def allowed_parameter?(name)
!(name.nil? || name.empty? || DISALLOWED_KEYS.include?(name))
end
def parse_parameter_value(param, value)
if value.is_a?(Array)
value.collect { |v| parse_primitive_parameter_value(v) }
else
parse_primitive_parameter_value(value)
end
end
def parse_primitive_parameter_value(value)
case value
when "true"
true
when "false"
false
when /^\d+$/
Integer(value)
when /^\d+\.\d+$/
value.to_f
else
value
end
end
def configure_profiler(request_headers, request_params)
if request_headers.has_key?(Puppet::Network::HTTP::HEADER_ENABLE_PROFILING.downcase) or Puppet[:profile]
Puppet::Util::Profiler.add_profiler(Puppet::Util::Profiler::Aggregate.new(Puppet.method(:info), request_params.object_id))
end
end
def remove_profiler(profiler)
profiler.shutdown
Puppet::Util::Profiler.remove_profiler(profiler)
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/network/http/connection.rb | lib/puppet/network/http/connection.rb | # frozen_string_literal: true
require_relative '../../../puppet/http'
# This will be raised if too many redirects happen for a given HTTP request
class Puppet::Network::HTTP::RedirectionLimitExceededException < Puppet::Error; end
# This class provides simple methods for issuing various types of HTTP
# requests. It's interface is intended to mirror Ruby's Net::HTTP
# object, but it provides a few important bits of additional
# functionality. Notably:
#
# * Any HTTPS requests made using this class will use Puppet's SSL
# certificate configuration for their authentication, and
# * Provides some useful error handling for any SSL errors that occur
# during a request.
#
# @deprecated Use {Puppet.runtime[:http]}
# @api public
class Puppet::Network::HTTP::Connection
include Puppet::HTTP::ResponseConverter
OPTION_DEFAULTS = {
:use_ssl => true,
:verifier => nil,
:redirect_limit => 10,
}
# Creates a new HTTP client connection to `host`:`port`.
# @param host [String] the host to which this client will connect to
# @param port [Integer] the port to which this client will connect to
# @param options [Hash] options influencing the properties of the created
# connection,
# @option options [Boolean] :use_ssl true to connect with SSL, false
# otherwise, defaults to true
# @option options [Puppet::SSL::Verifier] :verifier An object that will configure
# any verification to do on the connection
# @option options [Integer] :redirect_limit the number of allowed
# redirections, defaults to 10 passing any other option in the options
# hash results in a Puppet::Error exception
#
# @note the HTTP connection itself happens lazily only when {#request}, or
# one of the {#get}, {#post}, {#delete}, {#head} or {#put} is called
# @note The correct way to obtain a connection is to use one of the factory
# methods on {Puppet::Network::HttpPool}
# @api private
def initialize(host, port, options = {})
unknown_options = options.keys - OPTION_DEFAULTS.keys
raise Puppet::Error, _("Unrecognized option(s): %{opts}") % { opts: unknown_options.map(&:inspect).sort.join(', ') } unless unknown_options.empty?
options = OPTION_DEFAULTS.merge(options)
@use_ssl = options[:use_ssl]
if @use_ssl
unless options[:verifier].is_a?(Puppet::SSL::Verifier)
raise ArgumentError, _("Expected an instance of Puppet::SSL::Verifier but was passed a %{klass}") % { klass: options[:verifier].class }
end
@verifier = options[:verifier]
end
@redirect_limit = options[:redirect_limit]
@site = Puppet::HTTP::Site.new(@use_ssl ? 'https' : 'http', host, port)
@client = Puppet.runtime[:http]
end
# The address to connect to.
def address
@site.host
end
# The port to connect to.
def port
@site.port
end
# Whether to use ssl
def use_ssl?
@site.use_ssl?
end
# @api private
def verifier
@verifier
end
# @!macro [new] common_options
# @param options [Hash] options influencing the request made. Any
# options not recognized by this class will be ignored - no error will
# be thrown.
# @option options [Hash{Symbol => String}] :basic_auth The basic auth
# :username and :password to use for the request, :metric_id Ignored
# by this class - used by Puppet Server only. The metric id by which
# to track metrics on requests.
# @param path [String]
# @param headers [Hash{String => String}]
# @!macro common_options
# @api public
def get(path, headers = {}, options = {})
headers ||= {}
options[:ssl_context] ||= resolve_ssl_context
options[:redirect_limit] ||= @redirect_limit
with_error_handling do
to_ruby_response(@client.get(to_url(path), headers: headers, options: options))
end
end
# @param path [String]
# @param data [String]
# @param headers [Hash{String => String}]
# @!macro common_options
# @api public
def post(path, data, headers = nil, options = {})
headers ||= {}
headers['Content-Type'] ||= "application/x-www-form-urlencoded"
data ||= ''
options[:ssl_context] ||= resolve_ssl_context
options[:redirect_limit] ||= @redirect_limit
with_error_handling do
to_ruby_response(@client.post(to_url(path), data, headers: headers, options: options))
end
end
# @param path [String]
# @param headers [Hash{String => String}]
# @!macro common_options
# @api public
def head(path, headers = {}, options = {})
headers ||= {}
options[:ssl_context] ||= resolve_ssl_context
options[:redirect_limit] ||= @redirect_limit
with_error_handling do
to_ruby_response(@client.head(to_url(path), headers: headers, options: options))
end
end
# @param path [String]
# @param headers [Hash{String => String}]
# @!macro common_options
# @api public
def delete(path, headers = { 'Depth' => 'Infinity' }, options = {})
headers ||= {}
options[:ssl_context] ||= resolve_ssl_context
options[:redirect_limit] ||= @redirect_limit
with_error_handling do
to_ruby_response(@client.delete(to_url(path), headers: headers, options: options))
end
end
# @param path [String]
# @param data [String]
# @param headers [Hash{String => String}]
# @!macro common_options
# @api public
def put(path, data, headers = nil, options = {})
headers ||= {}
headers['Content-Type'] ||= "application/x-www-form-urlencoded"
data ||= ''
options[:ssl_context] ||= resolve_ssl_context
options[:redirect_limit] ||= @redirect_limit
with_error_handling do
to_ruby_response(@client.put(to_url(path), data, headers: headers, options: options))
end
end
def request_get(*args, &block)
path, headers = *args
headers ||= {}
options = {
ssl_context: resolve_ssl_context,
redirect_limit: @redirect_limit
}
ruby_response = nil
@client.get(to_url(path), headers: headers, options: options) do |response|
ruby_response = to_ruby_response(response)
yield ruby_response if block_given?
end
ruby_response
end
def request_head(*args, &block)
path, headers = *args
headers ||= {}
options = {
ssl_context: resolve_ssl_context,
redirect_limit: @redirect_limit
}
response = @client.head(to_url(path), headers: headers, options: options)
ruby_response = to_ruby_response(response)
yield ruby_response if block_given?
ruby_response
end
def request_post(*args, &block)
path, data, headers = *args
headers ||= {}
headers['Content-Type'] ||= "application/x-www-form-urlencoded"
options = {
ssl_context: resolve_ssl_context,
redirect_limit: @redirect_limit
}
ruby_response = nil
@client.post(to_url(path), data, headers: headers, options: options) do |response|
ruby_response = to_ruby_response(response)
yield ruby_response if block_given?
end
ruby_response
end
private
# Resolve the ssl_context based on the verifier associated with this
# connection or load the available set of certs and key on disk.
# Don't try to bootstrap the agent, as we only want that to be triggered
# when running `puppet ssl` or `puppet agent`.
def resolve_ssl_context
# don't need an ssl context for http connections
return nil unless @site.use_ssl?
# if our verifier has an ssl_context, use that
ctx = @verifier.ssl_context
return ctx if ctx
# load available certs
cert = Puppet::X509::CertProvider.new
ssl = Puppet::SSL::SSLProvider.new
begin
password = cert.load_private_key_password
ssl.load_context(certname: Puppet[:certname], password: password)
rescue Puppet::SSL::SSLError => e
Puppet.log_exception(e)
# if we don't have cacerts, then create a root context that doesn't
# trust anything. The old code used to fallback to VERIFY_NONE,
# which we don't want to emulate.
ssl.create_root_context(cacerts: [])
end
end
def to_url(path)
if path =~ %r{^https?://}
# The old Connection class accepts a URL as the request path, and sends
# it in "absolute-form" in the request line, e.g. GET https://puppet:8140/.
# See https://httpwg.org/specs/rfc7230.html#absolute-form. It just so happens
# to work because HTTP 1.1 servers are required to accept absolute-form even
# though clients are only supposed to send them to proxies, so the proxy knows
# what upstream server to CONNECT to. This method creates a URL using the
# scheme/host/port that the connection was created with, and appends the path
# and query portions of the absolute-form. The resulting request will use "origin-form"
# as it should have done all along.
abs_form = URI(path)
url = URI("#{@site.addr}/#{normalize_path(abs_form.path)}")
url.query = abs_form.query if abs_form.query
url
else
URI("#{@site.addr}/#{normalize_path(path)}")
end
end
def normalize_path(path)
if path[0] == '/'
path[1..]
else
path
end
end
def with_error_handling(&block)
yield
rescue Puppet::HTTP::TooManyRedirects => e
raise Puppet::Network::HTTP::RedirectionLimitExceededException.new(_("Too many HTTP redirections for %{host}:%{port}") % { host: @host, port: @port }, e)
rescue Puppet::HTTP::HTTPError => e
Puppet.log_exception(e, e.message)
case e.cause
when Net::OpenTimeout, Net::ReadTimeout, Net::HTTPError, EOFError
raise e.cause
else
raise e
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/network/http/memory_response.rb | lib/puppet/network/http/memory_response.rb | # frozen_string_literal: true
class Puppet::Network::HTTP::MemoryResponse
attr_reader :code, :type, :body
def initialize
@body = ''.dup
end
def respond_with(code, type, body)
@code = code
@type = type
@body += body
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/network/http/request.rb | lib/puppet/network/http/request.rb | # frozen_string_literal: true
# This class is effectively public API, because a Request object is passed as a
# parameter to the current Handler subclass. Puppetserver implements its own
# Handler
# https://github.com/puppetlabs/puppetserver/blob/8.3.0/src/ruby/puppetserver-lib/puppet/server/network/http/handler.rb#L9
# and the Request object is passed to its Handler#body method
# https://github.com/puppetlabs/puppetserver/blob/8.3.0/src/ruby/puppetserver-lib/puppet/server/network/http/handler.rb#L36
Puppet::Network::HTTP::Request = Struct.new(:headers, :params, :method, :path, :routing_path, :client_cert, :body) do # rubocop:disable Lint/StructNewOverride
def self.from_hash(hash)
symbol_members = members.collect(&:intern)
unknown = hash.keys - symbol_members
if unknown.empty?
new(hash[:headers] || {},
hash[:params] || {},
hash[:method] || "GET",
hash[:path],
hash[:routing_path] || hash[:path],
hash[:client_cert],
hash[:body])
else
raise ArgumentError, _("Unknown arguments: %{args}") % { args: unknown.collect(&:inspect).join(', ') }
end
end
def route_into(prefix)
self.class.new(headers, params, method, path, routing_path.sub(prefix, ''), client_cert, body)
end
def formatter
header = headers['content-type']
if header
header.gsub!(/\s*;.*$/, '') # strip any charset
format = Puppet::Network::FormatHandler.mime(header)
return format if valid_network_format?(format)
# TRANSLATORS "mime-type" is a keyword and should not be translated
raise Puppet::Network::HTTP::Error::HTTPUnsupportedMediaTypeError.new(
_("Client sent a mime-type (%{header}) that doesn't correspond to a format we support") % { header: headers['content-type'] },
Puppet::Network::HTTP::Issues::UNSUPPORTED_MEDIA_TYPE
)
end
raise Puppet::Network::HTTP::Error::HTTPBadRequestError.new(
_("No Content-Type header was received, it isn't possible to unserialize the request"),
Puppet::Network::HTTP::Issues::MISSING_HEADER_FIELD
)
end
def response_formatters_for(supported_formats, default_accepted_formats = nil)
accepted_formats = headers['accept'] || default_accepted_formats
if accepted_formats.nil?
raise Puppet::Network::HTTP::Error::HTTPBadRequestError.new(_("Missing required Accept header"), Puppet::Network::HTTP::Issues::MISSING_HEADER_FIELD)
end
formats = Puppet::Network::FormatHandler.most_suitable_formats_for(
accepted_formats.split(/\s*,\s*/),
supported_formats
)
formats.find_all do |format|
# we are only passed supported_formats that are suitable
# and whose klass implements the required_methods
valid_network_format?(format)
end
return formats unless formats.empty?
raise Puppet::Network::HTTP::Error::HTTPNotAcceptableError.new(
_("No supported formats are acceptable (Accept: %{accepted_formats})") % { accepted_formats: accepted_formats },
Puppet::Network::HTTP::Issues::UNSUPPORTED_FORMAT
)
end
private
def valid_network_format?(format)
# YAML in network requests is not supported. See http://links.puppet.com/deprecate_yaml_on_network
!format.nil? && format.name != :yaml && format.name != :b64_zlib_yaml
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/network/http/error.rb | lib/puppet/network/http/error.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/json'
module Puppet::Network::HTTP::Error
Issues = Puppet::Network::HTTP::Issues
class HTTPError < Exception # rubocop:disable Lint/InheritException
attr_reader :status, :issue_kind
def initialize(message, status, issue_kind)
super(message)
@status = status
@issue_kind = issue_kind
end
def to_json
Puppet::Util::Json.dump({ :message => message, :issue_kind => @issue_kind })
end
end
class HTTPNotAcceptableError < HTTPError
CODE = 406
def initialize(message, issue_kind = Issues::RUNTIME_ERROR)
super(_("Not Acceptable: %{message}") % { message: message }, CODE, issue_kind)
end
end
class HTTPNotFoundError < HTTPError
CODE = 404
def initialize(message, issue_kind = Issues::RUNTIME_ERROR)
super(_("Not Found: %{message}") % { message: message }, CODE, issue_kind)
end
end
class HTTPNotAuthorizedError < HTTPError
CODE = 403
def initialize(message, issue_kind = Issues::RUNTIME_ERROR)
super(_("Not Authorized: %{message}") % { message: message }, CODE, issue_kind)
end
end
class HTTPBadRequestError < HTTPError
CODE = 400
def initialize(message, issue_kind = Issues::RUNTIME_ERROR)
super(_("Bad Request: %{message}") % { message: message }, CODE, issue_kind)
end
end
class HTTPMethodNotAllowedError < HTTPError
CODE = 405
def initialize(message, issue_kind = Issues::RUNTIME_ERROR)
super(_("Method Not Allowed: %{message}") % { message: message }, CODE, issue_kind)
end
end
class HTTPUnsupportedMediaTypeError < HTTPError
CODE = 415
def initialize(message, issue_kind = Issues::RUNTIME_ERROR)
super(_("Unsupported Media Type: %{message}") % { message: message }, CODE, issue_kind)
end
end
class HTTPServerError < HTTPError
CODE = 500
def initialize(original_error, issue_kind = Issues::RUNTIME_ERROR)
super(_("Server Error: %{message}") % { message: original_error.message }, CODE, issue_kind)
end
def to_json
Puppet::Util::Json.dump({ :message => message, :issue_kind => @issue_kind })
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/network/http/api/master.rb | lib/puppet/network/http/api/master.rb | # frozen_string_literal: true
require_relative '../../../../puppet/network/http/api/server'
Puppet::Network::HTTP::API::Master = Puppet::Network::HTTP::API::Server
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/network/http/api/indirection_type.rb | lib/puppet/network/http/api/indirection_type.rb | # frozen_string_literal: true
class Puppet::Network::HTTP::API::IndirectionType
INDIRECTION_TYPE_MAP = {
"certificate" => :ca,
"certificate_request" => :ca,
"certificate_revocation_list" => :ca,
"certificate_status" => :ca
}
def self.master_url_prefix
"#{Puppet::Network::HTTP::MASTER_URL_PREFIX}/v3"
end
def self.ca_url_prefix
"#{Puppet::Network::HTTP::CA_URL_PREFIX}/v1"
end
def self.type_for(indirection)
INDIRECTION_TYPE_MAP[indirection] || :master
end
def self.url_prefix_for(indirection_name)
case type_for(indirection_name)
when :ca
ca_url_prefix
when :master
master_url_prefix
else
raise ArgumentError, _("Not a valid indirection type")
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/network/http/api/server.rb | lib/puppet/network/http/api/server.rb | # frozen_string_literal: true
module Puppet
module Network
module HTTP
class API
module Server
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/network/http/api/indirected_routes.rb | lib/puppet/network/http/api/indirected_routes.rb | # frozen_string_literal: true
require_relative '../../../../puppet/network/http/api/indirection_type'
class Puppet::Network::HTTP::API::IndirectedRoutes
# How we map http methods and the indirection name in the URI
# to an indirection method.
METHOD_MAP = {
"GET" => {
:plural => :search,
:singular => :find
},
"POST" => {
:singular => :find,
},
"PUT" => {
:singular => :save
},
"DELETE" => {
:singular => :destroy
},
"HEAD" => {
:singular => :head
}
}
IndirectionType = Puppet::Network::HTTP::API::IndirectionType
def self.routes
Puppet::Network::HTTP::Route.path(/.*/).any(new)
end
# Handle an HTTP request. The request has already been authenticated prior
# to calling this method.
def call(request, response)
indirection, method, key, params = uri2indirection(request.method, request.path, request.params)
certificate = request.client_cert
unless indirection.allow_remote_requests?
# TODO: should we tell the user we found an indirection but it doesn't
# allow remote requests, or just pretend there's no handler at all? what
# are the security implications for the former?
raise Puppet::Network::HTTP::Error::HTTPNotFoundError.new(_("No handler for %{indirection}") % { indirection: indirection.name }, :NO_INDIRECTION_REMOTE_REQUESTS)
end
overrides = {
trusted_information: Puppet::Context::TrustedInformation.remote(params[:authenticated], params[:node], certificate),
}
if params[:environment]
overrides[:current_environment] = params[:environment]
end
Puppet.override(overrides) do
send("do_#{method}", indirection, key, params, request, response)
end
end
def uri2indirection(http_method, uri, params)
# the first field is always nil because of the leading slash,
indirection_type, version, indirection_name, key = uri.split("/", 5)[1..]
url_prefix = "/#{indirection_type}/#{version}"
environment = params.delete(:environment)
if indirection_name !~ /^\w+$/
raise Puppet::Network::HTTP::Error::HTTPBadRequestError, _("The indirection name must be purely alphanumeric, not '%{indirection_name}'") % { indirection_name: indirection_name }
end
# this also depluralizes the indirection_name if it is a search
method = indirection_method(http_method, indirection_name)
# check whether this indirection matches the prefix and version in the
# request
if url_prefix != IndirectionType.url_prefix_for(indirection_name)
raise Puppet::Network::HTTP::Error::HTTPBadRequestError, _("Indirection '%{indirection_name}' does not match url prefix '%{url_prefix}'") % { indirection_name: indirection_name, url_prefix: url_prefix }
end
indirection = Puppet::Indirector::Indirection.instance(indirection_name.to_sym)
unless indirection
raise Puppet::Network::HTTP::Error::HTTPNotFoundError.new(
_("Could not find indirection '%{indirection_name}'") % { indirection_name: indirection_name },
Puppet::Network::HTTP::Issues::HANDLER_NOT_FOUND
)
end
unless environment
raise Puppet::Network::HTTP::Error::HTTPBadRequestError, _("An environment parameter must be specified")
end
unless Puppet::Node::Environment.valid_name?(environment)
raise Puppet::Network::HTTP::Error::HTTPBadRequestError, _("The environment must be purely alphanumeric, not '%{environment}'") % { environment: environment }
end
configured_environment = Puppet.lookup(:environments).get(environment)
unless configured_environment.nil?
configured_environment = configured_environment.override_from_commandline(Puppet.settings)
params[:environment] = configured_environment
end
if configured_environment.nil? && indirection.terminus.require_environment?
raise Puppet::Network::HTTP::Error::HTTPNotFoundError, _("Could not find environment '%{environment}'") % { environment: environment }
end
params.delete(:bucket_path)
if key == "" or key.nil?
raise Puppet::Network::HTTP::Error::HTTPBadRequestError, _("No request key specified in %{uri}") % { uri: uri }
end
[indirection, method, key, params]
end
private
# Execute our find.
def do_find(indirection, key, params, request, response)
result = indirection.find(key, params)
unless result
raise Puppet::Network::HTTP::Error::HTTPNotFoundError.new(_("Could not find %{value0} %{key}") % { value0: indirection.name, key: key }, Puppet::Network::HTTP::Issues::RESOURCE_NOT_FOUND)
end
rendered_result = result
rendered_format = first_response_formatter_for(indirection.model, request, key) do |format|
if result.respond_to?(:render)
Puppet::Util::Profiler.profile(_("Rendered result in %{format}") % { format: format }, [:http, :v3_render, format]) do
rendered_result = result.render(format)
end
end
end
Puppet::Util::Profiler.profile(_("Sent response"), [:http, :v3_response]) do
response.respond_with(200, rendered_format, rendered_result)
end
end
# Execute our head.
def do_head(indirection, key, params, request, response)
unless indirection.head(key, params)
raise Puppet::Network::HTTP::Error::HTTPNotFoundError.new(_("Could not find %{indirection} %{key}") % { indirection: indirection.name, key: key }, Puppet::Network::HTTP::Issues::RESOURCE_NOT_FOUND)
end
# No need to set a response because no response is expected from a
# HEAD request. All we need to do is not die.
end
# Execute our search.
def do_search(indirection, key, params, request, response)
result = indirection.search(key, params)
if result.nil?
raise Puppet::Network::HTTP::Error::HTTPNotFoundError.new(_("Could not find instances in %{indirection} with '%{key}'") % { indirection: indirection.name, key: key }, Puppet::Network::HTTP::Issues::RESOURCE_NOT_FOUND)
end
rendered_result = nil
rendered_format = first_response_formatter_for(indirection.model, request, key) do |format|
rendered_result = indirection.model.render_multiple(format, result)
end
response.respond_with(200, rendered_format, rendered_result)
end
# Execute our destroy.
def do_destroy(indirection, key, params, request, response)
formatter = accepted_response_formatter_or_json_for(indirection.model, request)
result = indirection.destroy(key, params)
response.respond_with(200, formatter, formatter.render(result))
end
# Execute our save.
def do_save(indirection, key, params, request, response)
formatter = accepted_response_formatter_or_json_for(indirection.model, request)
sent_object = read_body_into_model(indirection.model, request)
result = indirection.save(sent_object, key)
response.respond_with(200, formatter, formatter.render(result))
end
# Return the first response formatter that didn't cause the yielded
# block to raise a FormatError.
def first_response_formatter_for(model, request, key, &block)
formats = accepted_response_formatters_for(model, request)
formatter = formats.find do |format|
yield format
true
rescue Puppet::Network::FormatHandler::FormatError => err
msg = _("Failed to serialize %{model} for '%{key}': %{detail}") %
{ model: model, key: key, detail: err }
if Puppet[:allow_pson_serialization]
Puppet.warning(msg)
else
raise Puppet::Network::FormatHandler::FormatError, msg
end
false
end
return formatter if formatter
raise Puppet::Network::HTTP::Error::HTTPNotAcceptableError.new(
_("No supported formats are acceptable (Accept: %{accepted_formats})") % { accepted_formats: formats.map(&:mime).join(', ') },
Puppet::Network::HTTP::Issues::UNSUPPORTED_FORMAT
)
end
# Return an array of response formatters that the client accepts and
# the server supports.
def accepted_response_formatters_for(model_class, request)
request.response_formatters_for(model_class.supported_formats)
end
# Return the first response formatter that the client accepts and
# the server supports, or default to 'application/json'.
def accepted_response_formatter_or_json_for(model_class, request)
request.response_formatters_for(model_class.supported_formats, "application/json").first
end
def read_body_into_model(model_class, request)
data = request.body.to_s
formatter = request.formatter
if formatter.supported?(model_class)
begin
return model_class.convert_from(formatter.name.to_s, data)
rescue => e
raise Puppet::Network::HTTP::Error::HTTPBadRequestError, _("The request body is invalid: %{message}") % { message: e.message }
end
end
# TRANSLATORS "mime-type" is a keyword and should not be translated
raise Puppet::Network::HTTP::Error::HTTPUnsupportedMediaTypeError.new(
_("Client sent a mime-type (%{header}) that doesn't correspond to a format we support") % { header: request.headers['content-type'] },
Puppet::Network::HTTP::Issues::UNSUPPORTED_MEDIA_TYPE
)
end
def indirection_method(http_method, indirection)
raise Puppet::Network::HTTP::Error::HTTPMethodNotAllowedError, _("No support for http method %{http_method}") % { http_method: http_method } unless METHOD_MAP[http_method]
method = METHOD_MAP[http_method][plurality(indirection)]
unless method
raise Puppet::Network::HTTP::Error::HTTPBadRequestError, _("No support for plurality %{indirection} for %{http_method} operations") % { indirection: plurality(indirection), http_method: http_method }
end
method
end
def self.pluralize(indirection)
(indirection == "status" ? "statuses" : indirection + "s")
end
private_class_method :pluralize
def plurality(indirection)
# NOTE These specific hooks for paths are ridiculous, but it's a *many*-line
# fix to not need this, and our goal is to move away from the complication
# that leads to the fix being too long.
return :singular if indirection == "facts"
return :singular if indirection == "status"
return :singular if indirection == "certificate_status"
result = (indirection =~ /s$|_search$/) ? :plural : :singular
indirection.sub!(/s$|_search$/, '')
indirection.sub!(/statuse$/, 'status')
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/network/http/api/server/v3.rb | lib/puppet/network/http/api/server/v3.rb | # frozen_string_literal: true
require_relative 'v3/environments'
require_relative '../../../../../puppet/network/http/api/indirected_routes'
module Puppet
module Network
module HTTP
class API
module Server
class V3
def self.wrap(&block)
lambda do |request, response|
Puppet::Network::Authorization
.check_external_authorization(request.method,
request.path)
block.call.call(request, response)
end
end
INDIRECTED = Puppet::Network::HTTP::Route
.path(/.*/)
.any(wrap { Puppet::Network::HTTP::API::IndirectedRoutes.new })
ENVIRONMENTS = Puppet::Network::HTTP::Route
.path(%r{^/environments$})
.get(wrap { Environments.new(Puppet.lookup(:environments)) })
def self.routes
Puppet::Network::HTTP::Route.path(/v3/)
.any
.chain(ENVIRONMENTS, INDIRECTED)
end
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/network/http/api/server/v3/environments.rb | lib/puppet/network/http/api/server/v3/environments.rb | # frozen_string_literal: true
require_relative '../../../../../../puppet/util/json'
module Puppet
module Network
module HTTP
class API
module Server
class V3
class Environments
def initialize(env_loader)
@env_loader = env_loader
end
def call(request, response)
response
.respond_with(
200,
"application/json",
Puppet::Util::Json
.dump({
"search_paths" => @env_loader.search_paths,
"environments" => @env_loader.list.to_h do |env|
[env.name, {
"settings" => {
"modulepath" => env.full_modulepath,
"manifest" => env.manifest,
"environment_timeout" => timeout(env),
"config_version" => env.config_version || '',
}
}]
end
})
)
end
private
def timeout(env)
ttl = @env_loader.get_conf(env.name).environment_timeout
if ttl == Float::INFINITY
"unlimited"
else
ttl
end
end
end
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/network/http/api/master/v3.rb | lib/puppet/network/http/api/master/v3.rb | # frozen_string_literal: true
require_relative '../../../../../puppet/network/http/api/master'
require_relative '../../../../../puppet/network/http/api/server/v3'
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/network/http/api/master/v3/environments.rb | lib/puppet/network/http/api/master/v3/environments.rb | # frozen_string_literal: true
require_relative '../../../../../../puppet/network/http/api/master'
require_relative '../../../../../../puppet/network/http/api/server/v3/environments'
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/file_serving/content.rb | lib/puppet/file_serving/content.rb | # frozen_string_literal: true
require_relative '../../puppet/indirector'
require_relative '../../puppet/file_serving'
require_relative '../../puppet/file_serving/base'
# A class that handles retrieving file contents.
# It only reads the file when its content is specifically
# asked for.
class Puppet::FileServing::Content < Puppet::FileServing::Base
extend Puppet::Indirector
indirects :file_content, :terminus_class => :selector
attr_writer :content
def self.supported_formats
[:binary]
end
def self.from_binary(content)
instance = new("/this/is/a/fake/path")
instance.content = content
instance
end
# This is no longer used, but is still called by the file server implementations when interacting
# with their model abstraction.
def collect(source_permissions = nil)
end
# Read the content of our file in.
def content
unless @content
# This stat can raise an exception, too.
raise(ArgumentError, _("Cannot read the contents of links unless following links")) if stat.ftype == "symlink"
@content = Puppet::FileSystem.binread(full_path)
end
@content
end
def to_binary
File.new(full_path, "rb")
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/file_serving/http_metadata.rb | lib/puppet/file_serving/http_metadata.rb | # frozen_string_literal: true
require_relative '../../puppet/file_serving/metadata'
# Simplified metadata representation, suitable for the information
# that is available from HTTP headers.
class Puppet::FileServing::HttpMetadata < Puppet::FileServing::Metadata
def initialize(http_response, path = '/dev/null')
super(path)
# ignore options that do not apply to HTTP metadata
@owner = @group = @mode = nil
# hash available checksums for eventual collection
@checksums = {}
# use a default mtime in case there is no usable HTTP header
@checksums[:mtime] = "{mtime}#{Time.now}"
# RFC-1864, deprecated in HTTP/1.1 due to partial responses
checksum = http_response['content-md5']
if checksum
# convert base64 digest to hex
checksum = checksum.unpack1("m").unpack1("H*")
@checksums[:md5] = "{md5}#{checksum}"
end
{
md5: 'X-Checksum-Md5',
sha1: 'X-Checksum-Sha1',
sha256: 'X-Checksum-Sha256'
}.each_pair do |checksum_type, header|
checksum = http_response[header]
if checksum
@checksums[checksum_type] = "{#{checksum_type}}#{checksum}"
end
end
last_modified = http_response['last-modified']
if last_modified
mtime = DateTime.httpdate(last_modified).to_time
@checksums[:mtime] = "{mtime}#{mtime.utc}"
end
@ftype = 'file'
end
# Override of the parent class method. Does not call super!
# We can only return metadata that was extracted from the
# HTTP headers during #initialize.
def collect
# Prefer the checksum_type from the indirector request options
# but fall back to the alternative otherwise
[@checksum_type, :sha256, :sha1, :md5, :mtime].each do |type|
next if type == :md5 && Puppet::Util::Platform.fips_enabled?
@checksum_type = type
@checksum = @checksums[type]
break if @checksum
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/file_serving/terminus_helper.rb | lib/puppet/file_serving/terminus_helper.rb | # frozen_string_literal: true
require_relative '../../puppet/file_serving'
require_relative '../../puppet/file_serving/fileset'
# Define some common methods for FileServing termini.
module Puppet::FileServing::TerminusHelper
# Create model instance for a file in a file server.
def path2instance(request, path, options = {})
result = model.new(path, :relative_path => options[:relative_path])
result.links = request.options[:links] if request.options[:links]
result.checksum_type = request.options[:checksum_type] if request.options[:checksum_type]
result.source_permissions = request.options[:source_permissions] if request.options[:source_permissions]
result.collect
result
end
# Create model instances for all files in a fileset.
def path2instances(request, *paths)
filesets = paths.collect do |path|
# Filesets support indirector requests as an options collection
Puppet::FileServing::Fileset.new(path, request)
end
Puppet::FileServing::Fileset.merge(*filesets).collect do |file, base_path|
path2instance(request, base_path, :relative_path => file)
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/file_serving/terminus_selector.rb | lib/puppet/file_serving/terminus_selector.rb | # frozen_string_literal: true
require_relative '../../puppet/file_serving'
# This module is used to pick the appropriate terminus
# in file-serving indirections. This is necessary because
# the terminus varies based on the URI asked for.
module Puppet::FileServing::TerminusSelector
def select(request)
# We rely on the request's parsing of the URI.
case request.protocol
when "file"
:file
when "puppet"
if request.server
:rest
else
Puppet[:default_file_terminus]
end
when "http", "https"
:http
when nil
if Puppet::Util.absolute_path?(request.key)
:file
else
:file_server
end
else
raise ArgumentError, _("URI protocol '%{protocol}' is not currently supported for file serving") % { protocol: request.protocol }
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/file_serving/base.rb | lib/puppet/file_serving/base.rb | # frozen_string_literal: true
require_relative '../../puppet/file_serving'
require_relative '../../puppet/util'
# The base class for Content and Metadata; provides common
# functionality like the behaviour around links.
class Puppet::FileServing::Base
# This is for external consumers to store the source that was used
# to retrieve the metadata.
attr_accessor :source
# Does our file exist?
def exist?
stat
true
rescue
false
end
# Return the full path to our file. Fails if there's no path set.
def full_path
if relative_path.nil? or relative_path == "" or relative_path == "."
full_path = path
else
full_path = File.join(path, relative_path)
end
if Puppet::Util::Platform.windows?
# Replace multiple slashes as long as they aren't at the beginning of a filename
full_path.gsub(%r{(./)/+}, '\1')
else
full_path.gsub(%r{//+}, '/')
end
end
def initialize(path, links: nil, relative_path: nil, source: nil)
self.path = path
@links = :manage
self.links = links if links
self.relative_path = relative_path if relative_path
self.source = source if source
end
# Determine how we deal with links.
attr_reader :links
def links=(value)
value = value.to_sym
value = :manage if value == :ignore
# TRANSLATORS ':link', ':manage', ':follow' should not be translated
raise(ArgumentError, _(":links can only be set to :manage or :follow")) unless [:manage, :follow].include?(value)
@links = value
end
# Set our base path.
attr_reader :path
def path=(path)
raise ArgumentError, _("Paths must be fully qualified") unless Puppet::FileServing::Base.absolute?(path)
@path = path
end
# Set a relative path; this is used for recursion, and sets
# the file's path relative to the initial recursion point.
attr_reader :relative_path
def relative_path=(path)
raise ArgumentError, _("Relative paths must not be fully qualified") if Puppet::FileServing::Base.absolute?(path)
@relative_path = path
end
# Stat our file, using the appropriate link-sensitive method.
def stat
@stat_method ||= links == :manage ? :lstat : :stat
Puppet::FileSystem.send(@stat_method, full_path)
end
def to_data_hash
{
'path' => @path,
'relative_path' => @relative_path,
'links' => @links.to_s
}
end
def self.absolute?(path)
Puppet::Util.absolute_path?(path, :posix) || (Puppet::Util::Platform.windows? && Puppet::Util.absolute_path?(path, :windows))
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/file_serving/configuration.rb | lib/puppet/file_serving/configuration.rb | # frozen_string_literal: true
require_relative '../../puppet'
require_relative '../../puppet/file_serving'
require_relative '../../puppet/file_serving/mount'
require_relative '../../puppet/file_serving/mount/file'
require_relative '../../puppet/file_serving/mount/modules'
require_relative '../../puppet/file_serving/mount/plugins'
require_relative '../../puppet/file_serving/mount/locales'
require_relative '../../puppet/file_serving/mount/pluginfacts'
require_relative '../../puppet/file_serving/mount/scripts'
require_relative '../../puppet/file_serving/mount/tasks'
class Puppet::FileServing::Configuration
require_relative 'configuration/parser'
def self.configuration
@configuration ||= new
end
Mount = Puppet::FileServing::Mount
private_class_method :new
attr_reader :mounts
# private :mounts
# Find the right mount. Does some shenanigans to support old-style module
# mounts.
def find_mount(mount_name, environment)
# Reparse the configuration if necessary.
readconfig
# This can be nil.
mounts[mount_name]
end
def initialize
@mounts = {}
@config_file = nil
# We don't check to see if the file is modified the first time,
# because we always want to parse at first.
readconfig(false)
end
# Is a given mount available?
def mounted?(name)
@mounts.include?(name)
end
# Split the path into the separate mount point and path.
def split_path(request)
# Reparse the configuration if necessary.
readconfig
mount_name, path = request.key.split(File::Separator, 2)
raise(ArgumentError, _("Cannot find file: Invalid mount '%{mount_name}'") % { mount_name: mount_name }) unless mount_name =~ /^[-\w]+$/
raise(ArgumentError, _("Cannot find file: Invalid relative path '%{path}'") % { path: path }) if path and path.split('/').include?('..')
mount = find_mount(mount_name, request.environment)
return nil unless mount
if mount.name == "modules" and mount_name != "modules"
# yay backward-compatibility
path = "#{mount_name}/#{path}"
end
if path == ""
path = nil
elsif path
# Remove any double slashes that might have occurred
path = path.gsub(%r{/+}, "/")
end
[mount, path]
end
def umount(name)
@mounts.delete(name) if @mounts.include? name
end
private
def mk_default_mounts
@mounts["modules"] ||= Mount::Modules.new("modules")
@mounts["plugins"] ||= Mount::Plugins.new("plugins")
@mounts["locales"] ||= Mount::Locales.new("locales")
@mounts["pluginfacts"] ||= Mount::PluginFacts.new("pluginfacts")
@mounts["scripts"] ||= Mount::Scripts.new("scripts")
@mounts["tasks"] ||= Mount::Tasks.new("tasks")
end
# Read the configuration file.
def readconfig(check = true)
config = Puppet[:fileserverconfig]
return unless Puppet::FileSystem.exist?(config)
@parser ||= Puppet::FileServing::Configuration::Parser.new(config)
return if check and !@parser.changed?
# Don't assign the mounts hash until we're sure the parsing succeeded.
begin
newmounts = @parser.parse
@mounts = newmounts
rescue => detail
Puppet.log_exception(detail, _("Error parsing fileserver configuration: %{detail}; using old configuration") % { detail: detail })
end
ensure
# Make sure we've got our plugins and modules.
mk_default_mounts
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/file_serving/fileset.rb | lib/puppet/file_serving/fileset.rb | # frozen_string_literal: true
require 'find'
require_relative '../../puppet/file_serving'
require_relative '../../puppet/file_serving/metadata'
# Operate recursively on a path, returning a set of file paths.
class Puppet::FileServing::Fileset
attr_reader :path, :ignore, :links
attr_accessor :recurse, :recurselimit, :max_files, :checksum_type
# Produce a hash of files, with merged so that earlier files
# with the same postfix win. E.g., /dir1/subfile beats /dir2/subfile.
# It's a hash because we need to know the relative path of each file,
# and the base directory.
# This will probably only ever be used for searching for plugins.
def self.merge(*filesets)
result = {}
filesets.each do |fileset|
fileset.files.each do |file|
result[file] ||= fileset.path
end
end
result
end
def initialize(path, options = {})
if Puppet::Util::Platform.windows?
# REMIND: UNC path
path = path.chomp(File::SEPARATOR) unless path =~ %r{^[A-Za-z]:/$}
else
path = path.chomp(File::SEPARATOR) unless path == File::SEPARATOR
end
raise ArgumentError, _("Fileset paths must be fully qualified: %{path}") % { path: path } unless Puppet::Util.absolute_path?(path)
@path = path
# Set our defaults.
self.ignore = []
self.links = :manage
@recurse = false
@recurselimit = :infinite
@max_files = 0
if options.is_a?(Puppet::Indirector::Request)
initialize_from_request(options)
else
initialize_from_hash(options)
end
raise ArgumentError, _("Fileset paths must exist") unless valid?(path)
# TRANSLATORS "recurse" and "recurselimit" are parameter names and should not be translated
raise ArgumentError, _("Fileset recurse parameter must not be a number anymore, please use recurselimit") if @recurse.is_a?(Integer)
end
# Return a list of all files in our fileset. This is different from the
# normal definition of find in that we support specific levels
# of recursion, which means we need to know when we're going another
# level deep, which Find doesn't do.
def files
files = perform_recursion
soft_max_files = 1000
# munged_max_files is needed since puppet http handler is keeping negative numbers as strings
# https://github.com/puppetlabs/puppet/blob/main/lib/puppet/network/http/handler.rb#L196-L197
munged_max_files = max_files == '-1' ? -1 : max_files
if munged_max_files > 0 && files.size > munged_max_files
raise Puppet::Error, _("The directory '%{path}' contains %{entries} entries, which exceeds the limit of %{munged_max_files} specified by the max_files parameter for this resource. The limit may be increased, but be aware that large number of file resources can result in excessive resource consumption and degraded performance. Consider using an alternate method to manage large directory trees") % { path: path, entries: files.size, munged_max_files: munged_max_files }
elsif munged_max_files == 0 && files.size > soft_max_files
Puppet.warning _("The directory '%{path}' contains %{entries} entries, which exceeds the default soft limit %{soft_max_files} and may cause excessive resource consumption and degraded performance. To remove this warning set a value for `max_files` parameter or consider using an alternate method to manage large directory trees") % { path: path, entries: files.size, soft_max_files: soft_max_files }
end
# Now strip off the leading path, so each file becomes relative, and remove
# any slashes that might end up at the beginning of the path.
result = files.collect { |file| file.sub(%r{^#{Regexp.escape(@path)}/*}, '') }
# And add the path itself.
result.unshift(".")
result
end
def ignore=(values)
values = [values] unless values.is_a?(Array)
@ignore = values.collect(&:to_s)
end
def links=(links)
links = links.to_sym
# TRANSLATORS ":links" is a parameter name and should not be translated
raise(ArgumentError, _("Invalid :links value '%{links}'") % { links: links }) unless [:manage, :follow].include?(links)
@links = links
@stat_method = @links == :manage ? :lstat : :stat
end
private
def initialize_from_hash(options)
options.each do |option, value|
method = option.to_s + "="
begin
send(method, value)
rescue NoMethodError => e
raise ArgumentError, _("Invalid option '%{option}'") % { option: option }, e.backtrace
end
end
end
def initialize_from_request(request)
[:links, :ignore, :recurse, :recurselimit, :max_files, :checksum_type].each do |param|
if request.options.include?(param) # use 'include?' so the values can be false
value = request.options[param]
elsif request.options.include?(param.to_s)
value = request.options[param.to_s]
end
next if value.nil?
value = true if value == "true"
value = false if value == "false"
value = Integer(value) if value.is_a?(String) and value =~ /^\d+$/
send(param.to_s + "=", value)
end
end
FileSetEntry = Struct.new(:depth, :path, :ignored, :stat_method) do
def down_level(to)
FileSetEntry.new(depth + 1, File.join(path, to), ignored, stat_method)
end
def basename
File.basename(path)
end
def children
return [] unless directory?
Dir.entries(path, encoding: Encoding::UTF_8)
.reject { |child| ignore?(child) }
.collect { |child| down_level(child) }
end
def ignore?(child)
return true if child == "." || child == ".."
return false if ignored == [nil]
ignored.any? { |pattern| File.fnmatch?(pattern, child) }
end
def directory?
Puppet::FileSystem.send(stat_method, path).directory?
rescue Errno::ENOENT, Errno::EACCES
false
end
end
# Pull the recursion logic into one place. It's moderately hairy, and this
# allows us to keep the hairiness apart from what we do with the files.
def perform_recursion
current_dirs = [FileSetEntry.new(0, @path, @ignore, @stat_method)]
result = []
while entry = current_dirs.shift # rubocop:disable Lint/AssignmentInCondition
next unless continue_recursion_at?(entry.depth + 1)
entry.children.each do |child|
result << child.path
current_dirs << child
end
end
result
end
def valid?(path)
Puppet::FileSystem.send(@stat_method, path)
true
rescue Errno::ENOENT, Errno::EACCES
false
end
def continue_recursion_at?(depth)
# recurse if told to, and infinite recursion or current depth not at the limit
recurse && (recurselimit == :infinite || depth <= recurselimit)
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/file_serving/mount.rb | lib/puppet/file_serving/mount.rb | # frozen_string_literal: true
require_relative '../../puppet/util/logging'
require_relative '../../puppet/file_serving'
require_relative '../../puppet/file_serving/metadata'
require_relative '../../puppet/file_serving/content'
# Broker access to the filesystem, converting local URIs into metadata
# or content objects.
class Puppet::FileServing::Mount
include Puppet::Util::Logging
attr_reader :name
def find(path, options)
raise NotImplementedError
end
# Create our object. It must have a name.
def initialize(name)
unless name =~ /^[-\w]+$/
raise ArgumentError, _("Invalid mount name format '%{name}'") % { name: name }
end
@name = name
super()
end
def search(path, options)
raise NotImplementedError
end
def to_s
"mount[#{@name}]"
end
# A noop.
def validate
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/file_serving/metadata.rb | lib/puppet/file_serving/metadata.rb | # frozen_string_literal: true
require_relative '../../puppet'
require_relative '../../puppet/indirector'
require_relative '../../puppet/file_serving'
require_relative '../../puppet/file_serving/base'
require_relative '../../puppet/util/checksums'
require 'uri'
# A class that handles retrieving file metadata.
class Puppet::FileServing::Metadata < Puppet::FileServing::Base
include Puppet::Util::Checksums
extend Puppet::Indirector
indirects :file_metadata, :terminus_class => :selector
attr_reader :path, :owner, :group, :mode, :checksum_type, :checksum, :ftype, :destination, :source_permissions, :content_uri
PARAM_ORDER = [:mode, :ftype, :owner, :group]
def checksum_type=(type)
raise(ArgumentError, _("Unsupported checksum type %{type}") % { type: type }) unless Puppet::Util::Checksums.respond_to?("#{type}_file")
@checksum_type = type
end
def source_permissions=(source_permissions)
raise(ArgumentError, _("Unsupported source_permission %{source_permissions}") % { source_permissions: source_permissions }) unless [:use, :use_when_creating, :ignore].include?(source_permissions.intern)
@source_permissions = source_permissions.intern
end
def content_uri=(path)
begin
uri = URI.parse(Puppet::Util.uri_encode(path))
rescue URI::InvalidURIError => detail
raise(ArgumentError, _("Could not understand URI %{path}: %{detail}") % { path: path, detail: detail })
end
raise(ArgumentError, _("Cannot use opaque URLs '%{path}'") % { path: path }) unless uri.hierarchical?
raise(ArgumentError, _("Must use URLs of type puppet as content URI")) if uri.scheme != "puppet"
@content_uri = path.encode(Encoding::UTF_8)
end
class MetaStat
extend Forwardable
def initialize(stat, source_permissions)
@stat = stat
@source_permissions_ignore = !source_permissions || source_permissions == :ignore
end
def owner
@source_permissions_ignore ? Process.euid : @stat.uid
end
def group
@source_permissions_ignore ? Process.egid : @stat.gid
end
def mode
@source_permissions_ignore ? 0o644 : @stat.mode
end
def_delegators :@stat, :ftype
end
class WindowsStat < MetaStat
if Puppet::Util::Platform.windows?
require_relative '../../puppet/util/windows/security'
end
def initialize(stat, path, source_permissions)
super(stat, source_permissions)
@path = path
raise(ArgumentError, _("Unsupported Windows source permissions option %{source_permissions}") % { source_permissions: source_permissions }) unless @source_permissions_ignore
end
{ :owner => 'S-1-5-32-544',
:group => 'S-1-0-0',
:mode => 0o644 }.each do |method, default_value|
define_method method do
default_value
end
end
end
def collect_stat(path)
stat = stat()
if Puppet::Util::Platform.windows?
WindowsStat.new(stat, path, @source_permissions)
else
MetaStat.new(stat, @source_permissions)
end
end
# Retrieve the attributes for this file, relative to a base directory.
# Note that Puppet::FileSystem.stat(path) raises Errno::ENOENT
# if the file is absent and this method does not catch that exception.
def collect(source_permissions = nil)
real_path = full_path
stat = collect_stat(real_path)
@owner = stat.owner
@group = stat.group
@ftype = stat.ftype
# We have to mask the mode, yay.
@mode = stat.mode & 0o07777
case stat.ftype
when "file"
@checksum = "{#{@checksum_type}}" + send("#{@checksum_type}_file", real_path).to_s
when "directory" # Always just timestamp the directory.
@checksum_type = "ctime"
@checksum = "{#{@checksum_type}}" + send("#{@checksum_type}_file", path).to_s
when "link"
@destination = Puppet::FileSystem.readlink(real_path)
@checksum = begin
"{#{@checksum_type}}" + send("#{@checksum_type}_file", real_path).to_s
rescue
nil
end
when "fifo", "socket"
@checksum_type = "none"
@checksum = "{#{@checksum_type}}" + send("#{@checksum_type}_file", real_path).to_s
else
raise ArgumentError, _("Cannot manage files of type %{file_type}") % { file_type: stat.ftype }
end
end
def initialize(path, data = {})
@owner = data.delete('owner')
@group = data.delete('group')
@mode = data.delete('mode')
checksum = data.delete('checksum')
if checksum
@checksum_type = checksum['type']
@checksum = checksum['value']
end
@checksum_type ||= Puppet[:digest_algorithm]
@ftype = data.delete('type')
@destination = data.delete('destination')
@source = data.delete('source')
@content_uri = data.delete('content_uri')
links = data.fetch('links', nil) || data.fetch(:links, nil)
relative_path = data.fetch('relative_path', nil) || data.fetch(:relative_path, nil)
source = @source || data.fetch(:source, nil)
super(path, links: links, relative_path: relative_path, source: source)
end
def to_data_hash
super.update(
{
'owner' => owner,
'group' => group,
'mode' => mode,
'checksum' => {
'type' => checksum_type,
'value' => checksum
},
'type' => ftype,
'destination' => destination,
}.merge(content_uri ? { 'content_uri' => content_uri } : {})
.merge(source ? { 'source' => source } : {})
)
end
def self.from_data_hash(data)
new(data.delete('path'), data)
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/file_serving/mount/plugins.rb | lib/puppet/file_serving/mount/plugins.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/mount'
# Find files in the modules' plugins directories.
# This is a very strange mount because it merges
# many directories into one.
class Puppet::FileServing::Mount::Plugins < Puppet::FileServing::Mount
# Return an instance of the appropriate class.
def find(relative_path, request)
mod = request.environment.modules.find { |m| m.plugin(relative_path) }
return nil unless mod
mod.plugin(relative_path)
end
def search(relative_path, request)
# We currently only support one kind of search on plugins - return
# them all.
paths = request.environment.modules.find_all(&:plugins?).collect(&:plugin_directory)
if paths.empty?
# If the modulepath is valid then we still need to return a valid root
# directory for the search, but make sure nothing inside it is
# returned.
request.options[:recurse] = false
request.environment.modulepath.empty? ? [Puppet[:codedir]] : request.environment.modulepath
else
paths
end
end
def valid?
true
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/file_serving/mount/file.rb | lib/puppet/file_serving/mount/file.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/mount'
class Puppet::FileServing::Mount::File < Puppet::FileServing::Mount
def self.localmap
@localmap ||= {
"h" => Puppet.runtime[:facter].value('networking.hostname'),
"H" => [
Puppet.runtime[:facter].value('networking.hostname'),
Puppet.runtime[:facter].value('networking.domain')
].join("."),
"d" => Puppet.runtime[:facter].value('networking.domain')
}
end
def complete_path(relative_path, node)
full_path = path(node)
raise ArgumentError, _("Mounts without paths are not usable") unless full_path
# If there's no relative path name, then we're serving the mount itself.
return full_path unless relative_path
file = ::File.join(full_path, relative_path)
unless Puppet::FileSystem.exist?(file) or Puppet::FileSystem.symlink?(file)
Puppet.info(_("File does not exist or is not accessible: %{file}") % { file: file })
return nil
end
file
end
# Return an instance of the appropriate class.
def find(short_file, request)
complete_path(short_file, request.node)
end
# Return the path as appropriate, expanding as necessary.
def path(node = nil)
if expandable?
expand(@path, node)
else
@path
end
end
# Set the path.
def path=(path)
# FIXME: For now, just don't validate paths with replacement
# patterns in them.
if path =~ /%./
# Mark that we're expandable.
@expandable = true
else
raise ArgumentError, _("%{path} does not exist or is not a directory") % { path: path } unless FileTest.directory?(path)
raise ArgumentError, _("%{path} is not readable") % { path: path } unless FileTest.readable?(path)
@expandable = false
end
@path = path
end
def search(path, request)
path = complete_path(path, request.node)
return nil unless path
[path]
end
# Verify our configuration is valid. This should really check to
# make sure at least someone will be allowed, but, eh.
def validate
raise ArgumentError, _("Mounts without paths are not usable") if @path.nil?
end
private
# Create a map for a specific node.
def clientmap(node)
{
"h" => node.sub(/\..*$/, ""),
"H" => node,
"d" => node.sub(/[^.]+\./, "") # domain name
}
end
# Replace % patterns as appropriate.
def expand(path, node = nil)
# This map should probably be moved into a method.
map = nil
if node
map = clientmap(node)
else
Puppet.notice _("No client; expanding '%{path}' with local host") % { path: path }
# Else, use the local information
map = localmap
end
path.gsub(/%(.)/) do |v|
key = ::Regexp.last_match(1)
if key == "%"
"%"
else
map[key] || v
end
end
end
# Do we have any patterns in our path, yo?
def expandable?
if defined?(@expandable)
@expandable
else
false
end
end
# Cache this manufactured map, since if it's used it's likely
# to get used a lot.
def localmap
self.class.localmap
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/file_serving/mount/scripts.rb | lib/puppet/file_serving/mount/scripts.rb | # frozen_string_literal: true
require 'puppet/file_serving/mount'
class Puppet::FileServing::Mount::Scripts < Puppet::FileServing::Mount
# Return an instance of the appropriate class.
def find(path, request)
raise _("No module specified") if path.to_s.empty?
module_name, relative_path = path.split("/", 2)
mod = request.environment.module(module_name)
return nil unless mod
mod.script(relative_path)
end
def search(path, request)
result = find(path, request)
if result
[result]
end
end
def valid?
true
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/file_serving/mount/pluginfacts.rb | lib/puppet/file_serving/mount/pluginfacts.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/mount'
# Find files in the modules' pluginfacts directories.
# This is a very strange mount because it merges
# many directories into one.
class Puppet::FileServing::Mount::PluginFacts < Puppet::FileServing::Mount
# Return an instance of the appropriate class.
def find(relative_path, request)
mod = request.environment.modules.find { |m| m.pluginfact(relative_path) }
return nil unless mod
mod.pluginfact(relative_path)
end
def search(relative_path, request)
# We currently only support one kind of search on plugins - return
# them all.
paths = request.environment.modules.find_all(&:pluginfacts?).collect(&:plugin_fact_directory)
if paths.empty?
# If the modulepath is valid then we still need to return a valid root
# directory for the search, but make sure nothing inside it is
# returned.
request.options[:recurse] = false
request.environment.modulepath.empty? ? [Puppet[:codedir]] : request.environment.modulepath
else
paths
end
end
def valid?
true
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/file_serving/mount/locales.rb | lib/puppet/file_serving/mount/locales.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/mount'
# Find files in the modules' locales directories.
# This is a very strange mount because it merges
# many directories into one.
class Puppet::FileServing::Mount::Locales < Puppet::FileServing::Mount
# Return an instance of the appropriate class.
def find(relative_path, request)
mod = request.environment.modules.find { |m| m.locale(relative_path) }
return nil unless mod
mod.locale(relative_path)
end
def search(relative_path, request)
# We currently only support one kind of search on locales - return
# them all.
paths = request.environment.modules.find_all(&:locales?).collect(&:locale_directory)
if paths.empty?
# If the modulepath is valid then we still need to return a valid root
# directory for the search, but make sure nothing inside it is
# returned.
request.options[:recurse] = false
request.environment.modulepath.empty? ? [Puppet[:codedir]] : request.environment.modulepath
else
paths
end
end
def valid?
true
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/file_serving/mount/tasks.rb | lib/puppet/file_serving/mount/tasks.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/mount'
class Puppet::FileServing::Mount::Tasks < Puppet::FileServing::Mount
def find(path, request)
raise _("No task specified") if path.to_s.empty?
module_name, task_path = path.split("/", 2)
mod = request.environment.module(module_name)
return nil unless mod
mod.task_file(task_path)
end
def search(path, request)
result = find(path, request)
if result
[result]
end
end
def valid?
true
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/file_serving/mount/modules.rb | lib/puppet/file_serving/mount/modules.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/mount'
# This is the modules-specific mount: it knows how to search through
# modules for files. Yay.
class Puppet::FileServing::Mount::Modules < Puppet::FileServing::Mount
# Return an instance of the appropriate class.
def find(path, request)
raise _("No module specified") if path.to_s.empty?
module_name, relative_path = path.split("/", 2)
mod = request.environment.module(module_name)
return nil unless mod
mod.file(relative_path)
end
def search(path, request)
result = find(path, request)
if result
[result]
end
end
def valid?
true
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/file_serving/configuration/parser.rb | lib/puppet/file_serving/configuration/parser.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/configuration'
require_relative '../../../puppet/util/watched_file'
class Puppet::FileServing::Configuration::Parser
Mount = Puppet::FileServing::Mount
MODULES = 'modules'
# Parse our configuration file.
def parse
raise(_("File server configuration %{config_file} does not exist") % { config_file: @file }) unless Puppet::FileSystem.exist?(@file)
raise(_("Cannot read file server configuration %{config_file}") % { config_file: @file }) unless FileTest.readable?(@file)
@mounts = {}
@count = 0
File.open(@file) do |f|
mount = nil
f.each_line do |line|
# Have the count increment at the top, in case we throw exceptions.
@count += 1
case line
when /^\s*#/; next # skip comments
when /^\s*$/; next # skip blank lines
when /\[([-\w]+)\]/
mount = newmount(::Regexp.last_match(1))
when /^\s*(\w+)\s+(.+?)(\s*#.*)?$/
var = ::Regexp.last_match(1)
value = ::Regexp.last_match(2)
value.strip!
raise(ArgumentError, _("Fileserver configuration file does not use '=' as a separator")) if value =~ /^=/
case var
when "path"
path(mount, value)
when "allow", "deny"
# ignore `allow *`, otherwise report error
if var != 'allow' || value != '*'
error_location_str = Puppet::Util::Errors.error_location(@file.filename, @count)
Puppet.err("Entry '#{line.chomp}' is unsupported and will be ignored at #{error_location_str}")
end
else
error_location_str = Puppet::Util::Errors.error_location(@file.filename, @count)
raise ArgumentError, _("Invalid argument '%{var}' at %{error_location}") %
{ var: var, error_location: error_location_str }
end
else
error_location_str = Puppet::Util::Errors.error_location(@file.filename, @count)
raise ArgumentError, _("Invalid entry at %{error_location}: '%{file_text}'") %
{ file_text: line.chomp, error_location: error_location_str }
end
end
end
validate
@mounts
end
def initialize(filename)
@file = Puppet::Util::WatchedFile.new(filename)
end
def changed?
@file.changed?
end
private
# Create a new mount.
def newmount(name)
if @mounts.include?(name)
error_location_str = Puppet::Util::Errors.error_location(@file, @count)
raise ArgumentError, _("%{mount} is already mounted at %{name} at %{error_location}") %
{ mount: @mounts[name], name: name, error_location: error_location_str }
end
case name
when "modules"
mount = Mount::Modules.new(name)
when "plugins"
mount = Mount::Plugins.new(name)
when "scripts"
mount = Mount::Scripts.new(name)
when "tasks"
mount = Mount::Tasks.new(name)
when "locales"
mount = Mount::Locales.new(name)
else
mount = Mount::File.new(name)
end
@mounts[name] = mount
mount
end
# Set the path for a mount.
def path(mount, value)
if mount.respond_to?(:path=)
begin
mount.path = value
rescue ArgumentError => detail
Puppet.log_exception(detail, _("Removing mount \"%{mount}\": %{detail}") % { mount: mount.name, detail: detail })
@mounts.delete(mount.name)
end
else
Puppet.warning _("The '%{mount}' module can not have a path. Ignoring attempt to set it") % { mount: mount.name }
end
end
# Make sure all of our mounts are valid. We have to do this after the fact
# because details are added over time as the file is parsed.
def validate
@mounts.each { |_name, mount| mount.validate }
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/module/task.rb | lib/puppet/module/task.rb | # frozen_string_literal: true
require_relative '../../puppet/util/logging'
class Puppet::Module
class Task
class Error < Puppet::Error
attr_accessor :kind, :details
def initialize(message, kind, details = nil)
super(message)
@details = details || {}
@kind = kind
end
def to_h
{
msg: message,
kind: kind,
details: details
}
end
end
class InvalidName < Error
def initialize(name)
msg = _("Task names must start with a lowercase letter and be composed of only lowercase letters, numbers, and underscores")
super(msg, 'puppet.tasks/invalid-name')
end
end
class InvalidFile < Error
def initialize(msg)
super(msg, 'puppet.tasks/invalid-file')
end
end
class InvalidTask < Error
end
class InvalidMetadata < Error
end
class TaskNotFound < Error
def initialize(task_name, module_name)
msg = _("Task %{task_name} not found in module %{module_name}.") %
{ task_name: task_name, module_name: module_name }
super(msg, 'puppet.tasks/task-not-found', { 'name' => task_name })
end
end
FORBIDDEN_EXTENSIONS = %w[.conf .md]
MOUNTS = %w[files lib scripts tasks]
def self.is_task_name?(name)
return true if name =~ /^[a-z][a-z0-9_]*$/
false
end
def self.is_tasks_file?(path)
File.file?(path) && is_tasks_filename?(path)
end
# Determine whether a file has a legal name for either a task's executable or metadata file.
def self.is_tasks_filename?(path)
name_less_extension = File.basename(path, '.*')
return false unless is_task_name?(name_less_extension)
FORBIDDEN_EXTENSIONS.each do |ext|
return false if path.end_with?(ext)
end
true
end
def self.get_file_details(path, mod)
# This gets the path from the starting point onward
# For files this should be the file subpath from the metadata
# For directories it should be the directory subpath plus whatever we globbed
# Partition matches on the first instance it finds of the parameter
name = "#{mod.name}#{path.partition(mod.path).last}"
{ "name" => name, "path" => path }
end
private_class_method :get_file_details
# Find task's required lib files and retrieve paths for both 'files' and 'implementation:files' metadata keys
def self.find_extra_files(metadata, envname = nil)
return [] if metadata.nil?
files = metadata.fetch('files', [])
unless files.is_a?(Array)
msg = _("The 'files' task metadata expects an array, got %{files}.") % { files: files }
raise InvalidMetadata.new(msg, 'puppet.tasks/invalid-metadata')
end
impl_files = metadata.fetch('implementations', []).flat_map do |impl|
file_array = impl.fetch('files', [])
unless file_array.is_a?(Array)
msg = _("The 'files' task metadata expects an array, got %{files}.") % { files: file_array }
raise InvalidMetadata.new(msg, 'puppet.tasks/invalid-metadata')
end
file_array
end
combined_files = files + impl_files
combined_files.uniq.flat_map do |file|
module_name, mount, endpath = file.split("/", 3)
# If there's a mount directory with no trailing slash this will be nil
# We want it to be empty to construct a path
endpath ||= ''
pup_module = Puppet::Module.find(module_name, envname)
if pup_module.nil?
msg = _("Could not find module %{module_name} containing task file %{filename}" %
{ module_name: module_name, filename: endpath })
raise InvalidMetadata.new(msg, 'puppet.tasks/invalid-metadata')
end
unless MOUNTS.include? mount
msg = _("Files must be saved in module directories that Puppet makes available via mount points: %{mounts}" %
{ mounts: MOUNTS.join(', ') })
raise InvalidMetadata.new(msg, 'puppet.tasks/invalid-metadata')
end
path = File.join(pup_module.path, mount, endpath)
unless File.absolute_path(path) == File.path(path).chomp('/')
msg = _("File pathnames cannot include relative paths")
raise InvalidMetadata.new(msg, 'puppet.tasks/invalid-metadata')
end
unless File.exist?(path)
msg = _("Could not find %{path} on disk" % { path: path })
raise InvalidFile, msg
end
last_char = file[-1] == '/'
if File.directory?(path)
unless last_char
msg = _("Directories specified in task metadata must include a trailing slash: %{dir}" % { dir: file })
raise InvalidMetadata.new(msg, 'puppet.tasks/invalid-metadata')
end
dir_files = Dir.glob("#{path}**/*").select { |f| File.file?(f) }
dir_files.map { |f| get_file_details(f, pup_module) }
else
if last_char
msg = _("Files specified in task metadata cannot include a trailing slash: %{file}" % { file: file })
raise InvalidMetadata.new(msg, 'puppet.task/invalid-metadata')
end
get_file_details(path, pup_module)
end
end
end
private_class_method :find_extra_files
# Executables list should contain the full path of all possible implementation files
def self.find_implementations(name, directory, metadata, executables)
basename = name.split('::')[1] || 'init'
# If 'implementations' is defined, it needs to mention at least one
# implementation, and everything it mentions must exist.
metadata ||= {}
if metadata.key?('implementations')
unless metadata['implementations'].is_a?(Array)
msg = _("Task metadata for task %{name} does not specify implementations as an array" % { name: name })
raise InvalidMetadata.new(msg, 'puppet.tasks/invalid-metadata')
end
implementations = metadata['implementations'].map do |impl|
unless impl['requirements'].is_a?(Array) || impl['requirements'].nil?
msg = _("Task metadata for task %{name} does not specify requirements as an array" % { name: name })
raise InvalidMetadata.new(msg, 'puppet.tasks/invalid-metadata')
end
path = executables.find { |real_impl| File.basename(real_impl) == impl['name'] }
unless path
msg = _("Task metadata for task %{name} specifies missing implementation %{implementation}" % { name: name, implementation: impl['name'] })
raise InvalidTask.new(msg, 'puppet.tasks/missing-implementation', { missing: [impl['name']] })
end
{ "name" => impl['name'], "path" => path }
end
return implementations
end
# If implementations isn't defined, then we use executables matching the
# task name, and only one may exist.
implementations = executables.select { |impl| File.basename(impl, '.*') == basename }
if implementations.empty?
msg = _('No source besides task metadata was found in directory %{directory} for task %{name}') %
{ name: name, directory: directory }
raise InvalidTask.new(msg, 'puppet.tasks/no-implementation')
elsif implementations.length > 1
msg = _("Multiple executables were found in directory %{directory} for task %{name}; define 'implementations' in metadata to differentiate between them") %
{ name: name, directory: implementations[0] }
raise InvalidTask.new(msg, 'puppet.tasks/multiple-implementations')
end
[{ "name" => File.basename(implementations.first), "path" => implementations.first }]
end
private_class_method :find_implementations
def self.find_files(name, directory, metadata, executables, envname = nil)
# PXP agent relies on 'impls' (which is the task file) being first if there is no metadata
find_implementations(name, directory, metadata, executables) + find_extra_files(metadata, envname)
end
def self.is_tasks_metadata_filename?(name)
is_tasks_filename?(name) && name.end_with?('.json')
end
def self.is_tasks_executable_filename?(name)
is_tasks_filename?(name) && !name.end_with?('.json')
end
def self.tasks_in_module(pup_module)
task_files = Dir.glob(File.join(pup_module.tasks_directory, '*'))
.keep_if { |f| is_tasks_file?(f) }
module_executables = task_files.reject(&method(:is_tasks_metadata_filename?)).map.to_a
tasks = task_files.group_by { |f| task_name_from_path(f) }
tasks.map do |task, executables|
new_with_files(pup_module, task, executables, module_executables)
end
end
attr_reader :name, :module, :metadata_file
# file paths must be relative to the modules task directory
def initialize(pup_module, task_name, module_executables, metadata_file = nil)
unless Puppet::Module::Task.is_task_name?(task_name)
raise InvalidName, _("Task names must start with a lowercase letter and be composed of only lowercase letters, numbers, and underscores")
end
name = task_name == "init" ? pup_module.name : "#{pup_module.name}::#{task_name}"
@module = pup_module
@name = name
@metadata_file = metadata_file
@module_executables = module_executables || []
end
def self.read_metadata(file)
if file
content = Puppet::FileSystem.read(file, :encoding => 'utf-8')
content.empty? ? {} : Puppet::Util::Json.load(content)
end
rescue SystemCallError, IOError => err
msg = _("Error reading metadata: %{message}" % { message: err.message })
raise InvalidMetadata.new(msg, 'puppet.tasks/unreadable-metadata')
rescue Puppet::Util::Json::ParseError => err
raise InvalidMetadata.new(err.message, 'puppet.tasks/unparseable-metadata')
end
def metadata
@metadata ||= self.class.read_metadata(@metadata_file)
end
def files
@files ||= self.class.find_files(@name, @module.tasks_directory, metadata, @module_executables, environment_name)
end
def validate
files
true
end
def ==(other)
name == other.name &&
self.module == other.module
end
def environment_name
@module.environment.respond_to?(:name) ? @module.environment.name : 'production'
end
private :environment_name
def self.new_with_files(pup_module, name, task_files, module_executables)
metadata_file = task_files.find { |f| is_tasks_metadata_filename?(f) }
Puppet::Module::Task.new(pup_module, name, module_executables, metadata_file)
end
private_class_method :new_with_files
# Abstracted here so we can add support for subdirectories later
def self.task_name_from_path(path)
File.basename(path, '.*')
end
private_class_method :task_name_from_path
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/module/plan.rb | lib/puppet/module/plan.rb | # frozen_string_literal: true
require_relative '../../puppet/util/logging'
class Puppet::Module
class Plan
class Error < Puppet::Error
attr_accessor :kind, :details
def initialize(message, kind, details = nil)
super(message)
@details = details || {}
@kind = kind
end
def to_h
{
msg: message,
kind: kind,
details: details
}
end
end
class InvalidName < Error
def initialize(name, msg)
super(msg, 'puppet.plans/invalid-name')
end
end
class InvalidFile < Error
def initialize(msg)
super(msg, 'puppet.plans/invalid-file')
end
end
class InvalidPlan < Error
end
class InvalidMetadata < Error
end
class PlanNotFound < Error
def initialize(plan_name, module_name)
msg = _("Plan %{plan_name} not found in module %{module_name}.") %
{ plan_name: plan_name, module_name: module_name }
super(msg, 'puppet.plans/plan-not-found', { 'name' => plan_name })
end
end
ALLOWED_EXTENSIONS = %w[.pp .yaml]
RESERVED_WORDS = %w[and application attr case class consumes default else
elsif environment false function if import in inherits node or private
produces site true type undef unless]
RESERVED_DATA_TYPES = %w[any array boolean catalogentry class collection
callable data default enum float hash integer numeric optional pattern
resource runtime scalar string struct tuple type undef variant]
def self.is_plan_name?(name)
return true if name =~ /^[a-z][a-z0-9_]*$/
false
end
# Determine whether a plan file has a legal name and extension
def self.is_plans_filename?(path)
name = File.basename(path, '.*')
ext = File.extname(path)
return [false, _("Plan names must start with a lowercase letter and be composed of only lowercase letters, numbers, and underscores")] unless is_plan_name?(name)
unless ALLOWED_EXTENSIONS.include? ext
return [false, _("Plan name cannot have extension %{ext}, must be .pp or .yaml") % { ext: ext }]
end
if RESERVED_WORDS.include?(name)
return [false, _("Plan name cannot be a reserved word, but was '%{name}'") % { name: name }]
end
if RESERVED_DATA_TYPES.include?(name)
return [false, _("Plan name cannot be a Puppet data type, but was '%{name}'") % { name: name }]
end
[true]
end
# Executables list should contain the full path of all possible implementation files
def self.find_implementations(name, plan_files)
basename = name.split('::')[1] || 'init'
# If implementations isn't defined, then we use executables matching the
# plan name, and only one may exist.
implementations = plan_files.select { |impl| File.basename(impl, '.*') == basename }
# Select .pp before .yaml, since .pp comes before .yaml alphabetically.
chosen = implementations.min
[{ "name" => File.basename(chosen), "path" => chosen }]
end
private_class_method :find_implementations
def self.find_files(name, plan_files)
find_implementations(name, plan_files)
end
def self.plans_in_module(pup_module)
# Search e.g. 'modules/<pup_module>/plans' for all plans
plan_files = Dir.glob(File.join(pup_module.plans_directory, '*'))
.keep_if { |f| valid, _ = is_plans_filename?(f); valid }
plans = plan_files.group_by { |f| plan_name_from_path(f) }
plans.map do |plan, plan_filenames|
new_with_files(pup_module, plan, plan_filenames)
end
end
attr_reader :name, :module, :metadata_file
# file paths must be relative to the modules plan directory
def initialize(pup_module, plan_name, plan_files)
valid, reason = Puppet::Module::Plan.is_plans_filename?(plan_files.first)
unless valid
raise InvalidName.new(plan_name, reason)
end
name = plan_name == "init" ? pup_module.name : "#{pup_module.name}::#{plan_name}"
@module = pup_module
@name = name
@metadata_file = metadata_file
@plan_files = plan_files || []
end
def metadata
# Nothing to go here unless plans eventually support metadata.
@metadata ||= {}
end
def files
@files ||= self.class.find_files(@name, @plan_files)
end
def validate
files
true
end
def ==(other)
name == other.name &&
self.module == other.module
end
def environment_name
@module.environment.respond_to?(:name) ? @module.environment.name : 'production'
end
private :environment_name
def self.new_with_files(pup_module, name, plan_files)
Puppet::Module::Plan.new(pup_module, name, plan_files)
end
private_class_method :new_with_files
# Abstracted here so we can add support for subdirectories later
def self.plan_name_from_path(path)
File.basename(path, '.*')
end
private_class_method :plan_name_from_path
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/module_tool/errors.rb | lib/puppet/module_tool/errors.rb | # frozen_string_literal: true
require_relative '../../puppet/module_tool'
module Puppet::ModuleTool
module Errors
require_relative 'errors/base'
require_relative 'errors/installer'
require_relative 'errors/uninstaller'
require_relative 'errors/upgrader'
require_relative 'errors/shared'
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/module_tool/tar.rb | lib/puppet/module_tool/tar.rb | # frozen_string_literal: true
require_relative '../../puppet/module_tool'
require_relative '../../puppet/util'
module Puppet::ModuleTool::Tar
require_relative 'tar/gnu'
require_relative 'tar/mini'
def self.instance
if Puppet.features.minitar? && Puppet.features.zlib?
Mini.new
elsif Puppet::Util.which('tar') && !Puppet::Util::Platform.windows?
Gnu.new
else
# TRANSLATORS "tar" is a program name and should not be translated
raise RuntimeError, _('No suitable tar implementation found')
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/module_tool/applications.rb | lib/puppet/module_tool/applications.rb | # frozen_string_literal: true
require_relative '../../puppet/module_tool'
module Puppet::ModuleTool
module Applications
require_relative 'applications/application'
require_relative 'applications/checksummer'
require_relative 'applications/installer'
require_relative 'applications/unpacker'
require_relative 'applications/uninstaller'
require_relative 'applications/upgrader'
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/module_tool/shared_behaviors.rb | lib/puppet/module_tool/shared_behaviors.rb | # frozen_string_literal: true
module Puppet::ModuleTool::Shared
include Puppet::ModuleTool::Errors
def get_local_constraints
@local = Hash.new { |h, k| h[k] = {} }
@conditions = Hash.new { |h, k| h[k] = [] }
@installed = Hash.new { |h, k| h[k] = [] }
@environment.modules_by_path.values.flatten.each do |mod|
mod_name = (mod.forge_name || mod.name).tr('/', '-')
@installed[mod_name] << mod
d = @local["#{mod_name}@#{mod.version}"]
(mod.dependencies || []).each do |hash|
name = hash['name']
conditions = hash['version_requirement']
name = name.tr('/', '-')
d[name] = conditions
@conditions[name] << {
:module => mod_name,
:version => mod.version,
:dependency => conditions
}
end
end
end
def get_remote_constraints(forge)
@remote = Hash.new { |h, k| h[k] = {} }
@urls = {}
@versions = Hash.new { |h, k| h[k] = [] }
Puppet.notice _("Downloading from %{uri} ...") % { uri: forge.uri }
author, modname = Puppet::ModuleTool.username_and_modname_from(@module_name)
info = forge.remote_dependency_info(author, modname, @options[:version])
info.each do |pair|
mod_name, releases = pair
mod_name = mod_name.tr('/', '-')
releases.each do |rel|
semver = begin
SemanticPuppet::Version.parse(rel['version'])
rescue
SemanticPuppet::Version::MIN
end
@versions[mod_name] << { :vstring => rel['version'], :semver => semver }
@versions[mod_name].sort_by! { |a| a[:semver] }
@urls["#{mod_name}@#{rel['version']}"] = rel['file']
d = @remote["#{mod_name}@#{rel['version']}"]
(rel['dependencies'] || []).each do |name, conditions|
d[name.tr('/', '-')] = conditions
end
end
end
end
def implicit_version(mod)
return :latest if @conditions[mod].empty?
if @conditions[mod].all? { |c| c[:queued] || c[:module] == :you }
return :latest
end
:best
end
def annotated_version(mod, versions)
if versions.empty?
implicit_version(mod)
else
"#{implicit_version(mod)}: #{versions.last}"
end
end
def resolve_constraints(dependencies, source = [{ :name => :you }], seen = {}, action = @action)
dependencies = dependencies.filter_map do |mod, range|
source.last[:dependency] = range
@conditions[mod] << {
:module => source.last[:name],
:version => source.last[:version],
:dependency => range,
:queued => true
}
if forced?
range = begin
Puppet::Module.parse_range(@version)
rescue
Puppet::Module.parse_range('>= 0.0.0')
end
else
range = (@conditions[mod]).map do |r|
Puppet::Module.parse_range(r[:dependency])
rescue
Puppet::Module.parse_range('>= 0.0.0')
end.inject(&:&)
end
if @action == :install && seen.include?(mod)
next if range === seen[mod][:semver]
req_module = @module_name
req_versions = @versions[@module_name.to_s].map { |v| v[:semver] }
raise InvalidDependencyCycleError,
:module_name => mod,
:source => (source + [{ :name => mod, :version => source.last[:dependency] }]),
:requested_module => req_module,
:requested_version => @version || annotated_version(req_module, req_versions),
:conditions => @conditions
end
if !(forced? || @installed[mod].empty? || source.last[:name] == :you)
next if range === SemanticPuppet::Version.parse(@installed[mod].first.version)
action = :upgrade
elsif @installed[mod].empty?
action = :install
end
if action == :upgrade
@conditions.each { |_, conds| conds.delete_if { |c| c[:module] == mod } }
end
versions = @versions[mod.to_s].select { |h| range === h[:semver] }
valid_versions = versions.select { |x| x[:semver].special == '' }
valid_versions = versions if valid_versions.empty?
version = valid_versions.last
unless version
req_module = @module_name
req_versions = @versions[@module_name.to_s].map { |v| v[:semver] }
raise NoVersionsSatisfyError,
:requested_name => req_module,
:requested_version => @version || annotated_version(req_module, req_versions),
:installed_version => @installed[@module_name].empty? ? nil : @installed[@module_name].first.version,
:dependency_name => mod,
:conditions => @conditions[mod],
:action => @action
end
seen[mod] = version
{
:module => mod,
:version => version,
:action => action,
:previous_version => @installed[mod].empty? ? nil : @installed[mod].first.version,
:file => @urls["#{mod}@#{version[:vstring]}"],
:path => if action == :install
@options[:target_dir]
else
@installed[mod].empty? ? @options[:target_dir] : @installed[mod].first.modulepath
end,
:dependencies => []
}
end
dependencies.each do |mod|
deps = @remote["#{mod[:module]}@#{mod[:version][:vstring]}"].sort_by(&:first)
mod[:dependencies] = resolve_constraints(deps, source + [{ :name => mod[:module], :version => mod[:version][:vstring] }], seen, :install)
end unless @ignore_dependencies
dependencies
end
def download_tarballs(graph, default_path, forge)
graph.map do |release|
begin
if release[:tarball]
cache_path = Pathname(release[:tarball])
else
cache_path = forge.retrieve(release[:file])
end
rescue OpenURI::HTTPError => e
raise RuntimeError, _("Could not download module: %{message}") % { message: e.message }, e.backtrace
end
[
{ (release[:path] ||= default_path) => cache_path },
*download_tarballs(release[:dependencies], default_path, forge)
]
end.flatten
end
def forced?
options[:force]
end
def add_module_name_constraints_to_graph(graph)
# Puppet modules are installed by "module name", but resolved by
# "full name" (including namespace). So that we don't run into
# problems at install time, we should reject any solution that
# depends on multiple nodes with the same "module name".
graph.add_graph_constraint('PMT') do |nodes|
names = nodes.map { |x| x.dependency_names + [x.name] }.flatten
names = names.map { |x| x.tr('/', '-') }.uniq
names = names.map { |x| x[/-(.*)/, 1] }
names.length == names.uniq.length
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/module_tool/contents_description.rb | lib/puppet/module_tool/contents_description.rb | # frozen_string_literal: true
require_relative '../../puppet/module_tool'
module Puppet::ModuleTool
# = ContentsDescription
#
# This class populates +Metadata+'s Puppet type information.
class ContentsDescription
# Instantiate object for string +module_path+.
def initialize(module_path)
@module_path = module_path
end
# Update +Metadata+'s Puppet type information.
def annotate(metadata)
metadata.types.replace data.clone
end
# Return types for this module. Result is an array of hashes, each of which
# describes a Puppet type. The type description hash structure is:
# * :name => Name of this Puppet type.
# * :doc => Documentation for this type.
# * :properties => Array of hashes representing the type's properties, each
# containing :name and :doc.
# * :parameters => Array of hashes representing the type's parameters, each
# containing :name and :doc.
# * :providers => Array of hashes representing the types providers, each
# containing :name and :doc.
# TODO Write a TypeDescription to encapsulate these structures and logic?
def data
unless @data
@data = []
type_names = []
(Dir[File.join(@module_path, "lib/puppet/type/*.rb")]).each do |module_filename|
require module_filename
type_name = File.basename(module_filename, ".rb")
type_names << type_name
(Dir[File.join(@module_path, "lib/puppet/provider/#{type_name}/*.rb")]).each do |provider_filename|
require provider_filename
end
end
type_names.each do |name|
type = Puppet::Type.type(name.to_sym)
if type
type_hash = { :name => name, :doc => type.doc }
type_hash[:properties] = attr_doc(type, :property)
type_hash[:parameters] = attr_doc(type, :param)
if type.providers.size > 0
type_hash[:providers] = provider_doc(type)
end
@data << type_hash
else
Puppet.warning _("Could not find/load type: %{name}") % { name: name }
end
end
end
@data
end
# Return an array of hashes representing this +type+'s attrs of +kind+
# (e.g. :param or :property), each containing :name and :doc.
def attr_doc(type, kind)
attrs = []
type.allattrs.each do |name|
if type.attrtype(name) == kind && name != :provider
attrs.push(:name => name, :doc => type.attrclass(name).doc)
end
end
attrs
end
# Return an array of hashes representing this +type+'s providers, each
# containing :name and :doc.
def provider_doc(type)
providers = []
type.providers.sort.each do |prov|
providers.push(:name => prov, :doc => type.provider(prov).doc)
end
providers
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/module_tool/installed_modules.rb | lib/puppet/module_tool/installed_modules.rb | # frozen_string_literal: true
require 'pathname'
require_relative '../../puppet/forge'
require_relative '../../puppet/module_tool'
module Puppet::ModuleTool
class InstalledModules < SemanticPuppet::Dependency::Source
attr_reader :modules, :by_name
def priority
10
end
def initialize(env)
@env = env
modules = env.modules_by_path
@fetched = []
@modules = {}
@by_name = {}
env.modulepath.each do |path|
modules[path].each do |mod|
@by_name[mod.name] = mod
next unless mod.has_metadata?
release = ModuleRelease.new(self, mod)
@modules[release.name] ||= release
end
end
@modules.freeze
end
# Fetches {ModuleRelease} entries for each release of the named module.
#
# @param name [String] the module name to look up
# @return [Array<SemanticPuppet::Dependency::ModuleRelease>] a list of releases for
# the given name
# @see SemanticPuppet::Dependency::Source#fetch
def fetch(name)
name = name.tr('/', '-')
if @modules.key? name
@fetched << name
[@modules[name]]
else
[]
end
end
def fetched
@fetched
end
class ModuleRelease < SemanticPuppet::Dependency::ModuleRelease
attr_reader :mod, :metadata
def initialize(source, mod)
@mod = mod
@metadata = mod.metadata
name = mod.forge_name.tr('/', '-')
begin
version = SemanticPuppet::Version.parse(mod.version)
rescue SemanticPuppet::Version::ValidationFailure
Puppet.warning _("%{module_name} (%{path}) has an invalid version number (%{version}). The version has been set to 0.0.0. If you are the maintainer for this module, please update the metadata.json with a valid Semantic Version (http://semver.org).") % { module_name: mod.name, path: mod.path, version: mod.version }
version = SemanticPuppet::Version.parse("0.0.0")
end
release = "#{name}@#{version}"
super(source, name, version, {})
if mod.dependencies
mod.dependencies.each do |dependency|
results = Puppet::ModuleTool.parse_module_dependency(release, dependency)
dep_name, parsed_range, range = results
add_constraint('initialize', dep_name, range.to_s) do |node|
parsed_range === node.version
end
end
end
end
def install_dir
Pathname.new(@mod.path).dirname
end
def install(dir)
# If we're already installed, there's no need for us to faff about.
end
def prepare
# We're already installed; what preparation remains?
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/module_tool/local_tarball.rb | lib/puppet/module_tool/local_tarball.rb | # frozen_string_literal: true
require 'pathname'
require 'tmpdir'
require_relative '../../puppet/forge'
require_relative '../../puppet/module_tool'
module Puppet::ModuleTool
class LocalTarball < SemanticPuppet::Dependency::Source
attr_accessor :release
def initialize(filename)
unpack(filename, tmpdir)
Puppet.debug "Unpacked local tarball to #{tmpdir}"
mod = Puppet::Module.new('tarball', tmpdir, nil)
@release = ModuleRelease.new(self, mod)
end
def fetch(name)
if @release.name == name
[@release]
else
[]
end
end
def prepare(release)
release.mod.path
end
def install(release, dir)
staging_dir = release.prepare
module_dir = dir + release.name[/-(.*)/, 1]
module_dir.rmtree if module_dir.exist?
# Make sure unpacked module has the same ownership as the folder we are moving it into.
Puppet::ModuleTool::Applications::Unpacker.harmonize_ownership(dir, staging_dir)
FileUtils.mv(staging_dir, module_dir)
end
class ModuleRelease < SemanticPuppet::Dependency::ModuleRelease
attr_reader :mod, :install_dir, :metadata
def initialize(source, mod)
@mod = mod
@metadata = mod.metadata
name = mod.forge_name.tr('/', '-')
version = SemanticPuppet::Version.parse(mod.version)
release = "#{name}@#{version}"
if mod.dependencies
dependencies = mod.dependencies.map do |dep|
Puppet::ModuleTool.parse_module_dependency(release, dep)[0..1]
end
dependencies = dependencies.to_h
end
super(source, name, version, dependencies || {})
end
def install(dir)
@source.install(self, dir)
@install_dir = dir
end
def prepare
@source.prepare(self)
end
end
private
# Obtain a suitable temporary path for unpacking tarballs
#
# @return [String] path to temporary unpacking location
# rubocop:disable Naming/MemoizedInstanceVariableName
def tmpdir
@dir ||= Dir.mktmpdir('local-tarball', Puppet::Forge::Cache.base_path)
end
# rubocop:enable Naming/MemoizedInstanceVariableName
def unpack(file, destination)
Puppet::ModuleTool::Applications::Unpacker.unpack(file, destination)
rescue Puppet::ExecutionFailure => e
raise RuntimeError, _("Could not extract contents of module archive: %{message}") % { message: e.message }
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/module_tool/install_directory.rb | lib/puppet/module_tool/install_directory.rb | # frozen_string_literal: true
require_relative '../../puppet/module_tool'
require_relative '../../puppet/module_tool/errors'
module Puppet
module ModuleTool
# Control the install location for modules.
class InstallDirectory
include Puppet::ModuleTool::Errors
attr_reader :target
def initialize(target)
@target = target
end
# prepare the module install location. This will create the location if
# needed.
def prepare(module_name, version)
return if @target.directory?
begin
@target.mkpath
Puppet.notice _("Created target directory %{dir}") % { dir: @target }
rescue SystemCallError => orig_error
raise converted_to_friendly_error(module_name, version, orig_error)
end
end
private
ERROR_MAPPINGS = {
Errno::EACCES => PermissionDeniedCreateInstallDirectoryError,
Errno::EEXIST => InstallPathExistsNotDirectoryError,
}
def converted_to_friendly_error(module_name, version, orig_error)
return orig_error unless ERROR_MAPPINGS.include?(orig_error.class)
ERROR_MAPPINGS[orig_error.class].new(orig_error,
:requested_module => module_name,
:requested_version => version,
:directory => @target.to_s)
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/module_tool/dependency.rb | lib/puppet/module_tool/dependency.rb | # frozen_string_literal: true
require_relative '../../puppet/module_tool'
require_relative '../../puppet/network/format_support'
module Puppet::ModuleTool
class Dependency
include Puppet::Network::FormatSupport
attr_reader :full_module_name, :username, :name, :version_requirement, :repository
# Instantiates a new module dependency with a +full_module_name+ (e.g.
# "myuser-mymodule"), and optional +version_requirement+ (e.g. "0.0.1") and
# optional repository (a URL string).
def initialize(full_module_name, version_requirement = nil, repository = nil)
@full_module_name = full_module_name
# TODO: add error checking, the next line raises ArgumentError when +full_module_name+ is invalid
@username, @name = Puppet::ModuleTool.username_and_modname_from(full_module_name)
@version_requirement = version_requirement
@repository = repository ? Puppet::Forge::Repository.new(repository, nil) : nil
end
# We override Object's ==, eql, and hash so we can more easily find identical
# dependencies.
def ==(o)
hash == o.hash
end
alias :eql? :==
def hash
[@full_module_name, @version_requirement, @repository].hash
end
def to_data_hash
result = { :name => @full_module_name }
result[:version_requirement] = @version_requirement if @version_requirement && !@version_requirement.nil?
result[:repository] = @repository.to_s if @repository && !@repository.nil?
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/module_tool/metadata.rb | lib/puppet/module_tool/metadata.rb | # frozen_string_literal: true
require_relative '../../puppet/module_tool'
require_relative '../../puppet/network/format_support'
require 'uri'
require_relative '../../puppet/util/json'
require 'set'
module Puppet::ModuleTool
# This class provides a data structure representing a module's metadata.
# @api private
class Metadata
include Puppet::Network::FormatSupport
attr_accessor :module_name
DEFAULTS = {
'name' => nil,
'version' => nil,
'author' => nil,
'summary' => nil,
'license' => 'Apache-2.0',
'source' => '',
'project_page' => nil,
'issues_url' => nil,
'dependencies' => Set.new.freeze,
'data_provider' => nil,
}
def initialize
@data = DEFAULTS.dup
@data['dependencies'] = @data['dependencies'].dup
end
# Returns a filesystem-friendly version of this module name.
def dashed_name
@data['name'].tr('/', '-') if @data['name']
end
# Returns a string that uniquely represents this version of this module.
def release_name
return nil unless @data['name'] && @data['version']
[dashed_name, @data['version']].join('-')
end
alias :name :module_name
alias :full_module_name :dashed_name
# Merges the current set of metadata with another metadata hash. This
# method also handles the validation of module names and versions, in an
# effort to be proactive about module publishing constraints.
def update(data)
process_name(data) if data['name']
process_version(data) if data['version']
process_source(data) if data['source']
process_data_provider(data) if data['data_provider']
merge_dependencies(data) if data['dependencies']
@data.merge!(data)
self
end
# Validates the name and version_requirement for a dependency, then creates
# the Dependency and adds it.
# Returns the Dependency that was added.
def add_dependency(name, version_requirement = nil, repository = nil)
validate_name(name)
validate_version_range(version_requirement) if version_requirement
dup = @data['dependencies'].find { |d| d.full_module_name == name && d.version_requirement != version_requirement }
raise ArgumentError, _("Dependency conflict for %{module_name}: Dependency %{name} was given conflicting version requirements %{version_requirement} and %{dup_version}. Verify that there are no duplicates in the metadata.json.") % { module_name: full_module_name, name: name, version_requirement: version_requirement, dup_version: dup.version_requirement } if dup
dep = Dependency.new(name, version_requirement, repository)
@data['dependencies'].add(dep)
dep
end
# Provides an accessor for the now defunct 'description' property. This
# addresses a regression in Puppet 3.6.x where previously valid templates
# referring to the 'description' property were broken.
# @deprecated
def description
@data['description']
end
def dependencies
@data['dependencies'].to_a
end
# Returns a hash of the module's metadata. Used by Puppet's automated
# serialization routines.
#
# @see Puppet::Network::FormatSupport#to_data_hash
def to_hash
@data
end
alias :to_data_hash :to_hash
def to_json
data = @data.dup.merge('dependencies' => dependencies)
contents = data.keys.map do |k|
value = begin
Puppet::Util::Json.dump(data[k], :pretty => true)
rescue
data[k].to_json
end
%Q("#{k}": #{value})
end
"{\n" + contents.join(",\n").gsub(/^/, ' ') + "\n}\n"
end
# Expose any metadata keys as callable reader methods.
def method_missing(name, *args)
return @data[name.to_s] if @data.key? name.to_s
super
end
private
# Do basic validation and parsing of the name parameter.
def process_name(data)
validate_name(data['name'])
author, @module_name = data['name'].split(%r{[-/]}, 2)
data['author'] ||= author if @data['author'] == DEFAULTS['author']
end
# Do basic validation on the version parameter.
def process_version(data)
validate_version(data['version'])
end
def process_data_provider(data)
validate_data_provider(data['data_provider'])
end
# Do basic parsing of the source parameter. If the source is hosted on
# GitHub, we can predict sensible defaults for both project_page and
# issues_url.
def process_source(data)
if data['source'] =~ %r{://}
source_uri = URI.parse(data['source'])
else
source_uri = URI.parse("http://#{data['source']}")
end
if source_uri.host =~ /^(www\.)?github\.com$/
source_uri.scheme = 'https'
source_uri.path.sub!(/\.git$/, '')
data['project_page'] ||= @data['project_page'] || source_uri.to_s
data['issues_url'] ||= @data['issues_url'] || source_uri.to_s.sub(%r{/*$}, '') + '/issues'
end
rescue URI::Error
nil
end
# Validates and parses the dependencies.
def merge_dependencies(data)
data['dependencies'].each do |dep|
add_dependency(dep['name'], dep['version_requirement'], dep['repository'])
end
# Clear dependencies so @data dependencies are not overwritten
data.delete 'dependencies'
end
# Validates that the given module name is both namespaced and well-formed.
def validate_name(name)
return if name =~ %r{\A[a-z0-9]+[-/][a-z][a-z0-9_]*\Z}i
namespace, modname = name.split(%r{[-/]}, 2)
modname = :namespace_missing if namespace == ''
err = case modname
when nil, '', :namespace_missing
_("the field must be a namespaced module name")
when /[^a-z0-9_]/i
_("the module name contains non-alphanumeric (or underscore) characters")
when /^[^a-z]/i
_("the module name must begin with a letter")
else
_("the namespace contains non-alphanumeric characters")
end
raise ArgumentError, _("Invalid 'name' field in metadata.json: %{err}") % { err: err }
end
# Validates that the version string can be parsed as per SemVer.
def validate_version(version)
return if SemanticPuppet::Version.valid?(version)
err = _("version string cannot be parsed as a valid Semantic Version")
raise ArgumentError, _("Invalid 'version' field in metadata.json: %{err}") % { err: err }
end
# Validates that the given _value_ is a symbolic name that starts with a letter
# and then contains only letters, digits, or underscore. Will raise an ArgumentError
# if that's not the case.
#
# @param value [Object] The value to be tested
def validate_data_provider(value)
if value.is_a?(String)
unless value =~ /^[a-zA-Z][a-zA-Z0-9_]*$/
if value =~ /^[a-zA-Z]/
raise ArgumentError, _("field 'data_provider' contains non-alphanumeric characters")
else
raise ArgumentError, _("field 'data_provider' must begin with a letter")
end
end
else
raise ArgumentError, _("field 'data_provider' must be a string")
end
end
# Validates that the version range can be parsed by Semantic.
def validate_version_range(version_range)
SemanticPuppet::VersionRange.parse(version_range)
rescue ArgumentError => e
raise ArgumentError, _("Invalid 'version_range' field in metadata.json: %{err}") % { err: e }
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/module_tool/checksums.rb | lib/puppet/module_tool/checksums.rb | # frozen_string_literal: true
require 'digest/md5'
require_relative '../../puppet/network/format_support'
module Puppet::ModuleTool
# = Checksums
#
# This class provides methods for generating checksums for data and adding
# them to +Metadata+.
class Checksums
include Puppet::Network::FormatSupport
include Enumerable
# Instantiate object with string +path+ to create checksums from.
def initialize(path)
@path = Pathname.new(path)
end
# Return checksum for the +Pathname+.
def checksum(pathname)
Digest::MD5.hexdigest(Puppet::FileSystem.binread(pathname))
end
# Return checksums for object's +Pathname+, generate if it's needed.
# Result is a hash of path strings to checksum strings.
def data
unless @data
@data = {}
@path.find do |descendant|
if Puppet::ModuleTool.artifact?(descendant)
Find.prune
elsif descendant.file?
path = descendant.relative_path_from(@path)
@data[path.to_s] = checksum(descendant)
end
end
end
@data
end
alias :to_data_hash :data
alias :to_hash :data
# TODO: Why?
def each(&block)
data.each(&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/module_tool/errors/upgrader.rb | lib/puppet/module_tool/errors/upgrader.rb | # frozen_string_literal: true
module Puppet::ModuleTool::Errors
class UpgradeError < ModuleToolError
def initialize(msg)
@action = :upgrade
super
end
end
class VersionAlreadyInstalledError < UpgradeError
attr_reader :newer_versions
def initialize(options)
@module_name = options[:module_name]
@requested_version = options[:requested_version]
@installed_version = options[:installed_version]
@dependency_name = options[:dependency_name]
@newer_versions = options[:newer_versions]
@possible_culprits = options[:possible_culprits]
super _("Could not upgrade '%{module_name}'; more recent versions not found") % { module_name: @module_name }
end
def multiline
message = []
message << _("Could not upgrade module '%{module_name}' (%{version})") % { module_name: @module_name, version: vstring }
if @newer_versions.empty?
message << _(" The installed version is already the latest version matching %{version}") % { version: vstring }
else
message << _(" There are %{count} newer versions") % { count: @newer_versions.length }
message << _(" No combination of dependency upgrades would satisfy all dependencies")
unless @possible_culprits.empty?
message << _(" Dependencies will not be automatically upgraded across major versions")
message << _(" Upgrading one or more of these modules may permit the upgrade to succeed:")
@possible_culprits.each do |name|
message << " - #{name}"
end
end
end
# TRANSLATORS `puppet module upgrade --force` is a command line option that should not be translated
message << _(" Use `puppet module upgrade --force` to upgrade only this module")
message.join("\n")
end
end
class DowngradingUnsupportedError < UpgradeError
def initialize(options)
@module_name = options[:module_name]
@requested_version = options[:requested_version]
@installed_version = options[:installed_version]
@conditions = options[:conditions]
@action = options[:action]
super _("Could not %{action} '%{module_name}' (%{version}); downgrades are not allowed") % { action: @action, module_name: @module_name, version: vstring }
end
def multiline
message = []
message << _("Could not %{action} module '%{module_name}' (%{version})") % { action: @action, module_name: @module_name, version: vstring }
message << _(" Downgrading is not allowed.")
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/module_tool/errors/base.rb | lib/puppet/module_tool/errors/base.rb | # frozen_string_literal: true
module Puppet::ModuleTool::Errors
class ModuleToolError < Puppet::Error
def v(version)
(version || '???').to_s.sub(/^(?=\d)/, 'v')
end
def vstring
if @action == :upgrade
"#{v(@installed_version)} -> #{v(@requested_version)}"
else
v(@installed_version || @requested_version).to_s
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/module_tool/errors/installer.rb | lib/puppet/module_tool/errors/installer.rb | # frozen_string_literal: true
module Puppet::ModuleTool::Errors
class InstallError < ModuleToolError; end
class AlreadyInstalledError < InstallError
def initialize(options)
@module_name = options[:module_name]
@installed_version = v(options[:installed_version])
@requested_version = v(options[:requested_version])
@local_changes = options[:local_changes]
super _("'%{module_name}' (%{version}) requested; '%{module_name}' (%{installed_version}) already installed") % { module_name: @module_name, version: @requested_version, installed_version: @installed_version }
end
def multiline
message = []
message << _("Could not install module '%{module_name}' (%{version})") % { module_name: @module_name, version: @requested_version }
message << _(" Module '%{module_name}' (%{installed_version}) is already installed") % { module_name: @module_name, installed_version: @installed_version }
message << _(" Installed module has had changes made locally") unless @local_changes.empty?
# TRANSLATORS `puppet module upgrade` is a command line and should not be translated
message << _(" Use `puppet module upgrade` to install a different version")
# TRANSLATORS `puppet module install --force` is a command line and should not be translated
message << _(" Use `puppet module install --force` to re-install only this module")
message.join("\n")
end
end
class MissingPackageError < InstallError
def initialize(options)
@requested_package = options[:requested_package]
@source = options[:source]
super _("Could not install '%{requested_package}'; no releases are available from %{source}") % { requested_package: @requested_package, source: @source }
end
def multiline
message = []
message << _("Could not install '%{requested_package}'") % { requested_package: @requested_package }
message << _(" No releases are available from %{source}") % { source: @source }
message << _(" Does '%{requested_package}' have at least one published release?") % { requested_package: @requested_package }
message.join("\n")
end
end
class InstallPathExistsNotDirectoryError < InstallError
def initialize(original, options)
@requested_module = options[:requested_module]
@requested_version = options[:requested_version]
@directory = options[:directory]
super(_("'%{module_name}' (%{version}) requested; Path %{dir} is not a directory.") % { module_name: @requested_module, version: @requested_version, dir: @directory }, original)
end
def multiline
message = []
message << _("Could not install module '%{module_name}' (%{version})") % { module_name: @requested_module, version: @requested_version }
message << _(" Path '%{directory}' exists but is not a directory.") % { directory: @directory }
# TRANSLATORS "mkdir -p '%{directory}'" is a command line example and should not be translated
message << _(" A potential solution is to rename the path and then \"mkdir -p '%{directory}'\"") % { directory: @directory }
message.join("\n")
end
end
class PermissionDeniedCreateInstallDirectoryError < InstallError
def initialize(original, options)
@requested_module = options[:requested_module]
@requested_version = options[:requested_version]
@directory = options[:directory]
super(_("'%{module_name}' (%{version}) requested; Permission is denied to create %{dir}.") % { module_name: @requested_module, version: @requested_version, dir: @directory }, original)
end
def multiline
message = []
message << _("Could not install module '%{module_name}' (%{version})") % { module_name: @requested_module, version: @requested_version }
message << _(" Permission is denied when trying to create directory '%{directory}'.") % { directory: @directory }
message << _(' A potential solution is to check the ownership and permissions of parent directories.')
message.join("\n")
end
end
class InvalidPathInPackageError < InstallError
def initialize(options)
@entry_path = options[:entry_path]
@directory = options[:directory]
super _("Attempt to install file with an invalid path into %{path} under %{dir}") % { path: @entry_path.inspect, dir: @directory.inspect }
end
def multiline
message = []
message << _('Could not install package with an invalid path.')
message << _(' Package attempted to install file into %{path} under %{directory}.') % { path: @entry_path.inspect, directory: @directory.inspect }
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/module_tool/errors/shared.rb | lib/puppet/module_tool/errors/shared.rb | # frozen_string_literal: true
module Puppet::ModuleTool::Errors
class NoVersionsSatisfyError < ModuleToolError
def initialize(options)
@requested_name = options[:requested_name]
@requested_version = options[:requested_version]
@installed_version = options[:installed_version]
@conditions = options[:conditions]
@action = options[:action]
@unsatisfied = options[:unsatisfied]
super _("Could not %{action} '%{module_name}' (%{version}); no version satisfies all dependencies") % { action: @action, module_name: @requested_name, version: vstring }
end
def multiline
message = []
message << _("Could not %{action} module '%{module_name}' (%{version})") % { action: @action, module_name: @requested_name, version: vstring }
if @unsatisfied
message << _(" The requested version cannot satisfy one or more of the following installed modules:")
if @unsatisfied[:current_version]
message << _(" %{name}, installed: %{current_version}, expected: %{constraints}") % { name: @unsatisfied[:name], current_version: @unsatisfied[:current_version], constraints: @unsatisfied[:constraints][@unsatisfied[:name]] }
else
@unsatisfied[:constraints].each do |mod, range|
message << _(" %{mod}, expects '%{name}': %{range}") % { mod: mod, name: @requested_name, range: range }
end
end
message << _("")
else
message << _(" The requested version cannot satisfy all dependencies")
end
# TRANSLATORS `puppet module %{action} --ignore-dependencies` is a command line and should not be translated
message << _(" Use `puppet module %{action} '%{module_name}' --ignore-dependencies` to %{action} only this module") % { action: @action, module_name: @requested_name }
message.join("\n")
end
end
class NoCandidateReleasesError < ModuleToolError
def initialize(options)
@module_name = options[:module_name]
@requested_version = options[:requested_version]
@installed_version = options[:installed_version]
@source = options[:source]
@action = options[:action]
if @requested_version == :latest
super _("Could not %{action} '%{module_name}'; no releases are available from %{source}") % { action: @action, module_name: @module_name, source: @source }
else
super _("Could not %{action} '%{module_name}'; no releases matching '%{version}' are available from %{source}") % { action: @action, module_name: @module_name, version: @requested_version, source: @source }
end
end
def multiline
message = []
message << _("Could not %{action} '%{module_name}' (%{version})") % { action: @action, module_name: @module_name, version: vstring }
if @requested_version == :latest
message << _(" No releases are available from %{source}") % { source: @source }
message << _(" Does '%{module_name}' have at least one published release?") % { module_name: @module_name }
else
message << _(" No releases matching '%{requested_version}' are available from %{source}") % { requested_version: @requested_version, source: @source }
end
message.join("\n")
end
end
class InstallConflictError < ModuleToolError
def initialize(options)
@requested_module = options[:requested_module]
@requested_version = v(options[:requested_version])
@dependency = options[:dependency]
@directory = options[:directory]
@metadata = options[:metadata]
super _("'%{module_name}' (%{version}) requested; installation conflict") % { module_name: @requested_module, version: @requested_version }
end
def multiline
message = []
message << _("Could not install module '%{module_name}' (%{version})") % { module_name: @requested_module, version: @requested_version }
if @dependency
message << _(" Dependency '%{name}' (%{version}) would overwrite %{directory}") % { name: @dependency[:name], version: v(@dependency[:version]), directory: @directory }
else
message << _(" Installation would overwrite %{directory}") % { directory: @directory }
end
if @metadata
message << _(" Currently, '%{current_name}' (%{current_version}) is installed to that directory") % { current_name: @metadata["name"], current_version: v(@metadata["version"]) }
end
if @dependency
# TRANSLATORS `puppet module install --ignore-dependencies` is a command line and should not be translated
message << _(" Use `puppet module install --ignore-dependencies` to install only this module")
else
# TRANSLATORS `puppet module install --force` is a command line and should not be translated
message << _(" Use `puppet module install --force` to install this module anyway")
end
message.join("\n")
end
end
class InvalidDependencyCycleError < ModuleToolError
def initialize(options)
@module_name = options[:module_name]
@requested_module = options[:requested_module]
@requested_version = options[:requested_version]
@conditions = options[:conditions]
@source = options[:source][1..]
super _("'%{module_name}' (%{version}) requested; Invalid dependency cycle") % { module_name: @requested_module, version: v(@requested_version) }
end
def multiline
dependency_list = []
dependency_list << _("You specified '%{name}' (%{version})") % { name: @source.first[:name], version: v(@requested_version) }
dependency_list += @source[1..].map do |m|
# TRANSLATORS This message repeats as separate lines as a list under the heading "You specified '%{name}' (%{version})\n"
_("This depends on '%{name}' (%{version})") % { name: m[:name], version: v(m[:version]) }
end
message = []
message << _("Could not install module '%{module_name}' (%{version})") % { module_name: @requested_module, version: v(@requested_version) }
message << _(" No version of '%{module_name}' will satisfy dependencies") % { module_name: @module_name }
message << dependency_list.map { |s| " #{s}".join(",\n") }
# TRANSLATORS `puppet module install --force` is a command line and should not be translated
message << _(" Use `puppet module install --force` to install this module anyway")
message.join("\n")
end
end
class InvalidModuleNameError < ModuleToolError
def initialize(options)
@module_name = options[:module_name]
@suggestion = options[:suggestion]
@action = options[:action]
super _("Could not %{action} '%{module_name}', did you mean '%{suggestion}'?") % { action: @action, module_name: @module_name, suggestion: @suggestion }
end
def multiline
message = []
message << _("Could not %{action} module '%{module_name}'") % { action: @action, module_name: @module_name }
message << _(" The name '%{module_name}' is invalid") % { module_name: @module_name }
message << _(" Did you mean `puppet module %{action} %{suggestion}`?") % { action: @action, suggestion: @suggestion }
message.join("\n")
end
end
class NotInstalledError < ModuleToolError
def initialize(options)
@module_name = options[:module_name]
@suggestions = options[:suggestions] || []
@action = options[:action]
super _("Could not %{action} '%{module_name}'; module is not installed") % { action: @action, module_name: @module_name }
end
def multiline
message = []
message << _("Could not %{action} module '%{module_name}'") % { action: @action, module_name: @module_name }
message << _(" Module '%{module_name}' is not installed") % { module_name: @module_name }
message += @suggestions.map do |suggestion|
# TRANSLATORS `puppet module %{action} %{suggestion}` is a command line and should not be translated
_(" You may have meant `puppet module %{action} %{suggestion}`") % { action: @action, suggestion: suggestion }
end
# TRANSLATORS `puppet module install` is a command line and should not be translated
message << _(" Use `puppet module install` to install this module") if @action == :upgrade
message.join("\n")
end
end
class MultipleInstalledError < ModuleToolError
def initialize(options)
@module_name = options[:module_name]
@modules = options[:installed_modules]
@action = options[:action]
# TRANSLATORS "module path" refers to a set of directories where modules may be installed
super _("Could not %{action} '%{module_name}'; module appears in multiple places in the module path") % { action: @action, module_name: @module_name }
end
def multiline
message = []
message << _("Could not %{action} module '%{module_name}'") % { action: @action, module_name: @module_name }
message << _(" Module '%{module_name}' appears multiple places in the module path") % { module_name: @module_name }
message += @modules.map do |mod|
# TRANSLATORS This is repeats as separate lines as a list under "Module '%{module_name}' appears multiple places in the module path"
_(" '%{module_name}' (%{version}) was found in %{path}") % { module_name: @module_name, version: v(mod.version), path: mod.modulepath }
end
# TRANSLATORS `--modulepath` is command line option and should not be translated
message << _(" Use the `--modulepath` option to limit the search to specific directories")
message.join("\n")
end
end
class LocalChangesError < ModuleToolError
def initialize(options)
@module_name = options[:module_name]
@requested_version = options[:requested_version]
@installed_version = options[:installed_version]
@action = options[:action]
super _("Could not %{action} '%{module_name}'; module has had changes made locally") % { action: @action, module_name: @module_name }
end
def multiline
message = []
message << _("Could not %{action} module '%{module_name}' (%{version})") % { action: @action, module_name: @module_name, version: vstring }
message << _(" Installed module has had changes made locally")
# TRANSLATORS `puppet module %{action} --ignore-changes` is a command line and should not be translated
message << _(" Use `puppet module %{action} --ignore-changes` to %{action} this module anyway") % { action: @action }
message.join("\n")
end
end
class InvalidModuleError < ModuleToolError
def initialize(name, options)
@name = name
@action = options[:action]
@error = options[:error]
super _("Could not %{action} '%{module_name}'; %{error}") % { action: @action, module_name: @name, error: @error.message }
end
def multiline
message = []
message << _("Could not %{action} module '%{module_name}'") % { action: @action, module_name: @name }
message << _(" Failure trying to parse metadata")
message << _(" Original message was: %{message}") % { message: @error.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/module_tool/errors/uninstaller.rb | lib/puppet/module_tool/errors/uninstaller.rb | # frozen_string_literal: true
module Puppet::ModuleTool::Errors
class UninstallError < ModuleToolError; end
class NoVersionMatchesError < UninstallError
def initialize(options)
@module_name = options[:module_name]
@modules = options[:installed_modules]
@version = options[:version_range]
super _("Could not uninstall '%{module_name}'; no installed version matches") % { module_name: @module_name }
end
def multiline
message = []
message << _("Could not uninstall module '%{module_name}' (%{version})") % { module_name: @module_name, version: v(@version) }
message << _(" No installed version of '%{module_name}' matches (%{version})") % { module_name: @module_name, version: v(@version) }
message += @modules.map do |mod|
_(" '%{module_name}' (%{version}) is installed in %{path}") % { module_name: mod[:name], version: v(mod[:version]), path: mod[:path] }
end
message.join("\n")
end
end
class ModuleIsRequiredError < UninstallError
def initialize(options)
@module_name = options[:module_name]
@required_by = options[:required_by]
@requested_version = options[:requested_version]
@installed_version = options[:installed_version]
super _("Could not uninstall '%{module_name}'; installed modules still depend upon it") % { module_name: @module_name }
end
def multiline
message = []
if @requested_version
message << _("Could not uninstall module '%{module_name}' (v%{requested_version})") % { module_name: @module_name, requested_version: @requested_version }
else
message << _("Could not uninstall module '%{module_name}'") % { module_name: @module_name }
end
message << _(" Other installed modules have dependencies on '%{module_name}' (%{version})") % { module_name: @module_name, version: v(@installed_version) }
message += @required_by.map do |mod|
_(" '%{module_name}' (%{version}) requires '%{module_dep}' (%{dep_version})") % { module_name: mod['name'], version: v(mod['version']), module_dep: @module_name, dep_version: v(mod['version_requirement']) }
end
# TRANSLATORS `puppet module uninstall --force` is a command line option that should not be translated
message << _(" Use `puppet module uninstall --force` to uninstall this module anyway")
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/module_tool/tar/gnu.rb | lib/puppet/module_tool/tar/gnu.rb | # frozen_string_literal: true
require 'shellwords'
class Puppet::ModuleTool::Tar::Gnu
def unpack(sourcefile, destdir, owner)
safe_sourcefile = Shellwords.shellescape(File.expand_path(sourcefile))
destdir = File.expand_path(destdir)
safe_destdir = Shellwords.shellescape(destdir)
Puppet::Util::Execution.execute("gzip -dc #{safe_sourcefile} | tar --extract --no-same-owner --directory #{safe_destdir} --file -")
Puppet::Util::Execution.execute(['find', destdir, '-type', 'd', '-exec', 'chmod', '755', '{}', '+'])
Puppet::Util::Execution.execute(['find', destdir, '-type', 'f', '-exec', 'chmod', 'u+rw,g+r,a-st', '{}', '+'])
Puppet::Util::Execution.execute(['chown', '-R', owner, destdir])
end
def pack(sourcedir, destfile)
safe_sourcedir = Shellwords.shellescape(sourcedir)
safe_destfile = Shellwords.shellescape(File.basename(destfile))
Puppet::Util::Execution.execute("tar cf - #{safe_sourcedir} | gzip -c > #{safe_destfile}")
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/module_tool/tar/mini.rb | lib/puppet/module_tool/tar/mini.rb | # frozen_string_literal: true
class Puppet::ModuleTool::Tar::Mini
def unpack(sourcefile, destdir, _)
Zlib::GzipReader.open(sourcefile) do |reader|
# puppet doesn't have a hard dependency on minitar, so we
# can't be certain which version is installed. If it's 0.9
# or above then we can prevent minitar from fsync'ing each
# extracted file and directory, otherwise fallback to the
# old behavior
args = [reader, destdir, find_valid_files(reader)]
spec = Gem::Specification.find_by_name('minitar')
if spec && spec.version >= Gem::Version.new('0.9')
args << { :fsync => false }
end
Archive::Tar::Minitar.unpack(*args) do |action, name, stats|
case action
when :dir
validate_entry(destdir, name)
set_dir_mode!(stats)
Puppet.debug("Extracting: #{destdir}/#{name}")
when :file_start
# Octal string of the old file mode.
validate_entry(destdir, name)
set_file_mode!(stats)
Puppet.debug("Extracting: #{destdir}/#{name}")
end
set_default_user_and_group!(stats)
stats
end
end
end
def pack(sourcedir, destfile)
Zlib::GzipWriter.open(destfile) do |writer|
Archive::Tar::Minitar.pack(sourcedir, writer) do |step, name, stats|
# TODO smcclellan 2017-10-31 Set permissions here when this yield block
# executes before the header is written. As it stands, the `stats`
# argument isn't mutable in a way that will effect the desired mode for
# the file.
end
end
end
private
EXECUTABLE = 0o755
NOT_EXECUTABLE = 0o644
USER_EXECUTE = 0o100
def set_dir_mode!(stats)
if stats.key?(:mode)
# This is only the case for `pack`, so this code will not run.
stats[:mode] = EXECUTABLE
elsif stats.key?(:entry)
old_mode = stats[:entry].instance_variable_get(:@mode)
if old_mode.is_a?(Integer)
stats[:entry].instance_variable_set(:@mode, EXECUTABLE)
end
end
end
# Sets a file mode to 0755 if the file is executable by the user.
# Sets a file mode to 0644 if the file mode is set (non-Windows).
def sanitized_mode(old_mode)
old_mode & USER_EXECUTE != 0 ? EXECUTABLE : NOT_EXECUTABLE
end
def set_file_mode!(stats)
if stats.key?(:mode)
# This is only the case for `pack`, so this code will not run.
stats[:mode] = sanitized_mode(stats[:mode])
elsif stats.key?(:entry)
old_mode = stats[:entry].instance_variable_get(:@mode)
# If the user can execute the file, set 0755, otherwise 0644.
if old_mode.is_a?(Integer)
new_mode = sanitized_mode(old_mode)
stats[:entry].instance_variable_set(:@mode, new_mode)
end
end
end
# Sets UID and GID to 0 for standardization.
def set_default_user_and_group!(stats)
stats[:uid] = 0
stats[:gid] = 0
end
# Find all the valid files in tarfile.
#
# This check was mainly added to ignore 'x' and 'g' flags from the PAX
# standard but will also ignore any other non-standard tar flags.
# tar format info: https://pic.dhe.ibm.com/infocenter/zos/v1r13/index.jsp?topic=%2Fcom.ibm.zos.r13.bpxa500%2Ftaf.htm
# pax format info: https://pic.dhe.ibm.com/infocenter/zos/v1r13/index.jsp?topic=%2Fcom.ibm.zos.r13.bpxa500%2Fpxarchfm.htm
def find_valid_files(tarfile)
Archive::Tar::Minitar.open(tarfile).collect do |entry|
flag = entry.typeflag
if flag.nil? || flag =~ /[[:digit:]]/ && (0..7).cover?(flag.to_i)
entry.full_name
else
Puppet.debug "Invalid tar flag '#{flag}' will not be extracted: #{entry.name}"
next
end
end
end
def validate_entry(destdir, path)
if Pathname.new(path).absolute?
raise Puppet::ModuleTool::Errors::InvalidPathInPackageError, :entry_path => path, :directory => destdir
end
path = Pathname.new(File.join(destdir, path)).cleanpath.to_path
if path !~ /\A#{Regexp.escape destdir}/
raise Puppet::ModuleTool::Errors::InvalidPathInPackageError, :entry_path => path, :directory => destdir
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/module_tool/applications/application.rb | lib/puppet/module_tool/applications/application.rb | # frozen_string_literal: true
require 'net/http'
require_relative '../../../puppet/util/json'
require_relative '../../../puppet/util/colors'
module Puppet::ModuleTool
module Applications
class Application
include Puppet::Util::Colors
def self.run(*args)
new(*args).run
end
attr_accessor :options
def initialize(options = {})
@options = options
end
def run
raise NotImplementedError, "Should be implemented in child classes."
end
def discuss(response, success, failure)
case response
when Net::HTTPOK, Net::HTTPCreated
Puppet.notice success
else
errors = begin
Puppet::Util::Json.load(response.body)['error']
rescue
"HTTP #{response.code}, #{response.body}"
end
Puppet.warning "#{failure} (#{errors})"
end
end
def metadata(require_metadata = false)
return @metadata if @metadata
@metadata = Puppet::ModuleTool::Metadata.new
unless @path
raise ArgumentError, _("Could not determine module path")
end
if require_metadata && !Puppet::ModuleTool.is_module_root?(@path)
raise ArgumentError, _("Unable to find metadata.json in module root at %{path} See https://puppet.com/docs/puppet/latest/modules_publishing.html for required file format.") % { path: @path }
end
metadata_path = File.join(@path, 'metadata.json')
if File.file?(metadata_path)
File.open(metadata_path) do |f|
@metadata.update(Puppet::Util::Json.load(f))
rescue Puppet::Util::Json::ParseError => ex
raise ArgumentError, _("Could not parse JSON %{metadata_path}") % { metadata_path: metadata_path }, ex.backtrace
end
end
if File.file?(File.join(@path, 'Modulefile'))
Puppet.warning _("A Modulefile was found in the root directory of the module. This file will be ignored and can safely be removed.")
end
@metadata
end
def load_metadata!
@metadata = nil
metadata(true)
end
def parse_filename(filename)
match = /^((.*?)-(.*?))-(\d+\.\d+\.\d+.*?)$/.match(File.basename(filename, '.tar.gz'))
if match
module_name, author, shortname, version = match.captures
else
raise ArgumentError, _("Could not parse filename to obtain the username, module name and version. (%{release_name})") % { release_name: @release_name }
end
unless SemanticPuppet::Version.valid?(version)
raise ArgumentError, _("Invalid version format: %{version} (Semantic Versions are acceptable: http://semver.org)") % { version: version }
end
{
:module_name => module_name,
:author => author,
:dir_name => shortname,
:version => version
}
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/module_tool/applications/checksummer.rb | lib/puppet/module_tool/applications/checksummer.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/json'
require_relative '../../../puppet/module_tool/checksums'
module Puppet::ModuleTool
module Applications
class Checksummer < Application
def initialize(path, options = {})
@path = Pathname.new(path)
super(options)
end
def run
changes = []
sums = Puppet::ModuleTool::Checksums.new(@path)
checksums.each do |child_path, canonical_checksum|
# Avoid checksumming the checksums.json file
next if File.basename(child_path) == "checksums.json"
path = @path + child_path
unless path.exist? && canonical_checksum == sums.checksum(path)
changes << child_path
end
end
# Return an Array of strings representing file paths of files that have
# been modified since this module was installed. All paths are relative
# to the installed module directory. This return value is used by the
# module_tool face changes action, and displayed on the console.
#
# Example return value:
#
# [ "REVISION", "manifests/init.pp"]
#
changes
end
private
def checksums
if checksums_file.exist?
Puppet::Util::Json.load(checksums_file.read)
elsif metadata_file.exist?
# Check metadata.json too; legacy modules store their checksums there.
Puppet::Util::Json.load(metadata_file.read)['checksums'] or
raise ArgumentError, _("No file containing checksums found.")
else
raise ArgumentError, _("No file containing checksums found.")
end
end
def metadata_file
@path + 'metadata.json'
end
def checksums_file
@path + 'checksums.json'
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/module_tool/applications/upgrader.rb | lib/puppet/module_tool/applications/upgrader.rb | # frozen_string_literal: true
require 'pathname'
require_relative '../../../puppet/forge'
require_relative '../../../puppet/module_tool'
require_relative '../../../puppet/module_tool/shared_behaviors'
require_relative '../../../puppet/module_tool/install_directory'
require_relative '../../../puppet/module_tool/installed_modules'
module Puppet::ModuleTool
module Applications
class Upgrader < Application
include Puppet::ModuleTool::Errors
def initialize(name, options)
super(options)
@action = :upgrade
@environment = options[:environment_instance]
@name = name
@ignore_changes = forced? || options[:ignore_changes]
@ignore_dependencies = forced? || options[:ignore_dependencies]
SemanticPuppet::Dependency.add_source(installed_modules_source)
SemanticPuppet::Dependency.add_source(module_repository)
end
def run
# Disallow anything that invokes md5 to avoid un-friendly termination due to FIPS
raise _("Module upgrade is prohibited in FIPS mode.") if Puppet.runtime[:facter].value(:fips_enabled)
name = @name.tr('/', '-')
version = options[:version] || '>= 0.0.0'
results = {
:action => :upgrade,
:requested_version => options[:version] || :latest,
}
begin
all_modules = @environment.modules_by_path.values.flatten
matching_modules = all_modules.select do |x|
x.forge_name && x.forge_name.tr('/', '-') == name
end
if matching_modules.empty?
raise NotInstalledError, results.merge(:module_name => name)
elsif matching_modules.length > 1
raise MultipleInstalledError, results.merge(:module_name => name, :installed_modules => matching_modules)
end
installed_release = installed_modules[name]
# `priority` is an attribute of a `SemanticPuppet::Dependency::Source`,
# which is delegated through `ModuleRelease` instances for the sake of
# comparison (sorting). By default, the `InstalledModules` source has
# a priority of 10 (making it the most preferable source, so that
# already installed versions of modules are selected in preference to
# modules from e.g. the Forge). Since we are specifically looking to
# upgrade this module, we don't want the installed version of this
# module to be chosen in preference to those with higher versions.
#
# This implementation is suboptimal, and since we can expect this sort
# of behavior to be reasonably common in Semantic, we should probably
# see about implementing a `ModuleRelease#override_priority` method
# (or something similar).
def installed_release.priority
0
end
mod = installed_release.mod
results[:installed_version] = SemanticPuppet::Version.parse(mod.version)
dir = Pathname.new(mod.modulepath)
vstring = mod.version ? "v#{mod.version}" : '???'
Puppet.notice _("Found '%{name}' (%{version}) in %{dir} ...") % { name: name, version: colorize(:cyan, vstring), dir: dir }
unless @ignore_changes
changes = begin
Checksummer.run(mod.path)
rescue
[]
end
if mod.has_metadata? && !changes.empty?
raise LocalChangesError,
:action => :upgrade,
:module_name => name,
:requested_version => results[:requested_version],
:installed_version => mod.version
end
end
Puppet::Forge::Cache.clean
# Ensure that there is at least one candidate release available
# for the target package.
available_versions = module_repository.fetch(name)
if available_versions.empty?
raise NoCandidateReleasesError, results.merge(:module_name => name, :source => module_repository.host)
elsif results[:requested_version] != :latest
requested = Puppet::Module.parse_range(results[:requested_version])
unless available_versions.any? { |m| requested.include? m.version }
raise NoCandidateReleasesError, results.merge(:module_name => name, :source => module_repository.host)
end
end
Puppet.notice _("Downloading from %{host} ...") % { host: module_repository.host }
if @ignore_dependencies
graph = build_single_module_graph(name, version)
else
graph = build_dependency_graph(name, version)
end
unless forced?
add_module_name_constraints_to_graph(graph)
end
installed_modules.each do |installed_module, release|
installed_module = installed_module.tr('/', '-')
next if installed_module == name
version = release.version
next if forced?
# Since upgrading already installed modules can be troublesome,
# we'll place constraints on the graph for each installed
# module, locking it to upgrades within the same major version.
installed_range = ">=#{version} #{version.major}.x"
graph.add_constraint('installed', installed_module, installed_range) do |node|
Puppet::Module.parse_range(installed_range).include? node.version
end
release.mod.dependencies.each do |dep|
dep_name = dep['name'].tr('/', '-')
range = dep['version_requirement']
graph.add_constraint("#{installed_module} constraint", dep_name, range) do |node|
Puppet::Module.parse_range(range).include? node.version
end
end
end
begin
Puppet.info _("Resolving dependencies ...")
releases = SemanticPuppet::Dependency.resolve(graph)
rescue SemanticPuppet::Dependency::UnsatisfiableGraph
raise NoVersionsSatisfyError, results.merge(:requested_name => name)
end
releases.each do |rel|
mod = installed_modules_source.by_name[rel.name.split('-').last]
next unless mod
next if mod.has_metadata? && mod.forge_name.tr('/', '-') == rel.name
if rel.name != name
dependency = {
:name => rel.name,
:version => rel.version
}
end
raise InstallConflictError,
:requested_module => name,
:requested_version => options[:version] || 'latest',
:dependency => dependency,
:directory => mod.path,
:metadata => mod.metadata
end
child = releases.find { |x| x.name == name }
unless forced?
if child.version == results[:installed_version]
versions = graph.dependencies[name].map(&:version)
newer_versions = versions.select { |v| v > results[:installed_version] }
raise VersionAlreadyInstalledError,
:module_name => name,
:requested_version => results[:requested_version],
:installed_version => results[:installed_version],
:newer_versions => newer_versions,
:possible_culprits => installed_modules_source.fetched.reject { |x| x == name }
elsif child.version < results[:installed_version]
raise DowngradingUnsupportedError,
:module_name => name,
:requested_version => results[:requested_version],
:installed_version => results[:installed_version]
end
end
Puppet.info _("Preparing to upgrade ...")
releases.each(&:prepare)
Puppet.notice _('Upgrading -- do not interrupt ...')
releases.each do |release|
installed = installed_modules[release.name]
if installed
release.install(Pathname.new(installed.mod.modulepath))
else
release.install(dir)
end
end
results[:result] = :success
results[:base_dir] = releases.first.install_dir
results[:affected_modules] = releases
results[:graph] = [build_install_graph(releases.first, releases)]
rescue VersionAlreadyInstalledError => e
results[:result] = (e.newer_versions.empty? ? :noop : :failure)
results[:error] = { :oneline => e.message, :multiline => e.multiline }
rescue => e
results[:error] = {
:oneline => e.message,
:multiline => e.respond_to?(:multiline) ? e.multiline : [e.to_s, e.backtrace].join("\n")
}
ensure
results[:result] ||= :failure
end
results
end
private
# rubocop:disable Naming/MemoizedInstanceVariableName
def module_repository
@repo ||= Puppet::Forge.new(Puppet[:module_repository])
end
def installed_modules_source
@installed ||= Puppet::ModuleTool::InstalledModules.new(@environment)
end
# rubocop:enable Naming/MemoizedInstanceVariableName
def installed_modules
installed_modules_source.modules
end
def build_single_module_graph(name, version)
range = Puppet::Module.parse_range(version)
graph = SemanticPuppet::Dependency::Graph.new(name => range)
releases = SemanticPuppet::Dependency.fetch_releases(name)
releases.each { |release| release.dependencies.clear }
graph << releases
end
def build_dependency_graph(name, version)
SemanticPuppet::Dependency.query(name => version)
end
def build_install_graph(release, installed, graphed = [])
previous = installed_modules[release.name]
previous = previous.version if previous
action = :upgrade
unless previous && previous != release.version
action = :install
end
graphed << release
dependencies = release.dependencies.values.filter_map do |deps|
dep = (deps & installed).first
if dep == installed_modules[dep.name]
next
end
if dep && !graphed.include?(dep)
build_install_graph(dep, installed, graphed)
end
end
{
:release => release,
:name => release.name,
:path => release.install_dir,
:dependencies => dependencies.compact,
:version => release.version,
:previous_version => previous,
:action => action,
}
end
include Puppet::ModuleTool::Shared
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/module_tool/applications/installer.rb | lib/puppet/module_tool/applications/installer.rb | # frozen_string_literal: true
require 'open-uri'
require 'pathname'
require 'fileutils'
require 'tmpdir'
require_relative '../../../puppet/forge'
require_relative '../../../puppet/module_tool'
require_relative '../../../puppet/module_tool/shared_behaviors'
require_relative '../../../puppet/module_tool/install_directory'
require_relative '../../../puppet/module_tool/local_tarball'
require_relative '../../../puppet/module_tool/installed_modules'
require_relative '../../../puppet/network/uri'
module Puppet::ModuleTool
module Applications
class Installer < Application
include Puppet::ModuleTool::Errors
include Puppet::Forge::Errors
include Puppet::Network::Uri
def initialize(name, install_dir, options = {})
super(options)
@action = :install
@environment = options[:environment_instance]
@ignore_dependencies = forced? || options[:ignore_dependencies]
@name = name
@install_dir = install_dir
Puppet::Forge::Cache.clean
@local_tarball = Puppet::FileSystem.exist?(name)
if @local_tarball
release = local_tarball_source.release
@name = release.name
options[:version] = release.version.to_s
SemanticPuppet::Dependency.add_source(local_tarball_source)
# If we're operating on a local tarball and ignoring dependencies, we
# don't need to search any additional sources. This will cut down on
# unnecessary network traffic.
unless @ignore_dependencies
SemanticPuppet::Dependency.add_source(installed_modules_source)
SemanticPuppet::Dependency.add_source(module_repository)
end
else
SemanticPuppet::Dependency.add_source(installed_modules_source) unless forced?
SemanticPuppet::Dependency.add_source(module_repository)
end
end
def run
name = @name.tr('/', '-')
version = options[:version] || '>= 0.0.0'
results = { :action => :install, :module_name => name, :module_version => version }
begin
if !@local_tarball && name !~ /-/
raise InvalidModuleNameError.new(module_name: @name, suggestion: "puppetlabs-#{@name}", action: :install)
end
installed_module = installed_modules[name]
if installed_module
unless forced?
if Puppet::Module.parse_range(version).include? installed_module.version
results[:result] = :noop
results[:version] = installed_module.version
return results
else
changes = begin
Checksummer.run(installed_modules[name].mod.path)
rescue
[]
end
raise AlreadyInstalledError,
:module_name => name,
:installed_version => installed_modules[name].version,
:requested_version => options[:version] || :latest,
:local_changes => changes
end
end
end
@install_dir.prepare(name, options[:version] || 'latest')
results[:install_dir] = @install_dir.target
unless @local_tarball && @ignore_dependencies
Puppet.notice _("Downloading from %{host} ...") % {
host: mask_credentials(module_repository.host)
}
end
if @ignore_dependencies
graph = build_single_module_graph(name, version)
else
graph = build_dependency_graph(name, version)
end
unless forced?
add_module_name_constraints_to_graph(graph)
end
installed_modules.each do |mod, release|
mod = mod.tr('/', '-')
next if mod == name
version = release.version
next if forced?
# Since upgrading already installed modules can be troublesome,
# we'll place constraints on the graph for each installed module,
# locking it to upgrades within the same major version.
installed_range = ">=#{version} #{version.major}.x"
graph.add_constraint('installed', mod, installed_range) do |node|
Puppet::Module.parse_range(installed_range).include? node.version
end
release.mod.dependencies.each do |dep|
dep_name = dep['name'].tr('/', '-')
range = dep['version_requirement']
graph.add_constraint("#{mod} constraint", dep_name, range) do |node|
Puppet::Module.parse_range(range).include? node.version
end
end
end
# Ensure that there is at least one candidate release available
# for the target package.
if graph.dependencies[name].empty?
raise NoCandidateReleasesError, results.merge(:module_name => name, :source => module_repository.host, :requested_version => options[:version] || :latest)
end
begin
Puppet.info _("Resolving dependencies ...")
releases = SemanticPuppet::Dependency.resolve(graph)
rescue SemanticPuppet::Dependency::UnsatisfiableGraph => e
unsatisfied = nil
if e.respond_to?(:unsatisfied) && e.unsatisfied
constraints = {}
# If the module we're installing satisfies all its
# dependencies, but would break an already installed
# module that depends on it, show what would break.
if name == e.unsatisfied
graph.constraints[name].each do |mod, range, _|
next unless mod.split.include?('constraint')
# If the user requested a specific version or range,
# only show the modules with non-intersecting ranges
if options[:version]
requested_range = SemanticPuppet::VersionRange.parse(options[:version])
constraint_range = SemanticPuppet::VersionRange.parse(range)
if requested_range.intersection(constraint_range) == SemanticPuppet::VersionRange::EMPTY_RANGE
constraints[mod.split.first] = range
end
else
constraints[mod.split.first] = range
end
end
# If the module fails to satisfy one of its
# dependencies, show the unsatisfiable module
else
dep_constraints = graph.dependencies[name].max.constraints
if dep_constraints.key?(e.unsatisfied)
unsatisfied_range = dep_constraints[e.unsatisfied].first[1]
constraints[e.unsatisfied] = unsatisfied_range
end
end
installed_module = @environment.module_by_forge_name(e.unsatisfied.tr('-', '/'))
current_version = installed_module.version if installed_module
unsatisfied = {
:name => e.unsatisfied,
:constraints => constraints,
:current_version => current_version
} if constraints.any?
end
raise NoVersionsSatisfyError, results.merge(
:requested_name => name,
:requested_version => options[:version] || graph.dependencies[name].max.version.to_s,
:unsatisfied => unsatisfied
)
end
unless forced?
# Check for module name conflicts.
releases.each do |rel|
installed_module = installed_modules_source.by_name[rel.name.split('-').last]
next unless installed_module
next if installed_module.has_metadata? && installed_module.forge_name.tr('/', '-') == rel.name
if rel.name != name
dependency = {
:name => rel.name,
:version => rel.version
}
end
raise InstallConflictError,
:requested_module => name,
:requested_version => options[:version] || 'latest',
:dependency => dependency,
:directory => installed_module.path,
:metadata => installed_module.metadata
end
end
Puppet.info _("Preparing to install ...")
releases.each(&:prepare)
Puppet.notice _('Installing -- do not interrupt ...')
releases.each do |release|
installed = installed_modules[release.name]
if forced? || installed.nil?
release.install(Pathname.new(results[:install_dir]))
else
release.install(Pathname.new(installed.mod.modulepath))
end
end
results[:result] = :success
results[:installed_modules] = releases
results[:graph] = [build_install_graph(releases.first, releases)]
rescue ModuleToolError, ForgeError => err
results[:error] = {
:oneline => err.message,
:multiline => err.multiline,
}
ensure
results[:result] ||= :failure
end
results
end
private
def module_repository
@repo ||= Puppet::Forge.new(Puppet[:module_repository])
end
def local_tarball_source
@tarball_source ||= begin
Puppet::ModuleTool::LocalTarball.new(@name)
rescue Puppet::Module::Error => e
raise InvalidModuleError.new(@name, :action => @action, :error => e)
end
end
def installed_modules_source
@installed ||= Puppet::ModuleTool::InstalledModules.new(@environment)
end
def installed_modules
installed_modules_source.modules
end
def build_single_module_graph(name, version)
range = Puppet::Module.parse_range(version)
graph = SemanticPuppet::Dependency::Graph.new(name => range)
releases = SemanticPuppet::Dependency.fetch_releases(name)
releases.each { |release| release.dependencies.clear }
graph << releases
end
def build_dependency_graph(name, version)
SemanticPuppet::Dependency.query(name => version)
end
def build_install_graph(release, installed, graphed = [])
graphed << release
dependencies = release.dependencies.values.map do |deps|
dep = (deps & installed).first
unless dep.nil? || graphed.include?(dep)
build_install_graph(dep, installed, graphed)
end
end
previous = installed_modules[release.name]
previous = previous.version if previous
{
:release => release,
:name => release.name,
:path => release.install_dir.to_s,
:dependencies => dependencies.compact,
:version => release.version,
:previous_version => previous,
:action => (previous.nil? || previous == release.version || forced? ? :install : :upgrade),
}
end
include Puppet::ModuleTool::Shared
# Return a Pathname object representing the path to the module
# release package in the `Puppet.settings[:module_working_dir]`.
def get_release_packages
get_local_constraints
if !forced? && @installed.include?(@module_name)
raise AlreadyInstalledError,
:module_name => @module_name,
:installed_version => @installed[@module_name].first.version,
:requested_version => @version || (@conditions[@module_name].empty? ? :latest : :best),
:local_changes => Puppet::ModuleTool::Applications::Checksummer.run(@installed[@module_name].first.path)
end
if @ignore_dependencies && @source == :filesystem
@urls = {}
@remote = { "#{@module_name}@#{@version}" => {} }
@versions = {
@module_name => [
{ :vstring => @version, :semver => SemanticPuppet::Version.parse(@version) }
]
}
else
get_remote_constraints(@forge)
end
@graph = resolve_constraints({ @module_name => @version })
@graph.first[:tarball] = @filename if @source == :filesystem
resolve_install_conflicts(@graph) unless forced?
# This clean call means we never "cache" the module we're installing, but this
# is desired since module authors can easily rerelease modules different content but the same
# version number, meaning someone with the old content cached will be very confused as to why
# they can't get new content.
# Long term we should just get rid of this caching behavior and cleanup downloaded modules after they install
# but for now this is a quick fix to disable caching
Puppet::Forge::Cache.clean
download_tarballs(@graph, @graph.last[:path], @forge)
end
#
# Resolve installation conflicts by checking if the requested module
# or one of its dependencies conflicts with an installed module.
#
# Conflicts occur under the following conditions:
#
# When installing 'puppetlabs-foo' and an existing directory in the
# target install path contains a 'foo' directory and we cannot determine
# the "full name" of the installed module.
#
# When installing 'puppetlabs-foo' and 'pete-foo' is already installed.
# This is considered a conflict because 'puppetlabs-foo' and 'pete-foo'
# install into the same directory 'foo'.
#
def resolve_install_conflicts(graph, is_dependency = false)
Puppet.debug("Resolving conflicts for #{graph.map { |n| n[:module] }.join(',')}")
graph.each do |release|
@environment.modules_by_path[options[:target_dir]].each do |mod|
if mod.has_metadata?
metadata = {
:name => mod.forge_name.tr('/', '-'),
:version => mod.version
}
next if release[:module] == metadata[:name]
else
metadata = nil
end
next unless release[:module] =~ /-#{mod.name}$/
dependency_info = {
:name => release[:module],
:version => release[:version][:vstring]
}
dependency = is_dependency ? dependency_info : nil
all_versions = @versions[@module_name.to_s].sort_by { |h| h[:semver] }
versions = all_versions.select { |x| x[:semver].special == '' }
versions = all_versions if versions.empty?
latest_version = versions.last[:vstring]
raise InstallConflictError,
:requested_module => @module_name,
:requested_version => @version || "latest: v#{latest_version}",
:dependency => dependency,
:directory => mod.path,
:metadata => metadata
end
deps = release[:dependencies]
if deps && !deps.empty?
resolve_install_conflicts(deps, true)
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/module_tool/applications/unpacker.rb | lib/puppet/module_tool/applications/unpacker.rb | # frozen_string_literal: true
require 'pathname'
require 'tmpdir'
require_relative '../../../puppet/util/json'
require_relative '../../../puppet/file_system'
module Puppet::ModuleTool
module Applications
class Unpacker < Application
def self.unpack(filename, target)
app = new(filename, :target_dir => target)
app.unpack
app.sanity_check
app.move_into(target)
end
def self.harmonize_ownership(source, target)
unless Puppet::Util::Platform.windows?
source = Pathname.new(source) unless source.respond_to?(:stat)
target = Pathname.new(target) unless target.respond_to?(:stat)
FileUtils.chown_R(source.stat.uid, source.stat.gid, target)
end
end
def initialize(filename, options = {})
@filename = Pathname.new(filename)
super(options)
@module_path = Pathname(options[:target_dir])
end
def run
unpack
sanity_check
module_dir = @module_path + module_name
move_into(module_dir)
# Return the Pathname object representing the directory where the
# module release archive was unpacked the to.
module_dir
end
# @api private
# Error on symlinks and other junk
def sanity_check
symlinks = Dir.glob("#{tmpdir}/**/*", File::FNM_DOTMATCH).map { |f| Pathname.new(f) }.select { |p| Puppet::FileSystem.symlink? p }
tmpdirpath = Pathname.new tmpdir
symlinks.each do |s|
Puppet.warning _("Symlinks in modules are unsupported. Please investigate symlink %{from}->%{to}.") % { from: s.relative_path_from(tmpdirpath), to: Puppet::FileSystem.readlink(s) }
end
end
# @api private
def unpack
Puppet::ModuleTool::Tar.instance.unpack(@filename.to_s, tmpdir, [@module_path.stat.uid, @module_path.stat.gid].join(':'))
rescue Puppet::ExecutionFailure => e
raise RuntimeError, _("Could not extract contents of module archive: %{message}") % { message: e.message }
end
# @api private
def root_dir
return @root_dir if @root_dir
# Grab the first directory containing a metadata.json file
metadata_file = Dir["#{tmpdir}/**/metadata.json"].min_by(&:length)
if metadata_file
@root_dir = Pathname.new(metadata_file).dirname
else
raise _("No valid metadata.json found!")
end
end
# @api private
def module_name
metadata = Puppet::Util::Json.load((root_dir + 'metadata.json').read)
metadata['name'][/-(.*)/, 1]
end
# @api private
def move_into(dir)
dir = Pathname.new(dir)
dir.rmtree if dir.exist?
FileUtils.mv(root_dir, dir)
ensure
FileUtils.rmtree(tmpdir)
end
# Obtain a suitable temporary path for unpacking tarballs
#
# @api private
# @return [String] path to temporary unpacking location
# rubocop:disable Naming/MemoizedInstanceVariableName
def tmpdir
@dir ||= Dir.mktmpdir('tmp', Puppet::Forge::Cache.base_path)
end
# rubocop:enable Naming/MemoizedInstanceVariableName
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/module_tool/applications/uninstaller.rb | lib/puppet/module_tool/applications/uninstaller.rb | # frozen_string_literal: true
module Puppet::ModuleTool
module Applications
class Uninstaller < Application
include Puppet::ModuleTool::Errors
def initialize(name, options)
@name = name
@options = options
@errors = Hash.new { |h, k| h[k] = {} }
@unfiltered = []
@installed = []
@suggestions = []
@environment = options[:environment_instance]
@ignore_changes = options[:force] || options[:ignore_changes]
end
def run
results = {
:module_name => @name,
:requested_version => @version,
}
begin
find_installed_module
validate_module
FileUtils.rm_rf(@installed.first.path, :secure => true)
results[:affected_modules] = @installed
results[:result] = :success
rescue ModuleToolError => err
results[:error] = {
:oneline => err.message,
:multiline => err.multiline,
}
rescue => e
results[:error] = {
:oneline => e.message,
:multiline => e.respond_to?(:multiline) ? e.multiline : [e.to_s, e.backtrace].join("\n")
}
ensure
results[:result] ||= :failure
end
results
end
private
def find_installed_module
@environment.modules_by_path.values.flatten.each do |mod|
mod_name = (mod.forge_name || mod.name).tr('/', '-')
if mod_name == @name
@unfiltered << {
:name => mod_name,
:version => mod.version,
:path => mod.modulepath,
}
if @options[:version] && mod.version
next unless Puppet::Module.parse_range(@options[:version]).include?(SemanticPuppet::Version.parse(mod.version))
end
@installed << mod
elsif mod_name =~ /#{@name}/
@suggestions << mod_name
end
end
if @installed.length > 1
raise MultipleInstalledError,
:action => :uninstall,
:module_name => @name,
:installed_modules => @installed.sort_by { |mod| @environment.modulepath.index(mod.modulepath) }
elsif @installed.empty?
if @unfiltered.empty?
raise NotInstalledError,
:action => :uninstall,
:suggestions => @suggestions,
:module_name => @name
else
raise NoVersionMatchesError,
:installed_modules => @unfiltered.sort_by { |mod| @environment.modulepath.index(mod[:path]) },
:version_range => @options[:version],
:module_name => @name
end
end
end
def validate_module
mod = @installed.first
unless @ignore_changes
raise _("Either the `--ignore_changes` or `--force` argument must be specified to uninstall modules when running in FIPS mode.") if Puppet.runtime[:facter].value(:fips_enabled)
changes = begin
Puppet::ModuleTool::Applications::Checksummer.run(mod.path)
rescue ArgumentError
[]
end
if mod.has_metadata? && !changes.empty?
raise LocalChangesError,
:action => :uninstall,
:module_name => (mod.forge_name || mod.name).tr('/', '-'),
:requested_version => @options[:version],
:installed_version => mod.version
end
end
if !@options[:force] && !mod.required_by.empty?
raise ModuleIsRequiredError,
:module_name => (mod.forge_name || mod.name).tr('/', '-'),
:required_by => mod.required_by,
:requested_version => @options[:version],
:installed_version => mod.version
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/agent/disabler.rb | lib/puppet/agent/disabler.rb | # frozen_string_literal: true
require_relative '../../puppet/util/json_lockfile'
# This module is responsible for encapsulating the logic for
# "disabling" the puppet agent during a run; in other words,
# keeping track of enough state to answer the question
# "has the puppet agent been administratively disabled?"
#
# The implementation involves writing a lockfile with JSON
# contents, and is considered part of the public Puppet API
# because it used by external tools such as mcollective.
#
# For more information, please see docs on the website.
# http://links.puppet.com/agent_lockfiles
module Puppet::Agent::Disabler
DISABLED_MESSAGE_JSON_KEY = "disabled_message"
# Let the daemon run again, freely in the filesystem.
def enable
Puppet.notice _("Enabling Puppet.")
disable_lockfile.unlock
end
# Stop the daemon from making any catalog runs.
def disable(msg = nil)
data = {}
Puppet.notice _("Disabling Puppet.")
unless msg.nil?
data[DISABLED_MESSAGE_JSON_KEY] = msg
end
disable_lockfile.lock(data)
end
def disabled?
disable_lockfile.locked?
end
def disable_message
data = disable_lockfile.lock_data
return nil if data.nil?
if data.has_key?(DISABLED_MESSAGE_JSON_KEY)
return data[DISABLED_MESSAGE_JSON_KEY]
end
nil
end
def disable_lockfile
@disable_lockfile ||= Puppet::Util::JsonLockfile.new(Puppet[:agent_disabled_lockfile])
@disable_lockfile
end
private :disable_lockfile
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/agent/locker.rb | lib/puppet/agent/locker.rb | # frozen_string_literal: true
require_relative '../../puppet/util/pidlock'
require_relative '../../puppet/error'
# This module is responsible for encapsulating the logic for "locking" the
# puppet agent during a catalog run; in other words, keeping track of enough
# state to answer the question "is there a puppet agent currently applying a
# catalog?"
#
# The implementation involves writing a lockfile whose contents are simply the
# PID of the running agent process. This is considered part of the public
# Puppet API because it used by external tools such as mcollective.
#
# For more information, please see docs on the website.
# http://links.puppet.com/agent_lockfiles
module Puppet::Agent::Locker
# Yield if we get a lock, else raise Puppet::LockError. Return
# value of block yielded.
def lock
if lockfile.lock
begin
yield
ensure
lockfile.unlock
end
else
fail Puppet::LockError, _('Failed to acquire lock')
end
end
def running?
lockfile.locked?
end
def lockfile_path
@lockfile_path ||= Puppet[:agent_catalog_run_lockfile]
end
def lockfile
@lockfile ||= Puppet::Util::Pidlock.new(lockfile_path)
@lockfile
end
private :lockfile
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/face/resource.rb | lib/puppet/face/resource.rb | # frozen_string_literal: true
require_relative '../../puppet/indirector/face'
Puppet::Indirector::Face.define(:resource, '0.0.1') do
copyright "Puppet Inc.", 2011
license _("Apache 2 license; see COPYING")
summary _("API only: interact directly with resources via the RAL.")
description <<-'EOT'
API only: this face provides a Ruby API with functionality similar to the
puppet resource subcommand.
EOT
deactivate_action(:destroy)
search = get_action(:search)
search.summary _("API only: get all resources of a single type.")
search.arguments _("<resource_type>")
search.returns _("An array of Puppet::Resource objects.")
search.examples <<-'EOT'
Get a list of all user resources (API example):
all_users = Puppet::Face[:resource, '0.0.1'].search("user")
EOT
find = get_action(:find)
find.summary _("API only: get a single resource.")
find.arguments _("<type>/<title>")
find.returns _("A Puppet::Resource object.")
find.examples <<-'EOT'
Print information about a user on this system (API example):
puts Puppet::Face[:resource, '0.0.1'].find("user/luke").to_json
EOT
save = get_action(:save)
save.summary _("API only: create a new resource.")
save.description <<-EOT
API only: creates a new resource.
EOT
save.arguments _("<resource_object>")
save.returns _("The same resource object passed as an argument.")
save.examples <<-'EOT'
Create a new file resource (API example):
my_resource = Puppet::Resource.new(
:file,
"/tmp/demonstration",
:parameters => {:ensure => :present, :content => "some\nthing\n"}
)
Puppet::Face[:resource, '0.0.1'].save(my_resource)
EOT
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/face/report.rb | lib/puppet/face/report.rb | # frozen_string_literal: true
require_relative '../../puppet/indirector/face'
Puppet::Indirector::Face.define(:report, '0.0.1') do
copyright "Puppet Inc.", 2011
license _("Apache 2 license; see COPYING")
summary _("Create, display, and submit reports.")
save = get_action(:save)
save.summary _("API only: submit a report.")
save.arguments _("<report>")
save.returns _("Nothing.")
save.examples <<-'EOT'
From the implementation of `puppet report submit` (API example):
begin
Puppet::Transaction::Report.indirection.terminus_class = :rest
Puppet::Face[:report, "0.0.1"].save(report)
Puppet.notice "Uploaded report for #{report.name}"
rescue => detail
Puppet.log_exception(detail, "Could not send report: #{detail}")
end
EOT
action(:submit) do
summary _("API only: submit a report with error handling.")
description <<-'EOT'
API only: Submits a report to the puppet master. This action is
essentially a shortcut and wrapper for the `save` action with the `rest`
terminus, and provides additional details in the event of a failure.
EOT
arguments _("<report>")
examples <<-'EOT'
API example:
# ...
report = Puppet::Face[:catalog, '0.0.1'].apply
Puppet::Face[:report, '0.0.1'].submit(report)
return report
EOT
when_invoked do |report, _options|
Puppet::Transaction::Report.indirection.terminus_class = :rest
Puppet::Face[:report, "0.0.1"].save(report)
Puppet.notice _("Uploaded report for %{name}") % { name: report.name }
rescue => detail
Puppet.log_exception(detail, _("Could not send report: %{detail}") % { detail: detail })
end
end
deactivate_action(:find)
deactivate_action(:search)
deactivate_action(:destroy)
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.