repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/file.rb | lib/puppet/parser/functions/file.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_system'
Puppet::Parser::Functions.newfunction(
:file, :arity => -2, :type => :rvalue,
:doc => "Loads a file from a module and returns its contents as a string.
The argument to this function should be a `<MODULE NAME>/<FILE>`
reference, which will load `<FILE>` from a module's `files`
directory. (For example, the reference `mysql/mysqltuner.pl` will load the
file `<MODULES DIRECTORY>/mysql/files/mysqltuner.pl`.)
This function can also accept:
* An absolute path, which can load a file from anywhere on disk.
* Multiple arguments, which will return the contents of the **first** file
found, skipping any files that don't exist.
"
) do |vals|
path = nil
vals.each do |file|
found = Puppet::Parser::Files.find_file(file, compiler.environment)
if found && Puppet::FileSystem.exist?(found)
path = found
break
end
end
if path
Puppet::FileSystem.read_preserve_line_endings(path)
else
raise Puppet::ParseError, _("Could not find any files from %{values}") % { values: vals.join(", ") }
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/realize.rb | lib/puppet/parser/functions/realize.rb | # frozen_string_literal: true
# This is just syntactic sugar for a collection, although it will generally
# be a good bit faster.
Puppet::Parser::Functions.newfunction(:realize, :arity => -2, :doc => "Make a virtual object real. This is useful
when you want to know the name of the virtual object and don't want to
bother with a full collection. It is slightly faster than a collection,
and, of course, is a bit shorter. You must pass the object using a
reference; e.g.: `realize User[luke]`.") do |vals|
if Puppet[:tasks]
raise Puppet::ParseErrorWithIssue.from_issue_and_stack(
Puppet::Pops::Issues::CATALOG_OPERATION_NOT_SUPPORTED_WHEN_SCRIPTING,
{ :operation => 'realize' }
)
end
vals = [vals] unless vals.is_a?(Array)
coll = Puppet::Pops::Evaluator::Collectors::FixedSetCollector.new(self, vals.flatten)
compiler.add_collection(coll)
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/tagged.rb | lib/puppet/parser/functions/tagged.rb | # frozen_string_literal: true
# Test whether a given tag is set. This functions as a big OR -- if any of the specified tags are unset, we return false.
Puppet::Parser::Functions.newfunction(:tagged, :type => :rvalue, :arity => -2, :doc => "A boolean function that
tells you whether the current container is tagged with the specified tags.
The tags are ANDed, so that all of the specified tags must be included for
the function to return true.") do |vals|
if Puppet[:tasks]
raise Puppet::ParseErrorWithIssue.from_issue_and_stack(
Puppet::Pops::Issues::CATALOG_OPERATION_NOT_SUPPORTED_WHEN_SCRIPTING,
{ :operation => 'tagged' }
)
end
retval = true
vals.each do |val|
unless compiler.catalog.tagged?(val) or resource.tagged?(val)
retval = false
break
end
end
return retval
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/hiera.rb | lib/puppet/parser/functions/hiera.rb | # frozen_string_literal: true
require 'hiera_puppet'
module Puppet::Parser::Functions
newfunction(
:hiera,
:type => :rvalue,
:arity => -2,
:doc => <<~DOC
Performs a standard priority lookup of the hierarchy and returns the most specific value
for a given key. The returned value can be any type of data.
The function takes up to three arguments, in this order:
1. A string key that Hiera searches for in the hierarchy. **Required**.
2. An optional default value to return if Hiera doesn't find anything matching the key.
* If this argument isn't provided and this function results in a lookup failure, Puppet
fails with a compilation error.
3. The optional name of an arbitrary
[hierarchy level](https://puppet.com/docs/hiera/latest/hierarchy.html) to insert at the
top of the hierarchy. This lets you temporarily modify the hierarchy for a single lookup.
* If Hiera doesn't find a matching key in the overriding hierarchy level, it continues
searching the rest of the hierarchy.
The `hiera` function does **not** find all matches throughout a hierarchy, instead
returining the first specific value starting at the top of the hierarchy. To search
throughout a hierarchy, use the `hiera_array` or `hiera_hash` functions.
**Example**: Using `hiera`
~~~ yaml
# Assuming hiera.yaml
# :hierarchy:
# - web01.example.com
# - common
# Assuming web01.example.com.yaml:
# users:
# - "Amy Barry"
# - "Carrie Douglas"
# Assuming common.yaml:
users:
admins:
- "Edith Franklin"
- "Ginny Hamilton"
regular:
- "Iris Jackson"
- "Kelly Lambert"
~~~
~~~ puppet
# Assuming we are not web01.example.com:
$users = hiera('users', undef)
# $users contains {admins => ["Edith Franklin", "Ginny Hamilton"],
# regular => ["Iris Jackson", "Kelly Lambert"]}
~~~
You can optionally generate the default value with a
[lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) that
takes one parameter.
**Example**: Using `hiera` with a lambda
~~~ puppet
# Assuming the same Hiera data as the previous example:
$users = hiera('users') | $key | { "Key \'${key}\' not found" }
# $users contains {admins => ["Edith Franklin", "Ginny Hamilton"],
# regular => ["Iris Jackson", "Kelly Lambert"]}
# If hiera couldn't match its key, it would return the lambda result,
# "Key 'users' not found".
~~~
The returned value's data type depends on the types of the results. In the example
above, Hiera matches the 'users' key and returns it as a hash.
The `hiera` function is deprecated in favor of using `lookup` and will be removed in 6.0.0.
See https://puppet.com/docs/puppet/#{Puppet.minor_version}/deprecated_language.html.
Replace the calls as follows:
| from | to |
| ---- | ---|
| hiera($key) | lookup($key) |
| hiera($key, $default) | lookup($key, { 'default_value' => $default }) |
| hiera($key, $default, $level) | override level not supported |
Note that calls using the 'override level' option are not directly supported by 'lookup' and the produced
result must be post processed to get exactly the same result, for example using simple hash/array `+` or
with calls to stdlib's `deep_merge` function depending on kind of hiera call and setting of merge in hiera.yaml.
See
[the documentation](https://puppet.com/docs/hiera/latest/puppet.html#hiera-lookup-functions)
for more information about Hiera lookup functions.
- Since 4.0.0
DOC
) do |*_args|
Error.is4x('hiera')
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/step.rb | lib/puppet/parser/functions/step.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(
:step,
:type => :rvalue,
:arity => -1,
:doc => <<~DOC
Provides stepping with given interval over elements in an iterable and optionally runs a
[lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html) for each
element.
This function takes two to three arguments:
1. An 'Iterable' that the function will iterate over.
2. An `Integer` step factor. This must be a positive integer.
3. An optional lambda, which the function calls for each element in the interval. It must
request one parameter.
**Example:** Using the `step` function
```puppet
$data.step(<n>) |$parameter| { <PUPPET CODE BLOCK> }
```
or
```puppet
$stepped_data = $data.step(<n>)
```
or
```puppet
step($data, <n>) |$parameter| { <PUPPET CODE BLOCK> }
```
or
```puppet
$stepped_data = step($data, <n>)
```
When no block is given, Puppet returns an `Iterable` that yields the first element and every nth successor
element, from its first argument. This allows functions on iterables to be chained.
When a block is given, Puppet iterates and calls the block with the first element and then with
every nth successor element. It then returns `undef`.
**Example:** Using the `step` function with an array, a step factor, and a one-parameter block
```puppet
# For the array $data, call a block with the first element and then with each 3rd successor element
$data = [1,2,3,4,5,6,7,8]
$data.step(3) |$item| {
notice($item)
}
# Puppet notices the values '1', '4', '7'.
```
When no block is given, 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 `step` function chained with a `map` function.
```puppet
# For the array $data, return an array, set to the first element and each 5th successor element, in reverse
# order multiplied by 10
$data = Integer[0,20]
$transformed_data = $data.step(5).map |$item| { $item * 10 }
$transformed_data contains [0,50,100,150,200]
```
**Example:** The same example using `step` function chained with a `map` in alternative syntax
```puppet
# For the array $data, return an array, set to the first and each 5th
# successor, in reverse order, multiplied by 10
$data = Integer[0,20]
$transformed_data = map(step($data, 5)) |$item| { $item * 10 }
$transformed_data contains [0,50,100,150,200]
```
* Since 4.4.0
DOC
) do |_args|
Puppet::Parser::Functions::Error.is4x('step')
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/md5.rb | lib/puppet/parser/functions/md5.rb | # frozen_string_literal: true
require 'digest/md5'
Puppet::Parser::Functions.newfunction(:md5, :type => :rvalue, :arity => 1, :doc => "Returns a MD5 hash value from a provided string.") do |args|
Digest::MD5.hexdigest(args[0])
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/epp.rb | lib/puppet/parser/functions/epp.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(:epp, :type => :rvalue, :arity => -2, :doc =>
"Evaluates an Embedded Puppet (EPP) template file and returns the rendered text
result as a String.
`epp('<MODULE NAME>/<TEMPLATE FILE>', <PARAMETER HASH>)`
The first argument to this function should be a `<MODULE NAME>/<TEMPLATE FILE>`
reference, which loads `<TEMPLATE FILE>` from `<MODULE NAME>`'s `templates`
directory. 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 call the apache module's `templates/vhost/_docroot.epp`
template and pass the `docroot` and `virtual_docroot` parameters, call the `epp`
function like this:
`epp('apache/vhost/_docroot.epp', { 'docroot' => '/var/www/html',
'virtual_docroot' => '/var/www/example' })`
This function can also accept an absolute path, which can load a template file
from anywhere on disk.
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 `epp`
function fails to pass any required parameter.
- Since 4.0.0") do |_args|
Puppet::Parser::Functions::Error.is4x('epp')
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/defined.rb | lib/puppet/parser/functions/defined.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(
:defined,
:type => :rvalue,
:arity => -2,
:doc => <<~DOC
Determines whether a given class or resource type is defined and returns a Boolean
value. You can also use `defined` to determine whether a specific resource is defined,
or whether a variable has a value (including `undef`, as opposed to the variable never
being declared or assigned).
This function takes at least one string argument, which can be a class name, type name,
resource reference, or variable reference of the form `'$name'`.
The `defined` function checks both native and defined types, including types
provided by modules. Types and classes are matched by their names. The function matches
resource declarations by using resource references.
**Examples**: Different types of `defined` function matches
~~~ puppet
# Matching resource types
defined("file")
defined("customtype")
# Matching defines and classes
defined("foo")
defined("foo::bar")
# Matching variables
defined('$name')
# Matching declared resources
defined(File['/tmp/file'])
~~~
Puppet depends on the configuration's evaluation order when checking whether a resource
is declared.
**Example**: Importance of evaluation order when using `defined`
~~~ puppet
# Assign values to $is_defined_before and $is_defined_after using identical `defined`
# functions.
$is_defined_before = defined(File['/tmp/file'])
file { "/tmp/file":
ensure => present,
}
$is_defined_after = defined(File['/tmp/file'])
# $is_defined_before returns false, but $is_defined_after returns true.
~~~
This order requirement only refers to evaluation order. The order of resources in the
configuration graph (e.g. with `before` or `require`) does not affect the `defined`
function's behavior.
> **Warning:** Avoid relying on the result of the `defined` function in modules, as you
> might not be able to guarantee the evaluation order well enough to produce consistent
> results. This can cause other code that relies on the function's result to behave
> inconsistently or fail.
If you pass more than one argument to `defined`, the function returns `true` if _any_
of the arguments are defined. You can also match resources by type, allowing you to
match conditions of different levels of specificity, such as whether a specific resource
is of a specific data type.
**Example**: Matching multiple resources and resources by different types with `defined`
~~~ puppet
file { "/tmp/file1":
ensure => file,
}
$tmp_file = file { "/tmp/file2":
ensure => file,
}
# Each of these statements return `true` ...
defined(File['/tmp/file1'])
defined(File['/tmp/file1'],File['/tmp/file2'])
defined(File['/tmp/file1'],File['/tmp/file2'],File['/tmp/file3'])
# ... but this returns `false`.
defined(File['/tmp/file3'])
# Each of these statements returns `true` ...
defined(Type[Resource['file','/tmp/file2']])
defined(Resource['file','/tmp/file2'])
defined(File['/tmp/file2'])
defined('$tmp_file')
# ... but each of these returns `false`.
defined(Type[Resource['exec','/tmp/file2']])
defined(Resource['exec','/tmp/file2'])
defined(File['/tmp/file3'])
defined('$tmp_file2')
~~~
- Since 2.7.0
- Since 3.6.0 variable reference and future parser types
- Since 3.8.1 type specific requests with future parser
- Since 4.0.0 includes all future parser features
DOC
) do |_vals|
Puppet::Parser::Functions::Error.is4x('defined')
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/contain.rb | lib/puppet/parser/functions/contain.rb | # frozen_string_literal: true
# Called within a class definition, establishes a containment
# relationship with another class
Puppet::Parser::Functions.newfunction(
:contain,
:arity => -2,
:doc => "Contain one or more classes inside the current class. If any of
these classes are undeclared, they will be declared as if called with the
`include` function. Accepts a class name, an array of class names, or a
comma-separated list of class names.
A contained class will not be applied before the containing class is
begun, and will be finished before the containing class is finished.
You must use the class's full name;
relative names are not allowed. In addition to names in string form,
you may also directly use Class and Resource Type values that are produced by
evaluating resource and relationship expressions.
The function returns an array of references to the classes that were contained thus
allowing the function call to `contain` to directly continue.
- Since 4.0.0 support for Class and Resource Type values, absolute names
- Since 4.7.0 an Array[Type[Class[n]]] is returned with all the contained classes
"
) do |classes|
# Call the 4.x version of this function in case 3.x ruby code uses this function
Puppet.warn_once('deprecations', '3xfunction#contain', _("Calling function_contain via the Scope class is deprecated. Use Scope#call_function instead"))
call_function('contain', classes)
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/sprintf.rb | lib/puppet/parser/functions/sprintf.rb | # frozen_string_literal: true
# Copyright (C) 2009 Thomas Bellman
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THOMAS BELLMAN BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# Except as contained in this notice, the name of Thomas Bellman shall
# not be used in advertising or otherwise to promote the sale, use or
# other dealings in this Software without prior written authorization
# from Thomas Bellman.
Puppet::Parser::Functions.newfunction(
:sprintf, :type => :rvalue,
:arity => -2,
:doc => "Perform printf-style formatting of text.
The first parameter is format string describing how the rest of the parameters should be formatted.
See the documentation for the [`Kernel::sprintf` function](https://ruby-doc.org/core/Kernel.html)
in Ruby for details.
To use [named format](https://idiosyncratic-ruby.com/49-what-the-format.html) arguments, provide a
hash containing the target string values as the argument to be formatted. For example:
```puppet
notice sprintf(\"%<x>s : %<y>d\", { 'x' => 'value is', 'y' => 42 })
```
This statement produces a notice of `value is : 42`."
) do |args|
fmt = args[0]
args = args[1..]
begin
return sprintf(fmt, *args)
rescue KeyError => e
if args.size == 1 && args[0].is_a?(Hash)
# map the single hash argument such that all top level string keys are symbols
# as that allows named arguments to be used in the format string.
#
result = {}
args[0].each_pair { |k, v| result[k.is_a?(String) ? k.to_sym : k] = v }
return sprintf(fmt, result)
end
raise e
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/strftime.rb | lib/puppet/parser/functions/strftime.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(
:strftime,
:type => :rvalue,
:arity => -3,
:doc => <<~DOC
Formats timestamp or timespan according to the directives in the given format string. The directives begins with a percent (%) character.
Any text not listed as a directive will be passed through to the output string.
A third optional timezone argument can be provided. The first argument will then be formatted to represent a local time in that
timezone. The timezone can be any timezone that is recognized when using the '%z' or '%Z' formats, or the word 'current', in which
case the current timezone of the evaluating process will be used. The timezone argument is case insensitive.
The default timezone, when no argument is provided, or when using the keyword `default`, is 'UTC'.
The directive consists of a percent (%) character, zero or more flags, optional minimum field width and
a conversion specifier as follows:
```
%[Flags][Width]Conversion
```
### Flags that controls padding
| Flag | Meaning
| ---- | ---------------
| - | Don't pad numerical output
| _ | Use spaces for padding
| 0 | Use zeros for padding
### `Timestamp` specific flags
| Flag | Meaning
| ---- | ---------------
| # | Change case
| ^ | Use uppercase
| : | Use colons for %z
### Format directives applicable to `Timestamp` (names and padding can be altered using flags):
**Date (Year, Month, Day):**
| Format | Meaning |
| ------ | ------- |
| Y | Year with century, zero-padded to at least 4 digits |
| C | year / 100 (rounded down such as 20 in 2009) |
| y | year % 100 (00..99) |
| m | Month of the year, zero-padded (01..12) |
| B | The full month name ("January") |
| b | The abbreviated month name ("Jan") |
| h | Equivalent to %b |
| d | Day of the month, zero-padded (01..31) |
| e | Day of the month, blank-padded ( 1..31) |
| j | Day of the year (001..366) |
**Time (Hour, Minute, Second, Subsecond):**
| Format | Meaning |
| ------ | ------- |
| H | Hour of the day, 24-hour clock, zero-padded (00..23) |
| k | Hour of the day, 24-hour clock, blank-padded ( 0..23) |
| I | Hour of the day, 12-hour clock, zero-padded (01..12) |
| l | Hour of the day, 12-hour clock, blank-padded ( 1..12) |
| P | Meridian indicator, lowercase ("am" or "pm") |
| p | Meridian indicator, uppercase ("AM" or "PM") |
| M | Minute of the hour (00..59) |
| S | Second of the minute (00..60) |
| L | Millisecond of the second (000..999). Digits under millisecond are truncated to not produce 1000 |
| N | Fractional seconds digits, default is 9 digits (nanosecond). Digits under a specified width are truncated to avoid carry up |
**Time (Hour, Minute, Second, Subsecond):**
| Format | Meaning |
| ------ | ------- |
| z | Time zone as hour and minute offset from UTC (e.g. +0900) |
| :z | hour and minute offset from UTC with a colon (e.g. +09:00) |
| ::z | hour, minute and second offset from UTC (e.g. +09:00:00) |
| Z | Abbreviated time zone name or similar information. (OS dependent) |
**Weekday:**
| Format | Meaning |
| ------ | ------- |
| A | The full weekday name ("Sunday") |
| a | The abbreviated name ("Sun") |
| u | Day of the week (Monday is 1, 1..7) |
| w | Day of the week (Sunday is 0, 0..6) |
**ISO 8601 week-based year and week number:**
The first week of YYYY starts with a Monday and includes YYYY-01-04.
The days in the year before the first week are in the last week of
the previous year.
| Format | Meaning |
| ------ | ------- |
| G | The week-based year |
| g | The last 2 digits of the week-based year (00..99) |
| V | Week number of the week-based year (01..53) |
**Week number:**
The first week of YYYY that starts with a Sunday or Monday (according to %U
or %W). The days in the year before the first week are in week 0.
| Format | Meaning |
| ------ | ------- |
| U | Week number of the year. The week starts with Sunday. (00..53) |
| W | Week number of the year. The week starts with Monday. (00..53) |
**Seconds since the Epoch:**
| Format | Meaning |
| s | Number of seconds since 1970-01-01 00:00:00 UTC. |
**Literal string:**
| Format | Meaning |
| ------ | ------- |
| n | Newline character (\n) |
| t | Tab character (\t) |
| % | Literal "%" character |
**Combination:**
| Format | Meaning |
| ------ | ------- |
| c | date and time (%a %b %e %T %Y) |
| D | Date (%m/%d/%y) |
| F | The ISO 8601 date format (%Y-%m-%d) |
| v | VMS date (%e-%^b-%4Y) |
| x | Same as %D |
| X | Same as %T |
| r | 12-hour time (%I:%M:%S %p) |
| R | 24-hour time (%H:%M) |
| T | 24-hour time (%H:%M:%S) |
**Example**: Using `strftime` with a `Timestamp`:
~~~ puppet
$timestamp = Timestamp('2016-08-24T12:13:14')
# Notice the timestamp using a format that notices the ISO 8601 date format
notice($timestamp.strftime('%F')) # outputs '2016-08-24'
# Notice the timestamp using a format that notices weekday, month, day, time (as UTC), and year
notice($timestamp.strftime('%c')) # outputs 'Wed Aug 24 12:13:14 2016'
# Notice the timestamp using a specific timezone
notice($timestamp.strftime('%F %T %z', 'PST')) # outputs '2016-08-24 04:13:14 -0800'
# Notice the timestamp using timezone that is current for the evaluating process
notice($timestamp.strftime('%F %T', 'current')) # outputs the timestamp using the timezone for the current process
~~~
### Format directives applicable to `Timespan`:
| Format | Meaning |
| ------ | ------- |
| D | Number of Days |
| H | Hour of the day, 24-hour clock |
| M | Minute of the hour (00..59) |
| S | Second of the minute (00..59) |
| L | Millisecond of the second (000..999). Digits under millisecond are truncated to not produce 1000. |
| N | Fractional seconds digits, default is 9 digits (nanosecond). Digits under a specified length are truncated to avoid carry up |
The format directive that represents the highest magnitude in the format will be allowed to overflow.
I.e. if no "%D" is used but a "%H" is present, then the hours will be more than 23 in case the
timespan reflects more than a day.
**Example**: Using `strftime` with a Timespan and a format
~~~ puppet
$duration = Timespan({ hours => 3, minutes => 20, seconds => 30 })
# Notice the duration using a format that outputs <hours>:<minutes>:<seconds>
notice($duration.strftime('%H:%M:%S')) # outputs '03:20:30'
# Notice the duration using a format that outputs <minutes>:<seconds>
notice($duration.strftime('%M:%S')) # outputs '200:30'
~~~
- Since 4.8.0
DOC
) do |_args|
Puppet::Parser::Functions::Error.is4x('strftime')
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/sha1.rb | lib/puppet/parser/functions/sha1.rb | # frozen_string_literal: true
require 'digest/sha1'
Puppet::Parser::Functions.newfunction(:sha1, :type => :rvalue, :arity => 1, :doc => "Returns a SHA1 hash value from a provided string.") do |args|
Digest::SHA1.hexdigest(args[0])
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/match.rb | lib/puppet/parser/functions/match.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(
:match,
:arity => 2,
:doc => <<~DOC
Matches a regular expression against a string and returns an array containing the match
and any matched capturing groups.
The first argument is a string or array of strings. The second argument is either a
regular expression, regular expression represented as a string, or Regex or Pattern
data type that the function matches against the first argument.
The returned array contains the entire match at index 0, and each captured group at
subsequent index values. If the value or expression being matched is an array, the
function returns an array with mapped match results.
If the function doesn't find a match, it returns 'undef'.
**Example**: Matching a regular expression in a string
~~~ ruby
$matches = "abc123".match(/[a-z]+[1-9]+/)
# $matches contains [abc123]
~~~
**Example**: Matching a regular expressions with grouping captures in a string
~~~ ruby
$matches = "abc123".match(/([a-z]+)([1-9]+)/)
# $matches contains [abc123, abc, 123]
~~~
**Example**: Matching a regular expression with grouping captures in an array of strings
~~~ ruby
$matches = ["abc123","def456"].match(/([a-z]+)([1-9]+)/)
# $matches contains [[abc123, abc, 123], [def456, def, 456]]
~~~
- Since 4.0.0
DOC
) do |_args|
Puppet::Parser::Functions::Error.is4x('match')
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/lest.rb | lib/puppet/parser/functions/lest.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(
:lest,
:type => :rvalue,
:arity => -2,
:doc => <<~DOC
Call a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html)
(which should accept no arguments) if the argument given to the function is `undef`.
Returns the result of calling the lambda if the argument is `undef`, otherwise the
given argument.
The `lest` function is useful in a chain of `then` calls, or in general
as a guard against `undef` values. The function can be used to call `fail`, or to
return a default value.
These two expressions are equivalent:
```puppet
if $x == undef { do_things() }
lest($x) || { do_things() }
```
**Example:** Using the `lest` function
```puppet
$data = {a => [ b, c ] }
notice $data.dig(a, b, c)
.then |$x| { $x * 2 }
.lest || { fail("no value for $data[a][b][c]" }
```
Would fail the operation because $data[a][b][c] results in `undef`
(there is no `b` key in `a`).
In contrast - this example:
```puppet
$data = {a => { b => { c => 10 } } }
notice $data.dig(a, b, c)
.then |$x| { $x * 2 }
.lest || { fail("no value for $data[a][b][c]" }
```
Would notice the value `20`
* Since 4.5.0
DOC
) do |_args|
Puppet::Parser::Functions::Error.is4x('lest')
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/template.rb | lib/puppet/parser/functions/template.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(:template, :type => :rvalue, :arity => -2, :doc =>
"Loads an ERB template from a module, evaluates it, and returns the resulting
value as a string.
The argument to this function should be a `<MODULE NAME>/<TEMPLATE FILE>`
reference, which will load `<TEMPLATE FILE>` from a module's `templates`
directory. (For example, the reference `apache/vhost.conf.erb` will load the
file `<MODULES DIRECTORY>/apache/templates/vhost.conf.erb`.)
This function can also accept:
* An absolute path, which can load a template file from anywhere on disk.
* Multiple arguments, which will evaluate all of the specified templates and
return their outputs concatenated into a single string.") do |vals|
if Puppet[:tasks]
raise Puppet::ParseErrorWithIssue.from_issue_and_stack(
Puppet::Pops::Issues::FEATURE_NOT_SUPPORTED_WHEN_SCRIPTING,
{ :feature => 'ERB template' }
)
end
vals.collect do |file|
# Use a wrapper, so the template can't get access to the full
# Scope object.
debug "Retrieving template #{file}"
wrapper = Puppet::Parser::TemplateWrapper.new(self)
wrapper.file = file
begin
wrapper.result
rescue => detail
info = detail.backtrace.first.split(':')
message = []
message << _("Failed to parse template %{file}:") % { file: file }
message << _(" Filepath: %{file_path}") % { file_path: info[0] }
message << _(" Line: %{line}") % { line: info[1] }
message << _(" Detail: %{detail}") % { detail: detail }
raise Puppet::ParseError, message.join("\n") + "\n"
end
end.join("")
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/require.rb | lib/puppet/parser/functions/require.rb | # frozen_string_literal: true
# Requires the specified classes
Puppet::Parser::Functions.newfunction(
:require,
:arity => -2,
:doc => "Evaluate one or more classes, adding the required class as a dependency.
The relationship metaparameters work well for specifying relationships
between individual resources, but they can be clumsy for specifying
relationships between classes. This function is a superset of the
'include' function, adding a class relationship so that the requiring
class depends on the required class.
Warning: using require in place of include can lead to unwanted dependency cycles.
For instance the following manifest, with 'require' instead of 'include' would produce a nasty dependence cycle, because notify imposes a before between File[/foo] and Service[foo]:
class myservice {
service { foo: ensure => running }
}
class otherstuff {
include myservice
file { '/foo': notify => Service[foo] }
}
Note that this function only works with clients 0.25 and later, and it will
fail if used with earlier clients.
You must use the class's full name;
relative names are not allowed. In addition to names in string form,
you may also directly use Class and Resource Type values that are produced when evaluating
resource and relationship expressions.
- Since 4.0.0 Class and Resource types, absolute names
- Since 4.7.0 Returns an Array[Type[Class]] with references to the required classes
"
) do |classes|
call_function('require', classes)
Puppet.warn_once('deprecations', '3xfunction#require', _("Calling function_require via the Scope class is deprecated. Use Scope#call_function instead"))
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/assert_type.rb | lib/puppet/parser/functions/assert_type.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(
:assert_type,
:type => :rvalue,
:arity => -3,
:doc => <<~DOC
Returns the given value if it is of the given
[data type](https://puppet.com/docs/puppet/latest/lang_data.html), or
otherwise either raises an error or executes an optional two-parameter
[lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html).
The function takes two mandatory arguments, in this order:
1. The expected data type.
2. A value to compare against the expected data type.
**Example**: Using `assert_type`
~~~ puppet
$raw_username = 'Amy Berry'
# Assert that $raw_username is a non-empty string and assign it to $valid_username.
$valid_username = assert_type(String[1], $raw_username)
# $valid_username contains "Amy Berry".
# If $raw_username was an empty string or a different data type, the Puppet run would
# fail with an "Expected type does not match actual" error.
~~~
You can use an optional lambda to provide enhanced feedback. The lambda takes two
mandatory parameters, in this order:
1. The expected data type as described in the function's first argument.
2. The actual data type of the value.
**Example**: Using `assert_type` with a warning and default value
~~~ puppet
$raw_username = 'Amy Berry'
# Assert that $raw_username is a non-empty string and assign it to $valid_username.
# If it isn't, output a warning describing the problem and use a default value.
$valid_username = assert_type(String[1], $raw_username) |$expected, $actual| {
warning( "The username should be \'${expected}\', not \'${actual}\'. Using 'anonymous'." )
'anonymous'
}
# $valid_username contains "Amy Berry".
# If $raw_username was an empty string, the Puppet run would set $valid_username to
# "anonymous" and output a warning: "The username should be 'String[1, default]', not
# 'String[0, 0]'. Using 'anonymous'."
~~~
For more information about data types, see the
[documentation](https://puppet.com/docs/puppet/latest/lang_data.html).
- Since 4.0.0
DOC
) do |_args|
Puppet::Parser::Functions::Error.is4x('assert_type')
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/next.rb | lib/puppet/parser/functions/next.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(
:next,
:arity => -2,
:doc => <<~DOC
Immediately returns the given optional value from a block (lambda), function, class body or user defined type body.
If a value is not given, an `undef` value is returned. This function does not return to the immediate caller.
The signal produced to return a value bubbles up through
the call stack until reaching a code block (lambda), function, class definition or
definition of a user defined type at which point the value given to the function will
be produced as the result of that body of code. An error is raised
if the signal to return a value reaches the end of the call stack.
**Example:** Using `next` in `each`
```puppet
$data = [1,2,3]
$data.each |$x| { if $x == 2 { next() } notice $x }
```
Would notice the values `1` and `3`
**Example:** Using `next` to produce a value
If logic consists of deeply nested conditionals it may be complicated to get out of the innermost conditional.
A call to `next` can then simplify the logic. This example however, only shows the principle.
```puppet
$data = [1,2,3]
notice $data.map |$x| { if $x == 2 { next($x*100) }; $x*10 }
```
Would notice the value `[10, 200, 30]`
* Also see functions `return` and `break`
* Since 4.8.0
DOC
) do |_args|
Puppet::Parser::Functions::Error.is4x('next')
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/fail.rb | lib/puppet/parser/functions/fail.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(
:fail,
:arity => -1,
:doc => <<~DOC
Fail with a parse error. Any parameters will be stringified,
concatenated, and passed to the exception-handler.
DOC
) do |vals|
vals = vals.collect(&:to_s).join(" ") if vals.is_a? Array
raise Puppet::ParseError, vals.to_s
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/create_resources.rb | lib/puppet/parser/functions/create_resources.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(:create_resources, :arity => -3, :doc => <<-'ENDHEREDOC') do |args|
Converts a hash into a set of resources and adds them to the catalog.
**Note**: Use this function selectively. It's generally better to write resources in
[Puppet](https://puppet.com/docs/puppet/latest/lang_resources.html), as
resources created with `create_resource` are difficult to read and troubleshoot.
This function takes two mandatory arguments: a resource type, and a hash describing
a set of resources. The hash should be in the form `{title => {parameters} }`:
# A hash of user resources:
$myusers = {
'nick' => { uid => '1330',
gid => allstaff,
groups => ['developers', 'operations', 'release'], },
'dan' => { uid => '1308',
gid => allstaff,
groups => ['developers', 'prosvc', 'release'], },
}
create_resources(user, $myusers)
A third, optional parameter may be given, also as a hash:
$defaults = {
'ensure' => present,
'provider' => 'ldap',
}
create_resources(user, $myusers, $defaults)
The values given on the third argument are added to the parameters of each resource
present in the set given on the second argument. If a parameter is present on both
the second and third arguments, the one on the second argument takes precedence.
This function can be used to create defined resources and classes, as well
as native resources.
Virtual and Exported resources may be created by prefixing the type name
with @ or @@ respectively. For example, the $myusers hash may be exported
in the following manner:
create_resources("@@user", $myusers)
The $myusers may be declared as virtual resources using:
create_resources("@user", $myusers)
Note that `create_resources` filters out parameter values that are `undef` so that normal
data binding and Puppet default value expressions are considered (in that order) for the
final value of a parameter (just as when setting a parameter to `undef` in a Puppet language
resource declaration).
ENDHEREDOC
if Puppet[:tasks]
raise Puppet::ParseErrorWithIssue.from_issue_and_stack(
Puppet::Pops::Issues::CATALOG_OPERATION_NOT_SUPPORTED_WHEN_SCRIPTING,
{ :operation => 'create_resources' }
)
end
raise ArgumentError, (_("create_resources(): wrong number of arguments (%{count}; must be 2 or 3)") % { count: args.length }) if args.length > 3
raise ArgumentError, _('create_resources(): second argument must be a hash') unless args[1].is_a?(Hash)
if args.length == 3
raise ArgumentError, _('create_resources(): third argument, if provided, must be a hash') unless args[2].is_a?(Hash)
end
type, instances, defaults = args
defaults ||= {}
type_name = type.sub(/^@{1,2}/, '').downcase
# Get file/line information from the Puppet stack (where call comes from in Puppet source)
# If relayed via other Puppet functions in ruby that do not nest their calls, the source position
# will be in the original Puppet source.
#
file, line = Puppet::Pops::PuppetStack.top_of_stack
if type.start_with? '@@'
exported = true
virtual = true
elsif type.start_with? '@'
virtual = true
end
if type_name == 'class' && (exported || virtual)
# cannot find current evaluator, so use another
evaluator = Puppet::Pops::Parser::EvaluatingParser.new.evaluator
# optionally fails depending on configured severity of issue
evaluator.runtime_issue(Puppet::Pops::Issues::CLASS_NOT_VIRTUALIZABLE)
end
instances.map do |title, params|
# Add support for iteration if title is an array
resource_titles = title.is_a?(Array) ? title : [title]
Puppet::Pops::Evaluator::Runtime3ResourceSupport.create_resources(
file, line,
self,
virtual, exported,
type_name,
resource_titles,
defaults.merge(params).filter_map do |name, value|
value = nil if value == :undef
Puppet::Parser::Resource::Param.new(
:name => name,
:value => value, # wide open to various data types, must be correct
:source => source, # TODO: support :line => line, :file => file,
:add => false
)
end
)
end.flatten.compact
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/split.rb | lib/puppet/parser/functions/split.rb | # frozen_string_literal: true
module Puppet::Parser::Functions
newfunction(
:split, :type => :rvalue,
:arity => 2,
:doc => "\
Split a string variable into an array using the specified split regexp.
*Example:*
$string = 'v1.v2:v3.v4'
$array_var1 = split($string, ':')
$array_var2 = split($string, '[.]')
$array_var3 = split($string, Regexp['[.:]'])
`$array_var1` now holds the result `['v1.v2', 'v3.v4']`,
while `$array_var2` holds `['v1', 'v2:v3', 'v4']`, and
`$array_var3` holds `['v1', 'v2', 'v3', 'v4']`.
Note that in the second example, we split on a literal string that contains
a regexp meta-character (.), which must be escaped. A simple
way to do that for a single character is to enclose it in square
brackets; a backslash will also escape a single character."
) do |_args|
Error.is4x('split')
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/scanf.rb | lib/puppet/parser/functions/scanf.rb | # frozen_string_literal: true
require 'scanf'
Puppet::Parser::Functions.newfunction(
:scanf,
:type => :rvalue,
:arity => 2,
:doc => <<~DOC
Scans a string and returns an array of one or more converted values based on the given format string.
See the documentation of Ruby's String#scanf method for details about the supported formats (which
are similar but not identical to the formats used in Puppet's `sprintf` function.)
This function takes two mandatory arguments: the first is the string to convert, and the second is
the format string. The result of the scan is an array, with each successfully scanned and transformed value.
The scanning stops if a scan is unsuccessful, and the scanned result up to that point is returned. If there
was no successful scan, the result is an empty array.
```puppet
"42".scanf("%i")
```
You can also optionally pass a lambda to scanf, to do additional validation or processing.
```puppet
"42".scanf("%i") |$x| {
unless $x[0] =~ Integer {
fail "Expected a well formed integer value, got '$x[0]'"
}
$x[0]
}
```
- Since 4.0.0
DOC
) do |args|
data = args[0]
format = args[1]
data.scanf(format)
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/map.rb | lib/puppet/parser/functions/map.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(
:map,
:type => :rvalue,
:arity => -3,
:doc => <<~DOC
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 or hash 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
DOC
) do |_args|
Puppet::Parser::Functions::Error.is4x('map')
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/inline_template.rb | lib/puppet/parser/functions/inline_template.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(:inline_template, :type => :rvalue, :arity => -2, :doc =>
"Evaluate a template string and return its value. See
[the templating docs](https://puppet.com/docs/puppet/latest/lang_template.html) for
more information. Note that if multiple template strings are specified, their
output is all concatenated and returned as the output of the function.") do |vals|
if Puppet[:tasks]
raise Puppet::ParseErrorWithIssue.from_issue_and_stack(
Puppet::Pops::Issues::FEATURE_NOT_SUPPORTED_WHEN_SCRIPTING,
{ :feature => 'ERB inline_template' }
)
end
require 'erb'
vals.collect do |string|
# Use a wrapper, so the template can't get access to the full
# Scope object.
wrapper = Puppet::Parser::TemplateWrapper.new(self)
begin
wrapper.result(string)
rescue => detail
raise Puppet::ParseError, _("Failed to parse inline template: %{detail}") % { detail: detail }, detail.backtrace
end
end.join("")
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/return.rb | lib/puppet/parser/functions/return.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(
:return,
:arity => -2,
:doc => <<~DOC
Immediately returns the given optional value from a function, class body or user defined type body.
If a value is not given, an `undef` value is returned. This function does not return to the immediate caller.
If this function is called from within a lambda, the return action is from the scope of the
function containing the lambda (top scope), not the function accepting the lambda (local scope).
The signal produced to return a value bubbles up through
the call stack until reaching a function, class definition or
definition of a user defined type at which point the value given to the function will
be produced as the result of that body of code. An error is raised
if the signal to return a value reaches the end of the call stack.
**Example:** Using `return`
```puppet
function example($x) {
# handle trivial cases first for better readability of
# what follows
if $x == undef or $x == [] or $x == '' {
return false
}
# complex logic to determine if value is true
true
}
notice example([]) # would notice false
notice example(42) # would notice true
```
**Example:** Using `return` in a class
```puppet
class example($x) {
# handle trivial cases first for better readability of
# what follows
if $x == undef or $x == [] or $x == '' {
# Do some default configuration of this class
notice 'foo'
return()
}
# complex logic configuring the class if something more interesting
# was given in $x
notice 'bar'
}
```
When used like this:
```puppet
class { example: x => [] }
```
The code would notice `'foo'`, but not `'bar'`.
When used like this:
```puppet
class { example: x => [some_value] }
```
The code would notice `'bar'` but not `'foo'`
Note that the returned value is ignored if used in a class or user defined type.
**Example:** Using `return` in a lambda
```puppet
# Concatenate three strings into a single string formatted as a list.
function getFruit() {
with("apples", "oranges", "bananas") |$x, $y, $z| {
return("${x}, ${y}, and ${z}")
}
notice "not reached"
}
$fruit = getFruit()
notice $fruit
# The output contains "apples, oranges, and bananas".
# "not reached" is not output because the function returns its value within the
# calling function's scope, which stops processing the calling function before
# the `notice "not reached"` statement.
# Using `return()` outside of a calling function results in an error.
```
* Also see functions `return` and `break`
* Since 4.8.0
DOC
) do |_args|
Puppet::Parser::Functions::Error.is4x('return')
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/each.rb | lib/puppet/parser/functions/each.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(
:each,
:type => :rvalue,
:arity => -3,
:doc => <<~DOC
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 or hash 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
DOC
) do |_args|
Puppet::Parser::Functions::Error.is4x('each')
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/lookup.rb | lib/puppet/parser/functions/lookup.rb | # frozen_string_literal: true
module Puppet::Parser::Functions
newfunction(:lookup, :type => :rvalue, :arity => -2, :doc => <<~'ENDHEREDOC') do |_args|
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|unique|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 or undef) --- A string prefix to indicate a
value should be _removed_ from the final result. 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`.
#### Examples
Look up a key and return the first value found:
lookup('ntp::service_name')
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
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' => '--',
},
})
ENDHEREDOC
Error.is4x('lookup')
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/versioncmp.rb | lib/puppet/parser/functions/versioncmp.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/package'
Puppet::Parser::Functions.newfunction(:versioncmp, :type => :rvalue, :arity => 2, :doc =>
"Compares two version numbers.
Prototype:
\$result = versioncmp(a, b)
Where a and b are arbitrary version strings.
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:
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.
") do |args|
return Puppet::Util::Package.versioncmp(args[0], args[1])
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/inline_epp.rb | lib/puppet/parser/functions/inline_epp.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(:inline_epp, :type => :rvalue, :arity => -2, :doc =>
"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 3.5
- Requires [future parser](https://puppet.com/docs/puppet/3.8/experiments_future.html) in Puppet 3.5 to 3.8") do |_arguments|
Puppet::Parser::Functions::Error.is4x('inline_epp')
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/regsubst.rb | lib/puppet/parser/functions/regsubst.rb | # frozen_string_literal: true
# Copyright (C) 2009 Thomas Bellman
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
# IN NO EVENT SHALL THOMAS BELLMAN BE LIABLE FOR ANY CLAIM, DAMAGES OR
# OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
# ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
#
# Except as contained in this notice, the name of Thomas Bellman shall
# not be used in advertising or otherwise to promote the sale, use or
# other dealings in this Software without prior written authorization
# from Thomas Bellman.
module Puppet::Parser::Functions
newfunction(
:regsubst, :type => :rvalue,
:arity => -4,
:doc => "
Perform regexp replacement on a string or array of strings.
* *Parameters* (in order):
* _target_ 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.
* _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.
* _replacement_ Replacement string. Can contain backreferences to what was matched using \\0 (whole match), \\1 (first set of parentheses), and so on.
* _flags_ Optional. String of single letter flags for how the regexp is interpreted:
- *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.
* _encoding_ Optional. How to handle multibyte characters. A single-character string with the following values:
- *N* None
- *E* EUC
- *S* SJIS
- *U* UTF-8
* *Examples*
Get the third octet from the node's IP address:
$i3 = regsubst($ipaddress,'^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$','\\3')
Put angle brackets around each octet in the node's IP address:
$x = regsubst($ipaddress, '([0-9]+)', '<\\1>', 'G')
"
) do |_args|
Error.is4x('regsubst')
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/break.rb | lib/puppet/parser/functions/break.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(
:break,
:arity => 0,
:doc => <<~DOC
Breaks the 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
DOC
) do |_args|
Puppet::Parser::Functions::Error.is4x('break')
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/dig.rb | lib/puppet/parser/functions/dig.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(
:dig,
:type => :rvalue,
:arity => -1,
:doc => <<~DOC
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
DOC
) do |_args|
Puppet::Parser::Functions::Error.is4x('dig')
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/then.rb | lib/puppet/parser/functions/then.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(
:then,
:type => :rvalue,
:arity => -2,
:doc => <<~DOC
Call a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html)
with the given argument unless the argument is undef. Return `undef` if 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}, {ex => 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}'" }
)
```
Would notice "Picked Beatle 'Paul'", and would raise an error if the result
was not a String.
* Since 4.5.0
DOC
) do |_args|
Puppet::Parser::Functions::Error.is4x('then')
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/reverse_each.rb | lib/puppet/parser/functions/reverse_each.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(
:reverse_each,
:type => :rvalue,
:arity => -1,
:doc => <<~DOC
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
DOC
) do |_args|
Puppet::Parser::Functions::Error.is4x('reverse_each')
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/with.rb | lib/puppet/parser/functions/with.rb | # frozen_string_literal: true
Puppet::Parser::Functions.newfunction(
:with,
:type => :rvalue,
:arity => -1,
:doc => <<~DOC
Call a [lambda](https://puppet.com/docs/puppet/latest/lang_lambdas.html)
with the given arguments and return the result. Since a lambda's scope is
local 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
DOC
) do |_args|
Puppet::Parser::Functions::Error.is4x('with')
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/functions/sha256.rb | lib/puppet/parser/functions/sha256.rb | # frozen_string_literal: true
require 'digest/sha2'
Puppet::Parser::Functions.newfunction(:sha256, :type => :rvalue, :arity => 1, :doc => "Returns a SHA256 hash value from a provided string.") do |args|
Digest::SHA256.hexdigest(args[0])
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/ast/resource.rb | lib/puppet/parser/ast/resource.rb | # frozen_string_literal: true
# Instruction for Resource instantiation.
# Instantiates resources of both native and user defined types.
#
class Puppet::Parser::AST::Resource < Puppet::Parser::AST::Branch
attr_accessor :type, :instances, :exported, :virtual
def initialize(argshash)
Puppet.warn_once('deprecations', 'AST::Resource', _('Use of Puppet::Parser::AST::Resource is deprecated and not fully functional'))
super(argshash)
end
# Evaluates resources by adding them to the compiler for lazy evaluation
# and returning the produced resource references.
#
def evaluate(scope)
# We want virtual to be true if exported is true. We can't
# just set :virtual => self.virtual in the initialization,
# because sometimes the :virtual attribute is set *after*
# :exported, in which case it clobbers :exported if :exported
# is true. Argh, this was a very tough one to track down.
virt = virtual || exported
# First level of implicit iteration: build a resource for each
# instance. This handles things like:
# file { '/foo': owner => blah; '/bar': owner => blah }
@instances.map do |instance|
# Evaluate all of the specified params.
paramobjects = instance.parameters.map { |param| param.safeevaluate(scope) }
resource_titles = instance.title.safeevaluate(scope)
# it's easier to always use an array, even for only one name
resource_titles = [resource_titles] unless resource_titles.is_a?(Array)
fully_qualified_type, resource_titles = scope.resolve_type_and_titles(type, resource_titles)
# Second level of implicit iteration; build a resource for each
# title. This handles things like:
# file { ['/foo', '/bar']: owner => blah }
resource_titles.flatten.map do |resource_title|
exceptwrap :type => Puppet::ParseError do
resource = Puppet::Parser::Resource.new(
fully_qualified_type, resource_title,
:parameters => paramobjects,
:file => file,
:line => line,
:exported => exported,
:virtual => virt,
:source => scope.source,
:scope => scope,
:strict => true
)
if resource.resource_type.is_a? Puppet::Resource::Type
resource.resource_type.instantiate_resource(scope, resource)
end
scope.compiler.add_resource(scope, resource)
scope.compiler.evaluate_classes([resource_title], scope, false) if fully_qualified_type == 'class'
resource
end
end
end.flatten.compact
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/ast/resourceparam.rb | lib/puppet/parser/ast/resourceparam.rb | # frozen_string_literal: true
# The AST object for the parameters inside resource expressions
#
class Puppet::Parser::AST::ResourceParam < Puppet::Parser::AST::Branch
attr_accessor :value, :param, :add
def initialize(argshash)
Puppet.warn_once('deprecations', 'AST::ResourceParam', _('Use of Puppet::Parser::AST::ResourceParam is deprecated and not fully functional'))
super(argshash)
end
def each
[@param, @value].each { |child| yield child }
end
# Return the parameter and the value.
def evaluate(scope)
value = @value.safeevaluate(scope)
Puppet::Parser::Resource::Param.new(
:name => @param,
:value => value.nil? ? :undef : value,
:source => scope.source,
:line => line,
:file => file,
:add => add
)
end
def to_s
"#{@param} => #{@value}"
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/ast/node.rb | lib/puppet/parser/ast/node.rb | # frozen_string_literal: true
class Puppet::Parser::AST::Node < Puppet::Parser::AST::TopLevelConstruct
attr_accessor :names, :context
def initialize(names, context = {})
raise ArgumentError, _("names should be an array") unless names.is_a? Array
if context[:parent]
raise Puppet::DevError, _("Node inheritance is removed in Puppet 4.0.0. See http://links.puppet.com/puppet-node-inheritance-deprecation")
end
@names = names
@context = context
end
def instantiate(modname)
@names.map { |name| Puppet::Resource::Type.new(:node, name, @context.merge(:module_name => modname)) }
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/ast/block_expression.rb | lib/puppet/parser/ast/block_expression.rb | # frozen_string_literal: true
# Evaluates contained expressions, produce result of the last
#
class Puppet::Parser::AST::BlockExpression < Puppet::Parser::AST::Branch
def evaluate(scope)
@children.reduce(nil) { |_, child| child.safeevaluate(scope) }
end
def sequence_with(other)
Puppet::Parser::AST::BlockExpression.new(:children => children + other.children)
end
def to_s
"[" + @children.collect(&:to_s).join(', ') + "]"
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/ast/resource_instance.rb | lib/puppet/parser/ast/resource_instance.rb | # frozen_string_literal: true
# A simple container for a parameter for an object. Consists of a
# title and a set of parameters.
#
class Puppet::Parser::AST::ResourceInstance < Puppet::Parser::AST::Branch
attr_accessor :title, :parameters
def initialize(argshash)
Puppet.warn_once('deprecations', 'AST::ResourceInstance', _('Use of Puppet::Parser::AST::ResourceInstance is deprecated'))
super(argshash)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/ast/pops_bridge.rb | lib/puppet/parser/ast/pops_bridge.rb | # frozen_string_literal: true
require_relative '../../../puppet/parser/ast/top_level_construct'
require_relative '../../../puppet/pops'
# The AST::Bridge contains classes that bridges between the new Pops based model
# and the 3.x AST. This is required to be able to reuse the Puppet::Resource::Type which is
# fundamental for the rest of the logic.
#
class Puppet::Parser::AST::PopsBridge
# Bridges to one Pops Model Expression
# The @value is the expression
# This is used to represent the body of a class, definition, or node, and for each parameter's default value
# expression.
#
class Expression < Puppet::Parser::AST::Leaf
def to_s
Puppet::Pops::Model::ModelTreeDumper.new.dump(@value)
end
def source_text
source_adapter = Puppet::Pops::Utils.find_closest_positioned(@value)
source_adapter ? source_adapter.extract_text() : nil
end
def evaluate(scope)
evaluator = Puppet::Pops::Parser::EvaluatingParser.singleton
object = evaluator.evaluate(scope, @value)
evaluator.convert_to_3x(object, scope)
end
# Adapts to 3x where top level constructs needs to have each to iterate over children. Short circuit this
# by yielding self. By adding this there is no need to wrap a pops expression inside an AST::BlockExpression
#
def each
yield self
end
def sequence_with(other)
if value.nil?
# This happens when testing and not having a complete setup
other
else
# When does this happen ? Ever ?
raise "sequence_with called on Puppet::Parser::AST::PopsBridge::Expression - please report use case"
# What should be done if the above happens (We don't want this to happen).
# Puppet::Parser::AST::BlockExpression.new(:children => [self] + other.children)
end
end
# The 3x requires code plugged in to an AST to have this in certain positions in the tree. The purpose
# is to either print the content, or to look for things that needs to be defined. This implementation
# cheats by always returning an empty array. (This allows simple files to not require a "Program" at the top.
#
def children
[]
end
end
class ExpressionSupportingReturn < Expression
def evaluate(scope)
catch(:return) do
return catch(:next) do
return super(scope)
end
end
end
end
# Bridges the top level "Program" produced by the pops parser.
# Its main purpose is to give one point where all definitions are instantiated (actually defined since the
# Puppet 3x terminology is somewhat misleading - the definitions are instantiated, but instances of the created types
# are not created, that happens when classes are included / required, nodes are matched and when resources are instantiated
# by a resource expression (which is also used to instantiate a host class).
#
class Program < Puppet::Parser::AST::TopLevelConstruct
attr_reader :program_model, :context
def initialize(program_model, context = {})
@program_model = program_model
@context = context
@ast_transformer ||= Puppet::Pops::Model::AstTransformer.new(@context[:file])
end
# This is the 3x API, the 3x AST searches through all code to find the instructions that can be instantiated.
# This Pops-model based instantiation relies on the parser to build this list while parsing (which is more
# efficient as it avoids one full scan of all logic via recursive enumeration/yield)
#
def instantiate(modname)
@program_model.definitions.map do |d|
case d
when Puppet::Pops::Model::HostClassDefinition
instantiate_HostClassDefinition(d, modname)
when Puppet::Pops::Model::ResourceTypeDefinition
instantiate_ResourceTypeDefinition(d, modname)
when Puppet::Pops::Model::NodeDefinition
instantiate_NodeDefinition(d, modname)
else
loaders = Puppet::Pops::Loaders.loaders
loaders.instantiate_definition(d, loaders.find_loader(modname))
# The 3x logic calling this will not know what to do with the result, it is compacted away at the end
nil
end
end.flatten().compact() # flatten since node definition may have returned an array
# Compact since 4x definitions are not understood by compiler
end
def evaluate(scope)
Puppet::Pops::Parser::EvaluatingParser.singleton.evaluate(scope, program_model)
end
# Adapts to 3x where top level constructs needs to have each to iterate over children. Short circuit this
# by yielding self. This means that the HostClass container will call this bridge instance with `instantiate`.
#
def each
yield self
end
# Returns true if this Program only contains definitions
def is_definitions_only?
is_definition?(program_model)
end
private
def is_definition?(o)
case o
when Puppet::Pops::Model::Program
is_definition?(o.body)
when Puppet::Pops::Model::BlockExpression
o.statements.all { |s| is_definition?(s) }
when Puppet::Pops::Model::Definition
true
else
false
end
end
def instantiate_Parameter(o)
# 3x needs parameters as an array of `[name]` or `[name, value_expr]`
if o.value
[o.name, Expression.new(:value => o.value)]
else
[o.name]
end
end
def create_type_map(definition)
result = {}
# No need to do anything if there are no parameters
return result unless definition.parameters.size > 0
# No need to do anything if there are no typed parameters
typed_parameters = definition.parameters.select(&:type_expr)
return result if typed_parameters.empty?
# If there are typed parameters, they need to be evaluated to produce the corresponding type
# instances. This evaluation requires a scope. A scope is not available when doing deserialization
# (there is also no initialized evaluator). When running apply and test however, the environment is
# reused and we may reenter without a scope (which is fine). A debug message is then output in case
# there is the need to track down the odd corner case. See {#obtain_scope}.
#
scope = obtain_scope
if scope
evaluator = Puppet::Pops::Parser::EvaluatingParser.singleton
typed_parameters.each do |p|
result[p.name] = evaluator.evaluate(scope, p.type_expr)
end
end
result
end
# Obtains the scope or issues a warning if :global_scope is not bound
def obtain_scope
Puppet.lookup(:global_scope) do
# This occurs when testing and when applying a catalog (there is no scope available then), and
# when running tests that run a partial setup.
# This is bad if the logic is trying to compile, but a warning can not be issues since it is a normal
# use case that there is no scope when requesting the type in order to just get the parameters.
Puppet.debug { _("Instantiating Resource with type checked parameters - scope is missing, skipping type checking.") }
nil
end
end
# Produces a hash with data for Definition and HostClass
def args_from_definition(o, modname, expr_class = Expression)
args = {
:arguments => o.parameters.collect { |p| instantiate_Parameter(p) },
:argument_types => create_type_map(o),
:module_name => modname
}
unless is_nop?(o.body)
args[:code] = expr_class.new(:value => o.body)
end
@ast_transformer.merge_location(args, o)
end
def instantiate_HostClassDefinition(o, modname)
args = args_from_definition(o, modname, ExpressionSupportingReturn)
args[:parent] = absolute_reference(o.parent_class)
Puppet::Resource::Type.new(:hostclass, o.name, @context.merge(args))
end
def instantiate_ResourceTypeDefinition(o, modname)
instance = Puppet::Resource::Type.new(:definition, o.name, @context.merge(args_from_definition(o, modname, ExpressionSupportingReturn)))
Puppet::Pops::Loaders.register_runtime3_type(instance.name, o.locator.to_uri(o))
instance
end
def instantiate_NodeDefinition(o, modname)
args = { :module_name => modname }
unless is_nop?(o.body)
args[:code] = Expression.new(:value => o.body)
end
unless is_nop?(o.parent)
args[:parent] = @ast_transformer.hostname(o.parent)
end
args = @ast_transformer.merge_location(args, o)
host_matches = @ast_transformer.hostname(o.host_matches)
host_matches.collect do |name|
Puppet::Resource::Type.new(:node, name, @context.merge(args))
end
end
def code
Expression.new(:value => @value)
end
def is_nop?(o)
@ast_transformer.is_nop?(o)
end
def absolute_reference(ref)
if ref.nil? || ref.empty? || ref.start_with?('::')
ref
else
"::#{ref}"
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/ast/leaf.rb | lib/puppet/parser/ast/leaf.rb | # frozen_string_literal: true
# The base class for all of the leaves of the parse trees. These
# basically just have types and values. Both of these parameters
# are simple values, not AST objects.
#
class Puppet::Parser::AST::Leaf < Puppet::Parser::AST
attr_accessor :value, :type
# Return our value.
def evaluate(scope)
@value
end
def match(value)
@value == value
end
def to_s
@value.to_s unless @value.nil?
end
def initialize(value: nil, file: nil, line: nil, pos: nil)
@value = value
super(file: file, line: line, pos: pos)
end
end
# Host names, either fully qualified or just the short name, or even a regex
#
class Puppet::Parser::AST::HostName < Puppet::Parser::AST::Leaf
def initialize(value: nil, file: nil, line: nil, pos: nil)
super(value: value, file: file, line: line, pos: pos)
# Note that this is an AST::Regex, not a Regexp
unless @value.is_a?(Regex)
@value = @value.to_s.downcase
if @value =~ /[^-\w.]/
raise Puppet::DevError, _("'%{value}' is not a valid hostname") % { value: @value }
end
end
end
# implementing eql? and hash so that when an HostName is stored
# in a hash it has the same hashing properties as the underlying value
def eql?(value)
@value.eql?(value.is_a?(HostName) ? value.value : value)
end
def hash
@value.hash
end
end
class Puppet::Parser::AST::Regex < Puppet::Parser::AST::Leaf
def initialize(value: nil, file: nil, line: nil, pos: nil)
super(value: value, file: file, line: line, pos: pos)
# transform value from hash options unless it is already a regular expression
@value = Regexp.new(@value) unless @value.is_a?(Regexp)
end
# we're returning self here to wrap the regexp and to be used in places
# where a string would have been used, without modifying any client code.
# For instance, in many places we have the following code snippet:
# val = @val.safeevaluate(@scope)
# if val.match(otherval)
# ...
# end
# this way, we don't have to modify this test specifically for handling
# regexes.
#
def evaluate(scope)
self
end
def match(value)
@value.match(value)
end
def to_s
Puppet::Pops::Types::PRegexpType.regexp_to_s_with_delimiters(@value)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/ast/top_level_construct.rb | lib/puppet/parser/ast/top_level_construct.rb | # frozen_string_literal: true
# The base class for AST nodes representing top level things:
# hostclasses, definitions, and nodes.
class Puppet::Parser::AST::TopLevelConstruct < Puppet::Parser::AST
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/ast/hostclass.rb | lib/puppet/parser/ast/hostclass.rb | # frozen_string_literal: true
require_relative '../../../puppet/parser/ast/top_level_construct'
class Puppet::Parser::AST::Hostclass < Puppet::Parser::AST::TopLevelConstruct
attr_accessor :name, :context
def initialize(name, context = {})
@context = context
@name = name
end
def instantiate(modname)
new_class = Puppet::Resource::Type.new(:hostclass, @name, @context.merge(:module_name => modname))
all_types = [new_class]
if code
code.each do |nested_ast_node|
if nested_ast_node.respond_to? :instantiate
all_types += nested_ast_node.instantiate(modname)
end
end
end
all_types
end
def code
@context[:code]
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/ast/branch.rb | lib/puppet/parser/ast/branch.rb | # frozen_string_literal: true
# The parent class of all AST objects that contain other AST objects.
# Everything but the really simple objects descend from this. It is
# important to note that Branch objects contain other AST objects only --
# if you want to contain values, use a descendant of the AST::Leaf class.
#
# @api private
class Puppet::Parser::AST::Branch < Puppet::Parser::AST
include Enumerable
attr_accessor :pin, :children
def each
@children.each { |child| yield child }
end
def initialize(children: [], **args)
@children = children
super(**args)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/compiler/catalog_validator.rb | lib/puppet/parser/compiler/catalog_validator.rb | # frozen_string_literal: true
# Abstract class for a catalog validator that can be registered with the compiler to run at
# a certain stage.
class Puppet::Parser::Compiler
class CatalogValidator
PRE_FINISH = :pre_finish
FINAL = :final
# Returns true if the validator should run at the given stage. The default
# implementation will only run at stage `FINAL`
#
# @param stage [Symbol] One of the stage constants defined in this class
# @return [Boolean] true if the validator should run at the given stage
#
def self.validation_stage?(stage)
FINAL.equal?(stage)
end
attr_reader :catalog
# @param catalog [Puppet::Resource::Catalog] The catalog to validate
def initialize(catalog)
@catalog = catalog
end
# Validate some aspect of the catalog and raise a `CatalogValidationError` on failure
def validate
end
end
class CatalogValidationError < Puppet::Error
include Puppet::ExternalFileError
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/parser/compiler/catalog_validator/relationship_validator.rb | lib/puppet/parser/compiler/catalog_validator/relationship_validator.rb | # frozen_string_literal: true
class Puppet::Parser::Compiler
# Validator that asserts relationship metaparameters refer to valid resources
class CatalogValidator::RelationshipValidator < CatalogValidator
def validate
catalog.resources.each do |resource|
next unless resource.is_a?(Puppet::Parser::Resource)
next if resource.virtual?
resource.eachparam do |param|
pclass = Puppet::Type.metaparamclass(param.name)
validate_relationship(param) if !pclass.nil? && pclass < Puppet::Type::RelationshipMetaparam
end
end
nil
end
private
def validate_relationship(param)
# the referenced resource must exist
refs = param.value.is_a?(Array) ? param.value.flatten : [param.value]
refs.each do |r|
next if r.nil? || r == :undef
res = r.to_s
begin
found = catalog.resource(res)
rescue ArgumentError => e
# Raise again but with file and line information
raise CatalogValidationError.new(e.message, param.file, param.line)
end
unless found
msg = _("Could not find resource '%{res}' in parameter '%{param}'") % { res: res, param: param.name.to_s }
raise CatalogValidationError.new(msg, param.file, param.line)
end
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/context/trusted_information.rb | lib/puppet/context/trusted_information.rb | # frozen_string_literal: true
require_relative '../../puppet/trusted_external'
# @api private
class Puppet::Context::TrustedInformation
# one of 'remote', 'local', or false, where 'remote' is authenticated via cert,
# 'local' is trusted by virtue of running on the same machine (not a remote
# request), and false is an unauthenticated remote request.
#
# @return [String, Boolean]
attr_reader :authenticated
# The validated certificate name used for the request
#
# @return [String]
attr_reader :certname
# Extra information that comes from the trusted certificate's extensions.
#
# @return [Hash{Object => Object}]
attr_reader :extensions
# The domain name derived from the validated certificate name
#
# @return [String]
attr_reader :domain
# The hostname derived from the validated certificate name
#
# @return [String]
attr_reader :hostname
def initialize(authenticated, certname, extensions, external = {})
@authenticated = authenticated.freeze
@certname = certname.freeze
@extensions = extensions.freeze
if @certname
hostname, domain = @certname.split('.', 2)
else
hostname = nil
domain = nil
end
@hostname = hostname.freeze
@domain = domain.freeze
@external = external.is_a?(Proc) ? external : external.freeze
end
def self.remote(authenticated, node_name, certificate)
external = proc { retrieve_trusted_external(node_name) }
if authenticated
extensions = {}
if certificate.nil?
Puppet.info(_('TrustedInformation expected a certificate, but none was given.'))
else
extensions = certificate.custom_extensions.to_h do |ext|
[ext['oid'].freeze, ext['value'].freeze]
end
end
new('remote', node_name, extensions, external)
else
new(false, nil, {}, external)
end
end
def self.local(node)
# Always trust local data by picking up the available parameters.
client_cert = node ? node.parameters['clientcert'] : nil
external = proc { retrieve_trusted_external(client_cert) }
new('local', client_cert, {}, external)
end
# Additional external facts loaded through `trusted_external_command`.
#
# @return [Hash]
def external
if @external.is_a?(Proc)
@external = @external.call.freeze
end
@external
end
def self.retrieve_trusted_external(certname)
deep_freeze(Puppet::TrustedExternal.retrieve(certname) || {})
end
private_class_method :retrieve_trusted_external
# Deeply freezes the given object. The object and its content must be of the types:
# Array, Hash, Numeric, Boolean, Regexp, NilClass, or String. All other types raises an Error.
# (i.e. if they are assignable to Puppet::Pops::Types::Data type).
def self.deep_freeze(object)
case object
when Array
object.each { |v| deep_freeze(v) }
object.freeze
when Hash
object.each { |k, v| deep_freeze(k); deep_freeze(v) }
object.freeze
when NilClass, Numeric, TrueClass, FalseClass
# do nothing
when String
object.freeze
else
raise Puppet::Error, _("Unsupported data type: '%{klass}'") % { klass: object.class }
end
object
end
private_class_method :deep_freeze
def to_h
{
'authenticated' => authenticated,
'certname' => certname,
'extensions' => extensions,
'hostname' => hostname,
'domain' => domain,
'external' => external,
}.freeze
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/session.rb | lib/puppet/http/session.rb | # frozen_string_literal: true
# The session is the mechanism by which services may be connected to and accessed.
#
# @api public
class Puppet::HTTP::Session
# capabilities for a site
CAP_LOCALES = 'locales'
CAP_JSON = 'json'
# puppet version where locales mount was added
SUPPORTED_LOCALES_MOUNT_AGENT_VERSION = Gem::Version.new("5.3.4")
# puppet version where JSON was enabled by default
SUPPORTED_JSON_DEFAULT = Gem::Version.new("5.0.0")
# Create a new HTTP session. The session is the mechanism by which services
# may be connected to and accessed. Sessions should be created using
# `Puppet::HTTP::Client#create_session`.
#
# @param [Puppet::HTTP::Client] client the container for this session
# @param [Array<Puppet::HTTP::Resolver>] resolvers array of resolver strategies
# to implement.
#
# @api private
def initialize(client, resolvers)
@client = client
@resolvers = resolvers
@resolved_services = {}
@server_versions = {}
end
# If an explicit server and port are specified on the command line or
# configuration file, this method always returns a Service with that host and
# port. Otherwise, we walk the list of resolvers in priority order:
# - DNS SRV
# - Server List
# - Puppet server/port settings
# If a given resolver fails to connect, it tries the next available resolver
# until a successful connection is found and returned. The successful service
# is cached and returned if `route_to` is called again.
#
# @param [Symbol] name the service to resolve
# @param [URI] url optional explicit url to use, if it is already known
# @param [Puppet::SSL::SSLContext] ssl_context ssl context to be
# used for connections
#
# @return [Puppet::HTTP::Service] the resolved service
#
# @api public
def route_to(name, url: nil, ssl_context: nil)
raise ArgumentError, "Unknown service #{name}" unless Puppet::HTTP::Service.valid_name?(name)
# short circuit if explicit URL host & port given
if url && !url.host.nil? && !url.host.empty?
service = Puppet::HTTP::Service.create_service(@client, self, name, url.host, url.port)
service.connect(ssl_context: ssl_context)
return service
end
cached = @resolved_services[name]
return cached if cached
canceled = false
canceled_handler = ->(cancel) { canceled = cancel }
@resolvers.each do |resolver|
Puppet.debug("Resolving service '#{name}' using #{resolver.class}")
service = resolver.resolve(self, name, ssl_context: ssl_context, canceled_handler: canceled_handler)
if service
@resolved_services[name] = service
Puppet.debug("Resolved service '#{name}' to #{service.url}")
return service
elsif canceled
break
end
end
raise Puppet::HTTP::RouteError, "No more routes to #{name}"
end
# Collect per-site server versions. This will allow us to modify future
# requests based on the version of puppetserver we are talking to.
#
# @param [Puppet::HTTP::Response] response the request response containing headers
#
# @api private
def process_response(response)
version = response[Puppet::HTTP::HEADER_PUPPET_VERSION]
if version
site = Puppet::HTTP::Site.from_uri(response.url)
@server_versions[site] = version
end
end
# Determine if a session supports a capability. Depending on the server version
# we are talking to, we know certain features are available or not. These
# specifications are defined here so we can modify our requests appropriately.
#
# @param [Symbol] name name of the service to check
# @param [String] capability the capability, ie `locales` or `json`
#
# @return [Boolean]
#
# @api public
def supports?(name, capability)
raise ArgumentError, "Unknown service #{name}" unless Puppet::HTTP::Service.valid_name?(name)
service = @resolved_services[name]
return false unless service
site = Puppet::HTTP::Site.from_uri(service.url)
server_version = @server_versions[site]
case capability
when CAP_LOCALES
!server_version.nil? && Gem::Version.new(server_version) >= SUPPORTED_LOCALES_MOUNT_AGENT_VERSION
when CAP_JSON
server_version.nil? || Gem::Version.new(server_version) >= SUPPORTED_JSON_DEFAULT
else
false
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/errors.rb | lib/puppet/http/errors.rb | # frozen_string_literal: true
module Puppet::HTTP
# A base class for puppet http errors
# @api public
class HTTPError < Puppet::Error; end
# A connection error such as if the server refuses the connection.
# @api public
class ConnectionError < HTTPError; end
# A failure to route to the server such as if the `server_list` is exhausted.
# @api public
class RouteError < HTTPError; end
# An HTTP protocol error, such as the server's response missing a required header.
# @api public
class ProtocolError < HTTPError; end
# An error serializing or deserializing an object via REST.
# @api public
class SerializationError < HTTPError; end
# An error due to an unsuccessful HTTP response, such as HTTP 500.
# @api public
class ResponseError < HTTPError
attr_reader :response
def initialize(response)
super(response.reason)
@response = response
end
end
# An error if asked to follow too many redirects (such as HTTP 301).
# @api public
class TooManyRedirects < HTTPError
def initialize(addr)
super(_("Too many HTTP redirections for %{addr}") % { addr: addr })
end
end
# An error if asked to retry (such as HTTP 503) too many times.
# @api public
class TooManyRetryAfters < HTTPError
def initialize(addr)
super(_("Too many HTTP retries for %{addr}") % { addr: addr })
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/pool.rb | lib/puppet/http/pool.rb | # frozen_string_literal: true
# A pool for persistent `Net::HTTP` connections. Connections are
# stored in the pool indexed by their {Site}.
# Connections are borrowed from the pool, yielded to the caller, and
# released back into the pool. If a connection is expired, it will be
# closed either when a connection to that site is requested, or when
# the pool is closed. The pool can store multiple connections to the
# same site, and will be reused in MRU order.
#
# @api private
class Puppet::HTTP::Pool
attr_reader :factory, :keepalive_timeout
def initialize(keepalive_timeout)
@pool = {}
@factory = Puppet::HTTP::Factory.new
@keepalive_timeout = keepalive_timeout
end
def with_connection(site, verifier, &block)
reuse = true
http = borrow(site, verifier)
begin
if http.use_ssl? && http.verify_mode != OpenSSL::SSL::VERIFY_PEER
reuse = false
end
yield http
rescue => detail
reuse = false
raise detail
ensure
if reuse && http.started?
release(site, verifier, http)
else
close_connection(site, http)
end
end
end
def close
@pool.each_pair do |site, entries|
entries.each do |entry|
close_connection(site, entry.connection)
end
end
@pool.clear
end
# @api private
def pool
@pool
end
# Start a persistent connection
#
# @api private
def start(site, verifier, http)
Puppet.debug("Starting connection for #{site}")
if site.use_ssl?
verifier.setup_connection(http)
begin
http.start
print_ssl_info(http) if Puppet::Util::Log.sendlevel?(:debug)
rescue OpenSSL::SSL::SSLError => error
verifier.handle_connection_error(http, error)
end
else
http.start
end
end
# Safely close a persistent connection.
# Don't try to close a connection that's already closed.
#
# @api private
def close_connection(site, http)
return false unless http.started?
Puppet.debug("Closing connection for #{site}")
http.finish
true
rescue => detail
Puppet.log_exception(detail, _("Failed to close connection for %{site}: %{detail}") % { site: site, detail: detail })
nil
end
# Borrow and take ownership of a persistent connection. If a new
# connection is created, it will be started prior to being returned.
#
# @api private
def borrow(site, verifier)
@pool[site] = active_entries(site)
index = @pool[site].index do |entry|
(verifier.nil? && entry.verifier.nil?) ||
(!verifier.nil? && verifier.reusable?(entry.verifier))
end
entry = index ? @pool[site].delete_at(index) : nil
if entry
@pool.delete(site) if @pool[site].empty?
Puppet.debug("Using cached connection for #{site}")
entry.connection
else
http = @factory.create_connection(site)
start(site, verifier, http)
setsockopts(http.instance_variable_get(:@socket))
http
end
end
# Set useful socket option(s) which lack from default settings in Net:HTTP
#
# @api private
def setsockopts(netio)
return unless netio
socket = netio.io
socket.setsockopt(Socket::SOL_SOCKET, Socket::SO_KEEPALIVE, true)
end
# Release a connection back into the pool.
#
# @api private
def release(site, verifier, http)
expiration = Time.now + @keepalive_timeout
entry = Puppet::HTTP::PoolEntry.new(http, verifier, expiration)
Puppet.debug("Caching connection for #{site}")
entries = @pool[site]
if entries
entries.unshift(entry)
else
@pool[site] = [entry]
end
end
# Returns an Array of entries whose connections are not expired.
#
# @api private
def active_entries(site)
now = Time.now
entries = @pool[site] || []
entries.select do |entry|
if entry.expired?(now)
close_connection(site, entry.connection)
false
else
true
end
end
end
private
def print_ssl_info(http)
buffered_io = http.instance_variable_get(:@socket)
return unless buffered_io
socket = buffered_io.io
return unless socket
cipher = if Puppet::Util::Platform.jruby?
socket.cipher
else
socket.cipher.first
end
Puppet.debug("Using #{socket.ssl_version} with cipher #{cipher}")
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/response_converter.rb | lib/puppet/http/response_converter.rb | # frozen_string_literal: true
module Puppet::HTTP::ResponseConverter
module_function
# Borrowed from puppetserver, see https://github.com/puppetlabs/puppetserver/commit/a1ebeaaa5af590003ccd23c89f808ba4f0c89609
def to_ruby_response(response)
str_code = response.code.to_s
# Copied from Net::HTTPResponse because it is private there.
clazz = Net::HTTPResponse::CODE_TO_OBJ[str_code] or
Net::HTTPResponse::CODE_CLASS_TO_OBJ[str_code[0, 1]] or
Net::HTTPUnknownResponse
result = clazz.new(nil, str_code, nil)
result.body = response.body
# This is nasty, nasty. But apparently there is no way to create
# an instance of Net::HttpResponse from outside of the library and have
# the body be readable, unless you do stupid things like this.
result.instance_variable_set(:@read, true)
response.each_header do |k, v|
result[k] = v
end
result
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/proxy.rb | lib/puppet/http/proxy.rb | # frozen_string_literal: true
require 'uri'
require_relative '../../puppet/ssl/openssl_loader'
module Puppet::HTTP::Proxy
def self.proxy(uri)
if http_proxy_host && !no_proxy?(uri)
Net::HTTP.new(uri.host, uri.port, http_proxy_host, http_proxy_port, http_proxy_user, http_proxy_password)
else
http = Net::HTTP.new(uri.host, uri.port, nil, nil, nil, nil)
# Net::HTTP defaults the proxy port even though we said not to
# use one. Set it to nil so caller is not surprised
http.proxy_port = nil
http
end
end
def self.http_proxy_env
# Returns a URI object if proxy is set, or nil
proxy_env = ENV.fetch("http_proxy", nil) || ENV.fetch("HTTP_PROXY", nil)
begin
return URI.parse(proxy_env) if proxy_env
rescue URI::InvalidURIError
return nil
end
nil
end
# The documentation around the format of the no_proxy variable seems
# inconsistent. Some suggests the use of the * as a way of matching any
# hosts under a domain, e.g.:
# *.example.com
# Other documentation suggests that just a leading '.' indicates a domain
# level exclusion, e.g.:
# .example.com
# We'll accommodate both here.
def self.no_proxy?(dest)
no_proxy = self.no_proxy
unless no_proxy
return false
end
unless dest.is_a? URI
begin
dest = URI.parse(dest)
rescue URI::InvalidURIError
return false
end
end
no_proxy.split(/\s*,\s*/).each do |d|
host, port = d.split(':')
host = Regexp.escape(host).gsub('\*', '.*')
# If this no_proxy entry specifies a port, we want to match it against
# the destination port. Otherwise just match hosts.
if port
no_proxy_regex = /#{host}:#{port}$/
dest_string = "#{dest.host}:#{dest.port}"
else
no_proxy_regex = /#{host}$/
dest_string = dest.host.to_s
end
if no_proxy_regex.match(dest_string)
return true
end
end
false
end
def self.http_proxy_host
env = http_proxy_env
if env and env.host
return env.host
end
if Puppet.settings[:http_proxy_host] == 'none'
return nil
end
Puppet.settings[:http_proxy_host]
end
def self.http_proxy_port
env = http_proxy_env
if env and env.port
return env.port
end
Puppet.settings[:http_proxy_port]
end
def self.http_proxy_user
env = http_proxy_env
if env and env.user
return env.user
end
if Puppet.settings[:http_proxy_user] == 'none'
return nil
end
Puppet.settings[:http_proxy_user]
end
def self.http_proxy_password
env = http_proxy_env
if env and env.password
return env.password
end
if Puppet.settings[:http_proxy_user] == 'none' or Puppet.settings[:http_proxy_password] == 'none'
return nil
end
Puppet.settings[:http_proxy_password]
end
def self.no_proxy
no_proxy_env = ENV.fetch("no_proxy", nil) || ENV.fetch("NO_PROXY", nil)
if no_proxy_env
return no_proxy_env
end
if Puppet.settings[:no_proxy] == 'none'
return nil
end
Puppet.settings[:no_proxy]
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/response.rb | lib/puppet/http/response.rb | # frozen_string_literal: true
# Represents the response returned from the server from an HTTP request.
#
# @api abstract
# @api public
class Puppet::HTTP::Response
# @return [URI] the response url
attr_reader :url
# Create a response associated with the URL.
#
# @param [URI] url
# @param [Integer] HTTP status
# @param [String] HTTP reason
def initialize(url, code, reason)
@url = url
@code = code
@reason = reason
end
# Return the response code.
#
# @return [Integer] Response code for the request
#
# @api public
def code
@code
end
# Return the response message.
#
# @return [String] Response message for the request
#
# @api public
def reason
@reason
end
# Returns the entire response body. Can be used instead of
# `Puppet::HTTP::Response.read_body`, but both methods cannot be used for the
# same response.
#
# @return [String] Response body for the request
#
# @api public
def body
raise NotImplementedError
end
# Streams the response body to the caller in chunks. Can be used instead of
# `Puppet::HTTP::Response.body`, but both methods cannot be used for the same
# response.
#
# @yield [String] Streams the response body in chunks
#
# @raise [ArgumentError] raise if a block is not given
#
# @api public
def read_body(&block)
raise NotImplementedError
end
# Check if the request received a response of success (HTTP 2xx).
#
# @return [Boolean] Returns true if the response indicates success
#
# @api public
def success?
200 <= @code && @code < 300
end
# Get a header case-insensitively.
#
# @param [String] name The header name
# @return [String] The header value
#
# @api public
def [](name)
raise NotImplementedError
end
# Yield each header name and value. Returns an enumerator if no block is given.
#
# @yieldparam [String] header name
# @yieldparam [String] header value
#
# @api public
def each_header(&block)
raise NotImplementedError
end
# Ensure the response body is fully read so that the server is not blocked
# waiting for us to read data from the socket. Also if the caller streamed
# the response, but didn't read the data, we need a way to drain the socket
# before adding the connection back to the connection pool, otherwise the
# unread response data would "leak" into the next HTTP request/response.
#
# @api public
def drain
body
true
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/pool_entry.rb | lib/puppet/http/pool_entry.rb | # frozen_string_literal: true
# An entry in the peristent HTTP pool that references the connection and
# an expiration time for the connection.
#
# @api private
class Puppet::HTTP::PoolEntry
attr_reader :connection, :verifier
def initialize(connection, verifier, expiration_time)
@connection = connection
@verifier = verifier
@expiration_time = expiration_time
end
def expired?(now)
@expiration_time <= now
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/response_net_http.rb | lib/puppet/http/response_net_http.rb | # frozen_string_literal: true
# Adapts Net::HTTPResponse to Puppet::HTTP::Response
#
# @api public
class Puppet::HTTP::ResponseNetHTTP < Puppet::HTTP::Response
# Create a response associated with the URL.
#
# @param [URI] url
# @param [Net::HTTPResponse] nethttp The response
def initialize(url, nethttp)
super(url, nethttp.code.to_i, nethttp.message)
@nethttp = nethttp
end
# (see Puppet::HTTP::Response#body)
def body
@nethttp.body
end
# (see Puppet::HTTP::Response#read_body)
def read_body(&block)
raise ArgumentError, "A block is required" unless block_given?
@nethttp.read_body(&block)
end
# (see Puppet::HTTP::Response#success?)
def success?
@nethttp.is_a?(Net::HTTPSuccess)
end
# (see Puppet::HTTP::Response#[])
def [](name)
@nethttp[name]
end
# (see Puppet::HTTP::Response#each_header)
def each_header(&block)
@nethttp.each_header(&block)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/resolver.rb | lib/puppet/http/resolver.rb | # frozen_string_literal: true
# Resolver base class. Each resolver represents a different strategy for
# resolving a service name into a list of candidate servers and ports.
#
# @abstract Subclass and override {#resolve} to create a new resolver.
# @api public
class Puppet::HTTP::Resolver
#
# Create a new resolver.
#
# @param [Puppet::HTTP::Client] client
def initialize(client)
@client = client
end
# Return a working server/port for the resolver. This is the base
# implementation and is meant to be a placeholder.
#
# @param [Puppet::HTTP::Session] session
# @param [Symbol] name the service to resolve
# @param [Puppet::SSL::SSLContext] ssl_context (nil) optional ssl context to
# use when creating a connection
# @param [Proc] canceled_handler (nil) optional callback allowing a resolver
# to cancel resolution.
#
# @raise [NotImplementedError] this base class is not implemented
#
# @api public
def resolve(session, name, ssl_context: nil, canceled_handler: nil)
raise NotImplementedError
end
# Check a given connection to establish if it can be relied on for future use.
#
# @param [Puppet::HTTP::Session] session
# @param [Puppet::HTTP::Service] service
# @param [Puppet::SSL::SSLContext] ssl_context
#
# @return [Boolean] Returns true if a connection is successful, false otherwise
#
# @api public
def check_connection?(session, service, ssl_context: nil)
service.connect(ssl_context: ssl_context)
true
rescue Puppet::HTTP::ConnectionError => e
Puppet.log_exception(e, "Connection to #{service.url} failed, trying next route: #{e.message}")
false
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/dns.rb | lib/puppet/http/dns.rb | # frozen_string_literal: true
require 'resolv'
module Puppet::HTTP
class DNS
class CacheEntry
attr_reader :records, :ttl, :resolution_time
def initialize(records)
@records = records
@resolution_time = Time.now
@ttl = choose_lowest_ttl(records)
end
def choose_lowest_ttl(records)
ttl = records.first.ttl
records.each do |rec|
if rec.ttl < ttl
ttl = rec.ttl
end
end
ttl
end
end
def initialize(resolver = Resolv::DNS.new)
@resolver = resolver
# Stores DNS records per service, along with their TTL
# and the time at which they were resolved, for cache
# eviction.
@record_cache = {}
end
# Iterate through the list of records for this service
# and yield each server and port pair. Records are only fetched
# via DNS query the first time and cached for the duration of their
# service's TTL thereafter.
# @param [String] domain the domain to search for
# @param [Symbol] service_name the key of the service we are querying
# @yields [String, Integer] server and port of selected record
def each_srv_record(domain, service_name = :puppet, &block)
if domain.nil? or domain.empty?
Puppet.debug "Domain not known; skipping SRV lookup"
return
end
Puppet.debug "Searching for SRV records for domain: #{domain}"
case service_name
when :puppet then service = '_x-puppet'
when :file then service = '_x-puppet-fileserver'
else service = "_x-puppet-#{service_name}"
end
record_name = "#{service}._tcp.#{domain}"
if @record_cache.has_key?(service_name) && !expired?(service_name)
records = @record_cache[service_name].records
Puppet.debug "Using cached record for #{record_name}"
else
records = @resolver.getresources(record_name, Resolv::DNS::Resource::IN::SRV)
if records.size > 0
@record_cache[service_name] = CacheEntry.new(records)
end
Puppet.debug "Found #{records.size} SRV records for: #{record_name}"
end
if records.size == 0 && service_name != :puppet
# Try the generic :puppet service if no SRV records were found
# for the specific service.
each_srv_record(domain, :puppet, &block)
else
each_priority(records) do |recs|
while next_rr = recs.delete(find_weighted_server(recs)) # rubocop:disable Lint/AssignmentInCondition
Puppet.debug "Yielding next server of #{next_rr.target}:#{next_rr.port}"
yield next_rr.target.to_s, next_rr.port
end
end
end
end
# Given a list of records of the same priority, chooses a random one
# from among them, favoring those with higher weights.
# @param [[Resolv::DNS::Resource::IN::SRV]] records a list of records
# of the same priority
# @return [Resolv::DNS::Resource::IN:SRV] the chosen record
def find_weighted_server(records)
return nil if records.nil? || records.empty?
return records.first if records.size == 1
# Calculate the sum of all weights in the list of resource records,
# This is used to then select hosts until the weight exceeds what
# random number we selected. For example, if we have weights of 1 8 and 3:
#
# |-|--------|---|
# ^
# We generate a random number 5, and iterate through the records, adding
# the current record's weight to the accumulator until the weight of the
# current record plus previous records is greater than the random number.
total_weight = records.inject(0) { |sum, record|
sum + weight(record)
}
current_weight = 0
chosen_weight = 1 + Kernel.rand(total_weight)
records.each do |record|
current_weight += weight(record)
return record if current_weight >= chosen_weight
end
end
def weight(record)
record.weight == 0 ? 1 : record.weight * 10
end
# Returns TTL for the cached records for this service.
# @param [String] service_name the service whose TTL we want
# @return [Integer] the TTL for this service, in seconds
def ttl(service_name)
@record_cache[service_name].ttl
end
# Checks if the cached entry for the given service has expired.
# @param [String] service_name the name of the service to check
# @return [Boolean] true if the entry has expired, false otherwise.
# Always returns true if the record had no TTL.
def expired?(service_name)
entry = @record_cache[service_name]
if entry
Time.now > (entry.resolution_time + entry.ttl)
else
true
end
end
private
# Groups the records by their priority and yields the groups
# in order of highest to lowest priority (lowest to highest numbers),
# one at a time.
# { 1 => [records], 2 => [records], etc. }
#
# @param [[Resolv::DNS::Resource::IN::SRV]] records the list of
# records for a given service
# @yields [[Resolv::DNS::Resource::IN::SRV]] a group of records of
# the same priority
def each_priority(records)
pri_hash = records.each_with_object({}) do |element, groups|
groups[element.priority] ||= []
groups[element.priority] << element
end
pri_hash.keys.sort.each do |key|
yield pri_hash[key]
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/client.rb | lib/puppet/http/client.rb | # frozen_string_literal: true
# The HTTP client provides methods for making `GET`, `POST`, etc requests to
# HTTP(S) servers. It also provides methods for resolving Puppetserver REST
# service endpoints using SRV records and settings (such as `server_list`,
# `server`, `ca_server`, etc). Once a service endpoint has been resolved, there
# are methods for making REST requests (such as getting a node, sending facts,
# etc).
#
# The client uses persistent HTTP connections by default unless the `Connection:
# close` header is specified and supports streaming response bodies.
#
# By default the client only trusts the Puppet CA for HTTPS connections. However,
# if the `include_system_store` request option is set to true, then Puppet will
# trust certificates in the puppet-agent CA bundle.
#
# @example To access the HTTP client:
# client = Puppet.runtime[:http]
#
# @example To make an HTTP GET request:
# response = client.get(URI("http://www.example.com"))
#
# @example To make an HTTPS GET request, trusting the puppet CA and certs in Puppet's CA bundle:
# response = client.get(URI("https://www.example.com"), options: { include_system_store: true })
#
# @example To use a URL containing special characters, such as spaces:
# response = client.get(URI(Puppet::Util.uri_encode("https://www.example.com/path to file")))
#
# @example To pass query parameters:
# response = client.get(URI("https://www.example.com"), query: {'q' => 'puppet'})
#
# @example To pass custom headers:
# response = client.get(URI("https://www.example.com"), headers: {'Accept-Content' => 'application/json'})
#
# @example To check if the response is successful (2xx):
# response = client.get(URI("http://www.example.com"))
# puts response.success?
#
# @example To get the response code and reason:
# response = client.get(URI("http://www.example.com"))
# unless response.success?
# puts "HTTP #{response.code} #{response.reason}"
# end
#
# @example To read response headers:
# response = client.get(URI("http://www.example.com"))
# puts response['Content-Type']
#
# @example To stream the response body:
# client.get(URI("http://www.example.com")) do |response|
# if response.success?
# response.read_body do |data|
# puts data
# end
# end
# end
#
# @example To handle exceptions:
# begin
# client.get(URI("https://www.example.com"))
# rescue Puppet::HTTP::ResponseError => e
# puts "HTTP #{e.response.code} #{e.response.reason}"
# rescue Puppet::HTTP::ConnectionError => e
# puts "Connection error #{e.message}"
# rescue Puppet::SSL::SSLError => e
# puts "SSL error #{e.message}"
# rescue Puppet::HTTP::HTTPError => e
# puts "General HTTP error #{e.message}"
# end
#
# @example To route to the `:puppet` service:
# session = client.create_session
# service = session.route_to(:puppet)
#
# @example To make a node request:
# node = service.get_node(Puppet[:certname], environment: 'production')
#
# @example To submit facts:
# facts = Puppet::Indirection::Facts.indirection.find(Puppet[:certname])
# service.put_facts(Puppet[:certname], environment: 'production', facts: facts)
#
# @example To submit a report to the `:report` service:
# report = Puppet::Transaction::Report.new
# service = session.route_to(:report)
# service.put_report(Puppet[:certname], report, environment: 'production')
#
# @api public
class Puppet::HTTP::Client
attr_reader :pool
# Create a new http client instance. Use `Puppet.runtime[:http]` to get
# the current client instead of creating an instance of this class.
#
# @param [Puppet::HTTP::Pool] pool pool of persistent Net::HTTP
# connections
# @param [Puppet::SSL::SSLContext] ssl_context ssl context to be used for
# connections
# @param [Puppet::SSL::SSLContext] system_ssl_context the system ssl context
# used if :include_system_store is set to true
# @param [Integer] redirect_limit default number of HTTP redirections to allow
# in a given request. Can also be specified per-request.
# @param [Integer] retry_limit number of HTTP retries allowed in a given
# request
#
def initialize(pool: Puppet::HTTP::Pool.new(Puppet[:http_keepalive_timeout]), ssl_context: nil, system_ssl_context: nil, redirect_limit: 10, retry_limit: 100)
@pool = pool
@default_headers = {
'X-Puppet-Version' => Puppet.version,
'User-Agent' => Puppet[:http_user_agent],
}.freeze
@default_ssl_context = ssl_context
@default_system_ssl_context = system_ssl_context
@default_redirect_limit = redirect_limit
@retry_after_handler = Puppet::HTTP::RetryAfterHandler.new(retry_limit, Puppet[:runinterval])
end
# Create a new HTTP session. A session is the object through which services
# may be connected to and accessed.
#
# @return [Puppet::HTTP::Session] the newly created HTTP session
#
# @api public
def create_session
Puppet::HTTP::Session.new(self, build_resolvers)
end
# Open a connection to the given URI. It is typically not necessary to call
# this method as the client will create connections as needed when a request
# is made.
#
# @param [URI] uri the connection destination
# @param [Hash] options
# @option options [Puppet::SSL::SSLContext] :ssl_context (nil) ssl context to
# be used for connections
# @option options [Boolean] :include_system_store (false) if we should include
# the system store for connection
def connect(uri, options: {}, &block)
start = Time.now
verifier = nil
connected = false
site = Puppet::HTTP::Site.from_uri(uri)
if site.use_ssl?
ssl_context = options.fetch(:ssl_context, nil)
include_system_store = options.fetch(:include_system_store, false)
ctx = resolve_ssl_context(ssl_context, include_system_store)
verifier = Puppet::SSL::Verifier.new(site.host, ctx)
end
@pool.with_connection(site, verifier) do |http|
connected = true
if block_given?
yield http
end
end
rescue Net::OpenTimeout => e
raise_error(_("Request to %{uri} timed out connect operation after %{elapsed} seconds") % { uri: uri, elapsed: elapsed(start) }, e, connected)
rescue Net::ReadTimeout => e
raise_error(_("Request to %{uri} timed out read operation after %{elapsed} seconds") % { uri: uri, elapsed: elapsed(start) }, e, connected)
rescue EOFError => e
raise_error(_("Request to %{uri} interrupted after %{elapsed} seconds") % { uri: uri, elapsed: elapsed(start) }, e, connected)
rescue Puppet::SSL::SSLError
raise
rescue Puppet::HTTP::HTTPError
raise
rescue => e
raise_error(_("Request to %{uri} failed after %{elapsed} seconds: %{message}") %
{ uri: uri, elapsed: elapsed(start), message: e.message }, e, connected)
end
# These options apply to all HTTP request methods
#
# @!macro [new] request_options
# @param [Hash] options HTTP request options. Options not recognized by the
# HTTP implementation will be ignored.
# @option options [Puppet::SSL::SSLContext] :ssl_context (nil) ssl context to
# be used for connections
# @option options [Boolean] :include_system_store (false) if we should include
# the system store for connection
# @option options [Integer] :redirect_limit (10) The maximum number of HTTP
# redirections to allow for this request.
# @option options [Hash] :basic_auth A map of `:username` => `String` and
# `:password` => `String`
# @option options [String] :metric_id The metric id used to track metrics
# on requests.
# Submits a GET HTTP request to the given url
#
# @param [URI] url the location to submit the http request
# @param [Hash] headers merged with the default headers defined by the client
# @param [Hash] params encoded and set as the url query
# @!macro request_options
#
# @yield [Puppet::HTTP::Response] if a block is given yields the response
#
# @return [Puppet::HTTP::Response] the response
#
# @api public
def get(url, headers: {}, params: {}, options: {}, &block)
url = encode_query(url, params)
request = Net::HTTP::Get.new(url, @default_headers.merge(headers))
execute_streaming(request, options: options, &block)
end
# Submits a HEAD HTTP request to the given url
#
# @param [URI] url the location to submit the http request
# @param [Hash] headers merged with the default headers defined by the client
# @param [Hash] params encoded and set as the url query
# @!macro request_options
#
# @return [Puppet::HTTP::Response] the response
#
# @api public
def head(url, headers: {}, params: {}, options: {})
url = encode_query(url, params)
request = Net::HTTP::Head.new(url, @default_headers.merge(headers))
execute_streaming(request, options: options)
end
# Submits a PUT HTTP request to the given url
#
# @param [URI] url the location to submit the http request
# @param [String] body the body of the PUT request
# @param [Hash] headers merged with the default headers defined by the client. The
# `Content-Type` header is required and should correspond to the type of data passed
# as the `body` argument.
# @param [Hash] params encoded and set as the url query
# @!macro request_options
#
# @return [Puppet::HTTP::Response] the response
#
# @api public
def put(url, body, headers: {}, params: {}, options: {})
raise ArgumentError, "'put' requires a string 'body' argument" unless body.is_a?(String)
url = encode_query(url, params)
request = Net::HTTP::Put.new(url, @default_headers.merge(headers))
request.body = body
request.content_length = body.bytesize
raise ArgumentError, "'put' requires a 'content-type' header" unless request['Content-Type']
execute_streaming(request, options: options)
end
# Submits a POST HTTP request to the given url
#
# @param [URI] url the location to submit the http request
# @param [String] body the body of the POST request
# @param [Hash] headers merged with the default headers defined by the client. The
# `Content-Type` header is required and should correspond to the type of data passed
# as the `body` argument.
# @param [Hash] params encoded and set as the url query
# @!macro request_options
#
# @yield [Puppet::HTTP::Response] if a block is given yields the response
#
# @return [Puppet::HTTP::Response] the response
#
# @api public
def post(url, body, headers: {}, params: {}, options: {}, &block)
raise ArgumentError, "'post' requires a string 'body' argument" unless body.is_a?(String)
url = encode_query(url, params)
request = Net::HTTP::Post.new(url, @default_headers.merge(headers))
request.body = body
request.content_length = body.bytesize
raise ArgumentError, "'post' requires a 'content-type' header" unless request['Content-Type']
execute_streaming(request, options: options, &block)
end
# Submits a DELETE HTTP request to the given url.
#
# @param [URI] url the location to submit the http request
# @param [Hash] headers merged with the default headers defined by the client
# @param [Hash] params encoded and set as the url query
# @!macro request_options
#
# @return [Puppet::HTTP::Response] the response
#
# @api public
def delete(url, headers: {}, params: {}, options: {})
url = encode_query(url, params)
request = Net::HTTP::Delete.new(url, @default_headers.merge(headers))
execute_streaming(request, options: options)
end
# Close persistent connections in the pool.
#
# @return [void]
#
# @api public
def close
@pool.close
@default_ssl_context = nil
@default_system_ssl_context = nil
end
def default_ssl_context
cert = Puppet::X509::CertProvider.new
password = cert.load_private_key_password
ssl = Puppet::SSL::SSLProvider.new
ctx = ssl.load_context(certname: Puppet[:certname], password: password)
ssl.print(ctx)
ctx
rescue => e
# TRANSLATORS: `message` is an already translated string of why SSL failed to initialize
Puppet.log_exception(e, _("Failed to initialize SSL: %{message}") % { message: e.message })
# TRANSLATORS: `puppet agent -t` is a command and should not be translated
Puppet.err(_("Run `puppet agent -t`"))
raise e
end
protected
def encode_query(url, params)
return url if params.empty?
url = url.dup
url.query = encode_params(params)
url
end
private
# Connect or borrow a connection from the pool to the host and port associated
# with the request's URL. Then execute the HTTP request, retrying and
# following redirects as needed, and return the HTTP response. The response
# body will always be fully drained/consumed when this method returns.
#
# If a block is provided, then the response will be yielded to the caller,
# allowing the response body to be streamed.
#
# If the request/response did not result in an exception and the caller did
# not ask for the connection to be closed (via Connection: close), then the
# connection will be returned to the pool.
#
# @yieldparam [Puppet::HTTP::Response] response The final response, after
# following redirects and retrying
# @return [Puppet::HTTP::Response]
def execute_streaming(request, options: {}, &block)
redirector = Puppet::HTTP::Redirector.new(options.fetch(:redirect_limit, @default_redirect_limit))
basic_auth = options.fetch(:basic_auth, nil)
unless basic_auth
if request.uri.user && request.uri.password
basic_auth = { user: request.uri.user, password: request.uri.password }
end
end
redirects = 0
retries = 0
response = nil
done = false
until done
connect(request.uri, options: options) do |http|
apply_auth(request, basic_auth) if redirects.zero?
# don't call return within the `request` block
close_and_sleep = nil
http.request(request) do |nethttp|
response = Puppet::HTTP::ResponseNetHTTP.new(request.uri, nethttp)
begin
Puppet.debug("HTTP #{request.method.upcase} #{request.uri} returned #{response.code} #{response.reason}")
if redirector.redirect?(request, response)
request = redirector.redirect_to(request, response, redirects)
redirects += 1
next
elsif @retry_after_handler.retry_after?(request, response)
interval = @retry_after_handler.retry_after_interval(request, response, retries)
retries += 1
if interval
close_and_sleep = proc do
if http.started?
Puppet.debug("Closing connection for #{Puppet::HTTP::Site.from_uri(request.uri)}")
http.finish
end
Puppet.warning(_("Sleeping for %{interval} seconds before retrying the request") % { interval: interval })
::Kernel.sleep(interval)
end
next
end
end
if block_given?
yield response
else
response.body
end
ensure
# we need to make sure the response body is fully consumed before
# the connection is put back in the pool, otherwise the response
# for one request could leak into a future response.
response.drain
end
done = true
end
ensure
# If a server responded with a retry, make sure the connection is closed and then
# sleep the specified time.
close_and_sleep.call if close_and_sleep
end
end
response
end
def expand_into_parameters(data)
data.inject([]) do |params, key_value|
key, value = key_value
expanded_value = case value
when Array
value.collect { |val| [key, val] }
else
[key_value]
end
params.concat(expand_primitive_types_into_parameters(expanded_value))
end
end
def expand_primitive_types_into_parameters(data)
data.inject([]) do |params, key_value|
key, value = key_value
case value
when nil
params
when true, false, String, Symbol, Integer, Float
params << [key, value]
else
raise Puppet::HTTP::SerializationError, _("HTTP REST queries cannot handle values of type '%{klass}'") % { klass: value.class }
end
end
end
def encode_params(params)
params = expand_into_parameters(params)
params.map do |key, value|
"#{key}=#{Puppet::Util.uri_query_encode(value.to_s)}"
end.join('&')
end
def elapsed(start)
(Time.now - start).to_f.round(3)
end
def raise_error(message, cause, connected)
if connected
raise Puppet::HTTP::HTTPError.new(message, cause)
else
raise Puppet::HTTP::ConnectionError.new(message, cause)
end
end
def resolve_ssl_context(ssl_context, include_system_store)
if ssl_context
raise Puppet::HTTP::HTTPError, "The ssl_context and include_system_store parameters are mutually exclusive" if include_system_store
ssl_context
elsif include_system_store
system_ssl_context
else
@default_ssl_context || Puppet.lookup(:ssl_context)
end
end
def system_ssl_context
return @default_system_ssl_context if @default_system_ssl_context
cert_provider = Puppet::X509::CertProvider.new
cacerts = cert_provider.load_cacerts || []
ssl = Puppet::SSL::SSLProvider.new
@default_system_ssl_context = ssl.create_system_context(cacerts: cacerts, include_client_cert: true)
ssl.print(@default_system_ssl_context)
@default_system_ssl_context
end
def apply_auth(request, basic_auth)
if basic_auth
request.basic_auth(basic_auth[:user], basic_auth[:password])
end
end
def build_resolvers
resolvers = []
if Puppet[:use_srv_records]
resolvers << Puppet::HTTP::Resolver::SRV.new(self, domain: Puppet[:srv_domain])
end
server_list_setting = Puppet.settings.setting(:server_list)
if server_list_setting.value && !server_list_setting.value.empty?
# use server list to resolve all services
services = Puppet::HTTP::Service::SERVICE_NAMES.dup
# except if it's been explicitly set
if Puppet.settings.set_by_config?(:ca_server)
services.delete(:ca)
end
if Puppet.settings.set_by_config?(:report_server)
services.delete(:report)
end
resolvers << Puppet::HTTP::Resolver::ServerList.new(self, server_list_setting: server_list_setting, default_port: Puppet[:serverport], services: services)
end
resolvers << Puppet::HTTP::Resolver::Settings.new(self)
resolvers.freeze
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/external_client.rb | lib/puppet/http/external_client.rb | # frozen_string_literal: true
# Adapts an external http_client_class to the HTTP client API. The former
# is typically registered by puppetserver and only implements a subset of
# the Puppet::Network::HTTP::Connection methods. As a result, only the
# `get` and `post` methods are supported. Calling `delete`, etc will
# raise a NotImplementedError.
#
# @api private
class Puppet::HTTP::ExternalClient < Puppet::HTTP::Client
# Create an external http client.
#
# @param [Class] http_client_class The class to create to handle the request
def initialize(http_client_class)
@http_client_class = http_client_class
end
# (see Puppet::HTTP::Client#get)
# @api private
def get(url, headers: {}, params: {}, options: {}, &block)
url = encode_query(url, params)
options[:use_ssl] = url.scheme == 'https'
client = @http_client_class.new(url.host, url.port, options)
response = Puppet::HTTP::ResponseNetHTTP.new(url, client.get(url.request_uri, headers, options))
if block_given?
yield response
else
response
end
rescue Puppet::HTTP::HTTPError
raise
rescue => e
raise Puppet::HTTP::HTTPError.new(e.message, e)
end
# (see Puppet::HTTP::Client#post)
# @api private
def post(url, body, headers: {}, params: {}, options: {}, &block)
raise ArgumentError, "'post' requires a string 'body' argument" unless body.is_a?(String)
url = encode_query(url, params)
options[:use_ssl] = url.scheme == 'https'
client = @http_client_class.new(url.host, url.port, options)
response = Puppet::HTTP::ResponseNetHTTP.new(url, client.post(url.request_uri, body, headers, options))
if block_given?
yield response
else
response
end
rescue Puppet::HTTP::HTTPError, ArgumentError
raise
rescue => e
raise Puppet::HTTP::HTTPError.new(e.message, e)
end
# (see Puppet::HTTP::Client#close)
# @api private
def close
# This is a noop as puppetserver doesn't provide a way to close its http client.
end
# The following are intentionally not documented
def create_session
raise NotImplementedError
end
def connect(uri, options: {}, &block)
raise NotImplementedError
end
def head(url, headers: {}, params: {}, options: {})
raise NotImplementedError
end
def put(url, headers: {}, params: {}, options: {})
raise NotImplementedError
end
def delete(url, headers: {}, params: {}, options: {})
raise NotImplementedError
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/factory.rb | lib/puppet/http/factory.rb | # frozen_string_literal: true
require_relative '../../puppet/ssl/openssl_loader'
require 'net/http'
require_relative '../../puppet/http'
# Factory for `Net::HTTP` objects.
#
# Encapsulates the logic for creating a `Net::HTTP` object based on the
# specified {Site} and puppet settings.
#
# @api private
class Puppet::HTTP::Factory
@@openssl_initialized = false
KEEP_ALIVE_TIMEOUT = 2**31 - 1
def initialize
# PUP-1411, make sure that openssl is initialized before we try to connect
unless @@openssl_initialized
OpenSSL::SSL::SSLContext.new
@@openssl_initialized = true
end
end
def create_connection(site)
Puppet.debug("Creating new connection for #{site}")
http = Puppet::HTTP::Proxy.proxy(URI(site.addr))
http.use_ssl = site.use_ssl?
if site.use_ssl?
http.min_version = OpenSSL::SSL::TLS1_VERSION if http.respond_to?(:min_version)
http.ciphers = Puppet[:ciphers]
end
http.read_timeout = Puppet[:http_read_timeout]
http.open_timeout = Puppet[:http_connect_timeout]
http.keep_alive_timeout = KEEP_ALIVE_TIMEOUT if http.respond_to?(:keep_alive_timeout=)
# 0 means make one request and never retry
http.max_retries = 0
if Puppet[:sourceaddress]
Puppet.debug("Using source IP #{Puppet[:sourceaddress]}")
http.local_host = Puppet[:sourceaddress]
end
if Puppet[:http_debug]
http.set_debug_output($stderr)
end
http
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/service.rb | lib/puppet/http/service.rb | # frozen_string_literal: true
# Represents an abstract Puppet web service.
#
# @abstract Subclass and implement methods for the service's REST APIs.
# @api public
class Puppet::HTTP::Service
# @return [URI] the url associated with this service
attr_reader :url
# @return [Array<Symbol>] available services
SERVICE_NAMES = [:ca, :fileserver, :puppet, :puppetserver, :report].freeze
# @return [Array<Symbol>] format types that are unsupported
EXCLUDED_FORMATS = [:yaml, :b64_zlib_yaml, :dot].freeze
# Create a new web service, which contains the URL used to connect to the
# service. The four services implemented are `:ca`, `:fileserver`, `:puppet`,
# and `:report`.
#
# The `:ca` and `:report` services handle certs and reports, respectively. The
# `:fileserver` service handles puppet file metadata and content requests. And
# the default service, `:puppet`, handles nodes, facts, and catalogs.
#
# @param [Puppet::HTTP::Client] client the owner of the session
# @param [Puppet::HTTP::Session] session the owner of the service
# @param [Symbol] name the type of service to create
# @param [<Type>] server optional, the server to connect to
# @param [<Type>] port optional, the port to connect to
#
# @return [Puppet::HTTP::Service] an instance of the service type requested
#
# @api private
def self.create_service(client, session, name, server = nil, port = nil)
case name
when :ca
Puppet::HTTP::Service::Ca.new(client, session, server, port)
when :fileserver
Puppet::HTTP::Service::FileServer.new(client, session, server, port)
when :puppet
::Puppet::HTTP::Service::Compiler.new(client, session, server, port)
when :puppetserver
::Puppet::HTTP::Service::Puppetserver.new(client, session, server, port)
when :report
Puppet::HTTP::Service::Report.new(client, session, server, port)
else
raise ArgumentError, "Unknown service #{name}"
end
end
# Check if the service named is included in the list of available services.
#
# @param [Symbol] name
#
# @return [Boolean]
#
# @api private
def self.valid_name?(name)
SERVICE_NAMES.include?(name)
end
# Create a new service. Services should be created by calling `Puppet::HTTP::Session#route_to`.
#
# @param [Puppet::HTTP::Client] client
# @param [Puppet::HTTP::Session] session
# @param [URI] url The url to connect to
#
# @api private
def initialize(client, session, url)
@client = client
@session = session
@url = url
end
# Return the url with the given path encoded and appended
#
# @param [String] path the string to append to the base url
#
# @return [URI] the URI object containing the encoded path
#
# @api public
def with_base_url(path)
u = @url.dup
u.path += Puppet::Util.uri_encode(path)
u
end
# Open a connection using the given ssl context.
#
# @param [Puppet::SSL::SSLContext] ssl_context An optional ssl context to connect with
# @return [void]
#
# @api public
def connect(ssl_context: nil)
@client.connect(@url, options: { ssl_context: ssl_context })
end
protected
def add_puppet_headers(headers)
modified_headers = headers.dup
# Add 'X-Puppet-Profiling' to enable performance profiling if turned on
modified_headers['X-Puppet-Profiling'] = 'true' if Puppet[:profile]
# Add additional user-defined headers if they are defined
Puppet[:http_extra_headers].each do |name, value|
if modified_headers.keys.find { |key| key.casecmp(name) == 0 }
Puppet.warning(_('Ignoring extra header "%{name}" as it was previously set.') % { name: name })
elsif value.nil? || value.empty?
Puppet.warning(_('Ignoring extra header "%{name}" as it has no value.') % { name: name })
else
modified_headers[name] = value
end
end
modified_headers
end
def build_url(api, server, port)
URI::HTTPS.build(host: server,
port: port,
path: api).freeze
end
def get_mime_types(model)
network_formats = model.supported_formats - EXCLUDED_FORMATS
network_formats.map { |f| model.get_format(f).mime }
end
def formatter_for_response(response)
header = response['Content-Type']
raise Puppet::HTTP::ProtocolError, _("No content type in http response; cannot parse") unless header
header.gsub!(/\s*;.*$/, '') # strip any charset
formatter = Puppet::Network::FormatHandler.mime(header)
raise Puppet::HTTP::ProtocolError, "Content-Type is unsupported" if EXCLUDED_FORMATS.include?(formatter.name)
formatter
end
def serialize(formatter, object)
formatter.render(object)
rescue => err
raise Puppet::HTTP::SerializationError.new("Failed to serialize #{object.class} to #{formatter.name}: #{err.message}", err)
end
def serialize_multiple(formatter, object)
formatter.render_multiple(object)
rescue => err
raise Puppet::HTTP::SerializationError.new("Failed to serialize multiple #{object.class} to #{formatter.name}: #{err.message}", err)
end
def deserialize(response, model)
formatter = formatter_for_response(response)
begin
formatter.intern(model, response.body.to_s)
rescue => err
raise Puppet::HTTP::SerializationError.new("Failed to deserialize #{model} from #{formatter.name}: #{err.message}", err)
end
end
def deserialize_multiple(response, model)
formatter = formatter_for_response(response)
begin
formatter.intern_multiple(model, response.body.to_s)
rescue => err
raise Puppet::HTTP::SerializationError.new("Failed to deserialize multiple #{model} from #{formatter.name}: #{err.message}", err)
end
end
def process_response(response)
@session.process_response(response)
raise Puppet::HTTP::ResponseError, response unless response.success?
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/redirector.rb | lib/puppet/http/redirector.rb | # frozen_string_literal: true
# Handle HTTP redirects
#
# @api private
class Puppet::HTTP::Redirector
# Create a new redirect handler
#
# @param [Integer] redirect_limit maximum number of redirects allowed
#
# @api private
def initialize(redirect_limit)
@redirect_limit = redirect_limit
end
# Determine of the HTTP response code indicates a redirect
#
# @param [Net::HTTP] request request that received the response
# @param [Puppet::HTTP::Response] response
#
# @return [Boolean] true if the response code is 301, 302, or 307.
#
# @api private
def redirect?(request, response)
# Net::HTTPRedirection is not used because historically puppet
# has only handled these, and we're not a browser
case response.code
when 301, 302, 307
true
else
false
end
end
# Implement the HTTP request redirection
#
# @param [Net::HTTP] request request that has been redirected
# @param [Puppet::HTTP::Response] response
# @param [Integer] redirects the current number of redirects
#
# @return [Net::HTTP] A new request based on the original request, but with
# the redirected location
#
# @api private
def redirect_to(request, response, redirects)
raise Puppet::HTTP::TooManyRedirects, request.uri if redirects >= @redirect_limit
location = parse_location(response)
url = request.uri.merge(location)
new_request = request.class.new(url)
new_request.body = request.body
request.each do |header, value|
unless Puppet[:location_trusted]
# skip adding potentially sensitive header to other hosts
next if header.casecmp('Authorization').zero? && request.uri.host.casecmp(location.host) != 0
next if header.casecmp('Cookie').zero? && request.uri.host.casecmp(location.host) != 0
end
# Allow Net::HTTP to set its own Accept-Encoding header to avoid errors with HTTP compression.
# See https://github.com/puppetlabs/puppet/issues/9143
next if header.casecmp('Accept-Encoding').zero?
new_request[header] = value
end
# mimic private Net::HTTP#addr_port
new_request['Host'] = if (location.scheme == 'https' && location.port == 443) ||
(location.scheme == 'http' && location.port == 80)
location.host
else
"#{location.host}:#{location.port}"
end
new_request
end
private
def parse_location(response)
location = response['location']
raise Puppet::HTTP::ProtocolError, _("Location response header is missing") unless location
URI.parse(location)
rescue URI::InvalidURIError => e
raise Puppet::HTTP::ProtocolError.new(_("Location URI is invalid: %{detail}") % { detail: e.message }, e)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/retry_after_handler.rb | lib/puppet/http/retry_after_handler.rb | # frozen_string_literal: true
require 'date'
require 'time'
# Parse information relating to responses containing a Retry-After headers
#
# @api private
class Puppet::HTTP::RetryAfterHandler
# Create a handler to allow the system to sleep between HTTP requests
#
# @param [Integer] retry_limit number of retries allowed
# @param [Integer] max_sleep maximum sleep time allowed
def initialize(retry_limit, max_sleep)
@retry_limit = retry_limit
@max_sleep = max_sleep
end
# Does the response from the server tell us to wait until we attempt the next
# retry?
#
# @param [Net::HTTP] request
# @param [Puppet::HTTP::Response] response
#
# @return [Boolean] Return true if the response code is 429 or 503, return
# false otherwise
#
# @api private
def retry_after?(request, response)
case response.code
when 429, 503
true
else
false
end
end
# The amount of time to wait before attempting a retry
#
# @param [Net::HTTP] request
# @param [Puppet::HTTP::Response] response
# @param [Integer] retries number of retries attempted so far
#
# @return [Integer] the amount of time to wait
#
# @raise [Puppet::HTTP::TooManyRetryAfters] raise if we have hit our retry
# limit
#
# @api private
def retry_after_interval(request, response, retries)
raise Puppet::HTTP::TooManyRetryAfters, request.uri if retries >= @retry_limit
retry_after = response['Retry-After']
return nil unless retry_after
seconds = parse_retry_after(retry_after)
# if retry-after is far in the future, we could end up sleeping repeatedly
# for 30 minutes, effectively waiting indefinitely, seems like we should wait
# in total for 30 minutes, in which case this upper limit needs to be enforced
# by the client.
[seconds, @max_sleep].min
end
private
def parse_retry_after(retry_after)
Integer(retry_after)
rescue TypeError, ArgumentError
begin
tm = DateTime.rfc2822(retry_after)
seconds = (tm.to_time - DateTime.now.to_time).to_i
[seconds, 0].max
rescue ArgumentError
raise Puppet::HTTP::ProtocolError, _("Failed to parse Retry-After header '%{retry_after}' as an integer or RFC 2822 date") % { retry_after: retry_after }
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/site.rb | lib/puppet/http/site.rb | # frozen_string_literal: true
# Represents a site to which HTTP connections are made. It is a value
# object, and is suitable for use in a hash. If two sites are equal,
# then a persistent connection made to the first site, can be re-used
# for the second.
#
# @api private
class Puppet::HTTP::Site
attr_reader :scheme, :host, :port
def self.from_uri(uri)
new(uri.scheme, uri.host, uri.port)
end
def initialize(scheme, host, port)
@scheme = scheme
@host = host
@port = port.to_i
end
def addr
"#{@scheme}://#{@host}:#{@port}"
end
alias to_s addr
def ==(rhs)
(@scheme == rhs.scheme) && (@host == rhs.host) && (@port == rhs.port)
end
alias eql? ==
def hash
[@scheme, @host, @port].hash
end
def use_ssl?
@scheme == 'https'
end
def move_to(uri)
self.class.new(uri.scheme, uri.host, uri.port)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/service/report.rb | lib/puppet/http/service/report.rb | # frozen_string_literal: true
# The Report service is used to submit run reports to the report server.
#
# @api public
#
class Puppet::HTTP::Service::Report < Puppet::HTTP::Service
# @return [String] Default API for the report service
API = '/puppet/v3'
# Use `Puppet::HTTP::Session.route_to(:report)` to create or get an instance of this class.
#
# @param [Puppet::HTTP::Client] client
# @param [Puppet::HTTP::Session] session
# @param [String] server (Puppet[:ca_server]) If an explicit server is given,
# create a service using that server. If server is nil, the default value
# is used to create the service.
# @param [Integer] port (Puppet[:ca_port]) If an explicit port is given, create
# a service using that port. If port is nil, the default value is used to
# create the service.
#
# @api private
#
def initialize(client, session, server, port)
url = build_url(API, server || Puppet[:report_server], port || Puppet[:report_port])
super(client, session, url)
end
# Submit a report to the report server.
#
# @param [String] name the name of the report being submitted
# @param [Puppet::Transaction::Report] report run report to be submitted
# @param [String] environment name of the agent environment
#
# @return [Puppet::HTTP::Response] response returned by the server
#
# @api public
#
def put_report(name, report, environment:)
formatter = Puppet::Network::FormatHandler.format_for(Puppet[:preferred_serialization_format])
headers = add_puppet_headers(
'Accept' => get_mime_types(Puppet::Transaction::Report).join(', '),
'Content-Type' => formatter.mime
)
response = @client.put(
with_base_url("/report/#{name}"),
serialize(formatter, report),
headers: headers,
params: { environment: environment }
)
# override parent's process_response handling
@session.process_response(response)
if response.success?
response
else
raise Puppet::HTTP::ResponseError, response
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/service/compiler.rb | lib/puppet/http/service/compiler.rb | # frozen_string_literal: true
# The Compiler service is used to submit and retrieve data from the
# puppetserver.
#
# @api public
class Puppet::HTTP::Service::Compiler < Puppet::HTTP::Service
# @return [String] Default API for the Compiler service
API = '/puppet/v3'
# Use `Puppet::HTTP::Session.route_to(:puppet)` to create or get an instance of this class.
#
# @param [Puppet::HTTP::Client] client
# @param [Puppet::HTTP::Session] session
# @param [String] server (`Puppet[:server]`) If an explicit server is given,
# create a service using that server. If server is nil, the default value
# is used to create the service.
# @param [Integer] port (`Puppet[:masterport]`) If an explicit port is given, create
# a service using that port. If port is nil, the default value is used to
# create the service.
#
def initialize(client, session, server, port)
url = build_url(API, server || Puppet[:server], port || Puppet[:serverport])
super(client, session, url)
end
# Submit a GET request to retrieve a node from the server.
#
# @param [String] name The name of the node being requested
# @param [String] environment The name of the environment we are operating in
# @param [String] configured_environment Optional, the name of the configured
# environment. If unset, `environment` is used.
# @param [String] transaction_uuid An agent generated transaction uuid, used
# for connecting catalogs and reports.
#
# @return [Array<Puppet::HTTP::Response, Puppet::Node>] An array containing
# the request response and the deserialized requested node
#
# @api public
def get_node(name, environment:, configured_environment: nil, transaction_uuid: nil)
headers = add_puppet_headers('Accept' => get_mime_types(Puppet::Node).join(', '))
response = @client.get(
with_base_url("/node/#{name}"),
headers: headers,
params: {
environment: environment,
configured_environment: configured_environment || environment,
transaction_uuid: transaction_uuid,
}
)
process_response(response)
[response, deserialize(response, Puppet::Node)]
end
# Submit a POST request to submit a catalog to the server.
#
# @param [String] name The name of the catalog to be submitted
# @param [Puppet::Node::Facts] facts Facts for this catalog
# @param [String] environment The name of the environment we are operating in
# @param [String] configured_environment Optional, the name of the configured
# environment. If unset, `environment` is used.
# @param [Boolean] check_environment If true, request that the server check if
# our `environment` matches the server-specified environment. If they do not
# match, then the server may return an empty catalog in the server-specified
# environment.
# @param [String] transaction_uuid An agent generated transaction uuid, used
# for connecting catalogs and reports.
# @param [String] job_uuid A unique job identifier defined when the orchestrator
# starts a puppet run via pxp-agent. This is used to correlate catalogs and
# reports with the orchestrator job.
# @param [Boolean] static_catalog Indicates if the file metadata(s) are inlined
# in the catalog. This informs the agent if it needs to make a second request
# to retrieve metadata in addition to the initial catalog request.
# @param [Array<String>] checksum_type An array of accepted checksum types.
#
# @return [Array<Puppet::HTTP::Response, Puppet::Resource::Catalog>] An array
# containing the request response and the deserialized catalog returned by
# the server
#
# @api public
def post_catalog(name, facts:, environment:, configured_environment: nil, check_environment: false, transaction_uuid: nil, job_uuid: nil, static_catalog: true, checksum_type: Puppet[:supported_checksum_types])
if Puppet[:preferred_serialization_format] == "pson"
formatter = Puppet::Network::FormatHandler.format_for(:pson)
# must use 'pson' instead of 'text/pson'
facts_format = 'pson'
else
formatter = Puppet::Network::FormatHandler.format_for(:json)
facts_format = formatter.mime
end
facts_as_string = serialize(formatter, facts)
# query parameters are sent in the POST request body
body = {
facts_format: facts_format,
facts: Puppet::Util.uri_query_encode(facts_as_string),
environment: environment,
configured_environment: configured_environment || environment,
check_environment: !!check_environment,
transaction_uuid: transaction_uuid,
job_uuid: job_uuid,
static_catalog: static_catalog,
checksum_type: checksum_type.join('.')
}.map do |key, value|
"#{key}=#{Puppet::Util.uri_query_encode(value.to_s)}"
end.join("&")
headers = add_puppet_headers(
'Accept' => get_mime_types(Puppet::Resource::Catalog).join(', '),
'Content-Type' => 'application/x-www-form-urlencoded'
)
response = @client.post(
with_base_url("/catalog/#{name}"),
body,
headers: headers,
# for legacy reasons we always send environment as a query parameter too
params: { environment: environment }
)
if (compiler = response['X-Puppet-Compiler-Name'])
Puppet.notice("Catalog compiled by #{compiler}")
end
process_response(response)
[response, deserialize(response, Puppet::Resource::Catalog)]
end
#
# @api private
#
# Submit a POST request to request a catalog to the server using v4 endpoint
#
# @param [String] certname The name of the node for which to compile the catalog.
# @param [Hash] persistent A hash containing two required keys, facts and catalog,
# which when set to true will cause the facts and reports to be stored in
# PuppetDB, or discarded if set to false.
# @param [String] environment The name of the environment for which to compile the catalog.
# @param [Hash] facts A hash with a required values key, containing a hash of all the
# facts for the node. If not provided, Puppet will attempt to fetch facts for the node
# from PuppetDB.
# @param [Hash] trusted_facts A hash with a required values key containing a hash of
# the trusted facts for a node
# @param [String] transaction_uuid The id for tracking the catalog compilation and
# report submission.
# @param [String] job_id The id of the orchestrator job that triggered this run.
# @param [Hash] options A hash of options beyond direct input to catalogs. Options:
# - prefer_requested_environment Whether to always override a node's classified
# environment with the one supplied in the request. If this is true and no environment
# is supplied, fall back to the classified environment, or finally, 'production'.
# - capture_logs Whether to return the errors and warnings that occurred during
# compilation alongside the catalog in the response body.
# - log_level The logging level to use during the compile when capture_logs is true.
# Options are 'err', 'warning', 'info', and 'debug'.
#
# @return [Array<Puppet::HTTP::Response, Puppet::Resource::Catalog, Array<String>>] An array
# containing the request response, the deserialized catalog returned by
# the server and array containing logs (log array will be empty if capture_logs is false)
#
def post_catalog4(certname, persistence:, environment:, facts: nil, trusted_facts: nil, transaction_uuid: nil, job_id: nil, options: nil)
unless persistence.is_a?(Hash) && (missing = [:facts, :catalog] - persistence.keys.map(&:to_sym)).empty?
raise ArgumentError, "The 'persistence' hash is missing the keys: #{missing.join(', ')}"
end
raise ArgumentError, "Facts must be a Hash not a #{facts.class}" unless facts.nil? || facts.is_a?(Hash)
body = {
certname: certname,
persistence: persistence,
environment: environment,
transaction_uuid: transaction_uuid,
job_id: job_id,
options: options
}
body[:facts] = { values: facts } unless facts.nil?
body[:trusted_facts] = { values: trusted_facts } unless trusted_facts.nil?
headers = add_puppet_headers(
'Accept' => get_mime_types(Puppet::Resource::Catalog).join(', '),
'Content-Type' => 'application/json'
)
url = URI::HTTPS.build(host: @url.host, port: @url.port, path: Puppet::Util.uri_encode("/puppet/v4/catalog"))
response = @client.post(
url,
body.to_json,
headers: headers
)
process_response(response)
begin
response_body = JSON.parse(response.body)
catalog = Puppet::Resource::Catalog.from_data_hash(response_body['catalog'])
rescue => err
raise Puppet::HTTP::SerializationError.new("Failed to deserialize catalog from puppetserver response: #{err.message}", err)
end
logs = response_body['logs'] || []
[response, catalog, logs]
end
#
# @api private
#
# Submit a GET request to retrieve the facts for the named node
#
# @param [String] name Name of the node to retrieve facts for
# @param [String] environment Name of the environment we are operating in
#
# @return [Array<Puppet::HTTP::Response, Puppet::Node::Facts>] An array
# containing the request response and the deserialized facts for the
# specified node
#
# @api public
def get_facts(name, environment:)
headers = add_puppet_headers('Accept' => get_mime_types(Puppet::Node::Facts).join(', '))
response = @client.get(
with_base_url("/facts/#{name}"),
headers: headers,
params: { environment: environment }
)
process_response(response)
[response, deserialize(response, Puppet::Node::Facts)]
end
# Submits a PUT request to submit facts for the node to the server.
#
# @param [String] name Name of the node we are submitting facts for
# @param [String] environment Name of the environment we are operating in
# @param [Puppet::Node::Facts] facts Facts for the named node
#
# @return [Puppet::HTTP::Response] The request response
#
# @api public
def put_facts(name, environment:, facts:)
formatter = Puppet::Network::FormatHandler.format_for(Puppet[:preferred_serialization_format])
headers = add_puppet_headers(
'Accept' => get_mime_types(Puppet::Node::Facts).join(', '),
'Content-Type' => formatter.mime
)
response = @client.put(
with_base_url("/facts/#{name}"),
serialize(formatter, facts),
headers: headers,
params: { environment: environment }
)
process_response(response)
response
end
# Submit a GET request to retrieve a file stored with filebucket.
#
# @param [String] path The request path, formatted by `Puppet::FileBucket::Dipper`
# @param [String] environment Name of the environment we are operating in.
# This should not impact filebucket at all, but is included to be consistent
# with legacy code.
# @param [String] bucket_path
# @param [String] diff_with a checksum to diff against if we are comparing
# files that are both stored in the bucket
# @param [String] list_all
# @param [String] fromdate
# @param [String] todate
#
# @return [Array<Puppet::HTTP::Response, Puppet::FileBucket::File>] An array
# containing the request response and the deserialized file returned from
# the server.
#
# @api public
def get_filebucket_file(path, environment:, bucket_path: nil, diff_with: nil, list_all: nil, fromdate: nil, todate: nil)
headers = add_puppet_headers('Accept' => 'application/octet-stream')
response = @client.get(
with_base_url("/file_bucket_file/#{path}"),
headers: headers,
params: {
environment: environment,
bucket_path: bucket_path,
diff_with: diff_with,
list_all: list_all,
fromdate: fromdate,
todate: todate
}
)
process_response(response)
[response, deserialize(response, Puppet::FileBucket::File)]
end
# Submit a PUT request to store a file with filebucket.
#
# @param [String] path The request path, formatted by `Puppet::FileBucket::Dipper`
# @param [String] body The contents of the file to be backed
# @param [String] environment Name of the environment we are operating in.
# This should not impact filebucket at all, but is included to be consistent
# with legacy code.
#
# @return [Puppet::HTTP::Response] The response request
#
# @api public
def put_filebucket_file(path, body:, environment:)
headers = add_puppet_headers({
'Accept' => 'application/octet-stream',
'Content-Type' => 'application/octet-stream'
})
response = @client.put(
with_base_url("/file_bucket_file/#{path}"),
body,
headers: headers,
params: {
environment: environment
}
)
process_response(response)
response
end
# Submit a HEAD request to check the status of a file stored with filebucket.
#
# @param [String] path The request path, formatted by `Puppet::FileBucket::Dipper`
# @param [String] environment Name of the environment we are operating in.
# This should not impact filebucket at all, but is included to be consistent
# with legacy code.
# @param [String] bucket_path
#
# @return [Puppet::HTTP::Response] The request response
#
# @api public
def head_filebucket_file(path, environment:, bucket_path: nil)
headers = add_puppet_headers('Accept' => 'application/octet-stream')
response = @client.head(
with_base_url("/file_bucket_file/#{path}"),
headers: headers,
params: {
environment: environment,
bucket_path: bucket_path
}
)
process_response(response)
response
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/service/ca.rb | lib/puppet/http/service/ca.rb | # frozen_string_literal: true
# The CA service is used to handle certificate related REST requests.
#
# @api public
class Puppet::HTTP::Service::Ca < Puppet::HTTP::Service
# @return [Hash] default headers for the ca service
HEADERS = { 'Accept' => 'text/plain' }.freeze
# @return [String] default API for the ca service
API = '/puppet-ca/v1'
# Use `Puppet::HTTP::Session.route_to(:ca)` to create or get an instance of this class.
#
# @param [Puppet::HTTP::Client] client
# @param [Puppet::HTTP::Session] session
# @param [String] server (`Puppet[:ca_server]`) If an explicit server is given,
# create a service using that server. If server is nil, the default value
# is used to create the service.
# @param [Integer] port (`Puppet[:ca_port]`) If an explicit port is given, create
# a service using that port. If port is nil, the default value is used to
# create the service.
#
def initialize(client, session, server, port)
url = build_url(API, server || Puppet[:ca_server], port || Puppet[:ca_port])
super(client, session, url)
end
# Submit a GET request to retrieve the named certificate from the server.
#
# @param [String] name name of the certificate to request
# @param [Time] if_modified_since If not nil, only download the cert if it has
# been modified since the specified time.
# @param [Puppet::SSL::SSLContext] ssl_context
#
# @return [Array<Puppet::HTTP::Response, String>] An array containing the
# request response and the stringified body of the request response
#
# @api public
def get_certificate(name, if_modified_since: nil, ssl_context: nil)
headers = add_puppet_headers(HEADERS)
headers['If-Modified-Since'] = if_modified_since.httpdate if if_modified_since
response = @client.get(
with_base_url("/certificate/#{name}"),
headers: headers,
options: { ssl_context: ssl_context }
)
process_response(response)
[response, response.body.to_s]
end
# Submit a GET request to retrieve the certificate revocation list from the
# server.
#
# @param [Time] if_modified_since If not nil, only download the CRL if it has
# been modified since the specified time.
# @param [Puppet::SSL::SSLContext] ssl_context
#
# @return [Array<Puppet::HTTP::Response, String>] An array containing the
# request response and the stringified body of the request response
#
# @api public
def get_certificate_revocation_list(if_modified_since: nil, ssl_context: nil)
headers = add_puppet_headers(HEADERS)
headers['If-Modified-Since'] = if_modified_since.httpdate if if_modified_since
response = @client.get(
with_base_url("/certificate_revocation_list/ca"),
headers: headers,
options: { ssl_context: ssl_context }
)
process_response(response)
[response, response.body.to_s]
end
# Submit a PUT request to send a certificate request to the server.
#
# @param [String] name The name of the certificate request being sent
# @param [OpenSSL::X509::Request] csr Certificate request to send to the
# server
# @param [Puppet::SSL::SSLContext] ssl_context
#
# @return [Puppet::HTTP::Response] The request response
#
# @api public
def put_certificate_request(name, csr, ssl_context: nil)
headers = add_puppet_headers(HEADERS)
headers['Content-Type'] = 'text/plain'
response = @client.put(
with_base_url("/certificate_request/#{name}"),
csr.to_pem,
headers: headers,
options: {
ssl_context: ssl_context
}
)
process_response(response)
response
end
# Submit a POST request to send a certificate renewal request to the server
#
# @param [Puppet::SSL::SSLContext] ssl_context
#
# @return [Array<Puppet::HTTP::Response, String>] The request response
#
# @api public
def post_certificate_renewal(ssl_context)
headers = add_puppet_headers(HEADERS)
headers['Content-Type'] = 'text/plain'
response = @client.post(
with_base_url('/certificate_renewal'),
'', # Puppet::HTTP::Client.post requires a body, the API endpoint does not
headers: headers,
options: { ssl_context: ssl_context }
)
raise ArgumentError, _('SSL context must contain a client certificate.') unless ssl_context.client_cert
process_response(response)
[response, response.body.to_s]
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/service/puppetserver.rb | lib/puppet/http/service/puppetserver.rb | # frozen_string_literal: true
# The puppetserver service.
#
# @api public
#
class Puppet::HTTP::Service::Puppetserver < Puppet::HTTP::Service
# Use `Puppet::HTTP::Session.route_to(:puppetserver)` to create or get an instance of this class.
#
# @param [Puppet::HTTP::Client] client
# @param [Puppet::HTTP::Session] session
# @param [String] server (`Puppet[:server]`) If an explicit server is given,
# create a service using that server. If server is nil, the default value
# is used to create the service.
# @param [Integer] port (`Puppet[:masterport]`) If an explicit port is given, create
# a service using that port. If port is nil, the default value is used to
# create the service.
#
def initialize(client, session, server, port)
url = build_url('', server || Puppet[:server], port || Puppet[:serverport])
super(client, session, url)
end
# Request the puppetserver's simple status.
#
# @param [Puppet::SSL::SSLContext] ssl_context to use when establishing
# the connection.
# @return Puppet::HTTP::Response The HTTP response
#
# @api public
#
def get_simple_status(ssl_context: nil)
request_path = "/status/v1/simple/server"
begin
response = @client.get(
with_base_url(request_path),
headers: add_puppet_headers({}),
options: { ssl_context: ssl_context }
)
process_response(response)
rescue Puppet::HTTP::ResponseError => e
if e.response.code == 404 && e.response.url.path == "/status/v1/simple/server"
request_path = "/status/v1/simple/master"
retry
else
raise e
end
end
[response, response.body.to_s]
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/service/file_server.rb | lib/puppet/http/service/file_server.rb | # frozen_string_literal: true
require_relative '../../../puppet/file_serving/metadata'
# The FileServer service is used to retrieve file metadata and content.
#
# @api public
#
class Puppet::HTTP::Service::FileServer < Puppet::HTTP::Service
# @return [String] Default API for the FileServer service
API = '/puppet/v3'
# @return [RegEx] RegEx used to determine if a path contains a leading slash
PATH_REGEX = %r{^/}
# Use `Puppet::HTTP::Session.route_to(:fileserver)` to create or get an instance of this class.
#
# @param [Puppet::HTTP::Client] client
# @param [Puppet::HTTP::Session] session
# @param [String] server (`Puppet[:server]`) If an explicit server is given,
# create a service using that server. If server is nil, the default value
# is used to create the service.
# @param [Integer] port (`Puppet[:masterport]`) If an explicit port is given, create
# a service using that port. If port is nil, the default value is used to
# create the service.
#
def initialize(client, session, server, port)
url = build_url(API, server || Puppet[:server], port || Puppet[:serverport])
super(client, session, url)
end
# Submit a GET request to the server to retrieve the metadata for a specified file.
#
# @param [String] path path to the file to retrieve data from
# @param [String] environment the name of the environment we are operating in
# @param [Symbol] links Can be one of either `:follow` or `:manage`, defines
# how links are handled.
# @param [String] checksum_type The digest algorithm used to verify the file.
# Defaults to `sha256`.
# @param [Symbol] source_permissions Can be one of `:use`, `:use_when_creating`,
# or `:ignore`. This parameter tells the server if it should include the
# file permissions in the response. If set to `:ignore`, the server will
# return default permissions.
#
# @return [Array<Puppet::HTTP::Response, Puppet::FileServing::Metadata>] An
# array with the request response and the deserialized metadata for the
# file returned from the server
#
# @api public
#
def get_file_metadata(path:, environment:, links: :manage, checksum_type: Puppet[:digest_algorithm], source_permissions: :ignore)
validate_path(path)
headers = add_puppet_headers('Accept' => get_mime_types(Puppet::FileServing::Metadata).join(', '))
response = @client.get(
with_base_url("/file_metadata#{path}"),
headers: headers,
params: {
links: links,
checksum_type: checksum_type,
source_permissions: source_permissions,
environment: environment
}
)
process_response(response)
[response, deserialize(response, Puppet::FileServing::Metadata)]
end
# Submit a GET request to the server to retrieve the metadata for multiple files
#
# @param [String] path path to the file(s) to retrieve data from
# @param [String] environment the name of the environment we are operating in
# @param [Symbol] recurse Can be `:true`, `:false`, or `:remote`. Defines if
# we recursively return the contents of the directory. Used in conjunction
# with `:recurselimit`. See the reference documentation for the file type
# for more details.
# @param [Integer] recurselimit When `recurse` is set, `recurselimit` defines
# how far Puppet should descend into subdirectories. `0` is effectively the
# same as `recurse => false`, `1` will return files and directories directly
# inside the defined directory, `2` will return the direct content of the
# directory as well as the contents of the _first_ level of subdirectories.
# The pattern continues for each incremental value. See the reference
# documentation for the file type for more details.
# @param [Array<String>] ignore An optional array of files to ignore, ie `['CVS', '.git', '.hg']`
# @param [Symbol] links Can be one of either `:follow` or `:manage`, defines
# how links are handled.
# @param [String] checksum_type The digest algorithm used to verify the file.
# Currently if fips is enabled, this defaults to `sha256`. Otherwise, it's `md5`.
# @param [Symbol] source_permissions Can be one of `:use`, `:use_when_creating`,
# or `:ignore`. This parameter tells the server if it should include the
# file permissions in the report. If set to `:ignore`, the server will return
# default permissions.
#
# @return [Array<Puppet::HTTP::Response, Array<Puppet::FileServing::Metadata>>]
# An array with the request response and an array of the deserialized
# metadata for each file returned from the server
#
# @api public
#
def get_file_metadatas(environment:, path: nil, recurse: :false, recurselimit: nil, max_files: nil, ignore: nil, links: :manage, checksum_type: Puppet[:digest_algorithm], source_permissions: :ignore) # rubocop:disable Lint/BooleanSymbol
validate_path(path)
headers = add_puppet_headers('Accept' => get_mime_types(Puppet::FileServing::Metadata).join(', '))
response = @client.get(
with_base_url("/file_metadatas#{path}"),
headers: headers,
params: {
recurse: recurse,
recurselimit: recurselimit,
max_files: max_files,
ignore: ignore,
links: links,
checksum_type: checksum_type,
source_permissions: source_permissions,
environment: environment,
}
)
process_response(response)
[response, deserialize_multiple(response, Puppet::FileServing::Metadata)]
end
# Submit a GET request to the server to retrieve content of a file.
#
# @param [String] path path to the file to retrieve data from
# @param [String] environment the name of the environment we are operating in
#
# @yield [Sting] Yields the body of the response returned from the server
#
# @return [Puppet::HTTP::Response] The request response
#
# @api public
#
def get_file_content(path:, environment:, &block)
validate_path(path)
headers = add_puppet_headers('Accept' => 'application/octet-stream')
response = @client.get(
with_base_url("/file_content#{path}"),
headers: headers,
params: {
environment: environment
}
) do |res|
if res.success?
res.read_body(&block)
end
end
process_response(response)
response
end
# Submit a GET request to retrieve file content using the `static_file_content` API
# uniquely identified by (`code_id`, `environment`, `path`).
#
# @param [String] path path to the file to retrieve data from
# @param [String] environment the name of the environment we are operating in
# @param [String] code_id Defines the version of the resource to return
#
# @yield [String] Yields the body of the response returned
#
# @return [Puppet::HTTP::Response] The request response
#
# @api public
#
def get_static_file_content(path:, environment:, code_id:, &block)
validate_path(path)
headers = add_puppet_headers('Accept' => 'application/octet-stream')
response = @client.get(
with_base_url("/static_file_content#{path}"),
headers: headers,
params: {
environment: environment,
code_id: code_id,
}
) do |res|
if res.success?
res.read_body(&block)
end
end
process_response(response)
response
end
private
def validate_path(path)
raise ArgumentError, "Path must start with a slash" unless path =~ PATH_REGEX
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/resolver/srv.rb | lib/puppet/http/resolver/srv.rb | # frozen_string_literal: true
# Resolve a service using DNS SRV records.
#
# @api public
class Puppet::HTTP::Resolver::SRV < Puppet::HTTP::Resolver
# Create an DNS SRV resolver.
#
# @param [Puppet::HTTP::Client] client
# @param [String] domain srv domain
# @param [Resolv::DNS] dns
#
def initialize(client, domain:, dns: Resolv::DNS.new)
@client = client
@srv_domain = domain
@delegate = Puppet::HTTP::DNS.new(dns)
end
# Walk the available srv records and return the first that successfully connects
#
# @param [Puppet::HTTP::Session] session
# @param [Symbol] name the service being resolved
# @param [Puppet::SSL::SSLContext] ssl_context
# @param [Proc] canceled_handler optional callback allowing a resolver
# to cancel resolution.
#
# @return [Puppet::HTTP::Service] if an available service is found, return
# it. Return nil otherwise.
#
# @api public
def resolve(session, name, ssl_context: nil, canceled_handler: nil)
# Here we pass our HTTP service name as the DNS SRV service name
# This is fine for :ca, but note that :puppet and :file are handled
# specially in `each_srv_record`.
@delegate.each_srv_record(@srv_domain, name) do |server, port|
service = Puppet::HTTP::Service.create_service(@client, session, name, server, port)
return service if check_connection?(session, service, ssl_context: ssl_context)
end
nil
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/resolver/settings.rb | lib/puppet/http/resolver/settings.rb | # frozen_string_literal: true
# Resolve a service using settings. This is the default resolver if none of the
# other resolvers find a functional connection.
#
# @api public
class Puppet::HTTP::Resolver::Settings < Puppet::HTTP::Resolver
# Resolve a service using the default server and port settings for this service.
#
# @param [Puppet::HTTP::Session] session
# @param [Symbol] name the name of the service to be resolved
# @param [Puppet::SSL::SSLContext] ssl_context
# @param [Proc] canceled_handler optional callback allowing a resolver
# to cancel resolution.
#
# @return [Puppet::HTTP::Service] if the service successfully connects,
# return it. Otherwise, return nil.
#
# @api public
def resolve(session, name, ssl_context: nil, canceled_handler: nil)
service = Puppet::HTTP::Service.create_service(@client, session, name)
check_connection?(session, service, ssl_context: ssl_context) ? service : nil
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/http/resolver/server_list.rb | lib/puppet/http/resolver/server_list.rb | # frozen_string_literal: true
# Use the server_list setting to resolve a service. This resolver is only used
# if server_list is set either on the command line or in the configuration file.
#
# @api public
class Puppet::HTTP::Resolver::ServerList < Puppet::HTTP::Resolver
# Create a server list resolver.
#
# @param [Puppet::HTTP::Client] client
# @param [Array<String>] server_list_setting array of servers set via the
# configuration or the command line
# @param [Integer] default_port if a port is not set for a server in
# server_list, use this port
# @param [Array<Symbol>] services array of services that server_list can be
# used to resolve. If a service is not included in this array, this resolver
# will return nil.
#
def initialize(client, server_list_setting:, default_port:, services:)
@client = client
@server_list_setting = server_list_setting
@default_port = default_port
@services = services
end
# Walk the server_list to find a server and port that will connect successfully.
#
# @param [Puppet::HTTP::Session] session
# @param [Symbol] name the name of the service being resolved
# @param [Puppet::SSL::SSLContext] ssl_context
# @param [Proc] canceled_handler optional callback allowing a resolver
# to cancel resolution.
#
# @return [nil] return nil if the service to be resolved does not support
# server_list
# @return [Puppet::HTTP::Service] a validated service to use for future HTTP
# requests
#
# @raise [Puppet::Error] raise if none of the servers defined in server_list
# are available
#
# @api public
def resolve(session, name, ssl_context: nil, canceled_handler: nil)
# If we're configured to use an explicit service host, e.g. report_server
# then don't use server_list to resolve the `:report` service.
return nil unless @services.include?(name)
# If we resolved the URL already, use its host & port for the service
if @resolved_url
return Puppet::HTTP::Service.create_service(@client, session, name, @resolved_url.host, @resolved_url.port)
end
# Return the first simple service status endpoint we can connect to
@server_list_setting.value.each_with_index do |server, index|
host = server[0]
port = server[1] || @default_port
service = Puppet::HTTP::Service.create_service(@client, session, :puppetserver, host, port)
begin
service.get_simple_status(ssl_context: ssl_context)
@resolved_url = service.url
return Puppet::HTTP::Service.create_service(@client, session, name, @resolved_url.host, @resolved_url.port)
rescue Puppet::HTTP::ResponseError => detail
if index < @server_list_setting.value.length - 1
Puppet.warning(_("Puppet server %{host}:%{port} is unavailable: %{code} %{reason}") %
{ host: service.url.host, port: service.url.port, code: detail.response.code, reason: detail.response.reason } +
' ' + _("Trying with next server from server_list."))
else
Puppet.log_exception(detail, _("Puppet server %{host}:%{port} is unavailable: %{code} %{reason}") %
{ host: service.url.host, port: service.url.port, code: detail.response.code, reason: detail.response.reason })
end
rescue Puppet::HTTP::HTTPError => detail
if index < @server_list_setting.value.length - 1
Puppet.warning(_("Unable to connect to server from server_list setting: %{detail}") % { detail: detail } +
' ' + _("Trying with next server from server_list."))
else
Puppet.log_exception(detail, _("Unable to connect to server from server_list setting: %{detail}") % { detail: detail })
end
end
end
# don't fallback to other resolvers
canceled_handler.call(true) if canceled_handler
# not found
nil
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
peterkeen/ledger-web | https://github.com/peterkeen/ledger-web/blob/ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60/test/database_load_spec.rb | test/database_load_spec.rb | require File.expand_path(File.dirname(__FILE__) + "/spec_helper")
require 'ledger_web/db'
require 'ledger_web/config'
require 'csv'
describe LedgerWeb::Database do
describe "#dump_ledger_to_csv" do
it "should not die" do
set_config :ledger_file, fixture('small')
file = LedgerWeb::Database.dump_ledger_to_csv
end
it "should dump valid csv" do
set_config :ledger_file, fixture('small')
file = LedgerWeb::Database.dump_ledger_to_csv
rows = CSV.read(file.path)
rows.should eq([
["1", "2012/01/01", "Transaction One", "Assets:Savings", "$", "100", "true", "false", "", "$100.00"],
["1", "2012/01/01", "Transaction One", "Assets:Checking", "$", "200", "true", "false", "", "$200.00"],
["1", "2012/01/01", "Transaction One", "Equity:Opening Balances", "$", "-300", "true", "false", "", "$-300.00"],
["6", "2012/01/02", "Lunch", "Expenses:Lunch", "$", "10", "true", "false", "", "$10.00"],
["6", "2012/01/02", "Lunch", "Assets:Checking", "$", "-10", "true", "false", "", "$-10.00"]
])
end
it "should dump valid csv even with quoted commodities" do
set_config :ledger_file, fixture('quoted')
file = LedgerWeb::Database.dump_ledger_to_csv
rows = CSV.read(file.path)
rows.should eq([
["1", "2012/01/01", "Transaction One", "Assets:Savings", "\"Foo 123\"", "100", "true", "false", "", "100.00 \"Foo 123\""],
["1", "2012/01/01", "Transaction One", "Assets:Checking", "\"Foo 123\"", "200", "true", "false", "", "200.00 \"Foo 123\""],
["1", "2012/01/01", "Transaction One", "Equity:Opening Balances", "\"Foo 123\"", "-300", "true", "false", "", "-300.00 \"Foo 123\""],
["6", "2012/01/02", "Lunch", "Expenses:Lunch", "\"Foo 123\"", "10", "true", "false", "", "10.00 \"Foo 123\""],
["6", "2012/01/02", "Lunch", "Assets:Checking", "\"Foo 123\"", "-10", "true", "false", "", "-10.00 \"Foo 123\""]
])
end
end
describe "#load_database" do
it "should load the database from a csv file" do
set_config :ledger_file, fixture('small')
file = LedgerWeb::Database.dump_ledger_to_csv
count = LedgerWeb::Database.load_database(file)
count.should eq(5)
LedgerWeb::Database.handle[:ledger].count().should eq(5)
convert_bd_to_string(LedgerWeb::Database.handle[:ledger].all()).should eq([
{
:xtn_date => Date.new(2012,1,1),
:checknum => nil,
:note => 'Transaction One',
:account => 'Assets:Savings',
:commodity => '$',
:amount => "100.0",
:tags => '',
:xtn_month => Date.new(2012,1,1),
:xtn_year => Date.new(2012,1,1),
:virtual => false,
:xtn_id => 1,
:cleared => true,
:cost => "100.0"
},
{
:xtn_date => Date.new(2012,1,1),
:checknum => nil,
:note => 'Transaction One',
:account => 'Assets:Checking',
:commodity => '$',
:amount => "200.0",
:tags => '',
:xtn_month => Date.new(2012,1,1),
:xtn_year => Date.new(2012,1,1),
:virtual => false,
:xtn_id => 1,
:cleared => true,
:cost => "200.0"
},
{
:xtn_date => Date.new(2012,1,1),
:checknum => nil,
:note => 'Transaction One',
:account => 'Equity:Opening Balances',
:commodity => '$',
:amount => "-300.0",
:tags => '',
:xtn_month => Date.new(2012,1,1),
:xtn_year => Date.new(2012,1,1),
:virtual => false,
:xtn_id => 1,
:cleared => true,
:cost => "-300.0"
},
{
:xtn_date => Date.new(2012,1,2),
:checknum => nil,
:note => 'Lunch',
:account => 'Expenses:Lunch',
:commodity => '$',
:amount => "10.0",
:tags => '',
:xtn_month => Date.new(2012,1,1),
:xtn_year => Date.new(2012,1,1),
:virtual => false,
:xtn_id => 6,
:cleared => true,
:cost => "10.0"
},
{
:xtn_date => Date.new(2012,1,2),
:checknum => nil,
:note => 'Lunch',
:account => 'Assets:Checking',
:commodity => '$',
:amount => "-10.0",
:tags => '',
:xtn_month => Date.new(2012,1,1),
:xtn_year => Date.new(2012,1,1),
:virtual => false,
:xtn_id => 6,
:cleared => true,
:cost => "-10.0"
},
])
end
it "should load the database from a csv file containing quoted things" do
set_config :ledger_file, fixture('quoted')
file = LedgerWeb::Database.dump_ledger_to_csv
count = LedgerWeb::Database.load_database(file)
count.should eq(5)
LedgerWeb::Database.handle[:ledger].count().should eq(5)
convert_bd_to_string(LedgerWeb::Database.handle[:ledger].all()).should eq([
{
:xtn_date => Date.new(2012,1,1),
:checknum => nil,
:note => 'Transaction One',
:account => 'Assets:Savings',
:commodity => '"Foo 123"',
:amount => "100.0",
:tags => '',
:xtn_month => Date.new(2012,1,1),
:xtn_year => Date.new(2012,1,1),
:virtual => false,
:xtn_id => 1,
:cleared => true,
:cost => "100.0"
},
{
:xtn_date => Date.new(2012,1,1),
:checknum => nil,
:note => 'Transaction One',
:account => 'Assets:Checking',
:commodity => '"Foo 123"',
:amount => "200.0",
:tags => '',
:xtn_month => Date.new(2012,1,1),
:xtn_year => Date.new(2012,1,1),
:virtual => false,
:xtn_id => 1,
:cleared => true,
:cost => "200.0"
},
{
:xtn_date => Date.new(2012,1,1),
:checknum => nil,
:note => 'Transaction One',
:account => 'Equity:Opening Balances',
:commodity => '"Foo 123"',
:amount => "-300.0",
:tags => '',
:xtn_month => Date.new(2012,1,1),
:xtn_year => Date.new(2012,1,1),
:virtual => false,
:xtn_id => 1,
:cleared => true,
:cost => "-300.0"
},
{
:xtn_date => Date.new(2012,1,2),
:checknum => nil,
:note => 'Lunch',
:account => 'Expenses:Lunch',
:commodity => '"Foo 123"',
:amount => "10.0",
:tags => '',
:xtn_month => Date.new(2012,1,1),
:xtn_year => Date.new(2012,1,1),
:virtual => false,
:xtn_id => 6,
:cleared => true,
:cost => "10.0"
},
{
:xtn_date => Date.new(2012,1,2),
:checknum => nil,
:note => 'Lunch',
:account => 'Assets:Checking',
:commodity => '"Foo 123"',
:amount => "-10.0",
:tags => '',
:xtn_month => Date.new(2012,1,1),
:xtn_year => Date.new(2012,1,1),
:virtual => false,
:xtn_id => 6,
:cleared => true,
:cost => "-10.0"
},
])
end
it "should load the database from csv with a complicated cost string" do
count = 0
File.open(fixture('complex_costs')) do |file|
count = LedgerWeb::Database.load_database(file)
end
count.should eq(1)
convert_bd_to_string(LedgerWeb::Database.handle[:ledger].all()).should eq([
{
:xtn_date => Date.new(2011,8,30),
:checknum => nil,
:note => 'Tttttttttt Pagamento',
:account => 'Liabilities:Funds:Retirement Plan',
:commodity => '"B PGBL F10"',
:amount => "103.59",
:tags => '',
:xtn_month => Date.new(2011,8,1),
:xtn_year => Date.new(2011,1,1),
:virtual => true,
:xtn_id => 7288,
:cleared => false,
:cost => "442.33"
},
])
end
end
end
| ruby | MIT | ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60 | 2026-01-04T17:57:14.860475Z | false |
peterkeen/ledger-web | https://github.com/peterkeen/ledger-web/blob/ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60/test/report_spec.rb | test/report_spec.rb | require File.expand_path(File.dirname(__FILE__) + "/spec_helper")
require 'ledger_web/report'
require 'ledger_web/helpers'
describe LedgerWeb::Report do
describe "#from_query" do
let(:helpers) { TestHelper.new }
it "should run the query" do
LedgerWeb::Report.session = {:from => '2012/01/01', :to => '2012/01/01'}
load_fixture('small')
report = LedgerWeb::Report.from_query("select count(1) as foo from ledger")
rows = []
report.each do |row|
rows << row
end
rows[0][0].value.should eq(5)
rows[0][0].align.should eq('left')
end
it "should respect defaults" do
LedgerWeb::Report.params = {}
helpers.default('foo', 'bar')
report = LedgerWeb::Report.from_query("select :foo as foo")
rows = []
report.each do |row|
rows << row
end
rows[0][0].value.should eq("bar")
end
end
describe "#pivot" do
it "should create the correct fields" do
LedgerWeb::Report.session = {:from => '2012/01/01', :to => '2012/01/01'}
load_fixture('small')
report = LedgerWeb::Report.from_query("select xtn_month, account, sum(amount) from ledger group by xtn_month, account")
report = report.pivot("account", "asc")
report.fields.should eq([
'xtn_month',
'Assets:Checking',
'Assets:Savings',
'Equity:Opening Balances',
'Expenses:Lunch'
])
end
it "should put the values in the right place" do
LedgerWeb::Report.session = {:from => '2012/01/01', :to => '2012/01/01'}
load_fixture('small')
report = LedgerWeb::Report.from_query("select xtn_month, account, sum(amount)::integer from ledger group by xtn_month, account")
report = report.pivot("account", "asc")
report.rows[0].map(&:value).should eq(
[Date.new(2012,1,1), 190, 100, -300, 10]
)
end
it "should respect other date formats" do
LedgerWeb::Report.session = {:from => '2012-01-01', :to => '2012-01-01'}
load_fixture('small')
report = LedgerWeb::Report.from_query("select xtn_month, account, sum(amount)::integer from ledger group by xtn_month, account")
report = report.pivot("account", "asc")
report.rows[0].map(&:value).should eq(
[Date.new(2012,1,1), 190, 100, -300, 10]
)
end
end
end
| ruby | MIT | ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60 | 2026-01-04T17:57:14.860475Z | false |
peterkeen/ledger-web | https://github.com/peterkeen/ledger-web/blob/ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60/test/config_spec.rb | test/config_spec.rb | require File.expand_path(File.dirname(__FILE__) + "/spec_helper")
require 'ledger_web/config'
describe LedgerWeb::Config do
describe "#initialize" do
it "should get and set simple values" do
conf = LedgerWeb::Config.new do |config|
config.set :key_one, "value one"
config.set :key_two, "value two"
end
conf.get(:key_one).should eq("value one")
conf.get(:key_two).should eq("value two")
end
it "should get and run simple hooks" do
conf = LedgerWeb::Config.new do |config|
config.add_hook :sample do |val|
val[:foo] = val[:foo] * 2
end
end
test_val = { :foo => 2 }
conf.run_hooks(:sample, test_val)
test_val[:foo].should eq(4)
end
end
describe "#override_with" do
it "should override keys" do
conf_one = LedgerWeb::Config.new do |config|
config.set :key_one, "value one"
end
conf_two = LedgerWeb::Config.new do |config|
config.set :key_one, "value two"
end
conf_one.override_with(conf_two)
conf_one.get(:key_one).should eq("value two")
end
it "should append hooks" do
conf_one = LedgerWeb::Config.new do |config|
config.add_hook(:sample) do |val|
val[:list] << 'one'
end
end
conf_two = LedgerWeb::Config.new do |config|
config.add_hook(:sample) do |val|
val[:list] << 'two'
end
end
conf_one.override_with(conf_two)
test_val = {:list => []}
conf_one.run_hooks(:sample, test_val)
test_val[:list].should eq(['one', 'two'])
end
end
end
| ruby | MIT | ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60 | 2026-01-04T17:57:14.860475Z | false |
peterkeen/ledger-web | https://github.com/peterkeen/ledger-web/blob/ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60/test/spec_helper.rb | test/spec_helper.rb | $:.unshift(File.join(File.dirname(__FILE__), "..", "lib"))
require 'rspec'
require 'ledger_web/config'
require 'ledger_web/db'
require 'ledger_web/report'
require 'ledger_web/helpers'
require 'database_cleaner'
RSpec.configure do |config|
config.before(:suite) do
system 'createdb ledger-test'
LedgerWeb::Config.should_load_user_config = false
LedgerWeb::Config.instance.set :database_url, 'postgres://localhost/ledger-test'
LedgerWeb::Database.connect
LedgerWeb::Database.run_migrations
DatabaseCleaner.strategy = :truncation
DatabaseCleaner.clean_with(:truncation)
end
config.before(:each) do
DatabaseCleaner.start
end
config.after(:each) do
DatabaseCleaner.clean
end
config.after(:suite) do
LedgerWeb::Database.close
system 'dropdb ledger-test'
end
end
def set_config(key, val)
LedgerWeb::Config.instance.set key, val
end
def fixture(name)
File.join(File.dirname(__FILE__), "fixtures", name + ".dat")
end
def convert_bd_to_string(objs)
objs.map do |obj|
obj.each do |k,v|
if v.is_a? BigDecimal
obj[k] = v.truncate(2).to_s('F')
end
end
obj
end
end
def load_fixture(name)
set_config :ledger_file, fixture(name)
file = LedgerWeb::Database.dump_ledger_to_csv
LedgerWeb::Database.load_database(file)
end
def field(name, type, css_class)
LedgerWeb::Field.new(name, type, css_class)
end
def string_field(name)
field(name, 'string', 'pull-left')
end
def number_field(name)
field(name, 'number', 'pull-right')
end
class TestHelper
include LedgerWeb::Helpers
end
| ruby | MIT | ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60 | 2026-01-04T17:57:14.860475Z | false |
peterkeen/ledger-web | https://github.com/peterkeen/ledger-web/blob/ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60/lib/ledger_web.rb | lib/ledger_web.rb | libdir = File.dirname(__FILE__)
$LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir)
require 'ledger_web/price_lookup'
require 'ledger_web/config'
require 'ledger_web/db'
require 'ledger_web/report'
require 'ledger_web/table'
require 'ledger_web/decorators'
require 'ledger_web/watcher'
require 'ledger_web/helpers'
require 'ledger_web/app'
| ruby | MIT | ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60 | 2026-01-04T17:57:14.860475Z | false |
peterkeen/ledger-web | https://github.com/peterkeen/ledger-web/blob/ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60/lib/ledger_web/report.rb | lib/ledger_web/report.rb | module LedgerWeb
class Cell
attr_reader :title, :value, :style
attr_accessor :text, :align
def initialize(title, value)
@title = title
@value = value
@style = {}
@text = value
@align = 'left'
end
end
class Report
attr_accessor :error, :fields, :rows
@@session = {}
@@params = {}
def self.session=(session)
@@session = session
end
def self.session
@@session
end
def self.params=(params)
@@params = params
end
def self.params
@@params
end
def self.from_query(query)
params = {
:from => Report.session[:from],
:to => Report.session[:to]
}
@@params.each do |key, val|
params[key.to_sym] = val
end
ds = LedgerWeb::Database.handle.fetch(query, params)
report = self.new
begin
fields_added = false
ds.each do |row|
vals = []
unless fields_added
ds.columns.each do |col|
report.add_field col.to_s
end
fields_added = true
end
ds.columns.each do |col|
vals << Cell.new(col.to_s, row[col])
end
report.add_row(vals)
end
rescue Exception => e
report.error = e
end
if report.rows.length == 0 && report.error.nil?
report.error = "No data"
end
return report
end
def initialize
@fields = []
@rows = []
end
def add_field(field)
@fields << field
end
def add_row(row)
if row.length != @fields.length
raise "row length not equal to fields length"
end
@rows << row
end
def each
@rows.each do |row|
yield row
end
end
def pivot(column, sort_order)
new_report = self.class.new
bucket_column_index = 0
self.fields.each_with_index do |f, i|
if f == column
bucket_column_index = i
break
else
new_report.add_field(f)
end
end
buckets = {}
new_rows = {}
self.each do |row|
key = row[0, bucket_column_index].map { |r| r.value }
bucket_name = row[bucket_column_index].value
bucket_value = row[bucket_column_index + 1].value
if not buckets.has_key? bucket_name
buckets[bucket_name] = bucket_name
end
new_rows[key] ||= {}
new_rows[key][bucket_name] = bucket_value
end
bucket_keys = buckets.keys.sort
if sort_order && sort_order == 'desc'
bucket_keys = bucket_keys.reverse
end
bucket_keys.each do |bucket|
new_report.add_field(buckets[bucket])
end
new_rows.each do |key, value|
row = key.each_with_index.map { |k,i| Cell.new(new_report.fields[i], k) }
bucket_keys.each do |b|
row << Cell.new(b.to_s, value[b])
end
new_report.add_row(row)
end
return new_report
end
end
end
def find_all_reports
directories = LedgerWeb::Config.instance.get :report_directories
reports = {}
directories.each do |dir|
if File.directory? dir
Dir.glob(File.join(dir, "*.erb")) do |report|
basename = File.basename(report).gsub('.erb', '')
reports[basename] = 1
end
end
end
reports.keys.sort.map do |report|
name = report.split(/_/).map { |w| w.capitalize }.join(" ")
[report, name]
end
end
| ruby | MIT | ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60 | 2026-01-04T17:57:14.860475Z | false |
peterkeen/ledger-web | https://github.com/peterkeen/ledger-web/blob/ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60/lib/ledger_web/price_lookup.rb | lib/ledger_web/price_lookup.rb | require 'csv'
require 'uri'
require 'net/http'
module LedgerWeb
class YahooPriceLookup
def initialize(symbol, min_date, max_date)
@symbol = symbol.gsub(/"/,'')
@min_date = min_date
@max_date = max_date
end
def lookup
params = {
'a' => @min_date.month - 1,
'b' => @min_date.day,
'c' => @min_date.year,
'd' => @max_date.month - 1,
'e' => @max_date.day,
'f' => @max_date.year,
's' => @symbol,
'ignore' => '.csv',
}
query = params.map { |k,v| "#{k}=#{v}" }.join("&")
url = "https://ichart.finance.yahoo.com/table.csv?#{query}"
begin
response = RestClient.get(url)
rescue RestClient::Exception => e
puts "error retrieving #{url}: #{e.message}"
return []
end
if response.code != 200
return []
end
rows = []
CSV.parse(response.body, :headers => true) do |row|
rows << [Date.parse(row["Date"]), row["Close"].to_f]
end
rows
end
end
end
| ruby | MIT | ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60 | 2026-01-04T17:57:14.860475Z | false |
peterkeen/ledger-web | https://github.com/peterkeen/ledger-web/blob/ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60/lib/ledger_web/table.rb | lib/ledger_web/table.rb | module LedgerWeb
class Table
attr_reader :attributes, :hidden
def initialize(report)
@report = report
@decorators = []
@attributes = {}
@hidden = []
yield self if block_given?
end
def decorate decorator
@decorators << decorator
end
def hide regexp
@hidden << regexp
end
def clear_decorators
@decorators.clear
end
def link href
if_clause = href.delete(:if)
href[href.keys.first] = LedgerWeb::Decorators::LinkDecorator.new(href.values.first)
href[:if] = if_clause
@decorators << href
end
def render
body_rows = []
header_aligns = {}
@report.each do |row|
body_rows << row.each_with_index.map do |cell, cell_index|
@decorators.each do |decorator|
dec = decorator.dup
if_clause = dec.delete(:if)
matcher = dec.keys.first
next unless matcher == :all || cell.title =~ matcher
if if_clause
next unless if_clause.call(cell, row)
end
cell = dec[matcher].decorate(cell, row)
header_aligns[cell_index] = cell.align unless cell.nil?
end
if hidden.detect { |r| cell.title =~ r }
cell = nil
end
next if cell.nil?
style = cell.style.map { |key, val| "#{key}:#{val}"}.join(";")
%Q{<td style="#{style}"><span class="pull-#{cell.align}">#{cell.text}</span></td>}
end.compact.join("")
end
body = "<tbody>" + body_rows.map { |r| "<tr>#{r}</tr>" }.join("") + "</tbody>"
headers = @report.fields.each_with_index.map do |f,i|
next if hidden.detect { |r| f =~ r }
"<th><span class=\"pull-#{header_aligns[i] || 'left'}\">#{f}</span></th>"
end
header = "<thead><tr>" + headers.compact.join("") + "</tr></thead>"
attrs = attributes.map { |key,val| "#{key}=\"#{val}\"" }.join(" ")
"<table #{attrs}>#{header}#{body}</table>"
end
end
end
| ruby | MIT | ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60 | 2026-01-04T17:57:14.860475Z | false |
peterkeen/ledger-web | https://github.com/peterkeen/ledger-web/blob/ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60/lib/ledger_web/watcher.rb | lib/ledger_web/watcher.rb | require 'directory_watcher'
module LedgerWeb
class Watcher
def self.run!
directory = LedgerWeb::Config.instance.get :watch_directory
glob = "*"
if directory.nil?
directory = File.dirname(LedgerWeb::Config.instance.get :ledger_file)
glob = File.basename(LedgerWeb::Config.instance.get :ledger_file)
end
@@dw = DirectoryWatcher.new directory, :glob => glob
@@dw.interval = LedgerWeb::Config.instance.get :watch_interval
@@dw.stable = LedgerWeb::Config.instance.get :watch_stable_count
LedgerWeb::Database.connect
@@dw.add_observer do |*args|
args.each do |event|
if event.type == :stable
puts "Loading database"
LedgerWeb::Database.run_migrations
file = LedgerWeb::Database.dump_ledger_to_csv
count = LedgerWeb::Database.load_database(file)
puts "Loaded #{count} records"
end
end
end
@@dw.start
end
def self.stop!
@@dw.stop
end
end
end
| ruby | MIT | ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60 | 2026-01-04T17:57:14.860475Z | false |
peterkeen/ledger-web | https://github.com/peterkeen/ledger-web/blob/ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60/lib/ledger_web/version.rb | lib/ledger_web/version.rb | module LedgerWeb
VERSION = '1.5.2'
end
| ruby | MIT | ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60 | 2026-01-04T17:57:14.860475Z | false |
peterkeen/ledger-web | https://github.com/peterkeen/ledger-web/blob/ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60/lib/ledger_web/db.rb | lib/ledger_web/db.rb | require 'sequel'
require 'sequel/extensions/migration'
require 'csv'
require 'tempfile'
module LedgerWeb
class Database
def self.connect
@@db = Sequel.connect(LedgerWeb::Config.instance.get(:database_url))
self.run_migrations()
end
def self.close
@@db.disconnect
end
def self.handle
@@db
end
def self.run_migrations
Sequel::Migrator.apply(@@db, File.join(File.dirname(__FILE__), "db/migrate"))
user_migrations = LedgerWeb::Config.instance.get :user_migrate_dir
if not user_migrations.nil?
Sequel::Migrator.run(@@db, user_migrations, :table => "user_schema_changes")
end
end
def self.dump_ledger_to_csv
ledger_bin_path = LedgerWeb::Config.instance.get :ledger_bin_path
ledger_file = LedgerWeb::Config.instance.get :ledger_file
ledger_format = LedgerWeb::Config.instance.get :ledger_format
puts "Dumping ledger to file..."
file = Tempfile.new('ledger')
system "#{ledger_bin_path} -f #{ledger_file} --format='#{ledger_format}' reg > #{file.path}"
replaced_file = Tempfile.new('ledger')
replaced_file.write(file.read.gsub('\"', '""'))
replaced_file.flush
puts "Dump finished"
return replaced_file
end
def self.load_database(file)
counter = 0
@@db.transaction do
LedgerWeb::Config.instance.run_hooks(:before_load, @@db)
puts "Clearing ledger table...."
@@db[:ledger].truncate
puts "Done clearing ledger table"
puts "Loading into database...."
ledger_columns = LedgerWeb::Config.instance.get :ledger_columns
CSV.foreach(file.path) do |row|
counter += 1
row = Hash[*ledger_columns.zip(row).flatten]
xtn_date = Date.strptime(row[:xtn_date], '%Y/%m/%d')
row[:xtn_month] = xtn_date.strftime('%Y/%m/01')
row[:xtn_year] = xtn_date.strftime('%Y/01/01')
row[:cost] = parse_cost(row[:cost])
row = LedgerWeb::Config.instance.run_hooks(:before_insert_row, row)
@@db[:ledger].insert(row)
LedgerWeb::Config.instance.run_hooks(:after_insert_row, row)
end
puts "Running after_load hooks"
LedgerWeb::Config.instance.run_hooks(:after_load, @@db)
end
puts "Analyzing ledger table"
@@db.fetch('VACUUM ANALYZE ledger').all
puts "Done!"
counter
end
def self.parse_cost(cost)
match = cost.match(/([\d\.-]+) (.+) {(.+)} \[(.+)\]/)
if match
amount = match[1].to_f
price = match[3].gsub(/[^\d\.-]/, '').to_f
return price * amount
end
cost.gsub(/[^\d\.-]/, '')
end
def self.load_prices
query = <<HERE
select
commodity,
min_date,
case
when amount = 0 then max_date
else now()::date
end as max_date
from (
select
commodity,
min(xtn_date) as min_date,
max(xtn_date) as max_date,
sum(amount) as amount
from
ledger
group by
commodity
) x
HERE
puts " Deleting prices"
@@db[:prices].truncate
rows = @@db.fetch(query)
proc = LedgerWeb::Config.instance.get :price_function
skip = LedgerWeb::Config.instance.get :price_lookup_skip_symbols
puts "Loading prices"
rows.each do |row|
if skip.include?(row[:commodity])
next
end
prices = proc.call(row[:commodity], row[:min_date], row[:max_date])
prices.each do |price|
@@db[:prices].insert(:commodity => row[:commodity], :price_date => price[0], :price => price[1])
end
end
@@db.fetch("analyze prices").all
puts "Done loading prices"
end
end
end
| ruby | MIT | ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60 | 2026-01-04T17:57:14.860475Z | false |
peterkeen/ledger-web | https://github.com/peterkeen/ledger-web/blob/ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60/lib/ledger_web/helpers.rb | lib/ledger_web/helpers.rb | require 'rack/utils'
require 'time'
require 'cgi'
module LedgerWeb
module Helpers
include Rack::Utils
def partial (template, locals = {})
erb(template, :layout => false, :locals => locals)
end
def table(report, options = {})
Table.new(report) do |t|
t.decorate :all => LedgerWeb::Decorators::NumberDecorator.new
t.attributes[:class] = 'table table-striped table-hover table-bordered table-condensed'
yield t if block_given?
end.render
end
def query(options={}, &block)
q = capture(&block)
report = Report.from_query(q)
if options[:pivot]
report = report.pivot(options[:pivot], options[:pivot_sort_order])
end
return report
end
def expect(expected)
not_present = []
expected.each do |key|
if not params.has_key? key
not_present << key
end
end
if not_present.length > 0
raise "Missing params: #{not_present.join(', ')}"
end
end
def default(key, value)
if not Report.params.has_key? key
puts "Setting #{key} to #{value}"
Report.params[key] = value
end
end
def relative_time(start_time)
diff_seconds = Time.now.utc - start_time.utc
case diff_seconds
when 0 .. 59
return"#{diff_seconds.to_i} seconds ago"
when 60 .. (3600-1)
return "#{(diff_seconds/60).to_i} minutes ago"
when 3600 .. (3600*24-1)
return "#{(diff_seconds/3600).to_i} hours ago"
when (3600*24) .. (3600*24*30)
return "#{(diff_seconds/(3600*24)).to_i} days ago"
else
return start_time.strftime("%m/%d/%Y")
end
end
def visualization(report, options={}, &block)
vis = capture(&block)
@vis_count ||= 0
@vis_count += 1
@_out_buf.concat(
partial(
:visualization,
:report => report,
:visualization_code => vis,
:div_id => "vis_#{@vis_count}"
)
)
end
end
end
| ruby | MIT | ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60 | 2026-01-04T17:57:14.860475Z | false |
peterkeen/ledger-web | https://github.com/peterkeen/ledger-web/blob/ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60/lib/ledger_web/app.rb | lib/ledger_web/app.rb | require 'rubygems'
require 'sinatra/base'
require 'sinatra/contrib'
require 'sinatra/session'
require 'docverter'
module LedgerWeb
class Application < Sinatra::Base
register Sinatra::Session
set :session_secret, LedgerWeb::Config.instance.get(:session_secret)
set :session_expire, LedgerWeb::Config.instance.get(:session_expire)
set :reload_templates, true
helpers Sinatra::Capture
helpers LedgerWeb::Helpers
def find_template(views, name, engine, &block)
_views = LedgerWeb::Config.instance.get(:report_directories) + LedgerWeb::Config.instance.get(:additional_view_directories) + [File.join(File.dirname(__FILE__), 'views')]
Array(_views).each { |v| super(v, name, engine, &block) }
end
before do
if not session?
session_start!
today = Date.today
session[:from] = Date.new(today.year - 1, today.month, today.day).strftime("%Y/%m/%d")
session[:to] = today.strftime("%Y/%m/%d")
end
Report.session = session
Report.params = params
@reports = find_all_reports
end
post '/update-date-range' do
if params[:reset]
today = Date.today
session[:from] = Date.new(today.year - 1, today.month, today.day).strftime('%Y/%m/%d')
session[:to] = today.strftime('%Y/%m/%d')
else
session[:from] = Date.parse(params[:from]).strftime('%Y/%m/%d')
session[:to] = Date.parse(params[:to]).strftime('%Y/%m/%d')
end
redirect back
end
get '/reports/:name' do
begin
erb params[:name].to_sym
rescue Exception => e
@error = e
erb :error
end
end
get '/query' do
if params[:query] && params[:query] =~ /(insert|delete|drop|grant|create|commit|rollback)/i
raise 'Invalid query!'
end
if params[:csv]
report = Report.from_query(params[:query])
content_type 'text/csv'
return CSV.generate do |csv|
if !(params[:headers] == 'false')
csv << report.fields
end
report.each do |row|
csv << row.map(&:value)
end
end.to_s
end
erb :query
end
get '/pdf/:name' do
begin
res = Docverter::Conversion.run do |c|
c.from = 'html'
c.to = 'pdf'
c.content = erb(params[:name].to_sym, layout: :pdf)
end
content_type 'application/pdf'
return res
rescue Exception => e
@error = e
erb :error
end
end
get '/' do
index_report = LedgerWeb::Config.instance.get :index_report
if index_report
redirect "/reports/#{index_report.to_s}"
else
redirect '/help'
end
end
get '/help' do
erb :help
end
end
end
| ruby | MIT | ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60 | 2026-01-04T17:57:14.860475Z | false |
peterkeen/ledger-web | https://github.com/peterkeen/ledger-web/blob/ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60/lib/ledger_web/config.rb | lib/ledger_web/config.rb | module LedgerWeb
class Config
attr_reader :vars, :hooks
@@should_load_user_config = true
@@instance = nil
def self.should_load_user_config
@@should_load_user_config
end
def self.should_load_user_config=(val)
@@should_load_user_config = val
end
def initialize
@vars = {}
@hooks = {}
if block_given?
yield self
end
end
def set(key, value)
@vars[key] = value
end
def get(key)
@vars[key]
end
def add_hook(phase, &block)
_add_hook(phase, block)
end
def _add_hook(phase, hook)
@hooks[phase] ||= []
@hooks[phase] << hook
end
def run_hooks(phase, data)
if @hooks.has_key? phase
@hooks[phase].each do |hook|
hook.call(data)
end
end
return data
end
def override_with(config)
config.vars.each do |key, value|
set key, value
end
config.hooks.each do |phase, hooks|
hooks.each do |hook|
_add_hook phase, hook
end
end
end
def load_user_config(user_dir)
if LedgerWeb::Config.should_load_user_config && File.directory?(user_dir)
if File.directory? "#{user_dir}/reports"
dirs = self.get(:report_directories)
dirs.unshift "#{user_dir}/reports"
self.set :report_directories, dirs
end
if File.directory? "#{user_dir}/migrate"
self.set :user_migrate_dir, "#{user_dir}/migrate"
end
if File.exists? "#{user_dir}/config.rb"
self.override_with(LedgerWeb::Config.from_file("#{user_dir}/config.rb"))
end
end
end
def self.from_file(filename)
File.open(filename) do |file|
return eval(file.read, nil, filename)
end
end
def self.instance
@@instance ||= LedgerWeb::Config.new do |config|
config.set :database_url, "postgres://localhost/ledger"
config.set :port, "9090"
config.set :ledger_file, ENV['LEDGER_FILE']
config.set :report_directories, ["#{File.dirname(__FILE__)}/reports"]
config.set :additional_view_directories, []
config.set :session_secret, 'SomethingSecretThisWayPassed'
config.set :session_expire, 60*60
config.set :watch_interval, 5
config.set :watch_stable_count, 3
config.set :ledger_bin_path, "ledger"
config.set :ledger_format, "%(quoted(xact.beg_line)),%(quoted(date)),%(quoted(payee)),%(quoted(account)),%(quoted(commodity)),%(quoted(quantity(scrub(display_amount)))),%(quoted(cleared)),%(quoted(virtual)),%(quoted(join(note | xact.note))),%(quoted(cost))\n"
config.set :ledger_columns, [ :xtn_id, :xtn_date, :note, :account, :commodity, :amount, :cleared, :virtual, :tags, :cost ]
config.set :price_lookup_skip_symbols, ['$']
func = Proc.new do |symbol, min_date, max_date|
LedgerWeb::YahooPriceLookup.new(symbol, min_date - 1, max_date).lookup
end
config.set :price_function, func
end
end
end
end
| ruby | MIT | ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60 | 2026-01-04T17:57:14.860475Z | false |
peterkeen/ledger-web | https://github.com/peterkeen/ledger-web/blob/ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60/lib/ledger_web/decorators.rb | lib/ledger_web/decorators.rb | require 'cgi'
module LedgerWeb::Decorators
class NumberDecorator
def initialize(precision=2)
@precision = precision
end
def decorate(cell, row)
if cell.value.is_a?(Numeric)
cell.align = 'right'
raw_number = sprintf("%0.#{@precision}f", cell.value)
number_with_commas = raw_number.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse
cell.text = number_with_commas
end
cell
end
end
class LinkDecorator
def initialize(href_pattern)
@href_pattern = href_pattern
end
def decorate(cell, row)
url = String.new(@href_pattern)
row.each_with_index do |c,i|
url.gsub!(":#{i}", CGI.escape(c.value.to_s))
end
url.gsub!(':title', CGI.escape(cell.title.to_s))
url.gsub!(':now', CGI.escape(DateTime.now.strftime('%Y-%m-%d')))
url.gsub!(':this', CGI.escape(cell.value.to_s))
prev_text = cell.text
cell.text = "<a href=\"#{url}\">#{cell.text}</a>"
cell
end
end
class IconDecorator
def initialize(icon)
@icon = icon
end
def decorate(cell, row)
cell.text = "<i class=\"icon-#{@icon}\"></i>"
cell
end
end
class HighlightDecorator
def initialize(color)
@color = color
end
def decorate(cell, row)
cell.style['background-color'] = @color
cell
end
end
end
| ruby | MIT | ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60 | 2026-01-04T17:57:14.860475Z | false |
peterkeen/ledger-web | https://github.com/peterkeen/ledger-web/blob/ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60/lib/ledger_web/db/migrate/20120105185800_add_prices_table.rb | lib/ledger_web/db/migrate/20120105185800_add_prices_table.rb | Sequel.migration do
change do
create_table(:prices) do
Date :price_date
String :commodity, :text => true
BigDecimal :price
index [:price_date]
index [:commodity]
index [:price_date, :commodity]
end
end
end
| ruby | MIT | ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60 | 2026-01-04T17:57:14.860475Z | false |
peterkeen/ledger-web | https://github.com/peterkeen/ledger-web/blob/ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60/lib/ledger_web/db/migrate/20111226180900_initial_schema.rb | lib/ledger_web/db/migrate/20111226180900_initial_schema.rb | Sequel.migration do
up do
create_table(:ledger, :ignore_index_errors=>true) do
Date :xtn_date
String :checknum, :text=>true
String :note, :text=>true
String :account, :text=>true
String :commodity, :text=>true
BigDecimal :amount
String :tags, :text=>true
Date :xtn_month
Date :xtn_year
TrueClass :virtual
Integer :xtn_id
TrueClass :cleared
index [:account]
index [:commodity]
index [:note]
index [:tags]
index [:virtual]
index [:xtn_date]
index [:xtn_month]
index [:xtn_year]
end
create_table(:schema_info) do
String :filename, :text=>true, :null=>false
primary_key [:filename]
end
end
down do
drop_table(:ledger, :schema_info)
end
end
| ruby | MIT | ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60 | 2026-01-04T17:57:14.860475Z | false |
peterkeen/ledger-web | https://github.com/peterkeen/ledger-web/blob/ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60/lib/ledger_web/db/migrate/20111231132900_add_views.rb | lib/ledger_web/db/migrate/20111231132900_add_views.rb | Sequel.migration do
change do
create_or_replace_view(:accounts_days, <<HERE)
with
_a as (select account from ledger group by account),
_d as (select xtn_date from ledger group by xtn_date)
select
account,
xtn_date
from
_a cross join _d
HERE
create_or_replace_view(:accounts_months, <<HERE)
with
_a as (select account from ledger group by account),
_m as (select xtn_month from ledger group by xtn_month)
select
account,
xtn_month
from
_a cross join _m
HERE
create_or_replace_view(:accounts_years, <<HERE)
with
_a as (select account from ledger group by account),
_y as (select xtn_year from ledger group by xtn_year)
select
account,
xtn_year
from
_a cross join _y
HERE
end
end
| ruby | MIT | ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60 | 2026-01-04T17:57:14.860475Z | false |
peterkeen/ledger-web | https://github.com/peterkeen/ledger-web/blob/ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60/lib/ledger_web/db/migrate/20120104192400_add_cost_column.rb | lib/ledger_web/db/migrate/20120104192400_add_cost_column.rb | Sequel.migration do
change do
alter_table :ledger do
add_column :cost, BigDecimal
end
end
end
| ruby | MIT | ceb3cf0f1e4ae982b1d8048b8a6cf0c665744d60 | 2026-01-04T17:57:14.860475Z | false |
coorasse/passkit | https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/app/controllers/passkit/api/v1/passes_controller.rb | app/controllers/passkit/api/v1/passes_controller.rb | module Passkit
module Api
module V1
class PassesController < ActionController::API
before_action :decrypt_payload, only: :create
def create
set_generator
if @generator && @payload[:collection_name].present?
files = @generator.public_send(@payload[:collection_name]).collect do |collection_item|
Passkit::Factory.create_pass(@payload[:pass_class], collection_item)
end
file = Passkit::Generator.compress_passes_files(files)
send_file(file, type: 'application/vnd.apple.pkpasses', disposition: 'attachment')
else
file = Passkit::Factory.create_pass(@payload[:pass_class], @generator)
send_file(file, type: 'application/vnd.apple.pkpass', disposition: 'attachment')
end
end
# @return If request is authorized, returns HTTP status 200 with a payload of the pass data.
# @return If the request is not authorized, returns HTTP status 401.
# @return Otherwise, returns the appropriate standard HTTP status.
def show
authentication_token = request.headers["Authorization"]&.split(" ")&.last
unless authentication_token.present?
render json: {}, status: :unauthorized
return
end
pass = Pass.find_by(serial_number: params[:serial_number], authentication_token: authentication_token)
unless pass
render json: {}, status: :unauthorized
return
end
pass_output_path = Passkit::Generator.new(pass).generate_and_sign
response.headers["last-modified"] = pass.last_update.httpdate
if request.headers["If-Modified-Since"].nil? ||
(pass.last_update.to_i > Time.zone.parse(request.headers["If-Modified-Since"]).to_i)
send_file(pass_output_path, type: "application/vnd.apple.pkpass", disposition: "attachment")
else
head :not_modified
end
end
private
def decrypt_payload
@payload = Passkit::UrlEncrypt.decrypt(params[:payload])
if DateTime.parse(@payload[:valid_until]).past?
head :not_found
end
end
def set_generator
@generator = nil
return unless @payload[:generator_class].present? && @payload[:generator_id].present?
generator_class = @payload[:generator_class].constantize
@generator = generator_class.find(@payload[:generator_id])
end
end
end
end
end
| ruby | MIT | 83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f | 2026-01-04T17:57:15.346461Z | false |
coorasse/passkit | https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/app/controllers/passkit/api/v1/logs_controller.rb | app/controllers/passkit/api/v1/logs_controller.rb | module Passkit
module Api
module V1
class LogsController < ActionController::API
def create
params[:logs].each do |message|
Log.create!(content: message)
end
render json: {}, status: :ok
end
end
end
end
end
| ruby | MIT | 83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f | 2026-01-04T17:57:15.346461Z | false |
coorasse/passkit | https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/app/controllers/passkit/api/v1/registrations_controller.rb | app/controllers/passkit/api/v1/registrations_controller.rb | module Passkit
module Api
module V1
# TODO: check with authentication_token
# This Class Implements the Apple PassKit API
# @see Apple: https://developer.apple.com/library/archive/documentation/PassKit/Reference/PassKit_WebService/WebService.html
# @see Android: https://walletpasses.io/developer/
class RegistrationsController < ActionController::API
before_action :load_pass, only: %i[create destroy]
before_action :load_device, only: %i[show]
# @return If the serial number is already registered for this device, returns HTTP status 200.
# @return If registration succeeds, returns HTTP status 201.
# @return If the request is not authorized, returns HTTP status 401.
# @return Otherwise, returns the appropriate standard HTTP status.
def create
if @pass.devices.find_by(identifier: params[:device_id])
render json: {}, status: :ok
return
end
register_device
render json: {}, status: :created
end
# @return If there are matching passes, returns HTTP status 200
# with a JSON dictionary with the following keys and values:
# lastUpdated (string): The current modification tag.
# serialNumbers (array of strings): The serial numbers of the matching passes.
# @return If there are no matching passes, returns HTTP status 204.
# @return Otherwise, returns the appropriate standard HTTP status
def show
if @device.nil?
render json: {}, status: :not_found
return
end
passes = fetch_registered_passes
if passes.none?
render json: {}, status: :no_content
return
end
render json: updatable_passes(passes).to_json
end
# @return If disassociation succeeds, returns HTTP status 200.
# @return If the request is not authorized, returns HTTP status 401.
# @return Otherwise, returns the appropriate standard HTTP status.
def destroy
registrations = @pass.registrations.where(passkit_device_id: params[:device_id])
registrations.delete_all
render json: {}, status: :ok
end
private
def load_pass
authentication_token = request.headers["Authorization"]&.split(" ")&.last
unless authentication_token.present?
render json: {}, status: :unauthorized
return
end
@pass = Pass.find_by(serial_number: params[:serial_number], authentication_token: authentication_token)
unless @pass
render json: {}, status: :unauthorized
end
end
def load_device
@device = Passkit::Device.find_by(identifier: params[:device_id])
end
def register_device
device = Passkit::Device.find_or_create_by!(identifier: params[:device_id]) { |d| d.push_token = push_token }
@pass.registrations.create!(device: device)
end
def fetch_registered_passes
passes = @device.passes
if params[:passesUpdatedSince]&.present?
passes.all.filter { |a| a.last_update >= Date.parse(params[:passesUpdatedSince]) }
else
passes
end
end
def updatable_passes(passes)
{lastUpdated: Time.zone.now, serialNumbers: passes.pluck(:serial_number)}
end
# TODO: add authentication_token
# The value is the word ApplePass, followed by a space
# The value is the word AndroidPass (instead of ApplePass), followed by a space
def authentication_token
""
end
def push_token
return unless request&.body
request.body.rewind
json_body = JSON.parse(request.body.read)
json_body["pushToken"]
end
end
end
end
end
| ruby | MIT | 83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f | 2026-01-04T17:57:15.346461Z | false |
coorasse/passkit | https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/app/controllers/passkit/dashboard/passes_controller.rb | app/controllers/passkit/dashboard/passes_controller.rb | module Passkit
module Dashboard
class PassesController < ApplicationController
def index
@passes = Passkit::Pass.order(created_at: :desc).includes(:devices).first(100)
end
end
end
end
| ruby | MIT | 83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f | 2026-01-04T17:57:15.346461Z | false |
coorasse/passkit | https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/app/controllers/passkit/dashboard/logs_controller.rb | app/controllers/passkit/dashboard/logs_controller.rb | module Passkit
module Dashboard
class LogsController < ApplicationController
def index
@logs = Passkit::Log.order(created_at: :desc).first(100)
end
end
end
end
| ruby | MIT | 83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f | 2026-01-04T17:57:15.346461Z | false |
coorasse/passkit | https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/app/controllers/passkit/dashboard/previews_controller.rb | app/controllers/passkit/dashboard/previews_controller.rb | module Passkit
module Dashboard
class PreviewsController < ApplicationController
def index
end
def show
builder = Passkit.configuration.available_passes[params[:class_name]]
path = Factory.create_pass(params[:class_name].constantize, builder.call)
send_file path, type: "application/vnd.apple.pkpass", disposition: "attachment", filename: "pass.pkpass"
end
end
end
end
| ruby | MIT | 83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f | 2026-01-04T17:57:15.346461Z | false |
coorasse/passkit | https://github.com/coorasse/passkit/blob/83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f/app/controllers/passkit/dashboard/application_controller.rb | app/controllers/passkit/dashboard/application_controller.rb | module Passkit
module Dashboard
class ApplicationController < ActionController::Base
layout "passkit/application"
before_action :_authenticate_dashboard!
private
def _authenticate_dashboard!
instance_eval(&Passkit.configuration.authenticate_dashboard_with)
end
end
end
end
| ruby | MIT | 83c9c8ddcf6a7c8b1aa6a971f9c0dc02aef8323f | 2026-01-04T17:57:15.346461Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.