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/scheduler/job.rb | lib/puppet/scheduler/job.rb | # frozen_string_literal: true
module Puppet::Scheduler
class Job
attr_reader :run_interval
attr_accessor :last_run
attr_accessor :start_time
def initialize(run_interval, &block)
self.run_interval = run_interval
@last_run = nil
@run_proc = block
@enabled = true
end
def run_interval=(interval)
@run_interval = [interval, 0].max
end
def ready?(time)
if @last_run
@last_run + @run_interval <= time
else
true
end
end
def enabled?
@enabled
end
def enable
@enabled = true
end
def disable
@enabled = false
end
def interval_to_next_from(time)
if ready?(time)
0
else
@run_interval - (time - @last_run)
end
end
def run(now)
@last_run = now
if @run_proc
@run_proc.call(self)
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/plugins/syntax_checkers.rb | lib/puppet/plugins/syntax_checkers.rb | # frozen_string_literal: true
module Puppet::Plugins
module SyntaxCheckers
# The lookup **key** for the multibind containing syntax checkers used to syntax check embedded string in non
# puppet DSL syntax.
# @api public
SYNTAX_CHECKERS_KEY = :'puppet::syntaxcheckers'
# SyntaxChecker is a Puppet Extension Point for the purpose of extending Puppet with syntax checkers.
# The intended use is to create a class derived from this class and then register it with the Puppet context
#
# Creating the Extension Class
# ----------------------------
# As an example, a class for checking custom xml (aware of some custom schemes) may be authored in
# say a puppet module called 'exampleorg/xmldata'. The name of the class should start with `Puppetx::<user>::<module>`,
# e.g. 'Puppetx::Exampleorg::XmlData::XmlChecker" and
# be located in `lib/puppetx/exampleorg/xml_data/xml_checker.rb`. The Puppet Binder will auto-load this file when it
# has a binding to the class `Puppetx::Exampleorg::XmlData::XmlChecker'
# The Ruby Module `Puppetx` is created by Puppet, the remaining modules should be created by the loaded logic - e.g.:
#
# @example Defining an XmlChecker
# module Puppetx::Exampleorg
# module XmlData
# class XmlChecker < Puppetx::Puppetlabs::SyntaxCheckers::SyntaxChecker
# def check(text, syntax_identifier, acceptor, location_hash)
# # do the checking
# end
# end
# end
# end
#
# Implementing the check method
# -----------------------------
# The implementation of the {#check} method should naturally perform syntax checking of the given text/string and
# produce found issues on the given `acceptor`. These can be warnings or errors. The method should return `false` if
# any warnings or errors were produced (it is up to the caller to check for error/warning conditions and report them
# to the user).
#
# Issues are reported by calling the given `acceptor`, which takes a severity (e.g. `:error`,
# or `:warning), an {Puppet::Pops::Issues::Issue} instance, and a {Puppet::Pops::Adapters::SourcePosAdapter}
# (which describes details about linenumber, position, and length of the problem area). Note that the
# `location_info` given to the check method holds information about the location of the string in its *container*
# (e.g. the source position of a Heredoc); this information can be used if more detailed information is not
# available, or combined if there are more details (relative to the start of the checked string).
#
# @example Reporting an issue
# # create an issue with a symbolic name (that can serve as a reference to more details about the problem),
# # make the name unique
# issue = Puppet::Pops::Issues::issue(:EXAMPLEORG_XMLDATA_ILLEGAL_XML) { "syntax error found in xml text" }
# source_pos = Puppet::Pops::Adapters::SourcePosAdapter.new()
# source_pos.line = info[:line] # use this if there is no detail from the used parser
# source_pos.pos = info[:pos] # use this pos if there is no detail from used parser
#
# # report it
# acceptor.accept(Puppet::Pops::Validation::Diagnostic.new(:error, issue, info[:file], source_pos, {}))
#
# There is usually a cap on the number of errors/warnings that are presented to the user, this is handled by the
# reporting logic, but care should be taken to not generate too many as the issues are kept in memory until
# the checker returns. The acceptor may set a limit and simply ignore issues past a certain (high) number of reported
# issues (this number is typically higher than the cap on issues reported to the user).
#
# The `syntax_identifier`
# -----------------------
# The extension makes use of a syntax identifier written in mime-style. This identifier can be something simple
# as 'xml', or 'json', but can also consist of several segments joined with '+' where the most specific syntax variant
# is placed first. When searching for a syntax checker; say for JSON having some special traits, say 'userdata', the
# author of the text may indicate this as the text having the syntax "userdata+json" - when a checker is looked up it is
# first checked if there is a checker for "userdata+json", if none is found, a lookup is made for "json" (since the text
# must at least be valid json). The given identifier is passed to the checker (to allow the same checker to check for
# several dialects/specializations).
#
# Use in Puppet DSL
# -----------------
# The Puppet DSL Heredoc support makes use of the syntax checker extension. A user of a
# heredoc can specify the syntax in the heredoc tag, e.g.`@(END:userdata+json)`.
#
#
# @abstract
#
class SyntaxChecker
# Checks the text for syntax issues and reports them to the given acceptor.
# This implementation is abstract, it raises {NotImplementedError} since a subclass should have implemented the
# method.
#
# @param text [String] The text to check
# @param syntax_identifier [String] The syntax identifier in mime style (e.g. 'json', 'json-patch+json', 'xml', 'myapp+xml'
# @option location_info [String] :file The filename where the string originates
# @option location_info [Integer] :line The line number identifying the location where the string is being used/checked
# @option location_info [Integer] :position The position on the line identifying the location where the string is being used/checked
# @return [Boolean] Whether the checked string had issues (warnings and/or errors) or not.
# @api public
#
def check(text, syntax_identifier, acceptor, location_info)
raise NotImplementedError, "The class #{self.class.name} should have implemented the method check()"
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/plugins/configuration.rb | lib/puppet/plugins/configuration.rb | # frozen_string_literal: true
# Configures the Puppet Plugins, by registering extension points
# and default implementations.
#
# See the respective configured services for more information.
#
# @api private
#
module Puppet::Plugins
module Configuration
require_relative '../../puppet/plugins/syntax_checkers'
require_relative '../../puppet/syntax_checkers/base64'
require_relative '../../puppet/syntax_checkers/json'
require_relative '../../puppet/syntax_checkers/pp'
require_relative '../../puppet/syntax_checkers/epp'
def self.load_plugins
# Register extensions
# -------------------
{
SyntaxCheckers::SYNTAX_CHECKERS_KEY => {
'json' => Puppet::SyntaxCheckers::Json.new,
'base64' => Puppet::SyntaxCheckers::Base64.new,
'pp' => Puppet::SyntaxCheckers::PP.new,
'epp' => Puppet::SyntaxCheckers::EPP.new
}
}
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/feature/libuser.rb | lib/puppet/feature/libuser.rb | # frozen_string_literal: true
require_relative '../../puppet/util/feature'
require_relative '../../puppet/util/libuser'
Puppet.features.add(:libuser) {
File.executable?("/usr/sbin/lgroupadd") and
File.executable?("/usr/sbin/luseradd") and
Puppet::FileSystem.exist?(Puppet::Util::Libuser.getconf)
}
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/feature/hiera_eyaml.rb | lib/puppet/feature/hiera_eyaml.rb | # frozen_string_literal: true
require_relative '../../puppet/util/feature'
Puppet.features.add(:hiera_eyaml, :libs => ['hiera/backend/eyaml/parser/parser'])
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/feature/eventlog.rb | lib/puppet/feature/eventlog.rb | # frozen_string_literal: true
require_relative '../../puppet/util/feature'
if Puppet::Util::Platform.windows?
Puppet.features.add(:eventlog)
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/feature/cfpropertylist.rb | lib/puppet/feature/cfpropertylist.rb | # frozen_string_literal: true
require_relative '../../puppet/util/feature'
Puppet.features.add(:cfpropertylist, :libs => ['cfpropertylist'])
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/feature/msgpack.rb | lib/puppet/feature/msgpack.rb | # frozen_string_literal: true
require_relative '../../puppet/util/feature'
Puppet.features.add(:msgpack, :libs => ["msgpack"])
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/feature/selinux.rb | lib/puppet/feature/selinux.rb | # frozen_string_literal: true
require_relative '../../puppet/util/feature'
Puppet.features.add(:selinux, :libs => ["selinux"])
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/feature/ssh.rb | lib/puppet/feature/ssh.rb | # frozen_string_literal: true
require_relative '../../puppet/util/feature'
Puppet.features.add(:ssh, :libs => %(net/ssh))
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/feature/base.rb | lib/puppet/feature/base.rb | # frozen_string_literal: true
require_relative '../../puppet/util/feature'
# Add the simple features, all in one file.
# Order is important as some features depend on others
# We have a syslog implementation
Puppet.features.add(:syslog, :libs => ["syslog"])
# We can use POSIX user functions
Puppet.features.add(:posix) do
require 'etc'
!Etc.getpwuid(0).nil? && Puppet.features.syslog?
end
# We can use Microsoft Windows functions
Puppet.features.add(:microsoft_windows) { Puppet::Util::Platform.windows? }
raise Puppet::Error, _("Cannot determine basic system flavour") unless Puppet.features.posix? or Puppet.features.microsoft_windows?
# We've got LDAP available.
Puppet.features.add(:ldap, :libs => ["ldap"])
# We have the Rdoc::Usage library.
Puppet.features.add(:usage, :libs => %w[rdoc/ri/ri_paths rdoc/usage])
# We have libshadow, useful for managing passwords.
Puppet.features.add(:libshadow, :libs => ["shadow"])
# We're running as root.
Puppet.features.add(:root) do
require_relative '../../puppet/util/suidmanager'
Puppet::Util::SUIDManager.root?
end
# We have lcs diff
Puppet.features.add :diff, :libs => %w[diff/lcs diff/lcs/hunk]
# We have OpenSSL
Puppet.features.add(:openssl, :libs => ["openssl"])
# We have sqlite
Puppet.features.add(:sqlite, :libs => ["sqlite3"])
# We have Hiera
Puppet.features.add(:hiera, :libs => ["hiera"])
Puppet.features.add(:minitar, :libs => ["minitar"])
# We can manage symlinks
Puppet.features.add(:manages_symlinks) do
if !Puppet::Util::Platform.windows?
true
else
module WindowsSymlink
require 'ffi'
extend FFI::Library
def self.is_implemented # rubocop:disable Naming/PredicatePrefix
ffi_lib :kernel32
attach_function :CreateSymbolicLinkW, [:lpwstr, :lpwstr, :dword], :boolean
true
rescue LoadError
Puppet.debug { "CreateSymbolicLink is not available" }
false
end
end
WindowsSymlink.is_implemented
end
end
Puppet.features.add(:puppetserver_ca, libs: ['puppetserver/ca', 'puppetserver/ca/action/clean'])
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/feature/telnet.rb | lib/puppet/feature/telnet.rb | # frozen_string_literal: true
require_relative '../../puppet/util/feature'
Puppet.features.add(:telnet, :libs => %(net/telnet))
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/feature/bolt.rb | lib/puppet/feature/bolt.rb | # frozen_string_literal: true
require_relative '../../puppet/util/feature'
Puppet.features.add(:bolt, :libs => ['bolt'])
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/feature/pe_license.rb | lib/puppet/feature/pe_license.rb | # frozen_string_literal: true
require_relative '../../puppet/util/feature'
# Is the pe license library installed providing the ability to read licenses.
Puppet.features.add(:pe_license, :libs => %(pe_license))
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/feature/pson.rb | lib/puppet/feature/pson.rb | # frozen_string_literal: true
require_relative '../../puppet/util/feature'
# PSON is deprecated, use JSON instead
Puppet.features.add(:pson, :libs => ['puppet/external/pson'])
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/feature/hocon.rb | lib/puppet/feature/hocon.rb | # frozen_string_literal: true
require_relative '../../puppet/util/feature'
Puppet.features.add(:hocon, :libs => ['hocon'])
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/feature/dbus.rb | lib/puppet/feature/dbus.rb | # frozen_string_literal: true
require_relative '../../puppet/util/feature'
Puppet.features.add(:dbus, :libs => ['dbus'])
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/feature/zlib.rb | lib/puppet/feature/zlib.rb | # frozen_string_literal: true
require_relative '../../puppet/util/feature'
# We want this to load if possible, but it's not automatically
# required.
Puppet.features.add(:zlib, :libs => %(zlib))
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/reports/log.rb | lib/puppet/reports/log.rb | # frozen_string_literal: true
require_relative '../../puppet/reports'
Puppet::Reports.register_report(:log) do
desc "Send all received logs to the local log destinations. Usually
the log destination is syslog."
def process
logs.each do |log|
log.source = "//#{host}/#{log.source}"
Puppet::Util::Log.newmessage(log)
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/reports/store.rb | lib/puppet/reports/store.rb | # frozen_string_literal: true
require_relative '../../puppet'
require 'fileutils'
require_relative '../../puppet/util'
SEPARATOR = [Regexp.escape(File::SEPARATOR.to_s), Regexp.escape(File::ALT_SEPARATOR.to_s)].join
Puppet::Reports.register_report(:store) do
desc "Store the yaml report on disk. Each host sends its report as a YAML dump
and this just stores the file on disk, in the `reportdir` directory.
These files collect quickly -- one every half hour -- so it is a good idea
to perform some maintenance on them if you use this report (it's the only
default report)."
def process
validate_host(host)
dir = File.join(Puppet[:reportdir], host)
unless Puppet::FileSystem.exist?(dir)
FileUtils.mkdir_p(dir)
FileUtils.chmod_R(0o750, dir)
end
# Now store the report.
now = Time.now.gmtime
name = %w[year month day hour min].collect do |method|
# Make sure we're at least two digits everywhere
"%02d" % now.send(method).to_s
end.join("") + ".yaml"
file = File.join(dir, name)
begin
Puppet::FileSystem.replace_file(file, 0o640) do |fh|
fh.print to_yaml
end
rescue => detail
Puppet.log_exception(detail, "Could not write report for #{host} at #{file}: #{detail}")
end
# Only testing cares about the return value
file
end
# removes all reports for a given host?
def self.destroy(host)
validate_host(host)
dir = File.join(Puppet[:reportdir], host)
if Puppet::FileSystem.exist?(dir)
Dir.entries(dir).each do |file|
next if ['.', '..'].include?(file)
file = File.join(dir, file)
Puppet::FileSystem.unlink(file) if File.file?(file)
end
Dir.rmdir(dir)
end
end
def validate_host(host)
if host =~ Regexp.union(/[#{SEPARATOR}]/, /\A\.\.?\Z/)
raise ArgumentError, _("Invalid node name %{host}") % { host: host.inspect }
end
end
module_function :validate_host
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/reports/http.rb | lib/puppet/reports/http.rb | # frozen_string_literal: true
require_relative '../../puppet'
require_relative '../../puppet/network/http_pool'
require 'uri'
Puppet::Reports.register_report(:http) do
desc <<-DESC
Send reports via HTTP or HTTPS. This report processor submits reports as
POST requests to the address in the `reporturl` setting. When a HTTPS URL
is used, the remote server must present a certificate issued by the Puppet
CA or the connection will fail validation. The body of each POST request
is the YAML dump of a Puppet::Transaction::Report object, and the
Content-Type is set as `application/x-yaml`.
DESC
def process
url = URI.parse(Puppet[:reporturl])
headers = { "Content-Type" => "application/x-yaml" }
# This metric_id option is silently ignored by Puppet's http client
# (Puppet::Network::HTTP) but is used by Puppet Server's http client
# (Puppet::Server::HttpClient) to track metrics on the request made to the
# `reporturl` to store a report.
options = {
:metric_id => [:puppet, :report, :http],
:include_system_store => Puppet[:report_include_system_store],
}
# Puppet's http client implementation accepts userinfo in the URL
# but puppetserver's does not. So pass credentials explicitly.
if url.user && url.password
options[:basic_auth] = {
user: url.user,
password: url.password
}
end
client = Puppet.runtime[:http]
client.post(url, to_yaml, headers: headers, options: options) do |response|
unless response.success?
Puppet.err _("Unable to submit report to %{url} [%{code}] %{message}") % { url: Puppet[:reporturl].to_s, code: response.code, message: response.reason }
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/property/boolean.rb | lib/puppet/property/boolean.rb | # frozen_string_literal: true
require_relative '../../puppet/coercion'
class Puppet::Property::Boolean < Puppet::Property
def unsafe_munge(value)
Puppet::Coercion.boolean(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/property/ordered_list.rb | lib/puppet/property/ordered_list.rb | # frozen_string_literal: true
require_relative '../../puppet/property/list'
module Puppet
class Property
# This subclass of {Puppet::Property} manages an ordered list of values.
# The maintained order is the order defined by the 'current' set of values (i.e. the
# original order is not disrupted). Any additions are added after the current values
# in their given order).
#
# For an unordered list see {Puppet::Property::List}.
#
class OrderedList < List
def add_should_with_current(should, current)
if current.is_a?(Array)
# tricky trick
# Preserve all the current items in the list
# but move them to the back of the line
should += (current - should)
end
should
end
def dearrayify(array)
array.join(delimiter)
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/property/keyvalue.rb | lib/puppet/property/keyvalue.rb | # frozen_string_literal: true
require_relative '../../puppet/property'
module Puppet
class Property
# This subclass of {Puppet::Property} manages string key value pairs.
# In order to use this property:
#
# * the _should_ value must be an array of key-value pairs separated by the 'separator'
# * the retrieve method should return a hash with the keys as symbols
# @note **IMPORTANT**: In order for this property to work there must also be a 'membership' parameter
# The class that inherits from property should override that method with the symbol for the membership
# @todo The node with an important message is not very clear.
#
class KeyValue < Property
class << self
# This is a class-level variable that child properties can override
# if they wish.
attr_accessor :log_only_changed_or_new_keys
end
self.log_only_changed_or_new_keys = false
def hash_to_key_value_s(hash)
if self.class.log_only_changed_or_new_keys
hash = hash.select { |k, _| @changed_or_new_keys.include?(k) }
end
hash.map { |*pair| pair.join(separator) }.join(delimiter)
end
def should_to_s(should_value)
hash_to_key_value_s(should_value)
end
def is_to_s(current_value) # rubocop:disable Naming/PredicatePrefix
hash_to_key_value_s(current_value)
end
def membership
:key_value_membership
end
def inclusive?
@resource[membership] == :inclusive
end
def hashify_should
# Puppet casts all should values to arrays. Thus, if the user
# passed in a hash for our property's should value, the should_value
# parameter will be a single element array so we just extract our value
# directly.
if !@should.empty? && @should.first.is_a?(Hash)
return @should.first
end
# Here, should is an array of key/value pairs.
@should.each_with_object({}) do |key_value, hash|
tmp = key_value.split(separator)
hash[tmp[0].strip.intern] = tmp[1]
end
end
def process_current_hash(current)
return {} if current == :absent
# inclusive means we are managing everything so if it isn't in should, its gone
current.each_key { |key| current[key] = nil } if inclusive?
current
end
def should
return nil unless @should
members = hashify_should
current = process_current_hash(retrieve)
# shared keys will get overwritten by members
should_value = current.merge(members)
# Figure out the keys that will actually change in our Puppet run.
# This lets us reduce the verbosity of Puppet's logging for instances
# of this class when we want to.
#
# NOTE: We use ||= here because we only need to compute the
# changed_or_new_keys once (since this property will only be synced once).
#
@changed_or_new_keys ||= should_value.keys.select do |key|
!current.key?(key) || current[key] != should_value[key]
end
should_value
end
# @return [String] Returns a default separator of "="
def separator
"="
end
# @return [String] Returns a default delimiter of ";"
def delimiter
";"
end
# Retrieves the key-hash from the provider by invoking its method named the same as this property.
# @return [Hash] the hash from the provider, or `:absent`
#
def retrieve
# ok, some 'convention' if the keyvalue property is named properties, provider should implement a properties method
key_hash = provider.send(name) if provider
if key_hash && key_hash != :absent
key_hash
else
:absent
end
end
# Returns true if there is no _is_ value, else returns if _is_ is equal to _should_ using == as comparison.
# @return [Boolean] whether the property is in sync or not.
def insync?(is)
return true unless is
(is == should)
end
# We only accept an array of key/value pairs (strings), a single
# key/value pair (string) or a Hash as valid values for our property.
# Note that for an array property value, the 'value' passed into the
# block corresponds to the array element.
validate do |value|
unless value.is_a?(String) || value.is_a?(Hash)
raise ArgumentError, _("The %{name} property must be specified as a hash or an array of key/value pairs (strings)!") % { name: name }
end
next if value.is_a?(Hash)
unless value.include?(separator.to_s)
raise ArgumentError, _("Key/value pairs must be separated by '%{separator}'") % { separator: separator }
end
end
# The validate step ensures that our passed-in value is
# either a String or a Hash. If our value's a string,
# then nothing else needs to be done. Otherwise, we need
# to stringify the hash's keys and values to match our
# internal representation of the property's value.
munge do |value|
next value if value.is_a?(String)
munged_value = value.to_a.map! do |hash_key, hash_value|
[hash_key.to_s.strip.to_sym, hash_value.to_s]
end
munged_value.to_h
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/property/ensure.rb | lib/puppet/property/ensure.rb | # frozen_string_literal: true
require_relative '../../puppet/property'
# This property is automatically added to any {Puppet::Type} that responds
# to the methods 'exists?', 'create', and 'destroy'.
#
# Ensure defaults to having the wanted _(should)_ value `:present`.
#
# @api public
#
class Puppet::Property::Ensure < Puppet::Property
@name = :ensure
def self.defaultvalues
newvalue(:present) do
if @resource.provider and @resource.provider.respond_to?(:create)
@resource.provider.create
else
@resource.create
end
nil # return nil so the event is autogenerated
end
newvalue(:absent) do
if @resource.provider and @resource.provider.respond_to?(:destroy)
@resource.provider.destroy
else
@resource.destroy
end
nil # return nil so the event is autogenerated
end
defaultto do
if @resource.managed?
:present
else
nil
end
end
# This doc will probably get overridden
# rubocop:disable Naming/MemoizedInstanceVariableName
@doc ||= "The basic property that the resource should be in."
# rubocop:enable Naming/MemoizedInstanceVariableName
end
def self.inherited(sub)
# Add in the two properties that everyone will have.
sub.class_eval do
end
end
def change_to_s(currentvalue, newvalue)
if currentvalue == :absent || currentvalue.nil?
_("created")
elsif newvalue == :absent
_("removed")
else
_('%{name} changed %{is} to %{should}') % { name: name, is: is_to_s(currentvalue), should: should_to_s(newvalue) }
end
rescue Puppet::Error
raise
rescue => detail
raise Puppet::DevError, _("Could not convert change %{name} to string: %{detail}") % { name: name, detail: detail }, detail.backtrace
end
# Retrieves the _is_ value for the ensure property.
# The existence of the resource is checked by first consulting the provider (if it responds to
# `:exists`), and secondly the resource. A a value of `:present` or `:absent` is returned
# depending on if the managed entity exists or not.
#
# @return [Symbol] a value of `:present` or `:absent` depending on if it exists or not
# @raise [Puppet::DevError] if neither the provider nor the resource responds to `:exists`
#
def retrieve
# XXX This is a problem -- whether the object exists or not often
# depends on the results of other properties, yet we're the first property
# to get checked, which means that those other properties do not have
# @is values set. This seems to be the source of quite a few bugs,
# although they're mostly logging bugs, not functional ones.
prov = @resource.provider
if prov && prov.respond_to?(:exists?)
result = prov.exists?
elsif @resource.respond_to?(:exists?)
result = @resource.exists?
else
raise Puppet::DevError, _("No ability to determine if %{name} exists") % { name: @resource.class.name }
end
if result
:present
else
:absent
end
end
# If they're talking about the thing at all, they generally want to
# say it should exist.
# defaultto :present
defaultto do
if @resource.managed?
:present
else
nil
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/property/list.rb | lib/puppet/property/list.rb | # frozen_string_literal: true
require_relative '../../puppet/property'
module Puppet
class Property
# This subclass of {Puppet::Property} manages an unordered list of values.
# For an ordered list see {Puppet::Property::OrderedList}.
#
class List < Property
def is_to_s(currentvalue) # rubocop:disable Naming/PredicatePrefix
currentvalue == :absent ? super(currentvalue) : currentvalue.join(delimiter)
end
def membership
:membership
end
def add_should_with_current(should, current)
should += current if current.is_a?(Array)
should.uniq
end
def inclusive?
@resource[membership] == :inclusive
end
# dearrayify was motivated because to simplify the implementation of the OrderedList property
def dearrayify(array)
array.sort.join(delimiter)
end
def should
return nil unless @should
members = @should
# inclusive means we are managing everything so if it isn't in should, its gone
members = add_should_with_current(members, retrieve) unless inclusive?
dearrayify(members)
end
def delimiter
","
end
def retrieve
# ok, some 'convention' if the list property is named groups, provider should implement a groups method
tmp = provider.send(name) if provider
if tmp && tmp != :absent
tmp.instance_of?(Array) ? tmp : tmp.split(delimiter)
else
:absent
end
end
def prepare_is_for_comparison(is)
if is == :absent
is = []
end
dearrayify(is)
end
def insync?(is)
return true unless is
(prepare_is_for_comparison(is) == should)
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/datatypes/error.rb | lib/puppet/datatypes/error.rb | # frozen_string_literal: true
Puppet::DataTypes.create_type('Error') do
interface <<-PUPPET
type_parameters => {
kind => Optional[Variant[String,Regexp,Type[Enum],Type[Pattern],Type[NotUndef],Type[Undef]]],
issue_code => Optional[Variant[String,Regexp,Type[Enum],Type[Pattern],Type[NotUndef],Type[Undef]]]
},
attributes => {
msg => String[1],
kind => { type => Optional[String[1]], value => undef },
details => { type => Optional[Hash[String[1],Data]], value => undef },
issue_code => { type => Optional[String[1]], value => undef },
},
functions => {
message => Callable[[], String[1]]
}
PUPPET
require_relative '../../puppet/datatypes/impl/error'
implementation_class Puppet::DataTypes::Error
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/datatypes/impl/error.rb | lib/puppet/datatypes/impl/error.rb | # frozen_string_literal: true
class Puppet::DataTypes::Error
attr_reader :msg, :kind, :issue_code, :details
alias message msg
def self.from_asserted_hash(hash)
new(hash['msg'], hash['kind'], hash['details'], hash['issue_code'])
end
def _pcore_init_hash
result = { 'msg' => @msg }
result['kind'] = @kind unless @kind.nil?
result['details'] = @details unless @details.nil?
result['issue_code'] = @issue_code unless @issue_code.nil?
result
end
def initialize(msg, kind = nil, details = nil, issue_code = nil)
@msg = msg
@kind = kind
@details = details
@issue_code = issue_code
end
def eql?(o)
self.class.equal?(o.class) &&
@msg == o.msg &&
@kind == o.kind &&
@issue_code == o.issue_code &&
@details == o.details
end
alias == eql?
def hash
@msg.hash ^ @kind.hash ^ @issue_code.hash
end
def to_s
Puppet::Pops::Types::StringConverter.singleton.convert(self)
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_system/uniquefile.rb | lib/puppet/file_system/uniquefile.rb | # frozen_string_literal: true
require 'English'
require_relative '../../puppet/file_system'
require 'delegate'
require 'tmpdir'
# A class that provides `Tempfile`-like capabilities, but does not attempt to
# manage the deletion of the file for you. API is identical to the
# normal `Tempfile` class.
#
# @api public
class Puppet::FileSystem::Uniquefile < DelegateClass(File)
# Convenience method which ensures that the file is closed and
# unlinked before returning
#
# @param identifier [String] additional part of generated pathname
# @yieldparam file [File] the temporary file object
# @return result of the passed block
# @api private
def self.open_tmp(identifier)
f = new(identifier)
yield f
ensure
if f
f.close!
end
end
def initialize(basename, *rest)
create_tmpname(basename, *rest) do |tmpname, _n, opts|
mode = File::RDWR | File::CREAT | File::EXCL
perm = 0o600
if opts
mode |= opts.delete(:mode) || 0
opts[:perm] = perm
perm = nil
else
opts = perm
end
self.class.locking(tmpname) do
@tmpfile = File.open(tmpname, mode, opts)
@tmpname = tmpname
end
@mode = mode & ~(File::CREAT | File::EXCL)
perm or opts.freeze
@opts = opts
end
super(@tmpfile)
end
# Opens or reopens the file with mode "r+".
def open
@tmpfile.close if @tmpfile
@tmpfile = File.open(@tmpname, @mode, @opts)
__setobj__(@tmpfile)
end
def _close
@tmpfile.close if @tmpfile
ensure
@tmpfile = nil
end
protected :_close
def close(unlink_now = false)
if unlink_now
close!
else
_close
end
end
def close!
_close
unlink
end
def unlink
return unless @tmpname
begin
File.unlink(@tmpname)
rescue Errno::ENOENT
rescue Errno::EACCES
# may not be able to unlink on Windows; just ignore
return
end
@tmpname = nil
end
alias delete unlink
# Returns the full path name of the temporary file.
# This will be nil if #unlink has been called.
def path
@tmpname
end
private
def make_tmpname(prefix_suffix, n)
case prefix_suffix
when String
prefix = prefix_suffix
suffix = ""
when Array
prefix = prefix_suffix[0]
suffix = prefix_suffix[1]
else
raise ArgumentError, _("unexpected prefix_suffix: %{value}") % { value: prefix_suffix.inspect }
end
t = Time.now.strftime("%Y%m%d")
path = "#{prefix}#{t}-#{$PROCESS_ID}-#{rand(0x100000000).to_s(36)}"
path << "-#{n}" if n
path << suffix
end
def create_tmpname(basename, *rest)
opts = try_convert_to_hash(rest[-1])
if opts
opts = opts.dup if rest.pop.equal?(opts)
max_try = opts.delete(:max_try)
opts = [opts]
else
opts = []
end
tmpdir, = *rest
tmpdir ||= tmpdir()
n = nil
begin
path = File.join(tmpdir, make_tmpname(basename, n))
yield(path, n, *opts)
rescue Errno::EEXIST
n ||= 0
n += 1
retry if !max_try or n < max_try
raise _("cannot generate temporary name using `%{basename}' under `%{tmpdir}'") % { basename: basename, tmpdir: tmpdir }
end
path
end
def try_convert_to_hash(h)
h.to_hash
rescue NoMethodError
nil
end
@@systmpdir ||= defined?(Etc.systmpdir) ? Etc.systmpdir : '/tmp'
def tmpdir
tmp = '.'
[ENV.fetch('TMPDIR', nil), ENV.fetch('TMP', nil), ENV.fetch('TEMP', nil), @@systmpdir, '/tmp'].each do |dir|
stat = File.stat(dir) if dir
begin
if stat && stat.directory? && stat.writable?
tmp = dir
break
end
rescue
nil
end
end
File.expand_path(tmp)
end
class << self
# yields with locking for +tmpname+ and returns the result of the
# block.
def locking(tmpname)
lock = tmpname + '.lock'
mkdir(lock)
yield
rescue Errno::ENOENT => e
ex = Errno::ENOENT.new("A directory component in #{lock} does not exist or is a dangling symbolic link")
ex.set_backtrace(e.backtrace)
raise ex
ensure
rmdir(lock) if Puppet::FileSystem.exist?(lock)
end
def mkdir(*args)
Dir.mkdir(*args)
end
def rmdir(*args)
Dir.rmdir(*args)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_system/memory_impl.rb | lib/puppet/file_system/memory_impl.rb | # frozen_string_literal: true
class Puppet::FileSystem::MemoryImpl
def initialize(*files)
@files = files + all_children_of(files)
end
def expand_path(path, dir_string = nil)
File.expand_path(path, dir_string)
end
def exist?(path)
path.exist?
end
def directory?(path)
path.directory?
end
def file?(path)
path.file?
end
def executable?(path)
path.executable?
end
def symlink?(path)
path.symlink?
end
def readlink(path)
path = path.path
link = find(path)
return Puppet::FileSystem::MemoryFile.a_missing_file(path) unless link
source = link.source_path
return Puppet::FileSystem::MemoryFile.a_missing_file(link) unless source
find(source) || Puppet::FileSystem::MemoryFile.a_missing_file(source)
end
def children(path)
path.children
end
def each_line(path, &block)
path.each_line(&block)
end
def pathname(path)
find(path) || Puppet::FileSystem::MemoryFile.a_missing_file(path)
end
def basename(path)
path.duplicate_as(File.basename(path_string(path)))
end
def path_string(object)
object.path
end
def read(path, opts = {})
handle = assert_path(path).handle
handle.read
end
def read_preserve_line_endings(path)
read(path)
end
def open(path, *args, &block)
handle = assert_path(path).handle
if block_given?
yield handle
else
handle
end
end
def assert_path(path)
if path.is_a?(Puppet::FileSystem::MemoryFile)
path
else
find(path) or raise ArgumentError, _("Unable to find registered object for %{path}") % { path: path.inspect }
end
end
private
def find(path)
@files.find { |file| file.path == path }
end
def all_children_of(files)
children = files.collect(&:children).flatten
if children.empty?
[]
else
children + all_children_of(children)
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_system/jruby.rb | lib/puppet/file_system/jruby.rb | # frozen_string_literal: true
require_relative '../../puppet/file_system/posix'
class Puppet::FileSystem::JRuby < Puppet::FileSystem::Posix
def unlink(*paths)
File.unlink(*paths)
rescue Errno::ENOENT
# JRuby raises ENOENT if the path doesn't exist or the parent directory
# doesn't allow execute/traverse. If it's the former, `stat` will raise
# ENOENT, if it's the later, it'll raise EACCES
# See https://github.com/jruby/jruby/issues/5617
stat(*paths)
end
def replace_file(path, mode = nil, &block)
# MRI Ruby rename checks if destination is a directory and raises, while
# JRuby removes the directory and replaces the file.
if directory?(path)
raise Errno::EISDIR, _("Is a directory: %{directory}") % { directory: path }
end
super
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_system/path_pattern.rb | lib/puppet/file_system/path_pattern.rb | # frozen_string_literal: true
require 'pathname'
require_relative '../../puppet/error'
module Puppet::FileSystem
class PathPattern
class InvalidPattern < Puppet::Error; end
DOTDOT = '..'
ABSOLUTE_UNIX = %r{^/}
ABSOLUTE_WINDOWS = /^[a-z]:/i
CURRENT_DRIVE_RELATIVE_WINDOWS = /^\\/
def self.relative(pattern)
RelativePathPattern.new(pattern)
end
def self.absolute(pattern)
AbsolutePathPattern.new(pattern)
end
class << self
protected :new
end
# @param prefix [AbsolutePathPattern] An absolute path pattern instance
# @return [AbsolutePathPattern] A new AbsolutePathPattern prepended with
# the passed prefix's pattern.
def prefix_with(prefix)
new_pathname = prefix.pathname + pathname
self.class.absolute(new_pathname.to_s)
end
def glob
Dir.glob(@pathstr)
end
def to_s
@pathstr
end
protected
attr_reader :pathname
private
def validate
if @pathstr.split(Pathname::SEPARATOR_PAT).any? { |f| f == DOTDOT }
raise(InvalidPattern, _("PathPatterns cannot be created with directory traversals."))
elsif @pathstr.match?(CURRENT_DRIVE_RELATIVE_WINDOWS)
raise(InvalidPattern, _("A PathPattern cannot be a Windows current drive relative path."))
end
end
def initialize(pattern)
begin
@pathname = Pathname.new(pattern.strip)
@pathstr = @pathname.to_s
rescue ArgumentError => error
raise InvalidPattern.new(_("PathPatterns cannot be created with a zero byte."), error)
end
validate
end
end
class RelativePathPattern < PathPattern
def absolute?
false
end
def validate
super
if @pathstr.match?(ABSOLUTE_WINDOWS)
raise(InvalidPattern, _("A relative PathPattern cannot be prefixed with a drive."))
elsif @pathstr.match?(ABSOLUTE_UNIX)
raise(InvalidPattern, _("A relative PathPattern cannot be an absolute path."))
end
end
end
class AbsolutePathPattern < PathPattern
def absolute?
true
end
def validate
super
if !@pathstr.match?(ABSOLUTE_UNIX) && !@pathstr.match?(ABSOLUTE_WINDOWS)
raise(InvalidPattern, _("An absolute PathPattern cannot be a relative path."))
end
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_system/file_impl.rb | lib/puppet/file_system/file_impl.rb | # frozen_string_literal: true
# Abstract implementation of the Puppet::FileSystem
#
class Puppet::FileSystem::FileImpl
def pathname(path)
path.is_a?(Pathname) ? path : Pathname.new(path)
end
def assert_path(path)
return path if path.is_a?(Pathname)
# Some paths are string, or in the case of WatchedFile, it pretends to be
# one by implementing to_str.
if path.respond_to?(:to_str)
Pathname.new(path)
else
raise ArgumentError, _("FileSystem implementation expected Pathname, got: '%{klass}'") % { klass: path.class }
end
end
def path_string(path)
path.to_s
end
def expand_path(path, dir_string = nil)
# ensure `nil` values behave like underlying File.expand_path
::File.expand_path(path.nil? ? nil : path_string(path), dir_string)
end
def open(path, mode, options, &block)
::File.open(path, options, mode, &block)
end
def dir(path)
path.dirname
end
def basename(path)
path.basename.to_s
end
def size(path)
path.size
end
def exclusive_create(path, mode, &block)
opt = File::CREAT | File::EXCL | File::WRONLY
self.open(path, mode, opt, &block)
end
def exclusive_open(path, mode, options = 'r', timeout = 300, &block)
wait = 0.001 + (Kernel.rand / 1000)
written = false
until written
::File.open(path, options, mode) do |rf|
if rf.flock(::File::LOCK_EX | ::File::LOCK_NB)
Puppet.debug { _("Locked '%{path}'") % { path: path } }
yield rf
written = true
Puppet.debug { _("Unlocked '%{path}'") % { path: path } }
else
Puppet.debug { "Failed to lock '%s' retrying in %.2f milliseconds" % [path, wait * 1000] }
sleep wait
timeout -= wait
wait *= 2
if timeout < 0
raise Timeout::Error, _("Timeout waiting for exclusive lock on %{path}") % { path: path }
end
end
end
end
end
def each_line(path, &block)
::File.open(path) do |f|
f.each_line do |line|
yield line
end
end
end
def read(path, opts = {})
path.read(**opts)
end
def read_preserve_line_endings(path)
default_encoding = Encoding.default_external.name
encoding = default_encoding.downcase.start_with?('utf-') ? "bom|#{default_encoding}" : default_encoding
read(path, encoding: encoding)
end
def binread(path)
raise NotImplementedError
end
def exist?(path)
::File.exist?(path)
end
def directory?(path)
::File.directory?(path)
end
def file?(path)
::File.file?(path)
end
def executable?(path)
::File.executable?(path)
end
def writable?(path)
path.writable?
end
def touch(path, mtime: nil)
::FileUtils.touch(path, mtime: mtime)
end
def mkpath(path)
path.mkpath
end
def children(path)
path.children
end
def symlink(path, dest, options = {})
FileUtils.symlink(path, dest, **options)
end
def symlink?(path)
::File.symlink?(path)
end
def readlink(path)
::File.readlink(path)
end
def unlink(*paths)
::File.unlink(*paths)
end
def stat(path)
::File.stat(path)
end
def lstat(path)
::File.lstat(path)
end
def compare_stream(path, stream)
::File.open(path, 0, 'rb') { |this| FileUtils.compare_stream(this, stream) }
end
def chmod(mode, path)
FileUtils.chmod(mode, path)
end
def replace_file(path, mode = nil)
begin
stat = lstat(path)
gid = stat.gid
uid = stat.uid
mode ||= stat.mode & 0o7777
rescue Errno::ENOENT
mode ||= 0o640
end
tempfile = Puppet::FileSystem::Uniquefile.new(Puppet::FileSystem.basename_string(path), Puppet::FileSystem.dir_string(path))
begin
begin
yield tempfile
tempfile.flush
tempfile.fsync
ensure
tempfile.close
end
tempfile_path = tempfile.path
FileUtils.chown(uid, gid, tempfile_path) if uid && gid
chmod(mode, tempfile_path)
::File.rename(tempfile_path, path_string(path))
ensure
tempfile.close!
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_system/posix.rb | lib/puppet/file_system/posix.rb | # frozen_string_literal: true
class Puppet::FileSystem::Posix < Puppet::FileSystem::FileImpl
def binread(path)
path.binread
end
# Provide an encoding agnostic version of compare_stream
#
# The FileUtils implementation in Ruby 2.0+ was modified in a manner where
# it cannot properly compare File and StringIO instances. To sidestep that
# issue this method reimplements the faster 2.0 version that will correctly
# compare binary File and StringIO streams.
def compare_stream(path, stream)
::File.open(path, 'rb') do |this|
bsize = stream_blksize(this, stream)
sa = String.new.force_encoding('ASCII-8BIT')
sb = String.new.force_encoding('ASCII-8BIT')
loop do
this.read(bsize, sa)
stream.read(bsize, sb)
return true if sa.empty? && sb.empty?
break if sa != sb
end
false
end
end
private
def stream_blksize(*streams)
streams.each do |s|
next unless s.respond_to?(:stat)
size = blksize(s.stat)
return size if size
end
default_blksize()
end
def blksize(st)
s = st.blksize
return nil unless s
return nil if s == 0
s
end
def default_blksize
1024
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_system/windows.rb | lib/puppet/file_system/windows.rb | # frozen_string_literal: true
require_relative '../../puppet/file_system/posix'
require_relative '../../puppet/util/windows'
class Puppet::FileSystem::Windows < Puppet::FileSystem::Posix
FULL_CONTROL = Puppet::Util::Windows::File::FILE_ALL_ACCESS
FILE_READ = Puppet::Util::Windows::File::FILE_GENERIC_READ
def open(path, mode, options, &block)
# PUP-6959 mode is explicitly ignored until it can be implemented
# Ruby on Windows uses mode for setting file attributes like read-only and
# archived, not for setting permissions like POSIX
raise TypeError, 'mode must be specified as an Integer' if mode && !mode.is_a?(Numeric)
::File.open(path, options, nil, &block)
end
def expand_path(path, dir_string = nil)
# ensure `nil` values behave like underlying File.expand_path
string_path = ::File.expand_path(path.nil? ? nil : path_string(path), dir_string)
# if no tildes, nothing to expand, no need to call Windows API, return original string
return string_path unless string_path.index('~')
begin
# no need to do existence check up front as GetLongPathName implies that check is performed
# and it should be the exception that files aren't actually present
string_path = Puppet::Util::Windows::File.get_long_pathname(string_path)
rescue Puppet::Util::Windows::Error => e
# preserve original File.expand_path behavior for file / path not found by returning string
raise if e.code != Puppet::Util::Windows::File::ERROR_FILE_NOT_FOUND &&
e.code != Puppet::Util::Windows::File::ERROR_PATH_NOT_FOUND
end
string_path
end
def exist?(path)
Puppet::Util::Windows::File.exist?(path)
end
def symlink(path, dest, options = {})
raise_if_symlinks_unsupported
dest_exists = exist?(dest) # returns false on dangling symlink
dest_stat = Puppet::Util::Windows::File.stat(dest) if dest_exists
# silent fail to preserve semantics of original FileUtils
return 0 if dest_exists && dest_stat.ftype == 'directory'
if dest_exists && dest_stat.ftype == 'file' && options[:force] != true
raise(Errno::EEXIST, _("%{dest} already exists and the :force option was not specified") % { dest: dest })
end
if options[:noop] != true
::File.delete(dest) if dest_exists # can only be file
Puppet::Util::Windows::File.symlink(path, dest)
end
0
end
def symlink?(path)
return false unless Puppet.features.manages_symlinks?
Puppet::Util::Windows::File.symlink?(path)
end
def readlink(path)
raise_if_symlinks_unsupported
Puppet::Util::Windows::File.readlink(path)
end
def unlink(*file_names)
unless Puppet.features.manages_symlinks?
return ::File.unlink(*file_names)
end
file_names.each do |file_name|
file_name = file_name.to_s # handle PathName
stat = begin
Puppet::Util::Windows::File.stat(file_name)
rescue
nil
end
# sigh, Ruby + Windows :(
if !stat
begin
::File.unlink(file_name)
rescue
Dir.rmdir(file_name)
end
elsif stat.ftype == 'directory'
if Puppet::Util::Windows::File.symlink?(file_name)
Dir.rmdir(file_name)
else
raise Errno::EPERM, file_name
end
else
::File.unlink(file_name)
end
end
file_names.length
end
def stat(path)
Puppet::Util::Windows::File.stat(path)
end
def lstat(path)
unless Puppet.features.manages_symlinks?
return Puppet::Util::Windows::File.stat(path)
end
Puppet::Util::Windows::File.lstat(path)
end
def chmod(mode, path)
Puppet::Util::Windows::Security.set_mode(mode, path.to_s)
end
def read_preserve_line_endings(path)
contents = path.read(:mode => 'rb', :encoding => 'bom|utf-8')
contents = path.read(:mode => 'rb', :encoding => "bom|#{Encoding.default_external.name}") unless contents.valid_encoding?
contents = path.read unless contents.valid_encoding?
contents
end
# https://docs.microsoft.com/en-us/windows/desktop/debug/system-error-codes--0-499-
FILE_NOT_FOUND = 2
ACCESS_DENIED = 5
SHARING_VIOLATION = 32
LOCK_VIOLATION = 33
def replace_file(path, mode = nil)
if directory?(path)
raise Errno::EISDIR, _("Is a directory: %{directory}") % { directory: path }
end
current_sid = Puppet::Util::Windows::SID.name_to_sid(Puppet::Util::Windows::ADSI::User.current_user_name)
current_sid ||= Puppet::Util::Windows::SID.name_to_sid(Puppet::Util::Windows::ADSI::User.current_sam_compatible_user_name)
dacl = case mode
when 0o644
dacl = secure_dacl(current_sid)
dacl.allow(Puppet::Util::Windows::SID::BuiltinUsers, FILE_READ)
dacl
when 0o660, 0o640, 0o600, 0o440
secure_dacl(current_sid)
when nil
get_dacl_from_file(path) || secure_dacl(current_sid)
else
raise ArgumentError, "#{mode} is invalid: Only modes 0644, 0640, 0660, and 0440 are allowed"
end
tempfile = Puppet::FileSystem::Uniquefile.new(Puppet::FileSystem.basename_string(path), Puppet::FileSystem.dir_string(path))
begin
tempdacl = Puppet::Util::Windows::AccessControlList.new
tempdacl.allow(current_sid, FULL_CONTROL)
set_dacl(tempfile.path, tempdacl)
begin
yield tempfile
tempfile.flush
tempfile.fsync
ensure
tempfile.close
end
set_dacl(tempfile.path, dacl) if dacl
::File.rename(tempfile.path, path_string(path))
ensure
tempfile.close!
end
rescue Puppet::Util::Windows::Error => e
case e.code
when ACCESS_DENIED, SHARING_VIOLATION, LOCK_VIOLATION
raise Errno::EACCES.new(path_string(path), e)
else
raise SystemCallError, e.message
end
end
private
def set_dacl(path, dacl)
sd = Puppet::Util::Windows::Security.get_security_descriptor(path)
new_sd = Puppet::Util::Windows::SecurityDescriptor.new(sd.owner, sd.group, dacl, true)
Puppet::Util::Windows::Security.set_security_descriptor(path, new_sd)
end
def secure_dacl(current_sid)
dacl = Puppet::Util::Windows::AccessControlList.new
[
Puppet::Util::Windows::SID::LocalSystem,
Puppet::Util::Windows::SID::BuiltinAdministrators,
current_sid
].uniq.map do |sid|
dacl.allow(sid, FULL_CONTROL)
end
dacl
end
def get_dacl_from_file(path)
sd = Puppet::Util::Windows::Security.get_security_descriptor(path_string(path))
sd.dacl
rescue Puppet::Util::Windows::Error => e
raise e unless e.code == FILE_NOT_FOUND
end
def raise_if_symlinks_unsupported
unless Puppet.features.manages_symlinks?
msg = _("This version of Windows does not support symlinks. Windows Vista / 2008 or higher is required.")
raise Puppet::Util::Windows::Error, msg
end
unless Puppet::Util::Windows::Process.process_privilege_symlink?
Puppet.warning _("The current user does not have the necessary permission to manage symlinks.")
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/file_system/memory_file.rb | lib/puppet/file_system/memory_file.rb | # frozen_string_literal: true
# An in-memory file abstraction. Commonly used with Puppet::FileSystem::File#overlay
# @api private
class Puppet::FileSystem::MemoryFile
attr_reader :path, :children
def self.a_missing_file(path)
new(path, :exist? => false, :executable? => false)
end
def self.a_missing_directory(path)
new(path,
:exist? => false,
:executable? => false,
:directory? => true)
end
def self.a_regular_file_containing(path, content)
new(path, :exist? => true, :executable? => false, :content => content)
end
def self.an_executable(path)
new(path, :exist? => true, :executable? => true)
end
def self.a_directory(path, children = [])
new(path,
:exist? => true,
:executable? => true,
:directory? => true,
:children => children)
end
def self.a_symlink(target_path, source_path)
new(target_path, :exist? => true, :symlink? => true, :source_path => source_path)
end
def initialize(path, properties)
@path = path
@properties = properties
@children = (properties[:children] || []).collect do |child|
child.duplicate_as(File.join(@path, child.path))
end
end
def directory?; @properties[:directory?]; end
def exist?; @properties[:exist?]; end
def executable?; @properties[:executable?]; end
def symlink?; @properties[:symlink?]; end
def source_path; @properties[:source_path]; end
def each_line(&block)
handle.each_line(&block)
end
def handle
raise Errno::ENOENT unless exist?
StringIO.new(@properties[:content] || '')
end
def duplicate_as(other_path)
self.class.new(other_path, @properties)
end
def absolute?
Pathname.new(path).absolute?
end
def to_path
path
end
def to_s
to_path
end
def inspect
"<Puppet::FileSystem::MemoryFile:#{self}>"
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/reference/report.rb | lib/puppet/reference/report.rb | # frozen_string_literal: true
require_relative '../../puppet/reports'
report = Puppet::Util::Reference.newreference :report, :doc => "All available transaction reports" do
Puppet::Reports.reportdocs
end
report.header = "
Puppet can generate a report after applying a catalog. This report includes
events, log messages, resource statuses, and metrics and metadata about the run.
Puppet agent sends its report to a Puppet master server, and Puppet apply
processes its own reports.
Puppet master and Puppet apply will handle every report with a set of report
processors, configurable with the `reports` setting in puppet.conf. This page
documents the built-in report processors.
See [About Reporting](https://puppet.com/docs/puppet/latest/reporting_about.html)
for more details.
"
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/reference/type.rb | lib/puppet/reference/type.rb | # frozen_string_literal: true
Puppet::Util::Reference.newreference :type, :doc => "All Puppet resource types and all their details" do
types = {}
Puppet::Type.loadall
Puppet::Type.eachtype { |type|
next if type.name == :component
next if type.name == :whit
types[type.name] = type
}
str = %{
## Resource Types
- The *namevar* is the parameter used to uniquely identify a type instance.
This is the parameter that gets assigned when a string is provided before
the colon in a type declaration. In general, only developers will need to
worry about which parameter is the `namevar`.
In the following code:
file { "/etc/passwd":
owner => "root",
group => "root",
mode => "0644"
}
`/etc/passwd` is considered the title of the file object (used for things like
dependency handling), and because `path` is the namevar for `file`, that
string is assigned to the `path` parameter.
- *Parameters* determine the specific configuration of the instance. They either
directly modify the system (internally, these are called properties) or they affect
how the instance behaves (e.g., adding a search path for `exec` instances or determining recursion on `file` instances).
- *Providers* provide low-level functionality for a given resource type. This is
usually in the form of calling out to external commands.
When required binaries are specified for providers, fully qualified paths
indicate that the binary must exist at that specific path and unqualified
binaries indicate that Puppet will search for the binary using the shell
path.
- *Features* are abilities that some providers might not support. You can use the list
of supported features to determine how a given provider can be used.
Resource types define features they can use, and providers can be tested to see
which features they provide.
}.dup
types.sort_by(&:to_s).each { |name, type|
str << "
----------------
"
str << markdown_header(name, 3)
str << scrub(type.doc) + "\n\n"
# Handle the feature docs.
featuredocs = type.featuredocs
if featuredocs
str << markdown_header("Features", 4)
str << featuredocs
end
docs = {}
type.validproperties.sort_by(&:to_s).reject { |sname|
property = type.propertybyname(sname)
property.nodoc
}.each { |sname|
property = type.propertybyname(sname)
raise _("Could not retrieve property %{sname} on type %{type_name}") % { sname: sname, type_name: type.name } unless property
doc = property.doc
unless doc
$stderr.puts _("No docs for %{type}[%{sname}]") % { type: type, sname: sname }
next
end
doc = doc.dup
tmp = doc
tmp = scrub(tmp)
docs[sname] = tmp
}
str << markdown_header("Parameters", 4) + "\n"
type.parameters.sort_by(&:to_s).each { |type_name, _param|
docs[type_name] = scrub(type.paramdoc(type_name))
}
additional_key_attributes = type.key_attributes - [:name]
docs.sort { |a, b|
a[0].to_s <=> b[0].to_s
}.each { |type_name, doc|
if additional_key_attributes.include?(type_name)
doc = "(**Namevar:** If omitted, this parameter's value defaults to the resource's title.)\n\n" + doc
end
str << markdown_definitionlist(type_name, doc)
}
str << "\n"
}
str
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/reference/providers.rb | lib/puppet/reference/providers.rb | # frozen_string_literal: true
providers = Puppet::Util::Reference.newreference :providers, :title => "Provider Suitability Report", :depth => 1, :dynamic => true, :doc => "Which providers are valid for this machine" do
types = []
Puppet::Type.loadall
Puppet::Type.eachtype do |klass|
next unless klass && klass.providers.length > 0
types << klass
end
types.sort! { |a, b| a.name.to_s <=> b.name.to_s }
command_line = Puppet::Util::CommandLine.new
types.reject! { |type| !command_line.args.include?(type.name.to_s) } unless command_line.args.empty?
ret = "Details about this host:\n\n".dup
# Throw some facts in there, so we know where the report is from.
ret << option('Ruby Version', Facter.value('ruby.version'))
ret << option('Puppet Version', Facter.value('puppetversion'))
ret << option('Operating System', Facter.value('os.name'))
ret << option('Operating System Release', Facter.value('os.release.full'))
ret << "\n"
count = 1
# Produce output for each type.
types.each do |type|
features = type.features
ret << "\n" # add a trailing newline
# Now build up a table of provider suitability.
headers = %w[Provider Suitable?] + features.collect(&:to_s).sort
table_data = {}
notes = []
default = type.defaultprovider ? type.defaultprovider.name : 'none'
type.providers.sort_by(&:to_s).each do |pname|
data = []
table_data[pname] = data
provider = type.provider(pname)
# Add the suitability note
missing = provider.suitable?(false)
if missing && missing.empty?
data << "*X*"
suit = true
else
data << "[#{count}]_" # A pointer to the appropriate footnote
suit = false
end
# Add a footnote with the details about why this provider is unsuitable, if that's the case
unless suit
details = ".. [#{count}]\n"
missing.each do |test, values|
case test
when :exists
details << _(" - Missing files %{files}\n") % { files: values.join(", ") }
when :variable
values.each do |name, facts|
if Puppet.settings.valid?(name)
details << _(" - Setting %{name} (currently %{value}) not in list %{facts}\n") % { name: name, value: Puppet.settings.value(name).inspect, facts: facts.join(", ") }
else
details << _(" - Fact %{name} (currently %{value}) not in list %{facts}\n") % { name: name, value: Puppet.runtime[:facter].value(name).inspect, facts: facts.join(", ") }
end
end
when :true
details << _(" - Got %{values} true tests that should have been false\n") % { values: values }
when :false
details << _(" - Got %{values} false tests that should have been true\n") % { values: values }
when :feature
details << _(" - Missing features %{values}\n") % { values: values.collect(&:to_s).join(",") }
end
end
notes << details
count += 1
end
# Add a note for every feature
features.each do |feature|
if provider.features.include?(feature)
data << "*X*"
else
data << ""
end
end
end
ret << markdown_header(type.name.to_s + "_", 2)
ret << "[#{type.name}](https://puppet.com/docs/puppet/latest/type.html##{type.name})\n\n"
ret << option("Default provider", default)
ret << doctable(headers, table_data)
notes.each do |note|
ret << note + "\n"
end
ret << "\n"
end
ret << "\n"
ret
end
providers.header = "
Puppet resource types are usually backed by multiple implementations called `providers`,
which handle variance between platforms and tools.
Different providers are suitable or unsuitable on different platforms based on things
like the presence of a given tool.
Here are all of the provider-backed types and their different providers. Any unmentioned
types do not use providers yet.
"
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/reference/metaparameter.rb | lib/puppet/reference/metaparameter.rb | # frozen_string_literal: true
Puppet::Util::Reference.newreference :metaparameter, :doc => "All Puppet metaparameters and all their details" do
str = %{
Metaparameters are attributes that work with any resource type, including custom
types and defined types.
In general, they affect _Puppet's_ behavior rather than the desired state of the
resource. Metaparameters do things like add metadata to a resource (`alias`,
`tag`), set limits on when the resource should be synced (`require`, `schedule`,
etc.), prevent Puppet from making changes (`noop`), and change logging verbosity
(`loglevel`).
## Available Metaparameters
}.dup
begin
params = []
Puppet::Type.eachmetaparam { |param|
params << param
}
params.sort_by(&:to_s).each { |param|
str << markdown_header(param.to_s, 3)
str << scrub(Puppet::Type.metaparamdoc(param))
str << "\n\n"
}
rescue => detail
Puppet.log_exception(detail, _("incorrect metaparams: %{detail}") % { detail: detail })
exit(1)
end
str
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/reference/configuration.rb | lib/puppet/reference/configuration.rb | # frozen_string_literal: true
config = Puppet::Util::Reference.newreference(:configuration, :depth => 1, :doc => "A reference for all settings") do
docs = {}
Puppet.settings.each do |name, object|
docs[name] = object
end
str = ''.dup
docs.sort { |a, b|
a[0].to_s <=> b[0].to_s
}.each do |name, object|
# Make each name an anchor
header = name.to_s
str << markdown_header(header, 3)
# Print the doc string itself
begin
str << Puppet::Util::Docs.scrub(object.desc)
rescue => detail
Puppet.log_exception(detail)
end
str << "\n\n"
# Now print the data about the item.
val = object.default
case name.to_s
when 'vardir'
val = 'Unix/Linux: /opt/puppetlabs/puppet/cache -- Windows: C:\ProgramData\PuppetLabs\puppet\cache -- Non-root user: ~/.puppetlabs/opt/puppet/cache'
when 'publicdir'
val = 'Unix/Linux: /opt/puppetlabs/puppet/public -- Windows: C:\ProgramData\PuppetLabs\puppet\public -- Non-root user: ~/.puppetlabs/opt/puppet/public'
when 'confdir'
val = 'Unix/Linux: /etc/puppetlabs/puppet -- Windows: C:\ProgramData\PuppetLabs\puppet\etc -- Non-root user: ~/.puppetlabs/etc/puppet'
when 'codedir'
val = 'Unix/Linux: /etc/puppetlabs/code -- Windows: C:\ProgramData\PuppetLabs\code -- Non-root user: ~/.puppetlabs/etc/code'
when 'rundir'
val = 'Unix/Linux: /var/run/puppetlabs -- Windows: C:\ProgramData\PuppetLabs\puppet\var\run -- Non-root user: ~/.puppetlabs/var/run'
when 'logdir'
val = 'Unix/Linux: /var/log/puppetlabs/puppet -- Windows: C:\ProgramData\PuppetLabs\puppet\var\log -- Non-root user: ~/.puppetlabs/var/log'
when 'hiera_config'
val = '$confdir/hiera.yaml. However, for backwards compatibility, if a file exists at $codedir/hiera.yaml, Puppet uses that instead.'
when 'certname'
val = "the Host's fully qualified domain name, as determined by Facter"
when 'hostname'
val = "(the system's fully qualified hostname)"
when 'domain'
val = "(the system's own domain)"
when 'srv_domain'
val = 'example.com'
when 'http_user_agent'
val = 'Puppet/<version> Ruby/<version> (<architecture>)'
end
# Leave out the section information; it was apparently confusing people.
# str << "- **Section**: #{object.section}\n"
unless val == ""
str << "- *Default*: `#{val}`\n"
end
str << "\n"
end
return str
end
config.header = <<~EOT
## Configuration settings
* Each of these settings can be specified in `puppet.conf` or on the
command line.
* Puppet Enterprise (PE) and open source Puppet share the configuration settings
documented here. However, PE defaults differ from open source defaults for some
settings, such as `node_terminus`, `storeconfigs`, `always_retry_plugins`,
`disable18n`, `environment_timeout` (when Code Manager is enabled), and the
Puppet Server JRuby `max-active-instances` setting. To verify PE configuration
defaults, check the `puppet.conf` or `pe-puppet-server.conf` file after
installation.
* When using boolean settings on the command line, use `--setting` and
`--no-setting` instead of `--setting (true|false)`. (Using `--setting false`
results in "Error: Could not parse application options: needless argument".)
* Settings can be interpolated as `$variables` in other settings; `$environment`
is special, in that puppet master will interpolate each agent node's
environment instead of its own.
* Multiple values should be specified as comma-separated lists; multiple
directories should be separated with the system path separator (usually
a colon).
* Settings that represent time intervals should be specified in duration format:
an integer immediately followed by one of the units 'y' (years of 365 days),
'd' (days), 'h' (hours), 'm' (minutes), or 's' (seconds). The unit cannot be
combined with other units, and defaults to seconds when omitted. Examples are
'3600' which is equivalent to '1h' (one hour), and '1825d' which is equivalent
to '5y' (5 years).
* If you use the `splay` setting, note that the period that it waits changes
each time the Puppet agent is restarted.
* Settings that take a single file or directory can optionally set the owner,
group, and mode for their value: `rundir = $vardir/run { owner = puppet,
group = puppet, mode = 644 }`
* The Puppet executables ignores any setting that isn't relevant to
their function.
See the [configuration guide][confguide] for more details.
[confguide]: https://puppet.com/docs/puppet/latest/config_about_settings.html
EOT
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/reference/function.rb | lib/puppet/reference/function.rb | # frozen_string_literal: true
function = Puppet::Util::Reference.newreference :function, :doc => "All functions available in the parser" do
Puppet::Parser::Functions.functiondocs
end
function.header = "
There are two types of functions in Puppet: Statements and rvalues.
Statements stand on their own and do not return arguments; they are used for
performing stand-alone work like importing. Rvalues return values and can
only be used in a statement requiring a value, such as an assignment or a case
statement.
Functions execute on the Puppet master. They do not execute on the Puppet agent.
Hence they only have access to the commands and data available on the Puppet master
host.
Here are the functions available in Puppet:
"
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/reference/indirection.rb | lib/puppet/reference/indirection.rb | # frozen_string_literal: true
require_relative '../../puppet/indirector/indirection'
require_relative '../../puppet/util/checksums'
require_relative '../../puppet/file_serving/content'
require_relative '../../puppet/file_serving/metadata'
reference = Puppet::Util::Reference.newreference :indirection, :doc => "Indirection types and their terminus classes" do
text = ''.dup
Puppet::Indirector::Indirection.instances.sort_by(&:to_s).each do |indirection|
ind = Puppet::Indirector::Indirection.instance(indirection)
name = indirection.to_s.capitalize
text << "## " + indirection.to_s + "\n\n"
text << Puppet::Util::Docs.scrub(ind.doc) + "\n\n"
Puppet::Indirector::Terminus.terminus_classes(ind.name).sort_by(&:to_s).each do |terminus|
# this is an "abstract" terminus, ignore it
next if ind.name == :resource && terminus == :validator
terminus_name = terminus.to_s
term_class = Puppet::Indirector::Terminus.terminus_class(ind.name, terminus)
if term_class
terminus_doc = Puppet::Util::Docs.scrub(term_class.doc)
text << markdown_header("`#{terminus_name}` terminus", 3) << terminus_doc << "\n\n"
else
Puppet.warning _("Could not build docs for indirector %{name}, terminus %{terminus}: could not locate terminus.") % { name: name.inspect, terminus: terminus_name.inspect }
end
end
end
text
end
reference.header = <<~HEADER
## About Indirection
Puppet's indirector support pluggable backends (termini) for a variety of key-value stores (indirections).
Each indirection type corresponds to a particular Ruby class (the "Indirected Class" below) and values are instances of that class.
Each instance's key is available from its `name` method.
The termini can be local (e.g., on-disk files) or remote (e.g., using a REST interface to talk to a puppet master).
An indirector has five methods, which are mapped into HTTP verbs for the REST interface:
* `find(key)` - get a single value (mapped to GET or POST with a singular endpoint)
* `search(key)` - get a list of matching values (mapped to GET with a plural endpoint)
* `head(key)` - return true if the key exists (mapped to HEAD)
* `destroy(key)` - remove the key and value (mapped to DELETE)
* `save(instance)` - write the instance to the store, using the instance's name as the key (mapped to PUT)
These methods are available via the `indirection` class method on the indirected classes. For example:
node = Puppet::Node.indirection.find('foo.example.com')
At startup, each indirection is configured with a terminus.
In most cases, this is the default terminus defined by the indirected class, but it can be overridden by the application or face, or overridden with the `route_file` configuration.
The available termini differ for each indirection, and are listed below.
Indirections can also have a cache, represented by a second terminus.
This is a write-through cache: modifications are written both to the cache and to the primary terminus.
Values fetched from the terminus are written to the cache.
### Interaction with REST
REST endpoints have the form `/{prefix}/{version}/{indirection}/{key}?environment={environment}`, where the indirection can be singular or plural, following normal English spelling rules.
On the server side, REST responses are generated from the locally-configured endpoints.
### Indirections and Termini
Below is the list of all indirections, their associated terminus classes, and how you select between them.
In general, the appropriate terminus class is selected by the application for you (e.g., `puppet agent` would always use the `rest`
terminus for most of its indirected classes), but some classes are tunable via normal settings. These will have `terminus setting` documentation listed with them.
HEADER
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/configurer/fact_handler.rb | lib/puppet/configurer/fact_handler.rb | # frozen_string_literal: true
require_relative '../../puppet/indirector/facts/facter'
require_relative '../../puppet/configurer'
require_relative '../../puppet/configurer/downloader'
# Break out the code related to facts. This module is
# just included into the agent, but having it here makes it
# easier to test.
module Puppet::Configurer::FactHandler
def find_facts
# This works because puppet agent configures Facts to use 'facter' for
# finding facts and the 'rest' terminus for caching them. Thus, we'll
# compile them and then "cache" them on the server.
facts = Puppet::Node::Facts.indirection.find(Puppet[:node_name_value], :environment => Puppet::Node::Environment.remote(@environment))
unless Puppet[:node_name_fact].empty?
Puppet[:node_name_value] = facts.values[Puppet[:node_name_fact]]
facts.name = Puppet[:node_name_value]
end
facts
rescue SystemExit, NoMemoryError
raise
rescue Exception => detail
message = _("Could not retrieve local facts: %{detail}") % { detail: detail }
Puppet.log_exception(detail, message)
raise Puppet::Error, message, detail.backtrace
end
def facts_for_uploading
encode_facts(find_facts)
end
def encode_facts(facts)
# facts = find_facts
# NOTE: :facts specified as parameters are URI encoded here,
# then encoded for a second time depending on their length:
#
# <= 1024 characters sent via query string of a HTTP GET, additionally query string encoded
# > 1024 characters sent in POST data, additionally x-www-form-urlencoded
# so it's only important that encoding method here return original values
# correctly when CGI.unescape called against it (in compiler code)
if Puppet[:preferred_serialization_format] == "pson"
{ :facts_format => :pson, :facts => Puppet::Util.uri_query_encode(facts.render(:pson)) }
else
{ :facts_format => 'application/json', :facts => Puppet::Util.uri_query_encode(facts.render(:json)) }
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/configurer/plugin_handler.rb | lib/puppet/configurer/plugin_handler.rb | # frozen_string_literal: true
# Break out the code related to plugins. This module is
# just included into the agent, but having it here makes it
# easier to test.
require_relative '../../puppet/configurer'
class Puppet::Configurer::PluginHandler
SUPPORTED_LOCALES_MOUNT_AGENT_VERSION = Gem::Version.new("5.3.4")
def download_plugins(environment)
source_permissions = Puppet::Util::Platform.windows? ? :ignore : :use
plugin_downloader = Puppet::Configurer::Downloader.new(
"plugin",
Puppet[:plugindest],
Puppet[:pluginsource],
Puppet[:pluginsignore],
environment
)
plugin_fact_downloader = Puppet::Configurer::Downloader.new(
"pluginfacts",
Puppet[:pluginfactdest],
Puppet[:pluginfactsource],
Puppet[:pluginsignore],
environment,
source_permissions
)
result = []
result += plugin_fact_downloader.evaluate
result += plugin_downloader.evaluate
unless Puppet[:disable_i18n]
# until file metadata/content are using the rest client, we need to check
# both :server_agent_version and the session to see if the server supports
# the "locales" mount
server_agent_version = Puppet.lookup(:server_agent_version) { "0.0" }
locales = Gem::Version.new(server_agent_version) >= SUPPORTED_LOCALES_MOUNT_AGENT_VERSION
unless locales
session = Puppet.lookup(:http_session)
locales = session.supports?(:fileserver, 'locales') || session.supports?(:puppet, 'locales')
end
if locales
locales_downloader = Puppet::Configurer::Downloader.new(
"locales",
Puppet[:localedest],
Puppet[:localesource],
Puppet[:pluginsignore] + " *.pot config.yaml",
environment
)
result += locales_downloader.evaluate
end
end
Puppet::Util::Autoload.reload_changed(Puppet.lookup(:current_environment))
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/configurer/downloader.rb | lib/puppet/configurer/downloader.rb | # frozen_string_literal: true
require_relative '../../puppet/configurer'
require_relative '../../puppet/resource/catalog'
class Puppet::Configurer::Downloader
attr_reader :name, :path, :source, :ignore
# Evaluate our download, returning the list of changed values.
def evaluate
Puppet.info _("Retrieving %{name}") % { name: name }
files = []
begin
catalog.apply do |trans|
unless Puppet[:ignore_plugin_errors]
# Propagate the first failure associated with the transaction. The any_failed?
# method returns the first resource status that failed or nil, not a boolean.
first_failure = trans.any_failed?
if first_failure
event = (first_failure.events || []).first
detail = event ? event.message : 'unknown'
raise Puppet::Error, _("Failed to retrieve %{name}: %{detail}") % { name: name, detail: detail }
end
end
trans.changed?.each do |resource|
yield resource if block_given?
files << resource[:path]
end
end
rescue Puppet::Error => detail
if Puppet[:ignore_plugin_errors]
Puppet.log_exception(detail, _("Could not retrieve %{name}: %{detail}") % { name: name, detail: detail })
else
raise detail
end
end
files
end
def initialize(name, path, source, ignore = nil, environment = nil, source_permissions = :ignore)
@name = name
@path = path
@source = source
@ignore = ignore
@environment = environment
@source_permissions = source_permissions
end
def file
unless @file
args = default_arguments.merge(:path => path, :source => source)
args[:ignore] = ignore.split if ignore
@file = Puppet::Type.type(:file).new(args)
end
@file
end
def catalog
unless @catalog
@catalog = Puppet::Resource::Catalog.new("PluginSync", @environment)
@catalog.host_config = false
@catalog.add_resource(file)
end
@catalog
end
private
def default_arguments
defargs = {
:path => path,
:recurse => true,
:links => :follow,
:source => source,
:source_permissions => @source_permissions,
:tag => name,
:purge => true,
:force => true,
:backup => false,
:noop => false,
:max_files => -1
}
unless Puppet::Util::Platform.windows?
defargs[:owner] = Process.uid
defargs[:group] = Process.gid
end
defargs
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/syntax_checkers/json.rb | lib/puppet/syntax_checkers/json.rb | # frozen_string_literal: true
# A syntax checker for JSON.
# @api public
require_relative '../../puppet/syntax_checkers'
class Puppet::SyntaxCheckers::Json < Puppet::Plugins::SyntaxCheckers::SyntaxChecker
# Checks the text for JSON syntax issues and reports them to the given acceptor.
#
# Error messages from the checker are capped at 100 chars from the source text.
#
# @param text [String] The text to check
# @param syntax [String] The syntax identifier in mime style (e.g. 'json', 'json-patch+json', 'xml', 'myapp+xml'
# @param acceptor [#accept] A Diagnostic acceptor
# @param source_pos [Puppet::Pops::Adapters::SourcePosAdapter] A source pos adapter with location information
# @api public
#
def check(text, syntax, acceptor, source_pos)
raise ArgumentError, _("Json syntax checker: the text to check must be a String.") unless text.is_a?(String)
raise ArgumentError, _("Json syntax checker: the syntax identifier must be a String, e.g. json, data+json") unless syntax.is_a?(String)
raise ArgumentError, _("Json syntax checker: invalid Acceptor, got: '%{klass}'.") % { klass: acceptor.class.name } unless acceptor.is_a?(Puppet::Pops::Validation::Acceptor)
begin
Puppet::Util::Json.load(text)
rescue => e
# Cap the message to 100 chars and replace newlines
msg = _("JSON syntax checker: Cannot parse invalid JSON string. \"%{message}\"") % { message: e.message().slice(0, 100).gsub(/\r?\n/, "\\n") }
# TODO: improve the pops API to allow simpler diagnostic creation while still maintaining capabilities
# and the issue code. (In this case especially, where there is only a single error message being issued).
#
issue = Puppet::Pops::Issues.issue(:ILLEGAL_JSON) { msg }
acceptor.accept(Puppet::Pops::Validation::Diagnostic.new(:error, issue, source_pos.file, source_pos, {}))
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/syntax_checkers/base64.rb | lib/puppet/syntax_checkers/base64.rb | # frozen_string_literal: true
# A syntax checker for Base64.
# @api public
require_relative '../../puppet/syntax_checkers'
require 'base64'
class Puppet::SyntaxCheckers::Base64 < Puppet::Plugins::SyntaxCheckers::SyntaxChecker
# Checks the text for BASE64 syntax issues and reports them to the given acceptor.
# This checker allows the most relaxed form of Base64, including newlines and missing padding.
# It also accept URLsafe input.
#
# @param text [String] The text to check
# @param syntax [String] The syntax identifier in mime style (e.g. 'base64', 'text/xxx+base64')
# @param acceptor [#accept] A Diagnostic acceptor
# @param source_pos [Puppet::Pops::Adapters::SourcePosAdapter] A source pos adapter with location information
# @api public
#
def check(text, syntax, acceptor, source_pos)
raise ArgumentError, _("Base64 syntax checker: the text to check must be a String.") unless text.is_a?(String)
raise ArgumentError, _("Base64 syntax checker: the syntax identifier must be a String, e.g. json, data+json") unless syntax.is_a?(String)
raise ArgumentError, _("Base64 syntax checker: invalid Acceptor, got: '%{klass}'.") % { klass: acceptor.class.name } unless acceptor.is_a?(Puppet::Pops::Validation::Acceptor)
cleaned_text = text.gsub(/[\r?\n[:blank:]]/, '')
begin
# Do a strict decode64 on text with all whitespace stripped since the non strict version
# simply skips all non base64 characters
Base64.strict_decode64(cleaned_text)
rescue
msg = if (cleaned_text.bytes.to_a.size * 8) % 6 != 0
_("Base64 syntax checker: Cannot parse invalid Base64 string - padding is not correct")
else
_("Base64 syntax checker: Cannot parse invalid Base64 string - contains letters outside strict base 64 range (or whitespace)")
end
# TODO: improve the pops API to allow simpler diagnostic creation while still maintaining capabilities
# and the issue code. (In this case especially, where there is only a single error message being issued).
#
issue = Puppet::Pops::Issues.issue(:ILLEGAL_BASE64) { msg }
acceptor.accept(Puppet::Pops::Validation::Diagnostic.new(:error, issue, source_pos.file, source_pos, {}))
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/syntax_checkers/epp.rb | lib/puppet/syntax_checkers/epp.rb | # frozen_string_literal: true
# A syntax checker for JSON.
# @api public
require_relative '../../puppet/syntax_checkers'
class Puppet::SyntaxCheckers::EPP < Puppet::Plugins::SyntaxCheckers::SyntaxChecker
# Checks the text for Puppet Language EPP syntax issues and reports them to the given acceptor.
#
# Error messages from the checker are capped at 100 chars from the source text.
#
# @param text [String] The text to check
# @param syntax [String] The syntax identifier in mime style (only accepts 'pp')
# @param acceptor [#accept] A Diagnostic acceptor
# @param source_pos [Puppet::Pops::Adapters::SourcePosAdapter] A source pos adapter with location information
# @api public
#
def check(text, syntax, acceptor, source_pos)
raise ArgumentError, _("EPP syntax checker: the text to check must be a String.") unless text.is_a?(String)
raise ArgumentError, _("EPP syntax checker: the syntax identifier must be a String, e.g. pp") unless syntax == 'epp'
raise ArgumentError, _("EPP syntax checker: invalid Acceptor, got: '%{klass}'.") % { klass: acceptor.class.name } unless acceptor.is_a?(Puppet::Pops::Validation::Acceptor)
begin
Puppet::Pops::Parser::EvaluatingParser::EvaluatingEppParser.singleton.parse_string(text)
rescue => e
# Cap the message to 100 chars and replace newlines
msg = _("EPP syntax checker: \"%{message}\"") % { message: e.message().slice(0, 500).gsub(/\r?\n/, "\\n") }
# TODO: improve the pops API to allow simpler diagnostic creation while still maintaining capabilities
# and the issue code. (In this case especially, where there is only a single error message being issued).
#
issue = Puppet::Pops::Issues.issue(:ILLEGAL_EPP) { msg }
acceptor.accept(Puppet::Pops::Validation::Diagnostic.new(:error, issue, source_pos.file, source_pos, {}))
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/syntax_checkers/pp.rb | lib/puppet/syntax_checkers/pp.rb | # frozen_string_literal: true
# A syntax checker for JSON.
# @api public
require_relative '../../puppet/syntax_checkers'
class Puppet::SyntaxCheckers::PP < Puppet::Plugins::SyntaxCheckers::SyntaxChecker
# Checks the text for Puppet Language syntax issues and reports them to the given acceptor.
#
# Error messages from the checker are capped at 100 chars from the source text.
#
# @param text [String] The text to check
# @param syntax [String] The syntax identifier in mime style (only accepts 'pp')
# @param acceptor [#accept] A Diagnostic acceptor
# @param source_pos [Puppet::Pops::Adapters::SourcePosAdapter] A source pos adapter with location information
# @api public
#
def check(text, syntax, acceptor, source_pos)
raise ArgumentError, _("PP syntax checker: the text to check must be a String.") unless text.is_a?(String)
raise ArgumentError, _("PP syntax checker: the syntax identifier must be a String, e.g. pp") unless syntax == 'pp'
raise ArgumentError, _("PP syntax checker: invalid Acceptor, got: '%{klass}'.") % { klass: acceptor.class.name } unless acceptor.is_a?(Puppet::Pops::Validation::Acceptor)
begin
Puppet::Pops::Parser::EvaluatingParser.singleton.parse_string(text)
rescue => e
# Cap the message to 100 chars and replace newlines
msg = _("PP syntax checker: \"%{message}\"") % { message: e.message().slice(0, 500).gsub(/\r?\n/, "\\n") }
# TODO: improve the pops API to allow simpler diagnostic creation while still maintaining capabilities
# and the issue code. (In this case especially, where there is only a single error message being issued).
#
issue = Puppet::Pops::Issues.issue(:ILLEGAL_PP) { msg }
acceptor.accept(Puppet::Pops::Validation::Diagnostic.new(:error, issue, source_pos.file, source_pos, {}))
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/pal/compiler.rb | lib/puppet/pal/compiler.rb | # frozen_string_literal: true
module Puppet
module Pal
# A configured compiler as obtained in the callback from `Puppet::Pal.with_script_compiler`.
# (Later, there may also be a catalog compiler available.)
#
class Compiler
attr_reader :internal_compiler
protected :internal_compiler
attr_reader :internal_evaluator
protected :internal_evaluator
def initialize(internal_compiler)
@internal_compiler = internal_compiler
@internal_evaluator = Puppet::Pops::Parser::EvaluatingParser.new
end
# Calls a function given by name with arguments specified in an `Array`, and optionally accepts a code block.
# @param function_name [String] the name of the function to call
# @param args [Object] the arguments to the function
# @param block [Proc] an optional callable block that is given to the called function
# @return [Object] what the called function returns
#
def call_function(function_name, *args, &block)
# TRANSLATORS: do not translate variable name strings in these assertions
Pal.assert_non_empty_string(function_name, 'function_name', false)
Pal.assert_type(Pal::T_ANY_ARRAY, args, 'args', false)
internal_evaluator.evaluator.external_call_function(function_name, args, topscope, &block)
end
# Returns a Puppet::Pal::FunctionSignature object or nil if function is not found
# The returned FunctionSignature has information about all overloaded signatures of the function
#
# @example using function_signature
# # returns true if 'myfunc' is callable with three integer arguments 1, 2, 3
# compiler.function_signature('myfunc').callable_with?([1,2,3])
#
# @param function_name [String] the name of the function to get a signature for
# @return [Puppet::Pal::FunctionSignature] a function signature, or nil if function not found
#
def function_signature(function_name)
loader = internal_compiler.loaders.private_environment_loader
func = loader.load(:function, function_name)
if func
return FunctionSignature.new(func.class)
end
# Could not find function
nil
end
# Returns an array of TypedName objects for all functions, optionally filtered by a regular expression.
# The returned array has more information than just the leaf name - the typical thing is to just get
# the name as showing the following example.
#
# Errors that occur during function discovery will either be logged as warnings or collected by the optional
# `error_collector` array. When provided, it will receive {Puppet::DataTypes::Error} instances describing
# each error in detail and no warnings will be logged.
#
# @example getting the names of all functions
# compiler.list_functions.map {|tn| tn.name }
#
# @param filter_regex [Regexp] an optional regexp that filters based on name (matching names are included in the result)
# @param error_collector [Array<Puppet::DataTypes::Error>] an optional array that will receive errors during load
# @return [Array<Puppet::Pops::Loader::TypedName>] an array of typed names
#
def list_functions(filter_regex = nil, error_collector = nil)
list_loadable_kind(:function, filter_regex, error_collector)
end
# Evaluates a string of puppet language code in top scope.
# A "source_file" reference to a source can be given - if not an actual file name, by convention the name should
# be bracketed with < > to indicate it is something symbolic; for example `<commandline>` if the string was given on the
# command line.
#
# If the given `puppet_code` is `nil` or an empty string, `nil` is returned, otherwise the result of evaluating the
# puppet language string. The given string must form a complete and valid expression/statement as an error is raised
# otherwise. That is, it is not possible to divide a compound expression by line and evaluate each line individually.
#
# @param puppet_code [String, nil] the puppet language code to evaluate, must be a complete expression/statement
# @param source_file [String, nil] an optional reference to a source (a file or symbolic name/location)
# @return [Object] what the `puppet_code` evaluates to
#
def evaluate_string(puppet_code, source_file = nil)
return nil if puppet_code.nil? || puppet_code == ''
unless puppet_code.is_a?(String)
raise ArgumentError, _("The argument 'puppet_code' must be a String, got %{type}") % { type: puppet_code.class }
end
evaluate(parse_string(puppet_code, source_file))
end
# Evaluates a puppet language file in top scope.
# The file must exist and contain valid puppet language code or an error is raised.
#
# @param file [Path, String] an absolute path to a file with puppet language code, must exist
# @return [Object] what the last evaluated expression in the file evaluated to
#
def evaluate_file(file)
evaluate(parse_file(file))
end
# Evaluates an AST obtained from `parse_string` or `parse_file` in topscope.
# If the ast is a `Puppet::Pops::Model::Program` (what is returned from the `parse` methods, any definitions
# in the program (that is, any function, plan, etc. that is defined will be made available for use).
#
# @param ast [Puppet::Pops::Model::PopsObject] typically the returned `Program` from the parse methods, but can be any `Expression`
# @returns [Object] whatever the ast evaluates to
#
def evaluate(ast)
if ast.is_a?(Puppet::Pops::Model::Program)
loaders = Puppet.lookup(:loaders)
loaders.instantiate_definitions(ast, loaders.public_environment_loader)
end
internal_evaluator.evaluate(topscope, ast)
end
# Produces a literal value if the AST obtained from `parse_string` or `parse_file` does not require any actual evaluation.
# This method is useful if obtaining an AST that represents literal values; string, integer, float, boolean, regexp, array, hash;
# for example from having read this from the command line or as values in some file.
#
# @param ast [Puppet::Pops::Model::PopsObject] typically the returned `Program` from the parse methods, but can be any `Expression`
# @returns [Object] whatever the literal value the ast evaluates to
#
def evaluate_literal(ast)
catch :not_literal do
return Puppet::Pops::Evaluator::LiteralEvaluator.new().literal(ast)
end
# TRANSLATORS, the 'ast' is the name of a parameter, do not translate
raise ArgumentError, _("The given 'ast' does not represent a literal value")
end
# Parses and validates a puppet language string and returns an instance of Puppet::Pops::Model::Program on success.
# If the content is not valid an error is raised.
#
# @param code_string [String] a puppet language string to parse and validate
# @param source_file [String] an optional reference to a file or other location in angled brackets
# @return [Puppet::Pops::Model::Program] returns a `Program` instance on success
#
def parse_string(code_string, source_file = nil)
unless code_string.is_a?(String)
raise ArgumentError, _("The argument 'code_string' must be a String, got %{type}") % { type: code_string.class }
end
internal_evaluator.parse_string(code_string, source_file)
end
# Parses and validates a puppet language file and returns an instance of Puppet::Pops::Model::Program on success.
# If the content is not valid an error is raised.
#
# @param file [String] a file with puppet language content to parse and validate
# @return [Puppet::Pops::Model::Program] returns a `Program` instance on success
#
def parse_file(file)
unless file.is_a?(String)
raise ArgumentError, _("The argument 'file' must be a String, got %{type}") % { type: file.class }
end
internal_evaluator.parse_file(file)
end
# Parses a puppet data type given in String format and returns that type, or raises an error.
# A type is needed in calls to `new` to create an instance of the data type, or to perform type checking
# of values - typically using `type.instance?(obj)` to check if `obj` is an instance of the type.
#
# @example Verify if obj is an instance of a data type
# # evaluates to true
# pal.type('Enum[red, blue]').instance?("blue")
#
# @example Create an instance of a data type
# # using an already create type
# t = pal.type('Car')
# pal.create(t, 'color' => 'black', 'make' => 't-ford')
#
# # letting 'new_object' parse the type from a string
# pal.create('Car', 'color' => 'black', 'make' => 't-ford')
#
# @param type_string [String] a puppet language data type
# @return [Puppet::Pops::Types::PAnyType] the data type
#
def type(type_string)
Puppet::Pops::Types::TypeParser.singleton.parse(type_string)
end
# Creates a new instance of a given data type.
# @param data_type [String, Puppet::Pops::Types::PAnyType] the data type as a data type or in String form.
# @param arguments [Object] one or more arguments to the called `new` function
# @return [Object] an instance of the given data type,
# or raises an error if it was not possible to parse data type or create an instance.
#
def create(data_type, *arguments)
t = data_type.is_a?(String) ? type(data_type) : data_type
unless t.is_a?(Puppet::Pops::Types::PAnyType)
raise ArgumentError, _("Given data_type value is not a data type, got '%{type}'") % { type: t.class }
end
call_function('new', t, *arguments)
end
# Returns true if this is a compiler that compiles a catalog.
# This implementation returns `false`
# @return Boolan false
def has_catalog?
false
end
protected
def list_loadable_kind(kind, filter_regex = nil, error_collector = nil)
loader = internal_compiler.loaders.private_environment_loader
if filter_regex.nil?
loader.discover(kind, error_collector)
else
loader.discover(kind, error_collector) { |f| f.name =~ filter_regex }
end
end
private
def topscope
internal_compiler.topscope
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/pal/task_signature.rb | lib/puppet/pal/task_signature.rb | # frozen_string_literal: true
module Puppet
module Pal
# A TaskSignature is returned from `task_signature`. Its purpose is to answer questions about the task's parameters
# and if it can be run/called with a hash of named parameters.
#
class TaskSignature
def initialize(task)
@task = task
end
# Returns whether or not the given arguments are acceptable when running the task.
# In addition to returning the boolean outcome, if a block is given, it is called with a string of formatted
# error messages that describes the difference between what was given and what is expected. The error message may
# have multiple lines of text, and each line is indented one space.
#
# @param args_hash [Hash] a hash mapping parameter names to argument values
# @yieldparam [String] a formatted error message if a type mismatch occurs that explains the mismatch
# @return [Boolean] if the given arguments are acceptable when running the task
#
def runnable_with?(args_hash)
params = @task.parameters
params_type = if params.nil?
T_GENERIC_TASK_HASH
else
Puppet::Pops::Types::TypeFactory.struct(params)
end
return true if params_type.instance?(args_hash)
if block_given?
tm = Puppet::Pops::Types::TypeMismatchDescriber.singleton
error = if params.nil?
tm.describe_mismatch('', params_type,
Puppet::Pops::Types::TypeCalculator
.infer_set(args_hash))
else
tm.describe_struct_signature(params_type, args_hash)
.flatten
.map(&:format)
.join("\n")
end
yield "Task #{@task.name}:\n#{error}"
end
false
end
# Returns the Task instance as a hash
#
# @return [Hash{String=>Object}] the hash representation of the task
def task_hash
@task._pcore_init_hash
end
# Returns the Task instance which can be further explored. It contains all meta-data defined for
# the task such as the description, parameters, output, etc.
#
# @return [Puppet::Pops::Types::PuppetObject] An instance of a dynamically created Task class
def task
@task
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/pal/json_catalog_encoder.rb | lib/puppet/pal/json_catalog_encoder.rb | # frozen_string_literal: true
# The JsonCatalogEncoder is a wrapper around a catalog produced by the Pal::CatalogCompiler.with_json_encoding
# method.
# It allows encoding the entire catalog or an individual resource as Rich Data Json.
#
# @api public
#
module Puppet
module Pal
class JsonCatalogEncoder
# Is the resulting Json pretty printed or not.
attr_reader :pretty
# Should unrealized virtual resources be included in the result or not.
attr_reader :exclude_virtual
# The internal catalog being build - what this class wraps with a public API.
attr_reader :catalog
private :catalog
# Do not instantiate this class directly! Use the `Pal::CatalogCompiler#with_json_encoding` method
# instead.
#
# @param catalog [Puppet::Resource::Catalog] the internal catalog that this class wraps
# @param pretty [Boolean] (true), if the resulting JSON should be pretty printed or not
# @param exclude_virtual [Boolean] (true), if the resulting catalog should contain unrealzed virtual resources or not
#
# @api private
#
def initialize(catalog, pretty: true, exclude_virtual: true)
@catalog = catalog
@pretty = pretty
@exclude_virtual = exclude_virtual
end
# Encodes the entire catalog as a rich-data Json catalog.
# @return String The catalog in Json format using rich data format
# @api public
#
def encode
possibly_filtered_catalog.to_json(:pretty => pretty)
end
# Returns one particular resource as a Json string, or returns nil if resource was not found.
# @param type [String] the name of the puppet type (case independent)
# @param title [String] the title of the wanted resource
# @return [String] the resulting Json text
# @api public
#
def encode_resource(type, title)
# Ensure that both type and title are given since the underlying API will do mysterious things
# if 'title' is nil. (Other assertions are made by the catalog when looking up the resource).
#
# TRANSLATORS 'type' and 'title' are internal parameter names - do not translate
raise ArgumentError, _("Both type and title must be given") if type.nil? or title.nil?
r = possibly_filtered_catalog.resource(type, title)
return nil if r.nil?
r.to_data_hash.to_json(:pretty => pretty)
end
# Applies a filter for virtual resources and returns filtered catalog
# or the catalog itself if filtering was not needed.
# The result is cached.
# @api private
# rubocop:disable Naming/MemoizedInstanceVariableName
def possibly_filtered_catalog
@filtered ||= (exclude_virtual ? catalog.filter(&:virtual?) : catalog)
end
private :possibly_filtered_catalog
# rubocop:enable Naming/MemoizedInstanceVariableName
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/pal/script_compiler.rb | lib/puppet/pal/script_compiler.rb | # frozen_string_literal: true
module Puppet
module Pal
class ScriptCompiler < Compiler
# Returns the signature of the given plan name
# @param plan_name [String] the name of the plan to get the signature of
# @return [Puppet::Pal::PlanSignature, nil] returns a PlanSignature, or nil if plan is not found
#
def plan_signature(plan_name)
loader = internal_compiler.loaders.private_environment_loader
func = loader.load(:plan, plan_name)
if func
return PlanSignature.new(func)
end
# Could not find plan
nil
end
# Returns an array of TypedName objects for all plans, optionally filtered by a regular expression.
# The returned array has more information than just the leaf name - the typical thing is to just get
# the name as showing the following example.
#
# Errors that occur during plan discovery will either be logged as warnings or collected by the optional
# `error_collector` array. When provided, it will receive {Puppet::DataTypes::Error} instances describing
# each error in detail and no warnings will be logged.
#
# @example getting the names of all plans
# compiler.list_plans.map {|tn| tn.name }
#
# @param filter_regex [Regexp] an optional regexp that filters based on name (matching names are included in the result)
# @param error_collector [Array<Puppet::DataTypes::Error>] an optional array that will receive errors during load
# @return [Array<Puppet::Pops::Loader::TypedName>] an array of typed names
#
def list_plans(filter_regex = nil, error_collector = nil)
list_loadable_kind(:plan, filter_regex, error_collector)
end
# Returns the signature callable of the given task (the arguments it accepts, and the data type it returns)
# @param task_name [String] the name of the task to get the signature of
# @return [Puppet::Pal::TaskSignature, nil] returns a TaskSignature, or nil if task is not found
#
def task_signature(task_name)
loader = internal_compiler.loaders.private_environment_loader
task = loader.load(:task, task_name)
if task
return TaskSignature.new(task)
end
# Could not find task
nil
end
# Returns an array of TypedName objects for all tasks, optionally filtered by a regular expression.
# The returned array has more information than just the leaf name - the typical thing is to just get
# the name as showing the following example.
#
# @example getting the names of all tasks
# compiler.list_tasks.map {|tn| tn.name }
#
# Errors that occur during task discovery will either be logged as warnings or collected by the optional
# `error_collector` array. When provided, it will receive {Puppet::DataTypes::Error} instances describing
# each error in detail and no warnings will be logged.
#
# @param filter_regex [Regexp] an optional regexp that filters based on name (matching names are included in the result)
# @param error_collector [Array<Puppet::DataTypes::Error>] an optional array that will receive errors during load
# @return [Array<Puppet::Pops::Loader::TypedName>] an array of typed names
#
def list_tasks(filter_regex = nil, error_collector = nil)
list_loadable_kind(:task, filter_regex, error_collector)
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/pal/pal_api.rb | lib/puppet/pal/pal_api.rb | # frozen_string_literal: true
module Puppet
require_relative '../../puppet/parser/script_compiler'
require_relative '../../puppet/parser/catalog_compiler'
module Pal
require_relative '../../puppet/pal/json_catalog_encoder'
require_relative '../../puppet/pal/function_signature'
require_relative '../../puppet/pal/task_signature'
require_relative '../../puppet/pal/plan_signature'
require_relative '../../puppet/pal/compiler'
require_relative '../../puppet/pal/script_compiler'
require_relative '../../puppet/pal/catalog_compiler'
require_relative '../../puppet/pal/pal_impl'
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/pal/catalog_compiler.rb | lib/puppet/pal/catalog_compiler.rb | # frozen_string_literal: true
module Puppet
module Pal
# A CatalogCompiler is a compiler that builds a catalog of resources and dependencies as a side effect of
# evaluating puppet language code.
# When the compilation of the given input manifest(s)/code string/file is finished the catalog is complete
# for encoding and use. It is also possible to evaluate more strings within the same compilation context to
# add or remove things from the catalog.
#
# @api public
class CatalogCompiler < Compiler
# @api private
def catalog
internal_compiler.catalog
end
private :catalog
# Returns true if this is a compiler that compiles a catalog.
# This implementation returns `true`
# @return [Boolean] true
# @api public
def has_catalog?
true
end
# Calls a block of code and yields a configured `JsonCatalogEncoder` to the block.
# @example Get resulting catalog as pretty printed Json
# Puppet::Pal.in_environment(...) do |pal|
# pal.with_catalog_compiler(...) do |compiler|
# compiler.with_json_encoding { |encoder| encoder.encode }
# end
# end
#
# @api public
#
def with_json_encoding(pretty: true, exclude_virtual: true)
yield JsonCatalogEncoder.new(catalog, pretty: pretty, exclude_virtual: exclude_virtual)
end
# Returns a hash representation of the compiled catalog.
#
# @api public
def catalog_data_hash
catalog.to_data_hash
end
# Evaluates an AST obtained from `parse_string` or `parse_file` in topscope.
# If the ast is a `Puppet::Pops::Model::Program` (what is returned from the `parse` methods, any definitions
# in the program (that is, any function, plan, etc. that is defined will be made available for use).
#
# @param ast [Puppet::Pops::Model::PopsObject] typically the returned `Program` from the parse methods, but can be any `Expression`
# @returns [Object] whatever the ast evaluates to
#
def evaluate(ast)
if ast.is_a?(Puppet::Pops::Model::Program)
bridged = Puppet::Parser::AST::PopsBridge::Program.new(ast)
# define all catalog types
internal_compiler.environment.known_resource_types.import_ast(bridged, "")
bridged.evaluate(internal_compiler.topscope)
else
internal_evaluator.evaluate(topscope, ast)
end
end
# Compiles the result of additional evaluation taking place in a PAL catalog compilation.
# This will evaluate all lazy constructs until all have been evaluated, and will the validate
# the result.
#
# This should be called if evaluating string or files of puppet logic after the initial
# compilation taking place by giving PAL a manifest or code-string.
# This method should be called when a series of evaluation should have reached a
# valid state (there should be no dangling relationships (to resources that does not
# exist).
#
# As an alternative the methods `evaluate_additions` can be called without any
# requirements on consistency and then calling `validate` at the end.
#
# Can be called multiple times.
#
# @return [Void]
def compile_additions
internal_compiler.compile_additions
end
# Validates the state of the catalog (without performing evaluation of any elements
# requiring lazy evaluation. Can be called multiple times.
#
def validate
internal_compiler.validate
end
# Evaluates all lazy constructs that were produced as a side effect of evaluating puppet logic.
# Can be called multiple times.
#
def evaluate_additions
internal_compiler.evaluate_additions
end
# Attempts to evaluate AST for node defnintions https://puppet.com/docs/puppet/latest/lang_node_definitions.html
# if there are any.
def evaluate_ast_node
internal_compiler.evaluate_ast_node
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/pal/function_signature.rb | lib/puppet/pal/function_signature.rb | # frozen_string_literal: true
module Puppet
module Pal
# A FunctionSignature is returned from `function_signature`. Its purpose is to answer questions about the function's parameters
# and if it can be called with a set of parameters.
#
# It is also possible to get an array of puppet Callable data type where each callable describes one possible way
# the function can be called.
#
# @api public
#
class FunctionSignature
# @api private
def initialize(function_class)
@func = function_class
end
# Returns true if the function can be called with the given arguments and false otherwise.
# If the function is not callable, and a code block is given, it is given a formatted error message that describes
# the type mismatch. That error message can be quite complex if the function has multiple dispatch depending on
# given types.
#
# @param args [Array] The arguments as given to the function call
# @param callable [Proc, nil] An optional ruby Proc or puppet lambda given to the function
# @yield [String] a formatted error message describing a type mismatch if the function is not callable with given args + block
# @return [Boolean] true if the function can be called with given args + block, and false otherwise
# @api public
#
def callable_with?(args, callable = nil)
signatures = @func.dispatcher.to_type
callables = signatures.is_a?(Puppet::Pops::Types::PVariantType) ? signatures.types : [signatures]
return true if callables.any? { |t| t.callable_with?(args) }
return false unless block_given?
args_type = Puppet::Pops::Types::TypeCalculator.singleton.infer_set(callable.nil? ? args : args + [callable])
error_message = Puppet::Pops::Types::TypeMismatchDescriber.describe_signatures(@func.name, @func.signatures, args_type)
yield error_message
false
end
# Returns an array of Callable puppet data type
# @return [Array<Puppet::Pops::Types::PCallableType] one callable per way the function can be called
#
# @api public
#
def callables
signatures = @func.dispatcher.to_type
signatures.is_a?(Puppet::Pops::Types::PVariantType) ? signatures.types : [signatures]
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/pal/pal_impl.rb | lib/puppet/pal/pal_impl.rb | # frozen_string_literal: true
# Puppet as a Library "PAL"
# Yes, this requires all of puppet for now because 'settings' and many other things...
require_relative '../../puppet'
require_relative '../../puppet/parser/script_compiler'
require_relative '../../puppet/parser/catalog_compiler'
module Puppet
# This is the main entry point for "Puppet As a Library" PAL.
# This file should be required instead of "puppet"
# Initially, this will require ALL of puppet - over time this will change as the monolithical "puppet" is broken up
# into smaller components.
#
# @example Running a snippet of Puppet Language code
# require 'puppet_pal'
# result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: ['/tmp/testmodules']) do |pal|
# pal.evaluate_script_string('1+2+3')
# end
# # The result is the value 6
#
# @example Calling a function
# require 'puppet_pal'
# result = Puppet::Pal.in_tmp_environment('pal_env', modulepath: ['/tmp/testmodules']) do |pal|
# pal.call_function('mymodule::myfunction', 10, 20)
# end
# # The result is what 'mymodule::myfunction' returns
#
# @api public
module Pal
# Defines a context in which multiple operations in an env with a script compiler can be performed in a given block.
# The calls that takes place to PAL inside of the given block are all with the same instance of the compiler.
# The parameter `configured_by_env` makes it possible to either use the configuration in the environment, or specify
# `manifest_file` or `code_string` manually. If neither is given, an empty `code_string` is used.
#
# @example define a script compiler without any initial logic
# pal.with_script_compiler do | compiler |
# # do things with compiler
# end
#
# @example define a script compiler with a code_string containing initial logic
# pal.with_script_compiler(code_string: '$myglobal_var = 42') do | compiler |
# # do things with compiler
# end
#
# @param configured_by_env [Boolean] when true the environment's settings are used, otherwise the given `manifest_file` or `code_string`
# @param manifest_file [String] a Puppet Language file to load and evaluate before calling the given block, mutually exclusive with `code_string`
# @param code_string [String] a Puppet Language source string to load and evaluate before calling the given block, mutually exclusive with `manifest_file`
# @param facts [Hash] optional map of fact name to fact value - if not given will initialize the facts (which is a slow operation)
# If given at the environment level, the facts given here are merged with higher priority.
# @param variables [Hash] optional map of fully qualified variable name to value. If given at the environment level, the variables
# given here are merged with higher priority.
# @param set_local_facts [Boolean] when true, the $facts, $server_facts, and $trusted variables are set for the scope.
# @param block [Proc] the block performing operations on compiler
# @return [Object] what the block returns
# @yieldparam [Puppet::Pal::ScriptCompiler] compiler, a ScriptCompiler to perform operations on.
#
def self.with_script_compiler(
configured_by_env: false,
manifest_file: nil,
code_string: nil,
facts: {},
variables: {},
set_local_facts: true,
&block
)
# TRANSLATORS: do not translate variable name strings in these assertions
assert_mutually_exclusive(manifest_file, code_string, 'manifest_file', 'code_string')
assert_non_empty_string(manifest_file, 'manifest_file', true)
assert_non_empty_string(code_string, 'code_string', true)
assert_type(T_BOOLEAN, configured_by_env, "configured_by_env", false)
if configured_by_env
unless manifest_file.nil? && code_string.nil?
# TRANSLATORS: do not translate the variable names in this error message
raise ArgumentError, _("manifest_file or code_string cannot be given when configured_by_env is true")
end
# Use the manifest setting
manifest_file = Puppet[:manifest]
elsif manifest_file.nil? && code_string.nil?
# An "undef" code_string is the only way to override Puppet[:manifest] & Puppet[:code] settings since an
# empty string is taken as Puppet[:code] not being set.
#
code_string = 'undef'
end
previous_tasks_value = Puppet[:tasks]
previous_code_value = Puppet[:code]
Puppet[:tasks] = true
# After the assertions, if code_string is non nil - it has the highest precedence
Puppet[:code] = code_string unless code_string.nil?
# If manifest_file is nil, the #main method will use the env configured manifest
# to do things in the block while a Script Compiler is in effect
main(
manifest: manifest_file,
facts: facts,
variables: variables,
internal_compiler_class: :script,
set_local_facts: set_local_facts,
&block
)
ensure
Puppet[:tasks] = previous_tasks_value
Puppet[:code] = previous_code_value
end
# Evaluates a Puppet Language script string.
# @param code_string [String] a snippet of Puppet Language source code
# @return [Object] what the Puppet Language code_string evaluates to
# @deprecated Use {#with_script_compiler} and then evaluate_string on the given compiler - to be removed in 1.0 version
#
def self.evaluate_script_string(code_string)
# prevent the default loading of Puppet[:manifest] which is the environment's manifest-dir by default settings
# by setting code_string to 'undef'
with_script_compiler do |compiler|
compiler.evaluate_string(code_string)
end
end
# Evaluates a Puppet Language script (.pp) file.
# @param manifest_file [String] a file with Puppet Language source code
# @return [Object] what the Puppet Language manifest_file contents evaluates to
# @deprecated Use {#with_script_compiler} and then evaluate_file on the given compiler - to be removed in 1.0 version
#
def self.evaluate_script_manifest(manifest_file)
with_script_compiler do |compiler|
compiler.evaluate_file(manifest_file)
end
end
# Defines a context in which multiple operations in an env with a catalog producing compiler can be performed
# in a given block.
# The calls that takes place to PAL inside of the given block are all with the same instance of the compiler.
# The parameter `configured_by_env` makes it possible to either use the configuration in the environment, or specify
# `manifest_file` or `code_string` manually. If neither is given, an empty `code_string` is used.
#
# @example define a catalog compiler without any initial logic
# pal.with_catalog_compiler do | compiler |
# # do things with compiler
# end
#
# @example define a catalog compiler with a code_string containing initial logic
# pal.with_catalog_compiler(code_string: '$myglobal_var = 42') do | compiler |
# # do things with compiler
# end
#
# @param configured_by_env [Boolean] when true the environment's settings are used, otherwise the
# given `manifest_file` or `code_string`
# @param manifest_file [String] a Puppet Language file to load and evaluate before calling the given block, mutually exclusive
# with `code_string`
# @param code_string [String] a Puppet Language source string to load and evaluate before calling the given block, mutually
# exclusive with `manifest_file`
# @param facts [Hash] optional map of fact name to fact value - if not given will initialize the facts (which is a slow operation)
# If given at the environment level, the facts given here are merged with higher priority.
# @param variables [Hash] optional map of fully qualified variable name to value. If given at the environment level, the variables
# given here are merged with higher priority.
# @param block [Proc] the block performing operations on compiler
# @return [Object] what the block returns
# @yieldparam [Puppet::Pal::CatalogCompiler] compiler, a CatalogCompiler to perform operations on.
#
def self.with_catalog_compiler(
configured_by_env: false,
manifest_file: nil,
code_string: nil,
facts: {},
variables: {},
target_variables: {},
&block
)
# TRANSLATORS: do not translate variable name strings in these assertions
assert_mutually_exclusive(manifest_file, code_string, 'manifest_file', 'code_string')
assert_non_empty_string(manifest_file, 'manifest_file', true)
assert_non_empty_string(code_string, 'code_string', true)
assert_type(T_BOOLEAN, configured_by_env, "configured_by_env", false)
if configured_by_env
unless manifest_file.nil? && code_string.nil?
# TRANSLATORS: do not translate the variable names in this error message
raise ArgumentError, _("manifest_file or code_string cannot be given when configured_by_env is true")
end
# Use the manifest setting
manifest_file = Puppet[:manifest]
elsif manifest_file.nil? && code_string.nil?
# An "undef" code_string is the only way to override Puppet[:manifest] & Puppet[:code] settings since an
# empty string is taken as Puppet[:code] not being set.
#
code_string = 'undef'
end
# We need to make sure to set these back when we're done
previous_tasks_value = Puppet[:tasks]
previous_code_value = Puppet[:code]
Puppet[:tasks] = false
# After the assertions, if code_string is non nil - it has the highest precedence
Puppet[:code] = code_string unless code_string.nil?
# If manifest_file is nil, the #main method will use the env configured manifest
# to do things in the block while a Script Compiler is in effect
main(
manifest: manifest_file,
facts: facts,
variables: variables,
target_variables: target_variables,
internal_compiler_class: :catalog,
set_local_facts: false,
&block
)
ensure
# Clean up after ourselves
Puppet[:tasks] = previous_tasks_value
Puppet[:code] = previous_code_value
end
# Defines the context in which to perform puppet operations (evaluation, etc)
# The code to evaluate in this context is given in a block.
#
# @param env_name [String] a name to use for the temporary environment - this only shows up in errors
# @param modulepath [Array<String>] an array of directory paths containing Puppet modules, may be empty, defaults to empty array
# @param settings_hash [Hash] a hash of settings - currently not used for anything, defaults to empty hash
# @param facts [Hash] optional map of fact name to fact value - if not given will initialize the facts (which is a slow operation)
# @param variables [Hash] optional map of fully qualified variable name to value
# @return [Object] returns what the given block returns
# @yieldparam [Puppet::Pal] context, a context that responds to Puppet::Pal methods
#
def self.in_tmp_environment(env_name,
modulepath: [],
settings_hash: {},
facts: nil,
variables: {},
&block)
assert_non_empty_string(env_name, _("temporary environment name"))
# TRANSLATORS: do not translate variable name string in these assertions
assert_optionally_empty_array(modulepath, 'modulepath')
unless block_given?
raise ArgumentError, _("A block must be given to 'in_tmp_environment'") # TRANSLATORS 'in_tmp_environment' is a name, do not translate
end
env = Puppet::Node::Environment.create(env_name, modulepath)
in_environment_context(
Puppet::Environments::Static.new(env), # The tmp env is the only known env
env, facts, variables, &block
)
end
# Defines the context in which to perform puppet operations (evaluation, etc)
# The code to evaluate in this context is given in a block.
#
# The name of an environment (env_name) is always given. The location of that environment on disk
# is then either constructed by:
# * searching a given envpath where name is a child of a directory on that path, or
# * it is the directory given in env_dir (which must exist).
#
# The env_dir and envpath options are mutually exclusive.
#
# @param env_name [String] the name of an existing environment
# @param modulepath [Array<String>] an array of directory paths containing Puppet modules, overrides the modulepath of an existing env.
# Defaults to `{env_dir}/modules` if `env_dir` is given,
# @param pre_modulepath [Array<String>] like modulepath, but is prepended to the modulepath
# @param post_modulepath [Array<String>] like modulepath, but is appended to the modulepath
# @param settings_hash [Hash] a hash of settings - currently not used for anything, defaults to empty hash
# @param env_dir [String] a reference to a directory being the named environment (mutually exclusive with `envpath`)
# @param envpath [String] a path of directories in which there are environments to search for `env_name` (mutually exclusive with `env_dir`).
# Should be a single directory, or several directories separated with platform specific `File::PATH_SEPARATOR` character.
# @param facts [Hash] optional map of fact name to fact value - if not given will initialize the facts (which is a slow operation)
# @param variables [Hash] optional map of fully qualified variable name to value
# @return [Object] returns what the given block returns
# @yieldparam [Puppet::Pal] context, a context that responds to Puppet::Pal methods
#
# @api public
def self.in_environment(env_name,
modulepath: nil,
pre_modulepath: [],
post_modulepath: [],
settings_hash: {},
env_dir: nil,
envpath: nil,
facts: nil,
variables: {},
&block)
# TRANSLATORS terms in the assertions below are names of terms in code
assert_non_empty_string(env_name, 'env_name')
assert_optionally_empty_array(modulepath, 'modulepath', true)
assert_optionally_empty_array(pre_modulepath, 'pre_modulepath', false)
assert_optionally_empty_array(post_modulepath, 'post_modulepath', false)
assert_mutually_exclusive(env_dir, envpath, 'env_dir', 'envpath')
unless block_given?
raise ArgumentError, _("A block must be given to 'in_environment'") # TRANSLATORS 'in_environment' is a name, do not translate
end
if env_dir
unless Puppet::FileSystem.exist?(env_dir)
raise ArgumentError, _("The environment directory '%{env_dir}' does not exist") % { env_dir: env_dir }
end
# a nil modulepath for env_dir means it should use its ./modules directory
mid_modulepath = modulepath.nil? ? [Puppet::FileSystem.expand_path(File.join(env_dir, 'modules'))] : modulepath
env = Puppet::Node::Environment.create(env_name, pre_modulepath + mid_modulepath + post_modulepath)
environments = Puppet::Environments::StaticDirectory.new(env_name, env_dir, env) # The env being used is the only one...
else
assert_non_empty_string(envpath, 'envpath')
# The environment is resolved against the envpath. This is setup without a basemodulepath
# The modulepath defaults to the 'modulepath' in the found env when "Directories" is used
#
if envpath.is_a?(String) && envpath.include?(File::PATH_SEPARATOR)
# potentially more than one directory to search
env_loaders = Puppet::Environments::Directories.from_path(envpath, [])
environments = Puppet::Environments::Combined.new(*env_loaders)
else
environments = Puppet::Environments::Directories.new(envpath, [])
end
env = environments.get(env_name)
if env.nil?
raise ArgumentError, _("No directory found for the environment '%{env_name}' on the path '%{envpath}'") % { env_name: env_name, envpath: envpath }
end
# A given modulepath should override the default
mid_modulepath = modulepath.nil? ? env.modulepath : modulepath
env_path = env.configuration.path_to_env
env = env.override_with(:modulepath => pre_modulepath + mid_modulepath + post_modulepath)
# must configure this in case logic looks up the env by name again (otherwise the looked up env does
# not have the same effective modulepath).
environments = Puppet::Environments::StaticDirectory.new(env_name, env_path, env) # The env being used is the only one...
end
in_environment_context(environments, env, facts, variables, &block)
end
# Prepares the puppet context with pal information - and delegates to the block
# No set up is performed at this step - it is delayed until it is known what the
# operation is going to be (for example - using a ScriptCompiler).
#
def self.in_environment_context(environments, env, facts, variables, &block)
# Create a default node to use (may be overridden later)
node = Puppet::Node.new(Puppet[:node_name_value], :environment => env)
Puppet.override(
environments: environments, # The env being used is the only one...
pal_env: env, # provide as convenience
pal_current_node: node, # to allow it to be picked up instead of created
pal_variables: variables, # common set of variables across several inner contexts
pal_facts: facts # common set of facts across several inner contexts (or nil)
) do
# DELAY: prepare_node_facts(node, facts)
return block.call(self)
end
end
private_class_method :in_environment_context
# Prepares the node for use by giving it node_facts (if given)
# If a hash of facts values is given, then the operation of creating a node with facts is much
# speeded up (as getting a fresh set of facts is avoided in a later step).
#
def self.prepare_node_facts(node, facts)
# Prepare the node with facts if it does not already have them
if node.facts.nil?
node_facts = facts.nil? ? nil : Puppet::Node::Facts.new(Puppet[:node_name_value], facts)
node.fact_merge(node_facts)
# Add server facts so $server_facts[environment] exists when doing a puppet script
# SCRIPT TODO: May be needed when running scripts under orchestrator. Leave it for now.
#
node.add_server_facts({})
end
end
private_class_method :prepare_node_facts
def self.add_variables(scope, variables)
return if variables.nil?
unless variables.is_a?(Hash)
raise ArgumentError, _("Given variables must be a hash, got %{type}") % { type: variables.class }
end
rich_data_t = Puppet::Pops::Types::TypeFactory.rich_data
variables.each_pair do |k, v|
unless k =~ Puppet::Pops::Patterns::VAR_NAME
raise ArgumentError, _("Given variable '%{varname}' has illegal name") % { varname: k }
end
unless rich_data_t.instance?(v)
raise ArgumentError, _("Given value for '%{varname}' has illegal type - got: %{type}") % { varname: k, type: v.class }
end
scope.setvar(k, v)
end
end
private_class_method :add_variables
# The main routine for script compiler
# Picks up information from the puppet context and configures a script compiler which is given to
# the provided block
#
def self.main(
manifest: nil,
facts: {},
variables: {},
target_variables: {},
internal_compiler_class: nil,
set_local_facts: true
)
# Configure the load path
env = Puppet.lookup(:pal_env)
env.each_plugin_directory do |dir|
$LOAD_PATH << dir unless $LOAD_PATH.include?(dir)
end
# Puppet requires Facter, which initializes its lookup paths. Reset Facter to
# pickup the new $LOAD_PATH.
Puppet.runtime[:facter].reset
node = Puppet.lookup(:pal_current_node)
pal_facts = Puppet.lookup(:pal_facts)
pal_variables = Puppet.lookup(:pal_variables)
overrides = {}
unless facts.nil? || facts.empty?
pal_facts = pal_facts.merge(facts)
overrides[:pal_facts] = pal_facts
end
prepare_node_facts(node, pal_facts)
configured_environment = node.environment || Puppet.lookup(:current_environment)
apply_environment = manifest ?
configured_environment.override_with(:manifest => manifest) :
configured_environment
# Modify the node descriptor to use the special apply_environment.
# It is based on the actual environment from the node, or the locally
# configured environment if the node does not specify one.
# If a manifest file is passed on the command line, it overrides
# the :manifest setting of the apply_environment.
node.environment = apply_environment
# TRANSLATORS, the string "For puppet PAL" is not user facing
Puppet.override({ :current_environment => apply_environment }, "For puppet PAL") do
node.sanitize()
compiler = create_internal_compiler(internal_compiler_class, node)
case internal_compiler_class
when :script
pal_compiler = ScriptCompiler.new(compiler)
overrides[:pal_script_compiler] = overrides[:pal_compiler] = pal_compiler
when :catalog
pal_compiler = CatalogCompiler.new(compiler)
overrides[:pal_catalog_compiler] = overrides[:pal_compiler] = pal_compiler
end
# When scripting the trusted data are always local; default is to set them anyway
# When compiling for a catalog, the catalog compiler does this
if set_local_facts
compiler.topscope.set_trusted(node.trusted_data)
# Server facts are always about the local node's version etc.
compiler.topscope.set_server_facts(node.server_facts)
# Set $facts for the node running the script
facts_hash = node.facts.nil? ? {} : node.facts.values
compiler.topscope.set_facts(facts_hash)
# create the $settings:: variables
compiler.topscope.merge_settings(node.environment.name, false)
end
# Make compiler available to Puppet#lookup and injection in functions
# TODO: The compiler instances should be available under non PAL use as well!
# TRANSLATORS: Do not translate, symbolic name
Puppet.override(overrides, "PAL::with_#{internal_compiler_class}_compiler") do
compiler.compile do |_compiler_yield|
# In case the variables passed to the compiler are PCore types defined in modules, they
# need to be deserialized and added from within the this scope, so that loaders are
# available during deserizlization.
pal_variables = Puppet::Pops::Serialization::FromDataConverter.convert(pal_variables)
variables = Puppet::Pops::Serialization::FromDataConverter.convert(variables)
# Merge together target variables and plan variables. This will also shadow any
# collisions with facts and emit a warning.
topscope_vars = pal_variables.merge(merge_vars(target_variables, variables, node.facts.values))
add_variables(compiler.topscope, topscope_vars)
# wrap the internal compiler to prevent it from leaking in the PAL API
if block_given?
yield(pal_compiler)
end
end
end
rescue Puppet::Error
# already logged and handled by the compiler, including Puppet::ParseErrorWithIssue
raise
rescue => detail
Puppet.log_exception(detail)
raise
end
end
private_class_method :main
# Warn and remove variables that will be shadowed by facts of the same
# name, which are set in scope earlier.
def self.merge_vars(target_vars, vars, facts)
# First, shadow plan and target variables by facts of the same name
vars = shadow_vars(facts || {}, vars, 'fact', 'plan variable')
target_vars = shadow_vars(facts || {}, target_vars, 'fact', 'target variable')
# Then, shadow target variables by plan variables of the same name
target_vars = shadow_vars(vars, target_vars, 'plan variable', 'target variable')
target_vars.merge(vars)
end
private_class_method :merge_vars
def self.shadow_vars(vars, other_vars, vars_type, other_vars_type)
collisions, valid = other_vars.partition do |k, _|
vars.include?(k)
end
if collisions.any?
names = collisions.map { |k, _| "$#{k}" }.join(', ')
plural = collisions.length == 1 ? '' : 's'
Puppet.warning(
"#{other_vars_type.capitalize}#{plural} #{names} will be overridden by "\
"#{vars_type}#{plural} of the same name in the apply block"
)
end
valid.to_h
end
private_class_method :shadow_vars
def self.create_internal_compiler(compiler_class_reference, node)
case compiler_class_reference
when :script
Puppet::Parser::ScriptCompiler.new(node.environment, node.name)
when :catalog
Puppet::Parser::CatalogCompiler.new(node)
else
raise ArgumentError, "Internal Error: Invalid compiler type requested."
end
end
T_STRING = Puppet::Pops::Types::PStringType::NON_EMPTY
T_STRING_ARRAY = Puppet::Pops::Types::TypeFactory.array_of(T_STRING)
T_ANY_ARRAY = Puppet::Pops::Types::TypeFactory.array_of_any
T_BOOLEAN = Puppet::Pops::Types::PBooleanType::DEFAULT
T_GENERIC_TASK_HASH = Puppet::Pops::Types::TypeFactory.hash_kv(
Puppet::Pops::Types::TypeFactory.pattern(/\A[a-z][a-z0-9_]*\z/), Puppet::Pops::Types::TypeFactory.data
)
def self.assert_type(type, value, what, allow_nil = false)
Puppet::Pops::Types::TypeAsserter.assert_instance_of(nil, type, value, allow_nil) { _('Puppet Pal: %{what}') % { what: what } }
end
def self.assert_non_empty_string(s, what, allow_nil = false)
assert_type(T_STRING, s, what, allow_nil)
end
def self.assert_optionally_empty_array(a, what, allow_nil = false)
assert_type(T_STRING_ARRAY, a, what, allow_nil)
end
private_class_method :assert_optionally_empty_array
def self.assert_mutually_exclusive(a, b, a_term, b_term)
if a && b
raise ArgumentError, _("Cannot use '%{a_term}' and '%{b_term}' at the same time") % { a_term: a_term, b_term: b_term }
end
end
private_class_method :assert_mutually_exclusive
def self.assert_block_given(block)
if block.nil?
raise ArgumentError, _("A block must be given")
end
end
private_class_method :assert_block_given
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/pal/plan_signature.rb | lib/puppet/pal/plan_signature.rb | # frozen_string_literal: true
module Puppet
module Pal
# A PlanSignature is returned from `plan_signature`. Its purpose is to answer questions about the plans's parameters
# and if it can be called with a hash of named parameters.
#
# @api public
#
class PlanSignature
def initialize(plan_function)
@plan_func = plan_function
end
# Returns true or false depending on if the given PlanSignature is callable with a set of named arguments or not
# In addition to returning the boolean outcome, if a block is given, it is called with a string of formatted
# error messages that describes the difference between what was given and what is expected. The error message may
# have multiple lines of text, and each line is indented one space.
#
# @example Checking if signature is acceptable
#
# signature = pal.plan_signature('myplan')
# signature.callable_with?({x => 10}) { |errors| raise ArgumentError("Ooops: given arguments does not match\n#{errors}") }
#
# @api public
#
def callable_with?(args_hash)
dispatcher = @plan_func.class.dispatcher.dispatchers[0]
param_scope = {}
# Assign all non-nil values, even those that represent non-existent parameters.
args_hash.each { |k, v| param_scope[k] = v unless v.nil? }
dispatcher.parameters.each do |p|
name = p.name
arg = args_hash[name]
if arg.nil?
# Arg either wasn't given, or it was undef
if p.value.nil?
# No default. Assign nil if the args_hash included it
param_scope[name] = nil if args_hash.include?(name)
else
# parameter does not have a default value, it will be assigned its default when being called
# we assume that the default value is of the correct type and therefore simply skip
# checking this
# param_scope[name] = param_scope.evaluate(name, p.value, closure_scope, @evaluator)
end
end
end
errors = Puppet::Pops::Types::TypeMismatchDescriber.singleton.describe_struct_signature(dispatcher.params_struct, param_scope).flatten
return true if errors.empty?
if block_given?
yield errors.map(&:format).join("\n")
end
false
end
# Returns a PStructType describing the parameters as a puppet Struct data type
# Note that a `to_s` on the returned structure will result in a human readable Struct datatype as a
# description of what a plan expects.
#
# @return [Puppet::Pops::Types::PStructType] a struct data type describing the parameters and their types
#
# @api public
#
def params_type
dispatcher = @plan_func.class.dispatcher.dispatchers[0]
dispatcher.params_struct
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/provider/command.rb | lib/puppet/provider/command.rb | # frozen_string_literal: true
# A command that can be executed on the system
class Puppet::Provider::Command
attr_reader :executable
attr_reader :name
# @param [String] name A way of referencing the name
# @param [String] executable The path to the executable file
# @param resolver An object for resolving the executable to an absolute path (usually Puppet::Util)
# @param executor An object for performing the actual execution of the command (usually Puppet::Util::Execution)
# @param [Hash] options Extra options to be used when executing (see Puppet::Util::Execution#execute)
def initialize(name, executable, resolver, executor, options = {})
@name = name
@executable = executable
@resolver = resolver
@executor = executor
@options = options
end
# @param args [Array<String>] Any command line arguments to pass to the executable
# @return The output from the command
def execute(*args)
resolved_executable = @resolver.which(@executable) or raise Puppet::MissingCommand, _("Command %{name} is missing") % { name: @name }
@executor.execute([resolved_executable] + args, @options)
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/provider/package_targetable.rb | lib/puppet/provider/package_targetable.rb | # frozen_string_literal: true
# Targetable package providers implement a `command` attribute.
#
# The `packages` hash passed to `Puppet::Provider::Package::prefetch` is deduplicated,
# as it is keyed only by name in `Puppet::Transaction::prefetch_if_necessary`.
#
# (The `packages` hash passed to ``Puppet::Provider::Package::prefetch`` should be keyed by all namevars,
# possibly via a `prefetchV2` method that could take a better data structure.)
#
# In addition, `Puppet::Provider::Package::properties` calls `query` in the provider.
require_relative '../../puppet/provider/package'
# But `query` in the provider depends upon whether a `command` attribute is defined for the resource.
# This is a Catch-22.
#
# Instead ...
#
# Inspect any package to access the catalog (every package includes a reference to the catalog).
# Inspect the catalog to find all of the `command` attributes for all of the packages of this class.
# Find all of the package instances using each package `command`, including the default provider command.
# Assign each instance's `provider` by selecting it from the `packages` hash passed to `prefetch`, based upon `name` and `command`.
#
# The original `command` parameter in the catalog is not populated by the default (`:default`) for the parameter in type/package.rb.
# Rather, the result of the `original_parameters` is `nil` when the `command` parameter is undefined in the catalog.
class Puppet::Provider::Package::Targetable < Puppet::Provider::Package
# Prefetch our package list, yo.
def self.prefetch(packages)
catalog_packages = packages.values.first.catalog.resources.select { |p| p.provider.instance_of?(self) }
package_commands = catalog_packages.map { |catalog_package| catalog_package.original_parameters[:command] }.uniq
package_commands.each do |command|
instances(command).each do |instance|
catalog_packages.each do |catalog_package|
if catalog_package[:name] == instance.name && catalog_package.original_parameters[:command] == command
catalog_package.provider = instance
debug "Prefetched instance: %{name} via command: %{cmd}" % { name: instance.name, cmd: command || :default }
end
end
end
end
package_commands
end
# Returns the resource command or provider command.
def resource_or_provider_command
resource.original_parameters[:command] || self.class.provider_command
end
# Targetable providers use has_command/is_optional to defer validation of provider suitability.
# Evaluate provider suitability here and now by validating that the command is defined and exists.
#
# cmd: the full path to the package command.
def self.validate_command(cmd)
unless cmd
raise Puppet::Error, _("Provider %{name} package command is not functional on this host") % { name: name }
end
unless File.file?(cmd)
raise Puppet::Error, _("Provider %{name} package command '%{cmd}' does not exist on this host") % { name: name, cmd: cmd }
end
end
# Return information about the package, its provider, and its (optional) command.
def to_s
cmd = resource[:command] || :default
"#{@resource}(provider=#{self.class.name})(command=#{cmd})"
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/provider/aix_object.rb | lib/puppet/provider/aix_object.rb | # frozen_string_literal: true
# Common code for AIX user/group providers.
class Puppet::Provider::AixObject < Puppet::Provider
desc "Generic AIX resource provider"
# Class representing a MappedObject, which can either be an
# AIX attribute or a Puppet property. This class lets us
# write something like:
#
# attribute = mappings[:aix_attribute][:uid]
# attribute.name
# attribute.convert_property_value(uid)
#
# property = mappings[:puppet_property][:id]
# property.name
# property.convert_attribute_value(id)
#
# NOTE: This is an internal class specific to AixObject. It is
# not meant to be used anywhere else. That's why we do not have
# any validation code in here.
#
# NOTE: See the comments in the class-level mappings method to
# understand what we mean by pure and impure conversion functions.
#
# NOTE: The 'mapping' code, including this class, could possibly
# be moved to a separate module so that it can be re-used in some
# of our other providers. See PUP-9082.
class MappedObject
attr_reader :name
def initialize(name, conversion_fn, conversion_fn_code)
@name = name
@conversion_fn = conversion_fn
@conversion_fn_code = conversion_fn_code
return unless pure_conversion_fn?
# Our conversion function is pure, so we can go ahead
# and define it. This way, we can use this MappedObject
# at the class-level as well as at the instance-level.
define_singleton_method(@conversion_fn) do |value|
@conversion_fn_code.call(value)
end
end
def pure_conversion_fn?
@conversion_fn_code.arity == 1
end
# Sets our MappedObject's provider. This only makes sense
# if it has an impure conversion function. We will call this
# in the instance-level mappings method after the provider
# instance has been created to define our conversion function.
# Note that a MappedObject with an impure conversion function
# cannot be used at the class level.
def set_provider(provider)
define_singleton_method(@conversion_fn) do |value|
@conversion_fn_code.call(provider, value)
end
end
end
class << self
#-------------
# Mappings
# ------------
def mappings
return @mappings if @mappings
@mappings = {}
@mappings[:aix_attribute] = {}
@mappings[:puppet_property] = {}
@mappings
end
# Add a mapping from a Puppet property to an AIX attribute. The info must include:
#
# * :puppet_property -- The puppet property corresponding to this attribute
# * :aix_attribute -- The AIX attribute corresponding to this attribute. Defaults
# to puppet_property if this is not provided.
# * :property_to_attribute -- A lambda that converts a Puppet Property to an AIX attribute
# value. Defaults to the identity function if not provided.
# * :attribute_to_property -- A lambda that converts an AIX attribute to a Puppet property.
# Defaults to the identity function if not provided.
#
# NOTE: The lambdas for :property_to_attribute or :attribute_to_property can be 'pure'
# or 'impure'. A 'pure' lambda is one that needs only the value to do the conversion,
# while an 'impure' lambda is one that requires the provider instance along with the
# value. 'Pure' lambdas have the interface 'do |value| ...' while 'impure' lambdas have
# the interface 'do |provider, value| ...'.
#
# NOTE: 'Impure' lambdas are useful in case we need to generate more specific error
# messages or pass-in instance-specific command-line arguments.
def mapping(info = {})
identity_fn = ->(x) { x }
info[:aix_attribute] ||= info[:puppet_property]
info[:property_to_attribute] ||= identity_fn
info[:attribute_to_property] ||= identity_fn
mappings[:aix_attribute][info[:puppet_property]] = MappedObject.new(
info[:aix_attribute],
:convert_property_value,
info[:property_to_attribute]
)
mappings[:puppet_property][info[:aix_attribute]] = MappedObject.new(
info[:puppet_property],
:convert_attribute_value,
info[:attribute_to_property]
)
end
# Creates a mapping from a purely numeric Puppet property to
# an attribute
def numeric_mapping(info = {})
property = info[:puppet_property]
# We have this validation here b/c not all numeric properties
# handle this at the property level (e.g. like the UID). Given
# that, we might as well go ahead and do this validation for all
# of our numeric properties. Doesn't hurt.
info[:property_to_attribute] = lambda do |value|
unless value.is_a?(Integer)
raise ArgumentError, _("Invalid value %{value}: %{property} must be an Integer!") % { value: value, property: property }
end
value.to_s
end
# AIX will do the right validation to ensure numeric attributes
# can't be set to non-numeric values, so no need for the extra clutter.
info[:attribute_to_property] = lambda do |value|
value.to_i
end
mapping(info)
end
#-------------
# Useful Class Methods
# ------------
# Defines the getter and setter methods for each Puppet property that's mapped
# to an AIX attribute. We define only a getter for the :attributes property.
#
# Provider subclasses should call this method after they've defined all of
# their <puppet_property> => <aix_attribute> mappings.
def mk_resource_methods
# Define the Getter methods for each of our properties + the attributes
# property
properties = [:attributes]
properties += mappings[:aix_attribute].keys
properties.each do |property|
# Define the getter
define_method(property) do
get(property)
end
# We have a custom setter for the :attributes property,
# so no need to define it.
next if property == :attributes
# Define the setter
define_method("#{property}=".to_sym) do |value|
set(property, value)
end
end
end
# This helper splits a list separated by sep into its corresponding
# items. Note that a key precondition here is that none of the items
# in the list contain sep.
#
# Let A be the return value. Then one of our postconditions is:
# A.join(sep) == list
#
# NOTE: This function is only used by the parse_colon_separated_list
# function below. It is meant to be an inner lambda. The reason it isn't
# here is so we avoid having to create a proc. object for the split_list
# lambda each time parse_colon_separated_list is invoked. This will happen
# quite often since it is used at the class level and at the instance level.
# Since this function is meant to be an inner lambda and thus not exposed
# anywhere else, we do not have any unit tests for it. These test cases are
# instead covered by the unit tests for parse_colon_separated_list
def split_list(list, sep)
return [""] if list.empty?
list.split(sep, -1)
end
# Parses a colon-separated list. Example includes something like:
# <item1>:<item2>:<item3>:<item4>
#
# Returns an array of the parsed items, e.g.
# [ <item1>, <item2>, <item3>, <item4> ]
#
# Note that colons inside items are escaped by #!
def parse_colon_separated_list(colon_list)
# ALGORITHM:
# Treat the colon_list as a list separated by '#!:' We will get
# something like:
# [ <chunk1>, <chunk2>, ... <chunkn> ]
#
# Each chunk is now a list separated by ':' and none of the items
# in each chunk contains an escaped ':'. Now, split each chunk on
# ':' to get:
# [ [<piece11>, ..., <piece1n>], [<piece21>, ..., <piece2n], ... ]
#
# Now note that <item1> = <piece11>, <item2> = <piece12> in our original
# list, and that <itemn> = <piece1n>#!:<piece21>. This is the main idea
# behind what our inject method is trying to do at the end, except that
# we replace '#!:' with ':' since the colons are no longer escaped.
chunks = split_list(colon_list, '#!:')
chunks.map! { |chunk| split_list(chunk, ':') }
chunks.inject do |accum, chunk|
left = accum.pop
right = chunk.shift
accum.push("#{left}:#{right}")
accum += chunk
accum
end
end
# Parses the AIX objects from the command output, returning an array of
# hashes with each hash having the following schema:
# {
# :name => <object_name>
# :attributes => <object_attributes>
# }
#
# Output should be of the form
# #name:<attr1>:<attr2> ...
# <name>:<value1>:<value2> ...
# #name:<attr1>:<attr2> ...
# <name>:<value1>:<value2> ...
#
# NOTE: We need to parse the colon-formatted output in case we have
# space-separated attributes (e.g. 'gecos'). ":" characters are escaped
# with a "#!".
def parse_aix_objects(output)
# Object names cannot begin with '#', so we are safe to
# split individual users this way. We do not have to worry
# about an empty list either since there is guaranteed to be
# at least one instance of an AIX object (e.g. at least one
# user or one group on the system).
_, *objects = output.chomp.split(/^#/)
objects.map! do |object|
attributes_line, values_line = object.chomp.split("\n")
attributes = parse_colon_separated_list(attributes_line.chomp)
attributes.map!(&:to_sym)
values = parse_colon_separated_list(values_line.chomp)
attributes_hash = attributes.zip(values).to_h
object_name = attributes_hash.delete(:name)
[[:name, object_name.to_s], [:attributes, attributes_hash]].to_h
end
objects
end
# Lists all instances of the given object, taking in an optional set
# of ia_module arguments. Returns an array of hashes, each hash
# having the schema
# {
# :name => <object_name>
# :id => <object_id>
# }
def list_all(ia_module_args = [])
cmd = [command(:list), '-c', *ia_module_args, '-a', 'id', 'ALL']
parse_aix_objects(execute(cmd)).to_a.map do |object|
name = object[:name]
id = object[:attributes].delete(:id)
{ name: name, id: id }
end
end
#-------------
# Provider API
# ------------
def instances
list_all.to_a.map! do |object|
new({ :name => object[:name] })
end
end
end
# Instantiate our mappings. These need to be at the instance-level
# since some of our mapped objects may have impure conversion functions
# that need our provider instance.
def mappings
return @mappings if @mappings
@mappings = {}
self.class.mappings.each do |type, mapped_objects|
@mappings[type] = {}
mapped_objects.each do |input, mapped_object|
if mapped_object.pure_conversion_fn?
# Our mapped_object has a pure conversion function so we
# can go ahead and use it as-is.
@mappings[type][input] = mapped_object
next
end
# Otherwise, we need to dup it and set its provider to our
# provider instance. The dup is necessary so that we do not
# touch the class-level mapped object.
@mappings[type][input] = mapped_object.dup
@mappings[type][input].set_provider(self)
end
end
@mappings
end
# Converts the given attributes hash to CLI args.
def attributes_to_args(attributes)
attributes.map do |attribute, value|
"#{attribute}=#{value}"
end
end
def ia_module_args
raise ArgumentError, _("Cannot have both 'forcelocal' and 'ia_load_module' at the same time!") if @resource[:ia_load_module] && @resource[:forcelocal]
return ["-R", @resource[:ia_load_module].to_s] if @resource[:ia_load_module]
return ["-R", "files"] if @resource[:forcelocal]
[]
end
def lscmd
[self.class.command(:list), '-c'] + ia_module_args + [@resource[:name]]
end
def addcmd(attributes)
attribute_args = attributes_to_args(attributes)
[self.class.command(:add)] + ia_module_args + attribute_args + [@resource[:name]]
end
def deletecmd
[self.class.command(:delete)] + ia_module_args + [@resource[:name]]
end
def modifycmd(new_attributes)
attribute_args = attributes_to_args(new_attributes)
[self.class.command(:modify)] + ia_module_args + attribute_args + [@resource[:name]]
end
# Modifies the AIX object by setting its new attributes.
def modify_object(new_attributes)
execute(modifycmd(new_attributes))
object_info(true)
end
# Gets a Puppet property's value from object_info
def get(property)
return :absent unless exists?
object_info[property] || :absent
end
# Sets a mapped Puppet property's value.
def set(property, value)
aix_attribute = mappings[:aix_attribute][property]
modify_object(
{ aix_attribute.name => aix_attribute.convert_property_value(value) }
)
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error, _("Could not set %{property} on %{resource}[%{name}]: %{detail}") % { property: property, resource: @resource.class.name, name: @resource.name, detail: detail }, detail.backtrace
end
# This routine validates our new attributes property value to ensure
# that it does not contain any Puppet properties.
def validate_new_attributes(new_attributes)
# Gather all of the <puppet property>, <aix attribute> conflicts to print
# them all out when we create our error message. This makes it easy for the
# user to update their manifest based on our error message.
conflicts = {}
mappings[:aix_attribute].each do |property, aix_attribute|
next unless new_attributes.key?(aix_attribute.name)
conflicts[:properties] ||= []
conflicts[:properties].push(property)
conflicts[:attributes] ||= []
conflicts[:attributes].push(aix_attribute.name)
end
return if conflicts.empty?
properties, attributes = conflicts.keys.map do |key|
conflicts[key].map! { |name| "'#{name}'" }.join(', ')
end
detail = _("attributes is setting the %{properties} properties via. the %{attributes} attributes, respectively! Please specify these property values in the resource declaration instead.") % { properties: properties, attributes: attributes }
raise Puppet::Error, _("Could not set attributes on %{resource}[%{name}]: %{detail}") % { resource: @resource.class.name, name: @resource.name, detail: detail }
end
# Modifies the attribute property. Note we raise an error if the user specified
# an AIX attribute corresponding to a Puppet property.
def attributes=(new_attributes)
validate_new_attributes(new_attributes)
modify_object(new_attributes)
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error, _("Could not set attributes on %{resource}[%{name}]: %{detail}") % { resource: @resource.class.name, name: @resource.name, detail: detail }, detail.backtrace
end
# Collects the current property values of all mapped properties +
# the attributes property.
def object_info(refresh = false)
return @object_info if @object_info && !refresh
@object_info = nil
begin
output = execute(lscmd)
rescue Puppet::ExecutionFailure
Puppet.debug(_("aix.object_info(): Could not find %{resource}[%{name}]") % { resource: @resource.class.name, name: @resource.name })
return @object_info
end
# If lscmd succeeds, then output will contain our object's information.
# Thus, .parse_aix_objects will always return a single element array.
aix_attributes = self.class.parse_aix_objects(output).first[:attributes]
aix_attributes.each do |attribute, value|
@object_info ||= {}
# If our attribute has a Puppet property, then we store that. Else, we store it as part
# of our :attributes property hash
if (property = mappings[:puppet_property][attribute])
@object_info[property.name] = property.convert_attribute_value(value)
else
@object_info[:attributes] ||= {}
@object_info[:attributes][attribute] = value
end
end
@object_info
end
#-------------
# Methods that manage the ensure property
# ------------
# Check that the AIX object exists
def exists?
!object_info.nil?
end
# Creates a new instance of the resource
def create
attributes = @resource.should(:attributes) || {}
validate_new_attributes(attributes)
mappings[:aix_attribute].each do |property, aix_attribute|
property_should = @resource.should(property)
next if property_should.nil?
attributes[aix_attribute.name] = aix_attribute.convert_property_value(property_should)
end
execute(addcmd(attributes))
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error, _("Could not create %{resource} %{name}: %{detail}") % { resource: @resource.class.name, name: @resource.name, detail: detail }, detail.backtrace
end
# Deletes this instance resource
def delete
execute(deletecmd)
# Recollect the object info so that our current properties reflect
# the actual state of the system. Otherwise, puppet resource reports
# the wrong info. at the end. Note that this should return nil.
object_info(true)
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error, _("Could not delete %{resource} %{name}: %{detail}") % { resource: @resource.class.name, name: @resource.name, detail: detail }, detail.backtrace
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/provider/package.rb | lib/puppet/provider/package.rb | # frozen_string_literal: true
require_relative '../../puppet/provider'
class Puppet::Provider::Package < Puppet::Provider
# Prefetch our package list, yo.
def self.prefetch(packages)
instances.each do |prov|
pkg = packages[prov.name]
if pkg
pkg.provider = prov
end
end
end
# Clear out the cached values.
def flush
@property_hash.clear
end
# Look up the current status.
def properties
if @property_hash.empty?
# For providers that support purging, default to purged; otherwise default to absent
# Purged is the "most uninstalled" a package can be, so a purged package will be in-sync with
# either `ensure => absent` or `ensure => purged`; an absent package will be out of sync with `ensure => purged`.
default_status = self.class.feature?(:purgeable) ? :purged : :absent
@property_hash = query || { :ensure => default_status }
@property_hash[:ensure] = default_status if @property_hash.empty?
end
@property_hash.dup
end
def validate_source(value)
true
end
# Turns a array of options into flags to be passed to a command.
# The options can be passed as a string or hash. Note that passing a hash
# should only be used in case --foo=bar must be passed,
# which can be accomplished with:
# install_options => [ { '--foo' => 'bar' } ]
# Regular flags like '--foo' must be passed as a string.
# @param options [Array]
# @return Concatenated list of options
# @api private
def join_options(options)
return unless options
options.collect do |val|
case val
when Hash
val.keys.sort.collect do |k|
"#{k}=#{val[k]}"
end
else
val
end
end.flatten
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/provider/exec.rb | lib/puppet/provider/exec.rb | # frozen_string_literal: true
require_relative '../../puppet/provider'
require_relative '../../puppet/util/execution'
class Puppet::Provider::Exec < Puppet::Provider
include Puppet::Util::Execution
def environment
env = {}
if (path = resource[:path])
env[:PATH] = path.join(File::PATH_SEPARATOR)
end
return env unless (envlist = resource[:environment])
envlist = [envlist] unless envlist.is_a? Array
envlist.each do |setting|
unless (match = /^(\w+)=((.|\n)*)$/.match(setting))
warning _("Cannot understand environment setting %{setting}") % { setting: setting.inspect }
next
end
var = match[1]
value = match[2]
if env.include?(var) || env.include?(var.to_sym)
warning _("Overriding environment setting '%{var}' with '%{value}'") % { var: var, value: value }
end
if value.nil? || value.empty?
msg = _("Empty environment setting '%{var}'") % { var: var }
Puppet.warn_once('undefined_variables', "empty_env_var_#{var}", msg, resource.file, resource.line)
end
env[var] = value
end
env
end
def run(command, check = false)
output = nil
sensitive = resource.parameters[:command].sensitive
checkexe(command)
debug "Executing#{check ? ' check' : ''} '#{sensitive ? '[redacted]' : command}'"
# Ruby 2.1 and later interrupt execution in a way that bypasses error
# handling by default. Passing Timeout::Error causes an exception to be
# raised that can be rescued inside of the block by cleanup routines.
#
# This is backwards compatible all the way to Ruby 1.8.7.
Timeout.timeout(resource[:timeout], Timeout::Error) do
cwd = resource[:cwd]
# It's ok if cwd is nil. In that case Puppet::Util::Execution.execute() simply will not attempt to
# change the working directory, which is exactly the right behavior when no cwd parameter is
# expressed on the resource. Moreover, attempting to change to the directory that is already
# the working directory can fail under some circumstances, so avoiding the directory change attempt
# is preferable to defaulting cwd to that directory.
# note that we are passing "false" for the "override_locale" parameter, which ensures that the user's
# default/system locale will be respected. Callers may override this behavior by setting locale-related
# environment variables (LANG, LC_ALL, etc.) in their 'environment' configuration.
output = Puppet::Util::Execution.execute(
command,
:failonfail => false,
:combine => true,
:cwd => cwd,
:uid => resource[:user], :gid => resource[:group],
:override_locale => false,
:custom_environment => environment(),
:sensitive => sensitive
)
end
# The shell returns 127 if the command is missing.
if output.exitstatus == 127
raise ArgumentError, output
end
# Return output twice as processstatus was returned before, but only exitstatus was ever called.
# Output has the exitstatus on it so it is returned instead. This is here twice as changing this
# would result in a change to the underlying API.
[output, output]
end
def extractexe(command)
if command.is_a? Array
command.first
else
match = /^"([^"]+)"|^'([^']+)'/.match(command)
if match
# extract whichever of the two sides matched the content.
match[1] or match[2]
else
command.split(/ /)[0]
end
end
end
def validatecmd(command)
exe = extractexe(command)
# if we're not fully qualified, require a path
self.fail _("'%{exe}' is not qualified and no path was specified. Please qualify the command or specify a path.") % { exe: exe } if !absolute_path?(exe) and resource[:path].nil?
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/nameservice.rb | lib/puppet/provider/nameservice.rb | # frozen_string_literal: true
require_relative '../../puppet'
# This is the parent class of all NSS classes. They're very different in
# their backend, but they're pretty similar on the front-end. This class
# provides a way for them all to be as similar as possible.
class Puppet::Provider::NameService < Puppet::Provider
class << self
def autogen_default(param)
defined?(@autogen_defaults) ? @autogen_defaults[param.intern] : nil
end
def autogen_defaults(hash)
@autogen_defaults ||= {}
hash.each do |param, value|
@autogen_defaults[param.intern] = value
end
end
def initvars
@checks = {}
@options = {}
super
end
def instances
objects = []
begin
method = Puppet::Etc.method(:"get#{section}ent")
while ent = method.call # rubocop:disable Lint/AssignmentInCondition
objects << new(:name => ent.name, :canonical_name => ent.canonical_name, :ensure => :present)
end
ensure
Puppet::Etc.send("end#{section}ent")
end
objects
end
def option(name, option)
name = name.intern if name.is_a? String
(defined?(@options) and @options.include? name and @options[name].include? option) ? @options[name][option] : nil
end
def options(name, hash)
unless resource_type.valid_parameter?(name)
raise Puppet::DevError, _("%{name} is not a valid attribute for %{resource_type}") % { name: name, resource_type: resource_type.name }
end
@options ||= {}
@options[name] ||= {}
# Set options individually, so we can call the options method
# multiple times.
hash.each do |param, value|
@options[name][param] = value
end
end
def resource_type=(resource_type)
super
@resource_type.validproperties.each do |prop|
next if prop == :ensure
define_method(prop) { get(prop) || :absent } unless public_method_defined?(prop)
define_method(prop.to_s + "=") { |*vals| set(prop, *vals) } unless public_method_defined?(prop.to_s + "=")
end
end
# This is annoying, but there really aren't that many options,
# and this *is* built into Ruby.
def section
unless resource_type
raise Puppet::DevError,
"Cannot determine Etc section without a resource type"
end
if @resource_type.name == :group
"gr"
else
"pw"
end
end
def validate(name, value)
name = name.intern if name.is_a? String
if @checks.include? name
block = @checks[name][:block]
raise ArgumentError, _("Invalid value %{value}: %{error}") % { value: value, error: @checks[name][:error] } unless block.call(value)
end
end
def verify(name, error, &block)
name = name.intern if name.is_a? String
@checks[name] = { :error => error, :block => block }
end
private
def op(property)
@ops[property.name] || "-#{property.name}"
end
end
# Autogenerate a value. Mostly used for uid/gid, but also used heavily
# with DirectoryServices
def autogen(field)
field = field.intern
id_generators = { :user => :uid, :group => :gid }
if id_generators[@resource.class.name] == field
self.class.autogen_id(field, @resource.class.name)
else
value = self.class.autogen_default(field)
if value
value
elsif respond_to?("autogen_#{field}")
send("autogen_#{field}")
else
nil
end
end
end
# Autogenerate either a uid or a gid. This is not very flexible: we can
# only generate one field type per class, and get kind of confused if asked
# for both.
def self.autogen_id(field, resource_type)
# Figure out what sort of value we want to generate.
case resource_type
when :user; database = :passwd; method = :uid
when :group; database = :group; method = :gid
else
# TRANSLATORS "autogen_id()" is a method name and should not be translated
raise Puppet::DevError, _("autogen_id() does not support auto generation of id for resource type %{resource_type}") % { resource_type: resource_type }
end
# Initialize from the data set, if needed.
unless @prevauto
# Sadly, Etc doesn't return an enumerator, it just invokes the block
# given, or returns the first record from the database. There is no
# other, more convenient enumerator for these, so we fake one with this
# loop. Thanks, Ruby, for your awesome abstractions. --daniel 2012-03-23
highest = []
Puppet::Etc.send(database) { |entry| highest << entry.send(method) }
highest = highest.reject { |x| x > 65_000 }.max
@prevauto = highest || 1000
end
# ...and finally increment and return the next value.
@prevauto += 1
end
def create
if exists?
info _("already exists")
# The object already exists
return nil
end
begin
sensitive = has_sensitive_data?
execute(addcmd, { :failonfail => true, :combine => true, :custom_environment => @custom_environment, :sensitive => sensitive })
if feature?(:manages_password_age) && (cmd = passcmd)
execute(cmd, { :failonfail => true, :combine => true, :custom_environment => @custom_environment, :sensitive => sensitive })
end
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error, _("Could not create %{resource} %{name}: %{detail}") % { resource: @resource.class.name, name: @resource.name, detail: detail }, detail.backtrace
end
end
def delete
unless exists?
info _("already absent")
# the object already doesn't exist
return nil
end
begin
execute(deletecmd, { :failonfail => true, :combine => true, :custom_environment => @custom_environment })
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error, _("Could not delete %{resource} %{name}: %{detail}") % { resource: @resource.class.name, name: @resource.name, detail: detail }, detail.backtrace
end
end
def ensure
if exists?
:present
else
:absent
end
end
# Does our object exist?
def exists?
!!getinfo(true)
end
# Retrieve a specific value by name.
def get(param)
(hash = getinfo(false)) ? unmunge(param, hash[param]) : nil
end
def munge(name, value)
block = self.class.option(name, :munge)
if block and block.is_a? Proc
block.call(value)
else
value
end
end
def unmunge(name, value)
block = self.class.option(name, :unmunge)
if block and block.is_a? Proc
block.call(value)
else
value
end
end
# Retrieve what we can about our object
def getinfo(refresh)
if @objectinfo.nil? or refresh == true
@etcmethod ||= ("get" + self.class.section.to_s + "nam").intern
begin
@objectinfo = Puppet::Etc.send(@etcmethod, @canonical_name)
rescue ArgumentError
@objectinfo = nil
end
end
# Now convert our Etc struct into a hash.
@objectinfo ? info2hash(@objectinfo) : nil
end
# The list of all groups the user is a member of. Different
# user mgmt systems will need to override this method.
def groups
Puppet::Util::POSIX.groups_of(@resource[:name]).join(',')
end
# Convert the Etc struct into a hash.
def info2hash(info)
hash = {}
self.class.resource_type.validproperties.each do |param|
method = posixmethod(param)
hash[param] = info.send(posixmethod(param)) if info.respond_to? method
end
hash
end
def initialize(resource)
super
@custom_environment = {}
@objectinfo = nil
if resource.is_a?(Hash) && !resource[:canonical_name].nil?
@canonical_name = resource[:canonical_name]
else
@canonical_name = resource[:name]
end
end
def set(param, value)
self.class.validate(param, value)
cmd = modifycmd(param, munge(param, value))
raise Puppet::DevError, _("Nameservice command must be an array") unless cmd.is_a?(Array)
sensitive = has_sensitive_data?(param)
begin
execute(cmd, { :failonfail => true, :combine => true, :custom_environment => @custom_environment, :sensitive => sensitive })
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error, _("Could not set %{param} on %{resource}[%{name}]: %{detail}") % { param: param, resource: @resource.class.name, name: @resource.name, detail: detail }, detail.backtrace
end
end
# Derived classes can override to declare sensitive data so a flag can be passed to execute
def has_sensitive_data?(property = nil)
false
end
# From overriding Puppet::Property#insync? Ruby Etc::getpwnam < 2.1.0 always
# returns a struct with binary encoded string values, and >= 2.1.0 will return
# binary encoded strings for values incompatible with current locale charset,
# or Encoding.default_external if compatible. Compare a "should" value with
# encoding of "current" value, to avoid unnecessary property syncs and
# comparison of strings with different encodings. (PUP-6777)
#
# return basic string comparison after re-encoding (same as
# Puppet::Property#property_matches)
def comments_insync?(current, should)
# we're only doing comparison here so don't mutate the string
desired = should[0].to_s.dup
current == desired.force_encoding(current.encoding)
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/provider/parsedfile.rb | lib/puppet/provider/parsedfile.rb | # frozen_string_literal: true
require_relative '../../puppet'
require_relative '../../puppet/util/filetype'
require_relative '../../puppet/util/fileparsing'
# This provider can be used as the parent class for a provider that
# parses and generates files. Its content must be loaded via the
# 'prefetch' method, and the file will be written when 'flush' is called
# on the provider instance. At this point, the file is written once
# for every provider instance.
#
# Once the provider prefetches the data, it's the resource's job to copy
# that data over to the @is variables.
#
# NOTE: The prefetch method swallows FileReadErrors by treating the
# corresponding target as an empty file. If you would like to turn this
# behavior off, then set the raise_prefetch_errors class variable to
# true. Doing so will error all resources associated with the failed
# target.
class Puppet::Provider::ParsedFile < Puppet::Provider
extend Puppet::Util::FileParsing
class << self
attr_accessor :default_target, :target, :raise_prefetch_errors
end
attr_accessor :property_hash
def self.clean(hash)
newhash = hash.dup
[:record_type, :on_disk].each do |p|
newhash.delete(p) if newhash.include?(p)
end
newhash
end
def self.clear
@target_objects.clear
@records.clear
end
def self.filetype
@filetype ||= Puppet::Util::FileType.filetype(:flat)
end
def self.filetype=(type)
if type.is_a?(Class)
@filetype = type
else
klass = Puppet::Util::FileType.filetype(type)
if klass
@filetype = klass
else
raise ArgumentError, _("Invalid filetype %{type}") % { type: type }
end
end
end
# Flush all of the targets for which there are modified records. The only
# reason we pass a record here is so that we can add it to the stack if
# necessary -- it's passed from the instance calling 'flush'.
def self.flush(record)
# Make sure this record is on the list to be flushed.
unless record[:on_disk]
record[:on_disk] = true
@records << record
# If we've just added the record, then make sure our
# target will get flushed.
modified(record[:target] || default_target)
end
return unless defined?(@modified) and !@modified.empty?
flushed = []
begin
@modified.sort_by(&:to_s).uniq.each do |target|
Puppet.debug "Flushing #{@resource_type.name} provider target #{target}"
flushed << target
flush_target(target)
end
ensure
@modified.reject! { |t| flushed.include?(t) }
end
end
# Make sure our file is backed up, but only back it up once per transaction.
# We cheat and rely on the fact that @records is created on each prefetch.
def self.backup_target(target)
return nil unless target_object(target).respond_to?(:backup)
@backup_stats ||= {}
return nil if @backup_stats[target] == @records.object_id
target_object(target).backup
@backup_stats[target] = @records.object_id
end
# Flush all of the records relating to a specific target.
def self.flush_target(target)
if @raise_prefetch_errors && @failed_prefetch_targets.key?(target)
raise Puppet::Error, _("Failed to read %{target}'s records when prefetching them. Reason: %{detail}") % { target: target, detail: @failed_prefetch_targets[target] }
end
backup_target(target)
records = target_records(target).reject { |r|
r[:ensure] == :absent
}
target_object(target).write(to_file(records))
end
# Return the header placed at the top of each generated file, warning
# users that modifying this file manually is probably a bad idea.
def self.header
%(# HEADER: This file was autogenerated at #{Time.now}
# HEADER: by puppet. While it can still be managed manually, it
# HEADER: is definitely not recommended.\n)
end
# An optional regular expression matched by third party headers.
#
# For example, this can be used to filter the vixie cron headers as
# erroneously exported by older cron versions.
#
# @api private
# @abstract Providers based on ParsedFile may implement this to make it
# possible to identify a header maintained by a third party tool.
# The provider can then allow that header to remain near the top of the
# written file, or remove it after composing the file content.
# If implemented, the function must return a Regexp object.
# The expression must be tailored to match exactly one third party header.
# @see drop_native_header
# @note When specifying regular expressions in multiline mode, avoid
# greedy repetitions such as '.*' (use .*? instead). Otherwise, the
# provider may drop file content between sparse headers.
def self.native_header_regex
nil
end
# How to handle third party headers.
# @api private
# @abstract Providers based on ParsedFile that make use of the support for
# third party headers may override this method to return +true+.
# When this is done, headers that are matched by the native_header_regex
# are not written back to disk.
# @see native_header_regex
def self.drop_native_header
false
end
# Add another type var.
def self.initvars
@records = []
@target_objects = {}
# Hash of <target> => <failure reason>.
@failed_prefetch_targets = {}
@raise_prefetch_errors = false
@target = nil
# Default to flat files
@filetype ||= Puppet::Util::FileType.filetype(:flat)
super
end
# Return a list of all of the records we can find.
def self.instances
targets.collect do |target|
prefetch_target(target)
end.flatten.reject { |r| skip_record?(r) }.collect do |record|
new(record)
end
end
# Override the default method with a lot more functionality.
def self.mk_resource_methods
[resource_type.validproperties, resource_type.parameters].flatten.each do |attr|
attr = attr.intern
define_method(attr) do
# If it's not a valid field for this record type (which can happen
# when different platforms support different fields), then just
# return the should value, so the resource shuts up.
if @property_hash[attr] or self.class.valid_attr?(self.class.name, attr)
@property_hash[attr] || :absent
elsif defined?(@resource)
@resource.should(attr)
else
nil
end
end
define_method(attr.to_s + "=") do |val|
mark_target_modified
@property_hash[attr] = val
end
end
end
# Always make the resource methods.
def self.resource_type=(resource)
super
mk_resource_methods
end
# Mark a target as modified so we know to flush it. This only gets
# used within the attr= methods.
def self.modified(target)
@modified ||= []
@modified << target unless @modified.include?(target)
end
# Retrieve all of the data from disk. There are three ways to know
# which files to retrieve: We might have a list of file objects already
# set up, there might be instances of our associated resource and they
# will have a path parameter set, and we will have a default path
# set. We need to turn those three locations into a list of files,
# prefetch each one, and make sure they're associated with each appropriate
# resource instance.
def self.prefetch(resources = nil)
# Reset the record list.
@records = prefetch_all_targets(resources)
match_providers_with_resources(resources)
end
# Match a list of catalog resources with provider instances
#
# @api private
#
# @param [Array<Puppet::Resource>] resources A list of resources using this class as a provider
def self.match_providers_with_resources(resources)
return unless resources
matchers = resources.dup
@records.each do |record|
# Skip things like comments and blank lines
next if skip_record?(record)
if (resource = resource_for_record(record, resources))
resource.provider = new(record)
elsif respond_to?(:match)
resource = match(record, matchers)
if resource
matchers.delete(resource.title)
record[:name] = resource[:name]
resource.provider = new(record)
end
end
end
end
# Look up a resource based on a parsed file record
#
# @api private
#
# @param [Hash<Symbol, Object>] record
# @param [Array<Puppet::Resource>] resources
#
# @return [Puppet::Resource, nil] The resource if found, else nil
def self.resource_for_record(record, resources)
name = record[:name]
if name
resources[name]
end
end
def self.prefetch_all_targets(resources)
records = []
targets(resources).each do |target|
records += prefetch_target(target)
end
records
end
# Prefetch an individual target.
def self.prefetch_target(target)
begin
target_records = retrieve(target)
unless target_records
raise Puppet::DevError, _("Prefetching %{target} for provider %{name} returned nil") % { target: target, name: name }
end
rescue Puppet::Util::FileType::FileReadError => detail
if @raise_prefetch_errors
# We will raise an error later in flush_target. This way,
# only the resources linked to our target will fail
# evaluation.
@failed_prefetch_targets[target] = detail.to_s
else
puts detail.backtrace if Puppet[:trace]
Puppet.err _("Could not prefetch %{resource} provider '%{name}' target '%{target}': %{detail}. Treating as empty") % { resource: resource_type.name, name: name, target: target, detail: detail }
end
target_records = []
end
target_records.each do |r|
r[:on_disk] = true
r[:target] = target
r[:ensure] = :present
end
target_records = prefetch_hook(target_records) if respond_to?(:prefetch_hook)
raise Puppet::DevError, _("Prefetching %{target} for provider %{name} returned nil") % { target: target, name: name } unless target_records
target_records
end
# Is there an existing record with this name?
def self.record?(name)
return nil unless @records
@records.find { |r| r[:name] == name }
end
# Retrieve the text for the file. Returns nil in the unlikely
# event that it doesn't exist.
def self.retrieve(path)
# XXX We need to be doing something special here in case of failure.
text = target_object(path).read
if text.nil? or text == ""
# there is no file
[]
else
# Set the target, for logging.
old = @target
begin
@target = path
parse(text)
rescue Puppet::Error => detail
detail.file = @target if detail.respond_to?(:file=)
raise detail
ensure
@target = old
end
end
end
# Should we skip the record? Basically, we skip text records.
# This is only here so subclasses can override it.
def self.skip_record?(record)
record_type(record[:record_type]).text?
end
# The mode for generated files if they are newly created.
# No mode will be set on existing files.
#
# @abstract Providers inheriting parsedfile can override this method
# to provide a mode. The value should be suitable for File.chmod
def self.default_mode
nil
end
# Initialize the object if necessary.
def self.target_object(target)
# only send the default mode if the actual provider defined it,
# because certain filetypes (e.g. the crontab variants) do not
# expect it in their initialize method
if default_mode
@target_objects[target] ||= filetype.new(target, default_mode)
else
@target_objects[target] ||= filetype.new(target)
end
@target_objects[target]
end
# Find all of the records for a given target
def self.target_records(target)
@records.find_all { |r| r[:target] == target }
end
# Find a list of all of the targets that we should be reading. This is
# used to figure out what targets we need to prefetch.
def self.targets(resources = nil)
targets = []
# First get the default target
raise Puppet::DevError, _("Parsed Providers must define a default target") unless default_target
targets << default_target
# Then get each of the file objects
targets += @target_objects.keys
# Lastly, check the file from any resource instances
if resources
resources.each do |_name, resource|
value = resource.should(:target)
if value
targets << value
end
end
end
targets.uniq.compact
end
# Compose file contents from the set of records.
#
# If self.native_header_regex is not nil, possible vendor headers are
# identified by matching the return value against the expression.
# If one (or several consecutive) such headers, are found, they are
# either moved in front of the self.header if self.drop_native_header
# is false (this is the default), or removed from the return value otherwise.
#
# @api private
def self.to_file(records)
text = super
if native_header_regex and (match = text.match(native_header_regex))
if drop_native_header
# concatenate the text in front of and after the native header
text = match.pre_match + match.post_match
else
native_header = match[0]
return native_header + header + match.pre_match + match.post_match
end
end
header + text
end
def create
@resource.class.validproperties.each do |property|
value = @resource.should(property)
if value
@property_hash[property] = value
end
end
mark_target_modified
(@resource.class.name.to_s + "_created").intern
end
def destroy
# We use the method here so it marks the target as modified.
self.ensure = :absent
(@resource.class.name.to_s + "_deleted").intern
end
def exists?
!(@property_hash[:ensure] == :absent or @property_hash[:ensure].nil?)
end
# Write our data to disk.
def flush
# Make sure we've got a target and name set.
# If the target isn't set, then this is our first modification, so
# mark it for flushing.
unless @property_hash[:target]
@property_hash[:target] = @resource.should(:target) || self.class.default_target
self.class.modified(@property_hash[:target])
end
@resource.class.key_attributes.each do |attr|
@property_hash[attr] ||= @resource[attr]
end
self.class.flush(@property_hash)
end
def initialize(record)
super
# The 'record' could be a resource or a record, depending on how the provider
# is initialized. If we got an empty property hash (probably because the resource
# is just being initialized), then we want to set up some defaults.
@property_hash = self.class.record?(resource[:name]) || { :record_type => self.class.name, :ensure => :absent } if @property_hash.empty?
end
# Retrieve the current state from disk.
def prefetch
raise Puppet::DevError, _("Somehow got told to prefetch with no resource set") unless @resource
self.class.prefetch(@resource[:name] => @resource)
end
def record_type
@property_hash[:record_type]
end
private
# Mark both the resource and provider target as modified.
def mark_target_modified
restarget = @resource.should(:target) if defined?(@resource)
if restarget && restarget != @property_hash[:target]
self.class.modified(restarget)
end
self.class.modified(@property_hash[:target]) if @property_hash[:target] != :absent and @property_hash[:target]
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/provider/ldap.rb | lib/puppet/provider/ldap.rb | # frozen_string_literal: true
require_relative '../../puppet/provider'
# The base class for LDAP providers.
class Puppet::Provider::Ldap < Puppet::Provider
require_relative '../../puppet/util/ldap/manager'
class << self
attr_reader :manager
end
# Look up all instances at our location. Yay.
def self.instances
list = manager.search
return [] unless list
list.collect { |entry| new(entry) }
end
# Specify the ldap manager for this provider, which is
# used to figure out how we actually interact with ldap.
def self.manages(*args)
@manager = Puppet::Util::Ldap::Manager.new
@manager.manages(*args)
# Set up our getter/setter methods.
mk_resource_methods
@manager
end
# Query all of our resources from ldap.
def self.prefetch(resources)
resources.each do |name, resource|
result = manager.find(name)
if result
result[:ensure] = :present
resource.provider = new(result)
else
resource.provider = new(:ensure => :absent)
end
end
end
def manager
self.class.manager
end
def create
@property_hash[:ensure] = :present
self.class.resource_type.validproperties.each do |property|
val = resource.should(property)
if val
if property.to_s == 'gid'
self.gid = val
else
@property_hash[property] = val
end
end
end
end
def delete
@property_hash[:ensure] = :absent
end
def exists?
@property_hash[:ensure] != :absent
end
# Apply our changes to ldap, yo.
def flush
# Just call the manager's update() method.
@property_hash.delete(:groups)
@ldap_properties.delete(:groups)
manager.update(name, ldap_properties, properties)
@property_hash.clear
@ldap_properties.clear
end
def initialize(*args)
raise(Puppet::DevError, _("No LDAP Configuration defined for %{class_name}") % { class_name: self.class }) unless self.class.manager
raise(Puppet::DevError, _("Invalid LDAP Configuration defined for %{class_name}") % { class_name: self.class }) unless self.class.manager.valid?
super
@property_hash = @property_hash.each_with_object({}) do |ary, result|
param, values = ary
# Skip any attributes we don't manage.
next result unless self.class.resource_type.valid_parameter?(param)
paramclass = self.class.resource_type.attrclass(param)
unless values.is_a?(Array)
result[param] = values
next result
end
# Only use the first value if the attribute class doesn't manage
# arrays of values.
if paramclass.superclass == Puppet::Parameter or paramclass.array_matching == :first
result[param] = values[0]
else
result[param] = values
end
end
# Make a duplicate, so that we have a copy for comparison
# at the end.
@ldap_properties = @property_hash.dup
end
# Return the current state of ldap.
def ldap_properties
@ldap_properties.dup
end
# Return (and look up if necessary) the desired state.
def properties
if @property_hash.empty?
@property_hash = query || { :ensure => :absent }
@property_hash[:ensure] = :absent if @property_hash.empty?
end
@property_hash.dup
end
# Collect the current attributes from ldap. Returns
# the results, but also stores the attributes locally,
# so we have something to compare against when we update.
# LAK:NOTE This is normally not used, because we rely on prefetching.
def query
# Use the module function.
attributes = manager.find(name)
unless attributes
@ldap_properties = {}
return nil
end
@ldap_properties = attributes
@ldap_properties.dup
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/provider/network_device.rb | lib/puppet/provider/network_device.rb | # frozen_string_literal: true
# This is the base class of all prefetched network device provider
class Puppet::Provider::NetworkDevice < Puppet::Provider
def self.device(url)
raise "This provider doesn't implement the necessary device method"
end
def self.lookup(device, name)
raise "This provider doesn't implement the necessary lookup method"
end
def self.prefetch(resources)
resources.each do |name, resource|
device = Puppet::Util::NetworkDevice.current || device(resource[:device_url])
result = lookup(device, name)
if result
result[:ensure] = :present
resource.provider = new(device, result)
else
resource.provider = new(device, :ensure => :absent)
end
end
rescue => detail
# Preserving behavior introduced in #6907
# TRANSLATORS "prefetch" is a program name and should not be translated
Puppet.log_exception(detail, _("Could not perform network device prefetch: %{detail}") % { detail: detail })
end
def exists?
@property_hash[:ensure] != :absent
end
attr_accessor :device
def initialize(device, *args)
super(*args)
@device = device
# Make a duplicate, so that we have a copy for comparison
# at the end.
@properties = @property_hash.dup
end
def create
@property_hash[:ensure] = :present
self.class.resource_type.validproperties.each do |property|
val = resource.should(property)
if val
@property_hash[property] = val
end
end
end
def destroy
@property_hash[:ensure] = :absent
end
def flush
@property_hash.clear
end
def self.instances
end
def former_properties
@properties.dup
end
def properties
@property_hash.dup
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/provider/confine.rb | lib/puppet/provider/confine.rb | # frozen_string_literal: true
# Confines have been moved out of the provider as they are also used for other things.
# This provides backwards compatibility for people still including this old location.
require_relative '../../puppet/provider'
require_relative '../../puppet/confine'
Puppet::Provider::Confine = Puppet::Confine
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/service/openwrt.rb | lib/puppet/provider/service/openwrt.rb | # frozen_string_literal: true
Puppet::Type.type(:service).provide :openwrt, :parent => :init, :source => :init do
desc <<-EOT
Support for OpenWrt flavored init scripts.
Uses /etc/init.d/service_name enable, disable, and enabled.
EOT
defaultfor 'os.name' => :openwrt
confine 'os.name' => :openwrt
has_feature :enableable
def self.defpath
["/etc/init.d"]
end
def enable
system(initscript, 'enable')
end
def disable
system(initscript, 'disable')
end
def enabled?
# We can't define the "command" for the init script, so we call system?
system(initscript, 'enabled') ? (return :true) : (return :false)
end
# Purposely leave blank so we fail back to ps based status detection
# As OpenWrt init script do not have status commands
def statuscmd
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/provider/service/freebsd.rb | lib/puppet/provider/service/freebsd.rb | # frozen_string_literal: true
Puppet::Type.type(:service).provide :freebsd, :parent => :init do
desc "Provider for FreeBSD and DragonFly BSD. Uses the `rcvar` argument of init scripts and parses/edits rc files."
confine 'os.name' => [:freebsd, :dragonfly]
defaultfor 'os.name' => [:freebsd, :dragonfly]
def rcconf() '/etc/rc.conf' end
def rcconf_local() '/etc/rc.conf.local' end
def rcconf_dir() '/etc/rc.conf.d' end
def self.defpath
superclass.defpath
end
def error(msg)
raise Puppet::Error, msg
end
# Executing an init script with the 'rcvar' argument returns
# the service name, rcvar name and whether it's enabled/disabled
def rcvar
rcvar = execute([initscript, :rcvar], :failonfail => true, :combine => false, :squelch => false)
rcvar = rcvar.split("\n")
rcvar.delete_if { |str| str =~ /^#\s*$/ }
rcvar[1] = rcvar[1].gsub(/^\$/, '')
rcvar
end
# Extract value name from service or rcvar
def extract_value_name(name, rc_index, regex, regex_index)
value_name = rcvar[rc_index]
error("No #{name} name found in rcvar") if value_name.nil?
value_name = value_name.gsub!(regex, regex_index)
error("#{name} name is empty") if value_name.nil?
debug("#{name} name is #{value_name}")
value_name
end
# Extract service name
def service_name
extract_value_name('service', 0, /# (\S+).*/, '\1')
end
# Extract rcvar name
def rcvar_name
extract_value_name('rcvar', 1, /(.*?)(_enable)?=(.*)/, '\1')
end
# Extract rcvar value
def rcvar_value
value = rcvar[1]
error("No rcvar value found in rcvar") if value.nil?
value = value.gsub!(/(.*)(_enable)?="?(\w+)"?/, '\3')
error("rcvar value is empty") if value.nil?
debug("rcvar value is #{value}")
value
end
# Edit rc files and set the service to yes/no
def rc_edit(yesno)
service = service_name
rcvar = rcvar_name
debug("Editing rc files: setting #{rcvar} to #{yesno} for #{service}")
rc_add(service, rcvar, yesno) unless rc_replace(service, rcvar, yesno)
end
# Try to find an existing setting in the rc files
# and replace the value
def rc_replace(service, rcvar, yesno)
success = false
# Replace in all files, not just in the first found with a match
[rcconf, rcconf_local, rcconf_dir + "/#{service}"].each do |filename|
next unless Puppet::FileSystem.exist?(filename)
s = File.read(filename)
next unless s.gsub!(/^(#{rcvar}(_enable)?)="?(YES|NO)"?/, "\\1=\"#{yesno}\"")
Puppet::FileSystem.replace_file(filename) { |f| f << s }
debug("Replaced in #{filename}")
success = true
end
success
end
# Add a new setting to the rc files
def rc_add(service, rcvar, yesno)
append = "\# Added by Puppet\n#{rcvar}_enable=\"#{yesno}\"\n"
# First, try the one-file-per-service style
if Puppet::FileSystem.exist?(rcconf_dir)
File.open(rcconf_dir + "/#{service}", File::WRONLY | File::APPEND | File::CREAT, 0o644) { |f|
f << append
debug("Appended to #{f.path}")
}
elsif Puppet::FileSystem.exist?(rcconf_local)
# Else, check the local rc file first, but don't create it
File.open(rcconf_local, File::WRONLY | File::APPEND) { |f|
f << append
debug("Appended to #{f.path}")
}
else
# At last use the standard rc.conf file
File.open(rcconf, File::WRONLY | File::APPEND | File::CREAT, 0o644) { |f|
f << append
debug("Appended to #{f.path}")
}
end
end
def enabled?
if /YES$/ =~ rcvar_value
debug("Is enabled")
return :true
end
debug("Is disabled")
:false
end
def enable
debug("Enabling")
rc_edit("YES")
end
def disable
debug("Disabling")
rc_edit("NO")
end
def startcmd
[initscript, :onestart]
end
def stopcmd
[initscript, :onestop]
end
def statuscmd
[initscript, :onestatus]
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/provider/service/openrc.rb | lib/puppet/provider/service/openrc.rb | # frozen_string_literal: true
# Gentoo OpenRC
Puppet::Type.type(:service).provide :openrc, :parent => :base do
desc <<-EOT
Support for Gentoo's OpenRC initskripts
Uses rc-update, rc-status and rc-service to manage services.
EOT
defaultfor 'os.name' => :gentoo
defaultfor 'os.name' => :funtoo
has_command(:rcstatus, '/bin/rc-status') do
environment :RC_SVCNAME => nil
end
commands :rcservice => '/sbin/rc-service'
commands :rcupdate => '/sbin/rc-update'
self::STATUSLINE = /^\s+(.*?)\s*\[\s*(.*)\s*\]$/
def enable
rcupdate('-C', :add, @resource[:name])
end
def disable
rcupdate('-C', :del, @resource[:name])
end
# rc-status -a shows all runlevels and dynamic runlevels which
# are not considered as enabled. We have to find out under which
# runlevel our service is listed
def enabled?
enabled = :false
rcstatus('-C', '-a').each_line do |line|
case line.chomp
when /^Runlevel: /
enabled = :true
when /^\S+/ # caption of a dynamic runlevel
enabled = :false
when self.class::STATUSLINE
return enabled if @resource[:name] == Regexp.last_match(1)
end
end
:false
end
def self.instances
instances = []
rcservice('-C', '--list').each_line do |line|
instances << new(:name => line.chomp)
end
instances
end
def restartcmd
(@resource[:hasrestart] == :true) && [command(:rcservice), @resource[:name], :restart]
end
def startcmd
[command(:rcservice), @resource[:name], :start]
end
def stopcmd
[command(:rcservice), @resource[:name], :stop]
end
def statuscmd
((@resource.provider.get(:hasstatus) == true) || (@resource[:hasstatus] == :true)) && [command(:rcservice), @resource[:name], :status]
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/provider/service/gentoo.rb | lib/puppet/provider/service/gentoo.rb | # frozen_string_literal: true
# Manage gentoo services. Start/stop is the same as InitSvc, but enable/disable
# is special.
Puppet::Type.type(:service).provide :gentoo, :parent => :init do
desc <<-EOT
Gentoo's form of `init`-style service management.
Uses `rc-update` for service enabling and disabling.
EOT
commands :update => "/sbin/rc-update"
confine 'os.name' => :gentoo
def disable
output = update :del, @resource[:name], :default
rescue Puppet::ExecutionFailure => e
raise Puppet::Error, "Could not disable #{name}: #{output}", e.backtrace
end
def enabled?
begin
output = update :show
rescue Puppet::ExecutionFailure
return :false
end
line = output.split(/\n/).find { |l| l.include?(@resource[:name]) }
return :false unless line
# If it's enabled then it will print output showing service | runlevel
if output =~ /^\s*#{@resource[:name]}\s*\|\s*(boot|default)/
:true
else
:false
end
end
def enable
output = update :add, @resource[:name], :default
rescue Puppet::ExecutionFailure => e
raise Puppet::Error, "Could not enable #{name}: #{output}", e.backtrace
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/provider/service/redhat.rb | lib/puppet/provider/service/redhat.rb | # frozen_string_literal: true
# Manage Red Hat services. Start/stop uses /sbin/service and enable/disable uses chkconfig
Puppet::Type.type(:service).provide :redhat, :parent => :init, :source => :init do
desc "Red Hat's (and probably many others') form of `init`-style service
management. Uses `chkconfig` for service enabling and disabling.
"
commands :chkconfig => "/sbin/chkconfig", :service => "/sbin/service"
defaultfor 'os.name' => :amazon, 'os.release.major' => %w[2017 2018]
defaultfor 'os.name' => :redhat, 'os.release.major' => (4..6).to_a
defaultfor 'os.family' => :suse, 'os.release.major' => %w[10 11]
# Remove the symlinks
def disable
# The off method operates on run levels 2,3,4 and 5 by default We ensure
# all run levels are turned off because the reset method may turn on the
# service in run levels 0, 1 and/or 6
# We're not using --del here because we want to disable the service only,
# and --del removes the service from chkconfig management
chkconfig("--level", "0123456", @resource[:name], :off)
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error, "Could not disable #{name}: #{detail}", detail.backtrace
end
def enabled?
name = @resource[:name]
begin
output = chkconfig name
rescue Puppet::ExecutionFailure
return :false
end
# For Suse OS family, chkconfig returns 0 even if the service is disabled or non-existent
# Therefore, check the output for '<name> on' (or '<name> B for boot services)
# to see if it is enabled
return :false unless Puppet.runtime[:facter].value('os.family') != 'Suse' || output =~ /^#{name}\s+(on|B)$/
:true
end
# Don't support them specifying runlevels; always use the runlevels
# in the init scripts.
def enable
chkconfig("--add", @resource[:name])
chkconfig(@resource[:name], :on)
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error, "Could not enable #{name}: #{detail}", detail.backtrace
end
def initscript
raise Puppet::Error, "Do not directly call the init script for '#{@resource[:name]}'; use 'service' instead"
end
# use hasstatus=>true when its set for the provider.
def statuscmd
((@resource.provider.get(:hasstatus) == true) || (@resource[:hasstatus] == :true)) && [command(:service), @resource[:name], "status"]
end
def restartcmd
(@resource[:hasrestart] == :true) && [command(:service), @resource[:name], "restart"]
end
def startcmd
[command(:service), @resource[:name], "start"]
end
def stopcmd
[command(:service), @resource[:name], "stop"]
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/provider/service/systemd.rb | lib/puppet/provider/service/systemd.rb | # frozen_string_literal: true
# Manage systemd services using systemctl
require_relative '../../../puppet/file_system'
Puppet::Type.type(:service).provide :systemd, :parent => :base do
desc "Manages `systemd` services using `systemctl`.
Because `systemd` defaults to assuming the `.service` unit type, the suffix
may be omitted. Other unit types (such as `.path`) may be managed by
providing the proper suffix."
commands :systemctl => "systemctl"
confine :true => Puppet::FileSystem.exist?('/proc/1/comm') && Puppet::FileSystem.read('/proc/1/comm').include?('systemd')
defaultfor 'os.family' => [:archlinux]
defaultfor 'os.family' => :redhat
notdefaultfor 'os.name' => :redhat, 'os.release.major' => (4..6).to_a # Use the "RedHat" service provider
defaultfor 'os.family' => :redhat, 'os.name' => :fedora
defaultfor 'os.family' => :suse
defaultfor 'os.family' => :coreos
defaultfor 'os.family' => :gentoo
notdefaultfor 'os.name' => :amazon, 'os.release.major' => %w[2017 2018]
defaultfor 'os.name' => :amazon, 'os.release.major' => %w[2 2023]
defaultfor 'os.name' => :debian
notdefaultfor 'os.name' => :debian, 'os.release.major' => %w[5 6 7] # These are using the "debian" method
defaultfor 'os.name' => :LinuxMint
notdefaultfor 'os.name' => :LinuxMint, 'os.release.major' => %w[10 11 12 13 14 15 16 17] # These are using upstart
defaultfor 'os.name' => :ubuntu
notdefaultfor 'os.name' => :ubuntu, 'os.release.major' => ["10.04", "12.04", "14.04", "14.10"] # These are using upstart
defaultfor 'os.name' => :cumuluslinux, 'os.release.major' => %w[3 4]
defaultfor 'os.name' => :raspbian, 'os.release.major' => %w[12]
def self.instances
i = []
output = systemctl('list-unit-files', '--type', 'service', '--full', '--all', '--no-pager')
output.scan(/^(\S+)\s+(disabled|enabled|masked|indirect|bad|static)\s*([^-]\S+)?\s*$/i).each do |m|
Puppet.debug("#{m[0]} marked as bad by `systemctl`. It is recommended to be further checked.") if m[1] == "bad"
i << new(:name => m[0])
end
i
rescue Puppet::ExecutionFailure
[]
end
# Static services cannot be enabled or disabled manually. Indirect services
# should not be enabled or disabled due to limitations in systemd (see
# https://github.com/systemd/systemd/issues/6681).
def enabled_insync?(current)
case cached_enabled?[:output]
when 'static'
# masking static services is OK, but enabling/disabling them is not
if @resource[:enable] == :mask
current == @resource[:enable]
else
Puppet.debug("Unable to enable or disable static service #{@resource[:name]}")
true
end
when 'indirect'
Puppet.debug("Service #{@resource[:name]} is in 'indirect' state and cannot be enabled/disabled")
true
else
current == @resource[:enable]
end
end
# This helper ensures that the enable state cache is always reset
# after a systemctl enable operation. A particular service state is not guaranteed
# after such an operation, so the cache must be emptied to prevent inconsistencies
# in the provider's believed state of the service and the actual state.
# @param action [String,Symbol] One of 'enable', 'disable', 'mask' or 'unmask'
def systemctl_change_enable(action)
output = systemctl(action, '--', @resource[:name])
rescue => e
raise Puppet::Error, "Could not #{action} #{name}: #{output}", e.backtrace
ensure
@cached_enabled = nil
end
def disable
systemctl_change_enable(:disable)
end
def get_start_link_count
# Start links don't include '.service'. Just search for the service name.
if @resource[:name] =~ /\.service/
link_name = @resource[:name].split('.')[0]
else
link_name = @resource[:name]
end
Dir.glob("/etc/rc*.d/S??#{link_name}").length
end
def cached_enabled?
return @cached_enabled if @cached_enabled
cmd = [command(:systemctl), 'is-enabled', '--', @resource[:name]]
result = execute(cmd, :failonfail => false)
@cached_enabled = { output: result.chomp, exitcode: result.exitstatus }
end
def enabled?
output = cached_enabled?[:output]
code = cached_enabled?[:exitcode]
# The masked state is equivalent to the disabled state in terms of
# comparison so we only care to check if it is masked if we want to keep
# it masked.
#
# We only return :mask if we're trying to mask the service. This prevents
# flapping when simply trying to disable a masked service.
return :mask if (@resource[:enable] == :mask) && (output == 'masked')
# The indirect state indicates that the unit is not enabled.
return :false if output == 'indirect'
return :true if code == 0
if output.empty? && (code > 0) && Puppet.runtime[:facter].value('os.family').casecmp('debian').zero?
ret = debian_enabled?
return ret if ret
end
:false
end
# This method is required for Debian systems due to the way the SysVInit-Systemd
# compatibility layer works. When we are trying to manage a service which does not
# have a Systemd unit file, we need to go through the old init script to determine
# whether it is enabled or not. See PUP-5016 for more details.
#
def debian_enabled?
status = execute(["/usr/sbin/invoke-rc.d", "--quiet", "--query", @resource[:name], "start"], :failonfail => false)
if [104, 106].include?(status.exitstatus)
:true
elsif [101, 105].include?(status.exitstatus)
# 101 is action not allowed, which means we have to do the check manually.
# 105 is unknown, which generally means the initscript does not support query
# The debian policy states that the initscript should support methods of query
# For those that do not, perform the checks manually
# http://www.debian.org/doc/debian-policy/ch-opersys.html
if get_start_link_count >= 4
:true
else
:false
end
else
:false
end
end
# Define the daemon_reload? function to check if the unit is requiring to trigger a "systemctl daemon-reload"
# If the unit file is flagged with NeedDaemonReload=yes, then a systemd daemon-reload will be run.
# If multiple unit files have been updated, the first one flagged will trigger the daemon-reload for all of them.
# The others will be then flagged with NeedDaemonReload=no. So the command will run only once in a puppet run.
# This function is called only on start & restart unit options.
# Reference: (PUP-3483) Systemd provider doesn't scan for changed units
def daemon_reload?
cmd = [command(:systemctl), 'show', '--property=NeedDaemonReload', '--', @resource[:name]]
daemon_reload = execute(cmd, :failonfail => false).strip.split('=').last
if daemon_reload == 'yes'
daemon_reload_cmd = [command(:systemctl), 'daemon-reload']
execute(daemon_reload_cmd, :failonfail => false)
end
end
def enable
unmask
systemctl_change_enable(:enable)
end
def mask
disable if exist?
systemctl_change_enable(:mask)
end
def exist?
result = execute([command(:systemctl), 'cat', '--', @resource[:name]], :failonfail => false)
result.exitstatus == 0
end
def unmask
systemctl_change_enable(:unmask)
end
def restartcmd
[command(:systemctl), "restart", '--', @resource[:name]]
end
def startcmd
unmask
[command(:systemctl), "start", '--', @resource[:name]]
end
def stopcmd
[command(:systemctl), "stop", '--', @resource[:name]]
end
def statuscmd
[command(:systemctl), "is-active", '--', @resource[:name]]
end
def restart
daemon_reload?
super
rescue Puppet::Error => e
raise Puppet::Error, prepare_error_message(@resource[:name], 'restart', e)
end
def start
daemon_reload?
super
rescue Puppet::Error => e
raise Puppet::Error, prepare_error_message(@resource[:name], 'start', e)
end
def stop
super
rescue Puppet::Error => e
raise Puppet::Error, prepare_error_message(@resource[:name], 'stop', e)
end
def prepare_error_message(name, action, exception)
error_return = "Systemd #{action} for #{name} failed!\n"
journalctl_command = "journalctl -n 50 --since '5 minutes ago' -u #{name} --no-pager"
Puppet.debug("Running journalctl command to get logs for systemd #{action} failure: #{journalctl_command}")
journalctl_output = execute(journalctl_command)
error_return << "journalctl log for #{name}:\n#{journalctl_output}"
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/provider/service/openbsd.rb | lib/puppet/provider/service/openbsd.rb | # frozen_string_literal: true
Puppet::Type.type(:service).provide :openbsd, :parent => :init do
desc "Provider for OpenBSD's rc.d daemon control scripts"
commands :rcctl => '/usr/sbin/rcctl'
confine 'os.name' => :openbsd
defaultfor 'os.name' => :openbsd
has_feature :flaggable
def startcmd
[command(:rcctl), '-f', :start, @resource[:name]]
end
def stopcmd
[command(:rcctl), :stop, @resource[:name]]
end
def restartcmd
(@resource[:hasrestart] == :true) && [command(:rcctl), '-f', :restart, @resource[:name]]
end
def statuscmd
[command(:rcctl), :check, @resource[:name]]
end
# @api private
# When storing the name, take into account not everything has
# '_flags', like 'multicast_host' and 'pf'.
def self.instances
instances = []
begin
execpipe([command(:rcctl), :getall]) do |process|
process.each_line do |line|
match = /^(.*?)(?:_flags)?=(.*)$/.match(line)
attributes_hash = {
:name => match[1],
:flags => match[2],
:hasstatus => true,
:provider => :openbsd,
}
instances << new(attributes_hash);
end
end
instances
rescue Puppet::ExecutionFailure
nil
end
end
def enabled?
output = execute([command(:rcctl), "get", @resource[:name], "status"],
:failonfail => false, :combine => false, :squelch => false)
if output.exitstatus == 1
debug("Is disabled")
:false
else
debug("Is enabled")
:true
end
end
def enable
debug("Enabling")
rcctl(:enable, @resource[:name])
if @resource[:flags]
rcctl(:set, @resource[:name], :flags, @resource[:flags])
end
end
def disable
debug("Disabling")
rcctl(:disable, @resource[:name])
end
def running?
output = execute([command(:rcctl), "check", @resource[:name]],
:failonfail => false, :combine => false, :squelch => false).chomp
true if output =~ /\(ok\)/
end
# Uses the wrapper to prevent failure when the service is not running;
# rcctl(8) return non-zero in that case.
def flags
output = execute([command(:rcctl), "get", @resource[:name], "flags"],
:failonfail => false, :combine => false, :squelch => false).chomp
debug("Flags are: \"#{output}\"")
output
end
def flags=(value)
debug("Changing flags from #{flags} to #{value}")
rcctl(:set, @resource[:name], :flags, value)
# If the service is already running, force a restart as the flags have been changed.
rcctl(:restart, @resource[:name]) if running?
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/provider/service/src.rb | lib/puppet/provider/service/src.rb | # frozen_string_literal: true
require 'timeout'
# AIX System Resource controller (SRC)
Puppet::Type.type(:service).provide :src, :parent => :base do
desc "Support for AIX's System Resource controller.
Services are started/stopped based on the `stopsrc` and `startsrc`
commands, and some services can be refreshed with `refresh` command.
Enabling and disabling services is not supported, as it requires
modifications to `/etc/inittab`. Starting and stopping groups of subsystems
is not yet supported.
"
defaultfor 'os.name' => :aix
confine 'os.name' => :aix
optional_commands :stopsrc => "/usr/bin/stopsrc",
:startsrc => "/usr/bin/startsrc",
:refresh => "/usr/bin/refresh",
:lssrc => "/usr/bin/lssrc",
:lsitab => "/usr/sbin/lsitab",
:mkitab => "/usr/sbin/mkitab",
:rmitab => "/usr/sbin/rmitab",
:chitab => "/usr/sbin/chitab"
has_feature :refreshable
def self.instances
services = lssrc('-S')
services.split("\n").reject { |x| x.strip.start_with? '#' }.collect do |line|
data = line.split(':')
service_name = data[0]
new(:name => service_name)
end
end
def startcmd
[command(:startsrc), "-s", @resource[:name]]
end
def stopcmd
[command(:stopsrc), "-s", @resource[:name]]
end
def default_runlevel
"2"
end
def default_action
"once"
end
def enabled?
output = execute([command(:lsitab), @resource[:name]], { :failonfail => false, :combine => true })
output.exitstatus == 0 ? :true : :false
end
def enable
mkitab("%s:%s:%s:%s" % [@resource[:name], default_runlevel, default_action, startcmd.join(" ")])
end
def disable
rmitab(@resource[:name])
end
# Wait for the service to transition into the specified state before returning.
# This is necessary due to the asynchronous nature of AIX services.
# desired_state should either be :running or :stopped.
def wait(desired_state)
Timeout.timeout(60) do
loop do
status = self.status
break if status == desired_state.to_sym
sleep(1)
end
end
rescue Timeout::Error
raise Puppet::Error, "Timed out waiting for #{@resource[:name]} to transition states"
end
def start
super
wait(:running)
end
def stop
super
wait(:stopped)
end
def restart
execute([command(:lssrc), "-Ss", @resource[:name]]).each_line do |line|
args = line.split(":")
next unless args[0] == @resource[:name]
# Subsystems with the -K flag can get refreshed (HUPed)
# While subsystems with -S (signals) must be stopped/started
method = args[11]
do_refresh = case method
when "-K" then :true
when "-S" then :false
else self.fail("Unknown service communication method #{method}")
end
begin
if do_refresh == :true
execute([command(:refresh), "-s", @resource[:name]])
else
stop
start
end
return :true
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error.new("Unable to restart service #{@resource[:name]}, error was: #{detail}", detail)
end
end
self.fail("No such service found")
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error.new("Cannot get status of #{@resource[:name]}, error was: #{detail}", detail)
end
def status
execute([command(:lssrc), "-s", @resource[:name]]).each_line do |line|
args = line.split
# This is the header line
next unless args[0] == @resource[:name]
# PID is the 3rd field, but inoperative subsystems
# skip this so split doesn't work right
state = case args[-1]
when "active" then :running
when "inoperative" then :stopped
end
Puppet.debug("Service #{@resource[:name]} is #{args[-1]}")
return state
end
rescue Puppet::ExecutionFailure => detail
debug(detail.message)
:stopped
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/provider/service/base.rb | lib/puppet/provider/service/base.rb | # frozen_string_literal: true
Puppet::Type.type(:service).provide :base, :parent => :service do
desc "The simplest form of Unix service support.
You have to specify enough about your service for this to work; the
minimum you can specify is a binary for starting the process, and this
same binary will be searched for in the process table to stop the
service. As with `init`-style services, it is preferable to specify start,
stop, and status commands.
"
commands :kill => "kill"
# get the proper 'ps' invocation for the platform
# ported from the facter 2.x implementation, since facter 3.x
# is dropping the fact (for which this was the only use)
def getps
case Puppet.runtime[:facter].value('os.name')
when 'OpenWrt'
'ps www'
when 'FreeBSD', 'NetBSD', 'OpenBSD', 'Darwin', 'DragonFly'
'ps auxwww'
else
'ps -ef'
end
end
private :getps
# Get the process ID for a running process. Requires the 'pattern'
# parameter.
def getpid
@resource.fail "Either stop/status commands or a pattern must be specified" unless @resource[:pattern]
regex = Regexp.new(@resource[:pattern])
ps = getps
debug "Executing '#{ps}'"
table = Puppet::Util::Execution.execute(ps)
# The output of the PS command can be a mashup of several different
# encodings depending on which processes are running and what
# arbitrary data has been used to set their name in the process table.
#
# First, try a polite conversion to in order to match the UTF-8 encoding
# of our regular expression.
table = Puppet::Util::CharacterEncoding.convert_to_utf_8(table)
# If that fails, force to UTF-8 and then scrub as most uses are scanning
# for ACII-compatible program names.
table.force_encoding(Encoding::UTF_8) unless table.encoding == Encoding::UTF_8
table = table.scrub unless table.valid_encoding?
table.each_line { |line|
next unless regex.match(line)
debug "Process matched: #{line}"
ary = line.sub(/^[[:space:]]+/u, '').split(/[[:space:]]+/u)
return ary[1]
}
nil
end
private :getpid
# Check if the process is running. Prefer the 'status' parameter,
# then 'statuscmd' method, then look in the process table. We give
# the object the option to not return a status command, which might
# happen if, for instance, it has an init script (and thus responds to
# 'statuscmd') but does not have 'hasstatus' enabled.
def status
if @resource[:status] or statuscmd
# Don't fail when the exit status is not 0.
status = service_command(:status, false)
# Explicitly calling exitstatus to facilitate testing
if status.exitstatus == 0
:running
else
:stopped
end
else
pid = getpid
if pid
debug "PID is #{pid}"
:running
else
:stopped
end
end
end
# There is no default command, which causes other methods to be used
def statuscmd
end
# Run the 'start' parameter command, or the specified 'startcmd'.
def start
service_command(:start)
nil
end
# The command used to start. Generated if the 'binary' argument
# is passed.
def startcmd
@resource[:binary] || raise(Puppet::Error, "Services must specify a start command or a binary")
end
# Stop the service. If a 'stop' parameter is specified, it
# takes precedence; otherwise checks if the object responds to
# a 'stopcmd' method, and if so runs that; otherwise, looks
# for the process in the process table.
# This method will generally not be overridden by submodules.
def stop
if @resource[:stop] or stopcmd
service_command(:stop)
nil
else
pid = getpid
unless pid
info _("%{name} is not running") % { name: name }
return false
end
begin
output = kill pid
rescue Puppet::ExecutionFailure => e
@resource.fail Puppet::Error, "Could not kill #{name}, PID #{pid}: #{output}", e
end
true
end
end
# There is no default command, which causes other methods to be used
def stopcmd
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/provider/service/daemontools.rb | lib/puppet/provider/service/daemontools.rb | # frozen_string_literal: true
# Daemontools service management
#
# author Brice Figureau <brice-puppet@daysofwonder.com>
Puppet::Type.type(:service).provide :daemontools, :parent => :base do
desc <<-'EOT'
Daemontools service management.
This provider manages daemons supervised by D.J. Bernstein daemontools.
When detecting the service directory it will check, in order of preference:
* `/service`
* `/etc/service`
* `/var/lib/svscan`
The daemon directory should be in one of the following locations:
* `/var/lib/service`
* `/etc`
...or this can be overridden in the resource's attributes:
service { 'myservice':
provider => 'daemontools',
path => '/path/to/daemons',
}
This provider supports out of the box:
* start/stop (mapped to enable/disable)
* enable/disable
* restart
* status
If a service has `ensure => "running"`, it will link /path/to/daemon to
/path/to/service, which will automatically enable the service.
If a service has `ensure => "stopped"`, it will only shut down the service, not
remove the `/path/to/service` link.
EOT
commands :svc => "/usr/bin/svc", :svstat => "/usr/bin/svstat"
class << self
attr_writer :defpath
# Determine the daemon path.
def defpath
@defpath ||= ["/var/lib/service", "/etc"].find do |path|
Puppet::FileSystem.exist?(path) && FileTest.directory?(path)
end
@defpath
end
end
attr_writer :servicedir
# returns all providers for all existing services in @defpath
# ie enabled or not
def self.instances
path = defpath
unless path
Puppet.info("#{name} is unsuitable because service directory is nil")
return
end
unless FileTest.directory?(path)
Puppet.notice "Service path #{path} does not exist"
return
end
# reject entries that aren't either a directory
# or don't contain a run file
Dir.entries(path).reject { |e|
fullpath = File.join(path, e)
e =~ /^\./ or !FileTest.directory?(fullpath) or !Puppet::FileSystem.exist?(File.join(fullpath, "run"))
}.collect do |name|
new(:name => name, :path => path)
end
end
# returns the daemon dir on this node
def self.daemondir
defpath
end
# find the service dir on this node
def servicedir
unless @servicedir
["/service", "/etc/service", "/var/lib/svscan"].each do |path|
if Puppet::FileSystem.exist?(path)
@servicedir = path
break
end
end
raise "Could not find service directory" unless @servicedir
end
@servicedir
end
# returns the full path of this service when enabled
# (ie in the service directory)
def service
File.join(servicedir, resource[:name])
end
# returns the full path to the current daemon directory
# note that this path can be overridden in the resource
# definition
def daemon
path = resource[:path]
raise Puppet::Error, "#{self.class.name} must specify a path for daemon directory" unless path
File.join(path, resource[:name])
end
def status
begin
output = svstat service
if output =~ /:\s+up \(/
return :running
end
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error.new("Could not get status for service #{resource.ref}: #{detail}", detail)
end
:stopped
end
def setupservice
if resource[:manifest]
Puppet.notice "Configuring #{resource[:name]}"
command = [resource[:manifest], resource[:name]]
system(command.to_s)
end
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error.new("Cannot config #{service} to enable it: #{detail}", detail)
end
def enabled?
case status
when :running
# obviously if the daemon is running then it is enabled
:true
else
# the service is enabled if it is linked
Puppet::FileSystem.symlink?(service) ? :true : :false
end
end
def enable
unless FileTest.directory?(daemon)
Puppet.notice "No daemon dir, calling setupservice for #{resource[:name]}"
setupservice
end
if daemon
unless Puppet::FileSystem.symlink?(service)
Puppet.notice "Enabling #{service}: linking #{daemon} -> #{service}"
Puppet::FileSystem.symlink(daemon, service)
end
end
rescue Puppet::ExecutionFailure => e
raise Puppet::Error.new("No daemon directory found for #{service}", e)
end
def disable
begin
unless FileTest.directory?(daemon)
Puppet.notice "No daemon dir, calling setupservice for #{resource[:name]}"
setupservice
end
if daemon
if Puppet::FileSystem.symlink?(service)
Puppet.notice "Disabling #{service}: removing link #{daemon} -> #{service}"
Puppet::FileSystem.unlink(service)
end
end
rescue Puppet::ExecutionFailure => e
raise Puppet::Error.new("No daemon directory found for #{service}", e)
end
stop
end
def restart
svc "-t", service
end
def start
enable unless enabled? == :true
svc "-u", service
end
def stop
svc "-d", service
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/provider/service/launchd.rb | lib/puppet/provider/service/launchd.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/plist'
Puppet::Type.type(:service).provide :launchd, :parent => :base do
desc <<-'EOT'
This provider manages jobs with `launchd`, which is the default service
framework for Mac OS X (and may be available for use on other platforms).
For more information, see the `launchd` man page:
* <https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man8/launchd.8.html>
This provider reads plists out of the following directories:
* `/System/Library/LaunchDaemons`
* `/System/Library/LaunchAgents`
* `/Library/LaunchDaemons`
* `/Library/LaunchAgents`
...and builds up a list of services based upon each plist's "Label" entry.
This provider supports:
* ensure => running/stopped,
* enable => true/false
* status
* restart
Here is how the Puppet states correspond to `launchd` states:
* stopped --- job unloaded
* started --- job loaded
* enabled --- 'Disable' removed from job plist file
* disabled --- 'Disable' added to job plist file
Note that this allows you to do something `launchctl` can't do, which is to
be in a state of "stopped/enabled" or "running/disabled".
Note that this provider does not support overriding 'restart'
EOT
include Puppet::Util::Warnings
commands :launchctl => "/bin/launchctl"
defaultfor 'os.name' => :darwin
confine 'os.name' => :darwin
confine :feature => :cfpropertylist
has_feature :enableable
has_feature :refreshable
mk_resource_methods
# These are the paths in OS X where a launchd service plist could
# exist. This is a helper method, versus a constant, for easy testing
# and mocking
#
# @api private
def self.launchd_paths
[
"/Library/LaunchAgents",
"/Library/LaunchDaemons",
"/System/Library/LaunchAgents",
"/System/Library/LaunchDaemons"
]
end
# Gets the current Darwin version, example 10.6 returns 9 and 10.10 returns 14
# See https://en.wikipedia.org/wiki/Darwin_(operating_system)#Release_history
# for more information.
#
# @api private
def self.get_os_version
# rubocop:disable Naming/MemoizedInstanceVariableName
@os_version ||= Facter.value('os.release.major').to_i
# rubocop:enable Naming/MemoizedInstanceVariableName
end
# Defines the path to the overrides plist file where service enabling
# behavior is defined in 10.6 and greater.
#
# With the rewrite of launchd in 10.10+, this moves and slightly changes format.
#
# @api private
def self.launchd_overrides
if get_os_version < 14
"/var/db/launchd.db/com.apple.launchd/overrides.plist"
else
"/var/db/com.apple.xpc.launchd/disabled.plist"
end
end
# Caching is enabled through the following three methods. Self.prefetch will
# call self.instances to create an instance for each service. Self.flush will
# clear out our cache when we're done.
def self.prefetch(resources)
instances.each do |prov|
resource = resources[prov.name]
if resource
resource.provider = prov
end
end
end
# Self.instances will return an array with each element being a hash
# containing the name, provider, path, and status of each service on the
# system.
def self.instances
jobs = jobsearch
@job_list ||= job_list
jobs.keys.collect do |job|
job_status = @job_list.has_key?(job) ? :running : :stopped
new(:name => job, :provider => :launchd, :path => jobs[job], :status => job_status)
end
end
# This method will return a list of files in the passed directory. This method
# does not go recursively down the tree and does not return directories
#
# @param path [String] The directory to glob
#
# @api private
#
# @return [Array] of String instances modeling file paths
def self.return_globbed_list_of_file_paths(path)
array_of_files = Dir.glob(File.join(path, '*')).collect do |filepath|
File.file?(filepath) ? filepath : nil
end
array_of_files.compact
end
# Get a hash of all launchd plists, keyed by label. This value is cached, but
# the cache will be refreshed if refresh is true.
#
# @api private
def self.make_label_to_path_map(refresh = false)
return @label_to_path_map if @label_to_path_map and !refresh
@label_to_path_map = {}
launchd_paths.each do |path|
return_globbed_list_of_file_paths(path).each do |filepath|
Puppet.debug("Reading launchd plist #{filepath}")
job = read_plist(filepath)
next if job.nil?
if job.respond_to?(:key) && job.key?("Label")
@label_to_path_map[job["Label"]] = filepath
else
# TRANSLATORS 'plist' and label' should not be translated
Puppet.debug(_("The %{file} plist does not contain a 'label' key; Puppet is skipping it") % { file: filepath })
next
end
end
end
@label_to_path_map
end
# Sets a class instance variable with a hash of all launchd plist files that
# are found on the system. The key of the hash is the job id and the value
# is the path to the file. If a label is passed, we return the job id and
# path for that specific job.
def self.jobsearch(label = nil)
by_label = make_label_to_path_map
if label
if by_label.has_key? label
{ label => by_label[label] }
else
# try refreshing the map, in case a plist has been added in the interim
by_label = make_label_to_path_map(true)
if by_label.has_key? label
{ label => by_label[label] }
else
raise Puppet::Error, "Unable to find launchd plist for job: #{label}"
end
end
else
# caller wants the whole map
by_label
end
end
# This status method lists out all currently running services.
# This hash is returned at the end of the method.
def self.job_list
@job_list = Hash.new
begin
output = launchctl :list
raise Puppet::Error, "launchctl list failed to return any data." if output.nil?
output.split("\n").each do |line|
@job_list[line.split(/\s/).last] = :running
end
rescue Puppet::ExecutionFailure => e
raise Puppet::Error.new("Unable to determine status of #{resource[:name]}", e)
end
@job_list
end
# Read a plist, whether its format is XML or in Apple's "binary1"
# format.
def self.read_plist(path)
Puppet::Util::Plist.read_plist_file(path)
end
# Read overrides plist, retrying if necessary
def self.read_overrides
i = 1
overrides = nil
loop do
Puppet.debug(_("Reading overrides plist, attempt %{i}") % { i: i }) if i > 1
overrides = read_plist(launchd_overrides)
break unless overrides.nil?
raise Puppet::Error, _('Unable to read overrides plist, too many attempts') if i == 20
Puppet.info(_('Overrides file could not be read, trying again.'))
Kernel.sleep(0.1)
i += 1
end
overrides
end
# Clean out the @property_hash variable containing the cached list of services
def flush
@property_hash.clear
end
def exists?
Puppet.debug("Puppet::Provider::Launchd:Ensure for #{@property_hash[:name]}: #{@property_hash[:ensure]}")
@property_hash[:ensure] != :absent
end
# finds the path for a given label and returns the path and parsed plist
# as an array of [path, plist]. Note plist is really a Hash here.
def plist_from_label(label)
job = self.class.jobsearch(label)
job_path = job[label]
if FileTest.file?(job_path)
job_plist = self.class.read_plist(job_path)
else
raise Puppet::Error, "Unable to parse launchd plist at path: #{job_path}"
end
[job_path, job_plist]
end
# when a service includes hasstatus=>false, we override the launchctl
# status mechanism and fall back to the base provider status method.
def status
if @resource && ((@resource[:hasstatus] == :false) || (@resource[:status]))
super
elsif @property_hash[:status].nil?
# property_hash was flushed so the service changed status
service_name = @resource[:name]
# Updating services with new statuses
job_list = self.class.job_list
# if job is present in job_list, return its status
if job_list.key?(service_name)
job_list[service_name]
# if job is no longer present in job_list, it was stopped
else
:stopped
end
else
@property_hash[:status]
end
end
# start the service. To get to a state of running/enabled, we need to
# conditionally enable at load, then disable by modifying the plist file
# directly.
def start
if resource[:start]
service_command(:start)
return nil
end
job_path, _ = plist_from_label(resource[:name])
did_enable_job = false
cmds = []
cmds << :launchctl << :load
# always add -w so it always starts the job, it is a noop if it is not needed, this means we do
# not have to rescan all launchd plists.
cmds << "-w"
if enabled? == :false || status == :stopped # launchctl won't load disabled jobs
did_enable_job = true
end
cmds << job_path
begin
execute(cmds)
rescue Puppet::ExecutionFailure => e
raise Puppet::Error.new("Unable to start service: #{resource[:name]} at path: #{job_path}", e)
end
# As load -w clears the Disabled flag, we need to add it in after
disable if did_enable_job and resource[:enable] == :false
end
def stop
if resource[:stop]
service_command(:stop)
return nil
end
job_path, _ = plist_from_label(resource[:name])
did_disable_job = false
cmds = []
cmds << :launchctl << :unload
if enabled? == :true # keepalive jobs can't be stopped without disabling
cmds << "-w"
did_disable_job = true
end
cmds << job_path
begin
execute(cmds)
rescue Puppet::ExecutionFailure => e
raise Puppet::Error.new("Unable to stop service: #{resource[:name]} at path: #{job_path}", e)
end
# As unload -w sets the Disabled flag, we need to add it in after
enable if did_disable_job and resource[:enable] == :true
end
def restart
Puppet.debug("A restart has been triggered for the #{resource[:name]} service")
Puppet.debug("Stopping the #{resource[:name]} service")
stop
Puppet.debug("Starting the #{resource[:name]} service")
start
end
# launchd jobs are enabled by default. They are only disabled if the key
# "Disabled" is set to true, but it can also be set to false to enable it.
# Starting in 10.6, the Disabled key in the job plist is consulted, but only
# if there is no entry in the global overrides plist. We need to draw a
# distinction between undefined, true and false for both locations where the
# Disabled flag can be defined.
def enabled?
job_plist_disabled = nil
overrides_disabled = nil
begin
_, job_plist = plist_from_label(resource[:name])
rescue Puppet::Error => err
# if job does not exist, log the error and return false as on other platforms
Puppet.log_exception(err)
return :false
end
job_plist_disabled = job_plist["Disabled"] if job_plist.has_key?("Disabled")
overrides = self.class.read_overrides if FileTest.file?(self.class.launchd_overrides)
if overrides
if overrides.has_key?(resource[:name])
if self.class.get_os_version < 14
overrides_disabled = overrides[resource[:name]]["Disabled"] if overrides[resource[:name]].has_key?("Disabled")
else
overrides_disabled = overrides[resource[:name]]
end
end
end
if overrides_disabled.nil?
if job_plist_disabled.nil? or job_plist_disabled == false
return :true
end
elsif overrides_disabled == false
return :true
end
:false
end
# enable and disable are a bit hacky. We write out the plist with the appropriate value
# rather than dealing with launchctl as it is unable to change the Disabled flag
# without actually loading/unloading the job.
def enable
overrides = self.class.read_overrides
if self.class.get_os_version < 14
overrides[resource[:name]] = { "Disabled" => false }
else
overrides[resource[:name]] = false
end
Puppet::Util::Plist.write_plist_file(overrides, self.class.launchd_overrides)
end
def disable
overrides = self.class.read_overrides
if self.class.get_os_version < 14
overrides[resource[:name]] = { "Disabled" => true }
else
overrides[resource[:name]] = true
end
Puppet::Util::Plist.write_plist_file(overrides, self.class.launchd_overrides)
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/provider/service/bsd.rb | lib/puppet/provider/service/bsd.rb | # frozen_string_literal: true
Puppet::Type.type(:service).provide :bsd, :parent => :init do
desc <<-EOT
Generic BSD form of `init`-style service management with `rc.d`.
Uses `rc.conf.d` for service enabling and disabling.
EOT
confine 'os.name' => [:freebsd, :dragonfly]
def rcconf_dir
'/etc/rc.conf.d'
end
def self.defpath
superclass.defpath
end
# remove service file from rc.conf.d to disable it
def disable
rcfile = File.join(rcconf_dir, @resource[:name])
File.delete(rcfile) if Puppet::FileSystem.exist?(rcfile)
end
# if the service file exists in rc.conf.d then it's already enabled
def enabled?
rcfile = File.join(rcconf_dir, @resource[:name])
return :true if Puppet::FileSystem.exist?(rcfile)
:false
end
# enable service by creating a service file under rc.conf.d with the
# proper contents
def enable
Dir.mkdir(rcconf_dir) unless Puppet::FileSystem.exist?(rcconf_dir)
rcfile = File.join(rcconf_dir, @resource[:name])
File.open(rcfile, File::WRONLY | File::APPEND | File::CREAT, 0o644) { |f|
f << "%s_enable=\"YES\"\n" % @resource[:name]
}
end
# Override stop/start commands to use one<cmd>'s and the avoid race condition
# where provider tries to stop/start the service before it is enabled
def startcmd
[initscript, :onestart]
end
def stopcmd
[initscript, :onestop]
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/provider/service/service.rb | lib/puppet/provider/service/service.rb | # frozen_string_literal: true
Puppet::Type.type(:service).provide :service do
desc "The simplest form of service support."
def self.instances
[]
end
# How to restart the process.
def restart
if @resource[:restart] or restartcmd
service_command(:restart)
nil
else
stop
start
end
end
# There is no default command, which causes other methods to be used
def restartcmd
end
# @deprecated because the exit status is not returned, use service_execute instead
def texecute(type, command, fof = true, squelch = false, combine = true)
begin
execute(command, :failonfail => fof, :override_locale => false, :squelch => squelch, :combine => combine)
rescue Puppet::ExecutionFailure => detail
@resource.fail Puppet::Error, "Could not #{type} #{@resource.ref}: #{detail}", detail
end
nil
end
# @deprecated because the exitstatus is not returned, use service_command instead
def ucommand(type, fof = true)
c = @resource[type]
if c
cmd = [c]
else
cmd = [send("#{type}cmd")].flatten
end
texecute(type, cmd, fof)
end
# Execute a command, failing the resource if the command fails.
#
# @return [Puppet::Util::Execution::ProcessOutput]
def service_execute(type, command, fof = true, squelch = false, combine = true)
execute(command, :failonfail => fof, :override_locale => false, :squelch => squelch, :combine => combine)
rescue Puppet::ExecutionFailure => detail
@resource.fail Puppet::Error, "Could not #{type} #{@resource.ref}: #{detail}", detail
end
# Use either a specified command or the default for our provider.
#
# @return [Puppet::Util::Execution::ProcessOutput]
def service_command(type, fof = true)
c = @resource[type]
if c
cmd = [c]
else
cmd = [send("#{type}cmd")].flatten
end
service_execute(type, cmd, fof)
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/provider/service/init.rb | lib/puppet/provider/service/init.rb | # frozen_string_literal: true
# The standard init-based service type. Many other service types are
# customizations of this module.
Puppet::Type.type(:service).provide :init, :parent => :base do
desc "Standard `init`-style service management."
def self.defpath
case Puppet.runtime[:facter].value('os.name')
when "FreeBSD", "DragonFly"
["/etc/rc.d", "/usr/local/etc/rc.d"]
when "HP-UX"
"/sbin/init.d"
when "Archlinux"
"/etc/rc.d"
when "AIX"
"/etc/rc.d/init.d"
else
"/etc/init.d"
end
end
# Debian and Ubuntu should use the Debian provider.
confine :false => %w[Debian Ubuntu].include?(Puppet.runtime[:facter].value('os.name'))
# RedHat systems should use the RedHat provider.
confine :false => Puppet.runtime[:facter].value('os.family') == 'RedHat'
# We can't confine this here, because the init path can be overridden.
# confine :exists => defpath
# some init scripts are not safe to execute, e.g. we do not want
# to suddenly run /etc/init.d/reboot.sh status and reboot our system. The
# exclude list could be platform agnostic but I assume an invalid init script
# on system A will never be a valid init script on system B
def self.excludes
excludes = []
# these exclude list was found with grep -L '\/sbin\/runscript' /etc/init.d/* on gentoo
excludes += %w[functions.sh reboot.sh shutdown.sh]
# this exclude list is all from /sbin/service (5.x), but I did not exclude kudzu
excludes += %w[functions halt killall single linuxconf reboot boot]
# 'wait-for-state' and 'portmap-wait' are excluded from instances here
# because they take parameters that have unclear meaning. It looks like
# 'wait-for-state' is a generic waiter mainly used internally for other
# upstart services as a 'sleep until something happens'
# (http://lists.debian.org/debian-devel/2012/02/msg01139.html), while
# 'portmap-wait' is a specific instance of a waiter. There is an open
# launchpad bug
# (https://bugs.launchpad.net/ubuntu/+source/upstart/+bug/962047) that may
# eventually explain how to use the wait-for-state service or perhaps why
# it should remain excluded. When that bug is addressed this should be
# reexamined.
excludes += %w[wait-for-state portmap-wait]
# these excludes were found with grep -r -L start /etc/init.d
excludes += %w[rcS module-init-tools]
# Prevent puppet failing on unsafe scripts from Yocto Linux
if Puppet.runtime[:facter].value('os.family') == "cisco-wrlinux"
excludes += %w[banner.sh bootmisc.sh checkroot.sh devpts.sh dmesg.sh
hostname.sh mountall.sh mountnfs.sh populate-volatile.sh
rmnologin.sh save-rtc.sh sendsigs sysfs.sh umountfs
umountnfs.sh]
end
# Prevent puppet failing to get status of the new service introduced
# by the fix for this (bug https://bugs.launchpad.net/ubuntu/+source/lightdm/+bug/982889)
# due to puppet's inability to deal with upstart services with instances.
excludes += %w[plymouth-ready]
# Prevent puppet failing to get status of these services, which need parameters
# passed in (see https://bugs.launchpad.net/ubuntu/+source/puppet/+bug/1276766).
excludes += %w[idmapd-mounting startpar-bridge]
# Prevent puppet failing to get status of these services, additional upstart
# service with instances
excludes += %w[cryptdisks-udev]
excludes += %w[statd-mounting]
excludes += %w[gssd-mounting]
excludes
end
# List all services of this type.
def self.instances
get_services(defpath)
end
def self.get_services(defpath, exclude = excludes)
defpath = [defpath] unless defpath.is_a? Array
instances = []
defpath.each do |path|
unless Puppet::FileSystem.directory?(path)
Puppet.debug "Service path #{path} does not exist"
next
end
check = [:ensure]
check << :enable if public_method_defined? :enabled?
Dir.entries(path).each do |name|
fullpath = File.join(path, name)
next if name =~ /^\./
next if exclude.include? name
next if Puppet::FileSystem.directory?(fullpath)
next unless Puppet::FileSystem.executable?(fullpath)
next unless is_init?(fullpath)
instances << new(:name => name, :path => path, :hasstatus => true)
end
end
instances
end
# Mark that our init script supports 'status' commands.
def hasstatus=(value)
case value
when true, "true"; @parameters[:hasstatus] = true
when false, "false"; @parameters[:hasstatus] = false
else
raise Puppet::Error, "Invalid 'hasstatus' value #{value.inspect}"
end
end
# Where is our init script?
def initscript
@initscript ||= search(@resource[:name])
end
def paths
@paths ||= @resource[:path].find_all do |path|
if Puppet::FileSystem.directory?(path)
true
else
if Puppet::FileSystem.exist?(path)
debug "Search path #{path} is not a directory"
else
debug "Search path #{path} does not exist"
end
false
end
end
end
def search(name)
paths.each do |path|
fqname = File.join(path, name)
if Puppet::FileSystem.exist? fqname
return fqname
else
debug("Could not find #{name} in #{path}")
end
end
paths.each do |path|
fqname_sh = File.join(path, "#{name}.sh")
if Puppet::FileSystem.exist? fqname_sh
return fqname_sh
else
debug("Could not find #{name}.sh in #{path}")
end
end
raise Puppet::Error, "Could not find init script for '#{name}'"
end
# The start command is just the init script with 'start'.
def startcmd
[initscript, :start]
end
# The stop command is just the init script with 'stop'.
def stopcmd
[initscript, :stop]
end
def restartcmd
(@resource[:hasrestart] == :true) && [initscript, :restart]
end
def service_execute(type, command, fof = true, squelch = false, combine = true)
if type == :start && Puppet.runtime[:facter].value('os.family') == "Solaris"
command = ["/usr/bin/ctrun -l child", command].flatten.join(" ")
end
super(type, command, fof, squelch, combine)
end
# If it was specified that the init script has a 'status' command, then
# we just return that; otherwise, we return false, which causes it to
# fallback to other mechanisms.
def statuscmd
(@resource[:hasstatus] == :true) && [initscript, :status]
end
private
def self.is_init?(script = initscript)
file = Puppet::FileSystem.pathname(script)
!Puppet::FileSystem.symlink?(file) || Puppet::FileSystem.readlink(file) != "/lib/init/upstart-job"
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/provider/service/debian.rb | lib/puppet/provider/service/debian.rb | # frozen_string_literal: true
# Manage debian services. Start/stop is the same as InitSvc, but enable/disable
# is special.
Puppet::Type.type(:service).provide :debian, :parent => :init do
desc <<-EOT
Debian's form of `init`-style management.
The only differences from `init` are support for enabling and disabling
services via `update-rc.d` and the ability to determine enabled status via
`invoke-rc.d`.
EOT
commands :update_rc => "/usr/sbin/update-rc.d"
# note this isn't being used as a command until
# https://projects.puppetlabs.com/issues/2538
# is resolved.
commands :invoke_rc => "/usr/sbin/invoke-rc.d"
commands :service => "/usr/sbin/service"
confine :false => Puppet::FileSystem.exist?('/proc/1/comm') && Puppet::FileSystem.read('/proc/1/comm').include?('systemd')
defaultfor 'os.name' => :cumuluslinux, 'os.release.major' => %w[1 2]
defaultfor 'os.name' => :debian, 'os.release.major' => %w[5 6 7]
defaultfor 'os.name' => :devuan
# Remove the symlinks
def disable
if `dpkg --compare-versions $(dpkg-query -W --showformat '${Version}' sysv-rc) ge 2.88 ; echo $?`.to_i == 0
update_rc @resource[:name], "disable"
else
update_rc "-f", @resource[:name], "remove"
update_rc @resource[:name], "stop", "00", "1", "2", "3", "4", "5", "6", "."
end
end
def enabled?
status = execute(["/usr/sbin/invoke-rc.d", "--quiet", "--query", @resource[:name], "start"], :failonfail => false)
# 104 is the exit status when you query start an enabled service.
# 106 is the exit status when the policy layer supplies a fallback action
# See x-man-page://invoke-rc.d
if [104, 106].include?(status.exitstatus)
:true
elsif [101, 105].include?(status.exitstatus)
# 101 is action not allowed, which means we have to do the check manually.
# 105 is unknown, which generally means the initscript does not support query
# The debian policy states that the initscript should support methods of query
# For those that do not, perform the checks manually
# http://www.debian.org/doc/debian-policy/ch-opersys.html
if get_start_link_count >= 4
:true
else
:false
end
else
:false
end
end
def get_start_link_count
Dir.glob("/etc/rc*.d/S??#{@resource[:name]}").length
end
def enable
update_rc "-f", @resource[:name], "remove"
update_rc @resource[:name], "defaults"
end
def statuscmd
# /usr/sbin/service provides an abstraction layer which is able to query services
# independent of the init system used.
# See https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=775795
(@resource[:hasstatus] == :true) && [command(:service), @resource[:name], "status"]
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/provider/service/windows.rb | lib/puppet/provider/service/windows.rb | # frozen_string_literal: true
# Windows Service Control Manager (SCM) provider
Puppet::Type.type(:service).provide :windows, :parent => :service do
desc <<-EOT
Support for Windows Service Control Manager (SCM). This provider can
start, stop, enable, and disable services, and the SCM provides working
status methods for all services.
Control of service groups (dependencies) is not yet supported, nor is running
services as a specific user.
EOT
defaultfor 'os.name' => :windows
confine 'os.name' => :windows
has_feature :refreshable, :configurable_timeout, :manages_logon_credentials
def enable
Puppet::Util::Windows::Service.set_startup_configuration(@resource[:name], options: { startup_type: :SERVICE_AUTO_START })
rescue => detail
raise Puppet::Error.new(_("Cannot enable %{resource_name}, error was: %{detail}") % { resource_name: @resource[:name], detail: detail }, detail)
end
def disable
Puppet::Util::Windows::Service.set_startup_configuration(@resource[:name], options: { startup_type: :SERVICE_DISABLED })
rescue => detail
raise Puppet::Error.new(_("Cannot disable %{resource_name}, error was: %{detail}") % { resource_name: @resource[:name], detail: detail }, detail)
end
def manual_start
Puppet::Util::Windows::Service.set_startup_configuration(@resource[:name], options: { startup_type: :SERVICE_DEMAND_START })
rescue => detail
raise Puppet::Error.new(_("Cannot enable %{resource_name} for manual start, error was: %{detail}") % { resource_name: @resource[:name], detail: detail }, detail)
end
def delayed_start
Puppet::Util::Windows::Service.set_startup_configuration(@resource[:name], options: { startup_type: :SERVICE_AUTO_START, delayed: true })
rescue => detail
raise Puppet::Error.new(_("Cannot enable %{resource_name} for delayed start, error was: %{detail}") % { resource_name: @resource[:name], detail: detail }, detail)
end
def enabled?
return :false unless Puppet::Util::Windows::Service.exists?(@resource[:name])
start_type = Puppet::Util::Windows::Service.service_start_type(@resource[:name])
debug("Service #{@resource[:name]} start type is #{start_type}")
case start_type
when :SERVICE_AUTO_START, :SERVICE_BOOT_START, :SERVICE_SYSTEM_START
:true
when :SERVICE_DEMAND_START
:manual
when :SERVICE_DELAYED_AUTO_START
:delayed
when :SERVICE_DISABLED
:false
else
raise Puppet::Error, _("Unknown start type: %{start_type}") % { start_type: start_type }
end
rescue => detail
raise Puppet::Error.new(_("Cannot get start type %{resource_name}, error was: %{detail}") % { resource_name: @resource[:name], detail: detail }, detail)
end
def start
if status == :paused
Puppet::Util::Windows::Service.resume(@resource[:name], timeout: @resource[:timeout])
return
end
# status == :stopped here
if enabled? == :false
# If disabled and not managing enable, respect disabled and fail.
if @resource[:enable].nil?
raise Puppet::Error, _("Will not start disabled service %{resource_name} without managing enable. Specify 'enable => false' to override.") % { resource_name: @resource[:name] }
# Otherwise start. If enable => false, we will later sync enable and
# disable the service again.
elsif @resource[:enable] == :true
enable
else
manual_start
end
end
Puppet::Util::Windows::Service.start(@resource[:name], timeout: @resource[:timeout])
end
def stop
Puppet::Util::Windows::Service.stop(@resource[:name], timeout: @resource[:timeout])
end
def status
return :stopped unless Puppet::Util::Windows::Service.exists?(@resource[:name])
current_state = Puppet::Util::Windows::Service.service_state(@resource[:name])
state = case current_state
when :SERVICE_STOPPED, :SERVICE_STOP_PENDING
:stopped
when :SERVICE_PAUSED, :SERVICE_PAUSE_PENDING
:paused
when :SERVICE_RUNNING, :SERVICE_CONTINUE_PENDING, :SERVICE_START_PENDING
:running
else
raise Puppet::Error, _("Unknown service state '%{current_state}' for service '%{resource_name}'") % { current_state: current_state, resource_name: @resource[:name] }
end
debug("Service #{@resource[:name]} is #{current_state}")
state
rescue => detail
Puppet.warning("Status for service #{@resource[:name]} could not be retrieved: #{detail}")
:stopped
end
def default_timeout
Puppet::Util::Windows::Service::DEFAULT_TIMEOUT
end
# returns all providers for all existing services and startup state
def self.instances
services = []
Puppet::Util::Windows::Service.services.each do |service_name, _|
services.push(new(:name => service_name))
end
services
end
def logonaccount_insync?(current)
@normalized_logon_account ||= normalize_logonaccount
@resource[:logonaccount] = @normalized_logon_account
insync = @resource[:logonaccount].casecmp?(current)
self.logonpassword = @resource[:logonpassword] if insync
insync
end
def logonaccount
return unless Puppet::Util::Windows::Service.exists?(@resource[:name])
Puppet::Util::Windows::Service.logon_account(@resource[:name])
end
def logonaccount=(value)
validate_logon_credentials
Puppet::Util::Windows::Service.set_startup_configuration(@resource[:name], options: { logon_account: value, logon_password: @resource[:logonpassword] })
restart if @resource[:ensure] == :running && [:running, :paused].include?(status)
end
def logonpassword=(value)
validate_logon_credentials
Puppet::Util::Windows::Service.set_startup_configuration(@resource[:name], options: { logon_password: value })
end
private
def normalize_logonaccount
logon_account = @resource[:logonaccount].sub(/^\.\\/, "#{Puppet::Util::Windows::ADSI.computer_name}\\")
return 'LocalSystem' if Puppet::Util::Windows::User.localsystem?(logon_account)
@logonaccount_information ||= Puppet::Util::Windows::SID.name_to_principal(logon_account)
return logon_account unless @logonaccount_information
return ".\\#{@logonaccount_information.account}" if @logonaccount_information.domain == Puppet::Util::Windows::ADSI.computer_name
@logonaccount_information.domain_account
end
def validate_logon_credentials
unless Puppet::Util::Windows::User.localsystem?(@normalized_logon_account)
raise Puppet::Error, "\"#{@normalized_logon_account}\" is not a valid account" unless @logonaccount_information && [:SidTypeUser, :SidTypeWellKnownGroup].include?(@logonaccount_information.account_type)
user_rights = Puppet::Util::Windows::User.get_rights(@logonaccount_information.domain_account) unless Puppet::Util::Windows::User.default_system_account?(@normalized_logon_account)
raise Puppet::Error, "\"#{@normalized_logon_account}\" has the 'Log On As A Service' right set to denied." if user_rights =~ /SeDenyServiceLogonRight/
raise Puppet::Error, "\"#{@normalized_logon_account}\" is missing the 'Log On As A Service' right." unless user_rights.nil? || user_rights =~ /SeServiceLogonRight/
end
is_a_predefined_local_account = Puppet::Util::Windows::User.default_system_account?(@normalized_logon_account) || @normalized_logon_account == 'LocalSystem'
account_info = @normalized_logon_account.split("\\")
able_to_logon = Puppet::Util::Windows::User.password_is?(account_info[1], @resource[:logonpassword], account_info[0]) unless is_a_predefined_local_account
raise Puppet::Error, "The given password is invalid for user '#{@normalized_logon_account}'." unless is_a_predefined_local_account || able_to_logon
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/provider/service/smf.rb | lib/puppet/provider/service/smf.rb | # frozen_string_literal: true
require 'timeout'
# Solaris 10 SMF-style services.
Puppet::Type.type(:service).provide :smf, :parent => :base do
desc <<-EOT
Support for Sun's new Service Management Framework.
When managing the enable property, this provider will try to preserve
the previous ensure state per the enableable semantics. On Solaris,
enabling a service starts it up while disabling a service stops it. Thus,
there's a chance for this provider to execute two operations when managing
the enable property. For example, if enable is set to true and the ensure
state is stopped, this provider will manage the service using two operations:
one to enable the service which will start it up, and another to stop the
service (without affecting its enabled status).
By specifying `manifest => "/path/to/service.xml"`, the SMF manifest will
be imported if it does not exist.
EOT
defaultfor 'os.family' => :solaris
confine 'os.family' => :solaris
commands :adm => "/usr/sbin/svcadm",
:svcs => "/usr/bin/svcs",
:svccfg => "/usr/sbin/svccfg"
has_feature :refreshable
def self.instances
service_instances = svcs("-H", "-o", "state,fmri").split("\n")
# Puppet does not manage services in the legacy_run state, so filter those out.
service_instances.reject! { |line| line =~ /^legacy_run/ }
service_instances.collect! do |line|
state, fmri = line.split(/\s+/)
status = case state
when /online/; :running
when /maintenance/; :maintenance
when /degraded/; :degraded
else :stopped
end
new({ :name => fmri, :ensure => status })
end
service_instances
end
def initialize(*args)
super(*args)
# This hash contains the properties we need to sync. in our flush method.
#
# TODO (PUP-9051): Should we use @property_hash here? It seems like
# @property_hash should be empty by default and is something we can
# control so I think so?
@properties_to_sync = {}
end
def service_exists?
service_fmri
true
rescue Puppet::ExecutionFailure
false
end
def setup_service
return unless @resource[:manifest]
return if service_exists?
Puppet.notice("Importing #{@resource[:manifest]} for #{@resource[:name]}")
svccfg(:import, @resource[:manifest])
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error.new("Cannot config #{@resource[:name]} to enable it: #{detail}", detail)
end
# Returns the service's FMRI. We fail if multiple FMRIs correspond to
# @resource[:name].
#
# If the service does not exist or we fail to get any FMRIs from svcs,
# this method will raise a Puppet::Error
def service_fmri
return @fmri if @fmri
# `svcs -l` is better to use because we can detect service instances
# that have not yet been activated or enabled (i.e. it lets us detect
# services that svcadm has not yet touched). `svcs -H -o fmri` is a bit
# more limited.
lines = svcs("-l", @resource[:name]).chomp.lines.to_a
lines.select! { |line| line =~ /^fmri/ }
fmris = lines.map! { |line| line.split(' ')[-1].chomp }
unless fmris.length == 1
raise Puppet::Error, _("Failed to get the FMRI of the %{service} service: The pattern '%{service}' matches multiple FMRIs! These are the FMRIs it matches: %{all_fmris}") % { service: @resource[:name], all_fmris: fmris.join(', ') }
end
@fmri = fmris.first
end
# Returns true if the provider supports incomplete services.
def supports_incomplete_services?
Puppet::Util::Package.versioncmp(Puppet.runtime[:facter].value('os.release.full'), '11.1') >= 0
end
# Returns true if the service is complete. A complete service is a service that
# has the general/complete property defined.
def complete_service?
unless supports_incomplete_services?
raise Puppet::Error, _("Cannot query if the %{service} service is complete: The concept of complete/incomplete services was introduced in Solaris 11.1. You are on a Solaris %{release} machine.") % { service: @resource[:name], release: Puppet.runtime[:facter].value('os.release.full') }
end
return @complete_service if @complete_service
# We need to use the service's FMRI when querying its config. because
# general/complete is an instance-specific property.
fmri = service_fmri
# Check if the general/complete property is defined. If it is undefined,
# then svccfg will not print anything to the console.
property_defn = svccfg("-s", fmri, "listprop", "general/complete").chomp
@complete_service = !property_defn.empty?
end
def enable
@properties_to_sync[:enable] = true
end
def enabled?
return :false unless service_exists?
_property, _type, value = svccfg("-s", service_fmri, "listprop", "general/enabled").split(' ')
value == 'true' ? :true : :false
end
def disable
@properties_to_sync[:enable] = false
end
def restartcmd
if Puppet::Util::Package.versioncmp(Puppet.runtime[:facter].value('os.release.full'), '11.2') >= 0
[command(:adm), :restart, "-s", service_fmri]
else
# Synchronous restart only supported in Solaris 11.2 and above
[command(:adm), :restart, service_fmri]
end
end
def service_states
# Gets the current and next state of the service. We have a next state because SMF
# manages services asynchronously. If there is no 'next' state, svcs will put a '-'
# to indicate as such.
current_state, next_state = svcs("-H", "-o", "state,nstate", service_fmri).chomp.split(' ')
{
:current => current_state,
:next => next_state == "-" ? nil : next_state
}
end
# Wait for the service to transition into the specified state before returning.
# This is necessary due to the asynchronous nature of SMF services.
# desired_states should include only online, offline, disabled, or uninitialized.
# See PUP-5474 for long-term solution to this issue.
def wait(*desired_states)
Timeout.timeout(60) do
loop do
states = service_states
break if desired_states.include?(states[:current]) && states[:next].nil?
Kernel.sleep(1)
end
end
rescue Timeout::Error
raise Puppet::Error, "Timed out waiting for #{@resource[:name]} to transition states"
end
def start
@properties_to_sync[:ensure] = :running
end
def stop
@properties_to_sync[:ensure] = :stopped
end
def restart
# Wait for the service to actually start before returning.
super
wait('online')
end
def status
return super if @resource[:status]
begin
if supports_incomplete_services?
unless complete_service?
debug _("The %{service} service is incomplete so its status will be reported as :stopped. See `svcs -xv %{fmri}` for more details.") % { service: @resource[:name], fmri: service_fmri }
return :stopped
end
end
# Get the current state and the next state. If there is a next state,
# use that for the state comparison.
states = service_states
state = states[:next] || states[:current]
rescue Puppet::ExecutionFailure => e
# TODO (PUP-8957): Should this be set back to INFO ?
debug "Could not get status on service #{name} #{e}"
return :stopped
end
case state
when "online"
:running
when "offline", "disabled", "uninitialized"
:stopped
when "maintenance"
:maintenance
when "degraded"
:degraded
when "legacy_run"
raise Puppet::Error,
"Cannot manage legacy services through SMF"
else
raise Puppet::Error,
"Unmanageable state '#{state}' on service #{name}"
end
end
# Helper that encapsulates the clear + svcadm [enable|disable]
# logic in one place. Makes it easy to test things out and also
# cleans up flush's code.
def maybe_clear_service_then_svcadm(cur_state, subcmd, flags)
# If the cur_state is maint or degraded, then we need to clear the service
# before we enable or disable it.
adm('clear', service_fmri) if [:maintenance, :degraded].include?(cur_state)
adm(subcmd, flags, service_fmri)
end
# The flush method is necessary for the SMF provider because syncing the enable and ensure
# properties are not independent operations like they are in most of our other service
# providers.
def flush
# We append the "_" because ensure is a Ruby keyword, and it is good to keep property
# variable names consistent with each other.
enable_ = @properties_to_sync[:enable]
ensure_ = @properties_to_sync[:ensure]
# All of the relevant properties are in sync., so we do not need to do
# anything here.
return if enable_.nil? and ensure_.nil?
# Set-up our service so that we know it will exist and so we can collect its fmri. Also
# simplifies the code. For a nonexistent service, one of enable or ensure will be true
# here (since we're syncing them), so we can fail early if setup_service fails.
setup_service
fmri = service_fmri
# Useful constants for operations involving multiple states
stopped = %w[offline disabled uninitialized]
# Get the current state of the service.
cur_state = status
if enable_.nil?
# Only ensure needs to be syncd. The -t flag tells svcadm to temporarily
# enable/disable the service, where the temporary status is gone upon
# reboot. This is exactly what we want, because we do not want to touch
# the enable property.
if ensure_ == :stopped
maybe_clear_service_then_svcadm(cur_state, 'disable', '-st')
wait(*stopped)
else # ensure == :running
maybe_clear_service_then_svcadm(cur_state, 'enable', '-rst')
wait('online')
end
return
end
# Here, enable is being syncd. svcadm starts the service if we enable it, or shuts it down if we
# disable it. However, we want our service to be in a final state, which is either whatever the
# new ensured value is, or what our original state was prior to enabling it.
#
# NOTE: Even if you try to set the general/enabled property with svccfg, SMF will still
# try to start or shut down the service. Plus, setting general/enabled with svccfg does not
# enable the service's dependencies, while svcadm handles this correctly.
#
# NOTE: We're treating :running and :degraded the same. The reason is b/c an SMF managed service
# can only enter the :degraded state if it is online. Since disabling the service also shuts it
# off, we cannot set it back to the :degraded state. Thus, it is best to lump :running and :degraded
# into the same category to maintain a consistent postcondition on the service's final state when
# enabling and disabling it.
final_state = ensure_ || cur_state
final_state = :running if final_state == :degraded
if enable_
maybe_clear_service_then_svcadm(cur_state, 'enable', '-rs')
else
maybe_clear_service_then_svcadm(cur_state, 'disable', '-s')
end
# We're safe with 'whens' here since self.status already errors on any
# unmanageable states.
case final_state
when :running
adm('enable', '-rst', fmri) unless enable_
wait('online')
when :stopped
adm('disable', '-st', fmri) if enable_
wait(*stopped)
when :maintenance
adm('mark', '-I', 'maintenance', fmri)
wait('maintenance')
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/provider/service/upstart.rb | lib/puppet/provider/service/upstart.rb | # frozen_string_literal: true
Puppet::Type.type(:service).provide :upstart, :parent => :debian do
START_ON = /^\s*start\s+on/
COMMENTED_START_ON = /^\s*#+\s*start\s+on/
MANUAL = /^\s*manual\s*$/
desc "Ubuntu service management with `upstart`.
This provider manages `upstart` jobs on Ubuntu. For `upstart` documentation,
see <http://upstart.ubuntu.com/>.
"
confine :any => [
Puppet.runtime[:facter].value('os.name') == 'Ubuntu',
(Puppet.runtime[:facter].value('os.family') == 'RedHat' and Puppet.runtime[:facter].value('os.release.full') =~ /^6\./),
(Puppet.runtime[:facter].value('os.name') == 'Amazon' and Puppet.runtime[:facter].value('os.release.major') =~ /\d{4}/),
Puppet.runtime[:facter].value('os.name') == 'LinuxMint'
]
defaultfor 'os.name' => :ubuntu, 'os.release.major' => ["10.04", "12.04", "14.04", "14.10"]
defaultfor 'os.name' => :LinuxMint, 'os.release.major' => %w[10 11 12 13 14 15 16 17]
commands :start => "/sbin/start",
:stop => "/sbin/stop",
:restart => "/sbin/restart",
:status_exec => "/sbin/status",
:initctl => "/sbin/initctl"
# We only want to use upstart as our provider if the upstart daemon is running.
# This can be checked by running `initctl version --quiet` on a machine that has
# upstart installed.
confine :true => -> { has_initctl? }
def self.has_initctl?
# Puppet::Util::Execution.execute does not currently work on jRuby.
# Unfortunately, since this confine is invoked whenever we check for
# provider suitability and since provider suitability is still checked
# on the master, this confine will still be invoked on the master. Thus
# to avoid raising an exception, we do an early return if we're running
# on jRuby.
return false if Puppet::Util::Platform.jruby?
begin
initctl('version', '--quiet')
true
rescue
false
end
end
# upstart developer haven't implemented initctl enable/disable yet:
# http://www.linuxplanet.com/linuxplanet/tutorials/7033/2/
has_feature :enableable
def self.instances
get_services(excludes) # Take exclude list from init provider
end
def self.excludes
excludes = super
if Puppet.runtime[:facter].value('os.family') == 'RedHat'
# Puppet cannot deal with services that have instances, so we have to
# ignore these services using instances on redhat based systems.
excludes += %w[serial tty]
end
excludes
end
def self.get_services(exclude = [])
instances = []
execpipe("#{command(:initctl)} list") { |process|
process.each_line { |line|
# needs special handling of services such as network-interface:
# initctl list:
# network-interface (lo) start/running
# network-interface (eth0) start/running
# network-interface-security start/running
matcher = line.match(/^(network-interface)\s\(([^)]+)\)/)
name = if matcher
"#{matcher[1]} INTERFACE=#{matcher[2]}"
else
matcher = line.match(/^(network-interface-security)\s\(([^)]+)\)/)
if matcher
"#{matcher[1]} JOB=#{matcher[2]}"
else
line.split.first
end
end
instances << new(:name => name)
}
}
instances.reject { |instance| exclude.include?(instance.name) }
end
def self.defpath
["/etc/init", "/etc/init.d"]
end
def upstart_version
@upstart_version ||= initctl("--version").match(/initctl \(upstart ([^)]*)\)/)[1]
end
# Where is our override script?
def overscript
@overscript ||= initscript.gsub(/\.conf$/, ".override")
end
def search(name)
# Search prefers .conf as that is what upstart uses
[".conf", "", ".sh"].each do |suffix|
paths.each do |path|
service_name = name.match(/^(\S+)/)[1]
fqname = File.join(path, service_name + suffix)
if Puppet::FileSystem.exist?(fqname)
return fqname
end
debug("Could not find #{name}#{suffix} in #{path}")
end
end
raise Puppet::Error, "Could not find init script or upstart conf file for '#{name}'"
end
def enabled?
return super unless is_upstart?
script_contents = read_script_from(initscript)
if version_is_pre_0_6_7
enabled_pre_0_6_7?(script_contents)
elsif version_is_pre_0_9_0
enabled_pre_0_9_0?(script_contents)
elsif version_is_post_0_9_0
enabled_post_0_9_0?(script_contents, read_override_file)
end
end
def enable
return super unless is_upstart?
script_text = read_script_from(initscript)
if version_is_pre_0_9_0
enable_pre_0_9_0(script_text)
else
enable_post_0_9_0(script_text, read_override_file)
end
end
def disable
return super unless is_upstart?
script_text = read_script_from(initscript)
if version_is_pre_0_6_7
disable_pre_0_6_7(script_text)
elsif version_is_pre_0_9_0
disable_pre_0_9_0(script_text)
elsif version_is_post_0_9_0
disable_post_0_9_0(read_override_file)
end
end
def startcmd
is_upstart? ? [command(:start), @resource[:name]] : super
end
def stopcmd
is_upstart? ? [command(:stop), @resource[:name]] : super
end
def restartcmd
is_upstart? ? (@resource[:hasrestart] == :true) && [command(:restart), @resource[:name]] : super
end
def statuscmd
is_upstart? ? nil : super # this is because upstart is broken with its return codes
end
def status
if (@resource[:hasstatus] == :false) ||
@resource[:status] ||
!is_upstart?
return super
end
output = status_exec(@resource[:name].split)
if output =~ %r{start/}
:running
else
:stopped
end
end
private
def is_upstart?(script = initscript)
Puppet::FileSystem.exist?(script) && script.match(%r{/etc/init/\S+\.conf})
end
def version_is_pre_0_6_7
Puppet::Util::Package.versioncmp(upstart_version, "0.6.7") == -1
end
def version_is_pre_0_9_0
Puppet::Util::Package.versioncmp(upstart_version, "0.9.0") == -1
end
def version_is_post_0_9_0
Puppet::Util::Package.versioncmp(upstart_version, "0.9.0") >= 0
end
def enabled_pre_0_6_7?(script_text)
# Upstart version < 0.6.7 means no manual stanza.
if script_text.match(START_ON)
:true
else
:false
end
end
def enabled_pre_0_9_0?(script_text)
# Upstart version < 0.9.0 means no override files
# So we check to see if an uncommented start on or manual stanza is the last one in the file
# The last one in the file wins.
enabled = :false
script_text.each_line do |line|
if line.match(START_ON)
enabled = :true
elsif line.match(MANUAL)
enabled = :false
end
end
enabled
end
def enabled_post_0_9_0?(script_text, over_text)
# This version has manual stanzas and override files
# So we check to see if an uncommented start on or manual stanza is the last one in the
# conf file and any override files. The last one in the file wins.
enabled = :false
script_text.each_line do |line|
if line.match(START_ON)
enabled = :true
elsif line.match(MANUAL)
enabled = :false
end
end
over_text.each_line do |line|
if line.match(START_ON)
enabled = :true
elsif line.match(MANUAL)
enabled = :false
end
end if over_text
enabled
end
def enable_pre_0_9_0(text)
# We also need to remove any manual stanzas to ensure that it is enabled
text = remove_manual_from(text)
if enabled_pre_0_9_0?(text) == :false
enabled_script =
if text.match(COMMENTED_START_ON)
uncomment_start_block_in(text)
else
add_default_start_to(text)
end
else
enabled_script = text
end
write_script_to(initscript, enabled_script)
end
def enable_post_0_9_0(script_text, over_text)
over_text = remove_manual_from(over_text)
if enabled_post_0_9_0?(script_text, over_text) == :false
if script_text.match(START_ON)
over_text << extract_start_on_block_from(script_text)
else
over_text << "\nstart on runlevel [2,3,4,5]"
end
end
write_script_to(overscript, over_text)
end
def disable_pre_0_6_7(script_text)
disabled_script = comment_start_block_in(script_text)
write_script_to(initscript, disabled_script)
end
def disable_pre_0_9_0(script_text)
write_script_to(initscript, ensure_disabled_with_manual(script_text))
end
def disable_post_0_9_0(over_text)
write_script_to(overscript, ensure_disabled_with_manual(over_text))
end
def read_override_file
if Puppet::FileSystem.exist?(overscript)
read_script_from(overscript)
else
""
end
end
def uncomment(line)
line.gsub(/^(\s*)#+/, '\1')
end
def remove_trailing_comments_from_commented_line_of(line)
line.gsub(/^(\s*#+\s*[^#]*).*/, '\1')
end
def remove_trailing_comments_from(line)
line.gsub(/^(\s*[^#]*).*/, '\1')
end
def unbalanced_parens_on(line)
line.count('(') - line.count(')')
end
def remove_manual_from(text)
text.gsub(MANUAL, "")
end
def comment_start_block_in(text)
parens = 0
text.lines.map do |line|
if line.match(START_ON) || parens > 0
# If there are more opening parens than closing parens, we need to comment out a multiline 'start on' stanza
parens += unbalanced_parens_on(remove_trailing_comments_from(line))
"#" + line
else
line
end
end.join('')
end
def uncomment_start_block_in(text)
parens = 0
text.lines.map do |line|
if line.match(COMMENTED_START_ON) || parens > 0
parens += unbalanced_parens_on(remove_trailing_comments_from_commented_line_of(line))
uncomment(line)
else
line
end
end.join('')
end
def extract_start_on_block_from(text)
parens = 0
text.lines.map do |line|
if line.match(START_ON) || parens > 0
parens += unbalanced_parens_on(remove_trailing_comments_from(line))
line
end
end.join('')
end
def add_default_start_to(text)
text + "\nstart on runlevel [2,3,4,5]"
end
def ensure_disabled_with_manual(text)
remove_manual_from(text) + "\nmanual"
end
def read_script_from(filename)
File.read(filename)
end
def write_script_to(file, text)
Puppet::Util.replace_file(file, 0o644) do |f|
f.write(text)
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/provider/service/rcng.rb | lib/puppet/provider/service/rcng.rb | # frozen_string_literal: true
Puppet::Type.type(:service).provide :rcng, :parent => :bsd do
desc <<-EOT
RCng service management with rc.d
EOT
defaultfor 'os.name' => [:netbsd, :cargos]
confine 'os.name' => [:netbsd, :cargos]
def self.defpath
"/etc/rc.d"
end
# if the service file exists in rc.conf.d AND matches an expected pattern
# then it's already enabled
def enabled?
rcfile = File.join(rcconf_dir, @resource[:name])
if Puppet::FileSystem.exist?(rcfile)
File.open(rcfile).readlines.each do |line|
# Now look for something that looks like "service=${service:=YES}" or "service=YES"
if line =~ /^\s*#{@resource[:name]}=(?:YES|\${#{@resource[:name]}:=YES})/
return :true
end
end
end
:false
end
# enable service by creating a service file under rc.conf.d with the
# proper contents, or by modifying it's contents to to enable the service.
def enable
Dir.mkdir(rcconf_dir) unless Puppet::FileSystem.exist?(rcconf_dir)
rcfile = File.join(rcconf_dir, @resource[:name])
if Puppet::FileSystem.exist?(rcfile)
newcontents = []
File.open(rcfile).readlines.each do |line|
if line =~ /^\s*#{@resource[:name]}=(NO|\$\{#{@resource[:name]}:NO\})/
line = "#{@resource[:name]}=${#{@resource[:name]}:=YES}"
end
newcontents.push(line)
end
Puppet::Util.replace_file(rcfile, 0o644) do |f|
f.puts newcontents
end
else
Puppet::Util.replace_file(rcfile, 0o644) do |f|
f.puts "%s=${%s:=YES}\n" % [@resource[:name], @resource[:name]]
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/provider/service/runit.rb | lib/puppet/provider/service/runit.rb | # frozen_string_literal: true
# Daemontools service management
#
# author Brice Figureau <brice-puppet@daysofwonder.com>
Puppet::Type.type(:service).provide :runit, :parent => :daemontools do
desc <<-'EOT'
Runit service management.
This provider manages daemons running supervised by Runit.
When detecting the service directory it will check, in order of preference:
* `/service`
* `/etc/service`
* `/var/service`
The daemon directory should be in one of the following locations:
* `/etc/sv`
* `/var/lib/service`
or this can be overridden in the service resource parameters:
service { 'myservice':
provider => 'runit',
path => '/path/to/daemons',
}
This provider supports out of the box:
* start/stop
* enable/disable
* restart
* status
EOT
commands :sv => "/usr/bin/sv"
class << self
# this is necessary to autodetect a valid resource
# default path, since there is no standard for such directory.
def defpath
@defpath ||= ["/var/lib/service", "/etc/sv"].find do |path|
Puppet::FileSystem.exist?(path) && FileTest.directory?(path)
end
@defpath
end
end
# find the service dir on this node
def servicedir
unless @servicedir
["/service", "/etc/service", "/var/service"].each do |path|
if Puppet::FileSystem.exist?(path)
@servicedir = path
break
end
end
raise "Could not find service directory" unless @servicedir
end
@servicedir
end
def status
begin
output = sv "status", daemon
return :running if output =~ /^run: /
rescue Puppet::ExecutionFailure => detail
unless detail.message =~ /(warning: |runsv not running$)/
raise Puppet::Error.new("Could not get status for service #{resource.ref}: #{detail}", detail)
end
end
:stopped
end
def stop
sv "stop", service
end
def start
if enabled? != :true
enable
# Work around issue #4480
# runsvdir takes up to 5 seconds to recognize
# the symlink created by this call to enable
# TRANSLATORS 'runsvdir' is a linux service name and should not be translated
Puppet.info _("Waiting 5 seconds for runsvdir to discover service %{service}") % { service: service }
sleep 5
end
sv "start", service
end
def restart
sv "restart", service
end
# disable by removing the symlink so that runit
# doesn't restart our service behind our back
# note that runit doesn't need to perform a stop
# before a disable
def disable
# unlink the daemon symlink to disable it
Puppet::FileSystem.unlink(service) if Puppet::FileSystem.symlink?(service)
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/provider/file/posix.rb | lib/puppet/provider/file/posix.rb | # frozen_string_literal: true
Puppet::Type.type(:file).provide :posix do
desc "Uses POSIX functionality to manage file ownership and permissions."
confine :feature => :posix
has_features :manages_symlinks
include Puppet::Util::POSIX
include Puppet::Util::Warnings
require 'etc'
require_relative '../../../puppet/util/selinux'
class << self
def selinux_handle
return nil unless Puppet::Util::SELinux.selinux_support?
# selabel_open takes 3 args: backend, options, and nopt. The backend param
# is a constant, SELABEL_CTX_FILE, which happens to be 0. Since options is
# nil, nopt can be 0 since nopt represents the # of options specified.
@selinux_handle ||= Selinux.selabel_open(Selinux::SELABEL_CTX_FILE, nil, 0)
end
def post_resource_eval
if @selinux_handle
Selinux.selabel_close(@selinux_handle)
@selinux_handle = nil
end
end
end
def uid2name(id)
return id.to_s if id.is_a?(Symbol) or id.is_a?(String)
return nil if id > Puppet[:maximum_uid].to_i
begin
user = Etc.getpwuid(id)
rescue TypeError, ArgumentError
return nil
end
if user.uid == ""
nil
else
user.name
end
end
# Determine if the user is valid, and if so, return the UID
def name2uid(value)
Integer(value)
rescue
uid(value) || false
end
def gid2name(id)
return id.to_s if id.is_a?(Symbol) or id.is_a?(String)
return nil if id > Puppet[:maximum_uid].to_i
begin
group = Etc.getgrgid(id)
rescue TypeError, ArgumentError
return nil
end
if group.gid == ""
nil
else
group.name
end
end
def name2gid(value)
Integer(value)
rescue
gid(value) || false
end
def owner
stat = resource.stat
unless stat
return :absent
end
currentvalue = stat.uid
# On OS X, files that are owned by -2 get returned as really
# large UIDs instead of negative ones. This isn't a Ruby bug,
# it's an OS X bug, since it shows up in perl, too.
if currentvalue > Puppet[:maximum_uid].to_i
warning _("Apparently using negative UID (%{currentvalue}) on a platform that does not consistently handle them") % { currentvalue: currentvalue }
currentvalue = :silly
end
currentvalue
end
def owner=(should)
# Set our method appropriately, depending on links.
if resource[:links] == :manage
method = :lchown
else
method = :chown
end
begin
File.send(method, should, nil, resource[:path])
rescue => detail
raise Puppet::Error, _("Failed to set owner to '%{should}': %{detail}") % { should: should, detail: detail }, detail.backtrace
end
end
def group
stat = resource.stat
return :absent unless stat
currentvalue = stat.gid
# On OS X, files that are owned by -2 get returned as really
# large GIDs instead of negative ones. This isn't a Ruby bug,
# it's an OS X bug, since it shows up in perl, too.
if currentvalue > Puppet[:maximum_uid].to_i
warning _("Apparently using negative GID (%{currentvalue}) on a platform that does not consistently handle them") % { currentvalue: currentvalue }
currentvalue = :silly
end
currentvalue
end
def group=(should)
# Set our method appropriately, depending on links.
if resource[:links] == :manage
method = :lchown
else
method = :chown
end
begin
File.send(method, nil, should, resource[:path])
rescue => detail
raise Puppet::Error, _("Failed to set group to '%{should}': %{detail}") % { should: should, detail: detail }, detail.backtrace
end
end
def mode
stat = resource.stat
if stat
(stat.mode & 0o07777).to_s(8).rjust(4, '0')
else
:absent
end
end
def mode=(value)
File.chmod(value.to_i(8), resource[:path])
rescue => detail
error = Puppet::Error.new(_("failed to set mode %{mode} on %{path}: %{message}") % { mode: mode, path: resource[:path], message: detail.message })
error.set_backtrace detail.backtrace
raise error
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/file/windows.rb | lib/puppet/provider/file/windows.rb | # frozen_string_literal: true
Puppet::Type.type(:file).provide :windows do
desc "Uses Microsoft Windows functionality to manage file ownership and permissions."
confine 'os.name' => :windows
has_feature :manages_symlinks if Puppet.features.manages_symlinks?
include Puppet::Util::Warnings
if Puppet::Util::Platform.windows?
require_relative '../../../puppet/util/windows'
include Puppet::Util::Windows::Security
end
# Determine if the account is valid, and if so, return the UID
def name2id(value)
Puppet::Util::Windows::SID.name_to_sid(value)
end
# If it's a valid SID, get the name. Otherwise, it's already a name,
# so just return it.
def id2name(id)
if Puppet::Util::Windows::SID.valid_sid?(id)
Puppet::Util::Windows::SID.sid_to_name(id)
else
id
end
end
# We use users and groups interchangeably, so use the same methods for both
# (the type expects different methods, so we have to oblige).
alias :uid2name :id2name
alias :gid2name :id2name
alias :name2gid :name2id
alias :name2uid :name2id
def owner
return :absent unless resource.stat
get_owner(resource[:path])
end
def owner=(should)
set_owner(should, resolved_path)
rescue => detail
raise Puppet::Error, _("Failed to set owner to '%{should}': %{detail}") % { should: should, detail: detail }, detail.backtrace
end
def group
return :absent unless resource.stat
get_group(resource[:path])
end
def group=(should)
set_group(should, resolved_path)
rescue => detail
raise Puppet::Error, _("Failed to set group to '%{should}': %{detail}") % { should: should, detail: detail }, detail.backtrace
end
def mode
if resource.stat
mode = get_mode(resource[:path])
mode ? mode.to_s(8).rjust(4, '0') : :absent
else
:absent
end
end
def mode=(value)
managing_owner = !resource[:owner].nil?
managing_group = !resource[:group].nil?
set_mode(value.to_i(8), resource[:path], true, managing_owner, managing_group)
rescue => detail
error = Puppet::Error.new(_("failed to set mode %{mode} on %{path}: %{message}") % { mode: mode, path: resource[:path], message: detail.message })
error.set_backtrace detail.backtrace
raise error
end
def validate
if [:owner, :group, :mode].any? { |p| resource[p] } and !supports_acl?(resource[:path])
resource.fail(_("Can only manage owner, group, and mode on filesystems that support Windows ACLs, such as NTFS"))
end
end
# munge the windows group permissions if the user or group are set to SYSTEM
#
# when SYSTEM user is the group or user and the resoure is not managing them then treat
# the resource as insync if System has FullControl access.
#
# @param [String] current - the current mode returned by the resource
# @param [String] should - what the mode should be
#
# @return [String, nil] munged mode or nil if the resource should be out of sync
def munge_windows_system_group(current, should)
[
{
'type' => 'group',
'resource' => resource[:group],
'set_to_user' => group,
'fullcontrol' => "070".to_i(8),
'remove_mask' => "707".to_i(8),
'should_mask' => (should[0].to_i(8) & "070".to_i(8)),
},
{
'type' => 'owner',
'resource' => resource[:owner],
'set_to_user' => owner,
'fullcontrol' => "700".to_i(8),
'remove_mask' => "077".to_i(8),
'should_mask' => (should[0].to_i(8) & "700".to_i(8)),
}
].each do |mode_part|
if mode_part['resource'].nil? && (mode_part['set_to_user'] == Puppet::Util::Windows::SID::LocalSystem)
if (current.to_i(8) & mode_part['fullcontrol']) == mode_part['fullcontrol']
# Since the group is LocalSystem, and the permissions are FullControl,
# replace the value returned with the value expected. This will treat
# this specific situation as "insync"
current = ((current.to_i(8) & mode_part['remove_mask']) | mode_part['should_mask']).to_s(8).rjust(4, '0')
else
# If the SYSTEM account does _not_ have FullControl in this scenario, we should
# force the resource out of sync no matter what.
# TRANSLATORS 'SYSTEM' is a Windows name and should not be translated
Puppet.debug { _("%{resource_name}: %{mode_part_type} set to SYSTEM. SYSTEM permissions cannot be set below FullControl ('7')") % { resource_name: resource[:name], mode_part_type: mode_part['type'] } }
return nil
end
end
end
current
end
attr_reader :file
private
def file
@file ||= Puppet::FileSystem.pathname(resource[:path])
end
def resolved_path
path = file()
# under POSIX, :manage means use lchown - i.e. operate on the link
return path.to_s if resource[:links] == :manage
# otherwise, use chown -- that will resolve the link IFF it is a link
# otherwise it will operate on the path
Puppet::FileSystem.symlink?(path) ? Puppet::FileSystem.readlink(path) : path.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/provider/user/windows_adsi.rb | lib/puppet/provider/user/windows_adsi.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/windows'
Puppet::Type.type(:user).provide :windows_adsi do
desc "Local user management for Windows."
defaultfor 'os.name' => :windows
confine 'os.name' => :windows
has_features :manages_homedir, :manages_passwords, :manages_roles
def initialize(value = {})
super(value)
@deleted = false
end
def user
@user ||= Puppet::Util::Windows::ADSI::User.new(@resource[:name])
end
def roles
Puppet::Util::Windows::User.get_rights(@resource[:name])
end
def roles=(value)
current = roles.split(',')
should = value.split(',')
add_list = should - current
Puppet::Util::Windows::User.set_rights(@resource[:name], add_list) unless add_list.empty?
if @resource[:role_membership] == :inclusive
remove_list = current - should
Puppet::Util::Windows::User.remove_rights(@resource[:name], remove_list) unless remove_list.empty?
end
end
def groups
@groups ||= Puppet::Util::Windows::ADSI::Group.name_sid_hash(user.groups)
@groups.keys
end
def groups=(groups)
user.set_groups(groups, @resource[:membership] == :minimum)
end
def groups_insync?(current, should)
return false unless current
# By comparing account SIDs we don't have to worry about case
# sensitivity, or canonicalization of account names.
# Cannot use munge of the group property to canonicalize @should
# since the default array_matching comparison is not commutative
# dupes automatically weeded out when hashes built
current_groups = Puppet::Util::Windows::ADSI::Group.name_sid_hash(current)
specified_groups = Puppet::Util::Windows::ADSI::Group.name_sid_hash(should)
current_sids = current_groups.keys.to_a
specified_sids = specified_groups.keys.to_a
if @resource[:membership] == :inclusive
current_sids.sort == specified_sids.sort
else
(specified_sids & current_sids) == specified_sids
end
end
def groups_to_s(groups)
return '' if groups.nil? || !groups.is_a?(Array)
groups = groups.map do |group_name|
sid = Puppet::Util::Windows::SID.name_to_principal(group_name)
if sid.account =~ /\\/
account, _ = Puppet::Util::Windows::ADSI::Group.parse_name(sid.account)
else
account = sid.account
end
resource.debug("#{sid.domain}\\#{account} (#{sid.sid})")
"#{sid.domain}\\#{account}"
end
groups.join(',')
end
def create
@user = Puppet::Util::Windows::ADSI::User.create(@resource[:name])
@user.password = @resource[:password]
@user.commit
[:comment, :home, :groups].each do |prop|
send("#{prop}=", @resource[prop]) if @resource[prop]
end
if @resource.managehome?
Puppet::Util::Windows::User.load_profile(@resource[:name], @resource[:password])
end
end
def exists?
Puppet::Util::Windows::ADSI::User.exists?(@resource[:name])
end
def delete
# lookup sid before we delete account
sid = uid if @resource.managehome?
Puppet::Util::Windows::ADSI::User.delete(@resource[:name])
if sid
Puppet::Util::Windows::ADSI::UserProfile.delete(sid)
end
@deleted = true
end
# Only flush if we created or modified a user, not deleted
def flush
@user.commit if @user && !@deleted
end
def comment
user['Description']
end
def comment=(value)
user['Description'] = value
end
def home
user['HomeDirectory']
end
def home=(value)
user['HomeDirectory'] = value
end
def password
# avoid a LogonUserW style password check when the resource is not yet
# populated with a password (as is the case with `puppet resource user`)
return nil if @resource[:password].nil?
user.password_is?(@resource[:password]) ? @resource[:password] : nil
end
def password=(value)
if user.disabled?
info _("The user account '%s' is disabled; The password will still be changed" % @resource[:name])
elsif user.locked_out?
info _("The user account '%s' is locked out; The password will still be changed" % @resource[:name])
elsif user.expired?
info _("The user account '%s' is expired; The password will still be changed" % @resource[:name])
end
user.password = value
end
def uid
Puppet::Util::Windows::SID.name_to_sid(@resource[:name])
end
def uid=(value)
fail "uid is read-only"
end
[:gid, :shell].each do |prop|
define_method(prop) { nil }
define_method("#{prop}=") do |_v|
fail "No support for managing property #{prop} of user #{@resource[:name]} on Windows"
end
end
def self.instances
Puppet::Util::Windows::ADSI::User.map { |u| new(:ensure => :present, :name => u.name) }
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/user/hpux.rb | lib/puppet/provider/user/hpux.rb | # frozen_string_literal: true
Puppet::Type.type(:user).provide :hpuxuseradd, :parent => :useradd do
desc "User management for HP-UX. This provider uses the undocumented `-F`
switch to HP-UX's special `usermod` binary to work around the fact that
its standard `usermod` cannot make changes while the user is logged in.
New functionality provides for changing trusted computing passwords and
resetting password expirations under trusted computing."
defaultfor 'os.name' => "hp-ux"
confine 'os.name' => "hp-ux"
commands :modify => "/usr/sam/lbin/usermod.sam", :delete => "/usr/sam/lbin/userdel.sam", :add => "/usr/sam/lbin/useradd.sam"
options :comment, :method => :gecos
options :groups, :flag => "-G"
options :home, :flag => "-d", :method => :dir
verify :gid, "GID must be an integer" do |value|
value.is_a? Integer
end
verify :groups, "Groups must be comma-separated" do |value|
value !~ /\s/
end
has_features :manages_homedir, :allows_duplicates, :manages_passwords
def deletecmd
super.insert(1, "-F")
end
def modifycmd(param, value)
cmd = super(param, value)
cmd.insert(1, "-F")
if trusted then
# Append an additional command to reset the password age to 0
# until a workaround with expiry module can be found for trusted
# computing.
cmd << ";"
cmd << "/usr/lbin/modprpw"
cmd << "-v"
cmd << "-l"
cmd << resource.name.to_s
end
cmd
end
def password
# Password management routine for trusted and non-trusted systems
# temp=""
while ent = Etc.getpwent() # rubocop:disable Lint/AssignmentInCondition
if ent.name == resource.name
temp = ent.name
break
end
end
Etc.endpwent()
unless temp
return nil
end
ent = Etc.getpwnam(resource.name)
if ent.passwd == "*"
# Either no password or trusted password, check trusted
file_name = "/tcb/files/auth/#{resource.name.chars.first}/#{resource.name}"
if File.file?(file_name)
# Found the tcb user for the specific user, now get passwd
File.open(file_name).each do |line|
next unless line =~ /u_pwd/
temp_passwd = line.split(":")[1].split("=")[1]
ent.passwd = temp_passwd
return ent.passwd
end
else
debug "No trusted computing user file #{file_name} found."
end
else
ent.passwd
end
end
def trusted
# Check to see if the HP-UX box is running in trusted compute mode
# UID for root should always be 0
trusted_sys = exec_getprpw('root', '-m uid')
trusted_sys.chomp == "uid=0"
end
def exec_getprpw(user, opts)
Puppet::Util::Execution.execute("/usr/lbin/getprpw #{opts} #{user}", { :combine => 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/provider/user/aix.rb | lib/puppet/provider/user/aix.rb | # frozen_string_literal: true
# User Puppet provider for AIX. It uses standard commands to manage users:
# mkuser, rmuser, lsuser, chuser
#
# Notes:
# - AIX users can have expiry date defined with minute granularity,
# but Puppet does not allow it. There is a ticket open for that (#5431)
#
# - AIX maximum password age is in WEEKs, not days
#
# See https://puppet.com/docs/puppet/latest/provider_development.html
# for more information
require_relative '../../../puppet/provider/aix_object'
require_relative '../../../puppet/util/posix'
require 'tempfile'
require 'date'
Puppet::Type.type(:user).provide :aix, :parent => Puppet::Provider::AixObject do
desc "User management for AIX."
defaultfor 'os.name' => :aix
confine 'os.name' => :aix
# Commands that manage the element
commands :list => "/usr/sbin/lsuser"
commands :add => "/usr/bin/mkuser"
commands :delete => "/usr/sbin/rmuser"
commands :modify => "/usr/bin/chuser"
commands :chpasswd => "/bin/chpasswd"
# Provider features
has_features :manages_aix_lam
has_features :manages_homedir, :manages_passwords, :manages_shell
has_features :manages_expiry, :manages_password_age
has_features :manages_local_users_and_groups
class << self
def group_provider
@group_provider ||= Puppet::Type.type(:group).provider(:aix)
end
# Define some Puppet Property => AIX Attribute (and vice versa)
# conversion functions here.
def gid_to_pgrp(provider, gid)
group = group_provider.find(gid, provider.ia_module_args)
group[:name]
end
def pgrp_to_gid(provider, pgrp)
group = group_provider.find(pgrp, provider.ia_module_args)
group[:gid]
end
def expiry_to_expires(expiry)
return '0' if expiry == "0000-00-00" || expiry.to_sym == :absent
DateTime.parse(expiry, "%Y-%m-%d %H:%M")
.strftime("%m%d%H%M%y")
end
def expires_to_expiry(provider, expires)
return :absent if expires == '0'
unless (match_obj = /\A(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)\z/.match(expires))
# TRANSLATORS 'AIX' is the name of an operating system and should not be translated
Puppet.warning(_("Could not convert AIX expires date '%{expires}' on %{class_name}[%{resource_name}]") % { expires: expires, class_name: provider.resource.class.name, resource_name: provider.resource.name })
return :absent
end
month = match_obj[1]
day = match_obj[2]
year = match_obj[-1]
"20#{year}-#{month}-#{day}"
end
# We do some validation before-hand to ensure the value's an Array,
# a String, etc. in the property. This routine does a final check to
# ensure our value doesn't have whitespace before we convert it to
# an attribute.
def groups_property_to_attribute(groups)
if groups =~ /\s/
raise ArgumentError, _("Invalid value %{groups}: Groups must be comma separated!") % { groups: groups }
end
groups
end
# We do not directly use the groups attribute value because that will
# always include the primary group, even if our user is not one of its
# members. Instead, we retrieve our property value by parsing the etc/group file,
# which matches what we do on our other POSIX platforms like Linux and Solaris.
#
# See https://www.ibm.com/support/knowledgecenter/en/ssw_aix_72/com.ibm.aix.files/group_security.htm
def groups_attribute_to_property(provider, _groups)
Puppet::Util::POSIX.groups_of(provider.resource[:name]).join(',')
end
end
mapping puppet_property: :comment,
aix_attribute: :gecos
mapping puppet_property: :expiry,
aix_attribute: :expires,
property_to_attribute: method(:expiry_to_expires),
attribute_to_property: method(:expires_to_expiry)
mapping puppet_property: :gid,
aix_attribute: :pgrp,
property_to_attribute: method(:gid_to_pgrp),
attribute_to_property: method(:pgrp_to_gid)
mapping puppet_property: :groups,
property_to_attribute: method(:groups_property_to_attribute),
attribute_to_property: method(:groups_attribute_to_property)
mapping puppet_property: :home
mapping puppet_property: :shell
numeric_mapping puppet_property: :uid,
aix_attribute: :id
numeric_mapping puppet_property: :password_max_age,
aix_attribute: :maxage
numeric_mapping puppet_property: :password_min_age,
aix_attribute: :minage
numeric_mapping puppet_property: :password_warn_days,
aix_attribute: :pwdwarntime
# Now that we have all of our mappings, let's go ahead and make
# the resource methods (property getters + setters for our mapped
# properties + a getter for the attributes property).
mk_resource_methods
# Setting the primary group (pgrp attribute) on AIX causes both the
# current and new primary groups to be included in our user's groups,
# which is undesirable behavior. Thus, this custom setter resets the
# 'groups' property back to its previous value after setting the primary
# group.
def gid=(value)
old_pgrp = gid
cur_groups = groups
set(:gid, value)
begin
self.groups = cur_groups
rescue Puppet::Error => detail
raise Puppet::Error, _("Could not reset the groups property back to %{cur_groups} after setting the primary group on %{resource}[%{name}]. This means that the previous primary group of %{old_pgrp} and the new primary group of %{new_pgrp} have been added to %{cur_groups}. You will need to manually reset the groups property if this is undesirable behavior. Detail: %{detail}") % { cur_groups: cur_groups, resource: @resource.class.name, name: @resource.name, old_pgrp: old_pgrp, new_pgrp: value, detail: detail }, detail.backtrace
end
end
# Helper function that parses the password from the given
# password filehandle. This is here to make testing easier
# for #password since we cannot configure Mocha to mock out
# a method and have it return a block's value, meaning we
# cannot test #password directly (not in a simple and obvious
# way, at least).
# @api private
def parse_password(f)
# From the docs, a user stanza is formatted as (newlines are explicitly
# stated here for clarity):
# <user>:\n
# <attribute1>=<value1>\n
# <attribute2>=<value2>\n
#
# First, find our user stanza
stanza = f.each_line.find { |line| line =~ /\A#{@resource[:name]}:/ }
return :absent unless stanza
# Now find the password line, if it exists. Note our call to each_line here
# will pick up right where we left off.
match_obj = nil
f.each_line.find do |line|
# Break if we find another user stanza. This means our user
# does not have a password.
break if line =~ /^\S+:$/
match_obj = /password\s+=\s+(\S+)/.match(line)
end
return :absent unless match_obj
match_obj[1]
end
# - **password**
# The user's password, in whatever encrypted format the local machine
# requires. Be sure to enclose any value that includes a dollar sign ($)
# in single quotes ('). Requires features manages_passwords.
#
# Retrieve the password parsing the /etc/security/passwd file.
def password
# AIX reference indicates this file is ASCII
# https://www.ibm.com/support/knowledgecenter/en/ssw_aix_72/com.ibm.aix.files/passwd_security.htm
Puppet::FileSystem.open("/etc/security/passwd", nil, "r:ASCII") do |f|
parse_password(f)
end
end
def password=(value)
user = @resource[:name]
begin
# Puppet execute does not support strings as input, only files.
# The password is expected to be in an encrypted format given -e is specified:
# https://www.ibm.com/support/knowledgecenter/ssw_aix_71/com.ibm.aix.cmds1/chpasswd.htm
# /etc/security/passwd is specified as an ASCII file per the AIX documentation
tempfile = nil
tempfile = Tempfile.new("puppet_#{user}_pw", :encoding => Encoding::ASCII)
tempfile << "#{user}:#{value}\n"
tempfile.close()
# Options '-e', '-c', use encrypted password and clear flags
# Must receive "user:enc_password" as input
# command, arguments = {:failonfail => true, :combine => true}
# Fix for bugs #11200 and #10915
cmd = [self.class.command(:chpasswd), *ia_module_args, '-e', '-c']
execute_options = {
:failonfail => false,
:combine => true,
:stdinfile => tempfile.path
}
output = execute(cmd, execute_options)
# chpasswd can return 1, even on success (at least on AIX 6.1); empty output
# indicates success
if output != ""
raise Puppet::ExecutionFailure, "chpasswd said #{output}"
end
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error, "Could not set password on #{@resource.class.name}[#{@resource.name}]: #{detail}", detail.backtrace
ensure
if tempfile
# Extra close will noop. This is in case the write to our tempfile
# fails.
tempfile.close()
tempfile.delete()
end
end
end
def create
super
# We specify the 'groups' AIX attribute in AixObject's create method
# when creating our user. However, this does not always guarantee that
# our 'groups' property is set to the right value. For example, the
# primary group will always be included in the 'groups' property. This is
# bad if we're explicitly managing the 'groups' property under inclusive
# membership, and we are not specifying the primary group in the 'groups'
# property value.
#
# Setting the groups property here a second time will ensure that our user is
# created and in the right state. Note that this is an idempotent operation,
# so if AixObject's create method already set it to the right value, then this
# will noop.
if (groups = @resource.should(:groups))
self.groups = groups
end
if (password = @resource.should(:password))
self.password = password
end
end
# Lists all instances of the given object, taking in an optional set
# of ia_module arguments. Returns an array of hashes, each hash
# having the schema
# {
# :name => <object_name>
# :home => <object_home>
# }
def list_all_homes(ia_module_args = [])
cmd = [command(:list), '-c', *ia_module_args, '-a', 'home', 'ALL']
parse_aix_objects(execute(cmd)).to_a.map do |object|
name = object[:name]
home = object[:attributes].delete(:home)
{ name: name, home: home }
end
rescue => e
Puppet.debug("Could not list home of all users: #{e.message}")
{}
end
# Deletes this instance resource
def delete
homedir = home
super
return unless @resource.managehome?
if !Puppet::Util.absolute_path?(homedir) || File.realpath(homedir) == '/' || Puppet::FileSystem.symlink?(homedir)
Puppet.debug("Can not remove home directory '#{homedir}' of user '#{@resource[:name]}'. Please make sure the path is not relative, symlink or '/'.")
return
end
affected_home = list_all_homes.find { |info| info[:home].start_with?(File.realpath(homedir)) }
if affected_home
Puppet.debug("Can not remove home directory '#{homedir}' of user '#{@resource[:name]}' as it would remove the home directory '#{affected_home[:home]}' of user '#{affected_home[:name]}' also.")
return
end
FileUtils.remove_entry_secure(homedir, true)
end
def deletecmd
[self.class.command(:delete), '-p'] + ia_module_args + [@resource[:name]]
end
# UNSUPPORTED
# - **profile_membership**
# Whether specified roles should be treated as the only roles
# of which the user is a member or whether they should merely
# be treated as the minimum membership list. Valid values are
# `inclusive`, `minimum`.
# UNSUPPORTED
# - **profiles**
# The profiles the user has. Multiple profiles should be
# specified as an array. Requires features manages_solaris_rbac.
# UNSUPPORTED
# - **project**
# The name of the project associated with a user Requires features
# manages_solaris_rbac.
# UNSUPPORTED
# - **role_membership**
# Whether specified roles should be treated as the only roles
# of which the user is a member or whether they should merely
# be treated as the minimum membership list. Valid values are
# `inclusive`, `minimum`.
# UNSUPPORTED
# - **roles**
# The roles the user has. Multiple roles should be
# specified as an array. Requires features manages_roles.
# UNSUPPORTED
# - **key_membership**
# Whether specified key value pairs should be treated as the only
# attributes
# of the user or whether they should merely
# be treated as the minimum list. Valid values are `inclusive`,
# `minimum`.
# UNSUPPORTED
# - **keys**
# Specify user attributes in an array of keyvalue pairs Requires features
# manages_solaris_rbac.
# UNSUPPORTED
# - **allowdupe**
# Whether to allow duplicate UIDs. Valid values are `true`, `false`.
# UNSUPPORTED
# - **auths**
# The auths the user has. Multiple auths should be
# specified as an array. Requires features manages_solaris_rbac.
# UNSUPPORTED
# - **auth_membership**
# Whether specified auths should be treated as the only auths
# of which the user is a member or whether they should merely
# be treated as the minimum membership list. Valid values are
# `inclusive`, `minimum`.
# UNSUPPORTED
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/user/directoryservice.rb | lib/puppet/provider/user/directoryservice.rb | # frozen_string_literal: true
require_relative '../../../puppet'
require_relative '../../../puppet/util/plist' if Puppet.features.cfpropertylist?
require 'base64'
Puppet::Type.type(:user).provide :directoryservice do
desc "User management on OS X."
## ##
## Provider Settings ##
## ##
# Provider command declarations
commands :uuidgen => '/usr/bin/uuidgen'
commands :dsimport => '/usr/bin/dsimport'
commands :dscl => '/usr/bin/dscl'
commands :dscacheutil => '/usr/bin/dscacheutil'
# Provider confines and defaults
confine 'os.name' => :darwin
confine :feature => :cfpropertylist
defaultfor 'os.name' => :darwin
# Need this to create getter/setter methods automagically
# This command creates methods that return @property_hash[:value]
mk_resource_methods
# JJM: OS X can manage passwords.
has_feature :manages_passwords
# 10.8 Passwords use a PBKDF2 salt value
has_features :manages_password_salt
# provider can set the user's shell
has_feature :manages_shell
## ##
## Class Methods ##
## ##
# This method exists to map the dscl values to the correct Puppet
# properties. This stays relatively consistent, but who knows what
# Apple will do next year...
def self.ds_to_ns_attribute_map
{
'RecordName' => :name,
'PrimaryGroupID' => :gid,
'NFSHomeDirectory' => :home,
'UserShell' => :shell,
'UniqueID' => :uid,
'RealName' => :comment,
'Password' => :password,
'GeneratedUID' => :guid,
'IPAddress' => :ip_address,
'ENetAddress' => :en_address,
'GroupMembership' => :members,
}
end
def self.ns_to_ds_attribute_map
@ns_to_ds_attribute_map ||= ds_to_ns_attribute_map.invert
end
# Prefetching is necessary to use @property_hash inside any setter methods.
# self.prefetch uses self.instances to gather an array of user instances
# on the system, and then populates the @property_hash instance variable
# with attribute data for the specific instance in question (i.e. it
# gathers the 'is' values of the resource into the @property_hash instance
# variable so you don't have to read from the system every time you need
# to gather the 'is' values for a resource. The downside here is that
# populating this instance variable for every resource on the system
# takes time and front-loads your Puppet run.
def self.prefetch(resources)
instances.each do |prov|
resource = resources[prov.name]
if resource
resource.provider = prov
end
end
end
# This method assembles an array of provider instances containing
# information about every instance of the user type on the system (i.e.
# every user and its attributes). The `puppet resource` command relies
# on self.instances to gather an array of user instances in order to
# display its output.
def self.instances
get_all_users.collect do |user|
new(generate_attribute_hash(user))
end
end
# Return an array of hashes containing information about every user on
# the system.
def self.get_all_users
Puppet::Util::Plist.parse_plist(dscl('-plist', '.', 'readall', '/Users'))
end
# This method accepts an individual user plist, passed as a hash, and
# strips the dsAttrTypeStandard: prefix that dscl adds for each key.
# An attribute hash is assembled and returned from the properties
# supported by the user type.
def self.generate_attribute_hash(input_hash)
attribute_hash = {}
input_hash.each_key do |key|
ds_attribute = key.sub("dsAttrTypeStandard:", "")
next unless ds_to_ns_attribute_map.keys.include?(ds_attribute)
ds_value = input_hash[key]
case ds_to_ns_attribute_map[ds_attribute]
when :gid, :uid
# OS X stores objects like uid/gid as strings.
# Try casting to an integer for these cases to be
# consistent with the other providers and the group type
# validation
begin
ds_value = Integer(ds_value[0])
rescue ArgumentError
ds_value = ds_value[0]
end
else ds_value = ds_value[0]
end
attribute_hash[ds_to_ns_attribute_map[ds_attribute]] = ds_value
end
attribute_hash[:ensure] = :present
attribute_hash[:provider] = :directoryservice
attribute_hash[:shadowhashdata] = input_hash['dsAttrTypeNative:ShadowHashData']
##############
# Get Groups #
##############
groups_array = []
get_list_of_groups.each do |group|
if group["dsAttrTypeStandard:GroupMembership"] and group["dsAttrTypeStandard:GroupMembership"].include?(attribute_hash[:name])
groups_array << group["dsAttrTypeStandard:RecordName"][0]
end
if group["dsAttrTypeStandard:GroupMembers"] and group["dsAttrTypeStandard:GroupMembers"].include?(attribute_hash[:guid])
groups_array << group["dsAttrTypeStandard:RecordName"][0]
end
end
attribute_hash[:groups] = groups_array.uniq.sort.join(',')
################################
# Get Password/Salt/Iterations #
################################
if attribute_hash[:shadowhashdata].nil? or attribute_hash[:shadowhashdata].empty?
attribute_hash[:password] = '*'
else
embedded_binary_plist = get_embedded_binary_plist(attribute_hash[:shadowhashdata])
if embedded_binary_plist['SALTED-SHA512-PBKDF2']
attribute_hash[:password] = get_salted_sha512_pbkdf2('entropy', embedded_binary_plist, attribute_hash[:name])
attribute_hash[:salt] = get_salted_sha512_pbkdf2('salt', embedded_binary_plist, attribute_hash[:name])
attribute_hash[:iterations] = get_salted_sha512_pbkdf2('iterations', embedded_binary_plist, attribute_hash[:name])
elsif embedded_binary_plist['SALTED-SHA512']
attribute_hash[:password] = get_salted_sha512(embedded_binary_plist)
end
end
attribute_hash
end
def self.get_os_version
# rubocop:disable Naming/MemoizedInstanceVariableName
@os_version ||= Puppet.runtime[:facter].value('os.macosx.version.major')
# rubocop:enable Naming/MemoizedInstanceVariableName
end
# Use dscl to retrieve an array of hashes containing attributes about all
# of the local groups on the machine.
def self.get_list_of_groups
# rubocop:disable Naming/MemoizedInstanceVariableName
@groups ||= Puppet::Util::Plist.parse_plist(dscl('-plist', '.', 'readall', '/Groups'))
# rubocop:enable Naming/MemoizedInstanceVariableName
end
# Perform a dscl lookup at the path specified for the specific keyname
# value. The value returned is the first item within the array returned
# from dscl
def self.get_attribute_from_dscl(path, username, keyname)
Puppet::Util::Plist.parse_plist(dscl('-plist', '.', 'read', "/#{path}/#{username}", keyname))
end
# The plist embedded in the ShadowHashData key is a binary plist. The
# plist library doesn't read binary plists, so we need to
# extract the binary plist, convert it to XML, and return it.
def self.get_embedded_binary_plist(shadow_hash_data)
embedded_binary_plist = Array(shadow_hash_data[0].delete(' ')).pack('H*')
convert_binary_to_hash(embedded_binary_plist)
end
# This method will accept a hash and convert it to a binary plist (string value).
def self.convert_hash_to_binary(plist_data)
Puppet.debug('Converting plist hash to binary')
Puppet::Util::Plist.dump_plist(plist_data, :binary)
end
# This method will accept a binary plist (as a string) and convert it to a hash.
def self.convert_binary_to_hash(plist_data)
Puppet.debug('Converting binary plist to hash')
Puppet::Util::Plist.parse_plist(plist_data)
end
# The salted-SHA512 password hash in 10.7 is stored in the 'SALTED-SHA512'
# key as binary data. That data is extracted and converted to a hex string.
def self.get_salted_sha512(embedded_binary_plist)
embedded_binary_plist['SALTED-SHA512'].unpack1("H*")
end
# This method reads the passed embedded_binary_plist hash and returns values
# according to which field is passed. Arguments passed are the hash
# containing the value read from the 'ShadowHashData' key in the User's
# plist, and the field to be read (one of 'entropy', 'salt', or 'iterations')
def self.get_salted_sha512_pbkdf2(field, embedded_binary_plist, user_name = "")
case field
when 'salt', 'entropy'
value = embedded_binary_plist['SALTED-SHA512-PBKDF2'][field]
if value.nil?
raise Puppet::Error, "Invalid #{field} given for user #{user_name}"
end
value.unpack1('H*')
when 'iterations'
Integer(embedded_binary_plist['SALTED-SHA512-PBKDF2'][field])
else
raise Puppet::Error, "Puppet has tried to read an incorrect value from the user #{user_name} in the SALTED-SHA512-PBKDF2 hash. Acceptable fields are 'salt', 'entropy', or 'iterations'."
end
end
# In versions 10.5 and 10.6 of OS X, the password hash is stored in a file
# in the /var/db/shadow/hash directory that matches the GUID of the user.
def self.get_sha1(guid)
password_hash = nil
password_hash_file = "#{password_hash_dir}/#{guid}"
if Puppet::FileSystem.exist?(password_hash_file) and File.file?(password_hash_file)
raise Puppet::Error, "Could not read password hash file at #{password_hash_file}" unless File.readable?(password_hash_file)
f = File.new(password_hash_file)
password_hash = f.read
f.close
end
password_hash
end
## ##
## Ensurable Methods ##
## ##
def exists?
begin
dscl '.', 'read', "/Users/#{@resource.name}"
rescue Puppet::ExecutionFailure => e
Puppet.debug("User was not found, dscl returned: #{e.inspect}")
return false
end
true
end
# This method is called if ensure => present is passed and the exists?
# method returns false. Dscl will directly set most values, but the
# setter methods will be used for any exceptions.
def create
create_new_user(@resource.name)
# Retrieve the user's GUID
@guid = self.class.get_attribute_from_dscl('Users', @resource.name, 'GeneratedUID')['dsAttrTypeStandard:GeneratedUID'][0]
# Get an array of valid User type properties
valid_properties = Puppet::Type.type('User').validproperties
# Iterate through valid User type properties
valid_properties.each do |attribute|
next if attribute == :ensure
value = @resource.should(attribute)
# Value defaults
if value.nil?
value = case attribute
when :gid
'20'
when :uid
next_system_id
when :comment
@resource.name
when :shell
'/bin/bash'
when :home
"/Users/#{@resource.name}"
else
nil
end
end
# Ensure group names are converted to integers.
value = Puppet::Util.gid(value) if attribute == :gid
## Set values ##
# For the :password and :groups properties, call the setter methods
# to enforce those values. For everything else, use dscl with the
# ns_to_ds_attribute_map to set the appropriate values.
next unless value != "" and !value.nil?
case attribute
when :password
self.password = value
when :iterations
self.iterations = value
when :salt
self.salt = value
when :groups
value.split(',').each do |group|
merge_attribute_with_dscl('Groups', group, 'GroupMembership', @resource.name)
merge_attribute_with_dscl('Groups', group, 'GroupMembers', @guid)
end
else
create_attribute_with_dscl('Users', @resource.name, self.class.ns_to_ds_attribute_map[attribute], value)
end
end
end
# This method is called when ensure => absent has been set.
# Deleting a user is handled by dscl
def delete
dscl '.', '-delete', "/Users/#{@resource.name}"
end
## ##
## Getter/Setter Methods ##
## ##
# In the setter method we're only going to take action on groups for which
# the user is not currently a member.
def groups=(value)
guid = self.class.get_attribute_from_dscl('Users', @resource.name, 'GeneratedUID')['dsAttrTypeStandard:GeneratedUID'][0]
groups_to_add = value.split(',') - groups.split(',')
groups_to_add.each do |group|
merge_attribute_with_dscl('Groups', group, 'GroupMembership', @resource.name)
merge_attribute_with_dscl('Groups', group, 'GroupMembers', guid)
end
end
# If you thought GETTING a password was bad, try SETTING it. This method
# makes me want to cry. A thousand tears...
#
# I've been unsuccessful in tracking down a way to set the password for
# a user using dscl that DOESN'T require passing it as plaintext. We were
# also unable to get dsimport to work like this. Due to these downfalls,
# the sanest method requires opening the user's plist, dropping in the
# password hash, and serializing it back to disk. The problems with THIS
# method revolve around dscl. Any time you directly modify a user's plist,
# you need to flush the cache that dscl maintains.
def password=(value)
if self.class.get_os_version == '10.7'
if value.length != 136
raise Puppet::Error, "OS X 10.7 requires a Salted SHA512 hash password of 136 characters. Please check your password and try again."
end
else
if value.length != 256
raise Puppet::Error, "OS X versions > 10.7 require a Salted SHA512 PBKDF2 password hash of 256 characters. Please check your password and try again."
end
assert_full_pbkdf2_password
end
# Methods around setting the password on OS X are the ONLY methods that
# cannot use dscl (because the only way to set it via dscl is by passing
# a plaintext password - which is bad). Because of this, we have to change
# the user's plist directly. DSCL has its own caching mechanism, which
# means that every time we call dscl in this provider we're not directly
# changing values on disk (instead, those calls are cached and written
# to disk according to Apple's prioritization algorithms). When Puppet
# needs to set the password property on OS X > 10.6, the provider has to
# tell dscl to write its cache to disk before modifying the user's
# plist. The 'dscacheutil -flushcache' command does this. Another issue
# is how fast Puppet makes calls to dscl and how long it takes dscl to
# enter those calls into its cache. We have to sleep for 2 seconds before
# flushing the dscl cache to allow all dscl calls to get INTO the cache
# first. This could be made faster (and avoid a sleep call) by finding
# a way to enter calls into the dscl cache faster. A sleep time of 1
# second would intermittently require a second Puppet run to set
# properties, so 2 seconds seems to be the minimum working value.
sleep 2
flush_dscl_cache
write_password_to_users_plist(value)
# Since we just modified the user's plist, we need to flush the ds cache
# again so dscl can pick up on the changes we made.
flush_dscl_cache
end
# The iterations and salt properties, like the password property, can only
# be modified by directly changing the user's plist. Because of this fact,
# we have to treat the ds cache just like you would in the password=
# method.
def iterations=(value)
if Puppet::Util::Package.versioncmp(self.class.get_os_version, '10.7') > 0
assert_full_pbkdf2_password
sleep 3
flush_dscl_cache
users_plist = get_users_plist(@resource.name)
shadow_hash_data = get_shadow_hash_data(users_plist)
set_salted_pbkdf2(users_plist, shadow_hash_data, 'iterations', value)
flush_dscl_cache
end
end
# The iterations and salt properties, like the password property, can only
# be modified by directly changing the user's plist. Because of this fact,
# we have to treat the ds cache just like you would in the password=
# method.
def salt=(value)
if Puppet::Util::Package.versioncmp(self.class.get_os_version, '10.15') >= 0
if value.length != 64
self.fail "macOS versions 10.15 and higher require the salt to be 32-bytes. Since Puppet's user resource requires the value to be hex encoded, the length of the salt's string must be 64. Please check your salt and try again."
end
end
if Puppet::Util::Package.versioncmp(self.class.get_os_version, '10.7') > 0
assert_full_pbkdf2_password
sleep 3
flush_dscl_cache
users_plist = get_users_plist(@resource.name)
shadow_hash_data = get_shadow_hash_data(users_plist)
set_salted_pbkdf2(users_plist, shadow_hash_data, 'salt', value)
flush_dscl_cache
end
end
#####
# Dynamically create setter methods for dscl properties
#####
#
# Setter methods are only called when a resource currently has a value for
# that property and it needs changed (true here since all of these values
# have a default that is set in the create method). We don't want to merge
# in additional values if an incorrect value is set, we want to CHANGE it.
# When using the -change argument in dscl, the old value needs to be passed
# first (followed by the new value). Because of this, we get the current
# value from the @property_hash variable and then use the value passed as
# the new value. Because we're prefetching instances of the provider, it's
# possible that the value determined at the start of the run may be stale
# (i.e. someone changed the value by hand during a Puppet run) - if that's
# the case we rescue the error from dscl and alert the user.
#
# In the event that the user doesn't HAVE a value for the attribute, the
# provider should use the -create option with dscl to add the attribute value
# for the user record
%w[home uid gid comment shell].each do |setter_method|
define_method("#{setter_method}=") do |value|
if @property_hash[setter_method.intern]
if %w[home uid].include?(setter_method)
raise Puppet::Error, "OS X version #{self.class.get_os_version} does not allow changing #{setter_method} using puppet"
end
begin
dscl '.', '-change', "/Users/#{resource.name}", self.class.ns_to_ds_attribute_map[setter_method.intern], @property_hash[setter_method.intern], value
rescue Puppet::ExecutionFailure => e
raise Puppet::Error, "Cannot set the #{setter_method} value of '#{value}' for user " \
"#{@resource.name} due to the following error: #{e.inspect}", e.backtrace
end
else
begin
dscl '.', '-create', "/Users/#{resource.name}", self.class.ns_to_ds_attribute_map[setter_method.intern], value
rescue Puppet::ExecutionFailure => e
raise Puppet::Error, "Cannot set the #{setter_method} value of '#{value}' for user " \
"#{@resource.name} due to the following error: #{e.inspect}", e.backtrace
end
end
end
end
## ##
## Helper Methods ##
## ##
def assert_full_pbkdf2_password
missing = [:password, :salt, :iterations].select { |parameter| @resource[parameter].nil? }
unless missing.empty?
raise Puppet::Error, "OS X versions > 10\.7 use PBKDF2 password hashes, which requires all three of salt, iterations, and password hash. This resource is missing: #{missing.join(', ')}."
end
end
def users_plist_dir
'/var/db/dslocal/nodes/Default/users'
end
def self.password_hash_dir
'/var/db/shadow/hash'
end
# This method will create a given value using dscl
def create_attribute_with_dscl(path, username, keyname, value)
set_attribute_with_dscl('-create', path, username, keyname, value)
end
# This method will merge in a given value using dscl
def merge_attribute_with_dscl(path, username, keyname, value)
set_attribute_with_dscl('-merge', path, username, keyname, value)
end
def set_attribute_with_dscl(dscl_command, path, username, keyname, value)
dscl '.', dscl_command, "/#{path}/#{username}", keyname, value
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error, "Could not set the dscl #{keyname} key with value: #{value} - #{detail.inspect}", detail.backtrace
end
# Create the new user with dscl
def create_new_user(username)
dscl '.', '-create', "/Users/#{username}"
end
# Get the next available uid on the system by getting a list of user ids,
# sorting them, grabbing the last one, and adding a 1. Scientific stuff here.
def next_system_id(min_id = 20)
dscl_output = dscl '.', '-list', '/Users', 'uid'
# We're ok with throwing away negative uids here. Also, remove nil values.
user_ids = dscl_output.split.compact.collect { |l| l.to_i if l =~ /^\d+$/ }
ids = user_ids.compact!.sort_by!(&:to_f)
# We're just looking for an unused id in our sorted array.
ids.each_index do |i|
next_id = ids[i] + 1
return next_id if ids[i + 1] != next_id and next_id >= min_id
end
end
# This method is only called on version 10.7 or greater. On 10.7 machines,
# passwords are set using a salted-SHA512 hash, and on 10.8 machines,
# passwords are set using PBKDF2. It's possible to have users on 10.8
# who have upgraded from 10.7 and thus have a salted-SHA512 password hash.
# If we encounter this, do what 10.8 does - remove that key and give them
# a 10.8-style PBKDF2 password.
def write_password_to_users_plist(value)
users_plist = get_users_plist(@resource.name)
shadow_hash_data = get_shadow_hash_data(users_plist)
if self.class.get_os_version == '10.7'
set_salted_sha512(users_plist, shadow_hash_data, value)
else
# It's possible that a user could exist on the system and NOT have
# a ShadowHashData key (especially if the system was upgraded from 10.6).
# In this case, a conditional check is needed to determine if the
# shadow_hash_data variable is a Hash (it would be false if the key
# didn't exist for this user on the system). If the shadow_hash_data
# variable IS a Hash and contains the 'SALTED-SHA512' key (indicating an
# older 10.7-style password hash), it will be deleted and a newer
# 10.8-style (PBKDF2) password hash will be generated.
if shadow_hash_data.instance_of?(Hash) && shadow_hash_data.has_key?('SALTED-SHA512')
shadow_hash_data.delete('SALTED-SHA512')
end
# Starting with macOS 11 Big Sur, the AuthenticationAuthority field
# could be missing entirely and without it the managed user cannot log in
if needs_sha512_pbkdf2_authentication_authority_to_be_added?(users_plist)
Puppet.debug("Adding 'SALTED-SHA512-PBKDF2' AuthenticationAuthority key for ShadowHash to user '#{@resource.name}'")
merge_attribute_with_dscl('Users', @resource.name, 'AuthenticationAuthority', ERB::Util.html_escape(SHA512_PBKDF2_AUTHENTICATION_AUTHORITY))
end
set_salted_pbkdf2(users_plist, shadow_hash_data, 'entropy', value)
end
end
def flush_dscl_cache
dscacheutil '-flushcache'
end
def get_users_plist(username)
# This method will retrieve the data stored in a user's plist and
# return it as a native Ruby hash.
path = "#{users_plist_dir}/#{username}.plist"
Puppet::Util::Plist.read_plist_file(path)
end
# This method will return the binary plist that's embedded in the
# ShadowHashData key of a user's plist, or false if it doesn't exist.
def get_shadow_hash_data(users_plist)
if users_plist['ShadowHashData']
password_hash_plist = users_plist['ShadowHashData'][0]
self.class.convert_binary_to_hash(password_hash_plist)
else
false
end
end
# This method will check if authentication_authority key of a user's plist
# needs SALTED_SHA512_PBKDF2 to be added. This is a valid case for macOS 11 (Big Sur)
# where users created with `dscl` started to have this field missing
def needs_sha512_pbkdf2_authentication_authority_to_be_added?(users_plist)
authority = users_plist['authentication_authority']
return false if Puppet::Util::Package.versioncmp(self.class.get_os_version, '11.0.0') < 0 && authority && authority.include?(SHA512_PBKDF2_AUTHENTICATION_AUTHORITY)
Puppet.debug("User '#{@resource.name}' is missing the 'SALTED-SHA512-PBKDF2' AuthenticationAuthority key for ShadowHash")
true
end
# This method will embed the binary plist data comprising the user's
# password hash (and Salt/Iterations value if the OS is 10.8 or greater)
# into the ShadowHashData key of the user's plist.
def set_shadow_hash_data(users_plist, binary_plist)
binary_plist = Puppet::Util::Plist.string_to_blob(binary_plist)
if users_plist.has_key?('ShadowHashData')
users_plist['ShadowHashData'][0] = binary_plist
else
users_plist['ShadowHashData'] = [binary_plist]
end
write_and_import_shadow_hash_data(users_plist['ShadowHashData'].first)
end
# This method writes the ShadowHashData plist in a temporary file,
# then imports it using dsimport. macOS versions 10.15 and newer do
# not support directly managing binary plists, so we have to use an
# intermediary.
# dsimport is an archaic utilitary with hard-to-find documentation
#
# See http://web.archive.org/web/20090106120111/http://support.apple.com/kb/TA21305?viewlocale=en_US
# for information regarding the dsimport syntax
def write_and_import_shadow_hash_data(data_plist)
Tempfile.create("dsimport_#{@resource.name}", :encoding => Encoding::ASCII) do |dsimport_file|
dsimport_file.write <<~DSIMPORT
0x0A 0x5C 0x3A 0x2C dsRecTypeStandard:Users 2 dsAttrTypeStandard:RecordName base64:dsAttrTypeNative:ShadowHashData
#{@resource.name}:#{Base64.strict_encode64(data_plist)}
DSIMPORT
dsimport_file.flush
# Delete the user's existing ShadowHashData, since dsimport appends, not replaces
dscl('.', 'delete', "/Users/#{@resource.name}", 'ShadowHashData')
dsimport(dsimport_file.path, '/Local/Default', 'M')
end
end
# This method accepts an argument of a hex password hash, and base64
# decodes it into a format that OS X 10.7 and 10.8 will store
# in the user's plist.
def base64_decode_string(value)
Base64.decode64([[value].pack("H*")].pack("m").strip)
end
# Puppet requires a salted-sha512 password hash for 10.7 users to be passed
# in Hex, but the embedded plist stores that value as a Base64 encoded
# string. This method converts the string and calls the
# set_shadow_hash_data method to serialize and write the plist to disk.
def set_salted_sha512(users_plist, shadow_hash_data, value)
unless shadow_hash_data
shadow_hash_data = Hash.new
shadow_hash_data['SALTED-SHA512'] = ''.dup
end
shadow_hash_data['SALTED-SHA512'] = base64_decode_string(value)
binary_plist = self.class.convert_hash_to_binary(shadow_hash_data)
set_shadow_hash_data(users_plist, binary_plist)
end
# This method accepts a passed value and one of three fields: 'salt',
# 'entropy', or 'iterations'. These fields correspond with the fields
# utilized in a PBKDF2 password hashing system
# (see https://en.wikipedia.org/wiki/PBKDF2 ) where 'entropy' is the
# password hash, 'salt' is the password hash salt value, and 'iterations'
# is an integer recommended to be > 10,000. The remaining arguments are
# the user's plist itself, and the shadow_hash_data hash containing the
# existing PBKDF2 values.
def set_salted_pbkdf2(users_plist, shadow_hash_data, field, value)
shadow_hash_data ||= Hash.new
shadow_hash_data['SALTED-SHA512-PBKDF2'] = Hash.new unless shadow_hash_data['SALTED-SHA512-PBKDF2']
case field
when 'salt', 'entropy'
shadow_hash_data['SALTED-SHA512-PBKDF2'][field] = Puppet::Util::Plist.string_to_blob(base64_decode_string(value))
when 'iterations'
shadow_hash_data['SALTED-SHA512-PBKDF2'][field] = Integer(value)
else
raise Puppet::Error "Puppet has tried to set an incorrect field for the 'SALTED-SHA512-PBKDF2' hash. Acceptable fields are 'salt', 'entropy', or 'iterations'."
end
# on 10.8, this field *must* contain 8 stars, or authentication will
# fail.
users_plist['passwd'] = ('*' * 8)
# Convert shadow_hash_data to a binary plist, and call the
# set_shadow_hash_data method to serialize and write the data
# back to the user's plist.
binary_plist = self.class.convert_hash_to_binary(shadow_hash_data)
set_shadow_hash_data(users_plist, binary_plist)
end
private
SHA512_PBKDF2_AUTHENTICATION_AUTHORITY = ';ShadowHash;HASHLIST:<SALTED-SHA512-PBKDF2,SRP-RFC5054-4096-SHA512-PBKDF2>'
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
OpenVoxProject/openvox | https://github.com/OpenVoxProject/openvox/blob/9336df16a11679d701a2bd9ebe1308d4fb669f57/lib/puppet/provider/user/openbsd.rb | lib/puppet/provider/user/openbsd.rb | # frozen_string_literal: true
require_relative '../../../puppet/error'
Puppet::Type.type(:user).provide :openbsd, :parent => :useradd do
desc "User management via `useradd` and its ilk for OpenBSD. Note that you
will need to install Ruby's shadow password library (package known as
`ruby-shadow`) if you wish to manage user passwords."
commands :add => "useradd",
:delete => "userdel",
:modify => "usermod",
:password => "passwd"
defaultfor 'os.name' => :openbsd
confine 'os.name' => :openbsd
options :home, :flag => "-d", :method => :dir
options :comment, :method => :gecos
options :groups, :flag => "-G"
options :password, :method => :sp_pwdp
options :loginclass, :flag => '-L', :method => :sp_loginclass
options :expiry, :method => :sp_expire,
:munge => proc { |value|
if value == :absent
''
else
# OpenBSD uses a format like "january 1 1970"
Time.parse(value).strftime('%B %d %Y')
end
},
:unmunge => proc { |value|
if value == -1
:absent
else
# Expiry is days after 1970-01-01
(Date.new(1970, 1, 1) + value).strftime('%Y-%m-%d')
end
}
[:expiry, :password, :loginclass].each do |shadow_property|
define_method(shadow_property) do
if Puppet.features.libshadow?
ent = Shadow::Passwd.getspnam(@resource.name)
if ent
method = self.class.option(shadow_property, :method)
# ruby-shadow may not be new enough (< 2.4.1) and therefore lack the
# sp_loginclass field.
begin
return unmunge(shadow_property, ent.send(method))
rescue
# TRANSLATORS 'ruby-shadow' is a Ruby gem library
Puppet.warning _("ruby-shadow doesn't support %{method}") % { method: method }
end
end
end
:absent
end
end
has_features :manages_homedir, :manages_expiry, :system_users
has_features :manages_shell
if Puppet.features.libshadow?
has_features :manages_passwords, :manages_loginclass
end
def loginclass=(value)
set("loginclass", value)
end
def modifycmd(param, value)
cmd = super
if param == :groups
idx = cmd.index('-G')
cmd[idx] = '-S'
end
cmd
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/provider/user/pw.rb | lib/puppet/provider/user/pw.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/nameservice/pw'
require 'open3'
Puppet::Type.type(:user).provide :pw, :parent => Puppet::Provider::NameService::PW do
desc "User management via `pw` on FreeBSD and DragonFly BSD."
commands :pw => "pw"
has_features :manages_homedir, :allows_duplicates, :manages_passwords, :manages_expiry, :manages_shell
defaultfor 'os.name' => [:freebsd, :dragonfly]
confine 'os.name' => [:freebsd, :dragonfly]
options :home, :flag => "-d", :method => :dir
options :comment, :method => :gecos
options :groups, :flag => "-G"
options :expiry, :method => :expire, :munge => proc { |value|
value = '0000-00-00' if value == :absent
value.split("-").reverse.join("-")
}
verify :gid, "GID must be an integer" do |value|
value.is_a? Integer
end
verify :groups, "Groups must be comma-separated" do |value|
value !~ /\s/
end
def addcmd
cmd = [command(:pw), "useradd", @resource[:name]]
@resource.class.validproperties.each do |property|
next if property == :ensure or property == :password
value = @resource.should(property)
if value and value != ""
cmd << flag(property) << munge(property, value)
end
end
cmd << "-o" if @resource.allowdupe?
cmd << "-m" if @resource.managehome?
cmd
end
def modifycmd(param, value)
if param == :expiry
# FreeBSD uses DD-MM-YYYY rather than YYYY-MM-DD
value = value.split("-").reverse.join("-")
end
cmd = super(param, value)
cmd << "-m" if @resource.managehome?
cmd
end
def deletecmd
cmd = super
cmd << "-r" if @resource.managehome?
cmd
end
def create
super
# Set the password after create if given
self.password = @resource[:password] if @resource[:password]
end
# use pw to update password hash
def password=(cryptopw)
Puppet.debug "change password for user '#{@resource[:name]}' method called with hash [redacted]"
stdin, _, _ = Open3.popen3("pw user mod #{@resource[:name]} -H 0")
stdin.puts(cryptopw)
stdin.close
Puppet.debug "finished password for user '#{@resource[:name]}' method called with hash [redacted]"
end
# get password from /etc/master.passwd
def password
Puppet.debug "checking password for user '#{@resource[:name]}' method called"
current_passline = `getent passwd #{@resource[:name]}`
current_password = current_passline.chomp.split(':')[1] if current_passline
Puppet.debug "finished password for user '#{@resource[:name]}' method called : [redacted]"
current_password
end
def has_sensitive_data?(property = nil)
# Check for sensitive values?
properties = property ? [property] : Puppet::Type.type(:user).validproperties
properties.any? do |prop|
p = @resource.parameter(prop)
p && p.respond_to?(:is_sensitive) && p.is_sensitive
end
end
# Get expiry from system and convert to Puppet-style date
def expiry
expiry = get(:expiry)
expiry = :absent if expiry == 0
if expiry != :absent
t = Time.at(expiry)
expiry = "%4d-%02d-%02d" % [t.year, t.month, t.mday]
end
expiry
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/provider/user/user_role_add.rb | lib/puppet/provider/user/user_role_add.rb | # frozen_string_literal: true
require_relative '../../../puppet/util'
require_relative '../../../puppet/util/user_attr'
require 'date'
Puppet::Type.type(:user).provide :user_role_add, :parent => :useradd, :source => :useradd do
desc "User and role management on Solaris, via `useradd` and `roleadd`."
defaultfor 'os.family' => :solaris
commands :add => "useradd", :delete => "userdel", :modify => "usermod", :password => "passwd", :role_add => "roleadd", :role_delete => "roledel", :role_modify => "rolemod"
options :home, :flag => "-d", :method => :dir
options :comment, :method => :gecos
options :groups, :flag => "-G"
options :shell, :flag => "-s"
options :roles, :flag => "-R"
options :auths, :flag => "-A"
options :profiles, :flag => "-P"
options :password_min_age, :flag => "-n"
options :password_max_age, :flag => "-x"
options :password_warn_days, :flag => "-w"
verify :gid, "GID must be an integer" do |value|
value.is_a? Integer
end
verify :groups, "Groups must be comma-separated" do |value|
value !~ /\s/
end
def shell=(value)
check_valid_shell
set("shell", value)
end
has_features :manages_homedir, :allows_duplicates, :manages_solaris_rbac, :manages_roles, :manages_passwords, :manages_password_age, :manages_shell
def check_valid_shell
unless File.exist?(@resource.should(:shell))
raise(Puppet::Error, "Shell #{@resource.should(:shell)} must exist")
end
unless File.executable?(@resource.should(:shell).to_s)
raise(Puppet::Error, "Shell #{@resource.should(:shell)} must be executable")
end
end
# must override this to hand the keyvalue pairs
def add_properties
cmd = []
Puppet::Type.type(:user).validproperties.each do |property|
# skip the password because we can't create it with the solaris useradd
next if [:ensure, :password, :password_min_age, :password_max_age, :password_warn_days].include?(property)
# 1680 Now you can set the hashed passwords on solaris:lib/puppet/provider/user/user_role_add.rb
# the value needs to be quoted, mostly because -c might
# have spaces in it
value = @resource.should(property)
if value && value != ""
if property == :keys
cmd += build_keys_cmd(value)
else
cmd << flag(property) << value
end
end
end
cmd
end
def user_attributes
@user_attributes ||= UserAttr.get_attributes_by_name(@resource[:name])
end
def flush
@user_attributes = nil
end
def command(cmd)
cmd = "role_#{cmd}".intern if is_role? or (!exists? and @resource[:ensure] == :role)
super(cmd)
end
def is_role?
user_attributes and user_attributes[:type] == "role"
end
def run(cmd, msg)
execute(cmd)
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error, "Could not #{msg} #{@resource.class.name} #{@resource.name}: #{detail}", detail.backtrace
end
def transition(type)
cmd = [command(:modify)]
cmd << "-K" << "type=#{type}"
cmd += add_properties
cmd << @resource[:name]
end
def create
if is_role?
run(transition("normal"), "transition role to")
else
run(addcmd, "create")
cmd = passcmd
if cmd
run(cmd, "change password policy for")
end
end
# added to handle case when password is specified
self.password = @resource[:password] if @resource[:password]
end
def destroy
run(deletecmd, "delete " + (is_role? ? "role" : "user"))
end
def create_role
if exists? and !is_role?
run(transition("role"), "transition user to")
else
run(addcmd, "create role")
end
end
def roles
user_attributes[:roles] if user_attributes
end
def auths
user_attributes[:auths] if user_attributes
end
def profiles
user_attributes[:profiles] if user_attributes
end
def project
user_attributes[:project] if user_attributes
end
def managed_attributes
[:name, :type, :roles, :auths, :profiles, :project]
end
def remove_managed_attributes
managed = managed_attributes
user_attributes.select { |k, _v| !managed.include?(k) }.each_with_object({}) { |array, hash| hash[array[0]] = array[1]; }
end
def keys
if user_attributes
# we have to get rid of all the keys we are managing another way
remove_managed_attributes
end
end
def build_keys_cmd(keys_hash)
cmd = []
keys_hash.each do |k, v|
cmd << "-K" << "#{k}=#{v}"
end
cmd
end
def keys=(keys_hash)
run([command(:modify)] + build_keys_cmd(keys_hash) << @resource[:name], "modify attribute key pairs")
end
# This helper makes it possible to test this on stub data without having to
# do too many crazy things!
def target_file_path
"/etc/shadow"
end
private :target_file_path
# Read in /etc/shadow, find the line for this user (skipping comments, because who knows) and return it
# No abstraction, all esoteric knowledge of file formats, yay
def shadow_entry
return @shadow_entry if defined? @shadow_entry
@shadow_entry =
File.readlines(target_file_path)
.reject { |r| r =~ /^[^\w]/ }
.collect { |l| l.chomp.split(':', -1) } # Don't suppress empty fields (PUP-229)
.find { |user, _| user == @resource[:name] }
end
def password
return :absent unless shadow_entry
shadow_entry[1]
end
def password_min_age
return :absent unless shadow_entry
shadow_entry[3].empty? ? -1 : shadow_entry[3]
end
def password_max_age
return :absent unless shadow_entry
shadow_entry[4].empty? ? -1 : shadow_entry[4]
end
def password_warn_days
return :absent unless shadow_entry
shadow_entry[5].empty? ? -1 : shadow_entry[5]
end
def has_sensitive_data?(property = nil)
false
end
# Read in /etc/shadow, find the line for our used and rewrite it with the
# new pw. Smooth like 80 grit sandpaper.
#
# Now uses the `replace_file` mechanism to minimize the chance that we lose
# data, but it is still terrible. We still skip platform locking, so a
# concurrent `vipw -s` session will have no idea we risk data loss.
def password=(cryptopw)
shadow = File.read(target_file_path)
# Go Mifune loves the race here where we can lose data because
# /etc/shadow changed between reading it and writing it.
# --daniel 2012-02-05
Puppet::Util.replace_file(target_file_path, 0o640) do |fh|
shadow.each_line do |line|
line_arr = line.split(':')
if line_arr[0] == @resource[:name]
line_arr[1] = cryptopw
line_arr[2] = (Date.today - Date.new(1970, 1, 1)).to_i.to_s
line = line_arr.join(':')
end
fh.print line
end
end
rescue => detail
self.fail Puppet::Error, "Could not write replace #{target_file_path}: #{detail}", detail
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/provider/user/useradd.rb | lib/puppet/provider/user/useradd.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/nameservice/objectadd'
require 'date'
require_relative '../../../puppet/util/libuser'
require 'time'
require_relative '../../../puppet/error'
Puppet::Type.type(:user).provide :useradd, :parent => Puppet::Provider::NameService::ObjectAdd do
desc "User management via `useradd` and its ilk. Note that you will need to
install Ruby's shadow password library (often known as `ruby-libshadow`)
if you wish to manage user passwords.
To use the `forcelocal` parameter, you need to install the `libuser` package (providing
`/usr/sbin/lgroupadd` and `/usr/sbin/luseradd`)."
commands :add => "useradd", :delete => "userdel", :modify => "usermod", :password => "chage", :chpasswd => "chpasswd"
options :home, :flag => "-d", :method => :dir
options :comment, :method => :gecos
options :groups, :flag => "-G"
options :password_min_age, :flag => "-m", :method => :sp_min
options :password_max_age, :flag => "-M", :method => :sp_max
options :password_warn_days, :flag => "-W", :method => :sp_warn
options :password, :method => :sp_pwdp
options :expiry, :method => :sp_expire,
:munge => proc { |value|
if value == :absent
if Puppet.runtime[:facter].value('os.name') == 'SLES' && Puppet.runtime[:facter].value('os.release.major') == "11"
-1
else
''
end
else
case Puppet.runtime[:facter].value('os.name')
when 'Solaris'
# Solaris uses %m/%d/%Y for useradd/usermod
expiry_year, expiry_month, expiry_day = value.split('-')
[expiry_month, expiry_day, expiry_year].join('/')
else
value
end
end
},
:unmunge => proc { |value|
if value == -1
:absent
else
# Expiry is days after 1970-01-01
(Date.new(1970, 1, 1) + value).strftime('%Y-%m-%d')
end
}
optional_commands :localadd => "luseradd", :localdelete => "luserdel", :localmodify => "lusermod", :localpassword => "lchage"
has_feature :manages_local_users_and_groups if Puppet.features.libuser?
def exists?
return !!localuid if @resource.forcelocal?
super
end
def uid
return localuid if @resource.forcelocal?
get(:uid)
end
def gid
return localgid if @resource.forcelocal?
get(:gid)
end
def comment
return localcomment if @resource.forcelocal?
get(:comment)
end
def shell
return localshell if @resource.forcelocal?
get(:shell)
end
def home
return localhome if @resource.forcelocal?
get(:home)
end
def groups
return localgroups if @resource.forcelocal?
super
end
def finduser(key, value)
passwd_file = '/etc/passwd'
passwd_keys = [:account, :password, :uid, :gid, :gecos, :directory, :shell]
unless @users
unless Puppet::FileSystem.exist?(passwd_file)
raise Puppet::Error, "Forcelocal set for user resource '#{resource[:name]}', but #{passwd_file} does not exist"
end
@users = []
Puppet::FileSystem.each_line(passwd_file) do |line|
user = line.chomp.split(':')
@users << passwd_keys.zip(user).to_h
end
end
@users.find { |param| param[key] == value } || false
end
def local_username
finduser(:uid, @resource.uid)
end
def localuid
user = finduser(:account, resource[:name])
return user[:uid] if user
false
end
def localgid
user = finduser(:account, resource[:name])
if user
begin
return Integer(user[:gid])
rescue ArgumentError
Puppet.debug("Non-numeric GID found in /etc/passwd for user #{resource[:name]}")
return user[:gid]
end
end
false
end
def localcomment
user = finduser(:account, resource[:name])
user[:gecos]
end
def localshell
user = finduser(:account, resource[:name])
user[:shell]
end
def localhome
user = finduser(:account, resource[:name])
user[:directory]
end
def localgroups
@groups_of ||= {}
group_file = '/etc/group'
user = resource[:name]
return @groups_of[user] if @groups_of[user]
@groups_of[user] = []
unless Puppet::FileSystem.exist?(group_file)
raise Puppet::Error, "Forcelocal set for user resource '#{user}', but #{group_file} does not exist"
end
Puppet::FileSystem.each_line(group_file) do |line|
data = line.chomp.split(':')
if !data.empty? && data.last.split(',').include?(user)
@groups_of[user] << data.first
end
end
@groups_of[user]
end
def shell=(value)
check_valid_shell
set(:shell, value)
end
def groups=(value)
set(:groups, value)
end
def password=(value)
user = @resource[:name]
tempfile = Tempfile.new('puppet', :encoding => Encoding::UTF_8)
begin
# Puppet execute does not support strings as input, only files.
# The password is expected to be in an encrypted format given -e is specified:
tempfile << "#{user}:#{value}\n"
tempfile.flush
# Options '-e' use encrypted password
# Must receive "user:enc_password" as input
# command, arguments = {:failonfail => true, :combine => true}
cmd = [command(:chpasswd), '-e']
execute_options = {
:failonfail => false,
:combine => true,
:stdinfile => tempfile.path,
:sensitive => has_sensitive_data?
}
output = execute(cmd, execute_options)
rescue => detail
tempfile.close
tempfile.delete
raise Puppet::Error, "Could not set password on #{@resource.class.name}[#{@resource.name}]: #{detail}", detail.backtrace
end
# chpasswd can return 1, even on success (at least on AIX 6.1); empty output
# indicates success
raise Puppet::ExecutionFailure, "chpasswd said #{output}" if output != ''
end
verify :gid, "GID must be an integer" do |value|
value.is_a? Integer
end
verify :groups, "Groups must be comma-separated" do |value|
value !~ /\s/
end
has_features :manages_homedir, :allows_duplicates, :manages_expiry
has_features :system_users unless %w[HP-UX Solaris].include? Puppet.runtime[:facter].value('os.name')
has_features :manages_passwords, :manages_password_age if Puppet.features.libshadow?
has_features :manages_shell
def check_allow_dup
# We have to manually check for duplicates when using libuser
# because by default duplicates are allowed. This check is
# to ensure consistent behaviour of the useradd provider when
# using both useradd and luseradd
if !@resource.allowdupe? && @resource.forcelocal?
if @resource.should(:uid) && finduser(:uid, @resource.should(:uid).to_s)
raise(Puppet::Error, "UID #{@resource.should(:uid)} already exists, use allowdupe to force user creation")
end
elsif @resource.allowdupe? && !@resource.forcelocal?
return ["-o"]
end
[]
end
def check_valid_shell
unless File.exist?(@resource.should(:shell))
raise(Puppet::Error, "Shell #{@resource.should(:shell)} must exist")
end
unless File.executable?(@resource.should(:shell).to_s)
raise(Puppet::Error, "Shell #{@resource.should(:shell)} must be executable")
end
end
def check_manage_home
cmd = []
if @resource.managehome?
# libuser does not implement the -m flag
cmd << "-m" unless @resource.forcelocal?
else
osfamily = Puppet.runtime[:facter].value('os.family')
osversion = Puppet.runtime[:facter].value('os.release.major').to_i
# SLES 11 uses pwdutils instead of shadow, which does not have -M
# Solaris and OpenBSD use different useradd flavors
unless osfamily =~ /Solaris|OpenBSD/ || osfamily == 'Suse' && osversion <= 11
cmd << "-M"
end
end
cmd
end
def check_system_users
if self.class.system_users? && resource.system?
["-r"]
else
[]
end
end
# Add properties and flags but skipping password related properties due to
# security risks
def add_properties
cmd = []
# validproperties is a list of properties in undefined order
# sort them to have a predictable command line in tests
Puppet::Type.type(:user).validproperties.sort.each do |property|
value = get_value_for_property(property)
next if value.nil? || property == :password
# the value needs to be quoted, mostly because -c might
# have spaces in it
cmd << flag(property) << munge(property, value)
end
cmd
end
def get_value_for_property(property)
return nil if property == :ensure
return nil if property_manages_password_age?(property)
return nil if property == :groups and @resource.forcelocal?
return nil if property == :expiry and @resource.forcelocal?
value = @resource.should(property)
return nil if !value || value == ""
value
end
def has_sensitive_data?(property = nil)
# Check for sensitive values?
properties = property ? [property] : Puppet::Type.type(:user).validproperties
properties.any? do |prop|
p = @resource.parameter(prop)
p && p.respond_to?(:is_sensitive) && p.is_sensitive
end
end
def addcmd
if @resource.forcelocal?
cmd = [command(:localadd)]
@custom_environment = Puppet::Util::Libuser.getenv
else
cmd = [command(:add)]
end
if !@resource.should(:gid) && Puppet::Util.gid(@resource[:name])
cmd += ["-g", @resource[:name]]
end
cmd += add_properties
cmd += check_allow_dup
cmd += check_manage_home
cmd += check_system_users
cmd << @resource[:name]
end
def modifycmd(param, value)
if @resource.forcelocal?
case param
when :groups, :expiry
cmd = [command(:modify)]
else
cmd = [command(property_manages_password_age?(param) ? :localpassword : :localmodify)]
end
@custom_environment = Puppet::Util::Libuser.getenv
else
cmd = [command(property_manages_password_age?(param) ? :password : :modify)]
end
cmd << flag(param) << value
cmd += check_allow_dup if param == :uid
cmd << @resource[:name]
cmd
end
def deletecmd
if @resource.forcelocal?
cmd = [command(:localdelete)]
@custom_environment = Puppet::Util::Libuser.getenv
else
cmd = [command(:delete)]
end
# Solaris `userdel -r` will fail if the homedir does not exist.
if @resource.managehome? && (('Solaris' != Puppet.runtime[:facter].value('os.name')) || Dir.exist?(Dir.home(@resource[:name])))
cmd << '-r'
end
cmd << @resource[:name]
end
def passcmd
if @resource.forcelocal?
cmd = command(:localpassword)
@custom_environment = Puppet::Util::Libuser.getenv
else
cmd = command(:password)
end
age_limits = [:password_min_age, :password_max_age, :password_warn_days].select { |property| @resource.should(property) }
if age_limits.empty?
nil
else
[cmd, age_limits.collect { |property| [flag(property), @resource.should(property)] }, @resource[:name]].flatten
end
end
[:expiry, :password_min_age, :password_max_age, :password_warn_days, :password].each do |shadow_property|
define_method(shadow_property) do
if Puppet.features.libshadow?
ent = Shadow::Passwd.getspnam(@canonical_name)
if ent
method = self.class.option(shadow_property, :method)
return unmunge(shadow_property, ent.send(method))
end
end
:absent
end
end
def create
if @resource[:shell]
check_valid_shell
end
super
if @resource.forcelocal?
set(:groups, @resource[:groups]) if groups?
set(:expiry, @resource[:expiry]) if @resource[:expiry]
end
set(:password, @resource[:password]) if @resource[:password]
end
def groups?
!!@resource[:groups]
end
def property_manages_password_age?(property)
property.to_s =~ /password_.+_age|password_warn_days/
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/provider/user/ldap.rb | lib/puppet/provider/user/ldap.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/ldap'
Puppet::Type.type(:user).provide :ldap, :parent => Puppet::Provider::Ldap do
desc "User management via LDAP.
This provider requires that you have valid values for all of the
LDAP-related settings in `puppet.conf`, including `ldapbase`. You will
almost definitely need settings for `ldapuser` and `ldappassword` in order
for your clients to write to LDAP.
Note that this provider will automatically generate a UID for you if
you do not specify one, but it is a potentially expensive operation,
as it iterates across all existing users to pick the appropriate next one."
confine :feature => :ldap, :false => (Puppet[:ldapuser] == "")
has_feature :manages_passwords, :manages_shell
manages(:posixAccount, :person).at("ou=People").named_by(:uid).and.maps :name => :uid,
:password => :userPassword,
:comment => :cn,
:uid => :uidNumber,
:gid => :gidNumber,
:home => :homeDirectory,
:shell => :loginShell
# Use the last field of a space-separated array as
# the sn. LDAP requires a surname, for some stupid reason.
manager.generates(:sn).from(:cn).with do |cn|
cn[0].split(/\s+/)[-1]
end
# Find the next uid after the current largest uid.
provider = self
manager.generates(:uidNumber).with do
largest = 500
existing = provider.manager.search
if existing
existing.each do |hash|
value = hash[:uid]
next unless value
num = value[0].to_i
largest = num if num > largest
end
end
largest + 1
end
# Convert our gid to a group name, if necessary.
def gid=(value)
value = group2id(value) unless value.is_a?(Integer)
@property_hash[:gid] = value
end
# Find all groups this user is a member of in ldap.
def groups
# We want to cache the current result, so we know if we
# have to remove old values.
unless @property_hash[:groups]
result = group_manager.search("memberUid=#{name}")
unless result
return @property_hash[:groups] = :absent
end
return @property_hash[:groups] = result.collect { |r| r[:name] }.sort.join(",")
end
@property_hash[:groups]
end
# Manage the list of groups this user is a member of.
def groups=(values)
should = values.split(",")
if groups == :absent
is = []
else
is = groups.split(",")
end
modes = {}
[is, should].flatten.uniq.each do |group|
# Skip it when they're in both
next if is.include?(group) and should.include?(group)
# We're adding a group.
modes[group] = :add and next unless is.include?(group)
# We're removing a group.
modes[group] = :remove and next unless should.include?(group)
end
modes.each do |group, form|
ldap_group = group_manager.find(group)
self.fail "Could not find ldap group #{group}" unless ldap_group
current = ldap_group[:members]
if form == :add
if current.is_a?(Array) and !current.empty?
new = current + [name]
else
new = [name]
end
else
new = current - [name]
new = :absent if new.empty?
end
group_manager.update(group, { :ensure => :present, :members => current }, { :ensure => :present, :members => new })
end
end
# Convert a gropu name to an id.
def group2id(group)
Puppet::Type.type(:group).provider(:ldap).name2id(group)
end
private
def group_manager
Puppet::Type.type(:group).provider(:ldap).manager
end
def group_properties(values)
if values.empty? or values == :absent
{ :ensure => :present }
else
{ :ensure => :present, :members => values }
end
end
end
| ruby | Apache-2.0 | 9336df16a11679d701a2bd9ebe1308d4fb669f57 | 2026-01-04T17:47:45.967003Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.