Proyecto

General

Perfil

« Anterior | Siguiente » 

Revisión a7d31e36

Añadido por Rafael J. García Perdigón hace más de 6 años

puppet: Debianized puppet-linex, puppet-linex-common, facter-linex

Ver diferencias:

debian/stretch/facter-linex/debian/changelog
linex-arduino (1.0) linex; urgency=medium
* Collect and display facts about the system. Modified by Linex.
-- Rafael J. García Perdigón <rafael.garciap@juntaex.es> Tue, 20 Nov 2018 09:58:07 +0100
debian/stretch/facter-linex/debian/compat
9
debian/stretch/facter-linex/debian/control
Source: facter-linex
Section: admin
Priority: optional
Maintainer: Rafael Jesús García Perdigón <rafael.garciap@juntaex.es>
Build-Depends: debhelper (>= 8.0.0)
Standards-Version: 3.9.4
Package: facter-linex
Architecture: all
Depends: bind9-host | host, net-tools, ruby-json, ruby | ruby-interpreter
Recommends: pciutils, dmidecode, virt-what
Conflicts: facter
Provides: facter
Description: Collect and display facts about the system.
A cross-platform Ruby library for retrieving facts from operating systems.
Supports multiple resolution mechanisms, any of which can be restricted to
working only on certain operating systems or environments. Facter is
especially useful for retrieving things like operating system names, IP
addresses, MAC addresses, and SSH keys.
.
It is easy to extend Facter to include your own custom facts or to include
additional mechanisms for retrieving facts.
debian/stretch/facter-linex/debian/install
usr
debian/stretch/facter-linex/usr/bin/facter
#!/usr/bin/ruby
# For security reasons, ensure that '.' is not on the load path
# This is primarily for 1.8.7 since 1.9.2+ doesn't put '.' on the load path
$LOAD_PATH.delete '.'
require 'facter/application'
Facter::Application.run(ARGV)
debian/stretch/facter-linex/usr/lib/ruby/vendor_ruby/facter.rb
# Facter - Host Fact Detection and Reporting
#
# Copyright 2011 Puppet Labs Inc
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
require 'facter/version'
# Functions as a hash of 'facts' about your system system, such as MAC
# address, IP address, architecture, etc.
#
# @example Retrieve a fact
# puts Facter['operatingsystem'].value
#
# @example Retrieve all facts
# Facter.to_hash
# => { "kernel"=>"Linux", "uptime_days"=>0, "ipaddress"=>"10.0.0.1" }
#
# @api public
module Facter
# Most core functionality of facter is implemented in `Facter::Util`.
# @api public
module Util; end
require 'facter/util/fact'
require 'facter/util/collection'
include Comparable
include Enumerable
require 'facter/core/logging'
extend Facter::Core::Logging
# module methods
# Accessor for the collection object which holds all the facts
# @return [Facter::Util::Collection] the collection of facts
#
# @api private
def self.collection
unless defined?(@collection) and @collection
@collection = Facter::Util::Collection.new(
Facter::Util::Loader.new,
Facter::Util::Config.ext_fact_loader)
end
@collection
end
# Returns whether the JSON "feature" is available.
#
# @api private
def self.json?
begin
require 'json'
true
rescue LoadError
false
end
end
# Returns a fact object by name. If you use this, you still have to
# call {Facter::Util::Fact#value `value`} on it to retrieve the actual
# value.
#
# @param name [String] the name of the fact
#
# @return [Facter::Util::Fact, nil] The fact object, or nil if no fact
# is found.
#
# @api public
def self.[](name)
collection.fact(name)
end
# (see [])
def self.fact(name)
collection.fact(name)
end
# Flushes cached values for all facts. This does not cause code to be
# reloaded; it only clears the cached results.
#
# @return [void]
#
# @api public
def self.flush
collection.flush
end
# Lists all fact names
#
# @return [Array<String>] array of fact names
#
# @api public
def self.list
collection.list
end
# Gets the value for a fact. Returns `nil` if no such fact exists.
#
# @param name [String] the fact name
# @return [Object, nil] the value of the fact, or nil if no fact is
# found
#
# @api public
def self.value(name)
collection.value(name)
end
# Gets a hash mapping fact names to their values
#
# @return [Hash{String => Object}] the hash of fact names and values
#
# @api public
def self.to_hash
collection.load_all
collection.to_hash
end
# Define a new fact or extend an existing fact.
#
# @param name [Symbol] The name of the fact to define
# @param options [Hash] A hash of options to set on the fact
#
# @return [Facter::Util::Fact] The fact that was defined
#
# @api public
# @see {Facter::Util::Collection#define_fact}
def self.define_fact(name, options = {}, &block)
collection.define_fact(name, options, &block)
end
# Adds a {Facter::Util::Resolution resolution} mechanism for a named
# fact. This does not distinguish between adding a new fact and adding
# a new way to resolve a fact.
#
# @overload add(name, options = {}, { || ... })
# @param name [String] the fact name
# @param options [Hash] optional parameters for the fact - attributes
# of {Facter::Util::Fact} and {Facter::Util::Resolution} can be
# supplied here
# @option options [Integer] :timeout set the
# {Facter::Util::Resolution#timeout timeout} for this resolution
# @param block [Proc] a block defining a fact resolution
#
# @return [Facter::Util::Fact] the fact object, which includes any previously
# defined resolutions
#
# @api public
def self.add(name, options = {}, &block)
collection.add(name, options, &block)
end
# Iterates over fact names and values
#
# @yieldparam [String] name the fact name
# @yieldparam [String] value the current value of the fact
#
# @return [void]
#
# @api public
def self.each
# Make sure all facts are loaded.
collection.load_all
collection.each do |*args|
yield(*args)
end
end
# Clears all cached values and removes all facts from memory.
#
# @return [void]
#
# @api public
def self.clear
Facter.flush
Facter.reset
end
# Removes all facts from memory. Use this when the fact code has
# changed on disk and needs to be reloaded.
#
# @return [void]
#
# @api public
def self.reset
@collection = nil
reset_search_path!
end
# Loads all facts.
#
# @return [void]
#
# @api public
def self.loadfacts
collection.load_all
end
# Register directories to be searched for facts. The registered directories
# must be absolute paths or they will be ignored.
#
# @param dirs [String] directories to search
#
# @return [void]
#
# @api public
def self.search(*dirs)
@search_path += dirs
end
# Returns the registered search directories.
#
# @return [Array<String>] An array of the directories searched
#
# @api public
def self.search_path
@search_path.dup
end
# Reset the Facter search directories.
#
# @api private
# @return [void]
def self.reset_search_path!
@search_path = []
end
reset_search_path!
# Registers directories to be searched for external facts.
#
# @param dirs [Array<String>] directories to search
#
# @return [void]
#
# @api public
def self.search_external(dirs)
Facter::Util::Config.external_facts_dirs += dirs
end
# Returns the registered search directories.
#
# @return [Array<String>] An array of the directories searched
#
# @api public
def self.search_external_path
Facter::Util::Config.external_facts_dirs.dup
end
end
debian/stretch/facter-linex/usr/lib/ruby/vendor_ruby/facter/Cfkey.rb
# Fact: cfkey
#
# Purpose: Return the public key(s) for CFengine.
#
# Resolution:
# Tries each file of standard `localhost.pub` and `cfkey.pub` locations,
# checks if they appear to be a public key, and then join them all together.
#
# Caveats:
#
## Cfkey.rb
## Facts related to cfengine
##
Facter.add(:Cfkey) do
setcode do
value = nil
["/usr/local/etc/cfkey.pub",
"/etc/cfkey.pub",
"/var/cfng/keys/localhost.pub",
"/var/cfengine/ppkeys/localhost.pub",
"/var/lib/cfengine/ppkeys/localhost.pub",
"/var/lib/cfengine2/ppkeys/localhost.pub"
].each do |file|
if FileTest.file?(file)
File.open(file) { |openfile|
value = openfile.readlines.reject { |line|
line =~ /PUBLIC KEY/
}.collect { |line|
line.chomp
}.join("")
}
end
if value
break
end
end
value
end
end
debian/stretch/facter-linex/usr/lib/ruby/vendor_ruby/facter/application.rb
require 'optparse'
require 'facter'
require 'facter/util/formatter'
module Facter
module Application
require 'facter/util/nothing_loader'
def self.create_directory_loader(dir)
begin
Facter::Util::Config.ext_fact_loader = Facter::Util::DirectoryLoader.loader_for(dir)
rescue Facter::Util::DirectoryLoader::NoSuchDirectoryError => error
Facter.log_exception(error, "Specified external facts directory #{dir} does not exist.")
exit(1)
end
end
def self.create_nothing_loader
Facter::Util::Config.ext_fact_loader = Facter::Util::NothingLoader.new
end
def self.run(argv)
options = parse(argv)
# Accept fact names to return from the command line
names = argv
# Change location of external facts dir
# Check here for valid ext_dir and exit program
# Create the facts hash that is printed to standard out.
unless names.empty?
facts = {}
names.each do |name|
begin
facts[name] = Facter.value(name)
rescue => error
Facter.log_exception(error, "Could not retrieve #{name}: #{error.message}")
exit(10)
end
end
end
# Print everything if they didn't ask for specific facts.
facts ||= Facter.to_hash
output = nil
if options[:yaml]
output = Facter::Util::Formatter.format_yaml(facts)
elsif options[:json]
output = Facter::Util::Formatter.format_json(facts)
elsif options[:plaintext]
output = Facter::Util::Formatter.format_plaintext(facts)
else
output = Facter::Util::Formatter.format_plaintext(facts)
end
puts output
exit(0)
rescue => e
Facter.log_exception(e)
exit(12)
end
private
# Parses the given argument array destructively to return an options hash
# (and possibly perform side effects such as changing settings).
#
# @param [Array<String>] argv command line arguments
# @return [Hash] options hash
def self.parse(argv)
options = {}
parser = OptionParser.new do |opts|
opts.banner = <<-BANNER
facter(8) -- Gather system information
======
SYNOPSIS
--------
Collect and display facts about the system.
USAGE
-----
facter [-h|--help] [-t|--timing] [-d|--debug] [-p|--puppet] [-v|--version]
[-y|--yaml] [-j|--json] [--plaintext] [--external-dir DIR] [--no-external-dir]
[fact] [fact] [...]
DESCRIPTION
-----------
Collect and display facts about the current system. The library behind
Facter is easy to expand, making Facter an easy way to collect information
about a system from within the shell or within Ruby.
If no facts are specifically asked for, then all facts will be returned.
EXAMPLE
-------
Display all facts:
$ facter
architecture => amd64
blockdevices => sda,sr0
domain => example.com
fqdn => puppet.example.com
hardwaremodel => x86_64
[...]
Display a single fact:
$ facter kernel
Linux
Format facts as JSON:
$ facter --json architecture kernel hardwaremodel
{
"architecture": "amd64",
"kernel": "Linux",
"hardwaremodel": "x86_64"
}
AUTHOR
------
Luke Kanies
COPYRIGHT
---------
Copyright (c) 2011-2014 Puppet Labs, Inc Licensed under the Apache 2.0 license
OPTIONS
-------
BANNER
opts.on("-y",
"--yaml",
"Emit facts in YAML format.") { |v| options[:yaml] = v }
opts.on("-j",
"--json",
"Emit facts in JSON format.") { |v| options[:json] = v }
opts.on("--plaintext",
"Emit facts in plaintext format.") { |v| options[:plaintext] = v }
opts.on("--trace",
"Enable backtraces.") { |v| Facter.trace(true) }
opts.on("--external-dir DIR",
"The directory to use for external facts.") { |v| create_directory_loader(v) }
opts.on("--no-external-dir",
"Turn off external facts.") { |v| create_nothing_loader }
opts.on("-d",
"--debug",
"Enable debugging.") { |v| Facter.debugging(1) }
opts.on("-t",
"--timing",
"Enable timing.") { |v| Facter.timing(1) }
opts.on("-p",
"--puppet",
"(Deprecated: use `puppet facts` instead) Load the Puppet libraries, thus allowing Facter to load Puppet-specific facts.") do |v|
load_puppet
end
opts.on_tail("-v",
"--version",
"Print the version and exit.") do
puts Facter.version
exit(0)
end
opts.on_tail("-h",
"--help",
"Print this help message.") do
puts parser
exit(0)
end
end
parser.parse!(argv)
options
rescue OptionParser::InvalidOption => e
$stderr.puts e.message
exit(12)
end
def self.load_puppet
require 'puppet'
Puppet.initialize_settings
# If you've set 'vardir' but not 'libdir' in your
# puppet.conf, then the hook to add libdir to $:
# won't get triggered. This makes sure that it's setup
# correctly.
unless $LOAD_PATH.include?(Puppet[:libdir])
$LOAD_PATH << Puppet[:libdir]
end
rescue LoadError => detail
$stderr.puts "Could not load Puppet: #{detail}"
end
end
end
debian/stretch/facter-linex/usr/lib/ruby/vendor_ruby/facter/architecture.rb
# Fact: architecture
#
# Purpose:
# Return the CPU hardware architecture.
#
# Resolution:
# On non-AIX IBM, OpenBSD, Linux, and Debian's kfreebsd, use the hardwaremodel fact.
# On AIX get the arch value from `lsattr -El proc0 -a type`.
# Gentoo and Debian call "x86_86" "amd64".
# Gentoo also calls "i386" "x86".
#
# Caveats:
#
require 'facter/util/architecture'
Facter.add(:architecture) do
setcode do
model = Facter.value(:hardwaremodel)
case model
# most linuxen use "x86_64"
when /IBM*/
case Facter.value(:operatingsystem)
when "AIX"
arch = Facter::Util::Architecture.lsattr
if (match = arch.match /type\s(\S+)\s/)
match[1]
end
else
model
end
when "x86_64"
case Facter.value(:operatingsystem)
when "Debian", "Gentoo", "GNU/kFreeBSD", "Ubuntu"
"amd64"
else
model
end
when /(i[3456]86|pentium)/
case Facter.value(:operatingsystem)
when "Gentoo", "windows"
"x86"
else
"i386"
end
else
model
end
end
end
debian/stretch/facter-linex/usr/lib/ruby/vendor_ruby/facter/augeasversion.rb
# Fact: augeasversion
#
# Purpose: Report the version of the Augeas library.
#
# Resolution:
# Loads ruby-augeas and reports the value of `/augeas/version`, the version of
# the underlying Augeas library.
#
# Caveats:
# The library version may not indicate the presence of certain lenses,
# depending on the system packages updated, nor the version of ruby-augeas
# which may affect support for the Puppet Augeas provider.
# Versions prior to 0.3.6 cannot be interrogated for their version.
#
Facter.add(:augeasversion) do
setcode do
begin
require 'augeas'
aug = Augeas::open('/', nil, Augeas::NO_MODL_AUTOLOAD)
ver = aug.get('/augeas/version')
aug.close
ver
rescue Exception
Facter.debug('ruby-augeas not available')
end
end
end
debian/stretch/facter-linex/usr/lib/ruby/vendor_ruby/facter/blockdevices.rb
# Fact: blockdevice_<devicename>_size
#
# Purpose:
# Return the size of a block device in bytes.
#
# Resolution:
# Parse the contents of `/sys/block/<device>/size` to receive the size (multiplying by 512 to correct for blocks-to-bytes).
#
# Caveats:
# Only supports Linux 2.6+ at this time, due to the reliance on sysfs.
#
# Fact: blockdevice_<devicename>_vendor
#
# Purpose:
# Return the vendor name of block devices attached to the system.
#
# Resolution:
# Parse the contents of `/sys/block/<device>/device/vendor` to retrieve the vendor for a device.
#
# Caveats:
# Only supports Linux 2.6+ at this time, due to the reliance on sysfs.
#
# Fact: blockdevice_<devicename>_model
#
# Purpose:
# Return the model name of block devices attached to the system.
#
# Resolution:
# Parse the contents of `/sys/block/<device>/device/model` to retrieve the model name/number for a device.
#
# Caveats:
# Only supports Linux 2.6+ at this time, due to the reliance on sysfs.
#
# Fact: blockdevices
#
# Purpose:
# Return a comma separated list of block devices.
#
# Resolution:
# Retrieve the block devices that were identified and iterated over in the creation of the blockdevice_ facts.
#
# Caveats:
# Block devices must have been identified using sysfs information.
#
# Author: Jason Gill <jasongill@gmail.com>
require 'facter'
# Only Linux 2.6+ kernels support sysfs which is required to easily get device details
if Facter.value(:kernel) == 'Linux'
sysfs_block_directory = '/sys/block/'
blockdevices = []
# This should prevent any non-2.6 kernels or odd machines without sysfs support from being investigated further
if File.exist?(sysfs_block_directory)
# Iterate over each file in the /sys/block/ directory and skip ones that do not have a device subdirectory
Dir.entries(sysfs_block_directory).each do |device|
sysfs_device_directory = sysfs_block_directory + device + "/device"
next unless File.exist?(sysfs_device_directory)
# Add the device to the blockdevices list, which is returned as it's own fact later on
blockdevices << device
sizefile = sysfs_block_directory + device + "/size"
vendorfile = sysfs_device_directory + "/vendor"
modelfile = sysfs_device_directory + "/model"
if File.exist?(sizefile)
Facter.add("blockdevice_#{device}_size".to_sym) do
setcode { IO.read(sizefile).strip.to_i * 512 }
end
end
if File.exist?(vendorfile)
Facter.add("blockdevice_#{device}_vendor".to_sym) do
setcode { IO.read(vendorfile).strip }
end
end
if File.exist?(modelfile)
Facter.add("blockdevice_#{device}_model".to_sym) do
setcode { IO.read(modelfile).strip }
end
end
end
end
# Return a comma-seperated list of block devices found
unless blockdevices.empty?
Facter.add(:blockdevices) do
setcode { blockdevices.sort.join(',') }
end
end
end
debian/stretch/facter-linex/usr/lib/ruby/vendor_ruby/facter/core/aggregate.rb
require 'facter'
require 'facter/core/directed_graph'
require 'facter/core/suitable'
require 'facter/core/resolvable'
require 'facter/util/values'
# Aggregates provide a mechanism for facts to be resolved in multiple steps.
#
# Aggregates are evaluated in two parts: generating individual chunks and then
# aggregating all chunks together. Each chunk is a block of code that generates
# a value, and may depend on other chunks when it runs. After all chunks have
# been evaluated they are passed to the aggregate block as Hash<name, result>.
# The aggregate block converts the individual chunks into a single value that is
# returned as the final value of the aggregate.
#
# @api public
# @since 2.0.0
class Facter::Core::Aggregate
include Facter::Core::Suitable
include Facter::Core::Resolvable
# @!attribute [r] name
# @return [Symbol] The name of the aggregate resolution
attr_reader :name
# @!attribute [r] deps
# @api private
# @return [Facter::Core::DirectedGraph]
attr_reader :deps
# @!attribute [r] confines
# @return [Array<Facter::Core::Confine>] An array of confines restricting
# this to a specific platform
# @see Facter::Core::Suitable
attr_reader :confines
# @!attribute [r] fact
# @return [Facter::Util::Fact]
# @api private
attr_reader :fact
def initialize(name, fact)
@name = name
@fact = fact
@confines = []
@chunks = {}
@aggregate = nil
@deps = Facter::Core::DirectedGraph.new
end
def set_options(options)
if options[:name]
@name = options.delete(:name)
end
if options.has_key?(:timeout)
@timeout = options.delete(:timeout)
end
if options.has_key?(:weight)
@weight = options.delete(:weight)
end
if not options.keys.empty?
raise ArgumentError, "Invalid aggregate options #{options.keys.inspect}"
end
end
def evaluate(&block)
instance_eval(&block)
end
# Define a new chunk for the given aggregate
#
# @api public
#
# @example Defining a chunk with no dependencies
# aggregate.chunk(:mountpoints) do
# # generate mountpoint information
# end
#
# @example Defining an chunk to add mount options
# aggregate.chunk(:mount_options, :require => [:mountpoints]) do |mountpoints|
# # `mountpoints` is the result of the previous chunk
# # generate mount option information based on the mountpoints
# end
#
# @param name [Symbol] A name unique to this aggregate describing the chunk
# @param opts [Hash]
# @options opts [Array<Symbol>, Symbol] :require One or more chunks
# to evaluate and pass to this block.
# @yield [*Object] Zero or more chunk results
#
# @return [void]
def chunk(name, opts = {}, &block)
if not block_given?
raise ArgumentError, "#{self.class.name}#chunk requires a block"
end
deps = Array(opts.delete(:require))
if not opts.empty?
raise ArgumentError, "Unexpected options passed to #{self.class.name}#chunk: #{opts.keys.inspect}"
end
@deps[name] = deps
@chunks[name] = block
end
# Define how all chunks should be combined
#
# @api public
#
# @example Merge all chunks
# aggregate.aggregate do |chunks|
# final_result = {}
# chunks.each_value do |chunk|
# final_result.deep_merge(chunk)
# end
# final_result
# end
#
# @example Sum all chunks
# aggregate.aggregate do |chunks|
# total = 0
# chunks.each_value do |chunk|
# total += chunk
# end
# total
# end
#
# @yield [Hash<Symbol, Object>] A hash containing chunk names and
# chunk values
#
# @return [void]
def aggregate(&block)
if block_given?
@aggregate = block
else
raise ArgumentError, "#{self.class.name}#aggregate requires a block"
end
end
def resolution_type
:aggregate
end
private
# Evaluate the results of this aggregate.
#
# @see Facter::Core::Resolvable#value
# @return [Object]
def resolve_value
chunk_results = run_chunks()
aggregate_results(chunk_results)
end
# Order all chunks based on their dependencies and evaluate each one, passing
# dependent chunks as needed.
#
# @return [Hash<Symbol, Object>] A hash containing the chunk that
# generated value and the related value.
def run_chunks
results = {}
order_chunks.each do |(name, block)|
input = @deps[name].map { |dep_name| results[dep_name] }
output = block.call(*input)
results[name] = Facter::Util::Values.deep_freeze(output)
end
results
end
# Process the results of all chunks with the aggregate block and return the
# results. If no aggregate block has been specified, fall back to deep
# merging the given data structure
#
# @param results [Hash<Symbol, Object>] A hash of chunk names and the output
# of that chunk.
# @return [Object]
def aggregate_results(results)
if @aggregate
@aggregate.call(results)
else
default_aggregate(results)
end
end
def default_aggregate(results)
results.values.inject do |result, current|
Facter::Util::Values.deep_merge(result, current)
end
rescue Facter::Util::Values::DeepMergeError => e
raise ArgumentError, "Could not deep merge all chunks (Original error: " +
"#{e.message}), ensure that chunks return either an Array or Hash or " +
"override the aggregate block", e.backtrace
end
# Order chunks based on their dependencies
#
# @return [Array<Symbol, Proc>] A list of chunk names and blocks in evaluation order.
def order_chunks
if not @deps.acyclic?
raise DependencyError, "Could not order chunks; found the following dependency cycles: #{@deps.cycles.inspect}"
end
sorted_names = @deps.tsort
sorted_names.map do |name|
[name, @chunks[name]]
end
end
class DependencyError < StandardError; end
end
debian/stretch/facter-linex/usr/lib/ruby/vendor_ruby/facter/core/directed_graph.rb
require 'set'
require 'tsort'
module Facter
module Core
class DirectedGraph < Hash
include TSort
def acyclic?
cycles.empty?
end
def cycles
cycles = []
each_strongly_connected_component do |component|
cycles << component if component.size > 1
end
cycles
end
alias tsort_each_node each_key
def tsort_each_child(node)
fetch(node, []).each do |child|
yield child
end
end
def tsort
missing = Set.new(self.values.flatten) - Set.new(self.keys)
if not missing.empty?
raise MissingVertex, "Cannot sort elements; cannot depend on missing elements #{missing.to_a}"
end
super
rescue TSort::Cyclic
raise CycleError, "Cannot sort elements; found the following cycles: #{cycles.inspect}"
end
class CycleError < StandardError; end
class MissingVertex < StandardError; end
end
end
end
debian/stretch/facter-linex/usr/lib/ruby/vendor_ruby/facter/core/execution.rb
require 'facter/util/config'
module Facter
module Core
module Execution
require 'facter/core/execution/base'
require 'facter/core/execution/windows'
require 'facter/core/execution/posix'
@@impl = if Facter::Util::Config.is_windows?
Facter::Core::Execution::Windows.new
else
Facter::Core::Execution::Posix.new
end
def self.impl
@@impl
end
module_function
# Returns the locations to be searched when looking for a binary. This
# is currently determined by the +PATH+ environment variable plus
# `/sbin` and `/usr/sbin` when run on unix
#
# @return [Array<String>] the paths to be searched for binaries
# @api private
def search_paths
@@impl.search_paths
end
# Determines the full path to a binary. If the supplied filename does not
# already describe an absolute path then different locations (determined
# by {search_paths}) will be searched for a match.
#
# Returns nil if no matching executable can be found otherwise returns
# the expanded pathname.
#
# @param bin [String] the executable to locate
# @return [String,nil] the full path to the executable or nil if not
# found
#
# @api public
def which(bin)
@@impl.which(bin)
end
# Determine in a platform-specific way whether a path is absolute. This
# defaults to the local platform if none is specified.
#
# @param path [String] the path to check
# @param platform [:posix,:windows,nil] the platform logic to use
def absolute_path?(path, platform = nil)
@@impl.absolute_path?(path, platform)
end
# Given a command line, this returns the command line with the
# executable written as an absolute path. If the executable contains
# spaces, it has be put in double quotes to be properly recognized.
#
# @param command [String] the command line
#
# @return [String, nil] the command line with the executable's path
# expanded, or nil if the executable cannot be found.
def expand_command(command)
@@impl.expand_command(command)
end
# Overrides environment variables within a block of code. The
# specified values will be set for the duration of the block, after
# which the original values (if any) will be restored.
#
# @overload with_env(values, { || ... })
#
# @param values [Hash<String=>String>] A hash of the environment
# variables to override
#
# @return [void]
#
# @api public
def with_env(values, &block)
@@impl.with_env(values, &block)
end
# Try to execute a command and return the output.
#
# @param code [String] the program to run
#
# @return [String] the output of the program, or nil if the command does
# not exist or could not be executed.
#
# @deprecated Use #{execute} instead
# @api public
def exec(command)
@@impl.execute(command, :on_fail => nil)
end
# Execute a command and return the output of that program.
#
# @param code [String] the program to run
# @param options [Hash]
#
# @option options [Object] :on_fail How to behave when the command could
# not be run. Specifying :raise will raise an error, anything else will
# return that object on failure. Default is :raise.
#
# @raise [Facter::Core::Execution::ExecutionFailure] If the command does
# not exist or could not be executed.
#
# @return [String] the output of the program, or the value of :on_fail if
# command execution failed and :on_fail was specified.
#
# @api public
# @since 2.0.1
def execute(command, options = {})
@@impl.execute(command, options)
end
class ExecutionFailure < StandardError; end
end
end
end
debian/stretch/facter-linex/usr/lib/ruby/vendor_ruby/facter/core/execution/base.rb
class Facter::Core::Execution::Base
def with_env(values)
old = {}
values.each do |var, value|
# save the old value if it exists
if old_val = ENV[var]
old[var] = old_val
end
# set the new (temporary) value for the environment variable
ENV[var] = value
end
# execute the caller's block, capture the return value
rv = yield
# use an ensure block to make absolutely sure we restore the variables
ensure
# restore the old values
values.each do |var, value|
if old.include?(var)
ENV[var] = old[var]
else
# if there was no old value, delete the key from the current environment variables hash
ENV.delete(var)
end
end
# return the captured return value
rv
end
def execute(command, options = {})
on_fail = options.fetch(:on_fail, :raise)
# Set LC_ALL and LANG to force i18n to C for the duration of this exec; this ensures that any code that parses the
# output of the command can expect it to be in a consistent / predictable format / locale
with_env 'LC_ALL' => 'C', 'LANG' => 'C' do
expanded_command = expand_command(command)
if expanded_command.nil?
if on_fail == :raise
raise Facter::Core::Execution::ExecutionFailure.new, "Could not execute '#{command}': command not found"
else
return on_fail
end
end
out = ''
begin
wait_for_child = true
out = %x{#{expanded_command}}.chomp
wait_for_child = false
rescue => detail
if on_fail == :raise
raise Facter::Core::Execution::ExecutionFailure.new, "Failed while executing '#{expanded_command}': #{detail.message}"
else
return on_fail
end
ensure
if wait_for_child
# We need to ensure that if this command exits early then any spawned
# children will be reaped. Process execution is frequently
# terminated using Timeout.timeout but since the timeout isn't in
# this scope we can't rescue the raised exception. The best that
# we can do is determine if the child has exited, and if it hasn't
# then we need to spawn a thread to wait for the child.
#
# Due to the limitations of Ruby 1.8 there aren't good ways to
# asynchronously run a command and grab the PID of that command
# using the standard library. The best we can do is blindly wait
# on all processes and hope for the best. This issue is described
# at https://tickets.puppetlabs.com/browse/FACT-150
Thread.new { Process.waitall }
end
end
out
end
end
end
debian/stretch/facter-linex/usr/lib/ruby/vendor_ruby/facter/core/execution/posix.rb
class Facter::Core::Execution::Posix < Facter::Core::Execution::Base
DEFAULT_SEARCH_PATHS = ['/sbin', '/usr/sbin']
def search_paths
# Make sure facter is usable even for non-root users. Most commands
# in /sbin (like ifconfig) can be run as non privileged users as
# long as they do not modify anything - which we do not do with facter
ENV['PATH'].split(File::PATH_SEPARATOR) + DEFAULT_SEARCH_PATHS
end
def which(bin)
if absolute_path?(bin)
return bin if File.executable?(bin) and File.file?(bin)
else
search_paths.each do |dir|
dest = File.join(dir, bin)
return dest if File.executable?(dest) and File.file?(dest)
end
end
nil
end
ABSOLUTE_PATH_REGEX = %r{^/}
def absolute_path?(path)
!! (path =~ ABSOLUTE_PATH_REGEX)
end
DOUBLE_QUOTED_COMMAND = /^"(.+?)"(?:\s+(.*))?/
SINGLE_QUOTED_COMMAND = /^'(.+?)'(?:\s+(.*))?/
def expand_command(command)
exe = nil
args = nil
if (match = (command.match(DOUBLE_QUOTED_COMMAND) || command.match(SINGLE_QUOTED_COMMAND)))
exe, args = match.captures
else
exe, args = command.split(/ /,2)
end
if exe and (expanded = which(exe))
expanded = "'#{expanded}'" if expanded.match(/\s/)
expanded << " #{args}" if args
return expanded
end
end
end
debian/stretch/facter-linex/usr/lib/ruby/vendor_ruby/facter/core/execution/windows.rb
class Facter::Core::Execution::Windows < Facter::Core::Execution::Base
def search_paths
ENV['PATH'].split(File::PATH_SEPARATOR)
end
DEFAULT_COMMAND_EXTENSIONS = %w[.COM .EXE .BAT .CMD]
def which(bin)
if absolute_path?(bin)
return bin if File.executable?(bin)
else
search_paths.each do |dir|
dest = File.join(dir, bin)
dest.gsub!(File::SEPARATOR, File::ALT_SEPARATOR)
if File.extname(dest).empty?
exts = ENV['PATHEXT']
exts = exts ? exts.split(File::PATH_SEPARATOR) : DEFAULT_COMMAND_EXTENSIONS
exts.each do |ext|
destext = dest + ext
return destext if File.executable?(destext)
end
end
return dest if File.executable?(dest)
end
end
nil
end
slash = '[\\\\/]'
name = '[^\\\\/]+'
ABSOLUTE_PATH_REGEX = %r!^(([A-Z]:#{slash})|(#{slash}#{slash}#{name}#{slash}#{name})|(#{slash}#{slash}\?#{slash}#{name}))!i
def absolute_path?(path)
!! (path =~ ABSOLUTE_PATH_REGEX)
end
DOUBLE_QUOTED_COMMAND = /^"(.+?)"(?:\s+(.*))?/
def expand_command(command)
exe = nil
args = nil
if (match = command.match(DOUBLE_QUOTED_COMMAND))
exe, args = match.captures
else
exe, args = command.split(/ /,2)
end
if exe and (expanded = which(exe))
expanded = "\"#{expanded}\"" if expanded.match(/\s+/)
expanded << " #{args}" if args
return expanded
end
end
end
debian/stretch/facter-linex/usr/lib/ruby/vendor_ruby/facter/core/logging.rb
require 'facter'
module Facter::Core::Logging
extend self
# @api private
GREEN = ""
# @api private
RESET = ""
# @api private
@@debug = false
# @api private
@@timing = false
# @api private
@@trace = false
# @api private
@@warn_messages = {}
# @api private
@@debug_messages = {}
# @api private
@@message_callback = nil
# Used to register a callback that is called when a message is logged.
# If a block is given, Facter will not log messages.
# If a block is not given, Facter will resume logging messages.
# @param block [Proc] the callback to call when a message is logged.
# The first argument to the callback will be a symbol representing a level. The supported
# levels are: :trace, :debug, :info, :warn, :error, and :fatal.
# The second argument to the callback will be a string containing the message
# that was logged.
# @api public
def on_message(&block)
@@message_callback = block
end
# Prints a debug message if debugging is turned on
#
# @param msg [String] the debug message
# @return [void]
def debug(msg)
if self.debugging?
if msg.nil? or msg.empty?
invoker = caller[0].slice(/.*:\d+/)
self.warn "#{self.class}#debug invoked with invalid message #{msg.inspect}:#{msg.class} at #{invoker}"
elsif @@message_callback
@@message_callback.call(:debug, msg)
else
puts GREEN + msg + RESET
end
end
end
# Prints a debug message only once.
#
# @note Uniqueness is based on the string, not the specific location
# of the method call.
#
# @param msg [String] the debug message
# @return [void]
def debugonce(msg)
if msg and not msg.empty? and @@debug_messages[msg].nil?
@@debug_messages[msg] = true
debug(msg)
end
end
# Prints a warning message. The message is only printed if debugging
# is enabled.
#
# @param msg [String] the warning message to be printed
#
# @return [void]
def warn(msg)
if msg.nil? or msg.empty?
invoker = caller[0].slice(/.*:\d+/)
... Diferencia truncada por exceder el máximo tamaño visualizable.

Exportar a: Unified diff