repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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| # rubocop:disable Style/SymbolProc
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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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] == 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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/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 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/exec/shell.rb | lib/puppet/provider/exec/shell.rb | # frozen_string_literal: true
Puppet::Type.type(:exec).provide :shell, :parent => :posix do
include Puppet::Util::Execution
confine :feature => :posix
desc <<-EOT
Passes the provided command through `/bin/sh`; only available on
POSIX systems. This allows the use of shell globbing and built-ins, and
does not require that the path to a command be fully-qualified. Although
this can be more convenient than the `posix` provider, it also means that
you need to be more careful with escaping; as ever, with great power comes
etc. etc.
This provider closely resembles the behavior of the `exec` type
in Puppet 0.25.x.
EOT
def run(command, check = false)
super(['/bin/sh', '-c', command], check)
end
def validatecmd(command)
true
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/exec/posix.rb | lib/puppet/provider/exec/posix.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/exec'
Puppet::Type.type(:exec).provide :posix, :parent => Puppet::Provider::Exec do
has_feature :umask
confine :feature => :posix
defaultfor :feature => :posix
desc <<-EOT
Executes external binaries by invoking Ruby's `Kernel.exec`.
When the command is a string, it will be executed directly,
without a shell, if it follows these rules:
- no meta characters
- no shell reserved word and no special built-in
When the command is an Array of Strings, passed as `[cmdname, arg1, ...]`
it will be executed directly(the first element is taken as a command name
and the rest are passed as parameters to command with no shell expansion)
This is a safer and more predictable way to execute most commands,
but prevents the use of globbing and shell built-ins (including control
logic like "for" and "if" statements).
If the use of globbing and shell built-ins is desired, please check
the `shell` provider
EOT
# Verify that we have the executable
def checkexe(command)
exe = extractexe(command)
if File.expand_path(exe) == exe
if !Puppet::FileSystem.exist?(exe)
raise ArgumentError, _("Could not find command '%{exe}'") % { exe: exe }
elsif !File.file?(exe)
raise ArgumentError, _("'%{exe}' is a %{klass}, not a file") % { exe: exe, klass: File.ftype(exe) }
elsif !File.executable?(exe)
raise ArgumentError, _("'%{exe}' is not executable") % { exe: exe }
end
return
end
if resource[:path]
Puppet::Util.withenv :PATH => resource[:path].join(File::PATH_SEPARATOR) do
return if which(exe)
end
end
# 'which' will only return the command if it's executable, so we can't
# distinguish not found from not executable
raise ArgumentError, _("Could not find command '%{exe}'") % { exe: exe }
end
def run(command, check = false)
if resource[:umask]
Puppet::Util.withumask(resource[:umask]) { super(command, check) }
else
super(command, check)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/exec/windows.rb | lib/puppet/provider/exec/windows.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/exec'
Puppet::Type.type(:exec).provide :windows, :parent => Puppet::Provider::Exec do
confine 'os.name' => :windows
defaultfor 'os.name' => :windows
desc <<-'EOT'
Execute external binaries on Windows systems. As with the `posix`
provider, this provider directly calls the command with the arguments
given, without passing it through a shell or performing any interpolation.
To use shell built-ins --- that is, to emulate the `shell` provider on
Windows --- a command must explicitly invoke the shell:
exec {'echo foo':
command => 'cmd.exe /c echo "foo"',
}
If no extension is specified for a command, Windows will use the `PATHEXT`
environment variable to locate the executable.
**Note on PowerShell scripts:** PowerShell's default `restricted`
execution policy doesn't allow it to run saved scripts. To run PowerShell
scripts, specify the `remotesigned` execution policy as part of the
command:
exec { 'test':
path => 'C:/Windows/System32/WindowsPowerShell/v1.0',
command => 'powershell -executionpolicy remotesigned -file C:/test.ps1',
}
EOT
# Verify that we have the executable
def checkexe(command)
exe = extractexe(command)
if absolute_path?(exe)
if !Puppet::FileSystem.exist?(exe)
raise ArgumentError, _("Could not find command '%{exe}'") % { exe: exe }
elsif !File.file?(exe)
raise ArgumentError, _("'%{exe}' is a %{klass}, not a file") % { exe: exe, klass: File.ftype(exe) }
end
return
end
if resource[:path]
Puppet::Util.withenv('PATH' => resource[:path].join(File::PATH_SEPARATOR)) do
return if which(exe)
end
end
raise ArgumentError, _("Could not find command '%{exe}'") % { exe: exe }
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/group/windows_adsi.rb | lib/puppet/provider/group/windows_adsi.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/windows'
Puppet::Type.type(:group).provide :windows_adsi do
desc "Local group management for Windows. Group members can be both users and groups.
Additionally, local groups can contain domain users."
defaultfor 'os.name' => :windows
confine 'os.name' => :windows
has_features :manages_members
def initialize(value = {})
super(value)
@deleted = false
end
def members_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_members = Puppet::Util::Windows::ADSI::Group.name_sid_hash(current, true)
specified_members = Puppet::Util::Windows::ADSI::Group.name_sid_hash(should)
current_sids = current_members.keys.to_a
specified_sids = specified_members.keys.to_a
if @resource[:auth_membership]
current_sids.sort == specified_sids.sort
else
(specified_sids & current_sids) == specified_sids
end
end
def members_to_s(users)
return '' if users.nil? or !users.is_a?(Array)
users = users.map do |user_name|
sid = Puppet::Util::Windows::SID.name_to_principal(user_name)
unless sid
resource.debug("#{user_name} (unresolvable to SID)")
next user_name
end
if sid.account =~ /\\/
account, _ = Puppet::Util::Windows::ADSI::User.parse_name(sid.account)
else
account = sid.account
end
resource.debug("#{sid.domain}\\#{account} (#{sid.sid})")
sid.domain ? "#{sid.domain}\\#{account}" : account
end
users.join(',')
end
def member_valid?(user_name)
!Puppet::Util::Windows::SID.name_to_principal(user_name).nil?
end
def group
@group ||= Puppet::Util::Windows::ADSI::Group.new(@resource[:name])
end
def members
@members ||= Puppet::Util::Windows::ADSI::Group.name_sid_hash(group.members, true)
# @members.keys returns an array of SIDs. We need to convert those SIDs into
# names so that `puppet resource` prints the right output.
members_to_s(@members.keys).split(',')
end
def members=(members)
group.set_members(members, @resource[:auth_membership])
end
def create
@group = Puppet::Util::Windows::ADSI::Group.create(@resource[:name])
@group.commit
self.members = @resource[:members]
end
def exists?
Puppet::Util::Windows::ADSI::Group.exists?(@resource[:name])
end
def delete
Puppet::Util::Windows::ADSI::Group.delete(@resource[:name])
@deleted = true
end
# Only flush if we created or modified a group, not deleted
def flush
@group.commit if @group && !@deleted
end
def gid
Puppet::Util::Windows::SID.name_to_sid(@resource[:name])
end
def gid=(value)
fail "gid is read-only"
end
def self.instances
Puppet::Util::Windows::ADSI::Group.map { |g| new(:ensure => :present, :name => g.name) }
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/group/aix.rb | lib/puppet/provider/group/aix.rb | # frozen_string_literal: true
# Group Puppet provider for AIX. It uses standard commands to manage groups:
# mkgroup, rmgroup, lsgroup, chgroup
require_relative '../../../puppet/provider/aix_object'
Puppet::Type.type(:group).provide :aix, :parent => Puppet::Provider::AixObject do
desc "Group management for AIX."
# This will the default provider for this platform
defaultfor 'os.name' => :aix
confine 'os.name' => :aix
# Commands that manage the element
commands :list => "/usr/sbin/lsgroup"
commands :add => "/usr/bin/mkgroup"
commands :delete => "/usr/sbin/rmgroup"
commands :modify => "/usr/bin/chgroup"
# Provider features
has_features :manages_aix_lam
has_features :manages_members
has_features :manages_local_users_and_groups
class << self
# Used by the AIX user provider. Returns a hash of:
# {
# :name => <group_name>,
# :gid => <gid>
# }
#
# that matches the group, which can either be the group name or
# the gid. Takes an optional set of ia_module_args
def find(group, ia_module_args = [])
groups = list_all(ia_module_args)
id_property = mappings[:puppet_property][:id]
if group.is_a?(String)
# Find by name
group_hash = groups.find { |cur_group| cur_group[:name] == group }
else
# Find by gid
group_hash = groups.find do |cur_group|
id_property.convert_attribute_value(cur_group[:id]) == group
end
end
unless group_hash
raise ArgumentError, _("No AIX group exists with a group name or gid of %{group}!") % { group: group }
end
# Convert :id => :gid
id = group_hash.delete(:id)
group_hash[:gid] = id_property.convert_attribute_value(id)
group_hash
end
# Define some Puppet Property => AIX Attribute (and vice versa)
# conversion functions here. This is so we can unit test them.
def members_to_users(provider, members)
members = members.split(',') if members.is_a?(String)
unless provider.resource[:auth_membership]
current_members = provider.members
current_members = [] if current_members == :absent
members = (members + current_members).uniq
end
members.join(',')
end
def users_to_members(users)
users.split(',')
end
end
mapping puppet_property: :members,
aix_attribute: :users,
property_to_attribute: method(:members_to_users),
attribute_to_property: method(:users_to_members)
numeric_mapping puppet_property: :gid,
aix_attribute: :id
# 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
# We could add this to the top-level members property since the
# implementation is not platform-specific; however, it is best
# to do it this way so that we do not accidentally break something.
# This is ok for now, since we do plan on moving this and the
# auth_membership management over to the property class in a future
# Puppet release.
def members_insync?(current, should)
current.sort == @resource.parameter(:members).actual_should(current, should)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/group/directoryservice.rb | lib/puppet/provider/group/directoryservice.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/nameservice/directoryservice'
Puppet::Type.type(:group).provide :directoryservice, :parent => Puppet::Provider::NameService::DirectoryService do
desc "Group management using DirectoryService on OS X.
"
commands :dscl => "/usr/bin/dscl"
confine 'os.name' => :darwin
defaultfor 'os.name' => :darwin
has_feature :manages_members
def members_insync?(current, should)
return false unless current
if current == :absent
should.empty?
else
current.sort.uniq == should.sort.uniq
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/group/pw.rb | lib/puppet/provider/group/pw.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/nameservice/pw'
Puppet::Type.type(:group).provide :pw, :parent => Puppet::Provider::NameService::PW do
desc "Group management via `pw` on FreeBSD and DragonFly BSD."
commands :pw => "pw"
has_features :manages_members
defaultfor 'os.name' => [:freebsd, :dragonfly]
confine 'os.name' => [:freebsd, :dragonfly]
options :members, :flag => "-M", :method => :mem
verify :gid, _("GID must be an integer") do |value|
value.is_a? Integer
end
def addcmd
cmd = [command(:pw), "groupadd", @resource[:name]]
gid = @resource.should(:gid)
if gid
unless gid == :absent
cmd << flag(:gid) << gid
end
end
members = @resource.should(:members)
if members
unless members == :absent
if members.is_a?(Array)
members = members.join(",")
end
cmd << "-M" << members
end
end
cmd << "-o" if @resource.allowdupe?
cmd
end
def modifycmd(param, value)
# members may be an array, need a comma separated list
if param == :members and value.is_a?(Array)
value = value.join(",")
end
super(param, value)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/group/groupadd.rb | lib/puppet/provider/group/groupadd.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/nameservice/objectadd'
require_relative '../../../puppet/util/libuser'
Puppet::Type.type(:group).provide :groupadd, :parent => Puppet::Provider::NameService::ObjectAdd do
desc "Group management via `groupadd` and its ilk. The default for most platforms.
To use the `forcelocal` parameter, you need to install the `libuser` package (providing
`/usr/sbin/lgroupadd` and `/usr/sbin/luseradd`)."
commands :add => "groupadd", :delete => "groupdel", :modify => "groupmod"
has_feature :system_groups unless %w[HP-UX Solaris].include? Puppet.runtime[:facter].value('os.name')
verify :gid, _("GID must be an integer") do |value|
value.is_a? Integer
end
optional_commands :localadd => "lgroupadd", :localdelete => "lgroupdel", :localmodify => "lgroupmod", :purgemember => "usermod"
has_feature :manages_local_users_and_groups if Puppet.features.libuser?
has_feature :manages_members if Puppet.features.libuser? ||
(Puppet.runtime[:facter].value('os.name') == "Fedora" &&
Puppet.runtime[:facter].value('os.release.major').to_i >= 40)
# Libuser's modify command 'lgroupmod' requires '-M' flag for member additions.
# 'groupmod' command requires the '-aU' flags for it.
if Puppet.features.libuser?
options :members, :flag => '-M', :method => :mem
else
options :members, :flag => '-aU', :method => :mem
end
def exists?
return !!localgid if @resource.forcelocal?
super
end
def gid
return localgid if @resource.forcelocal?
get(:gid)
end
def localgid
group = findgroup(:group_name, resource[:name])
return group[:gid] if group
false
end
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? and @resource.forcelocal?
if @resource.should(:gid) and findgroup(:gid, @resource.should(:gid).to_s)
raise(Puppet::Error, _("GID %{resource} already exists, use allowdupe to force group creation") % { resource: @resource.should(:gid).to_s })
end
elsif @resource.allowdupe? and !@resource.forcelocal?
return ["-o"]
end
[]
end
def create
super
set(:members, @resource[:members]) if @resource[:members]
end
def addcmd
# The localadd command (lgroupadd) must only be called when libuser is supported.
if Puppet.features.libuser? && @resource.forcelocal?
cmd = [command(:localadd)]
@custom_environment = Puppet::Util::Libuser.getenv
else
cmd = [command(:add)]
end
gid = @resource.should(:gid)
if gid
unless gid == :absent
cmd << flag(:gid) << gid
end
end
cmd += check_allow_dup
cmd << "-r" if @resource.system? and self.class.system_groups?
cmd << @resource[:name]
cmd
end
def validate_members(members)
members.each do |member|
member.split(',').each do |user|
Etc.getpwnam(user.strip)
end
end
end
def modifycmd(param, value)
# The localmodify command (lgroupmod) must only be called when libuser is supported.
if Puppet.features.libuser? && (@resource.forcelocal? || @resource[:members])
cmd = [command(:localmodify)]
@custom_environment = Puppet::Util::Libuser.getenv
else
cmd = [command(:modify)]
end
if param == :members
validate_members(value)
value = members_to_s(value)
purge_members if @resource[:auth_membership] && !members.empty?
end
cmd << flag(param) << value
# TODO the group type only really manages gid, so there are currently no
# tests for this behavior
cmd += check_allow_dup if param == :gid
cmd << @resource[:name]
cmd
end
def deletecmd
# The localdelete command (lgroupdel) must only be called when libuser is supported.
if Puppet.features.libuser? && @resource.forcelocal?
@custom_environment = Puppet::Util::Libuser.getenv
[command(:localdelete), @resource[:name]]
else
[command(:delete), @resource[:name]]
end
end
def members_insync?(current, should)
current.uniq.sort == @resource.parameter(:members).actual_should(current, should)
end
def members_to_s(current)
return '' if current.nil? || !current.is_a?(Array)
current.join(',')
end
def purge_members
# The groupadd provider doesn't have the ability currently to remove members from a group, libuser does.
# Use libuser's lgroupmod command to achieve purging members if libuser is supported.
# Otherwise use the 'usermod' command.
if Puppet.features.libuser?
localmodify('-m', members_to_s(members), @resource.name)
else
members.each do |member|
purgemember('-rG', @resource.name, member)
end
end
end
private
def findgroup(key, value)
group_file = '/etc/group'
group_keys = [:group_name, :password, :gid, :user_list]
unless @groups
unless Puppet::FileSystem.exist?(group_file)
raise Puppet::Error, "Forcelocal set for group resource '#{resource[:name]}', but #{group_file} does not exist"
end
@groups = []
Puppet::FileSystem.each_line(group_file) do |line|
group = line.chomp.split(':')
@groups << group_keys.zip(group).to_h
end
end
@groups.find { |param| param[key] == value } || false
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/group/ldap.rb | lib/puppet/provider/group/ldap.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/ldap'
Puppet::Type.type(:group).provide :ldap, :parent => Puppet::Provider::Ldap do
desc "Group 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 GID for you if you do
not specify one, but it is a potentially expensive operation, as it
iterates across all existing groups to pick the appropriate next one."
confine :feature => :ldap, :false => (Puppet[:ldapuser] == "")
# We're mapping 'members' here because we want to make it
# easy for the ldap user provider to manage groups. This
# way it can just use the 'update' method in the group manager,
# whereas otherwise it would need to replicate that code.
manages(:posixGroup).at("ou=Groups").and.maps :name => :cn, :gid => :gidNumber, :members => :memberUid
# Find the next gid after the current largest gid.
provider = self
manager.generates(:gidNumber).with do
largest = 500
existing = provider.manager.search
if existing
existing.each do |hash|
value = hash[:gid]
next unless value
num = value[0].to_i
largest = num if num > largest
end
end
largest + 1
end
# Convert a group name to an id.
def self.name2id(group)
result = manager.search("cn=#{group}")
return nil unless result and result.length > 0
# Only use the first result.
group = result[0]
group[:gid][0]
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/nameservice/directoryservice.rb | lib/puppet/provider/nameservice/directoryservice.rb | # frozen_string_literal: true
require_relative '../../../puppet'
require_relative '../../../puppet/provider/nameservice'
require_relative '../../../puppet/util/plist' if Puppet.features.cfpropertylist?
require 'fileutils'
class Puppet::Provider::NameService::DirectoryService < Puppet::Provider::NameService
# JJM: Dive into the singleton_class
class << self
# JJM: This allows us to pass information when calling
# Puppet::Type.type
# e.g. Puppet::Type.type(:user).provide :directoryservice, :ds_path => "Users"
# This is referenced in the get_ds_path class method
attr_writer :ds_path
end
initvars
commands :dscl => "/usr/bin/dscl"
commands :dseditgroup => "/usr/sbin/dseditgroup"
commands :sw_vers => "/usr/bin/sw_vers"
confine 'os.name' => :darwin
confine :feature => :cfpropertylist
defaultfor 'os.name' => :darwin
# There is no generalized mechanism for provider cache management, but we can
# use post_resource_eval, which will be run for each suitable provider at the
# end of each transaction. Use this to clear @all_present after each run.
def self.post_resource_eval
@all_present = nil
end
# JJM 2007-07-25: This map is used to map NameService attributes to their
# corresponding DirectoryService attribute names.
# See: http://images.apple.com/server/docs.Open_Directory_v10.4.pdf
# JJM: Note, this is de-coupled from the Puppet::Type, and must
# be actively maintained. There may also be collisions with different
# types (Users, Groups, Mounts, Hosts, etc...)
def ds_to_ns_attribute_map; self.class.ds_to_ns_attribute_map; end
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
# JJM The same table as above, inverted.
def ns_to_ds_attribute_map; self.class.ns_to_ds_attribute_map end
def self.ns_to_ds_attribute_map
@ns_to_ds_attribute_map ||= ds_to_ns_attribute_map.invert
end
def self.password_hash_dir
'/var/db/shadow/hash'
end
def self.users_plist_dir
'/var/db/dslocal/nodes/Default/users'
end
def self.instances
# JJM Class method that provides an array of instance objects of this
# type.
# JJM: Properties are dependent on the Puppet::Type we're managing.
type_property_array = [:name] + @resource_type.validproperties
# Create a new instance of this Puppet::Type for each object present
# on the system.
list_all_present.collect do |name_string|
new(single_report(name_string, *type_property_array))
end
end
def self.get_ds_path
# JJM: 2007-07-24 This method dynamically returns the DS path we're concerned with.
# For example, if we're working with an user type, this will be /Users
# with a group type, this will be /Groups.
# @ds_path is an attribute of the class itself.
return @ds_path if defined?(@ds_path)
# JJM: "Users" or "Groups" etc ... (Based on the Puppet::Type)
# Remember this is a class method, so self.class is Class
# Also, @resource_type seems to be the reference to the
# Puppet::Type this class object is providing for.
@resource_type.name.to_s.capitalize + "s"
end
def self.list_all_present
# rubocop:disable Naming/MemoizedInstanceVariableName
@all_present ||= begin
# rubocop:enable Naming/MemoizedInstanceVariableName
# JJM: List all objects of this Puppet::Type already present on the system.
begin
dscl_output = execute(get_exec_preamble("-list"))
rescue Puppet::ExecutionFailure
fail(_("Could not get %{resource} list from DirectoryService") % { resource: @resource_type.name })
end
dscl_output.split("\n")
end
end
def self.parse_dscl_plist_data(dscl_output)
Puppet::Util::Plist.parse_plist(dscl_output)
end
def self.generate_attribute_hash(input_hash, *type_properties)
attribute_hash = {}
input_hash.each_key do |key|
ds_attribute = key.sub("dsAttrTypeStandard:", "")
next unless ds_to_ns_attribute_map.keys.include?(ds_attribute) and type_properties.include? ds_to_ns_attribute_map[ds_attribute]
ds_value = input_hash[key]
case ds_to_ns_attribute_map[ds_attribute]
when :members
# do nothing, only members uses arrays so far
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
# NBK: need to read the existing password here as it's not actually
# stored in the user record. It is stored at a path that involves the
# UUID of the user record for non-Mobile local accounts.
# Mobile Accounts are out of scope for this provider for now
attribute_hash[:password] = get_password(attribute_hash[:guid], attribute_hash[:name]) if @resource_type.validproperties.include?(:password) and Puppet.features.root?
attribute_hash
end
def self.single_report(resource_name, *type_properties)
# JJM 2007-07-24:
# Given a the name of an object and a list of properties of that
# object, return all property values in a hash.
#
# This class method returns nil if the object doesn't exist
# Otherwise, it returns a hash of the object properties.
all_present_str_array = list_all_present
# NBK: shortcut the process if the resource is missing
return nil unless all_present_str_array.include? resource_name
dscl_vector = get_exec_preamble("-read", resource_name)
begin
dscl_output = execute(dscl_vector)
rescue Puppet::ExecutionFailure
fail(_("Could not get report. command execution failed."))
end
dscl_plist = parse_dscl_plist_data(dscl_output)
generate_attribute_hash(dscl_plist, *type_properties)
end
def self.get_exec_preamble(ds_action, resource_name = nil)
# JJM 2007-07-24
# DSCL commands are often repetitive and contain the same positional
# arguments over and over. See https://developer.apple.com/documentation/Porting/Conceptual/PortingUnix/additionalfeatures/chapter_10_section_9.html
# for an example of what I mean.
# This method spits out proper DSCL commands for us.
# We EXPECT name to be @resource[:name] when called from an instance object.
command_vector = [command(:dscl), "-plist", "."]
# JJM: The actual action to perform. See "man dscl".
# Common actions: -create, -delete, -merge, -append, -passwd
command_vector << ds_action
# JJM: get_ds_path will spit back "Users" or "Groups",
# etc... Depending on the Puppet::Type of our self.
if resource_name
command_vector << "/#{get_ds_path}/#{resource_name}"
else
command_vector << "/#{get_ds_path}"
end
# JJM: This returns most of the preamble of the command.
# e.g. 'dscl / -create /Users/mccune'
command_vector
end
def self.set_password(resource_name, guid, password_hash)
# 10.7 uses salted SHA512 password hashes which are 128 characters plus
# an 8 character salt. Previous versions used a SHA1 hash padded with
# zeroes. If someone attempts to use a password hash that worked with
# a previous version of OS X, we will fail early and warn them.
if password_hash.length != 136
# TRANSLATORS 'OS X 10.7' is an operating system and should not be translated, 'Salted SHA512' is the name of a hashing algorithm
fail(_("OS X 10.7 requires a Salted SHA512 hash password of 136 characters.") +
' ' + _("Please check your password and try again."))
end
plist_file = "#{users_plist_dir}/#{resource_name}.plist"
if Puppet::FileSystem.exist?(plist_file)
# If a plist already exists in /var/db/dslocal/nodes/Default/users, then
# we will need to extract the binary plist from the 'ShadowHashData'
# key, log the new password into the resultant plist's 'SALTED-SHA512'
# key, and then save the entire structure back.
users_plist = Puppet::Util::Plist.read_plist_file(plist_file)
# users_plist['ShadowHashData'][0] is actually a binary plist
# that's nested INSIDE the user's plist (which itself is a binary
# plist). If we encounter a user plist that DOESN'T have a
# ShadowHashData field, create one.
if users_plist['ShadowHashData']
password_hash_plist = users_plist['ShadowHashData'][0]
converted_hash_plist = convert_binary_to_hash(password_hash_plist)
else
users_plist['ShadowHashData'] = ''.dup
converted_hash_plist = { 'SALTED-SHA512' => ''.dup }
end
# converted_hash_plist['SALTED-SHA512'] expects a Base64 encoded
# string. The password_hash provided as a resource attribute is a
# hex value. We need to convert the provided hex value to a Base64
# encoded string to nest it in the converted hash plist.
converted_hash_plist['SALTED-SHA512'] = \
password_hash.unpack('a2' * (password_hash.size / 2)).collect { |i| i.hex.chr }.join
# Finally, we can convert the nested plist back to binary, embed it
# into the user's plist, and convert the resultant plist back to
# a binary plist.
changed_plist = convert_hash_to_binary(converted_hash_plist)
users_plist['ShadowHashData'][0] = changed_plist
Puppet::Util::Plist.write_plist_file(users_plist, plist_file, :binary)
end
end
def self.get_password(guid, username)
plist_file = "#{users_plist_dir}/#{username}.plist"
if Puppet::FileSystem.exist?(plist_file)
# If a plist exists in /var/db/dslocal/nodes/Default/users, we will
# extract the binary plist from the 'ShadowHashData' key, decode the
# salted-SHA512 password hash, and then return it.
users_plist = Puppet::Util::Plist.read_plist_file(plist_file)
if users_plist['ShadowHashData']
# users_plist['ShadowHashData'][0] is actually a binary plist
# that's nested INSIDE the user's plist (which itself is a binary
# plist).
password_hash_plist = users_plist['ShadowHashData'][0]
converted_hash_plist = convert_binary_to_hash(password_hash_plist)
# converted_hash_plist['SALTED-SHA512'] is a Base64 encoded
# string. The password_hash provided as a resource attribute is a
# hex value. We need to convert the Base64 encoded string to a
# hex value and provide it back to Puppet.
converted_hash_plist['SALTED-SHA512'].unpack1("H*")
end
end
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
# Unlike most other *nixes, OS X doesn't provide built in functionality
# for automatically assigning uids and gids to accounts, so we set up these
# methods for consumption by functionality like --mkusers
# By default we restrict to a reasonably sane range for system accounts
def self.next_system_id(id_type, min_id = 20)
dscl_args = ['.', '-list']
case id_type
when 'uid'
dscl_args << '/Users' << 'uid'
when 'gid'
dscl_args << '/Groups' << 'gid'
else
fail(_("Invalid id_type %{id_type}. Only 'uid' and 'gid' supported") % { id_type: id_type })
end
dscl_out = dscl(dscl_args)
# We're ok with throwing away negative uids here.
ids = dscl_out.split.compact.collect { |l| l.to_i if l =~ /^\d+$/ }
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
def ensure=(ensure_value)
super
# We need to loop over all valid properties for the type we're
# managing and call the method which sets that property value
# dscl can't create everything at once unfortunately.
if ensure_value == :present
@resource.class.validproperties.each do |name|
next if name == :ensure
# LAK: We use property.sync here rather than directly calling
# the settor method because the properties might do some kind
# of conversion. In particular, the user gid property might
# have a string and need to convert it to a number
if @resource.should(name)
@resource.property(name).sync
else
value = autogen(name)
if value
send(name.to_s + "=", value)
else
next
end
end
end
end
end
def password=(passphrase)
exec_arg_vector = self.class.get_exec_preamble("-read", @resource.name)
exec_arg_vector << ns_to_ds_attribute_map[:guid]
begin
guid_output = execute(exec_arg_vector)
guid_plist = Puppet::Util::Plist.parse_plist(guid_output)
# Although GeneratedUID like all DirectoryService values can be multi-valued
# according to the schema, in practice user accounts cannot have multiple UUIDs
# otherwise Bad Things Happen, so we just deal with the first value.
guid = guid_plist["dsAttrTypeStandard:#{ns_to_ds_attribute_map[:guid]}"][0]
self.class.set_password(@resource.name, guid, passphrase)
rescue Puppet::ExecutionFailure => detail
fail(_("Could not set %{param} on %{resource}[%{name}]: %{detail}") % { param: param, resource: @resource.class.name, name: @resource.name, detail: detail })
end
end
# NBK: we override @parent.set as we need to execute a series of commands
# to deal with array values, rather than the single command nameservice.rb
# expects to be returned by modifycmd. Thus we don't bother defining modifycmd.
def set(param, value)
self.class.validate(param, value)
current_members = @property_value_cache_hash[:members]
if param == :members
# If we are meant to be authoritative for the group membership
# then remove all existing members who haven't been specified
# in the manifest.
remove_unwanted_members(current_members, value) if @resource[:auth_membership] and !current_members.nil?
# if they're not a member, make them one.
add_members(current_members, value)
else
exec_arg_vector = self.class.get_exec_preamble("-create", @resource[:name])
# JJM: The following line just maps the NS name to the DS name
# e.g. { :uid => 'UniqueID' }
exec_arg_vector << ns_to_ds_attribute_map[param.intern]
# JJM: The following line sends the actual value to set the property to
exec_arg_vector << value.to_s
begin
execute(exec_arg_vector)
rescue Puppet::ExecutionFailure => detail
fail(_("Could not set %{param} on %{resource}[%{name}]: %{detail}") % { param: param, resource: @resource.class.name, name: @resource.name, detail: detail })
end
end
end
# NBK: we override @parent.create as we need to execute a series of commands
# to create objects with dscl, rather than the single command nameservice.rb
# expects to be returned by addcmd. Thus we don't bother defining addcmd.
def create
if exists?
info _("already exists")
return nil
end
# NBK: First we create the object with a known guid so we can set the contents
# of the password hash if required
# Shelling out sucks, but for a single use case it doesn't seem worth
# requiring people install a UUID library that doesn't come with the system.
# This should be revisited if Puppet starts managing UUIDs for other platform
# user records.
guid = %x(/usr/bin/uuidgen).chomp
exec_arg_vector = self.class.get_exec_preamble("-create", @resource[:name])
exec_arg_vector << ns_to_ds_attribute_map[:guid] << guid
begin
execute(exec_arg_vector)
rescue Puppet::ExecutionFailure => detail
fail(_("Could not set GeneratedUID for %{resource} %{name}: %{detail}") % { resource: @resource.class.name, name: @resource.name, detail: detail })
end
value = @resource.should(:password)
if value && value != ""
self.class.set_password(@resource[:name], guid, value)
end
# Now we create all the standard properties
Puppet::Type.type(@resource.class.name).validproperties.each do |property|
next if property == :ensure
value = @resource.should(property)
if property == :gid and value.nil?
value = self.class.next_system_id('gid')
end
if property == :uid and value.nil?
value = self.class.next_system_id('uid')
end
if value != "" and !value.nil?
if property == :members
add_members(nil, value)
else
exec_arg_vector = self.class.get_exec_preamble("-create", @resource[:name])
exec_arg_vector << ns_to_ds_attribute_map[property.intern]
next if property == :password # skip setting the password here
exec_arg_vector << value.to_s
begin
execute(exec_arg_vector)
rescue Puppet::ExecutionFailure => detail
fail(_("Could not create %{resource} %{name}: %{detail}") % { resource: @resource.class.name, name: @resource.name, detail: detail })
end
end
end
end
end
def remove_unwanted_members(current_members, new_members)
current_members.each do |member|
next if new_members.flatten.include?(member)
cmd = [:dseditgroup, "-o", "edit", "-n", ".", "-d", member, @resource[:name]]
begin
execute(cmd)
rescue Puppet::ExecutionFailure
# TODO: We're falling back to removing the member using dscl due to rdar://8481241
# This bug causes dseditgroup to fail to remove a member if that member doesn't exist
cmd = [:dscl, ".", "-delete", "/Groups/#{@resource.name}", "GroupMembership", member]
begin
execute(cmd)
rescue Puppet::ExecutionFailure => detail
fail(_("Could not remove %{member} from group: %{resource}, %{detail}") % { member: member, resource: @resource.name, detail: detail })
end
end
end
end
def add_members(current_members, new_members)
new_members.flatten.each do |new_member|
next unless current_members.nil? or !current_members.include?(new_member)
cmd = [:dseditgroup, "-o", "edit", "-n", ".", "-a", new_member, @resource[:name]]
begin
execute(cmd)
rescue Puppet::ExecutionFailure => detail
fail(_("Could not add %{new_member} to group: %{name}, %{detail}") % { new_member: new_member, name: @resource.name, detail: detail })
end
end
end
def deletecmd
# JJM: Like addcmd, only called when deleting the object itself
# Note, this isn't used to delete properties of the object,
# at least that's how I understand it...
self.class.get_exec_preamble("-delete", @resource[:name])
end
def getinfo(refresh = false)
# JJM 2007-07-24:
# Override the getinfo method, which is also defined in nameservice.rb
# This method returns and sets @infohash
# I'm not re-factoring the name "getinfo" because this method will be
# most likely called by nameservice.rb, which I didn't write.
if refresh or (!defined?(@property_value_cache_hash) or !@property_value_cache_hash)
# JJM 2007-07-24: OK, there's a bit of magic that's about to
# happen... Let's see how strong my grip has become... =)
#
# self is a provider instance of some Puppet::Type, like
# Puppet::Type::User::ProviderDirectoryservice for the case of the
# user type and this provider.
#
# self.class looks like "user provider directoryservice", if that
# helps you ...
#
# self.class.resource_type is a reference to the Puppet::Type class,
# probably Puppet::Type::User or Puppet::Type::Group, etc...
#
# self.class.resource_type.validproperties is a class method,
# returning an Array of the valid properties of that specific
# Puppet::Type.
#
# So... something like [:comment, :home, :password, :shell, :uid,
# :groups, :ensure, :gid]
#
# Ultimately, we add :name to the list, delete :ensure from the
# list, then report on the remaining list. Pretty whacky, ehh?
type_properties = [:name] + self.class.resource_type.validproperties
type_properties.delete(:ensure) if type_properties.include? :ensure
type_properties << :guid # append GeneratedUID so we just get the report here
@property_value_cache_hash = self.class.single_report(@resource[:name], *type_properties)
[:uid, :gid].each do |param|
@property_value_cache_hash[param] = @property_value_cache_hash[param].to_i if @property_value_cache_hash and @property_value_cache_hash.include?(param)
end
end
@property_value_cache_hash
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/nameservice/pw.rb | lib/puppet/provider/nameservice/pw.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/nameservice/objectadd'
class Puppet::Provider::NameService
class PW < ObjectAdd
def deletecmd
[command(:pw), "#{@resource.class.name}del", @resource[:name]]
end
def modifycmd(param, value)
[
command(:pw),
"#{@resource.class.name}mod",
@resource[:name],
flag(param),
munge(param, value)
]
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/nameservice/objectadd.rb | lib/puppet/provider/nameservice/objectadd.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/nameservice'
class Puppet::Provider::NameService
class ObjectAdd < Puppet::Provider::NameService
def deletecmd
[command(:delete), @resource[:name]]
end
# Determine the flag to pass to our command.
def flag(name)
name = name.intern if name.is_a? String
self.class.option(name, :flag) || "-" + name.to_s[0, 1]
end
def posixmethod(name)
name = name.intern if name.is_a? String
self.class.option(name, :method) || name
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/freebsd.rb | lib/puppet/provider/package/freebsd.rb | # frozen_string_literal: true
Puppet::Type.type(:package).provide :freebsd, :parent => :openbsd do
desc "The specific form of package management on FreeBSD. This is an
extremely quirky packaging system, in that it freely mixes between
ports and packages. Apparently all of the tools are written in Ruby,
so there are plans to rewrite this support to directly use those
libraries."
commands :pkginfo => "/usr/sbin/pkg_info",
:pkgadd => "/usr/sbin/pkg_add",
:pkgdelete => "/usr/sbin/pkg_delete"
confine 'os.name' => :freebsd
def self.listcmd
command(:pkginfo)
end
def install
if @resource[:source] =~ %r{/$}
if @resource[:source] =~ /^(ftp|https?):/
Puppet::Util.withenv :PACKAGESITE => @resource[:source] do
pkgadd "-r", @resource[:name]
end
else
Puppet::Util.withenv :PKG_PATH => @resource[:source] do
pkgadd @resource[:name]
end
end
else
Puppet.warning _("source is defined but does not have trailing slash, ignoring %{source}") % { source: @resource[:source] } if @resource[:source]
pkgadd "-r", @resource[:name]
end
end
def query
self.class.instances.each do |provider|
if provider.name == @resource.name
return provider.properties
end
end
nil
end
def uninstall
pkgdelete "#{@resource[:name]}-#{@resource.should(:ensure)}"
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/urpmi.rb | lib/puppet/provider/package/urpmi.rb | # frozen_string_literal: true
Puppet::Type.type(:package).provide :urpmi, :parent => :rpm, :source => :rpm do
desc "Support via `urpmi`."
commands :urpmi => "urpmi", :urpmq => "urpmq", :rpm => "rpm", :urpme => "urpme"
defaultfor 'os.name' => [:mandriva, :mandrake]
has_feature :versionable
def install
should = @resource.should(:ensure)
debug "Ensuring => #{should}"
wanted = @resource[:name]
# XXX: We don't actually deal with epochs here.
case should
when true, false, Symbol
# pass
else
# Add the package version
wanted += "-#{should}"
end
urpmi "--auto", wanted
unless query
raise Puppet::Error, _("Package %{name} was not present after trying to install it") % { name: name }
end
end
# What's the latest package version available?
def latest
output = urpmq "-S", @resource[:name]
if output =~ /^#{Regexp.escape @resource[:name]}\s+:\s+.*\(\s+(\S+)\s+\)/
Regexp.last_match(1)
else
# urpmi didn't find updates, pretend the current
# version is the latest
@resource[:ensure]
end
end
def update
# Install in urpmi can be used for update, too
install
end
# For normal package removal the urpmi provider will delegate to the RPM
# provider. If the package to remove has dependencies then uninstalling via
# rpm will fail, but `urpme` can be used to remove a package and its
# dependencies.
def purge
urpme '--auto', @resource[:name]
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/aptrpm.rb | lib/puppet/provider/package/aptrpm.rb | # frozen_string_literal: true
Puppet::Type.type(:package).provide :aptrpm, :parent => :rpm, :source => :rpm do
# Provide sorting functionality
include Puppet::Util::Package
desc "Package management via `apt-get` ported to `rpm`."
has_feature :versionable
commands :aptget => "apt-get"
commands :aptcache => "apt-cache"
commands :rpm => "rpm"
# Mixing confine statements, control expressions, and exception handling
# confuses Rubocop's Layout cops, so we disable them entirely.
# rubocop:disable Layout
if command('rpm')
confine :true => begin
rpm('-ql', 'rpm')
rescue Puppet::ExecutionFailure
false
else
true
end
end
# rubocop:enable Layout
# Install a package using 'apt-get'. This function needs to support
# installing a specific version.
def install
should = @resource.should(:ensure)
str = @resource[:name]
case should
when true, false, Symbol
# pass
else
# Add the package version
str += "=#{should}"
end
cmd = %w[-q -y]
cmd << 'install' << str
aptget(*cmd)
end
# What's the latest package version available?
def latest
output = aptcache :showpkg, @resource[:name]
if output =~ /Versions:\s*\n((\n|.)+)^$/
versions = Regexp.last_match(1)
available_versions = versions.split(/\n/).filter_map { |version|
if version =~ /^([^(]+)\(/
Regexp.last_match(1)
else
warning _("Could not match version '%{version}'") % { version: version }
nil
end
}.sort { |a, b| versioncmp(a, b) }
if available_versions.length == 0
debug "No latest version"
print output if Puppet[:debug]
end
# Get the latest and greatest version number
available_versions.pop
else
err _("Could not match string")
end
end
def update
install
end
def uninstall
aptget "-y", "-q", 'remove', @resource[:name]
end
def purge
aptget '-y', '-q', 'remove', '--purge', @resource[:name]
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/portage.rb | lib/puppet/provider/package/portage.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/package'
require 'fileutils'
Puppet::Type.type(:package).provide :portage, :parent => Puppet::Provider::Package do
desc "Provides packaging support for Gentoo's portage system.
This provider supports the `install_options` and `uninstall_options` attributes, which allows command-line
flags to be passed to emerge. These options should be specified as an array where each element is either a string or a hash."
has_features :install_options, :purgeable, :reinstallable, :uninstall_options, :versionable, :virtual_packages
{
:emerge => '/usr/bin/emerge',
:eix => '/usr/bin/eix',
:qatom_bin => '/usr/bin/qatom',
:update_eix => '/usr/bin/eix-update',
}.each_pair do |name, path|
has_command(name, path) do
environment :HOME => '/'
end
end
confine 'os.family' => :gentoo
defaultfor 'os.family' => :gentoo
def self.instances
result_format = eix_result_format
result_fields = eix_result_fields
limit = eix_limit
version_format = eix_version_format
slot_versions_format = eix_slot_versions_format
installed_versions_format = eix_installed_versions_format
installable_versions_format = eix_install_versions_format
begin
eix_file = File.directory?('/var/cache/eix') ? '/var/cache/eix/portage.eix' : '/var/cache/eix'
update_eix unless FileUtils.uptodate?(eix_file, %w[/usr/bin/eix /usr/portage/metadata/timestamp])
search_output = nil
Puppet::Util.withenv :EIX_LIMIT => limit, :LASTVERSION => version_format, :LASTSLOTVERSIONS => slot_versions_format, :INSTALLEDVERSIONS => installed_versions_format, :STABLEVERSIONS => installable_versions_format do
search_output = eix(*(eix_search_arguments + ['--installed']))
end
packages = []
search_output.each_line do |search_result|
match = result_format.match(search_result)
next unless match
package = {}
result_fields.zip(match.captures) do |field, value|
package[field] = value unless !value or value.empty?
end
package[:provider] = :portage
packages << new(package)
end
packages
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error, detail
end
end
def install
should = @resource.should(:ensure)
cmd = %w[]
name = qatom[:category] ? "#{qatom[:category]}/#{qatom[:pn]}" : qatom[:pn]
name = qatom[:pfx] + name if qatom[:pfx]
name = name + '-' + qatom[:pv] if qatom[:pv]
name = name + '-' + qatom[:pr] if qatom[:pr]
name = name + ':' + qatom[:slot] if qatom[:slot]
cmd << '--update' if [:latest].include?(should)
cmd += install_options if @resource[:install_options]
cmd << name
emerge(*cmd)
end
def uninstall
should = @resource.should(:ensure)
cmd = %w[--rage-clean]
name = qatom[:category] ? "#{qatom[:category]}/#{qatom[:pn]}" : qatom[:pn]
name = qatom[:pfx] + name if qatom[:pfx]
name = name + '-' + qatom[:pv] if qatom[:pv]
name = name + '-' + qatom[:pr] if qatom[:pr]
name = name + ':' + qatom[:slot] if qatom[:slot]
cmd += uninstall_options if @resource[:uninstall_options]
cmd << name
if [:purged].include?(should)
Puppet::Util.withenv :CONFIG_PROTECT => "-*" do
emerge(*cmd)
end
else
emerge(*cmd)
end
end
def reinstall
install
end
def update
install
end
def qatom
output_format = qatom_output_format
result_format = qatom_result_format
result_fields = qatom_result_fields
@atom ||= begin
package_info = {}
# do the search
should = @resource[:ensure]
case should
# The terms present, absent, purged, installed, latest in :ensure
# resolve as Symbols, and we do not need specific package version in this case
when true, false, Symbol
search = @resource[:name]
else
search = '=' + @resource[:name] + '-' + should.to_s
end
search_output = qatom_bin(*[search, '--format', output_format])
# verify if the search found anything
match = result_format.match(search_output)
if match
result_fields.zip(match.captures) do |field, value|
# some fields can be empty or (null) (if we are not passed a category in the package name for instance)
if value == '(null)' || value == '<unset>'
package_info[field] = nil
elsif !value or value.empty?
package_info[field] = nil
else
package_info[field] = value
end
end
end
@atom = package_info
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error, detail
end
end
def qatom_output_format
'"[%[CATEGORY]] [%[PN]] [%[PV]] [%[PR]] [%[SLOT]] [%[pfx]] [%[sfx]]"'
end
def qatom_result_format
/^"\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\](.*)"$/
end
def qatom_result_fields
[:category, :pn, :pv, :pr, :slot, :pfx, :sfx]
end
def self.get_sets
@sets ||= @sets = emerge(*['--list-sets'])
end
def query
limit = self.class.eix_limit
result_format = self.class.eix_result_format
result_fields = self.class.eix_result_fields
version_format = self.class.eix_version_format
slot_versions_format = self.class.eix_slot_versions_format
installed_versions_format = self.class.eix_installed_versions_format
installable_versions_format = self.class.eix_install_versions_format
search_field = qatom[:category] ? '--category-name' : '--name'
search_value = qatom[:category] ? "#{qatom[:category]}/#{qatom[:pn]}" : qatom[:pn]
@eix_result ||= begin
# package sets
package_sets = []
self.class.get_sets.each_line do |package_set|
package_sets << package_set.to_s.strip
end
if @resource[:name] =~ /^@/
if package_sets.include?(@resource[:name][1..].to_s)
return({ :name => (@resource[:name]).to_s, :ensure => '9999', :version_available => nil, :installed_versions => nil, :installable_versions => "9999," })
end
end
eix_file = File.directory?('/var/cache/eix') ? '/var/cache/eix/portage.eix' : '/var/cache/eix'
update_eix unless FileUtils.uptodate?(eix_file, %w[/usr/bin/eix /usr/portage/metadata/timestamp])
search_output = nil
Puppet::Util.withenv :EIX_LIMIT => limit, :LASTVERSION => version_format, :LASTSLOTVERSIONS => slot_versions_format, :INSTALLEDVERSIONS => installed_versions_format, :STABLEVERSIONS => installable_versions_format do
search_output = eix(*(self.class.eix_search_arguments + ['--exact', search_field, search_value]))
end
packages = []
search_output.each_line do |search_result|
match = result_format.match(search_result)
next unless match
package = {}
result_fields.zip(match.captures) do |field, value|
package[field] = value unless !value or value.empty?
end
# dev-lang python [3.4.5] [3.5.2] [2.7.12:2.7,3.4.5:3.4] [2.7.12:2.7,3.4.5:3.4,3.5.2:3.5] https://www.python.org/ An interpreted, interactive, object-oriented programming language
# version_available is what we CAN install / update to
# ensure is what is currently installed
# This DOES NOT choose to install/upgrade or not, just provides current info
# prefer checking versions to slots as versions are finer grained
search = qatom[:pv]
search = search + '-' + qatom[:pr] if qatom[:pr]
if search
package[:version_available] = eix_get_version_for_versions(package[:installable_versions], search)
package[:ensure] = eix_get_version_for_versions(package[:installed_versions], search)
elsif qatom[:slot]
package[:version_available] = eix_get_version_for_slot(package[:slot_versions_available], qatom[:slot])
package[:ensure] = eix_get_version_for_slot(package[:installed_slots], qatom[:slot])
end
package[:ensure] = package[:ensure] || :absent
packages << package
end
case packages.size
when 0
raise Puppet::Error, _("No package found with the specified name [%{name}]") % { name: @resource[:name] }
when 1
@eix_result = packages[0]
else
raise Puppet::Error, _("More than one package with the specified name [%{search_value}], please use the category parameter to disambiguate") % { search_value: search_value }
end
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error, detail
end
end
def latest
query[:version_available]
end
private
def eix_get_version_for_versions(versions, target)
# [2.7.10-r1,2.7.12,3.4.3-r1,3.4.5,3.5.2] 3.5.2
return nil if versions.nil?
versions = versions.split(',')
# [2.7.10-r1 2.7.12 3.4.3-r1 3.4.5 3.5.2]
versions.find { |version| version == target }
# 3.5.2
end
private
def eix_get_version_for_slot(versions_and_slots, slot)
# [2.7.12:2.7 3.4.5:3.4 3.5.2:3.5] 3.5
return nil if versions_and_slots.nil?
versions_and_slots = versions_and_slots.split(',')
# [2.7.12:2.7 3.4.5:3.4 3.5.2:3.5]
versions_and_slots.map! { |version_and_slot| version_and_slot.split(':') }
# [2.7.12: 2.7
# 3.4.5: 3.4
# 3.5.2: 3.5]
version_for_slot = versions_and_slots.find { |version_and_slot| version_and_slot.last == slot }
# [3.5.2: 3.5]
version_for_slot.first if version_for_slot
# 3.5.2
end
def self.eix_search_format
"'<category> <name> [<installedversions:LASTVERSION>] [<bestversion:LASTVERSION>] [<installedversions:LASTSLOTVERSIONS>] [<installedversions:INSTALLEDVERSIONS>] [<availableversions:STABLEVERSIONS>] [<bestslotversions:LASTSLOTVERSIONS>] <homepage> <description>\n'"
end
def self.eix_result_format
/^(\S+)\s+(\S+)\s+\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\]\s+\[(\S*)\]\s+(\S+)\s+(.*)$/
end
def self.eix_result_fields
# ensure:[3.4.5], version_available:[3.5.2], installed_slots:[2.7.12:2.7,3.4.5:3.4], installable_versions:[2.7.10-r1,2.7.12,3.4.3-r1,3.4.5,3.5.2] slot_versions_available:[2.7.12:2.7,3.4.5:3.4,3.5.2:3.5]
[:category, :name, :ensure, :version_available, :installed_slots, :installed_versions, :installable_versions, :slot_versions_available, :vendor, :description]
end
def self.eix_version_format
'{last}<version>{}'
end
def self.eix_slot_versions_format
'{!first},{}<version>:<slot>'
end
def self.eix_installed_versions_format
'{!first},{}<version>'
end
def self.eix_install_versions_format
'{!first}{!last},{}{}{isstable}<version>{}'
end
def self.eix_limit
'0'
end
def self.eix_search_arguments
['--nocolor', '--pure-packages', '--format', eix_search_format]
end
def install_options
join_options(@resource[:install_options])
end
def uninstall_options
join_options(@resource[:uninstall_options])
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/pip2.rb | lib/puppet/provider/package/pip2.rb | # frozen_string_literal: true
# Puppet package provider for Python's `pip2` package management frontend.
# <http://pip.pypa.io/>
Puppet::Type.type(:package).provide :pip2,
:parent => :pip do
desc "Python packages via `pip2`.
This provider supports the `install_options` attribute, which allows command-line flags to be passed to pip2.
These options should be specified as an array where each element is either a string or a hash."
has_feature :installable, :uninstallable, :upgradeable, :versionable, :install_options, :targetable
def self.cmd
["pip2"]
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/zypper.rb | lib/puppet/provider/package/zypper.rb | # frozen_string_literal: true
Puppet::Type.type(:package).provide :zypper, :parent => :rpm, :source => :rpm do
desc "Support for SuSE `zypper` package manager. Found in SLES10sp2+ and SLES11.
This provider supports the `install_options` attribute, which allows command-line flags to be passed to zypper.
These options should be specified as an array where each element is either a
string or a hash."
has_feature :versionable, :install_options, :virtual_packages
commands :zypper => "/usr/bin/zypper"
defaultfor 'os.name' => [:suse, :sles, :sled, :opensuse]
confine 'os.name' => [:suse, :sles, :sled, :opensuse]
# @api private
# Reset the latest version hash to nil
# needed for spec tests to clear cached value
def self.reset!
@latest_versions = nil
end
def self.latest_package_version(package)
if @latest_versions.nil?
@latest_versions = list_updates
end
@latest_versions[package]
end
def self.list_updates
output = zypper 'list-updates'
avail_updates = {}
# split up columns
output.lines.each do |line|
pkg_ver = line.split(/\s*\|\s*/)
# ignore zypper headers
next unless pkg_ver[0] == 'v'
avail_updates[pkg_ver[2]] = pkg_ver[4]
end
avail_updates
end
# on zypper versions <1.0, the version option returns 1
# some versions of zypper output on stderr
def zypper_version
cmd = [self.class.command(:zypper), "--version"]
execute(cmd, { :failonfail => false, :combine => true })
end
def best_version(should)
if should.is_a?(String)
begin
should_range = Puppet::Util::Package::Version::Range.parse(should, Puppet::Util::Package::Version::Rpm)
rescue Puppet::Util::Package::Version::Range::ValidationFailure, Puppet::Util::Package::Version::Rpm::ValidationFailure
Puppet.debug("Cannot parse #{should} as a RPM version range")
return should
end
if should_range.is_a?(Puppet::Util::Package::Version::Range::Eq)
return should
end
versions = []
output = zypper('search', '--match-exact', '--type', 'package', '--uninstalled-only', '-s', @resource[:name])
output.lines.each do |line|
pkg_ver = line.split(/\s*\|\s*/)
next unless pkg_ver[1] == @resource[:name]
begin
rpm_version = Puppet::Util::Package::Version::Rpm.parse(pkg_ver[3])
versions << rpm_version if should_range.include?(rpm_version)
rescue Puppet::Util::Package::Version::Rpm::ValidationFailure
Puppet.debug("Cannot parse #{pkg_ver[3]} as a RPM version")
end
end
return versions.max if versions.any?
Puppet.debug("No available version for package #{@resource[:name]} is included in range #{should_range}")
should
end
end
# Install a package using 'zypper'.
def install
should = @resource.should(:ensure)
debug "Ensuring => #{should}"
wanted = @resource[:name]
# XXX: We don't actually deal with epochs here.
case should
when true, false, Symbol
should = nil
else
# Add the package version
should = best_version(should)
wanted = "#{wanted}-#{should}"
end
# This has been tested with following zypper versions
# SLE 10.4: 0.6.201
# SLE 11.3: 1.6.307
# SLE 12.0: 1.11.14
# Assume that this will work on newer zypper versions
# extract version numbers and convert to integers
major, minor, patch = zypper_version.scan(/\d+/).map(&:to_i)
debug "Detected zypper version #{major}.#{minor}.#{patch}"
# zypper version < 1.0 does not support --quiet flag
if major < 1
quiet = '--terse'
else
quiet = '--quiet'
end
inst_opts = []
inst_opts = install_options if resource[:install_options]
options = []
options << quiet
options << '--no-gpg-check' unless inst_opts.delete('--no-gpg-check').nil?
options << '--no-gpg-checks' unless inst_opts.delete('--no-gpg-checks').nil?
options << :install
# zypper 0.6.13 (OpenSuSE 10.2) does not support auto agree with licenses
options << '--auto-agree-with-licenses' unless major < 1 and minor <= 6 and patch <= 13
options << '--no-confirm'
options += inst_opts unless inst_opts.empty?
# Zypper 0.6.201 doesn't recognize '--name'
# It is unclear where this functionality was introduced, but it
# is present as early as 1.0.13
options << '--name' unless major < 1 || @resource.allow_virtual? || should
options << wanted
zypper(*options)
unless query
raise Puppet::ExecutionFailure, _("Could not find package %{name}") % { name: name }
end
end
# What's the latest package version available?
def latest
self.class.latest_package_version(@resource[:name]) ||
# zypper didn't find updates, pretend the current
# version is the latest
@property_hash[:ensure]
end
def update
# zypper install can be used for update, too
install
end
def uninstall
# extract version numbers and convert to integers
major, minor, _ = zypper_version.scan(/\d+/).map(&:to_i)
if major < 1
super
else
options = [:remove, '--no-confirm']
if major == 1 && minor < 6
options << '--force-resolution'
end
options << @resource[:name]
zypper(*options)
end
end
def insync?(is)
return false if [:purged, :absent].include?(is)
should = @resource[:ensure]
if should.is_a?(String)
begin
should_version = Puppet::Util::Package::Version::Range.parse(should, Puppet::Util::Package::Version::Rpm)
if should_version.is_a?(RPM_VERSION_RANGE::Eq)
return super
end
rescue Puppet::Util::Package::Version::Range::ValidationFailure, Puppet::Util::Package::Version::Rpm::ValidationFailure
Puppet.debug("Cannot parse #{should} as a RPM version range")
return super
end
begin
is_version = Puppet::Util::Package::Version::Rpm.parse(is)
should_version.include?(is_version)
rescue Puppet::Util::Package::Version::Rpm::ValidationFailure
Puppet.debug("Cannot parse #{is} as a RPM version")
end
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/macports.rb | lib/puppet/provider/package/macports.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/package'
require_relative '../../../puppet/provider/command'
Puppet::Type.type(:package).provide :macports, :parent => Puppet::Provider::Package do
desc "Package management using MacPorts on OS X.
Supports MacPorts versions and revisions, but not variants.
Variant preferences may be specified using
[the MacPorts variants.conf file](http://guide.macports.org/chunked/internals.configuration-files.html#internals.configuration-files.variants-conf).
When specifying a version in the Puppet DSL, only specify the version, not the revision.
Revisions are only used internally for ensuring the latest version/revision of a port.
"
confine 'os.name' => :darwin
has_command(:port, "/opt/local/bin/port") do
environment :HOME => "/opt/local"
end
has_feature :installable
has_feature :uninstallable
has_feature :upgradeable
has_feature :versionable
def self.parse_installed_query_line(line)
regex = /(\S+)\s+@(\S+)_(\d+).*\(active\)/
fields = [:name, :ensure, :revision]
hash_from_line(line, regex, fields)
end
def self.parse_info_query_line(line)
regex = /(\S+)\s+(\S+)/
fields = [:version, :revision]
hash_from_line(line, regex, fields)
end
def self.hash_from_line(line, regex, fields)
hash = {}
match = regex.match(line)
if match
fields.zip(match.captures) { |field, value|
hash[field] = value
}
hash[:provider] = name
return hash
end
nil
end
def self.instances
packages = []
port("-q", :installed).each_line do |line|
hash = parse_installed_query_line(line)
if hash
packages << new(hash)
end
end
packages
end
def install
should = @resource.should(:ensure)
if [:latest, :installed, :present].include?(should)
port("-q", :install, @resource[:name])
else
port("-q", :install, @resource[:name], "@#{should}")
end
# MacPorts now correctly exits non-zero with appropriate errors in
# situations where a port cannot be found or installed.
end
def query
result = self.class.parse_installed_query_line(execute([command(:port), "-q", :installed, @resource[:name]], :failonfail => false, :combine => false))
return {} if result.nil?
result
end
def latest
# We need both the version and the revision to be confident
# we've got the latest revision of a specific version
# Note we're still not doing anything with variants here.
info_line = execute([command(:port), "-q", :info, "--line", "--version", "--revision", @resource[:name]], :failonfail => false, :combine => false)
return nil if info_line == ""
newest = self.class.parse_info_query_line(info_line)
if newest
current = query
# We're doing some fiddling behind the scenes here to cope with updated revisions.
# If we're already at the latest version/revision, then just return the version
# so the current and desired values match. Otherwise return version and revision
# to trigger an upgrade to the latest revision.
if newest[:version] == current[:ensure] and newest[:revision] == current[:revision]
return current[:ensure]
else
return "#{newest[:version]}_#{newest[:revision]}"
end
end
nil
end
def uninstall
port("-q", :uninstall, @resource[:name])
end
def update
install
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/hpux.rb | lib/puppet/provider/package/hpux.rb | # frozen_string_literal: true
# HP-UX packaging.
require_relative '../../../puppet/provider/package'
Puppet::Type.type(:package).provide :hpux, :parent => Puppet::Provider::Package do
desc "HP-UX's packaging system."
commands :swinstall => "/usr/sbin/swinstall",
:swlist => "/usr/sbin/swlist",
:swremove => "/usr/sbin/swremove"
confine 'os.name' => "hp-ux"
defaultfor 'os.name' => "hp-ux"
def self.instances
# TODO: This is very hard on HP-UX!
[]
end
# source and name are required
def install
raise ArgumentError, _("source must be provided to install HP-UX packages") unless resource[:source]
args = standard_args + ["-s", resource[:source], resource[:name]]
swinstall(*args)
end
def query
swlist resource[:name]
{ :ensure => :present }
rescue
{ :ensure => :absent }
end
def uninstall
args = standard_args + [resource[:name]]
swremove(*args)
end
def standard_args
["-x", "mount_all_filesystems=false"]
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/opkg.rb | lib/puppet/provider/package/opkg.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/package'
Puppet::Type.type(:package).provide :opkg, :source => :opkg, :parent => Puppet::Provider::Package do
desc "Opkg packaging support. Common on OpenWrt and OpenEmbedded platforms"
commands :opkg => "opkg"
confine 'os.name' => :openwrt
defaultfor 'os.name' => :openwrt
def self.instances
packages = []
execpipe("#{command(:opkg)} list-installed") do |process|
regex = /^(\S+) - (\S+)/
fields = [:name, :ensure]
hash = {}
process.each_line { |line|
match = regex.match(line)
if match
fields.zip(match.captures) { |field, value| hash[field] = value }
hash[:provider] = name
packages << new(hash)
hash = {}
else
warning(_("Failed to match line %{line}") % { line: line })
end
}
end
packages
rescue Puppet::ExecutionFailure
nil
end
def latest
output = opkg("list", @resource[:name])
matches = /^(\S+) - (\S+)/.match(output).captures
matches[1]
end
def install
# OpenWrt package lists are ephemeral, make sure we have at least
# some entries in the list directory for opkg to use
opkg('update') if package_lists.size <= 2
if @resource[:source]
opkg('--force-overwrite', 'install', @resource[:source])
else
opkg('--force-overwrite', 'install', @resource[:name])
end
end
def uninstall
opkg('remove', @resource[:name])
end
def update
install
end
def query
# list out our specific package
output = opkg('list-installed', @resource[:name])
if output =~ /^(\S+) - (\S+)/
return { :ensure => Regexp.last_match(2) }
end
nil
rescue Puppet::ExecutionFailure
{
:ensure => :purged,
:status => 'missing',
:name => @resource[:name],
:error => 'ok',
}
end
private
def package_lists
Dir.entries('/var/opkg-lists/')
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/aix.rb | lib/puppet/provider/package/aix.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/package'
require_relative '../../../puppet/util/package'
Puppet::Type.type(:package).provide :aix, :parent => Puppet::Provider::Package do
desc "Installation from an AIX software directory, using the AIX `installp`
command. The `source` parameter is required for this provider, and should
be set to the absolute path (on the puppet agent machine) of a directory
containing one or more BFF package files.
The `installp` command will generate a table of contents file (named `.toc`)
in this directory, and the `name` parameter (or resource title) that you
specify for your `package` resource must match a package name that exists
in the `.toc` file.
Note that package downgrades are *not* supported; if your resource specifies
a specific version number and there is already a newer version of the package
installed on the machine, the resource will fail with an error message."
# The commands we are using on an AIX box are installed standard
# (except nimclient) nimclient needs the bos.sysmgt.nim.client fileset.
commands :lslpp => "/usr/bin/lslpp",
:installp => "/usr/sbin/installp"
# AIX supports versionable packages with and without a NIM server
has_feature :versionable
confine 'os.name' => [:aix]
defaultfor 'os.name' => :aix
attr_accessor :latest_info
STATE_CODE = {
'A' => :applied,
'B' => :broken,
'C' => :committed,
'E' => :efix_locked,
'O' => :obsolete,
'?' => :inconsistent,
}.freeze
def self.srclistcmd(source)
[command(:installp), "-L", "-d", source]
end
def self.prefetch(packages)
raise Puppet::Error, _("The aix provider can only be used by root") if Process.euid != 0
return unless packages.detect { |_name, package| package.should(:ensure) == :latest }
sources = packages.collect { |_name, package| package[:source] }.uniq.compact
updates = {}
sources.each do |source|
execute(srclistcmd(source)).each_line do |line|
next unless line =~ /^[^#][^:]*:([^:]*):([^:]*)/
current = {}
current[:name] = Regexp.last_match(1)
current[:version] = Regexp.last_match(2)
current[:source] = source
if updates.key?(current[:name])
previous = updates[current[:name]]
updates[current[:name]] = current unless Puppet::Util::Package.versioncmp(previous[:version], current[:version]) == 1
else
updates[current[:name]] = current
end
end
end
packages.each do |name, package|
if updates.key?(name)
package.provider.latest_info = updates[name]
end
end
end
def uninstall
# Automatically process dependencies when installing/uninstalling
# with the -g option to installp.
installp "-gu", @resource[:name]
# installp will return an exit code of zero even if it didn't uninstall
# anything... so let's make sure it worked.
unless query().nil?
self.fail _("Failed to uninstall package '%{name}'") % { name: @resource[:name] }
end
end
def install(useversion = true)
source = @resource[:source]
unless source
self.fail _("A directory is required which will be used to find packages")
end
pkg = @resource[:name]
pkg += " #{@resource.should(:ensure)}" if (!@resource.should(:ensure).is_a? Symbol) and useversion
output = installp "-acgwXY", "-d", source, pkg
# If the package is superseded, it means we're trying to downgrade and we
# can't do that.
if output =~ /^#{Regexp.escape(@resource[:name])}\s+.*\s+Already superseded by.*$/
self.fail _("aix package provider is unable to downgrade packages")
end
pkg_info = query
if pkg_info && [:broken, :inconsistent].include?(pkg_info[:status])
self.fail _("Package '%{name}' is in a %{status} state and requires manual intervention") % { name: @resource[:name], status: pkg_info[:status] }
end
end
def self.pkglist(hash = {})
cmd = [command(:lslpp), "-qLc"]
name = hash[:pkgname]
if name
cmd << name
end
begin
list = execute(cmd).scan(/^[^#][^:]*:([^:]*):([^:]*):[^:]*:[^:]*:([^:])/).collect { |n, e, s|
e = :absent if [:broken, :inconsistent].include?(STATE_CODE[s])
{ :name => n, :ensure => e, :status => STATE_CODE[s], :provider => self.name }
}
rescue Puppet::ExecutionFailure => detail
if hash[:pkgname]
return nil
else
raise Puppet::Error, _("Could not list installed Packages: %{detail}") % { detail: detail }, detail.backtrace
end
end
if hash[:pkgname]
list.shift
else
list
end
end
def self.instances
pkglist.collect do |hash|
new(hash)
end
end
def latest
upd = latest_info
if upd.nil?
raise Puppet::DevError, _("Tried to get latest on a missing package") if properties[:ensure] == :absent
properties[:ensure]
else
(upd[:version]).to_s
end
end
def query
self.class.pkglist(:pkgname => @resource[:name])
end
def update
install(false)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/yum.rb | lib/puppet/provider/package/yum.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/package/version/range'
require_relative '../../../puppet/util/package/version/rpm'
require_relative '../../../puppet/util/rpm_compare'
Puppet::Type.type(:package).provide :yum, :parent => :rpm, :source => :rpm do
# provides Rpm parsing and comparison
include Puppet::Util::RpmCompare
desc "Support via `yum`.
Using this provider's `uninstallable` feature will not remove dependent packages. To
remove dependent packages with this provider use the `purgeable` feature, but note this
feature is destructive and should be used with the utmost care.
This provider supports the `install_options` attribute, which allows command-line flags to be passed to yum.
These options should be specified as an array where each element is either a string or a hash."
has_feature :install_options, :versionable, :virtual_packages, :install_only, :version_ranges
RPM_VERSION = Puppet::Util::Package::Version::Rpm
RPM_VERSION_RANGE = Puppet::Util::Package::Version::Range
commands :cmd => "yum", :rpm => "rpm"
# Mixing confine statements, control expressions, and exception handling
# confuses Rubocop's Layout cops, so we disable them entirely.
# rubocop:disable Layout
if command('rpm')
confine :true => begin
rpm('--version')
rescue Puppet::ExecutionFailure
false
else
true
end
end
# rubocop:enable Layout
defaultfor 'os.name' => :amazon
defaultfor 'os.family' => :redhat, 'os.release.major' => (4..7).to_a
def insync?(is)
return false if [:purged, :absent].include?(is)
return false if is.include?(self.class::MULTIVERSION_SEPARATOR) && !@resource[:install_only]
should = @resource[:ensure]
if should.is_a?(String)
begin
should_version = RPM_VERSION_RANGE.parse(should, RPM_VERSION)
if should_version.is_a?(RPM_VERSION_RANGE::Eq)
return super
end
rescue RPM_VERSION_RANGE::ValidationFailure, RPM_VERSION::ValidationFailure
Puppet.debug("Cannot parse #{should} as a RPM version range")
return super
end
is.split(self.class::MULTIVERSION_SEPARATOR).any? do |version|
is_version = RPM_VERSION.parse(version)
should_version.include?(is_version)
rescue RPM_VERSION::ValidationFailure
Puppet.debug("Cannot parse #{is} as a RPM version")
end
end
end
VERSION_REGEX = /^(?:(\d+):)?(\S+)-(\S+)$/
def self.prefetch(packages)
raise Puppet::Error, _("The yum provider can only be used as root") if Process.euid != 0
super
end
# Retrieve the latest package version information for a given package name
# and combination of repos to enable and disable.
#
# @note If multiple package versions are defined (such as in the case where a
# package is built for multiple architectures), the first package found
# will be used.
#
# @api private
# @param package [String] The name of the package to query
# @param disablerepo [Array<String>] A list of repositories to disable for this query
# @param enablerepo [Array<String>] A list of repositories to enable for this query
# @param disableexcludes [Array<String>] A list of repository excludes to disable for this query
# @return [Hash<Symbol, String>]
def self.latest_package_version(package, disablerepo, enablerepo, disableexcludes)
key = [disablerepo, enablerepo, disableexcludes]
@latest_versions ||= {}
if @latest_versions[key].nil?
@latest_versions[key] = check_updates(disablerepo, enablerepo, disableexcludes)
end
if @latest_versions[key][package]
@latest_versions[key][package].first
end
end
# Search for all installed packages that have newer versions, given a
# combination of repositories to enable and disable.
#
# @api private
# @param disablerepo [Array<String>] A list of repositories to disable for this query
# @param enablerepo [Array<String>] A list of repositories to enable for this query
# @param disableexcludes [Array<String>] A list of repository excludes to disable for this query
# @return [Hash<String, Array<Hash<String, String>>>] All packages that were
# found with a list of found versions for each package.
# rubocop:disable Layout/SingleLineBlockChain
def self.check_updates(disablerepo, enablerepo, disableexcludes)
args = [command(:cmd), 'check-update']
args.concat(disablerepo.map { |repo| ["--disablerepo=#{repo}"] }.flatten)
args.concat(enablerepo.map { |repo| ["--enablerepo=#{repo}"] }.flatten)
args.concat(disableexcludes.map { |repo| ["--disableexcludes=#{repo}"] }.flatten)
output = Puppet::Util::Execution.execute(args, :failonfail => false, :combine => false)
updates = {}
case output.exitstatus
when 100
updates = parse_updates(output)
when 0
debug "#{command(:cmd)} check-update exited with 0; no package updates available."
else
warning _("Could not check for updates, '%{cmd} check-update' exited with %{status}") % { cmd: command(:cmd), status: output.exitstatus }
end
updates
end
# rubocop:enable Layout/SingleLineBlockChain
def self.parse_updates(str)
# Strip off all content that contains Obsoleting, Security: or Update
body = str.partition(/^(Obsoleting|Security:|Update)/).first
updates = Hash.new { |h, k| h[k] = [] }
body.split(/^\s*\n/).each do |line|
line.split.each_slice(3) do |tuple|
next unless tuple[0].include?('.') && tuple[1] =~ VERSION_REGEX
hash = update_to_hash(*tuple[0..1])
# Create entries for both the package name without a version and a
# version since yum considers those as mostly interchangeable.
short_name = hash[:name]
long_name = "#{hash[:name]}.#{hash[:arch]}"
updates[short_name] << hash
updates[long_name] << hash
end
end
updates
end
def self.update_to_hash(pkgname, pkgversion)
# The pkgname string has two parts: name, and architecture. Architecture
# is the portion of the string following the last "." character. All
# characters preceding the final dot are the package name. Parse out
# these two pieces of component data.
name, _, arch = pkgname.rpartition('.')
if name.empty?
raise _("Failed to parse package name and architecture from '%{pkgname}'") % { pkgname: pkgname }
end
match = pkgversion.match(VERSION_REGEX)
epoch = match[1] || '0'
version = match[2]
release = match[3]
{
:name => name,
:epoch => epoch,
:version => version,
:release => release,
:arch => arch,
}
end
def self.clear
@latest_versions = nil
end
def self.error_level
'0'
end
def self.update_command
# In yum both `upgrade` and `update` can be used to update packages
# `yum upgrade` == `yum --obsoletes update`
# Quote the DNF docs:
# "Yum does this if its obsoletes config option is enabled but
# the behavior is not properly documented and can be harmful."
# So we'll stick with the safer option
# If a user wants to remove obsoletes, they can use { :install_options => '--obsoletes' }
# More detail here: https://bugzilla.redhat.com/show_bug.cgi?id=1096506
'update'
end
def best_version(should)
if should.is_a?(String)
begin
should_range = RPM_VERSION_RANGE.parse(should, RPM_VERSION)
if should_range.is_a?(RPM_VERSION_RANGE::Eq)
return should
end
rescue RPM_VERSION_RANGE::ValidationFailure, RPM_VERSION::ValidationFailure
Puppet.debug("Cannot parse #{should} as a RPM version range")
return should
end
versions = []
available_versions(@resource[:name], disablerepo, enablerepo, disableexcludes).each do |version|
rpm_version = RPM_VERSION.parse(version)
versions << rpm_version if should_range.include?(rpm_version)
rescue RPM_VERSION::ValidationFailure
Puppet.debug("Cannot parse #{version} as a RPM version")
end
version = versions.max if versions.any?
if version
version = version.to_s.sub(/^\d+:/, '')
return version
end
Puppet.debug("No available version for package #{@resource[:name]} is included in range #{should_range}")
should
end
end
# rubocop:disable Layout/SingleLineBlockChain
def available_versions(package_name, disablerepo, enablerepo, disableexcludes)
args = [command(:cmd), 'list', package_name, '--showduplicates']
args.concat(disablerepo.map { |repo| ["--disablerepo=#{repo}"] }.flatten)
args.concat(enablerepo.map { |repo| ["--enablerepo=#{repo}"] }.flatten)
args.concat(disableexcludes.map { |repo| ["--disableexcludes=#{repo}"] }.flatten)
output = execute("#{args.compact.join(' ')} | sed -e '1,/Available Packages/ d' | awk '{print $2}'")
output.split("\n")
end
# rubocop:enable Layout/SingleLineBlockChain
def install
wanted = @resource[:name]
error_level = self.class.error_level
update_command = self.class.update_command
# If not allowing virtual packages, do a query to ensure a real package exists
unless @resource.allow_virtual?
execute([command(:cmd), '-d', '0', '-e', error_level, '-y', install_options, :list, wanted].compact)
end
should = @resource.should(:ensure)
debug "Ensuring => #{should}"
operation = :install
case should
when :latest
current_package = query
if current_package && !current_package[:ensure].to_s.empty?
operation = update_command
debug "Ensuring latest, so using #{operation}"
else
debug "Ensuring latest, but package is absent, so using install"
operation = :install
end
should = nil
when true, :present, :installed
# if we have been given a source and we were not asked for a specific
# version feed it to yum directly
if @resource[:source]
wanted = @resource[:source]
debug "Installing directly from #{wanted}"
end
should = nil
when false, :absent
# pass
should = nil
else
if @resource[:source]
# An explicit source was supplied, which means we're ensuring a specific
# version, and also supplying the path to a package that supplies that
# version.
wanted = @resource[:source]
debug "Installing directly from #{wanted}"
else
# No explicit source was specified, so add the package version
should = best_version(should)
wanted += "-#{should}"
if wanted.scan(self.class::ARCH_REGEX)
debug "Detected Arch argument in package! - Moving arch to end of version string"
wanted.gsub!(/(.+)(#{self.class::ARCH_REGEX})(.+)/, '\1\3\2')
end
end
current_package = query
if current_package
if @resource[:install_only]
debug "Updating package #{@resource[:name]} from version #{current_package[:ensure]} to #{should} as install_only packages are never downgraded"
operation = update_command
elsif rpm_compare_evr(should, current_package[:ensure]) < 0
debug "Downgrading package #{@resource[:name]} from version #{current_package[:ensure]} to #{should}"
operation = :downgrade
elsif rpm_compare_evr(should, current_package[:ensure]) > 0
debug "Upgrading package #{@resource[:name]} from version #{current_package[:ensure]} to #{should}"
operation = update_command
end
end
end
# Yum on el-4 and el-5 returns exit status 0 when trying to install a package it doesn't recognize;
# ensure we capture output to check for errors.
no_debug = Puppet.runtime[:facter].value('os.release.major').to_i > 5 ? ["-d", "0"] : []
command = [command(:cmd)] + no_debug + ["-e", error_level, "-y", install_options, operation, wanted].compact
output = execute(command)
if output.to_s =~ /^No package #{wanted} available\.$/
raise Puppet::Error, _("Could not find package %{wanted}") % { wanted: wanted }
end
# If a version was specified, query again to see if it is a matching version
if should
is = query
raise Puppet::Error, _("Could not find package %{name}") % { name: name } unless is
version = is[:ensure]
# FIXME: Should we raise an exception even if should == :latest
# and yum updated us to a version other than @param_hash[:ensure] ?
raise Puppet::Error, _("Failed to update to version %{should}, got version %{version} instead") % { should: should, version: version } unless
insync?(version)
end
end
# What's the latest package version available?
def latest
upd = self.class.latest_package_version(@resource[:name], disablerepo, enablerepo, disableexcludes)
if upd.nil?
# Yum didn't find updates, pretend the current version is the latest
debug "Yum didn't find updates, current version (#{properties[:ensure]}) is the latest"
version = properties[:ensure]
raise Puppet::DevError, _("Tried to get latest on a missing package") if version == :absent || version == :purged
version
else
# FIXME: there could be more than one update for a package
# because of multiarch
"#{upd[:epoch]}:#{upd[:version]}-#{upd[:release]}"
end
end
def update
# Install in yum can be used for update, too
install
end
def purge
execute([command(:cmd), "-y", :erase, @resource[:name]])
end
private
def enablerepo
scan_options(resource[:install_options], '--enablerepo')
end
def disablerepo
scan_options(resource[:install_options], '--disablerepo')
end
def disableexcludes
scan_options(resource[:install_options], '--disableexcludes')
end
# Scan a structure that looks like the package type 'install_options'
# structure for all hashes that have a specific key.
#
# @api private
# @param options [Array<String | Hash>, nil] The options structure. If the
# options are nil an empty array will be returned.
# @param key [String] The key to look for in all contained hashes
# @return [Array<String>] All hash values with the given key.
def scan_options(options, key)
return [] unless options.is_a?(Enumerable)
values =
options.map do |repo|
value =
if repo.is_a?(String)
next unless repo.include?('=')
Hash[*repo.strip.split('=')] # make it a hash
else
repo
end
value[key]
end
values.compact.uniq
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/pkgutil.rb | lib/puppet/provider/package/pkgutil.rb | # frozen_string_literal: true
# Packaging using Peter Bonivart's pkgutil program.
Puppet::Type.type(:package).provide :pkgutil, :parent => :sun, :source => :sun do
desc "Package management using Peter Bonivart's ``pkgutil`` command on Solaris."
pkgutil_bin = "pkgutil"
if FileTest.executable?("/opt/csw/bin/pkgutil")
pkgutil_bin = "/opt/csw/bin/pkgutil"
end
confine 'os.family' => :solaris
has_command(:pkguti, pkgutil_bin) do
environment :HOME => ENV.fetch('HOME', nil)
end
def self.healthcheck
unless Puppet::FileSystem.exist?("/var/opt/csw/pkgutil/admin")
Puppet.notice _("It is highly recommended you create '/var/opt/csw/pkgutil/admin'.")
Puppet.notice _("See /var/opt/csw/pkgutil")
end
correct_wgetopts = false
["/opt/csw/etc/pkgutil.conf", "/etc/opt/csw/pkgutil.conf"].each do |confpath|
File.open(confpath) do |conf|
conf.each_line { |line| correct_wgetopts = true if line =~ /^\s*wgetopts\s*=.*(-nv|-q|--no-verbose|--quiet)/ }
end
end
unless correct_wgetopts
Puppet.notice _("It is highly recommended that you set 'wgetopts=-nv' in your pkgutil.conf.")
end
end
def self.instances(hash = {})
healthcheck
# Use the available pkg list (-a) to work out aliases
aliases = {}
availlist.each do |pkg|
aliases[pkg[:name]] = pkg[:alias]
end
# The -c pkglist lists installed packages
pkginsts = []
output = pkguti(["-c"])
parse_pkglist(output).each do |pkg|
pkg.delete(:avail)
pkginsts << new(pkg)
# Create a second instance with the alias if it's different
pkgalias = aliases[pkg[:name]]
next unless pkgalias and pkg[:name] != pkgalias
apkg = pkg.dup
apkg[:name] = pkgalias
pkginsts << new(apkg)
end
pkginsts
end
# Turns a pkgutil -a listing into hashes with the common alias, full
# package name and available version
def self.availlist
output = pkguti ["-a"]
output.split("\n").filter_map do |line|
next if line =~ /^common\s+package/ # header of package list
next if noise?(line)
if line =~ /\s*(\S+)\s+(\S+)\s+(.*)/
{ :alias => Regexp.last_match(1), :name => Regexp.last_match(2), :avail => Regexp.last_match(3) }
else
Puppet.warning _("Cannot match %{line}") % { line: line }
end
end
end
# Turn our pkgutil -c listing into a hash for a single package.
def pkgsingle(resource)
# The --single option speeds up the execution, because it queries
# the package management system for one package only.
command = ["-c", "--single", resource[:name]]
self.class.parse_pkglist(run_pkgutil(resource, command), { :justme => resource[:name] })
end
# Turn our pkgutil -c listing into a bunch of hashes.
def self.parse_pkglist(output, hash = {})
output = output.split("\n")
if output[-1] == "Not in catalog"
Puppet.warning _("Package not in pkgutil catalog: %{package}") % { package: hash[:justme] }
return nil
end
list = output.filter_map do |line|
next if line =~ /installed\s+catalog/ # header of package list
next if noise?(line)
pkgsplit(line)
end
if hash[:justme]
# Single queries may have been for an alias so return the name requested
if list.any?
list[-1][:name] = hash[:justme]
list[-1]
end
else
list.reject! { |h| h[:ensure] == :absent }
list
end
end
# Identify common types of pkgutil noise as it downloads catalogs etc
def self.noise?(line)
return true if line =~ /^#/
return true if line =~ /^Checking integrity / # use_gpg
return true if line =~ /^gpg: / # gpg verification
return true if line =~ /^=+> / # catalog fetch
return true if line =~ /\d+:\d+:\d+ URL:/ # wget without -q
false
end
# Split the different lines into hashes.
def self.pkgsplit(line)
if line =~ /\s*(\S+)\s+(\S+)\s+(.*)/
hash = {}
hash[:name] = Regexp.last_match(1)
hash[:ensure] = if Regexp.last_match(2) == "notinst"
:absent
else
Regexp.last_match(2)
end
hash[:avail] = Regexp.last_match(3)
if hash[:avail] =~ /^SAME\s*$/
hash[:avail] = hash[:ensure]
end
# Use the name method, so it works with subclasses.
hash[:provider] = name
hash
else
Puppet.warning _("Cannot match %{line}") % { line: line }
nil
end
end
def run_pkgutil(resource, *args)
# Allow source to be one or more URLs pointing to a repository that all
# get passed to pkgutil via one or more -t options
if resource[:source]
sources = [resource[:source]].flatten
pkguti(*[sources.map { |src| ["-t", src] }, *args].flatten)
else
pkguti(*args.flatten)
end
end
def install
run_pkgutil @resource, "-y", "-i", @resource[:name]
end
# Retrieve the version from the current package file.
def latest
hash = pkgsingle(@resource)
hash[:avail] if hash
end
def query
hash = pkgsingle(@resource)
hash || { :ensure => :absent }
end
def update
run_pkgutil @resource, "-y", "-u", @resource[:name]
end
def uninstall
run_pkgutil @resource, "-y", "-r", @resource[:name]
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/sunfreeware.rb | lib/puppet/provider/package/sunfreeware.rb | # frozen_string_literal: true
# At this point, it's an exact copy of the Blastwave stuff.
Puppet::Type.type(:package).provide :sunfreeware, :parent => :blastwave, :source => :sun do
desc "Package management using sunfreeware.com's `pkg-get` command on Solaris.
At this point, support is exactly the same as `blastwave` support and
has not actually been tested."
commands :pkgget => "pkg-get"
confine 'os.family' => :solaris
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/up2date.rb | lib/puppet/provider/package/up2date.rb | # frozen_string_literal: true
Puppet::Type.type(:package).provide :up2date, :parent => :rpm, :source => :rpm do
desc "Support for Red Hat's proprietary `up2date` package update
mechanism."
commands :up2date => "/usr/sbin/up2date-nox"
defaultfor 'os.family' => :redhat, 'os.distro.release.full' => ["2.1", "3", "4"]
confine 'os.family' => :redhat
# Install a package using 'up2date'.
def install
up2date "-u", @resource[:name]
unless query
raise Puppet::ExecutionFailure, _("Could not find package %{name}") % { name: name }
end
end
# What's the latest package version available?
def latest
# up2date can only get a list of *all* available packages?
output = up2date "--showall"
if output =~ /^#{Regexp.escape @resource[:name]}-(\d+.*)\.\w+/
Regexp.last_match(1)
else
# up2date didn't find updates, pretend the current
# version is the latest
@property_hash[:ensure]
end
end
def update
# Install in up2date can be used for update, too
install
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/pacman.rb | lib/puppet/provider/package/pacman.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/package'
require 'set'
require 'uri'
Puppet::Type.type(:package).provide :pacman, :parent => Puppet::Provider::Package do
desc "Support for the Package Manager Utility (pacman) used in Archlinux.
This provider supports the `install_options` attribute, which allows command-line flags to be passed to pacman.
These options should be specified as an array where each element is either a string or a hash."
# If yaourt is installed, we can make use of it
def self.yaourt?
@yaourt ||= Puppet::FileSystem.exist?('/usr/bin/yaourt')
end
commands :pacman => "/usr/bin/pacman"
# Yaourt is a common AUR helper which, if installed, we can use to query the AUR
commands :yaourt => "/usr/bin/yaourt" if yaourt?
confine 'os.name' => [:archlinux, :manjarolinux, :artix]
defaultfor 'os.name' => [:archlinux, :manjarolinux, :artix]
has_feature :install_options
has_feature :uninstall_options
has_feature :upgradeable
has_feature :virtual_packages
has_feature :purgeable
# Checks if a given name is a group
def self.group?(name)
!pacman('--sync', '--groups', name).empty?
rescue Puppet::ExecutionFailure
# pacman returns an expected non-zero exit code when the name is not a group
false
end
# Install a package using 'pacman', or 'yaourt' if available.
# Installs quietly, without confirmation or progress bar, updates package
# list from servers defined in pacman.conf.
def install
if @resource[:source]
install_from_file
else
install_from_repo
end
unless query
fail(_("Could not find package '%{name}'") % { name: @resource[:name] })
end
end
# Fetch the list of packages and package groups that are currently installed on the system.
# Only package groups that are fully installed are included. If a group adds packages over time, it will not
# be considered as fully installed any more, and we would install the new packages on the next run.
# If a group removes packages over time, nothing will happen. This is intended.
def self.instances
instances = []
# Get the installed packages
installed_packages = get_installed_packages
installed_packages.sort_by { |k, _| k }.each do |package, version|
instances << new(to_resource_hash(package, version))
end
# Get the installed groups
get_installed_groups(installed_packages).each do |group, version|
instances << new(to_resource_hash(group, version))
end
instances
end
# returns a hash package => version of installed packages
def self.get_installed_packages
packages = {}
execpipe([command(:pacman), "--query"]) do |pipe|
# pacman -Q output is 'packagename version-rel'
regex = /^(\S+)\s(\S+)/
pipe.each_line do |line|
match = regex.match(line)
if match
packages[match.captures[0]] = match.captures[1]
else
warning(_("Failed to match line '%{line}'") % { line: line })
end
end
end
packages
rescue Puppet::ExecutionFailure
fail(_("Error getting installed packages"))
end
# returns a hash of group => version of installed groups
def self.get_installed_groups(installed_packages, filter = nil)
groups = {}
begin
# Build a hash of group name => list of packages
command = [command(:pacman), '--sync', '-gg']
command << filter if filter
execpipe(command) do |pipe|
pipe.each_line do |line|
name, package = line.split
packages = (groups[name] ||= [])
packages << package
end
end
# Remove any group that doesn't have all its packages installed
groups.delete_if do |_, packages|
!packages.all? { |package| installed_packages[package] }
end
# Replace the list of packages with a version string consisting of packages that make up the group
groups.each do |name, packages|
groups[name] = packages.sort.map { |package| "#{package} #{installed_packages[package]}" }.join ', '
end
rescue Puppet::ExecutionFailure
# pacman returns an expected non-zero exit code when the filter name is not a group
raise unless filter
end
groups
end
# Because Archlinux is a rolling release based distro, installing a package
# should always result in the newest release.
def update
# Install in pacman can be used for update, too
install
end
# We rescue the main check from Pacman with a check on the AUR using yaourt, if installed
def latest
resource_name = @resource[:name]
# If target is a group, construct the group version
return pacman("--sync", "--print", "--print-format", "%n %v", resource_name).lines.map(&:chomp).sort.join(', ') if self.class.group?(resource_name)
# Start by querying with pacman first
# If that fails, retry using yaourt against the AUR
pacman_check = true
begin
if pacman_check
output = pacman "--sync", "--print", "--print-format", "%v", resource_name
output.chomp
else
output = yaourt "-Qma", resource_name
output.split("\n").each do |line|
return line.split[1].chomp if line =~ /^aur/
end
end
rescue Puppet::ExecutionFailure
if pacman_check and self.class.yaourt?
pacman_check = false # now try the AUR
retry
else
raise
end
end
end
# Queries information for a package or package group
def query
installed_packages = self.class.get_installed_packages
resource_name = @resource[:name]
# Check for the resource being a group
version = self.class.get_installed_groups(installed_packages, resource_name)[resource_name]
if version
unless @resource.allow_virtual?
warning(_("%{resource_name} is a group, but allow_virtual is false.") % { resource_name: resource_name })
return nil
end
else
version = installed_packages[resource_name]
end
# Return nil if no package or group found
return nil unless version
self.class.to_resource_hash(resource_name, version)
end
def self.to_resource_hash(name, version)
{
:name => name,
:ensure => version,
:provider => self.name
}
end
# Removes a package from the system.
def uninstall
remove_package(false)
end
def purge
remove_package(true)
end
private
def remove_package(purge_configs = false)
resource_name = @resource[:name]
is_group = self.class.group?(resource_name)
fail(_("Refusing to uninstall package group %{resource_name}, because allow_virtual is false.") % { resource_name: resource_name }) if is_group && !@resource.allow_virtual?
cmd = %w[--noconfirm --noprogressbar]
cmd += uninstall_options if @resource[:uninstall_options]
cmd << "--remove"
cmd << '--recursive' if is_group
cmd << '--nosave' if purge_configs
cmd << resource_name
if self.class.yaourt?
yaourt(*cmd)
else
pacman(*cmd)
end
end
def install_options
join_options(@resource[:install_options])
end
def uninstall_options
join_options(@resource[:uninstall_options])
end
def install_from_file
source = @resource[:source]
begin
source_uri = URI.parse source
rescue => detail
self.fail Puppet::Error, _("Invalid source '%{source}': %{detail}") % { source: source, detail: detail }, detail
end
source = case source_uri.scheme
when nil then source
when /https?/i then source
when /ftp/i then source
when /file/i then source_uri.path
when /puppet/i
fail _("puppet:// URL is not supported by pacman")
else
fail _("Source %{source} is not supported by pacman") % { source: source }
end
pacman "--noconfirm", "--noprogressbar", "--update", source
end
def install_from_repo
resource_name = @resource[:name]
# Refuse to install if not allowing virtual packages and the resource is a group
fail(_("Refusing to install package group %{resource_name}, because allow_virtual is false.") % { resource_name: resource_name }) if self.class.group?(resource_name) && !@resource.allow_virtual?
cmd = %w[--noconfirm --needed --noprogressbar]
cmd += install_options if @resource[:install_options]
cmd << "--sync" << resource_name
if self.class.yaourt?
yaourt(*cmd)
else
pacman(*cmd)
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/dnf.rb | lib/puppet/provider/package/dnf.rb | # frozen_string_literal: true
Puppet::Type.type(:package).provide :dnf, :parent => :yum do
desc "Support via `dnf`.
Using this provider's `uninstallable` feature will not remove dependent packages. To
remove dependent packages with this provider use the `purgeable` feature, but note this
feature is destructive and should be used with the utmost care.
This provider supports the `install_options` attribute, which allows command-line flags to be passed to dnf.
These options should be specified as an array where each element is either
a string or a hash."
has_feature :install_options, :versionable, :virtual_packages, :install_only, :version_ranges
commands :cmd => "dnf", :rpm => "rpm"
# Note: this confine was borrowed from the Yum provider. The
# original purpose (from way back in 2007) was to make sure we
# never try to use RPM on a machine without it. We think this
# has probably become obsolete with the way `commands` work, so
# we should investigate removing it at some point.
#
# Mixing confine statements, control expressions, and exception handling
# confuses Rubocop's Layout cops, so we disable them entirely.
# rubocop:disable Layout
if command('rpm')
confine :true => begin
rpm('--version')
rescue Puppet::ExecutionFailure
false
else
true
end
end
# rubocop:enable Layout
defaultfor 'os.name' => :fedora
notdefaultfor 'os.name' => :fedora, 'os.release.major' => (19..21).to_a
defaultfor 'os.family' => :redhat
notdefaultfor 'os.family' => :redhat, 'os.release.major' => (4..7).to_a
defaultfor 'os.name' => :amazon, 'os.release.major' => ["2023"]
def self.update_command
# In DNF, update is deprecated for upgrade
'upgrade'
end
# The value to pass to DNF as its error output level.
# DNF differs from Yum slightly with regards to error outputting.
#
# @param None
# @return [String]
def self.error_level
'1'
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/openbsd.rb | lib/puppet/provider/package/openbsd.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/package'
# Packaging on OpenBSD. Doesn't work anywhere else that I know of.
Puppet::Type.type(:package).provide :openbsd, :parent => Puppet::Provider::Package do
desc "OpenBSD's form of `pkg_add` support.
This provider supports the `install_options` and `uninstall_options`
attributes, which allow command-line flags to be passed to pkg_add and pkg_delete.
These options should be specified as an array where each element is either a
string or a hash."
commands :pkginfo => "pkg_info",
:pkgadd => "pkg_add",
:pkgdelete => "pkg_delete"
defaultfor 'os.name' => :openbsd
confine 'os.name' => :openbsd
has_feature :versionable
has_feature :install_options
has_feature :uninstall_options
has_feature :upgradeable
has_feature :supports_flavors
def self.instances
packages = []
begin
execpipe(listcmd) do |process|
# our regex for matching pkg_info output
regex = /^(.*)-(\d[^-]*)-?([\w-]*)(.*)$/
fields = [:name, :ensure, :flavor]
hash = {}
# now turn each returned line into a package object
process.each_line { |line|
match = regex.match(line.split[0])
if match
fields.zip(match.captures) { |field, value|
hash[field] = value
}
hash[:provider] = name
packages << new(hash)
hash = {}
else
unless line =~ /Updating the pkgdb/
# Print a warning on lines we can't match, but move
# on, since it should be non-fatal
warning(_("Failed to match line %{line}") % { line: line })
end
end
}
end
packages
rescue Puppet::ExecutionFailure
nil
end
end
def self.listcmd
[command(:pkginfo), "-a"]
end
def latest
parse_pkgconf
if @resource[:source][-1, 1] == ::File::SEPARATOR
e_vars = { 'PKG_PATH' => @resource[:source] }
else
e_vars = {}
end
if @resource[:flavor]
query = "#{@resource[:name]}--#{@resource[:flavor]}"
else
query = @resource[:name]
end
output = Puppet::Util.withenv(e_vars) { pkginfo "-Q", query }
version = properties[:ensure]
if output.nil? or output.size == 0 or output =~ /Error from /
debug "Failed to query for #{resource[:name]}"
return version
else
# Remove all fuzzy matches first.
output = output.split.select { |p| p =~ /^#{resource[:name]}-(\d[^-]*)-?(\w*)/ }.join
debug "pkg_info -Q for #{resource[:name]}: #{output}"
end
if output =~ /^#{resource[:name]}-(\d[^-]*)-?(\w*) \(installed\)$/
debug "Package is already the latest available"
version
else
match = /^(.*)-(\d[^-]*)-?(\w*)$/.match(output)
debug "Latest available for #{resource[:name]}: #{match[2]}"
if version.to_sym == :absent || version.to_sym == :purged
return match[2]
end
vcmp = version.split('.').map(&:to_i) <=> match[2].split('.').map(&:to_i)
if vcmp > 0
# The locally installed package may actually be newer than what a mirror
# has. Log it at debug, but ignore it otherwise.
debug "Package #{resource[:name]} #{version} newer then available #{match[2]}"
version
else
match[2]
end
end
end
def update
install(true)
end
def parse_pkgconf
unless @resource[:source]
if Puppet::FileSystem.exist?("/etc/pkg.conf")
File.open("/etc/pkg.conf", "rb").readlines.each do |line|
matchdata = line.match(/^installpath\s*=\s*(.+)\s*$/i)
if matchdata
@resource[:source] = matchdata[1]
else
matchdata = line.match(/^installpath\s*\+=\s*(.+)\s*$/i)
if matchdata
if @resource[:source].nil?
@resource[:source] = matchdata[1]
else
@resource[:source] += ":" + matchdata[1]
end
end
end
end
unless @resource[:source]
raise Puppet::Error,
_("No valid installpath found in /etc/pkg.conf and no source was set")
end
else
raise Puppet::Error,
_("You must specify a package source or configure an installpath in /etc/pkg.conf")
end
end
end
def install(latest = false)
cmd = []
parse_pkgconf
if @resource[:source][-1, 1] == ::File::SEPARATOR
e_vars = { 'PKG_PATH' => @resource[:source] }
full_name = get_full_name(latest)
else
e_vars = {}
full_name = @resource[:source]
end
cmd << install_options
cmd << full_name
if latest
cmd.unshift('-rz')
end
Puppet::Util.withenv(e_vars) { pkgadd cmd.flatten.compact }
end
def get_full_name(latest = false)
# In case of a real update (i.e., the package already exists) then
# pkg_add(8) can handle the flavors. However, if we're actually
# installing with 'latest', we do need to handle the flavors. This is
# done so we can feed pkg_add(8) the full package name to install to
# prevent ambiguity.
if latest && resource[:flavor]
"#{resource[:name]}--#{resource[:flavor]}"
elsif latest
# Don't depend on get_version for updates.
@resource[:name]
else
# If :ensure contains a version, use that instead of looking it up.
# This allows for installing packages with the same stem, but multiple
# version such as openldap-server.
if @resource[:ensure].to_s =~ /(\d[^-]*)$/
use_version = @resource[:ensure]
else
use_version = get_version
end
[@resource[:name], use_version, @resource[:flavor]].join('-').gsub(/-+$/, '')
end
end
def get_version
execpipe([command(:pkginfo), "-I", @resource[:name]]) do |process|
# our regex for matching pkg_info output
regex = /^(.*)-(\d[^-]*)-?(\w*)(.*)$/
master_version = 0
version = -1
process.each_line do |line|
match = regex.match(line.split[0])
next unless match
# now we return the first version, unless ensure is latest
version = match.captures[1]
return version unless @resource[:ensure] == "latest"
master_version = version unless master_version > version
end
return master_version unless master_version == 0
return '' if version == -1
raise Puppet::Error, _("%{version} is not available for this package") % { version: version }
end
rescue Puppet::ExecutionFailure
nil
end
def query
# Search for the version info
if pkginfo(@resource[:name]) =~ /Information for (inst:)?#{@resource[:name]}-(\S+)/
{ :ensure => Regexp.last_match(2) }
else
nil
end
end
def install_options
join_options(resource[:install_options])
end
def uninstall_options
join_options(resource[:uninstall_options])
end
def uninstall
pkgdelete uninstall_options.flatten.compact, @resource[:name]
end
def purge
pkgdelete "-c", "-q", @resource[:name]
end
def flavor
@property_hash[:flavor]
end
def flavor=(value)
if flavor != @resource.should(:flavor)
uninstall
install
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/puppetserver_gem.rb | lib/puppet/provider/package/puppetserver_gem.rb | # frozen_string_literal: true
require 'English'
unless Puppet::Util::Platform.jruby_fips?
require 'rubygems/commands/list_command'
end
require 'stringio'
require 'uri'
# Ruby gems support.
Puppet::Type.type(:package).provide :puppetserver_gem, :parent => :gem do
desc "Puppet Server Ruby Gem support. If a URL is passed via `source`, then
that URL is appended to the list of remote gem repositories which by default
contains rubygems.org; To ensure that only the specified source is used also
pass `--clear-sources` in via `install_options`; if a source is present but
is not a valid URL, it will be interpreted as the path to a local gem file.
If source is not present at all, the gem will be installed from the default
gem repositories."
has_feature :versionable, :install_options, :uninstall_options
confine :feature => :hocon
# see SERVER-2578
confine :fips_enabled => false
# Define the default provider package command name, as the parent 'gem' provider is targetable.
# Required by Puppet::Provider::Package::Targetable::resource_or_provider_command
def self.provider_command
command(:puppetservercmd)
end
# The gem command uses HOME to locate a gemrc file.
# CommandDefiner in provider.rb will set failonfail, combine, and environment.
has_command(:puppetservercmd, '/opt/puppetlabs/bin/puppetserver') do
environment(HOME: ENV.fetch('HOME', nil))
end
def self.gemlist(options)
command_options = %w[gem list]
if options[:local]
command_options << '--local'
else
command_options << '--remote'
end
if options[:source]
command_options << '--source' << options[:source]
end
if options[:justme]
gem_regex = '\A' + options[:justme] + '\z'
command_options << gem_regex
end
if options[:local]
list = execute_rubygems_list_command(command_options)
else
begin
list = puppetservercmd(command_options)
rescue Puppet::ExecutionFailure => detail
raise Puppet::Error, _("Could not list gems: %{detail}") % { detail: detail }, detail.backtrace
end
end
# When `/tmp` is mounted `noexec`, `puppetserver gem list` will output:
# *** LOCAL GEMS ***
# causing gemsplit to output:
# Warning: Could not match *** LOCAL GEMS ***
gem_list = list
.lines
.select { |x| x =~ /^(\S+)\s+\((.+)\)/ }
.map { |set| gemsplit(set) }
if options[:justme]
gem_list.shift
else
gem_list
end
end
def install(useversion = true)
command_options = %w[gem install]
command_options += install_options if resource[:install_options]
command_options << '-v' << resource[:ensure] if (!resource[:ensure].is_a? Symbol) && useversion
command_options << '--no-document'
if resource[:source]
begin
uri = URI.parse(resource[:source])
rescue => detail
self.fail Puppet::Error, _("Invalid source '%{uri}': %{detail}") % { uri: uri, detail: detail }, detail
end
case uri.scheme
when nil
# no URI scheme => interpret the source as a local file
command_options << resource[:source]
when /file/i
command_options << uri.path
when 'puppet'
# we don't support puppet:// URLs (yet)
raise Puppet::Error, _('puppet:// URLs are not supported as gem sources')
else
# interpret it as a gem repository
command_options << '--source' << resource[:source].to_s << resource[:name]
end
else
command_options << resource[:name]
end
output = puppetservercmd(command_options)
# Apparently, some gem versions don't exit non-0 on failure.
self.fail _("Could not install: %{output}") % { output: output.chomp } if output.include?('ERROR')
end
def uninstall
command_options = %w[gem uninstall]
command_options << '--executables' << '--all' << resource[:name]
command_options += uninstall_options if resource[:uninstall_options]
output = puppetservercmd(command_options)
# Apparently, some gem versions don't exit non-0 on failure.
self.fail _("Could not uninstall: %{output}") % { output: output.chomp } if output.include?('ERROR')
end
private
# The puppetserver gem cli command is very slow, since it starts a JVM.
#
# Instead, for the list subcommand (which is executed with every puppet run),
# use the rubygems library from puppet ruby: setting GEM_HOME and GEM_PATH
# to the default values, or the values in the puppetserver configuration file.
#
# The rubygems library cannot access java platform gems,
# for example: json (1.8.3 java)
# but java platform gems should not be managed by this (or any) provider.
def self.execute_rubygems_list_command(command_options)
puppetserver_default_gem_home = '/opt/puppetlabs/server/data/puppetserver/jruby-gems'
puppetserver_default_vendored_jruby_gems = '/opt/puppetlabs/server/data/puppetserver/vendored-jruby-gems'
puppet_default_vendor_gems = '/opt/puppetlabs/puppet/lib/ruby/vendor_gems'
puppetserver_default_gem_path = [puppetserver_default_gem_home, puppetserver_default_vendored_jruby_gems, puppet_default_vendor_gems].join(':')
pe_puppetserver_conf_file = '/etc/puppetlabs/puppetserver/conf.d/pe-puppet-server.conf'
os_puppetserver_conf_file = '/etc/puppetlabs/puppetserver/puppetserver.conf'
puppetserver_conf_file = Puppet.runtime[:facter].value(:pe_server_version) ? pe_puppetserver_conf_file : os_puppetserver_conf_file
puppetserver_conf = Hocon.load(puppetserver_conf_file)
gem_env = {}
if puppetserver_conf.empty? || puppetserver_conf.key?('jruby-puppet') == false
gem_env['GEM_HOME'] = puppetserver_default_gem_home
gem_env['GEM_PATH'] = puppetserver_default_gem_path
else
gem_env['GEM_HOME'] = puppetserver_conf['jruby-puppet'].key?('gem-home') ? puppetserver_conf['jruby-puppet']['gem-home'] : puppetserver_default_gem_home
gem_env['GEM_PATH'] = puppetserver_conf['jruby-puppet'].key?('gem-path') ? puppetserver_conf['jruby-puppet']['gem-path'].join(':') : puppetserver_default_gem_path
end
gem_env['GEM_SPEC_CACHE'] = "/tmp/#{$PROCESS_ID}"
# Remove the 'gem' from the command_options
command_options.shift
gem_out = execute_gem_command(Puppet::Type::Package::ProviderPuppet_gem.provider_command, command_options, gem_env)
# There is no method exclude default gems from the local gem list,
# for example: psych (default: 2.2.2)
# but default gems should not be managed by this (or any) provider.
gem_list = gem_out.lines.reject { |gem| gem =~ / \(default: / }
gem_list.join("\n")
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/pkgng.rb | lib/puppet/provider/package/pkgng.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/package'
Puppet::Type.type(:package).provide :pkgng, :parent => Puppet::Provider::Package do
desc "A PkgNG provider for FreeBSD and DragonFly."
commands :pkg => "/usr/local/sbin/pkg"
confine 'os.name' => [:freebsd, :dragonfly]
defaultfor 'os.name' => [:freebsd, :dragonfly]
has_feature :versionable
has_feature :upgradeable
has_feature :install_options
def self.get_query
pkg(['query', '-a', '%n %v %o'])
end
def self.get_resource_info(name)
pkg(['query', '%n %v %o', name])
end
def self.cached_version_list
# rubocop:disable Naming/MemoizedInstanceVariableName
@version_list ||= get_version_list
# rubocop:enable Naming/MemoizedInstanceVariableName
end
def self.get_version_list
@version_list = pkg(['version', '-voRL='])
end
def self.get_latest_version(origin)
latest_version = cached_version_list.lines.find { |l| l =~ /^#{origin} / }
if latest_version
_name, compare, status = latest_version.chomp.split(' ', 3)
if ['!', '?'].include?(compare)
return nil
end
latest_version = status.split(' ').last.split(')').first
return latest_version
end
nil
end
def self.parse_pkg_query_line(line)
name, version, origin = line.chomp.split(' ', 3)
latest_version = get_latest_version(origin) || version
{
:ensure => version,
:name => name,
:provider => self.name,
:origin => origin,
:version => version,
:latest => latest_version
}
end
def self.instances
packages = []
begin
info = get_query
get_version_list
unless info
return packages
end
info.lines.each do |line|
hash = parse_pkg_query_line(line)
packages << new(hash)
end
packages
rescue Puppet::ExecutionFailure
[]
end
end
def self.prefetch(resources)
packages = instances
resources.each_key do |name|
provider = packages.find { |p| p.name == name or p.origin == name }
if provider
resources[name].provider = provider
end
end
end
def repo_tag_from_urn(urn)
# extract repo tag from URN: urn:freebsd:repo:<tag>
match = /^urn:freebsd:repo:(.+)$/.match(urn)
raise ArgumentError urn.inspect unless match
match[1]
end
def install
source = resource[:source]
source = URI(source) unless source.nil?
# Ensure we handle the version
case resource[:ensure]
when true, false, Symbol
installname = resource[:name]
else
# If resource[:name] is actually an origin (e.g. 'www/curl' instead of
# just 'curl'), drop the category prefix. pkgng doesn't support version
# pinning with the origin syntax (pkg install curl-1.2.3 is valid, but
# pkg install www/curl-1.2.3 is not).
if resource[:name] =~ %r{/}
installname = resource[:name].split('/')[1] + '-' + resource[:ensure]
else
installname = resource[:name] + '-' + resource[:ensure]
end
end
if !source # install using default repo logic
args = ['install', '-qy']
elsif source.scheme == 'urn' # install from repo named in URN
tag = repo_tag_from_urn(source.to_s)
args = ['install', '-qy', '-r', tag]
else # add package located at URL
args = ['add', '-q']
installname = source.to_s
end
args += install_options if @resource[:install_options]
args << installname
pkg(args)
end
def uninstall
pkg(['remove', '-qy', resource[:name]])
end
def query
begin
output = self.class.get_resource_info(resource[:name])
rescue Puppet::ExecutionFailure
return nil
end
self.class.parse_pkg_query_line(output)
end
def version
@property_hash[:version]
end
def version=
pkg(['install', '-qfy', "#{resource[:name]}-#{resource[:version]}"])
end
# Upgrade to the latest version
def update
install
end
# Return the latest version of the package
def latest
debug "returning the latest #{@property_hash[:name].inspect} version #{@property_hash[:latest].inspect}"
@property_hash[:latest]
end
def origin
@property_hash[:origin]
end
def install_options
join_options(@resource[:install_options])
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/pkgin.rb | lib/puppet/provider/package/pkgin.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/package'
Puppet::Type.type(:package).provide :pkgin, :parent => Puppet::Provider::Package do
desc "Package management using pkgin, a binary package manager for pkgsrc."
commands :pkgin => "pkgin"
defaultfor 'os.name' => [:smartos, :netbsd]
has_feature :installable, :uninstallable, :upgradeable, :versionable
def self.parse_pkgin_line(package)
# e.g.
# vim-7.2.446;Vim editor (vi clone) without GUI
match, name, version, status = *package.match(/([^\s;]+)-([^\s;]+)[;\s](=|>|<)?.+$/)
if match
{
:name => name,
:status => status,
:ensure => version
}
end
end
def self.prefetch(packages)
super
# Without -f, no fresh pkg_summary files are downloaded
pkgin("-yf", :update)
end
def self.instances
pkgin(:list).split("\n").map do |package|
new(parse_pkgin_line(package))
end
end
def query
packages = parse_pkgsearch_line
if packages.empty?
if @resource[:ensure] == :absent
notice _("declared as absent but unavailable %{file}:%{line}") % { file: @resource.file, line: resource.line }
return false
else
@resource.fail _("No candidate to be installed")
end
end
packages.first.update(:ensure => :absent)
end
def parse_pkgsearch_line
packages = pkgin(:search, resource[:name]).split("\n")
return [] if packages.length == 1
# Remove the last three lines of help text.
packages.slice!(-4, 4)
pkglist = packages.map { |line| self.class.parse_pkgin_line(line) }
pkglist.select { |package| resource[:name] == package[:name] }
end
def install
if @resource[:ensure].is_a?(String)
pkgin("-y", :install, "#{resource[:name]}-#{resource[:ensure]}")
else
pkgin("-y", :install, resource[:name])
end
end
def uninstall
pkgin("-y", :remove, resource[:name])
end
def latest
package = parse_pkgsearch_line.detect { |p| p[:status] == '<' }
return properties[:ensure] unless package
package[:ensure]
end
def update
pkgin("-y", :install, resource[:name])
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/sun.rb | lib/puppet/provider/package/sun.rb | # frozen_string_literal: true
# Sun packaging.
require_relative '../../../puppet/provider/package'
Puppet::Type.type(:package).provide :sun, :parent => Puppet::Provider::Package do
desc "Sun's packaging system. Requires that you specify the source for
the packages you're managing.
This provider supports the `install_options` attribute, which allows command-line flags to be passed to pkgadd.
These options should be specified as an array where each element is either a string
or a hash."
commands :pkginfo => "/usr/bin/pkginfo",
:pkgadd => "/usr/sbin/pkgadd",
:pkgrm => "/usr/sbin/pkgrm"
confine 'os.family' => :solaris
defaultfor 'os.family' => :solaris
has_feature :install_options
self::Namemap = {
"PKGINST" => :name,
"CATEGORY" => :category,
"ARCH" => :platform,
"VERSION" => :ensure,
"BASEDIR" => :root,
"VENDOR" => :vendor,
"DESC" => :description,
}
def self.namemap(hash)
self::Namemap.keys.inject({}) do |hsh, k|
hsh.merge(self::Namemap[k] => hash[k])
end
end
def self.parse_pkginfo(out)
# collect all the lines with : in them, and separate them out by ^$
pkgs = []
pkg = {}
out.each_line do |line|
case line.chomp
when /^\s*$/
pkgs << pkg unless pkg.empty?
pkg = {}
when /^\s*([^:]+):\s+(.+)$/
pkg[Regexp.last_match(1)] = Regexp.last_match(2)
end
end
pkgs << pkg unless pkg.empty?
pkgs
end
def self.instances
parse_pkginfo(pkginfo('-l')).collect do |p|
hash = namemap(p)
hash[:provider] = :sun
new(hash)
end
end
# Get info on a package, optionally specifying a device.
def info2hash(device = nil)
args = ['-l']
args << '-d' << device if device
args << @resource[:name]
begin
pkgs = self.class.parse_pkginfo(pkginfo(*args))
errmsg = case pkgs.size
when 0
'No message'
when 1
pkgs[0]['ERROR']
end
return self.class.namemap(pkgs[0]) if errmsg.nil?
# according to commit 41356a7 some errors do not raise an exception
# so even though pkginfo passed, we have to check the actual output
raise Puppet::Error, _("Unable to get information about package %{name} because of: %{errmsg}") % { name: @resource[:name], errmsg: errmsg }
rescue Puppet::ExecutionFailure
{ :ensure => :absent }
end
end
# Retrieve the version from the current package file.
def latest
info2hash(@resource[:source])[:ensure]
end
def query
info2hash
end
# only looking for -G now
def install
# TRANSLATORS Sun refers to the company name, do not translate
raise Puppet::Error, _("Sun packages must specify a package source") unless @resource[:source]
options = {
:adminfile => @resource[:adminfile],
:responsefile => @resource[:responsefile],
:source => @resource[:source],
:cmd_options => @resource[:install_options]
}
pkgadd prepare_cmd(options)
end
def uninstall
pkgrm prepare_cmd(:adminfile => @resource[:adminfile])
end
# Remove the old package, and install the new one. This will probably
# often fail.
def update
uninstall if (@property_hash[:ensure] || info2hash[:ensure]) != :absent
install
end
def prepare_cmd(opt)
[if_have_value('-a', opt[:adminfile]),
if_have_value('-r', opt[:responsefile]),
if_have_value('-d', opt[:source]),
opt[:cmd_options] || [],
['-n', @resource[:name]]].flatten
end
def if_have_value(prefix, value)
if value
[prefix, value]
else
[]
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/blastwave.rb | lib/puppet/provider/package/blastwave.rb | # frozen_string_literal: true
# Packaging using Blastwave's pkg-get program.
Puppet::Type.type(:package).provide :blastwave, :parent => :sun, :source => :sun do
desc "Package management using Blastwave.org's `pkg-get` command on Solaris."
pkgget = "pkg-get"
pkgget = "/opt/csw/bin/pkg-get" if FileTest.executable?("/opt/csw/bin/pkg-get")
confine 'os.family' => :solaris
commands :pkgget => pkgget
def pkgget_with_cat(*args)
Puppet::Util.withenv(:PAGER => "/usr/bin/cat") { pkgget(*args) }
end
def self.extended(mod)
unless command(:pkgget) != "pkg-get"
raise Puppet::Error,
_("The pkg-get command is missing; blastwave packaging unavailable")
end
unless Puppet::FileSystem.exist?("/var/pkg-get/admin")
Puppet.notice _("It is highly recommended you create '/var/pkg-get/admin'.")
Puppet.notice _("See /var/pkg-get/admin-fullauto")
end
end
def self.instances(hash = {})
blastlist(hash).collect do |bhash|
bhash.delete(:avail)
new(bhash)
end
end
# Turn our blastwave listing into a bunch of hashes.
def self.blastlist(hash)
command = ["-c"]
command << hash[:justme] if hash[:justme]
output = Puppet::Util.withenv(:PAGER => "/usr/bin/cat") { pkgget command }
list = output.split("\n").filter_map do |line|
next if line =~ /^#/
next if line =~ /^WARNING/
next if line =~ /localrev\s+remoterev/
blastsplit(line)
end
if hash[:justme]
list[0]
else
list.reject! { |h|
h[:ensure] == :absent
}
list
end
end
# Split the different lines into hashes.
def self.blastsplit(line)
if line =~ /\s*(\S+)\s+((\[Not installed\])|(\S+))\s+(\S+)/
hash = {}
hash[:name] = Regexp.last_match(1)
hash[:ensure] = if Regexp.last_match(2) == "[Not installed]"
:absent
else
Regexp.last_match(2)
end
hash[:avail] = Regexp.last_match(5)
hash[:avail] = hash[:ensure] if hash[:avail] == "SAME"
# Use the name method, so it works with subclasses.
hash[:provider] = name
hash
else
Puppet.warning _("Cannot match %{line}") % { line: line }
nil
end
end
def install
pkgget_with_cat "-f", :install, @resource[:name]
end
# Retrieve the version from the current package file.
def latest
hash = self.class.blastlist(:justme => @resource[:name])
hash[:avail]
end
def query
hash = self.class.blastlist(:justme => @resource[:name])
hash || { :ensure => :absent }
end
# Remove the old package, and install the new one
def update
pkgget_with_cat "-f", :upgrade, @resource[:name]
end
def uninstall
pkgget_with_cat "-f", :remove, @resource[:name]
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/appdmg.rb | lib/puppet/provider/package/appdmg.rb | # frozen_string_literal: true
# Jeff McCune <mccune.jeff@gmail.com>
# Changed to app.dmg by: Udo Waechter <root@zoide.net>
# Mac OS X Package Installer which handles application (.app)
# bundles inside an Apple Disk Image.
#
# Motivation: DMG files provide a true HFS file system
# and are easier to manage.
#
# Note: the 'apple' Provider checks for the package name
# in /L/Receipts. Since we possibly install multiple apps from
# a single source, we treat the source .app.dmg file as the package name.
# As a result, we store installed .app.dmg file names
# in /var/db/.puppet_appdmg_installed_<name>
require_relative '../../../puppet/provider/package'
require_relative '../../../puppet/util/plist' if Puppet.features.cfpropertylist?
Puppet::Type.type(:package).provide(:appdmg, :parent => Puppet::Provider::Package) do
desc "Package management which copies application bundles to a target."
confine 'os.name' => :darwin
confine :feature => :cfpropertylist
commands :hdiutil => "/usr/bin/hdiutil"
commands :curl => "/usr/bin/curl"
commands :ditto => "/usr/bin/ditto"
# JJM We store a cookie for each installed .app.dmg in /var/db
def self.instances_by_name
Dir.entries("/var/db").find_all { |f|
f =~ /^\.puppet_appdmg_installed_/
}.collect do |f|
name = f.sub(/^\.puppet_appdmg_installed_/, '')
yield name if block_given?
name
end
end
def self.instances
instances_by_name.collect do |name|
new(:name => name, :provider => :appdmg, :ensure => :installed)
end
end
def self.installapp(source, name, orig_source)
appname = File.basename(source);
ditto "--rsrc", source, "/Applications/#{appname}"
Puppet::FileSystem.open("/var/db/.puppet_appdmg_installed_#{name}", nil, "w:UTF-8") do |t|
t.print "name: '#{name}'\n"
t.print "source: '#{orig_source}'\n"
end
end
def self.installpkgdmg(source, name)
require 'open-uri'
cached_source = source
tmpdir = Dir.mktmpdir
begin
if %r{\A[A-Za-z][A-Za-z0-9+\-.]*://} =~ cached_source
cached_source = File.join(tmpdir, name)
begin
curl "-o", cached_source, "-C", "-", "-L", "-s", "--url", source
Puppet.debug "Success: curl transferred [#{name}]"
rescue Puppet::ExecutionFailure
Puppet.debug "curl did not transfer [#{name}]. Falling back to slower open-uri transfer methods."
cached_source = source
end
end
File.open(cached_source) do |dmg|
xml_str = hdiutil "mount", "-plist", "-nobrowse", "-readonly", "-mountrandom", "/tmp", dmg.path
ptable = Puppet::Util::Plist.parse_plist(xml_str)
# JJM Filter out all mount-paths into a single array, discard the rest.
mounts = ptable['system-entities'].collect { |entity|
entity['mount-point']
}.select { |mountloc|; mountloc }
begin
found_app = false
mounts.each do |fspath|
Dir.entries(fspath).select { |f|
f =~ /\.app$/i
}.each do |pkg|
found_app = true
installapp("#{fspath}/#{pkg}", name, source)
end
end
Puppet.debug "Unable to find .app in .appdmg. #{name} will not be installed." unless found_app
ensure
hdiutil "eject", mounts[0]
end
end
ensure
FileUtils.remove_entry_secure(tmpdir, true)
end
end
def query
Puppet::FileSystem.exist?("/var/db/.puppet_appdmg_installed_#{@resource[:name]}") ? { :name => @resource[:name], :ensure => :present } : nil
end
def install
source = @resource[:source]
unless source
self.fail _("Mac OS X PKG DMGs must specify a package source.")
end
name = @resource[:name]
unless name
self.fail _("Mac OS X PKG DMGs must specify a package name.")
end
self.class.installpkgdmg(source, name)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/apple.rb | lib/puppet/provider/package/apple.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/package'
# OS X Packaging sucks. We can install packages, but that's about it.
Puppet::Type.type(:package).provide :apple, :parent => Puppet::Provider::Package do
desc "Package management based on OS X's built-in packaging system. This is
essentially the simplest and least functional package system in existence --
it only supports installation; no deletion or upgrades. The provider will
automatically add the `.pkg` extension, so leave that off when specifying
the package name."
confine 'os.name' => :darwin
commands :installer => "/usr/sbin/installer"
def self.instances
instance_by_name.collect do |name|
new(
:name => name,
:provider => :apple,
:ensure => :installed
)
end
end
def self.instance_by_name
Dir.entries("/Library/Receipts").find_all { |f|
f =~ /\.pkg$/
}.collect { |f|
name = f.sub(/\.pkg/, '')
yield name if block_given?
name
}
end
def query
Puppet::FileSystem.exist?("/Library/Receipts/#{@resource[:name]}.pkg") ? { :name => @resource[:name], :ensure => :present } : nil
end
def install
source = @resource[:source]
unless source
self.fail _("Mac OS X packages must specify a package source")
end
installer "-pkg", source, "-target", "/"
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/pip3.rb | lib/puppet/provider/package/pip3.rb | # frozen_string_literal: true
# Puppet package provider for Python's `pip3` package management frontend.
# <http://pip.pypa.io/>
Puppet::Type.type(:package).provide :pip3,
:parent => :pip do
desc "Python packages via `pip3`.
This provider supports the `install_options` attribute, which allows command-line flags to be passed to pip3.
These options should be specified as an array where each element is either a string or a hash."
has_feature :installable, :uninstallable, :upgradeable, :versionable, :install_options, :targetable
def self.cmd
["pip3"]
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/pip.rb | lib/puppet/provider/package/pip.rb | # frozen_string_literal: true
# Puppet package provider for Python's `pip` package management frontend.
# <http://pip.pypa.io/>
require_relative '../../../puppet/util/package/version/pip'
require_relative '../../../puppet/util/package/version/range'
require_relative '../../../puppet/provider/package_targetable'
Puppet::Type.type(:package).provide :pip, :parent => ::Puppet::Provider::Package::Targetable do
desc "Python packages via `pip`.
This provider supports the `install_options` attribute, which allows command-line flags to be passed to pip.
These options should be specified as an array where each element is either a string or a hash."
has_feature :installable, :uninstallable, :upgradeable, :versionable, :version_ranges, :install_options, :targetable
PIP_VERSION = Puppet::Util::Package::Version::Pip
PIP_VERSION_RANGE = Puppet::Util::Package::Version::Range
# Override the specificity method to return 1 if pip is not set as default provider
def self.specificity
match = default_match
length = match ? match.length : 0
return 1 if length == 0
super
end
# Define the default provider package command name when the provider is targetable.
# Required by Puppet::Provider::Package::Targetable::resource_or_provider_command
def self.provider_command
# Ensure pip can upgrade pip, which usually puts pip into a new path /usr/local/bin/pip (compared to /usr/bin/pip)
cmd.map { |c| which(c) }.find { |c| !c.nil? }
end
def self.cmd
if Puppet::Util::Platform.windows?
["pip.exe"]
else
%w[pip pip-python pip2 pip-2]
end
end
def self.pip_version(command)
version = nil
execpipe [quote(command), '--version'] do |process|
process.collect do |line|
md = line.strip.match(/^pip (\d+\.\d+\.?\d*).*$/)
if md
version = md[1]
break
end
end
end
raise Puppet::Error, _("Cannot resolve pip version") unless version
version
end
# Return an array of structured information about every installed package
# that's managed by `pip` or an empty array if `pip` is not available.
def self.instances(target_command = nil)
if target_command
command = target_command
validate_command(command)
else
command = provider_command
end
packages = []
return packages unless command
command_options = ['freeze']
command_version = pip_version(command)
if compare_pip_versions(command_version, '8.1.0') >= 0
command_options << '--all'
end
execpipe [quote(command), command_options] do |process|
process.collect do |line|
pkg = parse(line)
next unless pkg
pkg[:command] = command
packages << new(pkg)
end
end
# Pip can also upgrade pip, but it's not listed in freeze so need to special case it
# Pip list would also show pip installed version, but "pip list" doesn't exist for older versions of pip (E.G v1.0)
# Not needed when "pip freeze --all" is available.
if compare_pip_versions(command_version, '8.1.0') == -1
packages << new({ :ensure => command_version, :name => File.basename(command), :provider => name, :command => command })
end
packages
end
# Parse lines of output from `pip freeze`, which are structured as:
# _package_==_version_ or _package_===_version_
# or _package_ @ someURL@_version_
def self.parse(line)
if line.chomp =~ /^([^=]+)===?([^=]+)$/
{ :ensure => Regexp.last_match(2), :name => Regexp.last_match(1), :provider => name }
elsif line.chomp =~ /^([^@]+) @ [^@]+@(.+)$/
{ :ensure => Regexp.last_match(2), :name => Regexp.last_match(1), :provider => name }
end
end
# Return structured information about a particular package or `nil`
# if the package is not installed or `pip` itself is not available.
def query
command = resource_or_provider_command
self.class.validate_command(command)
self.class.instances(command).each do |pkg|
return pkg.properties if @resource[:name].casecmp(pkg.name).zero?
end
nil
end
# Return latest version available for current package
def latest
command = resource_or_provider_command
self.class.validate_command(command)
command_version = self.class.pip_version(command)
if self.class.compare_pip_versions(command_version, '1.5.4') == -1
available_versions_with_old_pip.last
else
available_versions_with_new_pip(command_version).last
end
end
def self.compare_pip_versions(x, y)
Puppet::Util::Package::Version::Pip.compare(x, y)
rescue PIP_VERSION::ValidationFailure => ex
Puppet.debug("Cannot compare #{x} and #{y}. #{ex.message} Falling through default comparison mechanism.")
Puppet::Util::Package.versioncmp(x, y)
end
# Use pip CLI to look up versions from PyPI repositories,
# honoring local pip config such as custom repositories.
def available_versions
command = resource_or_provider_command
self.class.validate_command(command)
command_version = self.class.pip_version(command)
if self.class.compare_pip_versions(command_version, '1.5.4') == -1
available_versions_with_old_pip
else
available_versions_with_new_pip(command_version)
end
end
def available_versions_with_new_pip(command_version)
command = resource_or_provider_command
self.class.validate_command(command)
command_and_options = [self.class.quote(command), 'install', "#{@resource[:name]}==9!0dev0+x"]
extra_arg = list_extra_flags(command_version)
command_and_options << extra_arg if extra_arg
command_and_options << install_options if @resource[:install_options]
execpipe command_and_options do |process|
process.collect do |line|
# PIP OUTPUT: Could not find a version that satisfies the requirement example==versionplease (from versions: 1.2.3, 4.5.6)
next unless line =~ /from versions: (.+)\)/
versionList = Regexp.last_match(1).split(', ').sort do |x, y|
self.class.compare_pip_versions(x, y)
end
return versionList
end
end
[]
end
def available_versions_with_old_pip
command = resource_or_provider_command
self.class.validate_command(command)
Dir.mktmpdir("puppet_pip") do |dir|
command_and_options = [self.class.quote(command), 'install', (@resource[:name]).to_s, '-d', dir.to_s, '-v']
command_and_options << install_options if @resource[:install_options]
execpipe command_and_options do |process|
process.collect do |line|
# PIP OUTPUT: Using version 0.10.1 (newest of versions: 1.2.3, 4.5.6)
next unless line =~ /Using version .+? \(newest of versions: (.+?)\)/
versionList = Regexp.last_match(1).split(', ').sort do |x, y|
self.class.compare_pip_versions(x, y)
end
return versionList
end
end
return []
end
end
# Finds the most suitable version available in a given range
def best_version(should_range)
included_available_versions = []
available_versions.each do |version|
version = PIP_VERSION.parse(version)
included_available_versions.push(version) if should_range.include?(version)
end
included_available_versions.sort!
return included_available_versions.last unless included_available_versions.empty?
Puppet.debug("No available version for package #{@resource[:name]} is included in range #{should_range}")
should_range
end
def get_install_command_options
should = @resource[:ensure]
command_options = %w[install -q]
command_options += install_options if @resource[:install_options]
if @resource[:source]
if should.is_a?(String)
command_options << "#{@resource[:source]}@#{should}#egg=#{@resource[:name]}"
else
command_options << "#{@resource[:source]}#egg=#{@resource[:name]}"
end
return command_options
end
if should == :latest
command_options << "--upgrade" << @resource[:name]
return command_options
end
unless should.is_a?(String)
command_options << @resource[:name]
return command_options
end
begin
should_range = PIP_VERSION_RANGE.parse(should, PIP_VERSION)
rescue PIP_VERSION_RANGE::ValidationFailure, PIP_VERSION::ValidationFailure
Puppet.debug("Cannot parse #{should} as a pip version range, falling through.")
command_options << "#{@resource[:name]}==#{should}"
return command_options
end
if should_range.is_a?(PIP_VERSION_RANGE::Eq)
command_options << "#{@resource[:name]}==#{should}"
return command_options
end
should = best_version(should_range)
if should == should_range
# when no suitable version for the given range was found, let pip handle
if should.is_a?(PIP_VERSION_RANGE::MinMax)
command_options << "#{@resource[:name]} #{should.split.join(',')}"
else
command_options << "#{@resource[:name]} #{should}"
end
else
command_options << "#{@resource[:name]}==#{should}"
end
command_options
end
# Install a package. The ensure parameter may specify installed,
# latest, a version number, or, in conjunction with the source
# parameter, an SCM revision. In that case, the source parameter
# gives the fully-qualified URL to the repository.
def install
command = resource_or_provider_command
self.class.validate_command(command)
command_options = get_install_command_options
execute([command, command_options])
end
# Uninstall a package. Uninstall won't work reliably on Debian/Ubuntu unless this issue gets fixed.
# http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=562544
def uninstall
command = resource_or_provider_command
self.class.validate_command(command)
command_options = ["uninstall", "-y", "-q", @resource[:name]]
execute([command, command_options])
end
def update
install
end
def install_options
join_options(@resource[:install_options])
end
def insync?(is)
return false unless is && is != :absent
begin
should = @resource[:ensure]
should_range = PIP_VERSION_RANGE.parse(should, PIP_VERSION)
rescue PIP_VERSION_RANGE::ValidationFailure, PIP_VERSION::ValidationFailure
Puppet.debug("Cannot parse #{should} as a pip version range")
return false
end
begin
is_version = PIP_VERSION.parse(is)
rescue PIP_VERSION::ValidationFailure
Puppet.debug("Cannot parse #{is} as a pip version")
return false
end
should_range.include?(is_version)
end
# Quoting is required if the path to the pip command contains spaces.
# Required for execpipe() but not execute(), as execute() already does this.
def self.quote(path)
if path.include?(" ")
"\"#{path}\""
else
path
end
end
private
def list_extra_flags(command_version)
klass = self.class
if klass.compare_pip_versions(command_version, '20.2.4') == 1 &&
klass.compare_pip_versions(command_version, '21.1') == -1
'--use-deprecated=legacy-resolver'
end
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/portupgrade.rb | lib/puppet/provider/package/portupgrade.rb | # frozen_string_literal: true
# Whole new package, so include pack stuff
require_relative '../../../puppet/provider/package'
Puppet::Type.type(:package).provide :portupgrade, :parent => Puppet::Provider::Package do
include Puppet::Util::Execution
desc "Support for FreeBSD's ports using the portupgrade ports management software.
Use the port's full origin as the resource name. eg (ports-mgmt/portupgrade)
for the portupgrade port."
## has_features is usually autodetected based on defs below.
# has_features :installable, :uninstallable, :upgradeable
commands :portupgrade => "/usr/local/sbin/portupgrade",
:portinstall => "/usr/local/sbin/portinstall",
:portversion => "/usr/local/sbin/portversion",
:portuninstall => "/usr/local/sbin/pkg_deinstall",
:portinfo => "/usr/sbin/pkg_info"
## Activate this only once approved by someone important.
# defaultfor 'os.name' => :freebsd
# Remove unwanted environment variables.
%w[INTERACTIVE UNAME].each do |var|
if ENV.include?(var)
ENV.delete(var)
end
end
######## instances sub command (builds the installed packages list)
def self.instances
Puppet.debug "portupgrade.rb Building packages list from installed ports"
# regex to match output from pkg_info
regex = /^(\S+)-([^-\s]+):(\S+)$/
# Corresponding field names
fields = [:portname, :ensure, :portorigin]
# define Temporary hash used, packages array of hashes
hash = Hash.new
packages = []
# exec command
cmdline = ["-aoQ"]
begin
output = portinfo(*cmdline)
rescue Puppet::ExecutionFailure => e
raise Puppet::Error.new(output, e)
end
# split output and match it and populate temp hash
output.split("\n").each { |data|
# reset hash to nil for each line
hash.clear
match = regex.match(data)
if match
# Output matched regex
fields.zip(match.captures) { |field, value|
hash[field] = value
}
# populate the actual :name field from the :portorigin
# Set :provider to this object name
hash[:name] = hash[:portorigin]
hash[:provider] = name
# Add to the full packages listing
packages << new(hash)
else
# unrecognised output from pkg_info
Puppet.debug "portupgrade.Instances() - unable to match output: #{data}"
end
}
# return the packages array of hashes
packages
end
######## Installation sub command
def install
Puppet.debug "portupgrade.install() - Installation call on #{@resource[:name]}"
# -M: yes, we're a batch, so don't ask any questions
cmdline = ["-M BATCH=yes", @resource[:name]]
# FIXME: it's possible that portinstall prompts for data so locks up.
begin
output = portinstall(*cmdline)
rescue Puppet::ExecutionFailure => e
raise Puppet::Error.new(output, e)
end
if output =~ /\*\* No such /
raise Puppet::ExecutionFailure, _("Could not find package %{name}") % { name: @resource[:name] }
end
# No return code required, so do nil to be clean
nil
end
######## Latest subcommand (returns the latest version available, or current version if installed is latest)
def latest
Puppet.debug "portupgrade.latest() - Latest check called on #{@resource[:name]}"
# search for latest version available, or return current version.
# cmdline = "portversion -v <portorigin>", returns "<portname> <code> <stuff>"
# or "** No matching package found: <portname>"
cmdline = ["-v", @resource[:name]]
begin
output = portversion(*cmdline)
rescue Puppet::ExecutionFailure => e
raise Puppet::Error.new(output, e)
end
# Check: output format.
if output =~ /^\S+-([^-\s]+)\s+(\S)\s+(.*)/
installedversion = Regexp.last_match(1)
comparison = Regexp.last_match(2)
otherdata = Regexp.last_match(3)
# Only return a new version number when it's clear that there is a new version
# all others return the current version so no unexpected 'upgrades' occur.
case comparison
when "=", ">"
Puppet.debug "portupgrade.latest() - Installed package is latest (#{installedversion})"
installedversion
when "<"
# "portpkg-1.7_5 < needs updating (port has 1.14)"
# "portpkg-1.7_5 < needs updating (port has 1.14) (=> 'newport/pkg')
if otherdata =~ /\(port has (\S+)\)/
newversion = Regexp.last_match(1)
Puppet.debug "portupgrade.latest() - Installed version needs updating to (#{newversion})"
newversion
else
Puppet.debug "portupgrade.latest() - Unable to determine new version from (#{otherdata})"
installedversion
end
when "?", "!", "#"
Puppet.debug "portupgrade.latest() - Comparison Error reported from portversion (#{output})"
installedversion
else
Puppet.debug "portupgrade.latest() - Unknown code from portversion output (#{output})"
installedversion
end
elsif output =~ /^\*\* No matching package /
# error: output not parsed correctly, error out with nil.
# Seriously - this section should never be called in a perfect world.
# as verification that the port is installed has already happened in query.
raise Puppet::ExecutionFailure, _("Could not find package %{name}") % { name: @resource[:name] }
else
# Any other error (dump output to log)
raise Puppet::ExecutionFailure, _("Unexpected output from portversion: %{output}") % { output: output }
end
end
###### Query subcommand - return a hash of details if exists, or nil if it doesn't.
# Used to make sure the package is installed
def query
Puppet.debug "portupgrade.query() - Called on #{@resource[:name]}"
cmdline = ["-qO", @resource[:name]]
begin
output = portinfo(*cmdline)
rescue Puppet::ExecutionFailure => e
raise Puppet::Error.new(output, e)
end
# Check: if output isn't in the right format, return nil
if output =~ /^(\S+)-([^-\s]+)/
# Fill in the details
hash = Hash.new
hash[:portorigin] = name
hash[:portname] = Regexp.last_match(1)
hash[:ensure] = Regexp.last_match(2)
# If more details are required, then we can do another pkg_info
# query here and parse out that output and add to the hash
# return the hash to the caller
hash
else
Puppet.debug "portupgrade.query() - package (#{@resource[:name]}) not installed"
nil
end
end
####### Uninstall command
def uninstall
Puppet.debug "portupgrade.uninstall() - called on #{@resource[:name]}"
# Get full package name from port origin to uninstall with
cmdline = ["-qO", @resource[:name]]
begin
output = portinfo(*cmdline)
rescue Puppet::ExecutionFailure => e
raise Puppet::Error.new(output, e)
end
if output =~ /^(\S+)/
# output matches, so uninstall it
portuninstall Regexp.last_match(1)
end
end
######## Update/upgrade command
def update
Puppet.debug "portupgrade.update() - called on (#{@resource[:name]})"
cmdline = ["-qO", @resource[:name]]
begin
output = portinfo(*cmdline)
rescue Puppet::ExecutionFailure => e
raise Puppet::Error.new(output, e)
end
if output =~ /^(\S+)/
# output matches, so upgrade the software
cmdline = ["-M BATCH=yes", Regexp.last_match(1)]
begin
output = portupgrade(*cmdline)
rescue Puppet::ExecutionFailure => e
raise Puppet::Error.new(output, e)
end
end
end
## EOF
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/xbps.rb | lib/puppet/provider/package/xbps.rb | # frozen_string_literal: true
require_relative "../../../puppet/provider/package"
Puppet::Type.type(:package).provide :xbps, :parent => Puppet::Provider::Package do
desc "Support for the Package Manager Utility (xbps) used in VoidLinux.
This provider supports the `install_options` attribute, which allows command-line flags to be passed to xbps-install.
These options should be specified as an array where each element is either a string or a hash."
commands :xbps_install => "/usr/bin/xbps-install"
commands :xbps_remove => "/usr/bin/xbps-remove"
commands :xbps_query => "/usr/bin/xbps-query"
commands :xbps_pkgdb => "/usr/bin/xbps-pkgdb"
confine 'os.name' => :void
defaultfor 'os.name' => :void
has_feature :install_options, :uninstall_options, :upgradeable, :holdable, :virtual_packages
def self.defaultto_allow_virtual
false
end
# Fetch the list of packages that are currently installed on the system.
def self.instances
packages = []
execpipe([command(:xbps_query), "-l"]) do |pipe|
# xbps-query -l output is 'ii package-name-version desc'
regex = /^\S+\s(\S+)-(\S+)\s+\S+/
pipe.each_line do |line|
match = regex.match(line.chomp)
if match
packages << new({ name: match.captures[0], ensure: match.captures[1], provider: name })
else
warning(_("Failed to match line '%{line}'") % { line: line })
end
end
end
packages
rescue Puppet::ExecutionFailure
fail(_("Error getting installed packages"))
end
# Install a package quietly (without confirmation or progress bar) using 'xbps-install'.
def install
resource_name = @resource[:name]
resource_source = @resource[:source]
cmd = %w[-S -y]
cmd += install_options if @resource[:install_options]
cmd << "--repository=#{resource_source}" if resource_source
cmd << resource_name
unhold if properties[:mark] == :hold
begin
xbps_install(*cmd)
ensure
hold if @resource[:mark] == :hold
end
end
# Because Voidlinux is a rolling release based distro, installing a package
# should always result in the newest release.
def update
install
end
# Removes a package from the system.
def uninstall
resource_name = @resource[:name]
cmd = %w[-R -y]
cmd += uninstall_options if @resource[:uninstall_options]
cmd << resource_name
xbps_remove(*cmd)
end
# The latest version of a given package
def latest
query&.[] :ensure
end
# Queries information for a package
def query
resource_name = @resource[:name]
installed_packages = self.class.instances
installed_packages.each do |pkg|
return pkg.properties if @resource[:name].casecmp(pkg.name).zero?
end
return nil unless @resource.allow_virtual?
# Search for virtual package
output = xbps_query("-Rs", resource_name).chomp
# xbps-query -Rs output is '[*] package-name-version description'
regex = /^\[\*\]+\s(\S+)-(\S+)\s+\S+/
match = regex.match(output)
return nil unless match
{ name: match.captures[0], ensure: match.captures[1], provider: self.class.name }
end
# Puts a package on hold, so it doesn't update by itself on system update
def hold
xbps_pkgdb("-m", "hold", @resource[:name])
end
# Puts a package out of hold
def unhold
xbps_pkgdb("-m", "unhold", @resource[:name])
end
private
def install_options
join_options(@resource[:install_options])
end
def uninstall_options
join_options(@resource[:uninstall_options])
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/dnfmodule.rb | lib/puppet/provider/package/dnfmodule.rb | # frozen_string_literal: true
# dnfmodule - A puppet package provider for DNF modules
#
# Installing a module:
# package { 'postgresql':
# provider => 'dnfmodule',
# ensure => '9.6', # install a specific stream
# flavor => 'client', # install a specific profile
# }
require_relative '../../../puppet/provider/package'
Puppet::Type.type(:package).provide :dnfmodule, :parent => :dnf do
has_feature :installable, :uninstallable, :versionable, :supports_flavors, :disableable
# has_feature :upgradeable
# it's not (yet) feasible to make this upgradeable since module streams don't
# always have matching version types (i.e. idm has streams DL1 and client,
# other modules have semver streams, others have string streams... we cannot
# programatically determine a latest version for ensure => 'latest'
commands :dnf => '/usr/bin/dnf'
def self.current_version
@current_version ||= dnf('--version').split.first
end
def self.prefetch(packages)
if Puppet::Util::Package.versioncmp(current_version, '3.0.1') < 0
raise Puppet::Error, _("Modules are not supported on DNF versions lower than 3.0.1")
end
super
end
def self.instances
packages = []
cmd = "#{command(:dnf)} module list -y -d 0 -e #{error_level}"
execute(cmd).each_line do |line|
# select only lines with actual packages since DNF clutters the output
next unless line =~ /\[[eix]\][, ]/
line.gsub!(/\[d\]/, '') # we don't care about the default flag
flavor = if line.include?('[i]')
line.split('[i]').first.split.last
else
:absent
end
packages << new(
name: line.split[0],
ensure: if line.include?('[x]')
:disabled
else
line.split[1]
end,
flavor: flavor,
provider: name
)
end
packages
end
def query
pkg = self.class.instances.find do |package|
@resource[:name] == package.name
end
pkg ? pkg.properties : nil
end
# to install specific streams and profiles:
# $ dnf module install module-name:stream/profile
# $ dnf module install perl:5.24/minimal
# if unspecified, they will be defaulted (see [d] param in dnf module list output)
def install
# ensure we start fresh (remove existing stream)
uninstall unless [:absent, :purged].include?(@property_hash[:ensure])
args = @resource[:name].dup
case @resource[:ensure]
when true, false, Symbol
# pass
else
args << ":#{@resource[:ensure]}"
end
args << "/#{@resource[:flavor]}" if @resource[:flavor]
if @resource[:enable_only] == true
enable(args)
else
begin
execute([command(:dnf), 'module', 'install', '-d', '0', '-e', self.class.error_level, '-y', args])
rescue Puppet::ExecutionFailure => e
# module has no default profile and no profile was requested, so just enable the stream
# DNF versions prior to 4.2.8 do not need this workaround
# see https://bugzilla.redhat.com/show_bug.cgi?id=1669527
if @resource[:flavor].nil? && e.message =~ /^(?:missing|broken) groups or modules: #{Regexp.quote(args)}$/
enable(args)
else
raise
end
end
end
end
# should only get here when @resource[ensure] is :disabled
def insync?(is)
if resource[:ensure] == :disabled
# in sync only if package is already disabled
pkg = self.class.instances.find do |package|
@resource[:name] == package.name && package.properties[:ensure] == :disabled
end
return true if pkg
end
false
end
def enable(args = @resource[:name])
execute([command(:dnf), 'module', 'enable', '-d', '0', '-e', self.class.error_level, '-y', args])
end
def uninstall
execute([command(:dnf), 'module', 'remove', '-d', '0', '-e', self.class.error_level, '-y', @resource[:name]])
reset # reset module to the default stream
end
def disable(args = @resource[:name])
execute([command(:dnf), 'module', 'disable', '-d', '0', '-e', self.class.error_level, '-y', args])
end
def reset
execute([command(:dnf), 'module', 'reset', '-d', '0', '-e', self.class.error_level, '-y', @resource[:name]])
end
def flavor
@property_hash[:flavor]
end
def flavor=(value)
install if flavor != @resource.should(:flavor)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/apt.rb | lib/puppet/provider/package/apt.rb | # frozen_string_literal: true
require_relative '../../../puppet/util/package/version/range'
require_relative '../../../puppet/util/package/version/debian'
Puppet::Type.type(:package).provide :apt, :parent => :dpkg, :source => :dpkg do
# Provide sorting functionality
include Puppet::Util::Package
DebianVersion = Puppet::Util::Package::Version::Debian
VersionRange = Puppet::Util::Package::Version::Range
desc "Package management via `apt-get`.
This provider supports the `install_options` attribute, which allows command-line flags to be passed to apt-get.
These options should be specified as an array where each element is either a
string or a hash."
has_feature :versionable, :install_options, :virtual_packages, :version_ranges
commands :aptget => "/usr/bin/apt-get"
commands :aptcache => "/usr/bin/apt-cache"
commands :aptmark => "/usr/bin/apt-mark"
commands :preseed => "/usr/bin/debconf-set-selections"
defaultfor 'os.family' => :debian
ENV['DEBIAN_FRONTEND'] = "noninteractive"
# disable common apt helpers to allow non-interactive package installs
ENV['APT_LISTBUGS_FRONTEND'] = "none"
ENV['APT_LISTCHANGES_FRONTEND'] = "none"
def self.defaultto_allow_virtual
false
end
def self.instances
packages = super
manual_marks = aptmark('showmanual').split("\n")
packages.each do |package|
package.mark = :manual if manual_marks.include?(package.name)
end
packages
end
def query
hash = super
if !%i[absent purged].include?(hash[:ensure]) && aptmark('showmanual', @resource[:name]).strip == @resource[:name]
hash[:mark] = :manual
end
hash
end
def initialize(value = {})
super(value)
@property_flush = {}
end
def mark
@property_flush[:mark]
end
def mark=(value)
@property_flush[:mark] = value
end
def flush
# unless we are removing the package mark it if it hasn't already been marked
if @property_flush
unless @property_flush[:mark] || [:purge, :absent].include?(resource[:ensure])
aptmark('manual', resource[:name])
end
end
end
# A derivative of DPKG; this is how most people actually manage
# Debian boxes, and the only thing that differs is that it can
# install packages from remote sites.
# Double negation confuses Rubocop's Layout cops
# rubocop:disable Layout
def checkforcdrom
have_cdrom = begin
!!(File.read("/etc/apt/sources.list") =~ /^[^#]*cdrom:/)
rescue
# This is basically pathological...
false
end
# rubocop:enable Layout
if have_cdrom and @resource[:allowcdrom] != :true
raise Puppet::Error, _("/etc/apt/sources.list contains a cdrom source; not installing. Use 'allowcdrom' to override this failure.")
end
end
def best_version(should_range)
versions = []
output = aptcache :madison, @resource[:name]
output.each_line do |line|
is = line.split('|')[1].strip
begin
is_version = DebianVersion.parse(is)
versions << is_version if should_range.include?(is_version)
rescue DebianVersion::ValidationFailure
Puppet.debug("Cannot parse #{is} as a debian version")
end
end
return versions.max if versions.any?
Puppet.debug("No available version for package #{@resource[:name]} is included in range #{should_range}")
should_range
end
# Install a package using 'apt-get'. This function needs to support
# installing a specific version.
def install
run_preseed if @resource[:responsefile]
should = @resource[:ensure]
if should.is_a?(String)
begin
should_range = VersionRange.parse(should, DebianVersion)
unless should_range.is_a?(VersionRange::Eq)
should = best_version(should_range)
end
rescue VersionRange::ValidationFailure, DebianVersion::ValidationFailure
Puppet.debug("Cannot parse #{should} as a debian version range, falling through")
end
end
checkforcdrom
cmd = %w[-q -y]
config = @resource[:configfiles]
if config
if config == :keep
cmd << "-o" << 'DPkg::Options::=--force-confold'
else
cmd << "-o" << 'DPkg::Options::=--force-confnew'
end
end
str = @resource[:name]
case should
when true, false, Symbol
# pass
else
# Add the package version and --force-yes option
str += "=#{should}"
cmd << "--force-yes"
end
cmd += install_options if @resource[:install_options]
cmd << :install
# rubocop:disable Style/RedundantCondition
if source
cmd << source
else
cmd << str
end
# rubocop:enable Style/RedundantCondition
unhold if properties[:mark] == :hold
begin
aptget(*cmd)
ensure
hold if @resource[:mark] == :hold
end
# If a source file was specified, we must make sure the expected version was installed from specified file
if source && !%i[present installed].include?(should)
is = query
raise Puppet::Error, _("Could not find package %{name}") % { name: name } unless is
version = is[:ensure]
raise Puppet::Error, _("Failed to update to version %{should}, got version %{version} instead") % { should: should, version: version } unless
insync?(version)
end
end
# What's the latest package version available?
def latest
output = aptcache :policy, @resource[:name]
if output =~ /Candidate:\s+(\S+)\s/
Regexp.last_match(1)
else
err _("Could not find latest version")
nil
end
end
#
# preseeds answers to dpkg-set-selection from the "responsefile"
#
def run_preseed
response = @resource[:responsefile]
if response && Puppet::FileSystem.exist?(response)
info(_("Preseeding %{response} to debconf-set-selections") % { response: response })
preseed response
else
info _("No responsefile specified or non existent, not preseeding anything")
end
end
def uninstall
run_preseed if @resource[:responsefile]
args = ['-y', '-q']
args << '--allow-change-held-packages' if properties[:mark] == :hold
args << :remove << @resource[:name]
aptget(*args)
end
def purge
run_preseed if @resource[:responsefile]
args = ['-y', '-q']
args << '--allow-change-held-packages' if properties[:mark] == :hold
args << :remove << '--purge' << @resource[:name]
aptget(*args)
# workaround a "bug" in apt, that already removed packages are not purged
super
end
def install_options
join_options(@resource[:install_options])
end
def insync?(is)
# this is called after the generic version matching logic (insync? for the
# type), so we only get here if should != is
return false unless is && is != :absent
# if 'should' is a range and 'is' a debian version we should check if 'should' includes 'is'
should = @resource[:ensure]
return false unless is.is_a?(String) && should.is_a?(String)
begin
should_range = VersionRange.parse(should, DebianVersion)
rescue VersionRange::ValidationFailure, DebianVersion::ValidationFailure
Puppet.debug("Cannot parse #{should} as a debian version range")
return false
end
begin
is_version = DebianVersion.parse(is)
rescue DebianVersion::ValidationFailure
Puppet.debug("Cannot parse #{is} as a debian version")
return false
end
should_range.include?(is_version)
end
private
def source
@source ||= @resource[:source]
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/nim.rb | lib/puppet/provider/package/nim.rb | # frozen_string_literal: true
require_relative '../../../puppet/provider/package'
require_relative '../../../puppet/util/package'
Puppet::Type.type(:package).provide :nim, :parent => :aix, :source => :aix do
desc "Installation from an AIX NIM LPP source. The `source` parameter is required
for this provider, and should specify the name of a NIM `lpp_source` resource
that is visible to the puppet agent machine. This provider supports the
management of both BFF/installp and RPM packages.
Note that package downgrades are *not* supported; if your resource specifies
a specific version number and there is already a newer version of the package
installed on the machine, the resource will fail with an error message."
# The commands we are using on an AIX box are installed standard
# (except nimclient) nimclient needs the bos.sysmgt.nim.client fileset.
commands :nimclient => "/usr/sbin/nimclient",
:lslpp => "/usr/bin/lslpp",
:rpm => "rpm"
# If NIM has not been configured, /etc/niminfo will not be present.
# However, we have no way of knowing if the NIM server is not configured
# properly.
confine :exists => "/etc/niminfo"
has_feature :versionable
attr_accessor :latest_info
def self.srclistcmd(source)
[command(:nimclient), "-o", "showres", "-a", "installp_flags=L", "-a", "resource=#{source}"]
end
def uninstall
output = lslpp("-qLc", @resource[:name]).split(':')
# the 6th index in the colon-delimited output contains a " " for installp/BFF
# packages, and an "R" for RPMS. (duh.)
pkg_type = output[6]
case pkg_type
when " "
installp "-gu", @resource[:name]
when "R"
rpm "-e", @resource[:name]
else
self.fail(_("Unrecognized AIX package type identifier: '%{pkg_type}'") % { pkg_type: pkg_type })
end
# installp will return an exit code of zero even if it didn't uninstall
# anything... so let's make sure it worked.
unless query().nil?
self.fail _("Failed to uninstall package '%{name}'") % { name: @resource[:name] }
end
end
def install(useversion = true)
source = @resource[:source]
unless source
self.fail _("An LPP source location is required in 'source'")
end
pkg = @resource[:name]
version_specified = (useversion and (!@resource.should(:ensure).is_a? Symbol))
# This is unfortunate for a couple of reasons. First, because of a subtle
# difference in the command-line syntax for installing an RPM vs an
# installp/BFF package, we need to know ahead of time which type of
# package we're trying to install. This means we have to execute an
# extra command.
#
# Second, the command is easiest to deal with and runs fastest if we
# pipe it through grep on the shell. Unfortunately, the way that
# the provider `make_command_methods` metaprogramming works, we can't
# use that code path to execute the command (because it treats the arguments
# as an array of args that all apply to `nimclient`, which fails when you
# hit the `|grep`.) So here we just call straight through to P::U.execute
# with a single string argument for the full command, rather than going
# through the metaprogrammed layer. We could get rid of the grep and
# switch back to the metaprogrammed stuff, and just parse all of the output
# in Ruby... but we'd be doing an awful lot of unnecessary work.
showres_command = "/usr/sbin/nimclient -o showres -a resource=#{source} |/usr/bin/grep -p -E "
if version_specified
version = @resource.should(:ensure)
showres_command << "'#{Regexp.escape(pkg)}( |-)#{Regexp.escape(version)}'"
else
version = nil
showres_command << "'#{Regexp.escape(pkg)}'"
end
output = Puppet::Util::Execution.execute(showres_command)
if version_specified
package_type = determine_package_type(output, pkg, version)
else
package_type, version = determine_latest_version(output, pkg)
end
if package_type.nil?
errmsg = if version_specified
_("Unable to find package '%{package}' with version '%{version}' on lpp_source '%{source}'") %
{ package: pkg, version: version, source: source }
else
_("Unable to find package '%{package}' on lpp_source '%{source}'") % { package: pkg, source: source }
end
self.fail errmsg
end
# This part is a bit tricky. If there are multiple versions of the
# package available, then `version` will be set to a value, and we'll need
# to add that value to our installation command. However, if there is only
# one version of the package available, `version` will be set to `nil`, and
# we don't need to add the version string to the command.
if version
# Now we know if the package type is RPM or not, and we can adjust our
# `pkg` string for passing to the install command accordingly.
if package_type == :rpm
# RPMs expect a hyphen between the package name and the version number
version_separator = "-"
else
# installp/BFF packages expect a space between the package name and the
# version number.
version_separator = " "
end
pkg += version_separator + version
end
# NOTE: the installp flags here are ignored (but harmless) for RPMs
output = nimclient "-o", "cust", "-a", "installp_flags=acgwXY", "-a", "lpp_source=#{source}", "-a", "filesets=#{pkg}"
# If the package is superseded, it means we're trying to downgrade and we
# can't do that.
case package_type
when :installp
if output =~ /^#{Regexp.escape(@resource[:name])}\s+.*\s+Already superseded by.*$/
self.fail _("NIM package provider is unable to downgrade packages")
end
when :rpm
if output =~ /^#{Regexp.escape(@resource[:name])}.* is superseded by.*$/
self.fail _("NIM package provider is unable to downgrade packages")
end
end
end
private
## UTILITY METHODS FOR PARSING `nimclient -o showres` output
# This makes me very sad. These regexes seem pretty fragile, but
# I spent a lot of time trying to figure out a solution that didn't
# require parsing the `nimclient -o showres` output and was unable to
# do so.
self::HEADER_LINE_REGEX = /^([^\s]+)\s+[^@]+@@(I|R|S):(\1)\s+[^\s]+$/
self::PACKAGE_LINE_REGEX = /^.*@@(I|R|S):(.*)$/
self::RPM_PACKAGE_REGEX = /^(.*)-(.*-\d+\w*) \2$/
self::INSTALLP_PACKAGE_REGEX = /^(.*) (.*)$/
# Here is some sample output that shows what the above regexes will be up
# against:
# FOR AN INSTALLP(bff) PACKAGE:
#
# mypackage.foo ALL @@I:mypackage.foo _all_filesets
# + 1.2.3.4 MyPackage Runtime Environment @@I:mypackage.foo 1.2.3.4
# + 1.2.3.8 MyPackage Runtime Environment @@I:mypackage.foo 1.2.3.8
#
# FOR AN INSTALLP(bff) PACKAGE with security update:
#
# bos.net ALL @@S:bos.net _all_filesets
# + 7.2.0.1 TCP/IP ntp Applications @@S:bos.net.tcp.ntp 7.2.0.1
# + 7.2.0.2 TCP/IP ntp Applications @@S:bos.net.tcp.ntp 7.2.0.2
#
# FOR AN RPM PACKAGE:
#
# mypackage.foo ALL @@R:mypackage.foo _all_filesets
# @@R:mypackage.foo-1.2.3-1 1.2.3-1
# @@R:mypackage.foo-1.2.3-4 1.2.3-4
# @@R:mypackage.foo-1.2.3-8 1.2.3-8
# Parse the output of a `nimclient -o showres` command. Returns a two-dimensional
# hash, where the first-level keys are package names, the second-level keys are
# version number strings for all of the available version numbers for a package,
# and the values indicate the package type (:rpm / :installp)
def parse_showres_output(showres_output)
paragraphs = split_into_paragraphs(showres_output)
packages = {}
paragraphs.each do |para|
lines = para.split(/$/)
parse_showres_header_line(lines.shift)
lines.each do |l|
package, version, type = parse_showres_package_line(l)
packages[package] ||= {}
packages[package][version] = type
end
end
packages
end
# This method basically just splits the multi-line input string into chunks
# based on lines that contain nothing but whitespace. It also strips any
# leading or trailing whitespace (including newlines) from the resulting
# strings and then returns them as an array.
def split_into_paragraphs(showres_output)
showres_output.split(/^\s*$/).map(&:strip!)
end
def parse_showres_header_line(line)
# This method doesn't produce any meaningful output; it's basically just
# meant to validate that the header line for the package listing output
# looks sane, so we know we're dealing with the kind of output that we
# are capable of handling.
unless line.match(self.class::HEADER_LINE_REGEX)
self.fail _("Unable to parse output from nimclient showres: line does not match expected package header format:\n'%{line}'") % { line: line }
end
end
def parse_installp_package_string(package_string)
match = package_string.match(self.class::INSTALLP_PACKAGE_REGEX)
unless match
self.fail _("Unable to parse output from nimclient showres: package string does not match expected installp package string format:\n'%{package_string}'") % { package_string: package_string }
end
package_name = match.captures[0]
version = match.captures[1]
[package_name, version, :installp]
end
def parse_rpm_package_string(package_string)
match = package_string.match(self.class::RPM_PACKAGE_REGEX)
unless match
self.fail _("Unable to parse output from nimclient showres: package string does not match expected rpm package string format:\n'%{package_string}'") % { package_string: package_string }
end
package_name = match.captures[0]
version = match.captures[1]
[package_name, version, :rpm]
end
def parse_showres_package_line(line)
match = line.match(self.class::PACKAGE_LINE_REGEX)
unless match
self.fail _("Unable to parse output from nimclient showres: line does not match expected package line format:\n'%{line}'") % { line: line }
end
package_type_flag = match.captures[0]
package_string = match.captures[1]
case package_type_flag
when "I", "S"
parse_installp_package_string(package_string)
when "R"
parse_rpm_package_string(package_string)
else
self.fail _("Unrecognized package type specifier: '%{package_type_flag}' in package line:\n'%{line}'") % { package_type_flag: package_type_flag, line: line }
end
end
# Given a blob of output from `nimclient -o showres` and a package name,
# this method checks to see if there are multiple versions of the package
# available on the lpp_source. If there are, the method returns
# [package_type, latest_version] (where package_type is one of :installp or :rpm).
# If there is only one version of the package available, it returns
# [package_type, nil], because the caller doesn't need to pass the version
# string to the command-line command if there is only one version available.
# If the package is not available at all, the method simply returns nil (instead
# of a tuple).
def determine_latest_version(showres_output, package_name)
packages = parse_showres_output(showres_output)
unless packages.has_key?(package_name)
return nil
end
if packages[package_name].count == 1
version = packages[package_name].keys[0]
[packages[package_name][version], nil]
else
versions = packages[package_name].keys
latest_version = (versions.sort { |a, b| Puppet::Util::Package.versioncmp(b, a) })[0]
[packages[package_name][latest_version], latest_version]
end
end
def determine_package_type(showres_output, package_name, version)
packages = parse_showres_output(showres_output)
unless packages.has_key?(package_name) and packages[package_name].has_key?(version)
return nil
end
packages[package_name][version]
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/tdnf.rb | lib/puppet/provider/package/tdnf.rb | # frozen_string_literal: true
Puppet::Type.type(:package).provide :tdnf, :parent => :dnf do
desc "Support via `tdnf`.
This provider supports the `install_options` attribute, which allows command-line flags to be passed to tdnf.
These options should be spcified as a string (e.g. '--flag'), a hash (e.g. {'--flag' => 'value'}), or an
array where each element is either a string or a hash."
has_feature :install_options, :versionable, :virtual_packages
commands :cmd => "tdnf", :rpm => "rpm"
# Note: this confine was borrowed from the Yum provider. The
# original purpose (from way back in 2007) was to make sure we
# never try to use RPM on a machine without it. We think this
# has probably become obsolete with the way `commands` work, so
# we should investigate removing it at some point.
#
# Mixing confine statements, control expressions, and exception handling
# confuses Rubocop's Layout cops, so we disable them entirely.
# rubocop:disable Layout
if command('rpm')
confine :true => begin
rpm('--version')
rescue Puppet::ExecutionFailure
false
else
true
end
end
# rubocop:enable Layout
defaultfor 'os.name' => "PhotonOS"
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/puppet_gem.rb | lib/puppet/provider/package/puppet_gem.rb | # frozen_string_literal: true
Puppet::Type.type(:package).provide :puppet_gem, :parent => :gem do
desc "Puppet Ruby Gem support. This provider is useful for managing
gems needed by the ruby provided in the puppet-agent package."
has_feature :versionable, :install_options, :uninstall_options
confine :true => Puppet.runtime[:facter].value(:aio_agent_version)
commands :gemcmd => Puppet.run_mode.gem_cmd
def uninstall
super
Puppet.debug("Invalidating rubygems cache after uninstalling gem '#{resource[:name]}'")
Puppet::Util::Autoload.gem_source.clear_paths
end
def self.execute_gem_command(command, command_options, custom_environment = {})
if (pkg_config_path = Puppet.run_mode.pkg_config_path)
custom_environment['PKG_CONFIG_PATH'] = pkg_config_path
end
super(command, command_options, custom_environment)
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
puppetlabs/puppet | https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/provider/package/aptitude.rb | lib/puppet/provider/package/aptitude.rb | # frozen_string_literal: true
Puppet::Type.type(:package).provide :aptitude, :parent => :apt, :source => :dpkg do
desc "Package management via `aptitude`."
has_feature :versionable
commands :aptitude => "/usr/bin/aptitude"
commands :aptcache => "/usr/bin/apt-cache"
ENV['DEBIAN_FRONTEND'] = "noninteractive"
def aptget(*args)
args.flatten!
# Apparently aptitude hasn't always supported a -q flag.
args.delete("-q") if args.include?("-q")
args.delete("--force-yes") if args.include?("--force-yes")
output = aptitude(*args)
# Yay, stupid aptitude doesn't throw an error when the package is missing.
if args.include?(:install) and output.to_s =~ /Couldn't find any package/
raise Puppet::Error, _("Could not find package %{name}") % { name: name }
end
end
def purge
aptitude '-y', 'purge', @resource[:name]
end
private
def source
nil
end
end
| ruby | Apache-2.0 | e227c27540975c25aa22d533a52424a9d2fc886a | 2026-01-04T15:39:26.576514Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.