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/pops/parser/locator.rb
lib/puppet/pops/parser/locator.rb
# frozen_string_literal: true module Puppet::Pops module Parser # Helper class that keeps track of where line breaks are located and can answer questions about positions. # class Locator # Creates, or recreates a Locator. A Locator is created if index is not given (a scan is then # performed of the given source string. # def self.locator(string, file, index = nil, char_offsets = false) if char_offsets LocatorForChars.new(string, file, index) else Locator19.new(string, file, index) end end # Returns the file name associated with the string content def file end # Returns the string content def string end def to_s "Locator for file #{file}" end # Returns the position on line (first position on a line is 1) def pos_on_line(offset) end # Returns the line number (first line is 1) for the given offset def line_for_offset(offset) end # Returns the offset on line (first offset on a line is 0). # def offset_on_line(offset) end # Returns the character offset for a given reported offset def char_offset(byte_offset) end # Returns the length measured in number of characters from the given start and end byte offset def char_length(offset, end_offset) end # Extracts the text from offset with given length (measured in what the locator uses for offset) # @returns String - the extracted text def extract_text(offset, length) end def extract_tree_text(ast) first = ast.offset last = first + ast.length ast._pcore_all_contents([]) do |m| next unless m.is_a?(Model::Positioned) m_offset = m.offset m_last = m_offset + m.length first = m_offset if m_offset < first last = m_last if m_last > last end extract_text(first, last - first) end # Returns the line index - an array of line offsets for the start position of each line, starting at 0 for # the first line. # def line_index end # Common byte based impl that works for all rubies (stringscanner is byte based def self.compute_line_index(string) scanner = StringScanner.new(string) result = [0] # first line starts at 0 while scanner.scan_until(/\n/) result << scanner.pos end result.freeze end # Produces an URI with path?line=n&pos=n. If origin is unknown the URI is string:?line=n&pos=n def to_uri(ast) f = file if f.nil? || f.empty? f = 'string:' else f = Puppet::Util.path_to_uri(f).to_s end offset = ast.offset URI("#{f}?line=#{line_for_offset(offset)}&pos=#{pos_on_line(offset)}") end class AbstractLocator < Locator attr_accessor :line_index attr_reader :string attr_reader :file # Create a locator based on a content string, and a boolean indicating if ruby version support multi-byte strings # or not. # def initialize(string, file, line_index = nil) @string = string.freeze @file = file.freeze @prev_offset = nil @prev_line = nil @line_index = line_index.nil? ? Locator.compute_line_index(@string) : line_index end # Returns the position on line (first position on a line is 1) def pos_on_line(offset) offset_on_line(offset) + 1 end def to_location_hash(reported_offset, end_offset) pos = pos_on_line(reported_offset) offset = char_offset(reported_offset) length = char_length(reported_offset, end_offset) start_line = line_for_offset(reported_offset) { :line => start_line, :pos => pos, :offset => offset, :length => length } end # Returns the index of the smallest item for which the item > the given value # This is a min binary search. Although written in Ruby it is only slightly slower than # the corresponding method in C in Ruby 2.0.0 - the main benefit to use this method over # the Ruby C version is that it returns the index (not the value) which means there is not need # to have an additional structure to get the index (or record the index in the structure). This # saves both memory and CPU. It also does not require passing a block that is called since this # method is specialized to search the line index. # def ary_bsearch_i(ary, value) low = 0 high = ary.length mid = nil smaller = false satisfied = false v = nil while low < high mid = low + ((high - low) / 2) v = (ary[mid] > value) if v == true satisfied = true smaller = true elsif !v smaller = false else raise TypeError, "wrong argument, must be boolean or nil, got '#{v.class}'" end if smaller high = mid else low = mid + 1; end end return nil if low == ary.length return nil unless satisfied low end def hash [string, file, line_index].hash end # Equal method needed by serializer to perform tabulation def eql?(o) self.class == o.class && string == o.string && file == o.file && line_index == o.line_index end # Returns the line number (first line is 1) for the given offset def line_for_offset(offset) if @prev_offset == offset # use cache return @prev_line end line_nbr = ary_bsearch_i(line_index, offset) if line_nbr # cache @prev_offset = offset @prev_line = line_nbr return line_nbr end # If not found it is after last # clear cache @prev_offset = @prev_line = nil line_index.size end end # A Sublocator locates a concrete locator (subspace) in a virtual space. # The `leading_line_count` is the (virtual) number of lines preceding the first line in the concrete locator. # The `leading_offset` is the (virtual) byte offset of the first byte in the concrete locator. # The `leading_line_offset` is the (virtual) offset / margin in characters for each line. # # This illustrates characters in the sublocator (`.`) inside the subspace (`X`): # # 1:XXXXXXXX # 2:XXXX.... .. ... .. # 3:XXXX. . .... .. # 4:XXXX............ # # This sublocator would be configured with leading_line_count = 1, # leading_offset=8, and leading_line_offset=4 # # Note that leading_offset must be the same for all lines and measured in characters. # # A SubLocator is only used during parsing as the parser will translate the local offsets/lengths to # the parent locator when a sublocated expression is reduced. Do not call the methods # `char_offset` or `char_length` as those methods will raise an error. # class SubLocator < AbstractLocator attr_reader :locator attr_reader :leading_line_count attr_reader :leading_offset attr_reader :has_margin attr_reader :margin_per_line def initialize(locator, str, leading_line_count, leading_offset, has_margin, margin_per_line) super(str, locator.file) @locator = locator @leading_line_count = leading_line_count @leading_offset = leading_offset @has_margin = has_margin @margin_per_line = margin_per_line # Since lines can have different margin - accumulated margin per line must be computed # and since this accumulated margin adjustment is needed more than once; both for start offset, # and for end offset (to compute global length) it is computed up front here. # The accumulated_offset holds the sum of all removed margins before a position on line n (line index is 1-n, # and (unused) position 0 is always 0). # The last entry is duplicated since there will be the line "after last line" that would otherwise require # conditional logic. # @accumulated_margin = margin_per_line.each_with_object([0]) { |val, memo| memo << memo[-1] + val; } @accumulated_margin << @accumulated_margin[-1] end def file @locator.file end # Returns array with transposed (local) offset and (local) length. The transposed values # take the margin into account such that it is added to the content to the right # # Using X to denote margin and where end of line is explicitly shown as \n: # ``` # XXXXabc\n # XXXXdef\n # ``` # A local offset of 0 is translated to the start of the first heredoc line, and a length of 1 is adjusted to # 5 - i.e to cover "XXXXa". A local offset of 1, with length 1 would cover "b". # A local offset of 4 and length 1 would cover "XXXXd" # # It is possible that lines have different margin and that is taken into account. # def to_global(offset, length) # simple case, no margin return [offset + @leading_offset, length] unless @has_margin # compute local start and end line start_line = line_for_offset(offset) end_line = line_for_offset(offset + length) # complex case when there is a margin transposed_offset = offset == 0 ? @leading_offset : offset + @leading_offset + @accumulated_margin[start_line] transposed_length = length + @accumulated_margin[end_line] - @accumulated_margin[start_line] + # the margins between start and end (0 is line 1) (offset_on_line(offset) == 0 ? margin_per_line[start_line - 1] : 0) # include start's margin in position 0 [transposed_offset, transposed_length] end # Do not call this method def char_offset(offset) raise "Should not be called" end # Do not call this method def char_length(offset, end_offset) raise "Should not be called" end end class LocatorForChars < AbstractLocator def offset_on_line(offset) line_offset = line_index[line_for_offset(offset) - 1] offset - line_offset end def char_offset(char_offset) char_offset end def char_length(offset, end_offset) end_offset - offset end # Extracts the text from char offset with given byte length # @returns String - the extracted text def extract_text(offset, length) string.slice(offset, length) end end # This implementation is for Ruby19 and Ruby20. It uses byteslice to get strings from byte based offsets. # For Ruby20 this is faster than using the Stringscanner.charpos method (byteslice outperforms it, when # strings are frozen). # class Locator19 < AbstractLocator include Types::PuppetObject # rubocop:disable Naming/MemoizedInstanceVariableName def self._pcore_type @type ||= Types::PObjectType.new('Puppet::AST::Locator', { 'attributes' => { 'string' => Types::PStringType::DEFAULT, 'file' => Types::PStringType::DEFAULT, 'line_index' => { Types::KEY_TYPE => Types::POptionalType.new(Types::PArrayType.new(Types::PIntegerType::DEFAULT)), Types::KEY_VALUE => nil } } }) end # rubocop:enable Naming/MemoizedInstanceVariableName # Returns the offset on line (first offset on a line is 0). # Ruby 19 is multibyte but has no character position methods, must use byteslice def offset_on_line(offset) line_offset = line_index[line_for_offset(offset) - 1] @string.byteslice(line_offset, offset - line_offset).length end # Returns the character offset for a given byte offset # Ruby 19 is multibyte but has no character position methods, must use byteslice def char_offset(byte_offset) string.byteslice(0, byte_offset).length end # Returns the length measured in number of characters from the given start and end byte offset def char_length(offset, end_offset) string.byteslice(offset, end_offset - offset).length end # Extracts the text from byte offset with given byte length # @returns String - the extracted text def extract_text(offset, length) string.byteslice(offset, length) end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/parser/slurp_support.rb
lib/puppet/pops/parser/slurp_support.rb
# frozen_string_literal: true module Puppet::Pops module Parser # This module is an integral part of the Lexer. # It defines the string slurping behavior - finding the string and non string parts in interpolated # strings, translating escape sequences in strings to their single character equivalence. # # PERFORMANCE NOTE: The various kinds of slurping could be made even more generic, but requires # additional parameter passing and evaluation of conditional logic. # TODO: More detailed performance analysis of excessive character escaping and interpolation. # module SlurpSupport include LexerSupport SLURP_SQ_PATTERN = /(?:[^\\]|^)(?:\\{2})*'/ SLURP_DQ_PATTERN = /(?:[^\\]|^)(?:\\{2})*("|[$]\{?)/ SLURP_UQ_PATTERN = /(?:[^\\]|^)(?:\\{2})*([$]\{?|\z)/ # unquoted, no escapes SLURP_UQNE_PATTERN = /(\$\{?|\z)/m SLURP_ALL_PATTERN = /.*(\z)/m SQ_ESCAPES = %w[\\ '] DQ_ESCAPES = %w[\\ $ ' " r n t s u] + ["\r\n", "\n"] UQ_ESCAPES = %w[\\ $ r n t s u] + ["\r\n", "\n"] def slurp_sqstring # skip the leading ' @scanner.pos += 1 str = slurp(@scanner, SLURP_SQ_PATTERN, SQ_ESCAPES, :ignore_invalid_escapes) lex_error(Issues::UNCLOSED_QUOTE, :after => "\"'\"", :followed_by => followed_by) unless str str[0..-2] # strip closing "'" from result end def slurp_dqstring scn = @scanner last = scn.matched str = slurp(scn, SLURP_DQ_PATTERN, DQ_ESCAPES, false) unless str lex_error(Issues::UNCLOSED_QUOTE, :after => format_quote(last), :followed_by => followed_by) end # Terminator may be a single char '"', '$', or two characters '${' group match 1 (scn[1]) from the last slurp holds this terminator = scn[1] [str[0..(-1 - terminator.length)], terminator] end # Copy from old lexer - can do much better def slurp_uqstring scn = @scanner str = slurp(scn, @lexing_context[:uq_slurp_pattern], @lexing_context[:escapes], :ignore_invalid_escapes) # Terminator may be a single char '$', two characters '${', or empty string '' at the end of intput. # Group match 1 holds this. # The exceptional case is found by looking at the subgroup 1 of the most recent match made by the scanner (i.e. @scanner[1]). # This is the last match made by the slurp method (having called scan_until on the scanner). # If there is a terminating character is must be stripped and returned separately. # terminator = scn[1] [str[0..(-1 - terminator.length)], terminator] end # Slurps a string from the given scanner until the given pattern and then replaces any escaped # characters given by escapes into their control-character equivalent or in case of line breaks, replaces the # pattern \r?\n with an empty string. # The returned string contains the terminating character. Returns nil if the scanner can not scan until the given # pattern. # def slurp(scanner, pattern, escapes, ignore_invalid_escapes) str = scanner.scan_until(pattern) || return return str unless str.include?('\\') return str.gsub!(/\\(\\|')/m, '\1') || str if escapes.equal?(SQ_ESCAPES) # Process unicode escapes first as they require getting 4 hex digits # If later a \u is found it is warned not to be a unicode escape if escapes.include?('u') # gsub must be repeated to cater for adjacent escapes while str.gsub!(/((?:[^\\]|^)(?:\\{2})*)\\u(?:([\da-fA-F]{4})|\{([\da-fA-F]{1,6})\})/m) { ::Regexp.last_match(1) + [(::Regexp.last_match(2) || ::Regexp.last_match(3)).hex].pack("U") } # empty block. Everything happens in the gsub block end end begin str.gsub!(/\\([^\r\n]|(?:\r?\n))/m) { ch = ::Regexp.last_match(1) if escapes.include? ch case ch when 'r'; "\r" when 'n'; "\n" when 't'; "\t" when 's'; ' ' when 'u' lex_warning(Issues::ILLEGAL_UNICODE_ESCAPE) "\\u" when "\n"; '' when "\r\n"; '' else ch end else lex_warning(Issues::UNRECOGNIZED_ESCAPE, :ch => ch) unless ignore_invalid_escapes "\\#{ch}" end } rescue ArgumentError => e # A invalid byte sequence may be the result of faulty input as well, but that could not possibly # have reached this far... Unfortunately there is no more specific error and a match on message is # required to differentiate from other internal problems. if e.message =~ /invalid byte sequence/ lex_error(Issues::ILLEGAL_UNICODE_ESCAPE) else raise e end end str 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/pops/parser/evaluating_parser.rb
lib/puppet/pops/parser/evaluating_parser.rb
# frozen_string_literal: true require_relative '../../../puppet/concurrent/thread_local_singleton' module Puppet::Pops module Parser # Does not support "import" and parsing ruby files # class EvaluatingParser extend Puppet::Concurrent::ThreadLocalSingleton attr_reader :parser def initialize @parser = Parser.new() end def parse_string(s, file_source = nil) clear() # Handling of syntax error can be much improved (in general), now it bails out of the parser # and does not have as rich information (when parsing a string), need to update it with the file source # (ideally, a syntax error should be entered as an issue, and not just thrown - but that is a general problem # and an improvement that can be made in the eparser (rather than here). # Also a possible improvement (if the YAML parser returns positions) is to provide correct output of position. # begin assert_and_report(parser.parse_string(s, file_source), file_source).model rescue Puppet::ParseErrorWithIssue => e raise e rescue Puppet::ParseError => e # TODO: This is not quite right, why does not the exception have the correct file? e.file = file_source unless e.file.is_a?(String) && !e.file.empty? raise e end end def parse_file(file) clear() assert_and_report(parser.parse_file(file), file).model end def evaluate_string(scope, s, file_source = nil) evaluate(scope, parse_string(s, file_source)) end def evaluate_file(scope, file) evaluate(scope, parse_file(file)) end def clear @acceptor = nil end # Create a closure that can be called in the given scope def closure(model, scope) Evaluator::Closure::Dynamic.new(evaluator, model, scope) end def evaluate(scope, model) return nil unless model evaluator.evaluate(model, scope) end # Evaluates the given expression in a local scope with the given variable bindings # set in this local scope, returns what the expression returns. # def evaluate_expression_with_bindings(scope, variable_bindings, expression) evaluator.evaluate_block_with_bindings(scope, variable_bindings, expression) end def evaluator # Do not use the cached evaluator if this is a migration run if Puppet.lookup(:migration_checker) { nil } return Evaluator::EvaluatorImpl.new() end @@evaluator ||= Evaluator::EvaluatorImpl.new() @@evaluator end def convert_to_3x(object, scope) evaluator.convert(object, scope, nil) end def validate(parse_result) resulting_acceptor = acceptor() validator(resulting_acceptor).validate(parse_result) resulting_acceptor end def acceptor Validation::Acceptor.new end def validator(acceptor) Validation::ValidatorFactory_4_0.new().validator(acceptor) end def assert_and_report(parse_result, file_source) return nil unless parse_result if parse_result['source_ref'].nil? || parse_result['source_ref'] == '' parse_result['source_ref'] = file_source end validation_result = validate(parse_result.model) IssueReporter.assert_and_report(validation_result, :emit_warnings => true) parse_result end def quote(x) self.class.quote(x) end # Translates an already parsed string that contains control characters, quotes # and backslashes into a quoted string where all such constructs have been escaped. # Parsing the return value of this method using the puppet parser should yield # exactly the same string as the argument passed to this method # # The method makes an exception for the two character sequences \$ and \s. They # will not be escaped since they have a special meaning in puppet syntax. # # TODO: Handle \uXXXX characters ?? # # @param x [String] The string to quote and "unparse" # @return [String] The quoted string # def self.quote(x) escaped = '"'.dup p = nil x.each_char do |c| case p when nil # do nothing when "\t" escaped << '\\t' when "\n" escaped << '\\n' when "\f" escaped << '\\f' # TODO: \cx is a range of characters - skip for now # when "\c" # escaped << '\\c' when '"' escaped << '\\"' when '\\' escaped << ((c == '$' || c == 's') ? p : '\\\\') # don't escape \ when followed by s or $ else escaped << p end p = c end escaped << p unless p.nil? escaped << '"' end class EvaluatingEppParser < EvaluatingParser def initialize @parser = EppParser.new() end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/parser/interpolation_support.rb
lib/puppet/pops/parser/interpolation_support.rb
# frozen_string_literal: true # This module is an integral part of the Lexer. # It defines interpolation support # PERFORMANCE NOTE: There are 4 very similar methods in this module that are designed to be as # performant as possible. While it is possible to parameterize them into one common method, the overhead # of passing parameters and evaluating conditional logic has a negative impact on performance. # module Puppet::Pops::Parser::InterpolationSupport PATTERN_VARIABLE = /(::)?(\w+::)*\w+/ # This is the starting point for a double quoted string with possible interpolation # The structure mimics that of the grammar. # The logic is explicit (where the former implementation used parameters/structures) given to a # generic handler. # (This is both easier to understand and faster). # def interpolate_dq scn = @scanner ctx = @lexing_context before = scn.pos # skip the leading " by doing a scan since the slurp_dqstring uses last matched when there is an error scn.scan(/"/) value, terminator = slurp_dqstring() text = value after = scn.pos loop do case terminator when '"' # simple case, there was no interpolation, return directly return emit_completed([:STRING, text, scn.pos - before], before) when '${' count = ctx[:brace_count] ctx[:brace_count] += 1 # The ${ terminator is counted towards the string part enqueue_completed([:DQPRE, text, scn.pos - before], before) # Lex expression tokens until a closing (balanced) brace count is reached enqueue_until count break when '$' varname = scn.scan(PATTERN_VARIABLE) if varname # The $ is counted towards the variable enqueue_completed([:DQPRE, text, after - before - 1], before) enqueue_completed([:VARIABLE, varname, scn.pos - after + 1], after - 1) break else # false $ variable start text += terminator value, terminator = slurp_dqstring() text += value after = scn.pos end end end interpolate_tail_dq # return the first enqueued token and shift the queue @token_queue.shift end def interpolate_tail_dq scn = @scanner ctx = @lexing_context before = scn.pos value, terminator = slurp_dqstring text = value after = scn.pos loop do case terminator when '"' # simple case, there was no further interpolation, return directly enqueue_completed([:DQPOST, text, scn.pos - before], before) return when '${' count = ctx[:brace_count] ctx[:brace_count] += 1 # The ${ terminator is counted towards the string part enqueue_completed([:DQMID, text, scn.pos - before], before) # Lex expression tokens until a closing (balanced) brace count is reached enqueue_until count break when '$' varname = scn.scan(PATTERN_VARIABLE) if varname # The $ is counted towards the variable enqueue_completed([:DQMID, text, after - before - 1], before) enqueue_completed([:VARIABLE, varname, scn.pos - after + 1], after - 1) break else # false $ variable start text += terminator value, terminator = slurp_dqstring text += value after = scn.pos end end end interpolate_tail_dq end # This is the starting point for a un-quoted string with possible interpolation # The logic is explicit (where the former implementation used parameters/strucures) given to a # generic handler. # (This is both easier to understand and faster). # def interpolate_uq scn = @scanner ctx = @lexing_context before = scn.pos value, terminator = slurp_uqstring() text = value after = scn.pos loop do case terminator when '' # simple case, there was no interpolation, return directly enqueue_completed([:STRING, text, scn.pos - before], before) return when '${' count = ctx[:brace_count] ctx[:brace_count] += 1 # The ${ terminator is counted towards the string part enqueue_completed([:DQPRE, text, scn.pos - before], before) # Lex expression tokens until a closing (balanced) brace count is reached enqueue_until count break when '$' varname = scn.scan(PATTERN_VARIABLE) if varname # The $ is counted towards the variable enqueue_completed([:DQPRE, text, after - before - 1], before) enqueue_completed([:VARIABLE, varname, scn.pos - after + 1], after - 1) break else # false $ variable start text += terminator value, terminator = slurp_uqstring() text += value after = scn.pos end end end interpolate_tail_uq nil end def interpolate_tail_uq scn = @scanner ctx = @lexing_context before = scn.pos value, terminator = slurp_uqstring text = value after = scn.pos loop do case terminator when '' # simple case, there was no further interpolation, return directly enqueue_completed([:DQPOST, text, scn.pos - before], before) return when '${' count = ctx[:brace_count] ctx[:brace_count] += 1 # The ${ terminator is counted towards the string part enqueue_completed([:DQMID, text, scn.pos - before], before) # Lex expression tokens until a closing (balanced) brace count is reached enqueue_until count break when '$' varname = scn.scan(PATTERN_VARIABLE) if varname # The $ is counted towards the variable enqueue_completed([:DQMID, text, after - before - 1], before) enqueue_completed([:VARIABLE, varname, scn.pos - after + 1], after - 1) break else # false $ variable start text += terminator value, terminator = slurp_uqstring text += value after = scn.pos end end end interpolate_tail_uq end # Enqueues lexed tokens until either end of input, or the given brace_count is reached # def enqueue_until brace_count scn = @scanner ctx = @lexing_context queue = @token_queue queue_base = @token_queue[0] scn.skip(self.class::PATTERN_WS) queue_size = queue.size until scn.eos? token = lex_token if token if token.equal?(queue_base) # A nested #interpolate_dq call shifted the queue_base token from the @token_queue. It must # be put back since it is intended for the top level #interpolate_dq call only. queue.insert(0, token) next # all relevant tokens are already on the queue end token_name = token[0] ctx[:after] = token_name if token_name == :RBRACE && ctx[:brace_count] == brace_count qlength = queue.size - queue_size if qlength == 1 # Single token is subject to replacement queue[-1] = transform_to_variable(queue[-1]) elsif qlength > 1 && [:DOT, :LBRACK].include?(queue[queue_size + 1][0]) # A first word, number of name token followed by '[' or '.' is subject to replacement # But not for other operators such as ?, +, - etc. where user must use a $ before the name # to get a variable queue[queue_size] = transform_to_variable(queue[queue_size]) end return end queue << token else scn.skip(self.class::PATTERN_WS) end end end def transform_to_variable(token) token_name = token[0] if [:NUMBER, :NAME, :WORD].include?(token_name) || self.class::KEYWORD_NAMES[token_name] || @taskm_keywords[token_name] t = token[1] ta = t.token_array [:VARIABLE, self.class::TokenValue.new([:VARIABLE, ta[1], ta[2]], t.offset, t.locator)] else token end end # Interpolates unquoted string and transfers the result to the given lexer # (This is used when a second lexer instance is used to lex a substring) # def interpolate_uq_to(lexer) interpolate_uq queue = @token_queue until queue.empty? lexer.enqueue(queue.shift) 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/pops/parser/locatable.rb
lib/puppet/pops/parser/locatable.rb
# frozen_string_literal: true # Interface for something that is "locatable" (holds offset and length). class Puppet::Pops::Parser::Locatable # The offset in the locator's content def offset end # The length in the locator from the given offset def length end # This class is useful for testing class Fixed < Puppet::Pops::Parser::Locatable attr_reader :offset attr_reader :length def initialize(offset, length) @offset = offset @length = length end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/parser/pn_parser.rb
lib/puppet/pops/parser/pn_parser.rb
# frozen_string_literal: true module Puppet::Pops module Parser class PNParser LIT_TRUE = 'true' LIT_FALSE = 'false' LIT_NIL = 'nil' TOKEN_END = 0 TOKEN_BOOL = 1 TOKEN_NIL = 2 TOKEN_INT = 3 TOKEN_FLOAT = 4 TOKEN_IDENTIFIER = 5 TOKEN_WS = 0x20 TOKEN_STRING = 0x22 TOKEN_KEY = 0x3a TOKEN_LP = 0x28 TOKEN_RP = 0x29 TOKEN_LB = 0x5b TOKEN_RB = 0x5d TOKEN_LC = 0x7b TOKEN_RC = 0x7d TYPE_END = 0 TYPE_WS = 1 TYPE_DELIM = 2 TYPE_KEY_START = 3 TYPE_STRING_START = 4 TYPE_IDENTIFIER = 5 TYPE_MINUS = 6 TYPE_DIGIT = 7 TYPE_ALPHA = 8 def initialize @char_types = self.class.char_types end def parse(text, locator = nil, offset = nil) @locator = locator @offset = offset @text = text @codepoints = text.codepoints.to_a.freeze @pos = 0 @token = TOKEN_END @token_value = nil next_token parse_next end def self.char_types unless instance_variable_defined?(:@char_types) @char_types = Array.new(0x80, TYPE_IDENTIFIER) @char_types[0] = TYPE_END [0x09, 0x0d, 0x0a, 0x20].each { |n| @char_types[n] = TYPE_WS } [TOKEN_LP, TOKEN_RP, TOKEN_LB, TOKEN_RB, TOKEN_LC, TOKEN_RC].each { |n| @char_types[n] = TYPE_DELIM } @char_types[0x2d] = TYPE_MINUS (0x30..0x39).each { |n| @char_types[n] = TYPE_DIGIT } (0x41..0x5a).each { |n| @char_types[n] = TYPE_ALPHA } (0x61..0x7a).each { |n| @char_types[n] = TYPE_ALPHA } @char_types[TOKEN_KEY] = TYPE_KEY_START @char_types[TOKEN_STRING] = TYPE_STRING_START @char_types.freeze end @char_types end private def parse_next case @token when TOKEN_LB parse_array when TOKEN_LC parse_map when TOKEN_LP parse_call when TOKEN_BOOL, TOKEN_INT, TOKEN_FLOAT, TOKEN_STRING, TOKEN_NIL parse_literal when TOKEN_END parse_error(_('unexpected end of input')) else parse_error(_('unexpected %{value}' % { value: @token_value })) end end def parse_error(message) file = '' line = 1 pos = 1 if @locator file = @locator.file line = @locator.line_for_offset(@offset) pos = @locator.pos_on_line(@offset) end @codepoints[0, @pos].each do |c| if c == 0x09 line += 1 pos = 1 end end raise Puppet::ParseError.new(message, file, line, pos) end def parse_literal pn = PN::Literal.new(@token_value) next_token pn end def parse_array next_token PN::List.new(parse_elements(TOKEN_RB)) end def parse_map next_token entries = [] while @token != TOKEN_RC && @token != TOKEN_END parse_error(_('map key expected')) unless @token == TOKEN_KEY key = @token_value next_token entries << parse_next.with_name(key) end next_token PN::Map.new(entries) end def parse_call next_token parse_error(_("expected identifier to follow '('")) unless @token == TOKEN_IDENTIFIER name = @token_value next_token PN::Call.new(name, *parse_elements(TOKEN_RP)) end def parse_elements(end_token) elements = [] while @token != end_token && @token != TOKEN_END elements << parse_next end parse_error(_("missing '%{token}' to end list") % { token: end_token.chr(Encoding::UTF_8) }) unless @token == end_token next_token elements end # All methods below belong to the PN lexer def next_token skip_white s = @pos c = next_cp case @char_types[c] when TYPE_END @token_value = nil @token = TOKEN_END when TYPE_MINUS if @char_types[peek_cp] == TYPE_DIGIT next_token # consume float or integer @token_value = -@token_value else consume_identifier(s) end when TYPE_DIGIT skip_decimal_digits c = peek_cp if c == 0x2e # '.' @pos += 1 consume_float(s, c) else @token_value = @text[s..@pos].to_i @token = TOKEN_INT end when TYPE_DELIM @token_value = @text[s] @token = c when TYPE_KEY_START if @char_types[peek_cp] == TYPE_ALPHA next_token @token = TOKEN_KEY else parse_error(_("expected identifier after ':'")) end when TYPE_STRING_START consume_string else consume_identifier(s) end end def consume_identifier(s) while @char_types[peek_cp] >= TYPE_IDENTIFIER @pos += 1 end id = @text[s...@pos] case id when LIT_TRUE @token = TOKEN_BOOL @token_value = true when LIT_FALSE @token = TOKEN_BOOL @token_value = false when LIT_NIL @token = TOKEN_NIL @token_value = nil else @token = TOKEN_IDENTIFIER @token_value = id end end def consume_string s = @pos b = ''.dup loop do c = next_cp case c when TOKEN_END @pos = s - 1 parse_error(_('unterminated quote')) when TOKEN_STRING @token_value = b @token = TOKEN_STRING break when 0x5c # '\' c = next_cp case c when 0x74 # 't' b << "\t" when 0x72 # 'r' b << "\r" when 0x6e # 'n' b << "\n" when TOKEN_STRING b << '"' when 0x5c # '\' b << "\\" when 0x6f # 'o' c = 0 3.times do n = next_cp if 0x30 <= n && n <= 0x37c c *= 8 c += n - 0x30 else parse_error(_('malformed octal quote')) end end b << c else b << "\\" b << c end else b << c end end end def consume_float(s, d) parse_error(_('digit expected')) if skip_decimal_digits == 0 c = peek_cp if d == 0x2e # '.' if c == 0x45 || c == 0x65 # 'E' or 'e' @pos += 1 parse_error(_('digit expected')) if skip_decimal_digits == 0 c = peek_cp end end parse_error(_('digit expected')) if @char_types[c] == TYPE_ALPHA @token_value = @text[s...@pos].to_f @token = TOKEN_FLOAT end def skip_decimal_digits count = 0 c = peek_cp if c == 0x2d || c == 0x2b # '-' or '+' @pos += 1 c = peek_cp end while @char_types[c] == TYPE_DIGIT @pos += 1 c = peek_cp count += 1 end count end def skip_white while @char_types[peek_cp] == TYPE_WS @pos += 1 end end def next_cp c = 0 if @pos < @codepoints.size c = @codepoints[@pos] @pos += 1 end c end def peek_cp @pos < @codepoints.size ? @codepoints[@pos] : 0 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/pops/parser/lexer_support.rb
lib/puppet/pops/parser/lexer_support.rb
# frozen_string_literal: true module Puppet::Pops module Parser require_relative '../../../puppet/util/multi_match' # This is an integral part of the Lexer. It is broken out into a separate module # for maintainability of the code, and making the various parts of the lexer focused. # module LexerSupport # Returns "<eof>" if at end of input, else the following 5 characters with \n \r \t escaped def followed_by return "<eof>" if @scanner.eos? result = @scanner.rest[0, 5] + "..." result.gsub!("\t", '\t') result.gsub!("\n", '\n') result.gsub!("\r", '\r') result end # Returns a quoted string using " or ' depending on the given a strings's content def format_quote(q) if q == "'" '"\'"' else "'#{q}'" end end # Raises a Puppet::LexError with the given message def lex_error_without_pos(issue, args = {}) raise Puppet::ParseErrorWithIssue.new(issue.format(args), nil, nil, nil, nil, issue.issue_code, args) end # Raises a Puppet::ParserErrorWithIssue with the given issue and arguments def lex_error(issue, args = {}, pos = nil) raise create_lex_error(issue, args, pos) end def filename file = @locator.file file.is_a?(String) && !file.empty? ? file : nil end def line(pos) @locator.line_for_offset(pos || @scanner.pos) end def position(pos) @locator.pos_on_line(pos || @scanner.pos) end def lex_warning(issue, args = {}, pos = nil) Puppet::Util::Log.create({ :level => :warning, :message => issue.format(args), :issue_code => issue.issue_code, :file => filename, :line => line(pos), :pos => position(pos), }) end # @param issue [Issues::Issue] the issue # @param args [Hash<Symbol,String>] Issue arguments # @param pos [Integer] # @return [Puppet::ParseErrorWithIssue] the created error def create_lex_error(issue, args = {}, pos = nil) Puppet::ParseErrorWithIssue.new( issue.format(args), filename, line(pos), position(pos), nil, issue.issue_code, args ) end # Asserts that the given string value is a float, or an integer in decimal, octal or hex form. # An error is raised if the given value does not comply. # def assert_numeric(value, pos) case value when /^0[xX]/ lex_error(Issues::INVALID_HEX_NUMBER, { :value => value }, pos) unless value =~ /^0[xX][0-9A-Fa-f]+$/ when /^0[^.]/ lex_error(Issues::INVALID_OCTAL_NUMBER, { :value => value }, pos) unless value =~ /^0[0-7]+$/ when /^\d+[eE.]/ lex_error(Issues::INVALID_DECIMAL_NUMBER, { :value => value }, pos) unless value =~ /^\d+(?:\.\d+)?(?:[eE]-?\d+)?$/ else lex_error(Issues::ILLEGAL_NUMBER, { :value => value }, pos) unless value =~ /^\d+$/ end end # A TokenValue keeps track of the token symbol, the lexed text for the token, its length # and its position in its source container. There is a cost associated with computing the # line and position on line information. # class TokenValue < Locatable attr_reader :token_array attr_reader :offset attr_reader :locator def initialize(token_array, offset, locator) @token_array = token_array @offset = offset @locator = locator end def length @token_array[2] end def [](key) case key when :value @token_array[1] when :file @locator.file when :line @locator.line_for_offset(@offset) when :pos @locator.pos_on_line(@offset) when :length @token_array[2] when :locator @locator when :offset @offset else nil end end def to_s # This format is very compact and is intended for debugging output from racc parser in # debug mode. If this is made more elaborate the output from a debug run becomes very hard to read. # "'#{self[:value]} #{@token_array[0]}'" end # TODO: Make this comparable for testing # vs symbolic, vs array with symbol and non hash, array with symbol and hash) # end MM = Puppet::Util::MultiMatch MM_ANY = MM::NOT_NIL BOM_UTF_8 = MM.new(0xEF, 0xBB, 0xBF, MM_ANY) BOM_UTF_16_1 = MM.new(0xFE, 0xFF, MM_ANY, MM_ANY) BOM_UTF_16_2 = MM.new(0xFF, 0xFE, MM_ANY, MM_ANY) BOM_UTF_32_1 = MM.new(0x00, 0x00, 0xFE, 0xFF) BOM_UTF_32_2 = MM.new(0xFF, 0xFE, 0x00, 0x00) BOM_UTF_1 = MM.new(0xF7, 0x64, 0x4C, MM_ANY) BOM_UTF_EBCDIC = MM.new(0xDD, 0x73, 0x66, 0x73) BOM_SCSU = MM.new(0x0E, 0xFE, 0xFF, MM_ANY) BOM_BOCU = MM.new(0xFB, 0xEE, 0x28, MM_ANY) BOM_GB_18030 = MM.new(0x84, 0x31, 0x95, 0x33) LONGEST_BOM = 4 def assert_not_bom(content) name, size = case bom = get_bom(content) when BOM_UTF_32_1, BOM_UTF_32_2 ['UTF-32', 4] when BOM_GB_18030 ['GB-18030', 4] when BOM_UTF_EBCDIC ['UTF-EBCDIC', 4] when BOM_SCSU ['SCSU', 3] when BOM_UTF_8 ['UTF-8', 3] when BOM_UTF_1 ['UTF-1', 3] when BOM_BOCU ['BOCU', 3] when BOM_UTF_16_1, BOM_UTF_16_2 ['UTF-16', 2] else return end lex_error_without_pos( Puppet::Pops::Issues::ILLEGAL_BOM, { :format_name => name, :bytes => "[#{bom.values[0, size].map { |b| '%X' % b }.join(' ')}]" } ) end def get_bom(content) # get 5 bytes as efficiently as possible (none of the string methods works since a bom consists of # illegal characters on most platforms, and there is no get_bytes(n). Explicit calls are faster than # looping with a lambda. The get_byte returns nil if there are too few characters, and they # are changed to spaces MM.new( (content.getbyte(0) || ' '), (content.getbyte(1) || ' '), (content.getbyte(2) || ' '), (content.getbyte(3) || ' ') ) 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/pops/parser/epp_support.rb
lib/puppet/pops/parser/epp_support.rb
# frozen_string_literal: true module Puppet::Pops module Parser # This module is an integral part of the Lexer. # It handles scanning of EPP (Embedded Puppet), a form of string/expression interpolation similar to ERB. # require 'strscan' module EppSupport TOKEN_RENDER_STRING = [:RENDER_STRING, nil, 0] TOKEN_RENDER_EXPR = [:RENDER_EXPR, nil, 0] # Scans all of the content and returns it in an array # Note that the terminating [false, false] token is included in the result. # def fullscan_epp result = [] scan_epp { |token, value| result.push([token, value]) } result end # A block must be passed to scan. It will be called with two arguments, a symbol for the token, # and an instance of LexerSupport::TokenValue # PERFORMANCE NOTE: The TokenValue is designed to reduce the amount of garbage / temporary data # and to only convert the lexer's internal tokens on demand. It is slightly more costly to create an # instance of a class defined in Ruby than an Array or Hash, but the gain is much bigger since transformation # logic is avoided for many of its members (most are never used (e.g. line/pos information which is only of # value in general for error messages, and for some expressions (which the lexer does not know about). # def scan_epp # PERFORMANCE note: it is faster to access local variables than instance variables. # This makes a small but notable difference since instance member access is avoided for # every token in the lexed content. # scn = @scanner ctx = @lexing_context queue = @token_queue lex_error(Issues::EPP_INTERNAL_ERROR, :error => 'No string or file given to lexer to process.') unless scn ctx[:epp_mode] = :text enqueue_completed([:EPP_START, nil, 0], 0) interpolate_epp # This is the lexer's main loop until queue.empty? && scn.eos? token = queue.shift || lex_token if token yield [ctx[:after] = token[0], token[1]] end end if ctx[:epp_open_position] lex_error(Issues::EPP_UNBALANCED_TAG, {}, ctx[:epp_position]) end # Signals end of input yield [false, false] end def interpolate_epp(skip_leading = false) scn = @scanner ctx = @lexing_context eppscanner = EppScanner.new(scn) before = scn.pos s = eppscanner.scan(skip_leading) case eppscanner.mode when :text # Should be at end of scan, or something is terribly wrong unless @scanner.eos? lex_error(Issues::EPP_INTERNAL_ERROR, :error => 'template scanner returns text mode and is not and end of input') end if s # s may be nil if scanned text ends with an epp tag (i.e. no trailing text). enqueue_completed([:RENDER_STRING, s, scn.pos - before], before) end ctx[:epp_open_position] = nil # do nothing else, scanner is at the end when :error lex_error(eppscanner.issue) when :epp # It is meaningless to render empty string segments, and it is harmful to do this at # the start of the scan as it prevents specification of parameters with <%- ($x, $y) -%> # if s && s.length > 0 enqueue_completed([:RENDER_STRING, s, scn.pos - before], before) end # switch epp_mode to general (embedded) pp logic (non rendered result) ctx[:epp_mode] = :epp ctx[:epp_open_position] = scn.pos when :expr # It is meaningless to render an empty string segment if s && s.length > 0 enqueue_completed([:RENDER_STRING, s, scn.pos - before], before) end enqueue_completed(TOKEN_RENDER_EXPR, before) # switch mode to "epp expr interpolation" ctx[:epp_mode] = :expr ctx[:epp_open_position] = scn.pos else lex_error(Issues::EPP_INTERNAL_ERROR, :error => "Unknown mode #{eppscanner.mode} returned by template scanner") end nil end # A scanner specialized in processing text with embedded EPP (Embedded Puppet) tags. # The scanner is initialized with a StringScanner which it mutates as scanning takes place. # The intent is to use one instance of EppScanner per wanted scan, and this instance represents # the state after the scan. # # @example Sample usage # a = "some text <% pp code %> some more text" # scan = StringScanner.new(a) # eppscan = EppScanner.new(scan) # str = eppscan.scan # eppscan.mode # => :epp # eppscan.lines # => 0 # eppscan # # The scanner supports # * scanning text until <%, <%-, <%= # * while scanning text: # * tokens <%% and %%> are translated to <% and %>, respectively, and is returned as text. # * tokens <%# and %> (or ending with -%>) and the enclosed text is a comment and is not included in the returned text # * text following a comment that ends with -%> gets trailing whitespace (up to and including a line break) trimmed # and this whitespace is not included in the returned text. # * The continuation {#mode} is set to one of: # * `:epp` - for a <% token # * `:expr` - for a <%= token # * `:text` - when there was no continuation mode (e.g. when input ends with text) # * ':error` - if the tokens are unbalanced (reaching the end without a closing matching token). An error message # is then also available via the method {#message}. # # Note that the intent is to use this specialized scanner to scan the text parts, when continuation mode is `:epp` or `:expr` # the pp lexer should advance scanning (using the string scanner) until it reaches and consumes a `-%>` or '%>´ token. If it # finds a `-%> token it should pass this on as a `skip_leading` parameter when it performs the next {#scan}. # class EppScanner # The original scanner used by the lexer/container using EppScanner attr_reader :scanner # The resulting mode after the scan. # The mode is one of `:text` (the initial mode), `:epp` embedded code (no output), `:expr` (embedded # expression), or `:error` # attr_reader :mode # An error issue if `mode == :error`, `nil` otherwise. attr_reader :issue # If the first scan should skip leading whitespace (typically detected by the pp lexer when the # pp mode end-token is found (i.e. `-%>`) and then passed on to the scanner. # attr_reader :skip_leading # Creates an EppScanner based on a StringScanner that represents the state where EppScanner should start scanning. # The given scanner will be mutated (i.e. position moved) to reflect the EppScanner's end state after a scan. # def initialize(scanner) @scanner = scanner end # Here for backwards compatibility. # @deprecated Use issue instead # @return [String] the issue message def message @issue.nil? ? nil : @issue.format end # Scans from the current position in the configured scanner, advances this scanner's position until the end # of the input, or to the first position after a mode switching token (`<%`, `<%-` or `<%=`). Number of processed # lines and continuation mode can be obtained via {#lines}, and {#mode}. # # @return [String, nil] the scanned and processed text, or nil if at the end of the input. # def scan(skip_leading = false) @mode = :text @skip_leading = skip_leading return nil if scanner.eos? s = ''.dup until scanner.eos? part = @scanner.scan_until(/(<%)|\z/) if @skip_leading part.sub!(/^[ \t]*\r?(?:\n|\z)?/, '') @skip_leading = false end # The spec for %%> is to transform it into a literal %>. This is done here, as %%> otherwise would go # undetected in text mode. (i.e. it is not really necessary to escape %> with %%> in text mode unless # adding checks stating that a literal %> is illegal in text (unbalanced). # part.gsub!(/%%>/, '%>') s += part case @scanner.peek(1) when "" # at the end # if s ends with <% then this is an error (unbalanced <% %>) if s.end_with? "<%" @mode = :error @issue = Issues::EPP_UNBALANCED_EXPRESSION end return s when "-" # trim trailing whitespace on same line from accumulated s # return text and signal switch to pp mode @scanner.getch # drop the - s.sub!(/[ \t]*<%\z/, '') @mode = :epp return s when "%" # verbatim text # keep the scanned <%, and continue scanning after skipping one % # (i.e. do nothing here) @scanner.getch # drop the % to get a literal <% in the output when "=" # expression # return text and signal switch to expression mode # drop the scanned <%, and skip past -%>, or %>, but also skip %%> @scanner.getch # drop the = s.slice!(-2..-1) @mode = :expr return s when "#" # template comment # drop the scanned <%, and skip past -%>, or %>, but also skip %%> s.slice!(-2..-1) # unless there is an immediate termination i.e. <%#%> scan for the next %> that is not # preceded by a % (i.e. skip %%>) part = scanner.scan_until(/[^%]%>/) unless part @issue = Issues::EPP_UNBALANCED_COMMENT @mode = :error return s end # Trim leading whitespace on the same line when start was <%#- if part[1] == '-' s.sub!(/[ \t]*\z/, '') end @skip_leading = true if part.end_with?("-%>") # Continue scanning for more text else # Switch to pp after having removed the <% s.slice!(-2..-1) @mode = :epp return s end end end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/parser/epp_parser.rb
lib/puppet/pops/parser/epp_parser.rb
# frozen_string_literal: true # The EppParser is a specialized Puppet Parser that starts parsing in Epp Text mode class Puppet::Pops::Parser::EppParser < Puppet::Pops::Parser::Parser # Initializes the epp parser support by creating a new instance of {Puppet::Pops::Parser::Lexer} # configured to start in Epp Lexing mode. # @return [void] # def initvars self.lexer = Puppet::Pops::Parser::Lexer2.new() end # Parses a file expected to contain epp text/DSL logic. def parse_file(file) unless FileTest.exist?(file) unless file =~ /\.epp$/ file += ".epp" end end @lexer.file = file _parse() end # Performs the parsing and returns the resulting model. # The lexer holds state, and this is setup with {#parse_string}, or {#parse_file}. # # TODO: deal with options containing origin (i.e. parsing a string from externally known location). # TODO: should return the model, not a Hostclass # # @api private # def _parse begin @yydebug = false main = yyparse(@lexer, :scan_epp) # #Commented out now because this hides problems in the racc grammar while developing # # TODO include this when test coverage is good enough. # rescue Puppet::ParseError => except # except.line ||= @lexer.line # except.file ||= @lexer.file # except.pos ||= @lexer.pos # raise except # rescue => except # raise Puppet::ParseError.new(except.message, @lexer.file, @lexer.line, @lexer.pos, except) end main ensure @lexer.clear @namestack = [] @definitions = [] 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/pops/parser/heredoc_support.rb
lib/puppet/pops/parser/heredoc_support.rb
# frozen_string_literal: true module Puppet::Pops module Parser module HeredocSupport include LexerSupport # Pattern for heredoc `@(endtag[:syntax][/escapes]) # Produces groups for endtag (group 1), syntax (group 2), and escapes (group 3) # PATTERN_HEREDOC = %r{@\(([^:/\r\n)]+)(?::[[:blank:]]*([a-z][a-zA-Z0-9_+]+)[[:blank:]]*)?(?:/((?:\w|[$])*)[[:blank:]]*)?\)} def heredoc scn = @scanner ctx = @lexing_context locator = @locator before = scn.pos # scanner is at position before @( # find end of the heredoc spec str = scn.scan_until(/\)/) || lex_error(Issues::HEREDOC_UNCLOSED_PARENTHESIS, :followed_by => followed_by) pos_after_heredoc = scn.pos # Note: allows '+' as separator in syntax, but this needs validation as empty segments are not allowed md = str.match(PATTERN_HEREDOC) lex_error(Issues::HEREDOC_INVALID_SYNTAX) unless md endtag = md[1] syntax = md[2] || '' escapes = md[3] endtag.strip! # Is this a dq string style heredoc? (endtag enclosed in "") if endtag =~ /^"(.*)"$/ dqstring_style = true endtag = ::Regexp.last_match(1).strip end lex_error(Issues::HEREDOC_EMPTY_ENDTAG) unless endtag.length >= 1 resulting_escapes = [] if escapes escapes = "trnsuL$" if escapes.length < 1 escapes = escapes.split('') unless escapes.length == escapes.uniq.length lex_error(Issues::HEREDOC_MULTIPLE_AT_ESCAPES, :escapes => escapes) end resulting_escapes = ["\\"] escapes.each do |e| case e when "t", "r", "n", "s", "u", "$" resulting_escapes << e when "L" resulting_escapes += ["\n", "\r\n"] else lex_error(Issues::HEREDOC_INVALID_ESCAPE, :actual => e) end end end # Produce a heredoc token to make the syntax available to the grammar enqueue_completed([:HEREDOC, syntax, pos_after_heredoc - before], before) # If this is the second or subsequent heredoc on the line, the lexing context's :newline_jump contains # the position after the \n where the next heredoc text should scan. If not set, this is the first # and it should start scanning after the first found \n (or if not found == error). if ctx[:newline_jump] scn.pos = ctx[:newline_jump] else scn.scan_until(/\n/) || lex_error(Issues::HEREDOC_WITHOUT_TEXT) end # offset 0 for the heredoc, and its line number heredoc_offset = scn.pos heredoc_line = locator.line_for_offset(heredoc_offset) - 1 # Compute message to emit if there is no end (to make it refer to the opening heredoc position). eof_error = create_lex_error(Issues::HEREDOC_WITHOUT_END_TAGGED_LINE) # Text from this position (+ lexing contexts offset for any preceding heredoc) is heredoc until a line # that terminates the heredoc is found. # (Endline in EBNF form): WS* ('|' WS*)? ('-' WS*)? endtag WS* \r? (\n|$) endline_pattern = /([[:blank:]]*)(?:([|])[[:blank:]]*)?(?:(-)[[:blank:]]*)?#{Regexp.escape(endtag)}[[:blank:]]*\r?(?:\n|\z)/ lines = [] until scn.eos? one_line = scn.scan_until(/(?:\n|\z)/) raise eof_error unless one_line md = one_line.match(endline_pattern) if md leading = md[1] has_margin = md[2] == '|' remove_break = md[3] == '-' # Record position where next heredoc (from same line as current @()) should start scanning for content ctx[:newline_jump] = scn.pos # Process captured lines - remove leading, and trailing newline # get processed string and index of removed margin/leading size per line str, margin_per_line = heredoc_text(lines, leading, has_margin, remove_break) # Use a new lexer instance configured with a sub-locator to enable correct positioning sublexer = self.class.new() locator = Locator::SubLocator.new(locator, str, heredoc_line, heredoc_offset, has_margin, margin_per_line) # Emit a token that provides the grammar with location information about the lines on which the heredoc # content is based. enqueue([:SUBLOCATE, LexerSupport::TokenValue.new([:SUBLOCATE, lines, lines.reduce(0) { |size, s| size + s.length }], heredoc_offset, locator)]) sublexer.lex_unquoted_string(str, locator, resulting_escapes, dqstring_style) sublexer.interpolate_uq_to(self) # Continue scan after @(...) scn.pos = pos_after_heredoc return else lines << one_line end end raise eof_error end # Produces the heredoc text string given the individual (unprocessed) lines as an array and array with margin sizes per line # @param lines [Array<String>] unprocessed lines of text in the heredoc w/o terminating line # @param leading [String] the leading text up (up to pipe or other terminating char) # @param has_margin [Boolean] if the left margin should be adjusted as indicated by `leading` # @param remove_break [Boolean] if the line break (\r?\n) at the end of the last line should be removed or not # @return [Array] - a tuple with resulting string, and an array with margin size per line # def heredoc_text(lines, leading, has_margin, remove_break) if has_margin && leading.length > 0 leading_pattern = /^#{Regexp.escape(leading)}/ # TODO: This implementation is not according to the specification, but is kept to be bug compatible. # The specification says that leading space up to the margin marker should be removed, but this implementation # simply leaves lines that have text in the margin untouched. # processed_lines = lines.collect { |s| s.gsub(leading_pattern, '') } margin_per_line = Array.new(processed_lines.length) { |x| lines[x].length - processed_lines[x].length } lines = processed_lines else # Array with a 0 per line margin_per_line = Array.new(lines.length, 0) end result = lines.join('') result.gsub!(/\r?\n\z/m, '') if remove_break [result, margin_per_line] 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/pops/parser/lexer2.rb
lib/puppet/pops/parser/lexer2.rb
# frozen_string_literal: true # The Lexer is responsible for turning source text into tokens. # This version is a performance enhanced lexer (in comparison to the 3.x and earlier "future parser" lexer. # # Old returns tokens [:KEY, value, { locator = } # Could return [[token], locator] # or Token.new([token], locator) with the same API x[0] = token_symbol, x[1] = self, x[:key] = (:value, :file, :line, :pos) etc require 'strscan' require_relative '../../../puppet/pops/parser/lexer_support' require_relative '../../../puppet/pops/parser/heredoc_support' require_relative '../../../puppet/pops/parser/interpolation_support' require_relative '../../../puppet/pops/parser/epp_support' require_relative '../../../puppet/pops/parser/slurp_support' module Puppet::Pops module Parser class Lexer2 include LexerSupport include HeredocSupport include InterpolationSupport include SlurpSupport include EppSupport # ALl tokens have three slots, the token name (a Symbol), the token text (String), and a token text length. # All operator and punctuation tokens reuse singleton arrays Tokens that require unique values create # a unique array per token. # # PEFORMANCE NOTES: # This construct reduces the amount of object that needs to be created for operators and punctuation. # The length is pre-calculated for all singleton tokens. The length is used both to signal the length of # the token, and to advance the scanner position (without having to advance it with a scan(regexp)). # TOKEN_LBRACK = [:LBRACK, '[', 1].freeze TOKEN_LISTSTART = [:LISTSTART, '[', 1].freeze TOKEN_RBRACK = [:RBRACK, ']', 1].freeze TOKEN_LBRACE = [:LBRACE, '{', 1].freeze TOKEN_RBRACE = [:RBRACE, '}', 1].freeze TOKEN_SELBRACE = [:SELBRACE, '{', 1].freeze TOKEN_LPAREN = [:LPAREN, '(', 1].freeze TOKEN_WSLPAREN = [:WSLPAREN, '(', 1].freeze TOKEN_RPAREN = [:RPAREN, ')', 1].freeze TOKEN_EQUALS = [:EQUALS, '=', 1].freeze TOKEN_APPENDS = [:APPENDS, '+=', 2].freeze TOKEN_DELETES = [:DELETES, '-=', 2].freeze TOKEN_ISEQUAL = [:ISEQUAL, '==', 2].freeze TOKEN_NOTEQUAL = [:NOTEQUAL, '!=', 2].freeze TOKEN_MATCH = [:MATCH, '=~', 2].freeze TOKEN_NOMATCH = [:NOMATCH, '!~', 2].freeze TOKEN_GREATEREQUAL = [:GREATEREQUAL, '>=', 2].freeze TOKEN_GREATERTHAN = [:GREATERTHAN, '>', 1].freeze TOKEN_LESSEQUAL = [:LESSEQUAL, '<=', 2].freeze TOKEN_LESSTHAN = [:LESSTHAN, '<', 1].freeze TOKEN_FARROW = [:FARROW, '=>', 2].freeze TOKEN_PARROW = [:PARROW, '+>', 2].freeze TOKEN_LSHIFT = [:LSHIFT, '<<', 2].freeze TOKEN_LLCOLLECT = [:LLCOLLECT, '<<|', 3].freeze TOKEN_LCOLLECT = [:LCOLLECT, '<|', 2].freeze TOKEN_RSHIFT = [:RSHIFT, '>>', 2].freeze TOKEN_RRCOLLECT = [:RRCOLLECT, '|>>', 3].freeze TOKEN_RCOLLECT = [:RCOLLECT, '|>', 2].freeze TOKEN_PLUS = [:PLUS, '+', 1].freeze TOKEN_MINUS = [:MINUS, '-', 1].freeze TOKEN_DIV = [:DIV, '/', 1].freeze TOKEN_TIMES = [:TIMES, '*', 1].freeze TOKEN_MODULO = [:MODULO, '%', 1].freeze # rubocop:disable Layout/SpaceBeforeComma TOKEN_NOT = [:NOT, '!', 1].freeze TOKEN_DOT = [:DOT, '.', 1].freeze TOKEN_PIPE = [:PIPE, '|', 1].freeze TOKEN_AT = [:AT , '@', 1].freeze TOKEN_ATAT = [:ATAT , '@@', 2].freeze TOKEN_COLON = [:COLON, ':', 1].freeze TOKEN_COMMA = [:COMMA, ',', 1].freeze TOKEN_SEMIC = [:SEMIC, ';', 1].freeze TOKEN_QMARK = [:QMARK, '?', 1].freeze TOKEN_TILDE = [:TILDE, '~', 1].freeze # lexed but not an operator in Puppet # rubocop:enable Layout/SpaceBeforeComma TOKEN_REGEXP = [:REGEXP, nil, 0].freeze TOKEN_IN_EDGE = [:IN_EDGE, '->', 2].freeze TOKEN_IN_EDGE_SUB = [:IN_EDGE_SUB, '~>', 2].freeze TOKEN_OUT_EDGE = [:OUT_EDGE, '<-', 2].freeze TOKEN_OUT_EDGE_SUB = [:OUT_EDGE_SUB, '<~', 2].freeze # Tokens that are always unique to what has been lexed TOKEN_STRING = [:STRING, nil, 0].freeze TOKEN_WORD = [:WORD, nil, 0].freeze TOKEN_DQPRE = [:DQPRE, nil, 0].freeze TOKEN_DQMID = [:DQPRE, nil, 0].freeze TOKEN_DQPOS = [:DQPRE, nil, 0].freeze TOKEN_NUMBER = [:NUMBER, nil, 0].freeze TOKEN_VARIABLE = [:VARIABLE, nil, 1].freeze TOKEN_VARIABLE_EMPTY = [:VARIABLE, '', 1].freeze # HEREDOC has syntax as an argument. TOKEN_HEREDOC = [:HEREDOC, nil, 0].freeze # EPP_START is currently a marker token, may later get syntax # rubocop:disable Layout/ExtraSpacing TOKEN_EPPSTART = [:EPP_START, nil, 0].freeze TOKEN_EPPEND = [:EPP_END, '%>', 2].freeze TOKEN_EPPEND_TRIM = [:EPP_END_TRIM, '-%>', 3].freeze # rubocop:enable Layout/ExtraSpacing # This is used for unrecognized tokens, will always be a single character. This particular instance # is not used, but is kept here for documentation purposes. TOKEN_OTHER = [:OTHER, nil, 0] # Keywords are all singleton tokens with pre calculated lengths. # Booleans are pre-calculated (rather than evaluating the strings "false" "true" repeatedly. # KEYWORDS = { 'case' => [:CASE, 'case', 4], 'class' => [:CLASS, 'class', 5], 'default' => [:DEFAULT, 'default', 7], 'define' => [:DEFINE, 'define', 6], 'if' => [:IF, 'if', 2], 'elsif' => [:ELSIF, 'elsif', 5], 'else' => [:ELSE, 'else', 4], 'inherits' => [:INHERITS, 'inherits', 8], 'node' => [:NODE, 'node', 4], 'and' => [:AND, 'and', 3], 'or' => [:OR, 'or', 2], 'undef' => [:UNDEF, 'undef', 5], 'false' => [:BOOLEAN, false, 5], 'true' => [:BOOLEAN, true, 4], 'in' => [:IN, 'in', 2], 'unless' => [:UNLESS, 'unless', 6], 'function' => [:FUNCTION, 'function', 8], 'type' => [:TYPE, 'type', 4], 'attr' => [:ATTR, 'attr', 4], 'private' => [:PRIVATE, 'private', 7], } KEYWORDS.each { |_k, v| v[1].freeze; v.freeze } KEYWORDS.freeze # Reverse lookup of keyword name to string KEYWORD_NAMES = {} KEYWORDS.each { |k, v| KEYWORD_NAMES[v[0]] = k } KEYWORD_NAMES.freeze PATTERN_WS = /[[:blank:]\r]+/ PATTERN_NON_WS = /\w+\b?/ # The single line comment includes the line ending. PATTERN_COMMENT = /#.*\r?/ PATTERN_MLCOMMENT = %r{/\*(.*?)\*/}m PATTERN_REGEX = %r{/[^/]*/} PATTERN_REGEX_END = %r{/} PATTERN_REGEX_A = %r{\A/} # for replacement to "" PATTERN_REGEX_Z = %r{/\Z} # for replacement to "" PATTERN_REGEX_ESC = %r{\\/} # for replacement to "/" # The 3x patterns: # PATTERN_CLASSREF = %r{((::){0,1}[A-Z][-\w]*)+} # PATTERN_NAME = %r{((::)?[a-z0-9][-\w]*)(::[a-z0-9][-\w]*)*} # The NAME and CLASSREF in 4x are strict. Each segment must start with # a letter a-z and may not contain dashes (\w includes letters, digits and _). # PATTERN_CLASSREF = /((::){0,1}[A-Z]\w*)+/ PATTERN_NAME = /^((::)?[a-z]\w*)(::[a-z]\w*)*$/ PATTERN_BARE_WORD = /((?:::){0,1}(?:[a-z_](?:[\w-]*\w)?))+/ PATTERN_DOLLAR_VAR = /\$(::)?(\w+::)*\w+/ PATTERN_NUMBER = /\b(?:0[xX][0-9A-Fa-f]+|0?\d+(?:\.\d+)?(?:[eE]-?\d+)?)\b/ # PERFORMANCE NOTE: # Comparison against a frozen string is faster (than unfrozen). # STRING_BSLASH_SLASH = '\/' attr_reader :locator def initialize @selector = { '.' => -> { emit(TOKEN_DOT, @scanner.pos) }, ',' => -> { emit(TOKEN_COMMA, @scanner.pos) }, '[' => lambda do before = @scanner.pos # Must check the preceding character to see if it is whitespace. # The fastest thing to do is to simply byteslice to get the string ending at the offset before # and then check what the last character is. (This is the same as what an locator.char_offset needs # to compute, but with less overhead of trying to find out the global offset from a local offset in the # case when this is sublocated in a heredoc). if before == 0 || @scanner.string.byteslice(0, before)[-1] =~ /[[:blank:]\r\n]+/ emit(TOKEN_LISTSTART, before) else emit(TOKEN_LBRACK, before) end end, ']' => -> { emit(TOKEN_RBRACK, @scanner.pos) }, '(' => lambda do before = @scanner.pos # If first on a line, or only whitespace between start of line and '(' # then the token is special to avoid being taken as start of a call. line_start = @lexing_context[:line_lexical_start] if before == line_start || @scanner.string.byteslice(line_start, before - line_start) =~ /\A[[:blank:]\r]+\Z/ emit(TOKEN_WSLPAREN, before) else emit(TOKEN_LPAREN, before) end end, ')' => -> { emit(TOKEN_RPAREN, @scanner.pos) }, ';' => -> { emit(TOKEN_SEMIC, @scanner.pos) }, '?' => -> { emit(TOKEN_QMARK, @scanner.pos) }, '*' => -> { emit(TOKEN_TIMES, @scanner.pos) }, '%' => lambda do scn = @scanner before = scn.pos la = scn.peek(2) if la[1] == '>' && @lexing_context[:epp_mode] scn.pos += 2 if @lexing_context[:epp_mode] == :expr enqueue_completed(TOKEN_EPPEND, before) end @lexing_context[:epp_mode] = :text interpolate_epp else emit(TOKEN_MODULO, before) end end, '{' => lambda do # The lexer needs to help the parser since the technology used cannot deal with # lookahead of same token with different precedence. This is solved by making left brace # after ? into a separate token. # @lexing_context[:brace_count] += 1 emit(if @lexing_context[:after] == :QMARK TOKEN_SELBRACE else TOKEN_LBRACE end, @scanner.pos) end, '}' => lambda do @lexing_context[:brace_count] -= 1 emit(TOKEN_RBRACE, @scanner.pos) end, # TOKENS @, @@, @( '@' => lambda do scn = @scanner la = scn.peek(2) case la[1] when '@' emit(TOKEN_ATAT, scn.pos) # TODO; Check if this is good for the grammar when '(' heredoc else emit(TOKEN_AT, scn.pos) end end, # TOKENS |, |>, |>> '|' => lambda do scn = @scanner la = scn.peek(3) emit(if la[1] == '>' la[2] == '>' ? TOKEN_RRCOLLECT : TOKEN_RCOLLECT else TOKEN_PIPE end, scn.pos) end, # TOKENS =, =>, ==, =~ '=' => lambda do scn = @scanner la = scn.peek(2) emit(case la[1] when '=' TOKEN_ISEQUAL when '>' TOKEN_FARROW when '~' TOKEN_MATCH else TOKEN_EQUALS end, scn.pos) end, # TOKENS '+', '+=', and '+>' '+' => lambda do scn = @scanner la = scn.peek(2) emit(case la[1] when '=' TOKEN_APPENDS when '>' TOKEN_PARROW else TOKEN_PLUS end, scn.pos) end, # TOKENS '-', '->', and epp '-%>' (end of interpolation with trim) '-' => lambda do scn = @scanner la = scn.peek(3) before = scn.pos if @lexing_context[:epp_mode] && la[1] == '%' && la[2] == '>' scn.pos += 3 if @lexing_context[:epp_mode] == :expr enqueue_completed(TOKEN_EPPEND_TRIM, before) end interpolate_epp(:with_trim) else emit(case la[1] when '>' TOKEN_IN_EDGE when '=' TOKEN_DELETES else TOKEN_MINUS end, before) end end, # TOKENS !, !=, !~ '!' => lambda do scn = @scanner la = scn.peek(2) emit(case la[1] when '=' TOKEN_NOTEQUAL when '~' TOKEN_NOMATCH else TOKEN_NOT end, scn.pos) end, # TOKENS ~>, ~ '~' => lambda do scn = @scanner la = scn.peek(2) emit(la[1] == '>' ? TOKEN_IN_EDGE_SUB : TOKEN_TILDE, scn.pos) end, '#' => -> { @scanner.skip(PATTERN_COMMENT); nil }, # TOKENS '/', '/*' and '/ regexp /' '/' => lambda do scn = @scanner la = scn.peek(2) if la[1] == '*' lex_error(Issues::UNCLOSED_MLCOMMENT) if scn.skip(PATTERN_MLCOMMENT).nil? nil else before = scn.pos # regexp position is a regexp, else a div value = scn.scan(PATTERN_REGEX) if regexp_acceptable? if value # Ensure an escaped / was not matched while escaped_end(value) more = scn.scan_until(PATTERN_REGEX_END) return emit(TOKEN_DIV, before) unless more value << more end regex = value.sub(PATTERN_REGEX_A, '').sub(PATTERN_REGEX_Z, '').gsub(PATTERN_REGEX_ESC, '/') emit_completed([:REGEX, Regexp.new(regex), scn.pos - before], before) else emit(TOKEN_DIV, before) end end end, # TOKENS <, <=, <|, <<|, <<, <-, <~ '<' => lambda do scn = @scanner la = scn.peek(3) emit(case la[1] when '<' if la[2] == '|' TOKEN_LLCOLLECT else TOKEN_LSHIFT end when '=' TOKEN_LESSEQUAL when '|' TOKEN_LCOLLECT when '-' TOKEN_OUT_EDGE when '~' TOKEN_OUT_EDGE_SUB else TOKEN_LESSTHAN end, scn.pos) end, # TOKENS >, >=, >> '>' => lambda do scn = @scanner la = scn.peek(2) emit(case la[1] when '>' TOKEN_RSHIFT when '=' TOKEN_GREATEREQUAL else TOKEN_GREATERTHAN end, scn.pos) end, # TOKENS :, ::CLASSREF, ::NAME ':' => lambda do scn = @scanner la = scn.peek(3) before = scn.pos if la[1] == ':' # PERFORMANCE NOTE: This could potentially be speeded up by using a case/when listing all # upper case letters. Alternatively, the 'A', and 'Z' comparisons may be faster if they are # frozen. # la2 = la[2] if la2 >= 'A' && la2 <= 'Z' # CLASSREF or error value = scn.scan(PATTERN_CLASSREF) if value && scn.peek(2) != '::' after = scn.pos emit_completed([:CLASSREF, value.freeze, after - before], before) else # move to faulty position ('::<uc-letter>' was ok) scn.pos = scn.pos + 3 lex_error(Issues::ILLEGAL_FULLY_QUALIFIED_CLASS_REFERENCE) end else value = scn.scan(PATTERN_BARE_WORD) if value if value =~ PATTERN_NAME emit_completed([:NAME, value.freeze, scn.pos - before], before) else emit_completed([:WORD, value.freeze, scn.pos - before], before) end else # move to faulty position ('::' was ok) scn.pos = scn.pos + 2 lex_error(Issues::ILLEGAL_FULLY_QUALIFIED_NAME) end end else emit(TOKEN_COLON, before) end end, '$' => lambda do scn = @scanner before = scn.pos value = scn.scan(PATTERN_DOLLAR_VAR) if value emit_completed([:VARIABLE, value[1..].freeze, scn.pos - before], before) else # consume the $ and let higher layer complain about the error instead of getting a syntax error emit(TOKEN_VARIABLE_EMPTY, before) end end, '"' => lambda do # Recursive string interpolation, 'interpolate' either returns a STRING token, or # a DQPRE with the rest of the string's tokens placed in the @token_queue interpolate_dq end, "'" => lambda do scn = @scanner before = scn.pos emit_completed([:STRING, slurp_sqstring.freeze, scn.pos - before], before) end, "\n" => lambda do # If heredoc_cont is in effect there are heredoc text lines to skip over # otherwise just skip the newline. # ctx = @lexing_context if ctx[:newline_jump] @scanner.pos = ctx[:newline_jump] ctx[:newline_jump] = nil else @scanner.pos += 1 end ctx[:line_lexical_start] = @scanner.pos nil end, '' => -> { nil } # when the peek(1) returns empty } [' ', "\t", "\r"].each { |c| @selector[c] = -> { @scanner.skip(PATTERN_WS); nil } } ('0'..'9').each do |c| @selector[c] = lambda do scn = @scanner before = scn.pos value = scn.scan(PATTERN_NUMBER) if value length = scn.pos - before assert_numeric(value, before) emit_completed([:NUMBER, value.freeze, length], before) else invalid_number = scn.scan_until(PATTERN_NON_WS) if before > 1 after = scn.pos scn.pos = before - 1 if scn.peek(1) == '.' # preceded by a dot. Is this a bad decimal number then? scn.pos = before - 2 while scn.peek(1) =~ /^\d$/ invalid_number = nil before = scn.pos break if before == 0 scn.pos = scn.pos - 1 end end scn.pos = before invalid_number ||= scn.peek(after - before) end assert_numeric(invalid_number, before) scn.pos = before + 1 lex_error(Issues::ILLEGAL_NUMBER, { :value => invalid_number }) end end end ('a'..'z').to_a.push('_').each do |c| @selector[c] = lambda do scn = @scanner before = scn.pos value = scn.scan(PATTERN_BARE_WORD) if value && value =~ PATTERN_NAME emit_completed(KEYWORDS[value] || @taskm_keywords[value] || [:NAME, value.freeze, scn.pos - before], before) elsif value emit_completed([:WORD, value.freeze, scn.pos - before], before) else # move to faulty position ([a-z_] was ok) scn.pos = scn.pos + 1 fully_qualified = scn.match?(/::/) if fully_qualified lex_error(Issues::ILLEGAL_FULLY_QUALIFIED_NAME) else lex_error(Issues::ILLEGAL_NAME_OR_BARE_WORD) end end end end ('A'..'Z').each do |c| @selector[c] = lambda do scn = @scanner before = scn.pos value = @scanner.scan(PATTERN_CLASSREF) if value && @scanner.peek(2) != '::' emit_completed([:CLASSREF, value.freeze, scn.pos - before], before) else # move to faulty position ([A-Z] was ok) scn.pos = scn.pos + 1 lex_error(Issues::ILLEGAL_CLASS_REFERENCE) end end end @selector.default = lambda do # In case of unicode spaces of various kinds that are captured by a regexp, but not by the # simpler case expression above (not worth handling those special cases with better performance). scn = @scanner if scn.skip(PATTERN_WS) nil else # "unrecognized char" emit([:OTHER, scn.peek(0), 1], scn.pos) end end @selector.each { |k, _v| k.freeze } @selector.freeze end # Determine if last char of value is escaped by a backslash def escaped_end(value) escaped = false if value.end_with?(STRING_BSLASH_SLASH) value[1...-1].each_codepoint do |cp| if cp == 0x5c # backslash escaped = !escaped else escaped = false end end end escaped end # Clears the lexer state (it is not required to call this as it will be garbage collected # and the next lex call (lex_string, lex_file) will reset the internal state. # def clear # not really needed, but if someone wants to ensure garbage is collected as early as possible @scanner = nil @locator = nil @lexing_context = nil end # Convenience method, and for compatibility with older lexer. Use the lex_string instead which allows # passing the path to use without first having to call file= (which reads the file if it exists). # (Bad form to use overloading of assignment operator for something that is not really an assignment. Also, # overloading of = does not allow passing more than one argument). # def string=(string) lex_string(string, nil) end def lex_string(string, path = nil) initvars assert_not_bom(string) @scanner = StringScanner.new(string) @locator = Locator.locator(string, path) end # Lexes an unquoted string. # @param string [String] the string to lex # @param locator [Locator] the locator to use (a default is used if nil is given) # @param escapes [Array<String>] array of character strings representing the escape sequences to transform # @param interpolate [Boolean] whether interpolation of expressions should be made or not. # def lex_unquoted_string(string, locator, escapes, interpolate) initvars assert_not_bom(string) @scanner = StringScanner.new(string) @locator = locator || Locator.locator(string, '') @lexing_context[:escapes] = escapes || UQ_ESCAPES @lexing_context[:uq_slurp_pattern] = if interpolate escapes.include?('$') ? SLURP_UQ_PATTERN : SLURP_UQNE_PATTERN else SLURP_ALL_PATTERN end end # Convenience method, and for compatibility with older lexer. Use the lex_file instead. # (Bad form to use overloading of assignment operator for something that is not really an assignment). # def file=(file) lex_file(file) end # TODO: This method should not be used, callers should get the locator since it is most likely required to # compute line, position etc given offsets. # def file @locator ? @locator.file : nil end # Initializes lexing of the content of the given file. An empty string is used if the file does not exist. # def lex_file(file) initvars contents = Puppet::FileSystem.exist?(file) ? Puppet::FileSystem.read(file, :mode => 'rb', :encoding => 'utf-8') : '' assert_not_bom(contents) @scanner = StringScanner.new(contents.freeze) @locator = Locator.locator(contents, file) end def initvars @token_queue = [] # NOTE: additional keys are used; :escapes, :uq_slurp_pattern, :newline_jump, :epp_* @lexing_context = { :brace_count => 0, :after => nil, :line_lexical_start => 0 } # Use of --tasks introduces the new keyword 'plan' @taskm_keywords = Puppet[:tasks] ? { 'plan' => [:PLAN, 'plan', 4], 'apply' => [:APPLY, 'apply', 5] }.freeze : EMPTY_HASH end # Scans all of the content and returns it in an array # Note that the terminating [false, false] token is included in the result. # def fullscan result = [] scan { |token| result.push(token) } result end # A block must be passed to scan. It will be called with two arguments, a symbol for the token, # and an instance of LexerSupport::TokenValue # PERFORMANCE NOTE: The TokenValue is designed to reduce the amount of garbage / temporary data # and to only convert the lexer's internal tokens on demand. It is slightly more costly to create an # instance of a class defined in Ruby than an Array or Hash, but the gain is much bigger since transformation # logic is avoided for many of its members (most are never used (e.g. line/pos information which is only of # value in general for error messages, and for some expressions (which the lexer does not know about). # def scan # PERFORMANCE note: it is faster to access local variables than instance variables. # This makes a small but notable difference since instance member access is avoided for # every token in the lexed content. # scn = @scanner lex_error_without_pos(Issues::NO_INPUT_TO_LEXER) unless scn ctx = @lexing_context queue = @token_queue selector = @selector scn.skip(PATTERN_WS) # This is the lexer's main loop until queue.empty? && scn.eos? token = queue.shift || selector[scn.peek(1)].call if token ctx[:after] = token[0] yield token end end # Signals end of input yield [false, false] end # This lexes one token at the current position of the scanner. # PERFORMANCE NOTE: Any change to this logic should be performance measured. # def lex_token @selector[@scanner.peek(1)].call end # Emits (produces) a token [:tokensymbol, TokenValue] and moves the scanner's position past the token # def emit(token, byte_offset) @scanner.pos = byte_offset + token[2] [token[0], TokenValue.new(token, byte_offset, @locator)] end # Emits the completed token on the form [:tokensymbol, TokenValue. This method does not alter # the scanner's position. # def emit_completed(token, byte_offset) [token[0], TokenValue.new(token, byte_offset, @locator)] end # Enqueues a completed token at the given offset def enqueue_completed(token, byte_offset) @token_queue << emit_completed(token, byte_offset) end # Allows subprocessors for heredoc etc to enqueue tokens that are tokenized by a different lexer instance # def enqueue(emitted_token) @token_queue << emitted_token end # Answers after which tokens it is acceptable to lex a regular expression. # PERFORMANCE NOTE: # It may be beneficial to turn this into a hash with default value of true for missing entries. # A case expression with literal values will however create a hash internally. Since a reference is # always needed to the hash, this access is almost as costly as a method call. # def regexp_acceptable? case @lexing_context[:after] # Ends of (potential) R-value generating expressions when :RPAREN, :RBRACK, :RRCOLLECT, :RCOLLECT false # End of (potential) R-value - but must be allowed because of case expressions # Called out here to not be mistaken for a bug. when :RBRACE true # Operands (that can be followed by DIV (even if illegal in grammar) when :NAME, :CLASSREF, :NUMBER, :STRING, :BOOLEAN, :DQPRE, :DQMID, :DQPOST, :HEREDOC, :REGEX, :VARIABLE, :WORD false else true end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/serialization/json_path.rb
lib/puppet/pops/serialization/json_path.rb
# frozen_string_literal: true require_relative '../../../puppet/concurrent/thread_local_singleton' module Puppet::Pops module Serialization module JsonPath # Creates a _json_path_ reference from the given `path` argument # # @path path [Array<Integer,String>] An array of integers and strings # @return [String] the created json_path # # @api private def self.to_json_path(path) p = '$'.dup path.each do |seg| if seg.nil? p << '[null]' elsif Types::PScalarDataType::DEFAULT.instance?(seg) p << '[' << Types::StringConverter.singleton.convert(seg, '%p') << ']' else # Unable to construct json path from complex segments return nil end end p end # Resolver for JSON path that uses the Puppet parser to create the AST. The path must start # with '$' which denotes the value that is passed into the parser. This parser can easily # be extended with more elaborate resolution mechanisms involving document sets. # # The parser is limited to constructs generated by the {JsonPath#to_json_path} # method. # # @api private class Resolver extend Puppet::Concurrent::ThreadLocalSingleton def initialize @parser = Parser::Parser.new @visitor = Visitor.new(nil, 'resolve', 2, 2) end # Resolve the given _path_ in the given _context_. # @param context [Object] the context used for resolution # @param path [String] the json path # @return [Object] the resolved value # def resolve(context, path) factory = @parser.parse_string(path) v = resolve_any(factory.model.body, context, path) v.is_a?(Builder) ? v.resolve : v end def resolve_any(ast, context, path) @visitor.visit_this_2(self, ast, context, path) end def resolve_AccessExpression(ast, context, path) bad_json_path(path) unless ast.keys.size == 1 receiver = resolve_any(ast.left_expr, context, path) key = resolve_any(ast.keys[0], context, path) if receiver.is_a?(Types::PuppetObject) PCORE_TYPE_KEY == key ? receiver._pcore_type : receiver.send(key) else receiver[key] end end def resolve_NamedAccessExpression(ast, context, path) receiver = resolve_any(ast.left_expr, context, path) key = resolve_any(ast.right_expr, context, path) if receiver.is_a?(Types::PuppetObject) PCORE_TYPE_KEY == key ? receiver._pcore_type : receiver.send(key) else receiver[key] end end def resolve_QualifiedName(ast, _, _) v = ast.value 'null' == v ? nil : v end def resolve_QualifiedReference(ast, _, _) v = ast.cased_value 'null'.casecmp(v) == 0 ? nil : v end def resolve_ReservedWord(ast, _, _) ast.word end def resolve_LiteralUndef(_, _, _) 'undef' end def resolve_LiteralDefault(_, _, _) 'default' end def resolve_VariableExpression(ast, context, path) # A single '$' means root, i.e. the context. bad_json_path(path) unless EMPTY_STRING == resolve_any(ast.expr, context, path) context end def resolve_CallMethodExpression(ast, context, path) bad_json_path(path) unless ast.arguments.empty? resolve_any(ast.functor_expr, context, path) end def resolve_LiteralValue(ast, _, _) ast.value end def resolve_Object(ast, _, path) bad_json_path(path) end def bad_json_path(path) raise SerializationError, _('Unable to parse jsonpath "%{path}"') % { :path => path } end private :bad_json_path 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/pops/serialization/abstract_reader.rb
lib/puppet/pops/serialization/abstract_reader.rb
# frozen_string_literal: true require_relative 'extension' require_relative 'time_factory' module Puppet::Pops module Serialization # Abstract class for protocol specific readers such as MsgPack or JSON # The abstract reader is capable of reading the primitive scalars: # - Boolean # - Integer # - Float # - String # and, by using extensions, also # - Array start # - Map start # - Object start # - Regexp # - Version # - VersionRange # - Timespan # - Timestamp # - Default # # @api public class AbstractReader # @param [MessagePack::Unpacker,JSON::Unpacker] unpacker The low lever unpacker that delivers the primitive objects # @param [MessagePack::Unpacker,JSON::Unpacker] extension_unpacker Optional unpacker for extensions. Defaults to the unpacker # @api public def initialize(unpacker, extension_unpacker = nil) @read = [] @unpacker = unpacker @extension_unpacker = extension_unpacker.nil? ? unpacker : extension_unpacker register_types end # Read an object from the underlying unpacker # @return [Object] the object that was read # @api public def read obj = @unpacker.read case obj when Extension::InnerTabulation @read[obj.index] when Numeric, Symbol, Extension::NotTabulated, true, false, nil # not tabulated obj else @read << obj obj end end # @return [Integer] The total count of unique primitive values that has been read # @api private def primitive_count @read.size end # @api private def read_payload(data) raise SerializationError, "Internal error: Class #{self.class} does not implement method 'read_payload'" end # @api private def read_tpl_qname(ep) Array.new(ep.read) { read_tpl(ep) }.join('::') end # @api private def read_tpl(ep) obj = ep.read case obj when Integer @read[obj] else @read << obj obj end end # @api private def extension_unpacker @extension_unpacker end # @api private def register_type(extension_number, &block) @unpacker.register_type(extension_number, &block) end # @api private def register_types register_type(Extension::INNER_TABULATION) do |data| read_payload(data) { |ep| Extension::InnerTabulation.new(ep.read) } end register_type(Extension::TABULATION) do |data| read_payload(data) { |ep| Extension::Tabulation.new(ep.read) } end register_type(Extension::ARRAY_START) do |data| read_payload(data) { |ep| Extension::ArrayStart.new(ep.read) } end register_type(Extension::MAP_START) do |data| read_payload(data) { |ep| Extension::MapStart.new(ep.read) } end register_type(Extension::PCORE_OBJECT_START) do |data| read_payload(data) { |ep| type_name = read_tpl_qname(ep); Extension::PcoreObjectStart.new(type_name, ep.read) } end register_type(Extension::OBJECT_START) do |data| read_payload(data) { |ep| Extension::ObjectStart.new(ep.read) } end register_type(Extension::DEFAULT) do |data| read_payload(data) { |_ep| Extension::Default::INSTANCE } end register_type(Extension::COMMENT) do |data| read_payload(data) { |ep| Extension::Comment.new(ep.read) } end register_type(Extension::SENSITIVE_START) do |data| read_payload(data) { |_ep| Extension::SensitiveStart::INSTANCE } end register_type(Extension::REGEXP) do |data| read_payload(data) { |ep| Regexp.new(ep.read) } end register_type(Extension::TYPE_REFERENCE) do |data| read_payload(data) { |ep| Types::PTypeReferenceType.new(ep.read) } end register_type(Extension::SYMBOL) do |data| read_payload(data) { |ep| ep.read.to_sym } end register_type(Extension::TIME) do |data| read_payload(data) do |ep| sec = ep.read nsec = ep.read Time::Timestamp.new(sec * 1_000_000_000 + nsec) end end register_type(Extension::TIMESPAN) do |data| read_payload(data) do |ep| sec = ep.read nsec = ep.read Time::Timespan.new(sec * 1_000_000_000 + nsec) end end register_type(Extension::VERSION) do |data| read_payload(data) { |ep| SemanticPuppet::Version.parse(ep.read) } end register_type(Extension::VERSION_RANGE) do |data| read_payload(data) { |ep| SemanticPuppet::VersionRange.parse(ep.read) } end register_type(Extension::BASE64) do |data| read_payload(data) { |ep| Types::PBinaryType::Binary.from_base64_strict(ep.read) } end register_type(Extension::BINARY) do |data| # The Ruby MessagePack implementation have special treatment for "ASCII-8BIT" strings. They # are written as binary data. read_payload(data) { |ep| Types::PBinaryType::Binary.new(ep.read) } end register_type(Extension::URI) do |data| read_payload(data) { |ep| URI(ep.read) } end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/serialization/instance_writer.rb
lib/puppet/pops/serialization/instance_writer.rb
# frozen_string_literal: true module Puppet::Pops module Serialization # An instance writer is responsible for writing complex objects using a {Serializer} # @api private module InstanceWriter # @param [Types::PObjectType] type the type of instance to write # @param [Object] value the instance # @param [Serializer] serializer the serializer that will receive the written instance def write(type, value, serializer) Serialization.not_implemented(self, 'write') 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/pops/serialization/time_factory.rb
lib/puppet/pops/serialization/time_factory.rb
# frozen_string_literal: true module Puppet::Pops module Serialization # Implements all the constructors found in the Time class and ensures that # the created Time object can be serialized and deserialized using its # seconds and nanoseconds without loss of precision. # # @deprecated No longer in use. Functionality replaced by Timestamp # @api private class TimeFactory NANO_DENOMINATOR = 10**9 def self.at(*args) sec_nsec_safe(Time.at(*args)) end def self.gm(*args) sec_nsec_safe(Time.gm(*args)) end def self.local(*args) sec_nsec_safe(Time.local(*args)) end def self.mktime(*args) sec_nsec_safe(Time.mktime(*args)) end def self.new(*args) sec_nsec_safe(Time.new(*args)) end def self.now sec_nsec_safe(Time.now) end def self.utc(*args) sec_nsec_safe(Time.utc(*args)) end # Creates a Time object from a Rational defined as: # # (_sec_ * #NANO_DENOMINATOR + _nsec_) / #NANO_DENOMINATOR # # This ensures that a Time object can be reliably serialized and using its # its #tv_sec and #tv_nsec values and then recreated again (using this method) # without loss of precision. # # @param sec [Integer] seconds since Epoch # @param nsec [Integer] nano seconds # @return [Time] the created object # def self.from_sec_nsec(sec, nsec) Time.at(Rational(sec * NANO_DENOMINATOR + nsec, NANO_DENOMINATOR)) end # Returns a new Time object that is adjusted to ensure that precision is not # lost when it is serialized and deserialized using its seconds and nanoseconds # @param t [Time] the object to adjust # @return [Time] the adjusted object # def self.sec_nsec_safe(t) from_sec_nsec(t.tv_sec, t.tv_nsec) 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/pops/serialization/abstract_writer.rb
lib/puppet/pops/serialization/abstract_writer.rb
# frozen_string_literal: true require_relative 'extension' module Puppet::Pops module Serialization MAX_INTEGER = 0x7fffffffffffffff MIN_INTEGER = -0x8000000000000000 # Abstract class for protocol specific writers such as MsgPack or JSON # The abstract write is capable of writing the primitive scalars: # - Boolean # - Integer # - Float # - String # and, by using extensions, also # - Array start # - Map start # - Object start # - Regexp # - Version # - VersionRange # - Timespan # - Timestamp # - Default # # @api public class AbstractWriter # @param [MessagePack::Packer,JSON::Packer] packer the underlying packer stream # @param [Hash] options # @option options [Boolean] :tabulate `true` if tabulation is enabled (which is the default). # @param [DebugPacker,nil] extension_packer Optional specific extension packer. Only used for debug output # @api public def initialize(packer, options, extension_packer = nil) @tabulate = options[:tabulate] @tabulate = true if @tabulate.nil? @written = {} @packer = packer @extension_packer = extension_packer.nil? ? packer : extension_packer register_types end # Tell the underlying packer to flush. # @api public def finish @packer.flush end def supports_binary? false end # Write a value on the underlying stream # @api public def write(value) written = false case value when Integer # not tabulated, but integers larger than 64-bit cannot be allowed. raise SerializationError, _('Integer out of bounds') if value > MAX_INTEGER || value < MIN_INTEGER when Numeric, Symbol, Extension::NotTabulated, true, false, nil # not tabulated else if @tabulate index = @written[value] if index.nil? @packer.write(value) written = true @written[value] = @written.size else value = Extension::InnerTabulation.new(index) end end end @packer.write(value) unless written end # Called from extension callbacks only # # @api private def build_payload raise SerializationError, "Internal error: Class #{self.class} does not implement method 'build_payload'" end # @api private def extension_packer @extension_packer end # Called from extension callbacks only # # @api private def write_tpl_qname(ep, qname) names = qname.split('::') ep.write(names.size) names.each { |n| write_tpl(ep, n) } end # Called from extension callbacks only # # @api private def write_tpl(ep, value) # TRANSLATORS 'Integers' is a Ruby class for numbers and should not be translated raise ArgumentError, _('Internal error. Integers cannot be tabulated in extension payload') if value.is_a?(Integer) if @tabulate index = @written[value] if index.nil? @written[value] = @written.size else value = index end end ep.write(value) end # @api private def register_type(extension_number, payload_class, &block) @packer.register_type(extension_number, payload_class, &block) end # @api private def register_types # 0x00 - 0x0F are reserved for low-level serialization / tabulation extensions register_type(Extension::INNER_TABULATION, Extension::InnerTabulation) do |o| build_payload { |ep| ep.write(o.index) } end register_type(Extension::TABULATION, Extension::Tabulation) do |o| build_payload { |ep| ep.write(o.index) } end # 0x10 - 0x1F are reserved for structural extensions register_type(Extension::ARRAY_START, Extension::ArrayStart) do |o| build_payload { |ep| ep.write(o.size) } end register_type(Extension::MAP_START, Extension::MapStart) do |o| build_payload { |ep| ep.write(o.size) } end register_type(Extension::PCORE_OBJECT_START, Extension::PcoreObjectStart) do |o| build_payload { |ep| write_tpl_qname(ep, o.type_name); ep.write(o.attribute_count) } end register_type(Extension::OBJECT_START, Extension::ObjectStart) do |o| build_payload { |ep| ep.write(o.attribute_count) } end # 0x20 - 0x2f reserved for special extension objects register_type(Extension::DEFAULT, Extension::Default) do |_o| build_payload { |ep| } end register_type(Extension::COMMENT, Extension::Comment) do |o| build_payload { |ep| ep.write(o.comment) } end register_type(Extension::SENSITIVE_START, Extension::SensitiveStart) do |_o| build_payload { |ep| } end # 0x30 - 0x7f reserved for mapping of specific runtime classes register_type(Extension::REGEXP, Regexp) do |o| build_payload { |ep| ep.write(o.source) } end register_type(Extension::TYPE_REFERENCE, Types::PTypeReferenceType) do |o| build_payload { |ep| ep.write(o.type_string) } end register_type(Extension::SYMBOL, Symbol) do |o| build_payload { |ep| ep.write(o.to_s) } end register_type(Extension::TIME, Time::Timestamp) do |o| build_payload { |ep| nsecs = o.nsecs; ep.write(nsecs / 1_000_000_000); ep.write(nsecs % 1_000_000_000) } end register_type(Extension::TIMESPAN, Time::Timespan) do |o| build_payload { |ep| nsecs = o.nsecs; ep.write(nsecs / 1_000_000_000); ep.write(nsecs % 1_000_000_000) } end register_type(Extension::VERSION, SemanticPuppet::Version) do |o| build_payload { |ep| ep.write(o.to_s) } end register_type(Extension::VERSION_RANGE, SemanticPuppet::VersionRange) do |o| build_payload { |ep| ep.write(o.to_s) } end if supports_binary? register_type(Extension::BINARY, Types::PBinaryType::Binary) do |o| # The Ruby MessagePack implementation has special treatment for "ASCII-8BIT" strings. They # are written as binary data. build_payload { |ep| ep.write(o.binary_buffer) } end else register_type(Extension::BASE64, Types::PBinaryType::Binary) do |o| build_payload { |ep| ep.write(o.to_s) } end end URI.scheme_list.values.each do |uri_class| register_type(Extension::URI, uri_class) do |o| build_payload { |ep| ep.write(o.to_s) } end end end def to_s self.class.name.to_s end def inspect to_s end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/serialization/to_data_converter.rb
lib/puppet/pops/serialization/to_data_converter.rb
# frozen_string_literal: true module Puppet::Pops module Serialization # Class that can process an arbitrary object into a value that is assignable to `Data`. # # @api public class ToDataConverter include Evaluator::Runtime3Support # Convert the given _value_ according to the given _options_ and return the result of the conversion # # @param value [Object] the value to convert # @param options {Symbol => <Boolean,String>} options hash # @option options [Boolean] :rich_data `true` if rich data is enabled # @option options [Boolean] :local_reference use local references instead of duplicating complex entries # @option options [Boolean] :type_by_reference `true` if Object types are converted to references rather than embedded. # @option options [Boolean] :symbol_as_string `true` if Symbols should be converted to strings (with type loss) # @option options [String] :message_prefix String to prepend to in warnings and errors # @return [Data] the processed result. An object assignable to `Data`. # # @api public def self.convert(value, options = EMPTY_HASH) new(options).convert(value) end # Create a new instance of the processor # # @param options {Symbol => Object} options hash # @option options [Boolean] :rich_data `true` if rich data is enabled # @option options [Boolean] :local_references use local references instead of duplicating complex entries # @option options [Boolean] :type_by_reference `true` if Object types are converted to references rather than embedded. # @option options [Boolean] :symbol_as_string `true` if Symbols should be converted to strings (with type loss) # @option options [String] :message_prefix String to prepend to path in warnings and errors # @option semantic [Object] :semantic object to pass to the issue reporter def initialize(options = EMPTY_HASH) @type_by_reference = options[:type_by_reference] @type_by_reference = true if @type_by_reference.nil? @local_reference = options[:local_reference] @local_reference = true if @local_reference.nil? @symbol_as_string = options[:symbol_as_string] @symbol_as_string = false if @symbol_as_string.nil? @rich_data = options[:rich_data] @rich_data = false if @rich_data.nil? @message_prefix = options[:message_prefix] @semantic = options[:semantic] end # Convert the given _value_ # # @param value [Object] the value to convert # @return [Data] the processed result. An object assignable to `Data`. # # @api public def convert(value) @path = [] @values = {} to_data(value) end private def path_to_s s = String.new(@message_prefix || '') s << JsonPath.to_json_path(@path)[1..] s end def to_data(value) if value.nil? || Types::PScalarDataType::DEFAULT.instance?(value) if @rich_data && value.is_a?(String) && value.encoding == Encoding::ASCII_8BIT # Transform the binary string to rich Binary { PCORE_TYPE_KEY => PCORE_TYPE_BINARY, PCORE_VALUE_KEY => Puppet::Pops::Types::PBinaryType::Binary.from_binary_string(value).to_s } else value end elsif :default == value if @rich_data { PCORE_TYPE_KEY => PCORE_TYPE_DEFAULT } else serialization_issue(Issues::SERIALIZATION_DEFAULT_CONVERTED_TO_STRING, :path => path_to_s) 'default' end elsif value.is_a?(Symbol) if @symbol_as_string value.to_s elsif @rich_data { PCORE_TYPE_KEY => PCORE_TYPE_SYMBOL, PCORE_VALUE_KEY => value.to_s } else unknown_to_string_with_warning(value) end elsif value.instance_of?(Array) process(value) do result = [] value.each_with_index do |elem, index| with(index) { result << to_data(elem) } end result end elsif value.instance_of?(Hash) process(value) do if value.keys.all? { |key| key.is_a?(String) && key != PCORE_TYPE_KEY } result = {} value.each_pair { |key, elem| with(key) { result[key] = to_data(elem) } } result else non_string_keyed_hash_to_data(value) end end elsif value.instance_of?(Types::PSensitiveType::Sensitive) process(value) do { PCORE_TYPE_KEY => PCORE_TYPE_SENSITIVE, PCORE_VALUE_KEY => to_data(value.unwrap) } end else unknown_to_data(value) end end # If `:local_references` is enabled, then the `object_id` will be associated with the current _path_ of # the context the first time this method is called. The method then returns the result of yielding to # the given block. Subsequent calls with a value that has the same `object_id` will instead return a # reference based on the given path. # # If `:local_references` is disabled, then this method performs a check for endless recursion before # it yields to the given block. The result of yielding is returned. # # @param value [Object] the value # @yield The block that will produce the data for the value # @return [Data] the result of yielding to the given block, or a hash denoting a reference # # @api private def process(value, &block) if @local_reference id = value.object_id ref = @values[id] if ref.nil? @values[id] = @path.dup yield elsif ref.instance_of?(Hash) ref else json_ref = JsonPath.to_json_path(ref) if json_ref.nil? # Complex key and hence no way to reference the prior value. The value must therefore be # duplicated which in turn introduces a risk for endless recursion in case of self # referencing structures with_recursive_guard(value, &block) else @values[id] = { PCORE_TYPE_KEY => PCORE_LOCAL_REF_SYMBOL, PCORE_VALUE_KEY => json_ref } end end else with_recursive_guard(value, &block) end end # Pushes `key` to the end of the path and yields to the given block. The # `key` is popped when the yield returns. # @param key [Object] the key to push on the current path # @yield The block that will produce the returned value # @return [Object] the result of yielding to the given block # # @api private def with(key) @path.push(key) value = yield @path.pop value end # @param value [Object] the value to use when checking endless recursion # @yield The block that will produce the data # @return [Data] the result of yielding to the given block def with_recursive_guard(value) id = value.object_id if @recursive_lock if @recursive_lock.include?(id) serialization_issue(Issues::SERIALIZATION_ENDLESS_RECURSION, :type_name => value.class.name) end @recursive_lock[id] = true else @recursive_lock = { id => true } end v = yield @recursive_lock.delete(id) v end def unknown_to_data(value) @rich_data ? value_to_data_hash(value) : unknown_to_string_with_warning(value) end def unknown_key_to_string_with_warning(value) str = unknown_to_string(value) serialization_issue(Issues::SERIALIZATION_UNKNOWN_KEY_CONVERTED_TO_STRING, :path => path_to_s, :klass => value.class, :value => str) str end def unknown_to_string_with_warning(value) str = unknown_to_string(value) serialization_issue(Issues::SERIALIZATION_UNKNOWN_CONVERTED_TO_STRING, :path => path_to_s, :klass => value.class, :value => str) str end def unknown_to_string(value) value.is_a?(Regexp) ? Puppet::Pops::Types::PRegexpType.regexp_to_s_with_delimiters(value) : value.to_s end def non_string_keyed_hash_to_data(hash) if @rich_data to_key_extended_hash(hash) else result = {} hash.each_pair do |key, value| if key.is_a?(Symbol) && @symbol_as_string key = key.to_s elsif !key.is_a?(String) key = unknown_key_to_string_with_warning(key) end with(key) { result[key] = to_data(value) } end result end end # A Key extended hash is a hash whose keys are not entirely strings. Such a hash # cannot be safely represented as JSON or YAML # # @param hash {Object => Object} the hash to process # @return [String => Data] the representation of the extended hash def to_key_extended_hash(hash) key_value_pairs = [] hash.each_pair do |key, value| key = to_data(key) key_value_pairs << key key_value_pairs << with(key) { to_data(value) } end { PCORE_TYPE_KEY => PCORE_TYPE_HASH, PCORE_VALUE_KEY => key_value_pairs } end def value_to_data_hash(value) pcore_type = value.is_a?(Types::PuppetObject) ? value._pcore_type : Types::TypeCalculator.singleton.infer(value) if pcore_type.is_a?(Puppet::Pops::Types::PRuntimeType) unknown_to_string_with_warning(value) else pcore_tv = pcore_type_to_data(pcore_type) if pcore_type.roundtrip_with_string? { PCORE_TYPE_KEY => pcore_tv, # Scalar values are stored using their default string representation PCORE_VALUE_KEY => Types::StringConverter.singleton.convert(value) } elsif pcore_type.implementation_class.respond_to?(:_pcore_init_from_hash) process(value) do { PCORE_TYPE_KEY => pcore_tv, }.merge(to_data(value._pcore_init_hash)) end else process(value) do (names, _, required_count) = pcore_type.parameter_info(value.class) args = names.map { |name| value.send(name) } # Pop optional arguments that are default while args.size > required_count break unless pcore_type[names[args.size - 1]].default_value?(args.last) args.pop end result = { PCORE_TYPE_KEY => pcore_tv } args.each_with_index do |val, idx| key = names[idx] with(key) { result[key] = to_data(val) } end result end end end end def pcore_type_to_data(pcore_type) type_name = pcore_type.name if @type_by_reference || type_name.start_with?('Pcore::') type_name else with(PCORE_TYPE_KEY) { to_data(pcore_type) } end end private :pcore_type_to_data def serialization_issue(issue, options = EMPTY_HASH) semantic = @semantic if semantic.nil? tos = Puppet::Pops::PuppetStack.top_of_stack if tos.empty? semantic = Puppet::Pops::SemanticError.new(issue, nil, EMPTY_HASH) else file, line = stacktrace semantic = Puppet::Pops::SemanticError.new(issue, nil, { :file => file, :line => line }) end end optionally_fail(issue, semantic, options) 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/pops/serialization/json.rb
lib/puppet/pops/serialization/json.rb
# frozen_string_literal: true require_relative '../../../puppet/util/json' module Puppet::Pops module Serialization require_relative 'time_factory' require_relative 'abstract_reader' require_relative 'abstract_writer' module JSON # A Writer that writes output in JSON format # @api private class Writer < AbstractWriter def initialize(io, options = {}) super(Packer.new(io, options), options) end # Clear the underlying io stream but does not clear tabulation cache # Specifically designed to enable tabulation to span more than one # separately deserialized object. def clear_io @packer.clear_io end def extension_packer @packer end def packer @packer end def build_payload yield(@packer) end def to_a @packer.to_a end def to_json @packer.to_json end end # A Reader that reads JSON formatted input # @api private class Reader < AbstractReader def initialize(io) super(Unpacker.new(io)) end def re_initialize(io) @unpacker.re_initialize(io) end def read_payload(data) yield(@unpacker) end end # The JSON Packer. Modeled after the MessagePack::Packer # @api private class Packer def initialize(io, options = {}) @io = io @io << '[' @type_registry = {} @nested = [] @verbose = options[:verbose] @verbose = false if @verbose.nil? @indent = options[:indent] || 0 end def register_type(type, klass, &block) @type_registry[klass] = [type, klass, block] end def clear_io # Truncate everything except leading '[' if @io.is_a?(String) @io.slice!(1..-1) else @io.truncate(1) end end def empty? @io.is_a?(String) ? io.length == 1 : @io.pos == 1 end def flush # Drop last comma unless just start marker present if @io.is_a?(String) @io.chop! unless @io.length == 1 @io << ']' else pos = @io.pos @io.pos = pos - 1 unless pos == 1 @io << ']' @io.flush end end def write(obj) case obj when Array write_array_header(obj.size) obj.each { |x| write(x) } when Hash write_map_header(obj.size) obj.each_pair { |k, v| write(k); write(v) } when nil write_nil else write_scalar(obj) end end alias pack write def write_array_header(n) if n < 1 @io << '[]' else @io << '[' @nested << [false, n] end end def write_map_header(n) if n < 1 @io << '{}' else @io << '{' @nested << [true, n * 2] end end def write_nil @io << 'null' write_delim end def to_s to_json end def to_a ::Puppet::Util::Json.load(io_string) end def to_json if @indent > 0 ::Puppet::Util::Json.dump(to_a, { :pretty => true, :indent => ' ' * @indent }) else io_string end end # Write a payload object. Not subject to extensions def write_pl(obj) @io << Puppet::Util::Json.dump(obj) << ',' end def io_string if @io.is_a?(String) @io else @io.pos = 0 @io.read end end private :io_string def write_delim nesting = @nested.last cnt = nesting.nil? ? nil : nesting[1] case cnt when 1 @io << (nesting[0] ? '}' : ']') @nested.pop write_delim when Integer if cnt.even? || !nesting[0] @io << ',' else @io << ':' end nesting[1] = cnt - 1 else @io << ',' end end private :write_delim def write_scalar(obj) ext = @type_registry[obj.class] if ext.nil? case obj when Numeric, String, true, false, nil @io << Puppet::Util::Json.dump(obj) write_delim else raise SerializationError, _("Unable to serialize a %{obj}") % { obj: obj.class.name } end else write_extension(ext, obj) end end private :write_scalar def write_extension(ext, obj) @io << '[' << extension_indicator(ext).to_json << ',' @nested << nil write_extension_payload(ext, obj) @nested.pop if obj.is_a?(Extension::SequenceStart) && obj.sequence_size > 0 @nested << [false, obj.sequence_size] else if @io.is_a?(String) @io.chop! else @io.pos -= 1 end @io << ']' write_delim end end private :write_extension def write_extension_payload(ext, obj) ext[2].call(obj) end private :write_extension_payload def extension_indicator(ext) @verbose ? ext[1].name.sub(/^Puppet::Pops::Serialization::\w+::(.+)$/, '\1') : ext[0] end private :extension_indicator end class Unpacker def initialize(io) re_initialize(io) @type_registry = {} @nested = [] end def re_initialize(io) parsed = parse_io(io) raise SerializationError, _("JSON stream is not an array. It is a %{klass}") % { klass: io.class.name } unless parsed.is_a?(Array) @etor_stack = [parsed.each] end def read obj = nil loop do raise SerializationError, _('Unexpected end of input') if @etor_stack.empty? etor = @etor_stack.last begin obj = etor.next break rescue StopIteration @etor_stack.pop end end if obj.is_a?(Array) ext_etor = obj.each @etor_stack << ext_etor ext_no = ext_etor.next ext_block = @type_registry[ext_no] raise SerializationError, _("Invalid input. %{ext_no} is not a valid extension number") % { ext_no: ext_no } if ext_block.nil? obj = ext_block.call(nil) end obj end def register_type(extension_number, &block) @type_registry[extension_number] = block end private def parse_io(io) case io when IO, StringIO ::Puppet::Util::Json.load(io.read) when String ::Puppet::Util::Json.load(io) else io end end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/serialization/serializer.rb
lib/puppet/pops/serialization/serializer.rb
# frozen_string_literal: true require_relative 'extension' module Puppet::Pops module Serialization # The serializer is capable of writing, arrays, maps, and complex objects using an underlying protocol writer. It takes care of # tabulating and disassembling complex objects. # @api public class Serializer # Provides access to the writer. # @api private attr_reader :writer # @param writer [AbstractWriter] the writer that is used for writing primitive values # @param options [{String, Object}] serialization options # @option options [Boolean] :type_by_reference `true` if Object types are serialized by name only. # @api public def initialize(writer, options = EMPTY_HASH) # Hash#compare_by_identity is intentionally not used since we only need to map # object ids to their size and we don't want to store entire objects in memory @written = {} @writer = writer @options = options end # Tell the underlying writer to finish # @api public def finish @writer.finish end # Write an object # @param [Object] value the object to write # @api public def write(value) case value when Integer, Float, String, true, false, nil @writer.write(value) when :default @writer.write(Extension::Default::INSTANCE) else index = @written[value.object_id] # rubocop:disable Lint/HashCompareByIdentity if index.nil? write_tabulated_first_time(value) else @writer.write(Extension::Tabulation.new(index)) end end end # Write the start of an array. # @param [Integer] size the size of the array # @api private def start_array(size) @writer.write(Extension::ArrayStart.new(size)) end # Write the start of a map (hash). # @param [Integer] size the number of entries in the map # @api private def start_map(size) @writer.write(Extension::MapStart.new(size)) end # Write the start of a complex pcore object # @param [String] type_ref the name of the type # @param [Integer] attr_count the number of attributes in the object # @api private def start_pcore_object(type_ref, attr_count) @writer.write(Extension::PcoreObjectStart.new(type_ref, attr_count)) end # Write the start of a complex object # @param [Integer] attr_count the number of attributes in the object # @api private def start_object(attr_count) @writer.write(Extension::ObjectStart.new(attr_count)) end def push_written(value) @written[value.object_id] = @written.size # rubocop:disable Lint/HashCompareByIdentity end # Write the start of a sensitive object # @api private def start_sensitive @writer.write(Extension::SensitiveStart::INSTANCE) end def type_by_reference? @options[:type_by_reference] == true end def to_s "#{self.class.name} with #{@writer}" end def inspect to_s end # First time write of a tabulated object. This means that the object is written and then remembered. Subsequent writes # of the same object will yield a write of a tabulation index instead. # @param [Object] value the value to write # @api private def write_tabulated_first_time(value) if value.instance_of?(Symbol) || value.instance_of?(Regexp) || value.instance_of?(SemanticPuppet::Version) || value.instance_of?(SemanticPuppet::VersionRange) || value.instance_of?(Time::Timestamp) || value.instance_of?(Time::Timespan) || value.instance_of?(Types::PBinaryType::Binary) || value.is_a?(URI) push_written(value) @writer.write(value) elsif value.instance_of?(Array) push_written(value) start_array(value.size) value.each { |elem| write(elem) } elsif value.instance_of?(Hash) push_written(value) start_map(value.size) value.each_pair { |key, val| write(key); write(val) } elsif value.instance_of?(Types::PSensitiveType::Sensitive) start_sensitive write(value.unwrap) elsif value.instance_of?(Types::PTypeReferenceType) push_written(value) @writer.write(value) elsif value.is_a?(Types::PuppetObject) value._pcore_type.write(value, self) else impl_class = value.class type = Loaders.implementation_registry.type_for_module(impl_class) raise SerializationError, _("No Puppet Type found for %{klass}") % { klass: impl_class.name } unless type.is_a?(Types::PObjectType) type.write(value, self) end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/serialization/from_data_converter.rb
lib/puppet/pops/serialization/from_data_converter.rb
# frozen_string_literal: true module Puppet::Pops module Serialization class Builder def initialize(values) @values = values @resolved = true end def [](key) @values[key] end def []=(key, value) @values[key] = value @resolved = false if value.is_a?(Builder) end def resolve unless @resolved @resolved = true case @values when Array @values.each_with_index { |v, idx| @values[idx] = v.resolve if v.is_a?(Builder) } when Hash @values.each_pair { |k, v| @values[k] = v.resolve if v.is_a?(Builder) } end end @values end end class ObjectHashBuilder < Builder def initialize(instance) super({}) @instance = instance end def resolve @instance._pcore_init_from_hash(super) @instance end end class ObjectArrayBuilder < Builder def initialize(instance) super({}) @instance = instance end def resolve @instance.send(:initialize, *super.values) @instance end end # Class that can process the `Data` produced by the {ToDataConverter} class and reassemble # the objects that were converted. # # @api public class FromDataConverter # Converts the given `Data` _value_ according to the given _options_ and returns the resulting `RichData`. # # @param value [Data] the value to convert # @param options {Symbol => <Boolean,String>} options hash # @option options [Loaders::Loader] :loader the loader to use. Can be `nil` in which case the default is # determined by the {Types::TypeParser}. # @option options [Boolean] :allow_unresolved `true` to allow that rich_data hashes are kept "as is" if the # designated '__ptype' cannot be resolved. Defaults to `false`. # @return [RichData] the processed result. # # @api public def self.convert(value, options = EMPTY_HASH) new(options).convert(value) end # Creates a new instance of the processor # # @param options {Symbol => Object} options hash # @option options [Loaders::Loader] :loader the loader to use. Can be `nil` in which case the default is # determined by the {Types::TypeParser}. # @option options [Boolean] :allow_unresolved `true` to allow that rich_data hashes are kept "as is" if the # designated '__ptype' cannot be resolved. Defaults to `false`. # # @api public def initialize(options = EMPTY_HASH) @allow_unresolved = options[:allow_unresolved] @allow_unresolved = false if @allow_unresolved.nil? @loader = options[:loader] @pcore_type_procs = { PCORE_TYPE_HASH => proc do |hash, _| value = hash[PCORE_VALUE_KEY] build({}) do top = value.size idx = 0 while idx < top key = without_value { convert(value[idx]) } idx += 1 with(key) { convert(value[idx]) } idx += 1 end end end, PCORE_TYPE_SENSITIVE => proc do |hash, _| build(Types::PSensitiveType::Sensitive.new(convert(hash[PCORE_VALUE_KEY]))) end, PCORE_TYPE_DEFAULT => proc do |_, _| build(:default) end, PCORE_TYPE_SYMBOL => proc do |hash, _| build(:"#{hash[PCORE_VALUE_KEY]}") end, PCORE_LOCAL_REF_SYMBOL => proc do |hash, _| build(JsonPath::Resolver.singleton.resolve(@root, hash[PCORE_VALUE_KEY])) end } @pcore_type_procs.default = proc do |hash, type_value| value = hash.include?(PCORE_VALUE_KEY) ? hash[PCORE_VALUE_KEY] : hash.reject { |key, _| PCORE_TYPE_KEY == key } if type_value.is_a?(Hash) type = without_value { convert(type_value) } if type.is_a?(Hash) raise SerializationError, _('Unable to deserialize type from %{type}') % { type: type } unless @allow_unresolved hash else pcore_type_hash_to_value(type, value) end else type = Types::TypeParser.singleton.parse(type_value, @loader) if type.is_a?(Types::PTypeReferenceType) unless @allow_unresolved raise SerializationError, _('No implementation mapping found for Puppet Type %{type_name}') % { type_name: type_value } end hash else # not a string pcore_type_hash_to_value(type, value) end end end end # Converts the given `Data` _value_ and returns the resulting `RichData` # # @param value [Data] the value to convert # @return [RichData] the processed result # # @api public def convert(value) case value when Hash pcore_type = value[PCORE_TYPE_KEY] if pcore_type && (pcore_type.is_a?(String) || pcore_type.is_a?(Hash)) @pcore_type_procs[pcore_type].call(value, pcore_type) else build({}) { value.each_pair { |key, elem| with(key) { convert(elem) } } } end when Array build([]) { value.each_with_index { |elem, idx| with(idx) { convert(elem) } } } else build(value) end end private def with(key) parent_key = @key @key = key yield @key = parent_key end def with_value(value) @root = value unless instance_variable_defined?(:@root) parent = @current @current = value yield @current = parent value end def without_value parent = @current @current = nil value = yield @current = parent value end def build(value, &block) vx = Builder.new(value) @current[@key] = vx unless @current.nil? with_value(vx, &block) if block_given? vx.resolve end def build_object(builder, &block) @current[@key] = builder unless @current.nil? with_value(builder, &block) if block_given? builder.resolve end def pcore_type_hash_to_value(pcore_type, value) case value when Hash # Complex object if value.empty? build(pcore_type.create) elsif pcore_type.implementation_class.respond_to?(:_pcore_init_from_hash) build_object(ObjectHashBuilder.new(pcore_type.allocate)) { value.each_pair { |key, elem| with(key) { convert(elem) } } } else build_object(ObjectArrayBuilder.new(pcore_type.allocate)) { value.each_pair { |key, elem| with(key) { convert(elem) } } } end when String build(pcore_type.create(value)) else raise SerializationError, _('Cannot create a %{type_name} from a %{arg_class}') % { :type_name => pcore_type.name, :arg_class => value.class.name } end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/pops/serialization/object.rb
lib/puppet/pops/serialization/object.rb
# frozen_string_literal: true require_relative 'instance_reader' require_relative 'instance_writer' module Puppet::Pops module Serialization # Instance reader for objects that implement {Types::PuppetObject} # @api private class ObjectReader include InstanceReader def read(type, impl_class, value_count, deserializer) (names, types, required_count) = type.parameter_info(impl_class) max = names.size unless value_count >= required_count && value_count <= max raise Serialization::SerializationError, _("Feature count mismatch for %{value0}. Expected %{required_count} - %{max}, actual %{value_count}") % { value0: impl_class.name, required_count: required_count, max: max, value_count: value_count } end # Deserializer must know about this instance before we read its attributes val = deserializer.remember(impl_class.allocate) args = Array.new(value_count) { deserializer.read } types.each_with_index do |ptype, index| if index < args.size arg = args[index] Types::TypeAsserter.assert_instance_of(nil, ptype, arg) { "#{type.name}[#{names[index]}]" } unless arg == :default else attr = type[names[index]] raise Serialization::SerializationError, _("Missing default value for %{type_name}[%{name}]") % { type_name: type.name, name: names[index] } unless attr && attr.value? args << attr.value end end val.send(:initialize, *args) val end INSTANCE = ObjectReader.new end # Instance writer for objects that implement {Types::PuppetObject} # @api private class ObjectWriter include InstanceWriter def write(type, value, serializer) impl_class = value.class (names, _, required_count) = type.parameter_info(impl_class) args = names.map { |name| value.send(name) } # Pop optional arguments that are default while args.size > required_count break unless type[names[args.size - 1]].default_value?(args.last) args.pop end if type.name.start_with?('Pcore::') || serializer.type_by_reference? serializer.push_written(value) serializer.start_pcore_object(type.name, args.size) else serializer.start_object(args.size + 1) serializer.write(type) serializer.push_written(value) end args.each { |arg| serializer.write(arg) } end INSTANCE = ObjectWriter.new 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/pops/serialization/deserializer.rb
lib/puppet/pops/serialization/deserializer.rb
# frozen_string_literal: true require_relative 'extension' module Puppet::Pops module Serialization # The deserializer is capable of reading, arrays, maps, and complex objects using an underlying protocol reader. It takes care of # resolving tabulations and assembling complex objects. The type of the complex objects are resolved using a loader. # @api public class Deserializer # Provides access to the reader. # @api private attr_reader :reader, :loader # @param [AbstractReader] reader the reader used when reading primitive objects from a stream # @param [Loader::Loader] loader the loader used when resolving names of types # @api public def initialize(reader, loader) @read = [] @reader = reader @loader = loader end # Read the next value from the reader. # # @return [Object] the value that was read # @api public def read val = @reader.read case val when Extension::Tabulation @read[val.index] when Extension::Default :default when Extension::ArrayStart result = remember([]) val.size.times { result << read } result when Extension::MapStart result = remember({}) val.size.times { key = read; result[key] = read } result when Extension::SensitiveStart Types::PSensitiveType::Sensitive.new(read) when Extension::PcoreObjectStart type_name = val.type_name type = Types::TypeParser.singleton.parse(type_name, @loader) raise SerializationError, _("No implementation mapping found for Puppet Type %{type_name}") % { type_name: type_name } if type.is_a?(Types::PTypeReferenceType) result = type.read(val.attribute_count, self) if result.is_a?(Types::PObjectType) existing_type = loader.load(:type, result.name) if result.eql?(existing_type) result = existing_type else # Add result to the loader unless it is equal to the existing_type. The add # will only succeed when the existing_type is nil. loader.add_entry(:type, result.name, result, nil) end end result when Extension::ObjectStart type = read type.read(val.attribute_count - 1, self) when Numeric, String, true, false, nil val else remember(val) end end # Remember that a value has been read. This means that the value is given an index # and that subsequent reads of a tabulation with that index should return the value. # @param [Object] value The value to remember # @return [Object] the argument # @api private def remember(value) @read << value value 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/pops/serialization/to_stringified_converter.rb
lib/puppet/pops/serialization/to_stringified_converter.rb
# frozen_string_literal: true module Puppet::Pops module Serialization # Class that can process an arbitrary object into a value that is assignable to `Data` # and where contents is converted from rich data to one of: # * Numeric (Integer, Float) # * Boolean # * Undef (nil) # * String # * Array # * Hash # # The conversion is lossy - the result cannot be deserialized to produce the original data types. # All rich values are transformed to strings.. # Hashes with rich keys are transformed to use string representation of such keys. # # @api public class ToStringifiedConverter include Evaluator::Runtime3Support # Converts the given _value_ according to the given _options_ and return the result of the conversion # # @param value [Object] the value to convert # @param options {Symbol => <Boolean,String>} options hash # @option options [String] :message_prefix String to prepend to in warnings and errors # @option options [String] :semantic object (AST) to pass to the issue reporter # @return [Data] the processed result. An object assignable to `Data` with rich data stringified. # # @api public def self.convert(value, options = EMPTY_HASH) new(options).convert(value) end # Creates a new instance of the processor # # @param options {Symbol => Object} options hash # @option options [String] :message_prefix String to prepend to path in warnings and errors # @option semantic [Object] :semantic object to pass to the issue reporter def initialize(options = EMPTY_HASH) @message_prefix = options[:message_prefix] @semantic = options[:semantic] end # Converts the given _value_ # # @param value [Object] the value to convert # @return [Data] the processed result. An object assignable to `Data` with rich data stringified. # # @api public def convert(value) @path = [] @values = {} to_data(value) end private def path_to_s s = @message_prefix || '' s << JsonPath.to_json_path(@path)[1..] s end def to_data(value) if value.instance_of?(String) to_string_or_binary(value) elsif value.nil? || Types::PScalarDataType::DEFAULT.instance?(value) value elsif :default == value 'default' elsif value.is_a?(Symbol) value.to_s elsif value.instance_of?(Array) process(value) do result = [] value.each_with_index do |elem, index| with(index) { result << to_data(elem) } end result end elsif value.instance_of?(Hash) process(value) do if value.keys.all? { |key| key.is_a?(String) && key != PCORE_TYPE_KEY && key != PCORE_VALUE_KEY } result = {} value.each_pair { |key, elem| with(key) { result[key] = to_data(elem) } } result else non_string_keyed_hash_to_data(value) end end else unknown_to_string(value) end end # Turns an ASCII-8BIT encoded string into a Binary, returns US_ASCII encoded and transforms all other strings to UTF-8 # with replacements for non Unicode characters. # If String cannot be represented as UTF-8 def to_string_or_binary(value) encoding = value.encoding if encoding == Encoding::ASCII_8BIT Puppet::Pops::Types::PBinaryType::Binary.from_binary_string(value).to_s else # Transform to UTF-8 (do not assume UTF-8 is correct) with source invalid byte # sequences and UTF-8 undefined characters replaced by the default unicode uFFFD character # (black diamond with question mark). value.encode(Encoding::UTF_8, encoding, :invalid => :replace, :undef => :replace) end end # Performs a check for endless recursion before # it yields to the given block. The result of yielding is returned. # # @param value [Object] the value # @yield The block that will produce the data for the value # @return [Data] the result of yielding to the given block, or a hash denoting a reference # # @api private def process(value, &block) with_recursive_guard(value, &block) end # Pushes `key` to the end of the path and yields to the given block. The # `key` is popped when the yield returns. # @param key [Object] the key to push on the current path # @yield The block that will produce the returned value # @return [Object] the result of yielding to the given block # # @api private def with(key) @path.push(key) value = yield @path.pop value end # @param value [Object] the value to use when checking endless recursion # @yield The block that will produce the data # @return [Data] the result of yielding to the given block def with_recursive_guard(value) id = value.object_id if @recursive_lock if @recursive_lock.include?(id) serialization_issue(Issues::SERIALIZATION_ENDLESS_RECURSION, :type_name => value.class.name) end @recursive_lock[id] = true else @recursive_lock = { id => true } end v = yield @recursive_lock.delete(id) v end # A hash key that is non conforming def unknown_key_to_string(value) unknown_to_string(value) end def unknown_to_string(value) if value.is_a?(Regexp) return Puppet::Pops::Types::PRegexpType.regexp_to_s_with_delimiters(value) elsif value.instance_of?(Types::PSensitiveType::Sensitive) # to_s does not differentiate between instances - if they were used as keys in a hash # the stringified result would override all Sensitive keys with the last such key's value # this adds object_id. # return "#<#{value}:#{value.object_id}>" elsif value.is_a?(Puppet::Pops::Types::PObjectType) # regular to_s on an ObjectType gives the entire definition return value.name end # Do a to_s on anything else result = value.to_s # The result may be ascii-8bit encoded without being a binary (low level object.inspect returns ascii-8bit string) # This can be the case if runtime objects have very simple implementation (no to_s or inspect method). # They are most likely not of Binary nature. Therefore the encoding is forced and only if it errors # will the result be taken as binary and encoded as base64 string. if result.encoding == Encoding::ASCII_8BIT begin result.force_encoding(Encoding::UTF_8) rescue # The result cannot be represented in UTF-8, make it a binary Base64 encoded string Puppet::Pops::Types::PBinaryType::Binary.from_binary_string(result).to_s end end result end def non_string_keyed_hash_to_data(hash) result = {} hash.each_pair do |key, value| if key.is_a?(Symbol) key = key.to_s elsif !key.is_a?(String) key = unknown_key_to_string(key) end if key == "__ptype" || key == "__pvalue" key = "reserved key: #{key}" end with(key) { result[key] = to_data(value) } end result end def serialization_issue(issue, options = EMPTY_HASH) semantic = @semantic if semantic.nil? tos = Puppet::Pops::PuppetStack.top_of_stack if tos.empty? semantic = Puppet::Pops::SemanticError.new(issue, nil, EMPTY_HASH) else file, line = stacktrace semantic = Puppet::Pops::SemanticError.new(issue, nil, { :file => file, :line => line }) end end optionally_fail(issue, semantic, options) 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/pops/serialization/extension.rb
lib/puppet/pops/serialization/extension.rb
# frozen_string_literal: true module Puppet::Pops module Serialization module Extension # 0x00 - 0x0F are reserved for low-level serialization / tabulation extensions # Tabulation internal to the low level protocol reader/writer INNER_TABULATION = 0x00 # Tabulation managed by the serializer / deserializer TABULATION = 0x01 # 0x10 - 0x1F are reserved for structural extensions ARRAY_START = 0x10 MAP_START = 0x11 PCORE_OBJECT_START = 0x12 OBJECT_START = 0x13 SENSITIVE_START = 0x14 # 0x20 - 0x2f reserved for special extension objects DEFAULT = 0x20 COMMENT = 0x21 # 0x30 - 0x7f reserved for mapping of specific runtime classes REGEXP = 0x30 TYPE_REFERENCE = 0x31 SYMBOL = 0x32 TIME = 0x33 TIMESPAN = 0x34 VERSION = 0x35 VERSION_RANGE = 0x36 BINARY = 0x37 BASE64 = 0x38 URI = 0x39 # Marker module indicating whether or not an instance is tabulated or not module NotTabulated; end # Marker module for objects that starts a sequence, i.e. ArrayStart, MapStart, and PcoreObjectStart module SequenceStart; end # The class that triggers the use of the DEFAULT extension. It doesn't have any payload class Default include NotTabulated INSTANCE = Default.new end # The class that triggers the use of the TABULATION extension. The payload is the tabulation index class Tabulation include NotTabulated attr_reader :index def initialize(index) @index = index end end # Tabulation internal to the protocol reader/writer class InnerTabulation < Tabulation end # The class that triggers the use of the MAP_START extension. The payload is the map size (number of entries) class MapStart include NotTabulated include SequenceStart attr_reader :size def initialize(size) @size = size end # Sequence size is twice the map size since each entry is written as key and value def sequence_size @size * 2 end end # The class that triggers the use of the ARRAY_START extension. The payload is the array size class ArrayStart include NotTabulated include SequenceStart attr_reader :size def initialize(size) @size = size end def sequence_size @size end end # The class that triggers the use of the SENSITIVE_START extension. It has no payload class SensitiveStart include NotTabulated INSTANCE = SensitiveStart.new end # The class that triggers the use of the PCORE_OBJECT_START extension. The payload is the name of the object type # and the number of attributes in the instance. class PcoreObjectStart include SequenceStart attr_reader :type_name, :attribute_count def initialize(type_name, attribute_count) @type_name = type_name @attribute_count = attribute_count end def hash @type_name.hash * 29 + attribute_count.hash end def eql?(o) o.is_a?(PcoreObjectStart) && o.type_name == @type_name && o.attribute_count == @attribute_count end alias == eql? def sequence_size @attribute_count end end class ObjectStart include SequenceStart attr_reader :attribute_count def initialize(attribute_count) @attribute_count = attribute_count end def hash attribute_count.hash end def eql?(o) o.is_a?(ObjectStart) && o.attribute_count == @attribute_count end alias == eql? def sequence_size @attribute_count end end # The class that triggers the use of the COMMENT extension. The payload is comment text class Comment attr_reader :comment def initialize(comment) @comment = comment end def hash @comment.hash end def eql?(o) o.is_a?(Comment) && o.comment == @comment end alias == eql? 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/pops/serialization/instance_reader.rb
lib/puppet/pops/serialization/instance_reader.rb
# frozen_string_literal: true module Puppet::Pops module Serialization # An InstanceReader is responsible for reading an instance of a complex object using a deserializer. The read involves creating the # instance, register it with the deserializer (so that self references can be resolved) and then read the instance data (which normally # amounts to all attribute values). # Instance readers are registered with of {Types::PObjectType}s to aid the type when reading instances. # # @api private module InstanceReader # @param [Class] impl_class the class of the instance to be created and initialized # @param [Integer] value_count the expected number of objects that forms the initialization data # @param [Deserializer] deserializer the deserializer to read from, and to register the instance with # @return [Object] the instance that has been read def read(impl_class, value_count, deserializer) Serialization.not_implemented(self, 'read') 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/external/dot.rb
lib/puppet/external/dot.rb
# frozen_string_literal: true # rdot.rb # # # This is a modified version of dot.rb from Dave Thomas's rdoc project. I [Horst Duchene] # renamed it to rdot.rb to avoid collision with an installed rdoc/dot. # # It also supports undirected edges. module DOT # These global vars are used to make nice graph source. $tab = ' ' $tab2 = $tab * 2 # if we don't like 4 spaces, we can change it any time def change_tab(t) $tab = t $tab2 = t * 2 end # options for node declaration NODE_OPTS = [ # attributes due to # http://www.graphviz.org/Documentation/dotguide.pdf # March, 26, 2005 'bottomlabel', # auxiliary label for nodes of shape M* 'color', # default: black; node shape color 'comment', # any string (format-dependent) 'distortion', # default: 0.0; node distortion for shape=polygon 'fillcolor', # default: lightgrey/black; node fill color 'fixedsize', # default: false; label text has no affect on node size 'fontcolor', # default: black; type face color 'fontname', # default: Times-Roman; font family 'fontsize', # default: 14; point size of label 'group', # name of node's group 'height', # default: .5; height in inches 'label', # default: node name; any string 'layer', # default: overlay range; all, id or id:id 'orientation', # default: 0.0; node rotation angle 'peripheries', # shape-dependent number of node boundaries 'regular', # default: false; force polygon to be regular 'shape', # default: ellipse; node shape; see Section 2.1 and Appendix E 'shapefile', # external EPSF or SVG custom shape file 'sides', # default: 4; number of sides for shape=polygon 'skew', # default: 0.0; skewing of node for shape=polygon 'style', # graphics options, e.g. bold, dotted, filled; cf. Section 2.3 'toplabel', # auxiliary label for nodes of shape M* 'URL', # URL associated with node (format-dependent) 'width', # default: .75; width in inches 'z', # default: 0.0; z coordinate for VRML output # maintained for backward compatibility or rdot internal 'bgcolor', 'rank' ] # options for edge declaration EDGE_OPTS = [ 'arrowhead', # default: normal; style of arrowhead at head end 'arrowsize', # default: 1.0; scaling factor for arrowheads 'arrowtail', # default: normal; style of arrowhead at tail end 'color', # default: black; edge stroke color 'comment', # any string (format-dependent) 'constraint', # default: true use edge to affect node ranking 'decorate', # if set, draws a line connecting labels with their edges 'dir', # default: forward; forward, back, both, or none 'fontcolor', # default: black type face color 'fontname', # default: Times-Roman; font family 'fontsize', # default: 14; point size of label 'headlabel', # label placed near head of edge 'headport', # n,ne,e,se,s,sw,w,nw 'headURL', # URL attached to head label if output format is ismap 'label', # edge label 'labelangle', # default: -25.0; angle in degrees which head or tail label is rotated off edge 'labeldistance', # default: 1.0; scaling factor for distance of head or tail label from node 'labelfloat', # default: false; lessen constraints on edge label placement 'labelfontcolor', # default: black; type face color for head and tail labels 'labelfontname', # default: Times-Roman; font family for head and tail labels 'labelfontsize', # default: 14 point size for head and tail labels 'layer', # default: overlay range; all, id or id:id 'lhead', # name of cluster to use as head of edge 'ltail', # name of cluster to use as tail of edge 'minlen', # default: 1 minimum rank distance between head and tail 'samehead', # tag for head node; edge heads with the same tag are merged onto the same port 'sametail', # tag for tail node; edge tails with the same tag are merged onto the same port 'style', # graphics options, e.g. bold, dotted, filled; cf. Section 2.3 'taillabel', # label placed near tail of edge 'tailport', # n,ne,e,se,s,sw,w,nw 'tailURL', # URL attached to tail label if output format is ismap 'weight', # default: 1; integer cost of stretching an edge # maintained for backward compatibility or rdot internal 'id' ] # options for graph declaration GRAPH_OPTS = %w[ bgcolor center clusterrank color concentrate fontcolor fontname fontsize label layerseq margin mclimit nodesep nslimit ordering orientation page rank rankdir ranksep ratio size ] # a root class for any element in dot notation class DOTSimpleElement attr_accessor :name def initialize(params = {}) @label = params['name'] || '' end def to_s @name end end # an element that has options ( node, edge, or graph ) class DOTElement < DOTSimpleElement # attr_reader :parent attr_accessor :name, :options def initialize(params = {}, option_list = []) super(params) @name = params['name'] || nil @parent = params['parent'] || nil @options = {} option_list.each { |i| @options[i] = params[i] if params[i] } @options['label'] ||= @name if @name != 'node' end def each_option @options.each { |i| yield i } end def each_option_pair @options.each_pair { |key, val| yield key, val } end end # This is used when we build nodes that have shape=record # ports don't have options :) class DOTPort < DOTSimpleElement attr_accessor :label def initialize(params = {}) super(params) @name = params['label'] || '' end def to_s (@name && @name != "" ? "<#{@name}>" : "") + @label.to_s end end # node element class DOTNode < DOTElement def initialize(params = {}, option_list = NODE_OPTS) super(params, option_list) @ports = params['ports'] || [] end def each_port @ports.each { |i| yield i } end def <<(thing) @ports << thing end def push(thing) @ports.push(thing) end def pop @ports.pop end def to_s(t = '') # This code is totally incomprehensible; it needs to be replaced! label = if @options['shape'] != 'record' && @ports.length == 0 if @options['label'] t + $tab + "label = #{stringify(@options['label'])}\n" else '' end else t + $tab + 'label = "' + " \\\n" + t + $tab2 + "#{stringify(@options['label'])}| \\\n" + @ports.collect { |i| t + $tab2 + i.to_s }.join("| \\\n") + " \\\n" + t + $tab + '"' + "\n" end t + "#{@name} [\n" + @options.to_a.filter_map { |i| i[1] && i[0] != 'label' ? t + $tab + "#{i[0]} = #{i[1]}" : nil }.join(",\n") + (label != '' ? ",\n" : "\n") + label + t + "]\n" end private def stringify(s) %("#{s.gsub('"', '\\"')}") end end # A subgraph element is the same to graph, but has another header in dot # notation. class DOTSubgraph < DOTElement def initialize(params = {}, option_list = GRAPH_OPTS) super(params, option_list) @nodes = params['nodes'] || [] @dot_string = 'graph' end def each_node @nodes.each { |i| yield i } end def <<(thing) @nodes << thing end def push(thing) @nodes.push(thing) end def pop @nodes.pop end def to_s(t = '') hdr = t + "#{@dot_string} #{@name} {\n" options = @options.to_a.filter_map { |name, val| if val && name != 'label' t + $tab + "#{name} = #{val}" else name ? t + $tab + "#{name} = \"#{val}\"" : nil end }.join("\n") + "\n" nodes = @nodes.collect { |i| i.to_s(t + $tab) }.join("\n") + "\n" hdr + options + nodes + t + "}\n" end end # This is a graph. class DOTDigraph < DOTSubgraph def initialize(params = {}, option_list = GRAPH_OPTS) super(params, option_list) @dot_string = 'digraph' end end # This is an edge. class DOTEdge < DOTElement attr_accessor :from, :to def initialize(params = {}, option_list = EDGE_OPTS) super(params, option_list) @from = params['from'] || nil @to = params['to'] || nil end def edge_link '--' end def to_s(t = '') t + "#{@from} #{edge_link} #{to} [\n" + @options.to_a.filter_map { |i| if i[1] && i[0] != 'label' t + $tab + "#{i[0]} = #{i[1]}" else i[1] ? t + $tab + "#{i[0]} = \"#{i[1]}\"" : nil end }.join("\n") + "\n#{t}]\n" end end class DOTDirectedEdge < DOTEdge def edge_link '->' 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/application/agent.rb
lib/puppet/application/agent.rb
# frozen_string_literal: true require_relative '../../puppet/application' require_relative '../../puppet/daemon' require_relative '../../puppet/util/pidlock' require_relative '../../puppet/agent' require_relative '../../puppet/configurer' require_relative '../../puppet/ssl/oids' class Puppet::Application::Agent < Puppet::Application run_mode :agent def app_defaults super.merge({ :catalog_terminus => :rest, :catalog_cache_terminus => :json, :node_terminus => :rest, :facts_terminus => :facter, }) end def preinit # Do an initial trap, so that cancels don't get a stack trace. Signal.trap(:INT) do $stderr.puts _("Cancelling startup") exit(0) end { :waitforcert => nil, :detailed_exitcodes => false, :verbose => false, :debug => false, :setdest => false, :enable => false, :disable => false, :fqdn => nil, :serve => [], :digest => 'SHA256', :graph => true, :fingerprint => false, :sourceaddress => nil, :start_time => Time.now, }.each do |opt, val| options[opt] = val end @argv = ARGV.dup end option("--disable [MESSAGE]") do |message| options[:disable] = true options[:disable_message] = message end option("--enable") option("--debug", "-d") option("--fqdn FQDN", "-f") option("--test", "-t") option("--verbose", "-v") option("--fingerprint") option("--digest DIGEST") option("--sourceaddress IP_ADDRESS") option("--detailed-exitcodes") do |_arg| options[:detailed_exitcodes] = true end option("--logdest DEST", "-l DEST") do |arg| handle_logdest_arg(arg) end option("--waitforcert WAITFORCERT", "-w") do |arg| options[:waitforcert] = arg.to_i end option("--job-id ID") do |arg| options[:job_id] = arg end def summary _("The puppet agent daemon") end def help <<~HELP puppet-agent(8) -- #{summary} ======== SYNOPSIS -------- Retrieves the client configuration from the Puppet master and applies it to the local host. This service may be run as a daemon, run periodically using cron (or something similar), or run interactively for testing purposes. USAGE ----- puppet agent [--certname <NAME>] [-D|--daemonize|--no-daemonize] [-d|--debug] [--detailed-exitcodes] [--digest <DIGEST>] [--disable [MESSAGE]] [--enable] [--fingerprint] [-h|--help] [-l|--logdest syslog|eventlog|<ABS FILEPATH>|console] [--serverport <PORT>] [--noop] [-o|--onetime] [--sourceaddress <IP_ADDRESS>] [-t|--test] [-v|--verbose] [-V|--version] [-w|--waitforcert <SECONDS>] DESCRIPTION ----------- This is the main puppet client. Its job is to retrieve the local machine's configuration from a remote server and apply it. In order to successfully communicate with the remote server, the client must have a certificate signed by a certificate authority that the server trusts; the recommended method for this, at the moment, is to run a certificate authority as part of the puppet server (which is the default). The client will connect and request a signed certificate, and will continue connecting until it receives one. Once the client has a signed certificate, it will retrieve its configuration and apply it. USAGE NOTES ----------- 'puppet agent' does its best to find a compromise between interactive use and daemon use. If you run it with no arguments and no configuration, it goes into the background, attempts to get a signed certificate, and retrieves and applies its configuration every 30 minutes. Some flags are meant specifically for interactive use --- in particular, 'test', 'tags' and 'fingerprint' are useful. '--test' runs once in the foreground with verbose logging, then exits. It also exits if it can't get a valid catalog. `--test` includes the '--detailed-exitcodes' option by default and exits with one of the following exit codes: * 0: The run succeeded with no changes or failures; the system was already in the desired state. * 1: The run failed, or wasn't attempted due to another run already in progress. * 2: The run succeeded, and some resources were changed. * 4: The run succeeded, and some resources failed. * 6: The run succeeded, and included both changes and failures. '--tags' allows you to specify what portions of a configuration you want to apply. Puppet elements are tagged with all of the class or definition names that contain them, and you can use the 'tags' flag to specify one of these names, causing only configuration elements contained within that class or definition to be applied. This is very useful when you are testing new configurations --- for instance, if you are just starting to manage 'ntpd', you would put all of the new elements into an 'ntpd' class, and call puppet with '--tags ntpd', which would only apply that small portion of the configuration during your testing, rather than applying the whole thing. '--fingerprint' is a one-time flag. In this mode 'puppet agent' runs once and displays on the console (and in the log) the current certificate (or certificate request) fingerprint. Providing the '--digest' option allows you to use a different digest algorithm to generate the fingerprint. The main use is to verify that before signing a certificate request on the master, the certificate request the master received is the same as the one the client sent (to prevent against man-in-the-middle attacks when signing certificates). '--skip_tags' is a flag used to filter resources. If this is set, then only resources not tagged with the specified tags will be applied. Values must be comma-separated. OPTIONS ------- Note that any Puppet setting that's valid in the configuration file is also a valid long argument. For example, 'server' is a valid setting, so you can specify '--server <servername>' as an argument. Boolean settings accept a '--no-' prefix to turn off a behavior, translating into '--setting' and '--no-setting' pairs, such as `--daemonize` and `--no-daemonize`. See the configuration file documentation at https://puppet.com/docs/puppet/latest/configuration.html for the full list of acceptable settings. A commented list of all settings can also be generated by running puppet agent with '--genconfig'. * --certname: Set the certname (unique ID) of the client. The master reads this unique identifying string, which is usually set to the node's fully-qualified domain name, to determine which configurations the node will receive. Use this option to debug setup problems or implement unusual node identification schemes. (This is a Puppet setting, and can go in puppet.conf.) * --daemonize: Send the process into the background. This is the default. (This is a Puppet setting, and can go in puppet.conf. Note the special 'no-' prefix for boolean settings on the command line.) * --no-daemonize: Do not send the process into the background. (This is a Puppet setting, and can go in puppet.conf. Note the special 'no-' prefix for boolean settings on the command line.) * --debug: Enable full debugging. * --detailed-exitcodes: Provide extra information about the run via exit codes; works only if '--test' or '--onetime' is also specified. If enabled, 'puppet agent' uses the following exit codes: 0: The run succeeded with no changes or failures; the system was already in the desired state. 1: The run failed, or wasn't attempted due to another run already in progress. 2: The run succeeded, and some resources were changed. 4: The run succeeded, and some resources failed. 6: The run succeeded, and included both changes and failures. * --digest: Change the certificate fingerprinting digest algorithm. The default is SHA256. Valid values depends on the version of OpenSSL installed, but will likely contain MD5, MD2, SHA1 and SHA256. * --disable: Disable working on the local system. This puts a lock file in place, causing 'puppet agent' not to work on the system until the lock file is removed. This is useful if you are testing a configuration and do not want the central configuration to override the local state until everything is tested and committed. Disable can also take an optional message that will be reported by the 'puppet agent' at the next disabled run. 'puppet agent' uses the same lock file while it is running, so no more than one 'puppet agent' process is working at a time. 'puppet agent' exits after executing this. * --enable: Enable working on the local system. This removes any lock file, causing 'puppet agent' to start managing the local system again However, it continues to use its normal scheduling, so it might not start for another half hour. 'puppet agent' exits after executing this. * --evaltrace: Logs each resource as it is being evaluated. This allows you to interactively see exactly what is being done. (This is a Puppet setting, and can go in puppet.conf. Note the special 'no-' prefix for boolean settings on the command line.) * --fingerprint: Display the current certificate or certificate signing request fingerprint and then exit. Use the '--digest' option to change the digest algorithm used. * --help: Print this help message * --job-id: Attach the specified job id to the catalog request and the report used for this agent run. This option only works when '--onetime' is used. When using Puppet Enterprise this flag should not be used as the orchestrator sets the job-id for you and it must be unique. * --logdest: Where to send log messages. Choose between 'syslog' (the POSIX syslog service), 'eventlog' (the Windows Event Log), 'console', or the path to a log file. If debugging or verbosity is enabled, this defaults to 'console'. Otherwise, it defaults to 'syslog' on POSIX systems and 'eventlog' on Windows. Multiple destinations can be set using a comma separated list (eg: `/path/file1,console,/path/file2`)" A path ending with '.json' will receive structured output in JSON format. The log file will not have an ending ']' automatically written to it due to the appending nature of logging. It must be appended manually to make the content valid JSON. A path ending with '.jsonl' will receive structured output in JSON Lines format. * --masterport: The port on which to contact the Puppet Server. (This is a Puppet setting, and can go in puppet.conf. Deprecated in favor of the 'serverport' setting.) * --noop: Use 'noop' mode where the daemon runs in a no-op or dry-run mode. This is useful for seeing what changes Puppet would make without actually executing the changes. (This is a Puppet setting, and can go in puppet.conf. Note the special 'no-' prefix for boolean settings on the command line.) * --onetime: Run the configuration once. Runs a single (normally daemonized) Puppet run. Useful for interactively running puppet agent when used in conjunction with the --no-daemonize option. (This is a Puppet setting, and can go in puppet.conf. Note the special 'no-' prefix for boolean settings on the command line.) * --serverport: The port on which to contact the Puppet Server. (This is a Puppet setting, and can go in puppet.conf.) * --sourceaddress: Set the source IP address for transactions. This defaults to automatically selected. (This is a Puppet setting, and can go in puppet.conf.) * --test: Enable the most common options used for testing. These are 'onetime', 'verbose', 'no-daemonize', 'no-usecacheonfailure', 'detailed-exitcodes', 'no-splay', and 'show_diff'. * --trace Prints stack traces on some errors. (This is a Puppet setting, and can go in puppet.conf. Note the special 'no-' prefix for boolean settings on the command line.) * --verbose: Turn on verbose reporting. * --version: Print the puppet version number and exit. * --waitforcert: This option only matters for daemons that do not yet have certificates and it is enabled by default, with a value of 120 (seconds). This causes 'puppet agent' to connect to the server every 2 minutes and ask it to sign a certificate request. This is useful for the initial setup of a puppet client. You can turn off waiting for certificates by specifying a time of 0. (This is a Puppet setting, and can go in puppet.conf.) * --write_catalog_summary After compiling the catalog saves the resource list and classes list to the node in the state directory named classes.txt and resources.txt (This is a Puppet setting, and can go in puppet.conf.) EXAMPLE ------- $ puppet agent --server puppet.domain.com DIAGNOSTICS ----------- Puppet agent accepts the following signals: * SIGHUP: Restart the puppet agent daemon. * SIGINT and SIGTERM: Shut down the puppet agent daemon. * SIGUSR1: Immediately retrieve and apply configurations from the puppet master. * SIGUSR2: Close file descriptors for log files and reopen them. Used with logrotate. AUTHOR ------ Luke Kanies COPYRIGHT --------- Copyright (c) 2011 Puppet Inc., LLC Licensed under the Apache 2.0 License HELP end def run_command if options[:fingerprint] fingerprint else # It'd be nice to daemonize later, but we have to daemonize before # waiting for certificates so that we don't block daemon = daemonize_process_when(Puppet[:daemonize]) # Setup signal traps immediately after daemonization so we clean up the daemon daemon.set_signal_traps log_config if Puppet[:daemonize] # Each application is responsible for pushing loaders onto the context. # Use the current environment that has already been established, though # it may change later during the configurer run. env = Puppet.lookup(:current_environment) Puppet.override(current_environment: env, loaders: Puppet::Pops::Loaders.new(env, true)) do if Puppet[:onetime] onetime(daemon) else main(daemon) end end end end def log_config # skip also config reading and parsing if debug is not enabled return unless Puppet::Util::Log.sendlevel?(:debug) Puppet.settings.stringify_settings(:agent, :all).each_pair do |k, v| next if k.include?("password") || v.to_s.empty? Puppet.debug("Using setting: #{k}=#{v}") end end # rubocop:disable Lint/RedundantStringCoercion def fingerprint Puppet::Util::Log.newdestination(:console) cert_provider = Puppet::X509::CertProvider.new client_cert = cert_provider.load_client_cert(Puppet[:certname]) if client_cert puts Puppet::SSL::Digest.new(options[:digest].to_s, client_cert.to_der).to_s else csr = cert_provider.load_request(Puppet[:certname]) if csr puts Puppet::SSL::Digest.new(options[:digest].to_s, csr.to_der).to_s else $stderr.puts _("Fingerprint asked but neither the certificate, nor the certificate request have been issued") exit(1) end end rescue => e Puppet.log_exception(e, _("Failed to generate fingerprint: %{message}") % { message: e.message }) exit(1) end # rubocop:enable Lint/RedundantStringCoercion def onetime(daemon) begin exitstatus = daemon.agent.run({ :job_id => options[:job_id], :start_time => options[:start_time], :waitforcert => options[:waitforcert] }) rescue => detail Puppet.log_exception(detail) end daemon.stop(:exit => false) if !exitstatus exit(1) elsif options[:detailed_exitcodes] then exit(exitstatus) else exit(0) end end def main(daemon) Puppet.notice _("Starting Puppet client version %{version}") % { version: Puppet.version } daemon.start end # Enable all of the most common test options. def setup_test Puppet.settings.handlearg("--no-usecacheonfailure") Puppet.settings.handlearg("--no-splay") Puppet.settings.handlearg("--show_diff") Puppet.settings.handlearg("--no-daemonize") options[:verbose] = true Puppet[:onetime] = true options[:detailed_exitcodes] = true end def setup raise ArgumentError, _("The puppet agent command does not take parameters") unless command_line.args.empty? setup_test if options[:test] setup_logs exit(Puppet.settings.print_configs ? 0 : 1) if Puppet.settings.print_configs? Puppet::SSL::Oids.register_puppet_oids if options[:fqdn] Puppet[:certname] = options[:fqdn] end Puppet.settings.use :main, :agent, :ssl Puppet::Transaction::Report.indirection.terminus_class = :rest # we want the last report to be persisted locally Puppet::Transaction::Report.indirection.cache_class = :yaml if Puppet[:catalog_cache_terminus] Puppet::Resource::Catalog.indirection.cache_class = Puppet[:catalog_cache_terminus] end # In fingerprint mode we don't need to set up the whole agent unless options[:fingerprint] setup_agent end end private def enable_disable_client(agent) if options[:enable] agent.enable elsif options[:disable] agent.disable(options[:disable_message] || 'reason not specified') end exit(0) end def setup_agent agent = Puppet::Agent.new(Puppet::Configurer, !(Puppet[:onetime])) enable_disable_client(agent) if options[:enable] or options[:disable] @agent = agent end def daemonize_process_when(should_daemonize) daemon = Puppet::Daemon.new(@agent, Puppet::Util::Pidlock.new(Puppet[:pidfile])) daemon.argv = @argv daemon.daemonize if should_daemonize daemon 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/application/resource.rb
lib/puppet/application/resource.rb
# frozen_string_literal: true require_relative '../../puppet/application' class Puppet::Application::Resource < Puppet::Application environment_mode :not_required attr_accessor :host, :extra_params def preinit @extra_params = [:provider] end option("--debug", "-d") option("--verbose", "-v") option("--edit", "-e") option("--to_yaml", "-y") option('--fail', '-f') option("--types", "-t") do |_arg| env = Puppet.lookup(:environments).get(Puppet[:environment]) || create_default_environment types = [] Puppet::Type.typeloader.loadall(env) Puppet::Type.eachtype do |t| next if t.name == :component types << t.name.to_s end puts types.sort exit(0) end option("--param PARAM", "-p") do |arg| @extra_params << arg.to_sym end def summary _("The resource abstraction layer shell") end def help <<~HELP puppet-resource(8) -- #{summary} ======== SYNOPSIS -------- Uses the Puppet RAL to directly interact with the system. USAGE ----- puppet resource [-h|--help] [-d|--debug] [-v|--verbose] [-e|--edit] [-p|--param <parameter>] [-t|--types] [-y|--to_yaml] <type> [<name>] [<attribute>=<value> ...] DESCRIPTION ----------- This command provides simple facilities for converting current system state into Puppet code, along with some ability to modify the current state using Puppet's RAL. By default, you must at least provide a type to list, in which case puppet resource will tell you everything it knows about all resources of that type. You can optionally specify an instance name, and puppet resource will only describe that single instance. If given a type, a name, and a series of <attribute>=<value> pairs, puppet resource will modify the state of the specified resource. Alternately, if given a type, a name, and the '--edit' flag, puppet resource will write its output to a file, open that file in an editor, and then apply the saved file as a Puppet transaction. OPTIONS ------- Note that any setting that's valid in the configuration file is also a valid long argument. For example, 'ssldir' is a valid setting, so you can specify '--ssldir <directory>' as an argument. See the configuration file documentation at https://puppet.com/docs/puppet/latest/configuration.html for the full list of acceptable parameters. A commented list of all configuration options can also be generated by running puppet with '--genconfig'. * --debug: Enable full debugging. * --edit: Write the results of the query to a file, open the file in an editor, and read the file back in as an executable Puppet manifest. * --help: Print this help message. * --param: Add more parameters to be outputted from queries. * --types: List all available types. * --verbose: Print extra information. * --to_yaml: Output found resources in yaml format, suitable to use with Hiera and create_resources. * --fail: Fails and returns an exit code of 1 if the resource could not be modified. EXAMPLE ------- This example uses `puppet resource` to return a Puppet configuration for the user `luke`: $ puppet resource user luke user { 'luke': home => '/home/luke', uid => '100', ensure => 'present', comment => 'Luke Kanies,,,', gid => '1000', shell => '/bin/bash', groups => ['sysadmin','audio','video','puppet'] } AUTHOR ------ Luke Kanies COPYRIGHT --------- Copyright (c) 2011 Puppet Inc., LLC Licensed under the Apache 2.0 License HELP end def main # If the specified environment does not exist locally, fall back to the default (production) environment env = Puppet.lookup(:environments).get(Puppet[:environment]) || create_default_environment Puppet.override( current_environment: env, loaders: Puppet::Pops::Loaders.new(env), stringify_rich: true ) do type, name, params = parse_args(command_line.args) raise _("Editing with Yaml output is not supported") if options[:edit] and options[:to_yaml] resources = find_or_save_resources(type, name, params) if options[:to_yaml] data = resources.map do |resource| resource.prune_parameters(:parameters_to_include => @extra_params).to_hiera_hash end.inject(:merge!) text = YAML.dump(type.downcase => data) else text = resources.map do |resource| resource.prune_parameters(:parameters_to_include => @extra_params).to_manifest.force_encoding(Encoding.default_external) end.join("\n") end options[:edit] ? handle_editing(text) : (puts text) end end def setup Puppet::Util::Log.newdestination(:console) set_log_level end private def local_key(type, name) [type, name].join('/') end def handle_editing(text) require 'tempfile' # Prefer the current directory, which is more likely to be secure # and, in the case of interactive use, accessible to the user. tmpfile = Tempfile.new('x2puppet', Dir.pwd, :encoding => Encoding::UTF_8) begin # sync write, so nothing buffers before we invoke the editor. tmpfile.sync = true tmpfile.puts text # edit the content system(ENV.fetch("EDITOR", nil) || 'vi', tmpfile.path) # ...and, now, pass that file to puppet to apply. Because # many editors rename or replace the original file we need to # feed the pathname, not the file content itself, to puppet. system('puppet apply -v ' + tmpfile.path) ensure # The temporary file will be safely removed. tmpfile.close(true) end end def parse_args(args) type = args.shift or raise _("You must specify the type to display") Puppet::Type.type(type) or raise _("Could not find type %{type}") % { type: type } name = args.shift params = {} args.each do |setting| if setting =~ /^(\w+)=(.+)$/ params[::Regexp.last_match(1)] = ::Regexp.last_match(2) else raise _("Invalid parameter setting %{setting}") % { setting: setting } end end [type, name, params] end def create_default_environment Puppet.debug("Specified environment '#{Puppet[:environment]}' does not exist on the filesystem, defaulting to 'production'") Puppet[:environment] = :production basemodulepath = Puppet::Node::Environment.split_path(Puppet[:basemodulepath]) modulepath = Puppet[:modulepath] modulepath = (modulepath.nil? || modulepath.empty?) ? basemodulepath : Puppet::Node::Environment.split_path(modulepath) Puppet::Node::Environment.create(Puppet[:environment], modulepath, Puppet::Node::Environment::NO_MANIFEST) end def find_or_save_resources(type, name, params) key = local_key(type, name) Puppet.override(stringify_rich: true) do if name if params.empty? [Puppet::Resource.indirection.find(key)] else resource = Puppet::Resource.new(type, name, :parameters => params) # save returns [resource that was saved, transaction log from applying the resource] save_result, report = Puppet::Resource.indirection.save(resource, key) status = report.resource_statuses[resource.ref] raise "Failed to manage resource #{resource.ref}" if status&.failed? && options[:fail] [save_result] end else if type == "file" raise _("Listing all file instances is not supported. Please specify a file or directory, e.g. puppet resource file /etc") end Puppet::Resource.indirection.search(key, {}) 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/application/report.rb
lib/puppet/application/report.rb
# frozen_string_literal: true require_relative '../../puppet/application/indirection_base' class Puppet::Application::Report < Puppet::Application::IndirectionBase end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/application/script.rb
lib/puppet/application/script.rb
# frozen_string_literal: true require_relative '../../puppet/application' require_relative '../../puppet/configurer' require_relative '../../puppet/util/profiler/aggregate' require_relative '../../puppet/parser/script_compiler' class Puppet::Application::Script < Puppet::Application option("--debug", "-d") option("--execute EXECUTE", "-e") do |arg| options[:code] = arg end option("--test", "-t") option("--verbose", "-v") option("--logdest LOGDEST", "-l") do |arg| handle_logdest_arg(arg) end def summary _("Run a puppet manifests as a script without compiling a catalog") end def help <<~HELP puppet-script(8) -- #{summary} ======== SYNOPSIS -------- Runs a puppet language script without compiling a catalog. USAGE ----- puppet script [-h|--help] [-V|--version] [-d|--debug] [-v|--verbose] [-e|--execute] [-l|--logdest syslog|eventlog|<FILE>|console] [--noop] <file> DESCRIPTION ----------- This is a standalone puppet script runner tool; use it to run puppet code without compiling a catalog. When provided with a modulepath, via command line or config file, puppet script can load functions, types, tasks and plans from modules. OPTIONS ------- Note that any setting that's valid in the configuration file is also a valid long argument. For example, 'environment' is a valid setting, so you can specify '--environment mytest' as an argument. See the configuration file documentation at https://puppet.com/docs/puppet/latest/configuration.html for the full list of acceptable parameters. A commented list of all configuration options can also be generated by running puppet with '--genconfig'. * --debug: Enable full debugging. * --help: Print this help message * --logdest: Where to send log messages. Choose between 'syslog' (the POSIX syslog service), 'eventlog' (the Windows Event Log), 'console', or the path to a log file. Defaults to 'console'. Multiple destinations can be set using a comma separated list (eg: `/path/file1,console,/path/file2`)" A path ending with '.json' will receive structured output in JSON format. The log file will not have an ending ']' automatically written to it due to the appending nature of logging. It must be appended manually to make the content valid JSON. A path ending with '.jsonl' will receive structured output in JSON Lines format. * --noop: Use 'noop' mode where Puppet runs in a no-op or dry-run mode. This is useful for seeing what changes Puppet will make without actually executing the changes. Applies to tasks only. * --execute: Execute a specific piece of Puppet code * --verbose: Print extra information. EXAMPLE ------- $ puppet script -l /tmp/manifest.log manifest.pp $ puppet script --modulepath=/root/dev/modules -e 'notice("hello world")' AUTHOR ------ Henrik Lindberg COPYRIGHT --------- Copyright (c) 2017 Puppet Inc., LLC Licensed under the Apache 2.0 License HELP end def app_defaults super.merge({ :default_file_terminus => :file_server, }) end def run_command if Puppet.features.bolt? Puppet.override(:bolt_executor => Bolt::Executor.new) do main end else raise _("Bolt must be installed to use the script application") end end def main # The tasks feature is always on Puppet[:tasks] = true # Set the puppet code or file to use. if options[:code] || command_line.args.length == 0 Puppet[:code] = options[:code] || STDIN.read else manifest = command_line.args.shift raise _("Could not find file %{manifest}") % { manifest: manifest } unless Puppet::FileSystem.exist?(manifest) Puppet.warning(_("Only one file can be used per run. Skipping %{files}") % { files: command_line.args.join(', ') }) if command_line.args.size > 0 end unless Puppet[:node_name_fact].empty? # Collect the facts specified for that node facts = Puppet::Node::Facts.indirection.find(Puppet[:node_name_value]) raise _("Could not find facts for %{node}") % { node: Puppet[:node_name_value] } unless facts Puppet[:node_name_value] = facts.values[Puppet[:node_name_fact]] facts.name = Puppet[:node_name_value] end # Find the Node node = Puppet::Node.indirection.find(Puppet[:node_name_value]) raise _("Could not find node %{node}") % { node: Puppet[:node_name_value] } unless node 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 # TRANSLATION, the string "For puppet script" is not user facing Puppet.override({ :current_environment => apply_environment }, "For puppet script") do # Merge in the facts. node.merge(facts.values) if 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({}) begin # Compile the catalog # When compiling, the compiler traps and logs certain errors # Those that do not lead to an immediate exit are caught by the general # rule and gets logged. # begin # support the following features when evaluating puppet code # * $facts with facts from host running the script # * $settings with 'settings::*' namespace populated, and '$settings::all_local' hash # * $trusted as setup when using puppet apply # * an environment # # fixup trusted information node.sanitize() compiler = Puppet::Parser::ScriptCompiler.new(node.environment, node.name) topscope = compiler.topscope # When scripting the trusted data are always local, but set them anyway topscope.set_trusted(node.trusted_data) # Server facts are always about the local node's version etc. topscope.set_server_facts(node.server_facts) # Set $facts for the node running the script facts_hash = node.facts.nil? ? {} : node.facts.values topscope.set_facts(facts_hash) # create the $settings:: variables topscope.merge_settings(node.environment.name, false) compiler.compile() rescue Puppet::Error # already logged and handled by the compiler, including Puppet::ParseErrorWithIssue exit(1) end exit(0) rescue => detail Puppet.log_exception(detail) exit(1) end end ensure if @profiler Puppet::Util::Profiler.remove_profiler(@profiler) @profiler.shutdown end end def setup exit(Puppet.settings.print_configs ? 0 : 1) if Puppet.settings.print_configs? handle_logdest_arg(Puppet[:logdest]) Puppet::Util::Log.newdestination(:console) unless options[:setdest] Signal.trap(:INT) do $stderr.puts _("Exiting") exit(1) end # TODO: This skips applying the settings catalog for these settings, but # the effect of doing this is unknown. It may be that it only works if there is a puppet # installed where a settings catalog have already been applied... # This saves 1/5th of the startup time # Puppet.settings.use :main, :agent, :ssl # When running a script, the catalog is not relevant, and neither is caching of it Puppet::Resource::Catalog.indirection.cache_class = nil # we do not want the last report to be persisted Puppet::Transaction::Report.indirection.cache_class = nil set_log_level if Puppet[:profile] @profiler = Puppet::Util::Profiler.add_profiler(Puppet::Util::Profiler::Aggregate.new(Puppet.method(:info), "script")) 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/application/generate.rb
lib/puppet/application/generate.rb
# frozen_string_literal: true require_relative '../../puppet/application/face_base' # The Generate application. class Puppet::Application::Generate < Puppet::Application::FaceBase end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/application/doc.rb
lib/puppet/application/doc.rb
# frozen_string_literal: true require_relative '../../puppet/application' class Puppet::Application::Doc < Puppet::Application run_mode :server attr_accessor :unknown_args, :manifest def preinit { :references => [], :mode => :text, :format => :to_markdown }.each do |name, value| options[name] = value end @unknown_args = [] @manifest = false end option("--all", "-a") option("--outputdir OUTPUTDIR", "-o") option("--verbose", "-v") option("--debug", "-d") option("--charset CHARSET") option("--format FORMAT", "-f") do |arg| method = "to_#{arg}" require_relative '../../puppet/util/reference' if Puppet::Util::Reference.method_defined?(method) options[:format] = method else raise _("Invalid output format %{arg}") % { arg: arg } end end option("--mode MODE", "-m") do |arg| require_relative '../../puppet/util/reference' if Puppet::Util::Reference.modes.include?(arg) or arg.intern == :rdoc options[:mode] = arg.intern else raise _("Invalid output mode %{arg}") % { arg: arg } end end option("--list", "-l") do |_arg| require_relative '../../puppet/util/reference' refs = Puppet::Util::Reference.references(Puppet.lookup(:current_environment)) puts refs.collect { |r| Puppet::Util::Reference.reference(r).doc }.join("\n") exit(0) end option("--reference REFERENCE", "-r") do |arg| options[:references] << arg.intern end def summary _("Generate Puppet references") end def help <<~HELP puppet-doc(8) -- #{summary} ======== SYNOPSIS -------- Generates a reference for all Puppet types. Largely meant for internal Puppet Inc. use. (Deprecated) USAGE ----- puppet doc [-h|--help] [-l|--list] [-r|--reference <reference-name>] DESCRIPTION ----------- This deprecated command generates a Markdown document to stdout describing all installed Puppet types or all allowable arguments to puppet executables. It is largely meant for internal use and is used to generate the reference document available on the Puppet Inc. web site. For Puppet module documentation (and all other use cases) this command has been superseded by the "puppet-strings" module - see https://github.com/puppetlabs/puppetlabs-strings for more information. This command (puppet-doc) will be removed once the puppetlabs internal documentation processing pipeline is completely based on puppet-strings. OPTIONS ------- * --help: Print this help message * --reference: Build a particular reference. Get a list of references by running 'puppet doc --list'. EXAMPLE ------- $ puppet doc -r type > /tmp/type_reference.markdown AUTHOR ------ Luke Kanies COPYRIGHT --------- Copyright (c) 2011 Puppet Inc., LLC Licensed under the Apache 2.0 License HELP end def handle_unknown(opt, arg) @unknown_args << { :opt => opt, :arg => arg } true end def run_command [:rdoc].include?(options[:mode]) ? send(options[:mode]) : other end def rdoc exit_code = 0 files = [] unless @manifest env = Puppet.lookup(:current_environment) files += env.modulepath files << ::File.dirname(env.manifest) if env.manifest != Puppet::Node::Environment::NO_MANIFEST end files += command_line.args Puppet.info _("scanning: %{files}") % { files: files.inspect } Puppet.settings[:document_all] = options[:all] || false begin require_relative '../../puppet/util/rdoc' if @manifest Puppet::Util::RDoc.manifestdoc(files) else options[:outputdir] = "doc" unless options[:outputdir] Puppet::Util::RDoc.rdoc(options[:outputdir], files, options[:charset]) end rescue => detail Puppet.log_exception(detail, _("Could not generate documentation: %{detail}") % { detail: detail }) exit_code = 1 end exit exit_code end def other text = ''.dup with_contents = options[:references].length <= 1 exit_code = 0 require_relative '../../puppet/util/reference' options[:references].sort_by(&:to_s).each do |name| section = Puppet::Util::Reference.reference(name) raise _("Could not find reference %{name}") % { name: name } unless section begin # Add the per-section text, but with no ToC text += section.send(options[:format], with_contents) rescue => detail Puppet.log_exception(detail, _("Could not generate reference %{name}: %{detail}") % { name: name, detail: detail }) exit_code = 1 next end end text += Puppet::Util::Reference.footer unless with_contents # We've only got one reference puts text exit exit_code end def setup # sole manifest documentation if command_line.args.size > 0 options[:mode] = :rdoc @manifest = true end if options[:mode] == :rdoc setup_rdoc else setup_reference end setup_logging end def setup_reference if options[:all] # Don't add dynamic references to the "all" list. require_relative '../../puppet/util/reference' refs = Puppet::Util::Reference.references(Puppet.lookup(:current_environment)) options[:references] = refs.reject do |ref| Puppet::Util::Reference.reference(ref).dynamic? end end options[:references] << :type if options[:references].empty? end def setup_rdoc # consume the unknown options # and feed them as settings if @unknown_args.size > 0 @unknown_args.each do |option| # force absolute path for modulepath when passed on commandline if option[:opt] == "--modulepath" option[:arg] = option[:arg].split(::File::PATH_SEPARATOR).collect { |p| ::File.expand_path(p) }.join(::File::PATH_SEPARATOR) end Puppet.settings.handlearg(option[:opt], option[:arg]) end end end def setup_logging Puppet::Util::Log.level = :warning set_log_level Puppet::Util::Log.newdestination(:console) 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/application/node.rb
lib/puppet/application/node.rb
# frozen_string_literal: true require_relative '../../puppet/application/indirection_base' class Puppet::Application::Node < Puppet::Application::IndirectionBase end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/application/ssl.rb
lib/puppet/application/ssl.rb
# frozen_string_literal: true require_relative '../../puppet/application' require_relative '../../puppet/ssl/oids' class Puppet::Application::Ssl < Puppet::Application run_mode :agent def summary _("Manage SSL keys and certificates for puppet SSL clients") end def help <<~HELP puppet-ssl(8) -- #{summary} ======== SYNOPSIS -------- Manage SSL keys and certificates for SSL clients needing to communicate with a puppet infrastructure. USAGE ----- puppet ssl <action> [-h|--help] [-v|--verbose] [-d|--debug] [--localca] [--target CERTNAME] OPTIONS ------- * --help: Print this help message. * --verbose: Print extra information. * --debug: Enable full debugging. * --localca Also clean the local CA certificate and CRL. * --target CERTNAME Clean the specified device certificate instead of this host's certificate. ACTIONS ------- * bootstrap: Perform all of the steps necessary to request and download a client certificate. If autosigning is disabled, then puppet will wait every `waitforcert` seconds for its certificate to be signed. To only attempt once and never wait, specify a time of 0. Since `waitforcert` is a Puppet setting, it can be specified as a time interval, such as 30s, 5m, 1h. * submit_request: Generate a certificate signing request (CSR) and submit it to the CA. If a private and public key pair already exist, they will be used to generate the CSR. Otherwise, a new key pair will be generated. If a CSR has already been submitted with the given `certname`, then the operation will fail. * generate_request: Generate a certificate signing request (CSR). If a private and public key pair exist, they will be used to generate the CSR. Otherwise a new key pair will be generated. * download_cert: Download a certificate for this host. If the current private key matches the downloaded certificate, then the certificate will be saved and used for subsequent requests. If there is already an existing certificate, it will be overwritten. * verify: Verify the private key and certificate are present and match, verify the certificate is issued by a trusted CA, and check revocation status. * clean: Remove the private key and certificate related files for this host. If `--localca` is specified, then also remove this host's local copy of the CA certificate(s) and CRL bundle. if `--target CERTNAME` is specified, then remove the files for the specified device on this host instead of this host. * show: Print the full-text version of this host's certificate. HELP end option('--target CERTNAME') do |arg| options[:target] = arg.to_s end option('--localca') option('--verbose', '-v') option('--debug', '-d') def initialize(command_line = Puppet::Util::CommandLine.new) super(command_line) @cert_provider = Puppet::X509::CertProvider.new @ssl_provider = Puppet::SSL::SSLProvider.new @machine = Puppet::SSL::StateMachine.new @session = Puppet.runtime[:http].create_session end def setup_logs set_log_level(options) Puppet::Util::Log.newdestination(:console) end def main if command_line.args.empty? raise Puppet::Error, _("An action must be specified.") end if options[:target] # Override the following, as per lib/puppet/application/device.rb Puppet[:certname] = options[:target] Puppet[:confdir] = File.join(Puppet[:devicedir], Puppet[:certname]) Puppet[:vardir] = File.join(Puppet[:devicedir], Puppet[:certname]) Puppet.settings.use(:main, :agent, :device) else Puppet.settings.use(:main, :agent) end Puppet::SSL::Oids.register_puppet_oids Puppet::SSL::Oids.load_custom_oid_file(Puppet[:trusted_oid_mapping_file]) certname = Puppet[:certname] action = command_line.args.first case action when 'submit_request' ssl_context = @machine.ensure_ca_certificates if submit_request(ssl_context) cert = download_cert(ssl_context) unless cert Puppet.info(_("The certificate for '%{name}' has not yet been signed") % { name: certname }) end end when 'download_cert' ssl_context = @machine.ensure_ca_certificates cert = download_cert(ssl_context) unless cert raise Puppet::Error, _("The certificate for '%{name}' has not yet been signed") % { name: certname } end when 'generate_request' generate_request(certname) when 'verify' verify(certname) when 'clean' possible_extra_args = command_line.args.drop(1) unless possible_extra_args.empty? raise Puppet::Error, _(<<~END) % { args: possible_extra_args.join(' ') } Extra arguments detected: %{args} Did you mean to run: puppetserver ca clean --certname <name> Or: puppet ssl clean --target <name> END end clean(certname) when 'bootstrap' unless Puppet::Util::Log.sendlevel?(:info) Puppet::Util::Log.level = :info end @machine.ensure_client_certificate Puppet.notice(_("Completed SSL initialization")) when 'show' show(certname) else raise Puppet::Error, _("Unknown action '%{action}'") % { action: action } end end def show(certname) password = @cert_provider.load_private_key_password ssl_context = @ssl_provider.load_context(certname: certname, password: password) puts ssl_context.client_cert.to_text end def submit_request(ssl_context) key = @cert_provider.load_private_key(Puppet[:certname]) unless key key = create_key(Puppet[:certname]) @cert_provider.save_private_key(Puppet[:certname], key) end csr = @cert_provider.create_request(Puppet[:certname], key) route = create_route(ssl_context) route.put_certificate_request(Puppet[:certname], csr, ssl_context: ssl_context) @cert_provider.save_request(Puppet[:certname], csr) Puppet.notice _("Submitted certificate request for '%{name}' to %{url}") % { name: Puppet[:certname], url: route.url } rescue Puppet::HTTP::ResponseError => e if e.response.code == 400 raise Puppet::Error, _("Could not submit certificate request for '%{name}' to %{url} due to a conflict on the server") % { name: Puppet[:certname], url: route.url } else raise Puppet::Error.new(_("Failed to submit certificate request: %{message}") % { message: e.message }, e) end rescue => e raise Puppet::Error.new(_("Failed to submit certificate request: %{message}") % { message: e.message }, e) end def generate_request(certname) key = @cert_provider.load_private_key(certname) unless key key = create_key(certname) @cert_provider.save_private_key(certname, key) end csr = @cert_provider.create_request(certname, key) @cert_provider.save_request(certname, csr) Puppet.notice _("Generated certificate request in '%{path}'") % { path: @cert_provider.to_path(Puppet[:requestdir], certname) } rescue => e raise Puppet::Error.new(_("Failed to generate certificate request: %{message}") % { message: e.message }, e) end def download_cert(ssl_context) key = @cert_provider.load_private_key(Puppet[:certname]) # try to download cert route = create_route(ssl_context) Puppet.info _("Downloading certificate '%{name}' from %{url}") % { name: Puppet[:certname], url: route.url } _, x509 = route.get_certificate(Puppet[:certname], ssl_context: ssl_context) cert = OpenSSL::X509::Certificate.new(x509) Puppet.notice _("Downloaded certificate '%{name}' with fingerprint %{fingerprint}") % { name: Puppet[:certname], fingerprint: fingerprint(cert) } # verify client cert before saving @ssl_provider.create_context( cacerts: ssl_context.cacerts, crls: ssl_context.crls, private_key: key, client_cert: cert ) @cert_provider.save_client_cert(Puppet[:certname], cert) @cert_provider.delete_request(Puppet[:certname]) cert rescue Puppet::HTTP::ResponseError => e if e.response.code == 404 nil else raise Puppet::Error.new(_("Failed to download certificate: %{message}") % { message: e.message }, e) end rescue => e raise Puppet::Error.new(_("Failed to download certificate: %{message}") % { message: e.message }, e) end def verify(certname) password = @cert_provider.load_private_key_password ssl_context = @ssl_provider.load_context(certname: certname, password: password) # print from root to client ssl_context.client_chain.reverse.each_with_index do |cert, i| digest = Puppet::SSL::Digest.new('SHA256', cert.to_der) if i == ssl_context.client_chain.length - 1 Puppet.notice("Verified client certificate '#{cert.subject.to_utf8}' fingerprint #{digest}") else Puppet.notice("Verified CA certificate '#{cert.subject.to_utf8}' fingerprint #{digest}") end end end def clean(certname) # make sure cert has been removed from the CA if certname == Puppet[:ca_server] cert = nil begin ssl_context = @machine.ensure_ca_certificates route = create_route(ssl_context) _, cert = route.get_certificate(certname, ssl_context: ssl_context) rescue Puppet::HTTP::ResponseError => e if e.response.code.to_i != 404 raise Puppet::Error.new(_("Failed to connect to the CA to determine if certificate %{certname} has been cleaned") % { certname: certname }, e) end rescue => e raise Puppet::Error.new(_("Failed to connect to the CA to determine if certificate %{certname} has been cleaned") % { certname: certname }, e) end if cert raise Puppet::Error, _(<<~END) % { certname: certname } The certificate %{certname} must be cleaned from the CA first. To fix this, run the following commands on the CA: puppetserver ca clean --certname %{certname} puppet ssl clean END end end paths = { 'private key' => Puppet[:hostprivkey], 'public key' => Puppet[:hostpubkey], 'certificate request' => Puppet[:hostcsr], 'certificate' => Puppet[:hostcert], 'private key password file' => Puppet[:passfile] } if options[:localca] paths['local CA certificate'] = Puppet[:localcacert] paths['local CRL'] = Puppet[:hostcrl] end paths.each_pair do |label, path| if Puppet::FileSystem.exist?(path) Puppet::FileSystem.unlink(path) Puppet.notice _("Removed %{label} %{path}") % { label: label, path: path } end end end private def fingerprint(cert) Puppet::SSL::Digest.new(nil, cert.to_der) end def create_route(ssl_context) @session.route_to(:ca, ssl_context: ssl_context) end def create_key(certname) if Puppet[:key_type] == 'ec' Puppet.info _("Creating a new EC SSL key for %{name} using curve %{curve}") % { name: certname, curve: Puppet[:named_curve] } OpenSSL::PKey::EC.generate(Puppet[:named_curve]) else Puppet.info _("Creating a new SSL key for %{name}") % { name: certname } OpenSSL::PKey::RSA.new(Puppet[:keylength].to_i) 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/application/plugin.rb
lib/puppet/application/plugin.rb
# frozen_string_literal: true require_relative '../../puppet/application/face_base' class Puppet::Application::Plugin < Puppet::Application::FaceBase environment_mode :not_required end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/application/parser.rb
lib/puppet/application/parser.rb
# frozen_string_literal: true require_relative '../../puppet/application/face_base' require_relative '../../puppet/face' class Puppet::Application::Parser < Puppet::Application::FaceBase end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/application/indirection_base.rb
lib/puppet/application/indirection_base.rb
# frozen_string_literal: true require_relative '../../puppet/application/face_base' class Puppet::Application::IndirectionBase < Puppet::Application::FaceBase end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/application/catalog.rb
lib/puppet/application/catalog.rb
# frozen_string_literal: true require_relative '../../puppet/application/indirection_base' class Puppet::Application::Catalog < Puppet::Application::IndirectionBase end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/application/epp.rb
lib/puppet/application/epp.rb
# frozen_string_literal: true require_relative '../../puppet/application/face_base' require_relative '../../puppet/face' class Puppet::Application::Epp < Puppet::Application::FaceBase end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/application/help.rb
lib/puppet/application/help.rb
# frozen_string_literal: true require_relative '../../puppet/application/face_base' class Puppet::Application::Help < Puppet::Application::FaceBase environment_mode :not_required end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/application/facts.rb
lib/puppet/application/facts.rb
# frozen_string_literal: true require_relative '../../puppet/application/indirection_base' class Puppet::Application::Facts < Puppet::Application::IndirectionBase # Allows `puppet facts` actions to be run against environments that # don't exist locally, such as using the `--environment` flag to make a REST # request to a specific environment on a master. There is no way to set this # behavior per-action, so it must be set for the face as a whole. environment_mode :not_required end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/application/describe.rb
lib/puppet/application/describe.rb
# frozen_string_literal: true require_relative '../../puppet/application' class Formatter def initialize(width) @width = width end def wrap(txt, opts) return "" unless txt && !txt.empty? work = (opts[:scrub] ? scrub(txt) : txt) indent = opts[:indent] || 0 textLen = @width - indent patt = Regexp.new("\\A(.{0,#{textLen}})[ \n]") prefix = " " * indent res = [] while work.length > textLen if work =~ patt res << ::Regexp.last_match(1) work.slice!(0, ::Regexp.last_match(0).length) else res << work.slice!(0, textLen) end end res << work if work.length.nonzero? prefix + res.join("\n#{prefix}") end def header(txt, sep = "-") "\n#{txt}\n" + sep * txt.size end private def scrub(text) # For text with no carriage returns, there's nothing to do. return text if text !~ /\n/ # If we can match an indentation, then just remove that same level of # indent from every line. if text =~ /^(\s+)/ indent = ::Regexp.last_match(1) text.gsub(/^#{indent}/, '') else text end end end class TypeDoc def initialize @format = Formatter.new(76) @types = {} Puppet::Type.loadall Puppet::Type.eachtype { |type| next if type.name == :component @types[type.name] = type } end def list_types puts "These are the types known to puppet:\n" @types.keys.sort_by(&:to_s).each do |name| type = @types[name] s = type.doc.gsub(/\s+/, " ") if s.empty? s = ".. no documentation .." else n = s.index(".") || s.length if n > 45 s = s[0, 45] + " ..." else s = s[0, n] end end printf "%-15s - %s\n", name, s end end def format_type(name, opts) name = name.to_sym unless @types.has_key?(name) puts "Unknown type #{name}" return end type = @types[name] puts @format.header(name.to_s, "=") puts @format.wrap(type.doc, :indent => 0, :scrub => true) + "\n\n" puts @format.header("Parameters") if opts[:parameters] format_attrs(type, [:property, :param]) else list_attrs(type, [:property, :param]) end if opts[:meta] puts @format.header("Meta Parameters") if opts[:parameters] format_attrs(type, [:meta]) else list_attrs(type, [:meta]) end end if type.providers.size > 0 puts @format.header("Providers") if opts[:providers] format_providers(type) else list_providers(type) end end end # List details about attributes def format_attrs(type, attrs) docs = {} type.allattrs.each do |name| kind = type.attrtype(name) docs[name] = type.attrclass(name).doc if attrs.include?(kind) && name != :provider end docs.sort { |a, b| a[0].to_s <=> b[0].to_s }.each { |name, doc| print "\n- **#{name}**" if type.key_attributes.include?(name) and name != :name puts " (*namevar*)" else puts "" end puts @format.wrap(doc, :indent => 4, :scrub => true) } end # List the names of attributes def list_attrs(type, attrs) params = [] type.allattrs.each do |name| kind = type.attrtype(name) params << name.to_s if attrs.include?(kind) && name != :provider end puts @format.wrap(params.sort.join(", "), :indent => 4) end def format_providers(type) type.providers.sort_by(&:to_s).each { |prov| puts "\n- **#{prov}**" puts @format.wrap(type.provider(prov).doc, :indent => 4, :scrub => true) } end def list_providers(type) list = type.providers.sort_by(&:to_s).join(", ") puts @format.wrap(list, :indent => 4) end end class Puppet::Application::Describe < Puppet::Application banner "puppet describe [options] [type]" option("--short", "-s", "Only list parameters without detail") do |_arg| options[:parameters] = false end option("--providers", "-p") option("--list", "-l") option("--meta", "-m") def summary _("Display help about resource types") end def help <<~HELP puppet-describe(8) -- #{summary} ======== SYNOPSIS -------- Prints help about Puppet resource types, providers, and metaparameters. USAGE ----- puppet describe [-h|--help] [-s|--short] [-p|--providers] [-l|--list] [-m|--meta] OPTIONS ------- * --help: Print this help text * --providers: Describe providers in detail for each type * --list: List all types * --meta: List all metaparameters * --short: List only parameters without detail EXAMPLE ------- $ puppet describe --list $ puppet describe file --providers $ puppet describe user -s -m AUTHOR ------ David Lutterkort COPYRIGHT --------- Copyright (c) 2011 Puppet Inc., LLC Licensed under the Apache 2.0 License HELP end def preinit options[:parameters] = true end def main doc = TypeDoc.new if options[:list] doc.list_types else options[:types].each { |name| doc.format_type(name, options) } end end def setup options[:types] = command_line.args.dup handle_help(nil) unless options[:list] || options[:types].size > 0 $stderr.puts "Warning: ignoring types when listing all types" if options[:list] && options[:types].size > 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/application/filebucket.rb
lib/puppet/application/filebucket.rb
# frozen_string_literal: true require_relative '../../puppet/application' class Puppet::Application::Filebucket < Puppet::Application environment_mode :not_required option("--bucket BUCKET", "-b") option("--debug", "-d") option("--fromdate FROMDATE", "-f") option("--todate TODATE", "-t") option("--local", "-l") option("--remote", "-r") option("--verbose", "-v") attr_reader :args def summary _("Store and retrieve files in a filebucket") end def digest_algorithm Puppet.default_digest_algorithm end def help <<~HELP puppet-filebucket(8) -- #{summary} ======== SYNOPSIS -------- A stand-alone Puppet filebucket client. USAGE ----- puppet filebucket <mode> [-h|--help] [-V|--version] [-d|--debug] [-v|--verbose] [-l|--local] [-r|--remote] [-s|--server <server>] [-f|--fromdate <date>] [-t|--todate <date>] [-b|--bucket <directory>] <file> <file> ... Puppet filebucket can operate in three modes, with only one mode per call: backup: Send one or more files to the specified file bucket. Each sent file is printed with its resulting #{digest_algorithm} sum. get: Return the text associated with an #{digest_algorithm} sum. The text is printed to stdout, and only one file can be retrieved at a time. restore: Given a file path and an #{digest_algorithm} sum, store the content associated with the sum into the specified file path. You can specify an entirely new path to this argument; you are not restricted to restoring the content to its original location. diff: Print a diff in unified format between two checksums in the filebucket or between a checksum and its matching file. list: List all files in the current local filebucket. Listing remote filebuckets is not allowed. DESCRIPTION ----------- This is a stand-alone filebucket client for sending files to a local or central filebucket. Note that 'filebucket' defaults to using a network-based filebucket available on the server named 'puppet'. To use this, you'll have to be running as a user with valid Puppet certificates. Alternatively, you can use your local file bucket by specifying '--local', or by specifying '--bucket' with a local path. **Important**: When you enable and use the backup option, and by extension the filebucket resource, you must ensure that sufficient disk space is available for the file backups. Generally, you can provide the disk space by using one of the following two options: - Use a `find` command and `crontab` entry to retain only the last X days of file backups. For example: ```shell find /opt/puppetlabs/server/data/puppetserver/bucket -type f -mtime +45 -atime +45 -print0 | xargs -0 rm ``` - Restrict the directory to a maximum size after which the oldest items are removed. OPTIONS ------- Note that any setting that's valid in the configuration file is also a valid long argument. For example, 'ssldir' is a valid setting, so you can specify '--ssldir <directory>' as an argument. See the configuration file documentation at https://puppet.com/docs/puppet/latest/configuration.html for the full list of acceptable parameters. A commented list of all configuration options can also be generated by running puppet with '--genconfig'. * --bucket: Specify a local filebucket path. This overrides the default path set in '$clientbucketdir'. * --debug: Enable full debugging. * --fromdate: (list only) Select bucket files from 'fromdate'. * --help: Print this help message. * --local: Use the local filebucket. This uses the default configuration information and the bucket located at the '$clientbucketdir' setting by default. If '--bucket' is set, puppet uses that path instead. * --remote: Use a remote filebucket. This uses the default configuration information and the bucket located at the '$bucketdir' setting by default. * --server_list: A list of comma separated servers; only the first entry is used for file storage. This setting takes precidence over `server`. * --server: The server to use for file storage. This setting is only used if `server_list` is not set. * --todate: (list only) Select bucket files until 'todate'. * --verbose: Print extra information. * --version: Print version information. EXAMPLES -------- ## Backup a file to the filebucket, then restore it to a temporary directory $ puppet filebucket backup /etc/passwd /etc/passwd: 429b225650b912a2ee067b0a4cf1e949 $ puppet filebucket restore /tmp/passwd 429b225650b912a2ee067b0a4cf1e949 ## Diff between two files in the filebucket $ puppet filebucket -l diff d43a6ecaa892a1962398ac9170ea9bf2 7ae322f5791217e031dc60188f4521ef 1a2 > again ## Diff between the file in the filebucket and a local file $ puppet filebucket -l diff d43a6ecaa892a1962398ac9170ea9bf2 /tmp/testFile 1a2 > again ## Backup a file to the filebucket and observe that it keeps each backup separate $ puppet filebucket -l list d43a6ecaa892a1962398ac9170ea9bf2 2015-05-11 09:27:56 /tmp/TestFile $ echo again >> /tmp/TestFile $ puppet filebucket -l backup /tmp/TestFile /tmp/TestFile: 7ae322f5791217e031dc60188f4521ef $ puppet filebucket -l list d43a6ecaa892a1962398ac9170ea9bf2 2015-05-11 09:27:56 /tmp/TestFile 7ae322f5791217e031dc60188f4521ef 2015-05-11 09:52:15 /tmp/TestFile ## List files in a filebucket within date ranges $ puppet filebucket -l -f 2015-01-01 -t 2015-01-11 list <Empty Output> $ puppet filebucket -l -f 2015-05-10 list d43a6ecaa892a1962398ac9170ea9bf2 2015-05-11 09:27:56 /tmp/TestFile 7ae322f5791217e031dc60188f4521ef 2015-05-11 09:52:15 /tmp/TestFile $ puppet filebucket -l -f "2015-05-11 09:30:00" list 7ae322f5791217e031dc60188f4521ef 2015-05-11 09:52:15 /tmp/TestFile $ puppet filebucket -l -t "2015-05-11 09:30:00" list d43a6ecaa892a1962398ac9170ea9bf2 2015-05-11 09:27:56 /tmp/TestFile ## Manage files in a specific local filebucket $ puppet filebucket -b /tmp/TestBucket backup /tmp/TestFile2 /tmp/TestFile2: d41d8cd98f00b204e9800998ecf8427e $ puppet filebucket -b /tmp/TestBucket list d41d8cd98f00b204e9800998ecf8427e 2015-05-11 09:33:22 /tmp/TestFile2 ## From a Puppet Server, list files in the server bucketdir $ puppet filebucket -b $(puppet config print bucketdir --section server) list d43a6ecaa892a1962398ac9170ea9bf2 2015-05-11 09:27:56 /tmp/TestFile 7ae322f5791217e031dc60188f4521ef 2015-05-11 09:52:15 /tmp/TestFile AUTHOR ------ Luke Kanies COPYRIGHT --------- Copyright (c) 2011 Puppet Inc., LLC Licensed under the Apache 2.0 License HELP end def run_command @args = command_line.args command = args.shift return send(command) if %w[get backup restore diff list].include? command help end def get digest = args.shift out = @client.getfile(digest) print out end def backup raise _("You must specify a file to back up") unless args.length > 0 args.each do |file| unless Puppet::FileSystem.exist?(file) $stderr.puts _("%{file}: no such file") % { file: file } next end unless FileTest.readable?(file) $stderr.puts _("%{file}: cannot read file") % { file: file } next end digest = @client.backup(file) puts "#{file}: #{digest}" end end def list fromdate = options[:fromdate] todate = options[:todate] out = @client.list(fromdate, todate) print out end def restore file = args.shift digest = args.shift @client.restore(file, digest) end def diff raise Puppet::Error, _("Need exactly two arguments: filebucket diff <file_a> <file_b>") unless args.count == 2 left = args.shift right = args.shift if Puppet::FileSystem.exist?(left) # It's a file file_a = left checksum_a = nil else file_a = nil checksum_a = left end if Puppet::FileSystem.exist?(right) # It's a file file_b = right checksum_b = nil else file_b = nil checksum_b = right end if (checksum_a || file_a) && (checksum_b || file_b) Puppet.info(_("Comparing %{checksum_a} %{checksum_b} %{file_a} %{file_b}") % { checksum_a: checksum_a, checksum_b: checksum_b, file_a: file_a, file_b: file_b }) print @client.diff(checksum_a, checksum_b, file_a, file_b) else raise Puppet::Error, _("Need exactly two arguments: filebucket diff <file_a> <file_b>") end end def setup Puppet::Log.newdestination(:console) @client = nil @server = nil Signal.trap(:INT) do $stderr.puts _("Cancelling") exit(1) end if options[:debug] Puppet::Log.level = :debug elsif options[:verbose] Puppet::Log.level = :info end exit(Puppet.settings.print_configs ? 0 : 1) if Puppet.settings.print_configs? require_relative '../../puppet/file_bucket/dipper' begin if options[:local] or options[:bucket] path = options[:bucket] || Puppet[:clientbucketdir] @client = Puppet::FileBucket::Dipper.new(:Path => path) else session = Puppet.lookup(:http_session) api = session.route_to(:puppet) @client = Puppet::FileBucket::Dipper.new(Server: api.url.host, Port: api.url.port) end rescue => detail Puppet.log_exception(detail) exit(1) 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/application/apply.rb
lib/puppet/application/apply.rb
# frozen_string_literal: true require_relative '../../puppet/application' require_relative '../../puppet/configurer' require_relative '../../puppet/util/profiler/aggregate' class Puppet::Application::Apply < Puppet::Application require_relative '../../puppet/util/splayer' include Puppet::Util::Splayer option("--debug", "-d") option("--execute EXECUTE", "-e") do |arg| options[:code] = arg end option("--loadclasses", "-L") option("--test", "-t") option("--verbose", "-v") option("--use-nodes") option("--detailed-exitcodes") option("--write-catalog-summary") do |arg| Puppet[:write_catalog_summary] = arg end option("--catalog catalog", "-c catalog") do |arg| options[:catalog] = arg end option("--logdest LOGDEST", "-l") do |arg| handle_logdest_arg(arg) end option("--parseonly") do |_args| puts "--parseonly has been removed. Please use 'puppet parser validate <manifest>'" exit 1 end def summary _("Apply Puppet manifests locally") end def help <<~HELP puppet-apply(8) -- #{summary} ======== SYNOPSIS -------- Applies a standalone Puppet manifest to the local system. USAGE ----- puppet apply [-h|--help] [-V|--version] [-d|--debug] [-v|--verbose] [-e|--execute] [--detailed-exitcodes] [-L|--loadclasses] [-l|--logdest syslog|eventlog|<ABS FILEPATH>|console] [--noop] [--catalog <catalog>] [--write-catalog-summary] <file> DESCRIPTION ----------- This is the standalone puppet execution tool; use it to apply individual manifests. When provided with a modulepath, via command line or config file, puppet apply can effectively mimic the catalog that would be served by puppet master with access to the same modules, although there are some subtle differences. When combined with scheduling and an automated system for pushing manifests, this can be used to implement a serverless Puppet site. Most users should use 'puppet agent' and 'puppet master' for site-wide manifests. OPTIONS ------- Any setting that's valid in the configuration file is a valid long argument for puppet apply. For example, 'tags' is a valid setting, so you can specify '--tags <class>,<tag>' as an argument. See the configuration file documentation at https://puppet.com/docs/puppet/latest/configuration.html for the full list of acceptable parameters. You can generate a commented list of all configuration options by running puppet with '--genconfig'. * --debug: Enable full debugging. * --detailed-exitcodes: Provide extra information about the run via exit codes. If enabled, 'puppet apply' will use the following exit codes: 0: The run succeeded with no changes or failures; the system was already in the desired state. 1: The run failed. 2: The run succeeded, and some resources were changed. 4: The run succeeded, and some resources failed. 6: The run succeeded, and included both changes and failures. * --help: Print this help message * --loadclasses: Load any stored classes. 'puppet agent' caches configured classes (usually at /etc/puppetlabs/puppet/classes.txt), and setting this option causes all of those classes to be set in your puppet manifest. * --logdest: Where to send log messages. Choose between 'syslog' (the POSIX syslog service), 'eventlog' (the Windows Event Log), 'console', or the path to a log file. Defaults to 'console'. Multiple destinations can be set using a comma separated list (eg: `/path/file1,console,/path/file2`)" A path ending with '.json' will receive structured output in JSON format. The log file will not have an ending ']' automatically written to it due to the appending nature of logging. It must be appended manually to make the content valid JSON. A path ending with '.jsonl' will receive structured output in JSON Lines format. * --noop: Use 'noop' mode where Puppet runs in a no-op or dry-run mode. This is useful for seeing what changes Puppet will make without actually executing the changes. * --execute: Execute a specific piece of Puppet code * --test: Enable the most common options used for testing. These are 'verbose', 'detailed-exitcodes' and 'show_diff'. * --verbose: Print extra information. * --catalog: Apply a JSON catalog (such as one generated with 'puppet master --compile'). You can either specify a JSON file or pipe in JSON from standard input. * --write-catalog-summary After compiling the catalog saves the resource list and classes list to the node in the state directory named classes.txt and resources.txt EXAMPLE ------- $ puppet apply -e 'notify { "hello world": }' $ puppet apply -l /tmp/manifest.log manifest.pp $ puppet apply --modulepath=/root/dev/modules -e "include ntpd::server" $ puppet apply --catalog catalog.json AUTHOR ------ Luke Kanies COPYRIGHT --------- Copyright (c) 2011 Puppet Inc., LLC Licensed under the Apache 2.0 License HELP end def app_defaults super.merge({ :default_file_terminus => :file_server, :write_catalog_summary => false }) end def run_command if options[:catalog] apply else main end ensure if @profiler Puppet::Util::Profiler.remove_profiler(@profiler) @profiler.shutdown end end def apply if options[:catalog] == "-" text = $stdin.read else text = Puppet::FileSystem.read(options[:catalog], :encoding => 'utf-8') end env = Puppet.lookup(:environments).get(Puppet[:environment]) Puppet.override(:current_environment => env, :loaders => create_loaders(env)) do catalog = read_catalog(text) apply_catalog(catalog) end end def main # rubocop:disable Layout/ExtraSpacing manifest = get_manifest() # Get either a manifest or nil if apply should use content of Puppet[:code] splay # splay if needed facts = get_facts() # facts or nil node = get_node() # node or error apply_environment = get_configured_environment(node, manifest) # rubocop:enable Layout/ExtraSpacing # TRANSLATORS "puppet apply" is a program command and should not be translated Puppet.override({ :current_environment => apply_environment, :loaders => create_loaders(apply_environment) }, _("For puppet apply")) do configure_node_facts(node, facts) # Allow users to load the classes that puppet agent creates. if options[:loadclasses] file = Puppet[:classfile] if Puppet::FileSystem.exist?(file) unless FileTest.readable?(file) $stderr.puts _("%{file} is not readable") % { file: file } exit(63) end node.classes = Puppet::FileSystem.read(file, :encoding => 'utf-8').split(/\s+/) end end begin # Compile the catalog starttime = Time.now # When compiling, the compiler traps and logs certain errors # Those that do not lead to an immediate exit are caught by the general # rule and gets logged. # catalog = begin Puppet::Resource::Catalog.indirection.find(node.name, :use_node => node) rescue Puppet::Error # already logged and handled by the compiler, including Puppet::ParseErrorWithIssue exit(1) end # Resolve all deferred values and replace them / mutate the catalog Puppet::Pops::Evaluator::DeferredResolver.resolve_and_replace(node.facts, catalog, apply_environment, Puppet[:preprocess_deferred]) # Translate it to a RAL catalog catalog = catalog.to_ral catalog.finalize catalog.retrieval_duration = Time.now - starttime # We accept either the global option `--write_catalog_summary` # corresponding to the new setting, or the application option # `--write-catalog-summary`. The latter is needed to maintain backwards # compatibility. # # Puppet settings parse global options using PuppetOptionParser, but it # only recognizes underscores, not dashes. # The base application parses app specific options using ruby's builtin # OptionParser. As of ruby 2.4, it will accept either underscores or # dashes, but prefer dashes. # # So if underscores are used, the PuppetOptionParser will parse it and # store that in Puppet[:write_catalog_summary]. If dashes are used, # OptionParser will parse it, and set Puppet[:write_catalog_summary]. In # either case, settings will contain the correct value. if Puppet[:write_catalog_summary] catalog.write_class_file catalog.write_resource_file end exit_status = apply_catalog(catalog) if !exit_status exit(1) elsif options[:detailed_exitcodes] then exit(exit_status) else exit(0) end rescue => detail Puppet.log_exception(detail) exit(1) end end end # Enable all of the most common test options. def setup_test Puppet.settings.handlearg("--no-splay") Puppet.settings.handlearg("--show_diff") options[:verbose] = true options[:detailed_exitcodes] = true end def setup setup_test if options[:test] exit(Puppet.settings.print_configs ? 0 : 1) if Puppet.settings.print_configs? handle_logdest_arg(Puppet[:logdest]) Puppet::Util::Log.newdestination(:console) unless options[:setdest] Signal.trap(:INT) do $stderr.puts _("Exiting") exit(1) end Puppet.settings.use :main, :agent, :ssl if Puppet[:catalog_cache_terminus] Puppet::Resource::Catalog.indirection.cache_class = Puppet[:catalog_cache_terminus] end # we want the last report to be persisted locally Puppet::Transaction::Report.indirection.cache_class = :yaml set_log_level if Puppet[:profile] @profiler = Puppet::Util::Profiler.add_profiler(Puppet::Util::Profiler::Aggregate.new(Puppet.method(:info), "apply")) end end private def create_loaders(env) # Ignore both 'cached_puppet_lib' and pcore resource type loaders Puppet::Pops::Loaders.new(env, false, false) end def read_catalog(text) facts = get_facts() node = get_node() configured_environment = get_configured_environment(node) # TRANSLATORS "puppet apply" is a program command and should not be translated Puppet.override({ :current_environment => configured_environment }, _("For puppet apply")) do configure_node_facts(node, facts) # NOTE: Does not set rich_data = true automatically (which would ensure always reading catalog with rich data # on (seemingly the right thing to do)), but that would remove the ability to test what happens when a # rich catalog is processed without rich_data being turned on. format = Puppet::Resource::Catalog.default_format begin catalog = Puppet::Resource::Catalog.convert_from(format, text) rescue => detail raise Puppet::Error, _("Could not deserialize catalog from %{format}: %{detail}") % { format: format, detail: detail }, detail.backtrace end # Resolve all deferred values and replace them / mutate the catalog Puppet::Pops::Evaluator::DeferredResolver.resolve_and_replace(node.facts, catalog, configured_environment, Puppet[:preprocess_deferred]) catalog.to_ral end end def apply_catalog(catalog) configurer = Puppet::Configurer.new configurer.run(:catalog => catalog, :pluginsync => false) end # Returns facts or nil # def get_facts facts = nil unless Puppet[:node_name_fact].empty? # Collect our facts. facts = Puppet::Node::Facts.indirection.find(Puppet[:node_name_value]) raise _("Could not find facts for %{node}") % { node: Puppet[:node_name_value] } unless facts Puppet[:node_name_value] = facts.values[Puppet[:node_name_fact]] facts.name = Puppet[:node_name_value] end facts end # Returns the node or raises and error if node not found. # def get_node node = Puppet::Node.indirection.find(Puppet[:node_name_value]) raise _("Could not find node %{node}") % { node: Puppet[:node_name_value] } unless node node end # Returns either a manifest (filename) or nil if apply should use content of Puppet[:code] # def get_manifest manifest = nil # Set our code or file to use. if options[:code] or command_line.args.length == 0 Puppet[:code] = options[:code] || STDIN.read else manifest = command_line.args.shift raise _("Could not find file %{manifest}") % { manifest: manifest } unless Puppet::FileSystem.exist?(manifest) Puppet.warning(_("Only one file can be applied per run. Skipping %{files}") % { files: command_line.args.join(', ') }) if command_line.args.size > 0 end manifest end # Returns a configured environment, if a manifest is given it overrides what is configured for the environment # specified by the node (or the current_environment found in the Puppet context). # The node's resolved environment is modified if needed. # def get_configured_environment(node, manifest = nil) 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 apply_environment end # Mixes the facts into the node, and mixes in server facts def configure_node_facts(node, facts) node.merge(facts.values) if facts # Add server facts so $server_facts[environment] exists when doing a puppet apply node.add_server_facts({}) 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/application/config.rb
lib/puppet/application/config.rb
# frozen_string_literal: true require_relative '../../puppet/application/face_base' class Puppet::Application::Config < Puppet::Application::FaceBase environment_mode :not_required end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/application/face_base.rb
lib/puppet/application/face_base.rb
# frozen_string_literal: true require_relative '../../puppet/application' require_relative '../../puppet/face' require 'optparse' class Puppet::Application::FaceBase < Puppet::Application option("--debug", "-d") do |_arg| set_log_level(:debug => true) end option("--verbose", "-v") do |_| set_log_level(:verbose => true) end option("--render-as FORMAT") do |format| self.render_as = format.to_sym end option("--help", "-h") do |_arg| if action && !@is_default_action # Only invoke help on the action if it was specified, not if # it was the default action. puts Puppet::Face[:help, :current].help(face.name, action.name) else puts Puppet::Face[:help, :current].help(face.name) end exit(0) end attr_reader :render_as attr_accessor :face, :action, :type, :arguments def render_as=(format) @render_as = Puppet::Network::FormatHandler.format(format) @render_as or raise ArgumentError, _("I don't know how to render '%{format}'") % { format: format } end def render(result, args_and_options) hook = action.when_rendering(render_as.name) if hook # when defining when_rendering on your action you can optionally # include arguments and options if hook.arity > 1 result = hook.call(result, *args_and_options) else result = hook.call(result) end end render_as.render(result) end def preinit super Signal.trap(:INT) do $stderr.puts _("Cancelling Face") exit(0) end end def parse_options # We need to parse enough of the command line out early, to identify what # the action is, so that we can obtain the full set of options to parse. # REVISIT: These should be configurable versions, through a global # '--version' option, but we don't implement that yet... --daniel 2011-03-29 @type = Puppet::Util::ConstantInflector.constant2file(self.class.name.to_s.sub(/.+:/, '')).to_sym @face = Puppet::Face[@type, :current] # Now, walk the command line and identify the action. We skip over # arguments based on introspecting the action and all, and find the first # non-option word to use as the action. action_name = nil index = -1 until action_name or (index += 1) >= command_line.args.length item = command_line.args[index] if item =~ /^-/ option = @face.options.find do |name| item =~ /^-+#{name.to_s.gsub(/[-_]/, '[-_]')}(?:[ =].*)?$/ end if option option = @face.get_option(option) # If we have an inline argument, just carry on. We don't need to # care about optional vs mandatory in that case because we do a real # parse later, and that will totally take care of raising the error # when we get there. --daniel 2011-04-04 if option.takes_argument? and !item.index('=') index += 1 unless option.optional_argument? and command_line.args[index + 1] =~ /^-/ end else option = find_global_settings_argument(item) if option unless Puppet.settings.boolean? option.name # As far as I can tell, we treat non-bool options as always having # a mandatory argument. --daniel 2011-04-05 # ... But, the mandatory argument will not be the next item if an = is # employed in the long form of the option. --jeffmccune 2012-09-18 index += 1 unless item =~ /^--#{option.name}=/ end else option = find_application_argument(item) if option index += 1 if option[:argument] and !(option[:optional]) else raise OptionParser::InvalidOption, item.sub(/=.*$/, '') end end end else # Stash away the requested action name for later, and try to fetch the # action object it represents; if this is an invalid action name that # will be nil, and handled later. action_name = item.to_sym @action = Puppet::Face.find_action(@face.name, action_name) @face = @action.face if @action end end if @action.nil? @action = @face.get_default_action() if @action @is_default_action = true else # First try to handle global command line options # But ignoring invalid options as this is a invalid action, and # we want the error message for that instead. begin super rescue OptionParser::InvalidOption end face = @face.name action = action_name.nil? ? 'default' : "'#{action_name}'" msg = _("'%{face}' has no %{action} action. See `puppet help %{face}`.") % { face: face, action: action } Puppet.err(msg) Puppet::Util::Log.force_flushqueue() exit false end end # Now we can interact with the default option code to build behaviour # around the full set of options we now know we support. @action.options.each do |o| o = @action.get_option(o) # make it the object. self.class.option(*o.optparse) # ...and make the CLI parse it. end # ...and invoke our parent to parse all the command line options. super end def find_global_settings_argument(item) Puppet.settings.each do |_name, object| object.optparse_args.each do |arg| next unless arg =~ /^-/ # sadly, we have to emulate some of optparse here... pattern = /^#{arg.sub('[no-]', '').sub(/[ =].*$/, '')}(?:[ =].*)?$/ pattern.match item and return object end end nil # nothing found. end def find_application_argument(item) self.class.option_parser_commands.each do |options, _function| options.each do |option| next unless option =~ /^-/ pattern = /^#{option.sub('[no-]', '').sub(/[ =].*$/, '')}(?:[ =].*)?$/ next unless pattern.match(item) return { :argument => option =~ /[ =]/, :optional => option =~ /[ =]\[/ } end end nil # not found end def setup Puppet::Util::Log.newdestination :console @arguments = command_line.args # Note: because of our definition of where the action is set, we end up # with it *always* being the first word of the remaining set of command # line arguments. So, strip that off when we construct the arguments to # pass down to the face action. --daniel 2011-04-04 # Of course, now that we have default actions, we should leave the # "action" name on if we didn't actually consume it when we found our # action. @arguments.delete_at(0) unless @is_default_action # We copy all of the app options to the end of the call; This allows each # action to read in the options. This replaces the older model where we # would invoke the action with options set as global state in the # interface object. --daniel 2011-03-28 @arguments << options # If we don't have a rendering format, set one early. self.render_as ||= @action.render_as || :console end def main status = false # Call the method associated with the provided action (e.g., 'find'). unless @action puts Puppet::Face[:help, :current].help(@face.name) raise _("%{face} does not respond to action %{arg}") % { face: face, arg: arguments.first } end # We need to do arity checking here because this is generic code # calling generic methods – that have argument defaulting. We need to # make sure we don't accidentally pass the options as the first # argument to a method that takes one argument. eg: # # puppet facts find # => options => {} # @arguments => [{}] # => @face.send :bar, {} # # def face.bar(argument, options = {}) # => bar({}, {}) # oops! we thought the options were the # # positional argument!! # # We could also fix this by making it mandatory to pass the options on # every call, but that would make the Ruby API much more annoying to # work with; having the defaulting is a much nicer convention to have. # # We could also pass the arguments implicitly, by having a magic # 'options' method that was visible in the scope of the action, which # returned the right stuff. # # That sounds attractive, but adds complications to all sorts of # things, especially when you think about how to pass options when you # are writing Ruby code that calls multiple faces. Especially if # faces are involved in that. ;) # # --daniel 2011-04-27 if (arity = @action.positional_arg_count) > 0 unless (count = arguments.length) == arity then raise ArgumentError, n_("puppet %{face} %{action} takes %{arg_count} argument, but you gave %{given_count}", "puppet %{face} %{action} takes %{arg_count} arguments, but you gave %{given_count}", arity - 1) % { face: @face.name, action: @action.name, arg_count: arity - 1, given_count: count - 1 } end end if @face.deprecated? Puppet.deprecation_warning(_("'puppet %{face}' is deprecated and will be removed in a future release") % { face: @face.name }) end result = @face.send(@action.name, *arguments) puts render(result, arguments) unless result.nil? status = true # We need an easy way for the action to set a specific exit code, so we # rescue SystemExit here; This allows each action to set the desired exit # code by simply calling Kernel::exit. eg: # # exit(2) # # --kelsey 2012-02-14 rescue SystemExit => detail status = detail.status rescue => detail Puppet.log_exception(detail) Puppet.err _("Try 'puppet help %{face} %{action}' for usage") % { face: @face.name, action: @action.name } ensure exit 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/application/module.rb
lib/puppet/application/module.rb
# frozen_string_literal: true require_relative '../../puppet/application/face_base' class Puppet::Application::Module < Puppet::Application::FaceBase end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/application/lookup.rb
lib/puppet/application/lookup.rb
# frozen_string_literal: true require_relative '../../puppet/application' require_relative '../../puppet/pops' require_relative '../../puppet/node' require_relative '../../puppet/node/server_facts' require_relative '../../puppet/parser/compiler' class Puppet::Application::Lookup < Puppet::Application RUN_HELP = _("Run 'puppet lookup --help' for more details").freeze DEEP_MERGE_OPTIONS = '--knock-out-prefix, --sort-merged-arrays, and --merge-hash-arrays' TRUSTED_INFORMATION_FACTS = %w[hostname domain fqdn clientcert].freeze run_mode :server # Options for lookup option('--merge TYPE') do |arg| options[:merge] = arg end option('--debug', '-d') option('--verbose', '-v') option('--render-as FORMAT') do |format| options[:render_as] = format.downcase.to_sym end option('--type TYPE_STRING') do |arg| options[:type] = arg end option('--compile', '-c') option('--knock-out-prefix PREFIX_STRING') do |arg| options[:prefix] = arg end option('--sort-merged-arrays') option('--merge-hash-arrays') option('--explain') option('--explain-options') option('--default VALUE') do |arg| options[:default_value] = arg end # not yet supported option('--trusted') # Options for facts/scope option('--node NODE_NAME') do |arg| options[:node] = arg end option('--facts FACT_FILE') do |arg| options[:fact_file] = arg end def app_defaults super.merge({ :facts_terminus => 'yaml' }) end def setup_logs # This sets up logging based on --debug or --verbose if they are set in `options` set_log_level # This uses console for everything that is not a compilation Puppet::Util::Log.newdestination(:console) end def setup_terminuses require_relative '../../puppet/file_serving/content' require_relative '../../puppet/file_serving/metadata' Puppet::FileServing::Content.indirection.terminus_class = :file_server Puppet::FileServing::Metadata.indirection.terminus_class = :file_server Puppet::FileBucket::File.indirection.terminus_class = :file end def setup setup_logs exit(Puppet.settings.print_configs ? 0 : 1) if Puppet.settings.print_configs? if options[:node] Puppet::Util.skip_external_facts do Puppet.settings.use :main, :server, :ssl, :metrics end else Puppet.settings.use :main, :server, :ssl, :metrics end setup_terminuses end def summary _("Interactive Hiera lookup") end def help <<~HELP puppet-lookup(8) -- #{summary} ======== SYNOPSIS -------- Does Hiera lookups from the command line. Since this command needs access to your Hiera data, make sure to run it on a node that has a copy of that data. This usually means logging into a Puppet Server node and running 'puppet lookup' with sudo. The most common version of this command is: 'puppet lookup <KEY> --node <NAME> --environment <ENV> --explain' USAGE ----- puppet lookup [--help] [--type <TYPESTRING>] [--merge first|unique|hash|deep] [--knock-out-prefix <PREFIX-STRING>] [--sort-merged-arrays] [--merge-hash-arrays] [--explain] [--environment <ENV>] [--default <VALUE>] [--node <NODE-NAME>] [--facts <FILE>] [--compile] [--render-as s|json|yaml|binary|msgpack] <keys> DESCRIPTION ----------- The lookup command is a CLI for Puppet's 'lookup()' function. It searches your Hiera data and returns a value for the requested lookup key, so you can test and explore your data. It is a modern replacement for the 'hiera' command. Lookup uses the setting for global hiera.yaml from puppet's config, and the environment to find the environment level hiera.yaml as well as the resulting modulepath for the environment (for hiera.yaml files in modules). Hiera usually relies on a node's facts to locate the relevant data sources. By default, 'puppet lookup' uses facts from the node you run the command on, but you can get data for any other node with the '--node <NAME>' option. If possible, the lookup command will use the requested node's real stored facts from PuppetDB; if PuppetDB isn't configured or you want to provide arbitrary fact values, you can pass alternate facts as a JSON or YAML file with '--facts <FILE>'. If you're debugging your Hiera data and want to see where values are coming from, use the '--explain' option. If '--explain' isn't specified, lookup exits with 0 if a value was found and 1 otherwise. With '--explain', lookup always exits with 0 unless there is a major error. You can provide multiple lookup keys to this command, but it only returns a value for the first found key, omitting the rest. For more details about how Hiera works, see the Hiera documentation: https://puppet.com/docs/puppet/latest/hiera_intro.html OPTIONS ------- * --help: Print this help message. * --explain Explain the details of how the lookup was performed and where the final value came from (or the reason no value was found). * --node <NODE-NAME> Specify which node to look up data for; defaults to the node where the command is run. Since Hiera's purpose is to provide different values for different nodes (usually based on their facts), you'll usually want to use some specific node's facts to explore your data. If the node where you're running this command is configured to talk to PuppetDB, the command will use the requested node's most recent facts. Otherwise, you can override facts with the '--facts' option. * --facts <FILE> Specify a .json or .yaml file of key => value mappings to override the facts for this lookup. Any facts not specified in this file maintain their original value. * --environment <ENV> Like with most Puppet commands, you can specify an environment on the command line. This is important for lookup because different environments can have different Hiera data. This environment will be always be the one used regardless of any other factors. * --merge first|unique|hash|deep: Specify the merge behavior, overriding any merge behavior from the data's lookup_options. 'first' returns the first value found. 'unique' appends everything to a merged, deduplicated array. 'hash' performs a simple hash merge by overwriting keys of lower lookup priority. 'deep' performs a deep merge on values of Array and Hash type. There are additional options that can be used with 'deep'. * --knock-out-prefix <PREFIX-STRING> Can be used with the 'deep' merge strategy. Specifies a prefix to indicate a value should be removed from the final result. * --sort-merged-arrays Can be used with the 'deep' merge strategy. When this flag is used, all merged arrays are sorted. * --merge-hash-arrays Can be used with the 'deep' merge strategy. When this flag is used, hashes WITHIN arrays are deep-merged with their counterparts by position. * --explain-options Explain whether a lookup_options hash affects this lookup, and how that hash was assembled. (lookup_options is how Hiera configures merge behavior in data.) * --default <VALUE> A value to return if Hiera can't find a value in data. For emulating calls to the 'lookup()' function that include a default. * --type <TYPESTRING>: Assert that the value has the specified type. For emulating calls to the 'lookup()' function that include a data type. * --compile Perform a full catalog compilation prior to the lookup. If your hierarchy and data only use the $facts, $trusted, and $server_facts variables, you don't need this option; however, if your Hiera configuration uses arbitrary variables set by a Puppet manifest, you might need this option to get accurate data. No catalog compilation takes place unless this flag is given. * --render-as s|json|yaml|binary|msgpack Specify the output format of the results; "s" means plain text. The default when producing a value is yaml and the default when producing an explanation is s. EXAMPLE ------- To look up 'key_name' using the Puppet Server node's facts: $ puppet lookup key_name To look up 'key_name' using the Puppet Server node's arbitrary variables from a manifest, and classify the node if applicable: $ puppet lookup key_name --compile To look up 'key_name' using the Puppet Server node's facts, overridden by facts given in a file: $ puppet lookup key_name --facts fact_file.yaml To look up 'key_name' with agent.local's facts: $ puppet lookup --node agent.local key_name To get the first value found for 'key_name_one' and 'key_name_two' with agent.local's facts while merging values and knocking out the prefix 'foo' while merging: $ puppet lookup --node agent.local --merge deep --knock-out-prefix foo key_name_one key_name_two To lookup 'key_name' with agent.local's facts, and return a default value of 'bar' if nothing was found: $ puppet lookup --node agent.local --default bar key_name To see an explanation of how the value for 'key_name' would be found, using agent.local's facts: $ puppet lookup --node agent.local --explain key_name COPYRIGHT --------- Copyright (c) 2015 Puppet Inc., LLC Licensed under the Apache 2.0 License HELP end def main keys = command_line.args if (options[:sort_merged_arrays] || options[:merge_hash_arrays] || options[:prefix]) && options[:merge] != 'deep' raise _("The options %{deep_merge_opts} are only available with '--merge deep'\n%{run_help}") % { deep_merge_opts: DEEP_MERGE_OPTIONS, run_help: RUN_HELP } end use_default_value = !options[:default_value].nil? merge_options = nil merge = options[:merge] unless merge.nil? strategies = Puppet::Pops::MergeStrategy.strategy_keys unless strategies.include?(merge.to_sym) strategies = strategies.map { |k| "'#{k}'" } raise _("The --merge option only accepts %{strategies}, or %{last_strategy}\n%{run_help}") % { strategies: strategies[0...-1].join(', '), last_strategy: strategies.last, run_help: RUN_HELP } end if merge == 'deep' merge_options = { 'strategy' => 'deep', 'sort_merged_arrays' => !options[:sort_merged_arrays].nil?, 'merge_hash_arrays' => !options[:merge_hash_arrays].nil? } if options[:prefix] merge_options['knockout_prefix'] = options[:prefix] end else merge_options = { 'strategy' => merge } end end explain_data = !!options[:explain] explain_options = !!options[:explain_options] only_explain_options = explain_options && !explain_data if keys.empty? if only_explain_options # Explain lookup_options for lookup of an unqualified value. keys = Puppet::Pops::Lookup::GLOBAL else raise _('No keys were given to lookup.') end end explain = explain_data || explain_options # Format defaults to text (:s) when producing an explanation and :yaml when producing the value format = options[:render_as] || (explain ? :s : :yaml) renderer = Puppet::Network::FormatHandler.format(format) raise _("Unknown rendering format '%{format}'") % { format: format } if renderer.nil? generate_scope do |scope| lookup_invocation = Puppet::Pops::Lookup::Invocation.new(scope, {}, {}, explain ? Puppet::Pops::Lookup::Explainer.new(explain_options, only_explain_options) : nil) begin type = options.include?(:type) ? Puppet::Pops::Types::TypeParser.singleton.parse(options[:type], scope) : nil result = Puppet::Pops::Lookup.lookup(keys, type, options[:default_value], use_default_value, merge_options, lookup_invocation) puts renderer.render(result) unless explain rescue Puppet::DataBinding::LookupError => e lookup_invocation.report_text { e.message } exit(1) unless explain end puts format == :s ? lookup_invocation.explainer.explain : renderer.render(lookup_invocation.explainer.to_hash) if explain end exit(0) end def generate_scope if options[:node] node = options[:node] else node = Puppet[:node_name_value] # If we want to lookup the node we are currently on # we must returning these settings to their default values Puppet.settings[:facts_terminus] = 'facter' end fact_file = options[:fact_file] if fact_file if fact_file.end_with?('.json') given_facts = Puppet::Util::Json.load_file(fact_file) elsif fact_file.end_with?('.yml', '.yaml') given_facts = Puppet::Util::Yaml.safe_load_file(fact_file) else given_facts = Puppet::Util::Json.load_file_if_valid(fact_file) given_facts ||= Puppet::Util::Yaml.safe_load_file_if_valid(fact_file) end unless given_facts.instance_of?(Hash) raise _("Incorrectly formatted data in %{fact_file} given via the --facts flag (only accepts yaml and json files)") % { fact_file: fact_file } end if TRUSTED_INFORMATION_FACTS.any? { |key| given_facts.key? key } unless TRUSTED_INFORMATION_FACTS.all? { |key| given_facts.key? key } raise _("When overriding any of the %{trusted_facts_list} facts with %{fact_file} "\ "given via the --facts flag, they must all be overridden.") % { fact_file: fact_file, trusted_facts_list: TRUSTED_INFORMATION_FACTS.join(',') } end end end if node.is_a?(Puppet::Node) node.add_extra_facts(given_facts) if given_facts else # to allow unit tests to pass a node instance facts = retrieve_node_facts(node, given_facts) ni = Puppet::Node.indirection tc = ni.terminus_class if options[:compile] if tc == :plain node = ni.find(node, facts: facts, environment: Puppet[:environment]) else begin service = Puppet.runtime[:http] session = service.create_session cert = session.route_to(:ca) _, x509 = cert.get_certificate(node) cert = OpenSSL::X509::Certificate.new(x509) Puppet::SSL::Oids.register_puppet_oids trusted = Puppet::Context::TrustedInformation.remote(true, facts.values['certname'] || node, Puppet::SSL::Certificate.from_instance(cert)) Puppet.override(trusted_information: trusted) do node = ni.find(node, facts: facts, environment: Puppet[:environment]) end rescue Puppet.warning _("CA is not available, the operation will continue without using trusted facts.") node = ni.find(node, facts: facts, environment: Puppet[:environment]) end end else ni.terminus_class = :plain node = ni.find(node, facts: facts, environment: Puppet[:environment]) ni.terminus_class = tc end end node.environment = Puppet[:environment] if Puppet.settings.set_by_cli?(:environment) node.add_server_facts(Puppet::Node::ServerFacts.load) Puppet[:code] = 'undef' unless options[:compile] compiler = Puppet::Parser::Compiler.new(node) if options[:node] Puppet::Util.skip_external_facts do compiler.compile { |catalog| yield(compiler.topscope); catalog } end else compiler.compile { |catalog| yield(compiler.topscope); catalog } end end def retrieve_node_facts(node, given_facts) facts = Puppet::Node::Facts.indirection.find(node, :environment => Puppet.lookup(:current_environment)) facts = Puppet::Node::Facts.new(node, {}) if facts.nil? facts.add_extra_values(given_facts) if given_facts if facts.values.empty? raise _("No facts available for target node: %{node}") % { node: node } end facts 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/application/device.rb
lib/puppet/application/device.rb
# frozen_string_literal: true require_relative '../../puppet/application' require_relative '../../puppet/configurer' require_relative '../../puppet/util/network_device' require_relative '../../puppet/ssl/oids' class Puppet::Application::Device < Puppet::Application run_mode :agent attr_accessor :args, :agent, :host def app_defaults super.merge({ :catalog_terminus => :rest, :catalog_cache_terminus => :json, :node_terminus => :rest, :facts_terminus => :network_device, }) end def preinit # Do an initial trap, so that cancels don't get a stack trace. Signal.trap(:INT) do $stderr.puts _("Cancelling startup") exit(0) end { :apply => nil, :waitforcert => nil, :detailed_exitcodes => false, :verbose => false, :debug => false, :centrallogs => false, :setdest => false, :resource => false, :facts => false, :target => nil, :to_yaml => false, }.each do |opt, val| options[opt] = val end @args = {} end option("--centrallogging") option("--debug", "-d") option("--resource", "-r") option("--facts", "-f") option("--to_yaml", "-y") option("--verbose", "-v") option("--detailed-exitcodes") do |_arg| options[:detailed_exitcodes] = true end option("--libdir LIBDIR") do |arg| options[:libdir] = arg end option("--apply MANIFEST") do |arg| options[:apply] = arg.to_s end option("--logdest DEST", "-l DEST") do |arg| handle_logdest_arg(arg) end option("--waitforcert WAITFORCERT", "-w") do |arg| options[:waitforcert] = arg.to_i end option("--port PORT", "-p") do |arg| @args[:Port] = arg end option("--target DEVICE", "-t") do |arg| options[:target] = arg.to_s end def summary _("Manage remote network devices") end def help <<~HELP puppet-device(8) -- #{summary} ======== SYNOPSIS -------- Retrieves catalogs from the Puppet master and applies them to remote devices. This subcommand can be run manually; or periodically using cron, a scheduled task, or a similar tool. USAGE ----- puppet device [-h|--help] [-v|--verbose] [-d|--debug] [-l|--logdest syslog|<file>|console] [--detailed-exitcodes] [--deviceconfig <file>] [-w|--waitforcert <seconds>] [--libdir <directory>] [-a|--apply <file>] [-f|--facts] [-r|--resource <type> [name]] [-t|--target <device>] [--user=<user>] [-V|--version] DESCRIPTION ----------- Devices require a proxy Puppet agent to request certificates, collect facts, retrieve and apply catalogs, and store reports. USAGE NOTES ----------- Devices managed by the puppet-device subcommand on a Puppet agent are configured in device.conf, which is located at $confdir/device.conf by default, and is configurable with the $deviceconfig setting. The device.conf file is an INI-like file, with one section per device: [<DEVICE_CERTNAME>] type <TYPE> url <URL> debug The section name specifies the certname of the device. The values for the type and url properties are specific to each type of device. The optional debug property specifies transport-level debugging, and is limited to telnet and ssh transports. See https://puppet.com/docs/puppet/latest/config_file_device.html for details. OPTIONS ------- Note that any setting that's valid in the configuration file is also a valid long argument. For example, 'server' is a valid configuration parameter, so you can specify '--server <servername>' as an argument. * --help, -h: Print this help message * --verbose, -v: Turn on verbose reporting. * --debug, -d: Enable full debugging. * --logdest, -l: Where to send log messages. Choose between 'syslog' (the POSIX syslog service), 'console', or the path to a log file. If debugging or verbosity is enabled, this defaults to 'console'. Otherwise, it defaults to 'syslog'. Multiple destinations can be set using a comma separated list (eg: `/path/file1,console,/path/file2`)" A path ending with '.json' will receive structured output in JSON format. The log file will not have an ending ']' automatically written to it due to the appending nature of logging. It must be appended manually to make the content valid JSON. * --detailed-exitcodes: Provide transaction information via exit codes. If this is enabled, an exit code of '1' means at least one device had a compile failure, an exit code of '2' means at least one device had resource changes, and an exit code of '4' means at least one device had resource failures. Exit codes of '3', '5', '6', or '7' means that a bitwise combination of the preceding exit codes happened. * --deviceconfig: Path to the device config file for puppet device. Default: $confdir/device.conf * --waitforcert, -w: This option only matters for targets that do not yet have certificates and it is enabled by default, with a value of 120 (seconds). This causes +puppet device+ to poll the server every 2 minutes and ask it to sign a certificate request. This is useful for the initial setup of a target. You can turn off waiting for certificates by specifying a time of 0. * --libdir: Override the per-device libdir with a local directory. Specifying a libdir also disables pluginsync. This is useful for testing. A path ending with '.jsonl' will receive structured output in JSON Lines format. * --apply: Apply a manifest against a remote target. Target must be specified. * --facts: Displays the facts of a remote target. Target must be specified. * --resource: Displays a resource state as Puppet code, roughly equivalent to `puppet resource`. Can be filtered by title. Requires --target be specified. * --target: Target a specific device/certificate in the device.conf. Doing so will perform a device run against only that device/certificate. * --to_yaml: Output found resources in yaml format, suitable to use with Hiera and create_resources. * --user: The user to run as. EXAMPLE ------- $ puppet device --target remotehost --verbose AUTHOR ------ Brice Figureau COPYRIGHT --------- Copyright (c) 2011-2018 Puppet Inc., LLC Licensed under the Apache 2.0 License HELP end def main if options[:resource] and !options[:target] raise _("resource command requires target") end if options[:facts] and !options[:target] raise _("facts command requires target") end unless options[:apply].nil? raise _("missing argument: --target is required when using --apply") if options[:target].nil? raise _("%{file} does not exist, cannot apply") % { file: options[:apply] } unless File.file?(options[:apply]) end libdir = Puppet[:libdir] vardir = Puppet[:vardir] confdir = Puppet[:confdir] ssldir = Puppet[:ssldir] certname = Puppet[:certname] env = Puppet::Node::Environment.remote(Puppet[:environment]) returns = Puppet.override(:current_environment => env, :loaders => Puppet::Pops::Loaders.new(env)) do # find device list require_relative '../../puppet/util/network_device/config' devices = Puppet::Util::NetworkDevice::Config.devices.dup if options[:target] devices.select! { |key, _value| key == options[:target] } end if devices.empty? if options[:target] raise _("Target device / certificate '%{target}' not found in %{config}") % { target: options[:target], config: Puppet[:deviceconfig] } else Puppet.err _("No device found in %{config}") % { config: Puppet[:deviceconfig] } exit(1) end end devices.collect do |_devicename, device| # TODO when we drop support for ruby < 2.5 we can remove the extra block here device_url = URI.parse(device.url) # Handle nil scheme & port scheme = "#{device_url.scheme}://" if device_url.scheme port = ":#{device_url.port}" if device_url.port # override local $vardir and $certname Puppet[:ssldir] = ::File.join(Puppet[:deviceconfdir], device.name, 'ssl') Puppet[:confdir] = ::File.join(Puppet[:devicedir], device.name) Puppet[:libdir] = options[:libdir] || ::File.join(Puppet[:devicedir], device.name, 'lib') Puppet[:vardir] = ::File.join(Puppet[:devicedir], device.name) Puppet[:certname] = device.name ssl_context = nil # create device directory under $deviceconfdir Puppet::FileSystem.dir_mkpath(Puppet[:ssldir]) unless Puppet::FileSystem.dir_exist?(Puppet[:ssldir]) # this will reload and recompute default settings and create device-specific sub vardir Puppet.settings.use :main, :agent, :ssl # Workaround for PUP-8736: store ssl certs outside the cache directory to prevent accidental removal and keep the old path as symlink optssldir = File.join(Puppet[:confdir], 'ssl') Puppet::FileSystem.symlink(Puppet[:ssldir], optssldir) unless Puppet::FileSystem.exist?(optssldir) unless options[:resource] || options[:facts] || options[:apply] # Since it's too complicated to fix properly in the default settings, we workaround for PUP-9642 here. # See https://github.com/puppetlabs/puppet/pull/7483#issuecomment-483455997 for details. # This has to happen after `settings.use` above, so the directory is created and before `setup_host` below, where the SSL # routines would fail with access errors if Puppet.features.root? && !Puppet::Util::Platform.windows? user = Puppet::Type.type(:user).new(name: Puppet[:user]).exists? ? Puppet[:user] : nil group = Puppet::Type.type(:group).new(name: Puppet[:group]).exists? ? Puppet[:group] : nil Puppet.debug("Fixing perms for #{user}:#{group} on #{Puppet[:confdir]}") FileUtils.chown(user, group, Puppet[:confdir]) if user || group end ssl_context = setup_context unless options[:libdir] Puppet.override(ssl_context: ssl_context) do Puppet::Configurer::PluginHandler.new.download_plugins(env) if Puppet::Configurer.should_pluginsync? end end end # this inits the device singleton, so that the facts terminus # and the various network_device provider can use it Puppet::Util::NetworkDevice.init(device) if options[:resource] type, name = parse_args(command_line.args) Puppet.info _("retrieving resource: %{resource} from %{target} at %{scheme}%{url_host}%{port}%{url_path}") % { resource: type, target: device.name, scheme: scheme, url_host: device_url.host, port: port, url_path: device_url.path } resources = find_resources(type, name) if options[:to_yaml] data = resources.map do |resource| resource.prune_parameters(:parameters_to_include => @extra_params).to_hiera_hash end.inject(:merge!) text = YAML.dump(type.downcase => data) else text = resources.map do |resource| resource.prune_parameters(:parameters_to_include => @extra_params).to_manifest.force_encoding(Encoding.default_external) end.join("\n") end (puts text) 0 elsif options[:facts] Puppet.info _("retrieving facts from %{target} at %{scheme}%{url_host}%{port}%{url_path}") % { resource: type, target: device.name, scheme: scheme, url_host: device_url.host, port: port, url_path: device_url.path } remote_facts = Puppet::Node::Facts.indirection.find(name, :environment => env) # Give a proper name to the facts remote_facts.name = remote_facts.values['clientcert'] renderer = Puppet::Network::FormatHandler.format(:console) puts renderer.render(remote_facts) 0 elsif options[:apply] # avoid reporting to server Puppet::Transaction::Report.indirection.terminus_class = :yaml Puppet::Resource::Catalog.indirection.cache_class = nil require_relative '../../puppet/application/apply' begin Puppet[:node_terminus] = :plain Puppet[:catalog_terminus] = :compiler Puppet[:catalog_cache_terminus] = nil Puppet[:facts_terminus] = :network_device Puppet.override(:network_device => true) do Puppet::Application::Apply.new(Puppet::Util::CommandLine.new('puppet', ["apply", options[:apply]])).run_command end end else Puppet.info _("starting applying configuration to %{target} at %{scheme}%{url_host}%{port}%{url_path}") % { target: device.name, scheme: scheme, url_host: device_url.host, port: port, url_path: device_url.path } overrides = {} overrides[:ssl_context] = ssl_context if ssl_context Puppet.override(overrides) do configurer = Puppet::Configurer.new configurer.run(:network_device => true, :pluginsync => false) end end rescue => detail Puppet.log_exception(detail) # If we rescued an error, then we return 1 as the exit code 1 ensure Puppet[:libdir] = libdir Puppet[:vardir] = vardir Puppet[:confdir] = confdir Puppet[:ssldir] = ssldir Puppet[:certname] = certname end end if !returns or returns.compact.empty? exit(1) elsif options[:detailed_exitcodes] # Bitwise OR the return codes together, puppet style exit(returns.compact.reduce(:|)) elsif returns.include? 1 exit(1) else exit(0) end end def parse_args(args) type = args.shift or raise _("You must specify the type to display") Puppet::Type.type(type) or raise _("Could not find type %{type}") % { type: type } name = args.shift [type, name] end def find_resources(type, name) key = [type, name].join('/') if name [Puppet::Resource.indirection.find(key)] else Puppet::Resource.indirection.search(key, {}) end end def setup_context waitforcert = options[:waitforcert] || (Puppet[:onetime] ? 0 : Puppet[:waitforcert]) sm = Puppet::SSL::StateMachine.new(waitforcert: waitforcert) sm.ensure_client_certificate end def setup setup_logs Puppet::SSL::Oids.register_puppet_oids # setup global device-specific defaults; creates all necessary directories, etc Puppet.settings.use :main, :agent, :device, :ssl if options[:apply] || options[:facts] || options[:resource] Puppet::Util::Log.newdestination(:console) else args[:Server] = Puppet[:server] if options[:centrallogs] logdest = args[:Server] logdest += ":" + args[:Port] if args.include?(:Port) Puppet::Util::Log.newdestination(logdest) end Puppet::Transaction::Report.indirection.terminus_class = :rest if Puppet[:catalog_cache_terminus] Puppet::Resource::Catalog.indirection.cache_class = Puppet[:catalog_cache_terminus].intern 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/concurrent/thread_local_singleton.rb
lib/puppet/concurrent/thread_local_singleton.rb
# frozen_string_literal: true module Puppet module Concurrent module ThreadLocalSingleton def singleton key = (name + ".singleton").intern thread = Thread.current value = thread.thread_variable_get(key) if value.nil? value = new thread.thread_variable_set(key, value) end value 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/concurrent/synchronized.rb
lib/puppet/concurrent/synchronized.rb
# frozen_string_literal: true module Puppet module Concurrent # Including Puppet::Concurrent::Synchronized into a class when running on JRuby # causes all of its instance methods to be synchronized on the instance itself. # When running on MRI it has no effect. if RUBY_PLATFORM == 'java' require 'jruby/synchronized' Synchronized = JRuby::Synchronized else module Synchronized; 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/concurrent/lock.rb
lib/puppet/concurrent/lock.rb
# frozen_string_literal: true require_relative '../../puppet/concurrent/synchronized' module Puppet module Concurrent # A simple lock that at the moment only does any locking on jruby class Lock include Puppet::Concurrent::Synchronized def synchronize yield 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/scheduler/scheduler.rb
lib/puppet/scheduler/scheduler.rb
# frozen_string_literal: true module Puppet::Scheduler class Scheduler def initialize(timer = Puppet::Scheduler::Timer.new) @timer = timer end def run_loop(jobs) mark_start_times(jobs, @timer.now) until enabled(jobs).empty? @timer.wait_for(min_interval_to_next_run_from(jobs, @timer.now)) run_ready(jobs, @timer.now) end end private def enabled(jobs) jobs.select(&:enabled?) end def mark_start_times(jobs, start_time) jobs.each do |job| job.start_time = start_time end end def min_interval_to_next_run_from(jobs, from_time) enabled(jobs).map do |j| j.interval_to_next_from(from_time) end.min end def run_ready(jobs, at_time) enabled(jobs).each do |j| # This check intentionally happens right before each run, # instead of filtering on ready schedulers, since one may adjust # the readiness of a later one if j.ready?(at_time) j.run(at_time) end end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/scheduler/splay_job.rb
lib/puppet/scheduler/splay_job.rb
# frozen_string_literal: true module Puppet::Scheduler class SplayJob < Job attr_reader :splay, :splay_limit def initialize(run_interval, splay_limit, &block) @splay, @splay_limit = calculate_splay(splay_limit) super(run_interval, &block) end def interval_to_next_from(time) if last_run super else (start_time + splay) - time end end def ready?(time) if last_run super else start_time + splay <= time end end # Recalculates splay. # # @param splay_limit [Integer] the maximum time (in seconds) to delay before an agent's first run. # @return @splay [Integer] a random integer less than or equal to the splay limit that represents the seconds to # delay before next agent run. def splay_limit=(splay_limit) if @splay_limit != splay_limit @splay, @splay_limit = calculate_splay(splay_limit) end end private def calculate_splay(limit) [rand(limit + 1), limit] 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/scheduler/timer.rb
lib/puppet/scheduler/timer.rb
# frozen_string_literal: true module Puppet::Scheduler class Timer def wait_for(seconds) if seconds > 0 sleep(seconds) end end def now Time.now 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/scheduler/job.rb
lib/puppet/scheduler/job.rb
# frozen_string_literal: true module Puppet::Scheduler class Job attr_reader :run_interval attr_accessor :last_run attr_accessor :start_time def initialize(run_interval, &block) self.run_interval = run_interval @last_run = nil @run_proc = block @enabled = true end def run_interval=(interval) @run_interval = [interval, 0].max end def ready?(time) if @last_run @last_run + @run_interval <= time else true end end def enabled? @enabled end def enable @enabled = true end def disable @enabled = false end def interval_to_next_from(time) if ready?(time) 0 else @run_interval - (time - @last_run) end end def run(now) @last_run = now if @run_proc @run_proc.call(self) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/plugins/syntax_checkers.rb
lib/puppet/plugins/syntax_checkers.rb
# frozen_string_literal: true module Puppet::Plugins module SyntaxCheckers # The lookup **key** for the multibind containing syntax checkers used to syntax check embedded string in non # puppet DSL syntax. # @api public SYNTAX_CHECKERS_KEY = :'puppet::syntaxcheckers' # SyntaxChecker is a Puppet Extension Point for the purpose of extending Puppet with syntax checkers. # The intended use is to create a class derived from this class and then register it with the Puppet context # # Creating the Extension Class # ---------------------------- # As an example, a class for checking custom xml (aware of some custom schemes) may be authored in # say a puppet module called 'exampleorg/xmldata'. The name of the class should start with `Puppetx::<user>::<module>`, # e.g. 'Puppetx::Exampleorg::XmlData::XmlChecker" and # be located in `lib/puppetx/exampleorg/xml_data/xml_checker.rb`. The Puppet Binder will auto-load this file when it # has a binding to the class `Puppetx::Exampleorg::XmlData::XmlChecker' # The Ruby Module `Puppetx` is created by Puppet, the remaining modules should be created by the loaded logic - e.g.: # # @example Defining an XmlChecker # module Puppetx::Exampleorg # module XmlData # class XmlChecker < Puppetx::Puppetlabs::SyntaxCheckers::SyntaxChecker # def check(text, syntax_identifier, acceptor, location_hash) # # do the checking # end # end # end # end # # Implementing the check method # ----------------------------- # The implementation of the {#check} method should naturally perform syntax checking of the given text/string and # produce found issues on the given `acceptor`. These can be warnings or errors. The method should return `false` if # any warnings or errors were produced (it is up to the caller to check for error/warning conditions and report them # to the user). # # Issues are reported by calling the given `acceptor`, which takes a severity (e.g. `:error`, # or `:warning), an {Puppet::Pops::Issues::Issue} instance, and a {Puppet::Pops::Adapters::SourcePosAdapter} # (which describes details about linenumber, position, and length of the problem area). Note that the # `location_info` given to the check method holds information about the location of the string in its *container* # (e.g. the source position of a Heredoc); this information can be used if more detailed information is not # available, or combined if there are more details (relative to the start of the checked string). # # @example Reporting an issue # # create an issue with a symbolic name (that can serve as a reference to more details about the problem), # # make the name unique # issue = Puppet::Pops::Issues::issue(:EXAMPLEORG_XMLDATA_ILLEGAL_XML) { "syntax error found in xml text" } # source_pos = Puppet::Pops::Adapters::SourcePosAdapter.new() # source_pos.line = info[:line] # use this if there is no detail from the used parser # source_pos.pos = info[:pos] # use this pos if there is no detail from used parser # # # report it # acceptor.accept(Puppet::Pops::Validation::Diagnostic.new(:error, issue, info[:file], source_pos, {})) # # There is usually a cap on the number of errors/warnings that are presented to the user, this is handled by the # reporting logic, but care should be taken to not generate too many as the issues are kept in memory until # the checker returns. The acceptor may set a limit and simply ignore issues past a certain (high) number of reported # issues (this number is typically higher than the cap on issues reported to the user). # # The `syntax_identifier` # ----------------------- # The extension makes use of a syntax identifier written in mime-style. This identifier can be something simple # as 'xml', or 'json', but can also consist of several segments joined with '+' where the most specific syntax variant # is placed first. When searching for a syntax checker; say for JSON having some special traits, say 'userdata', the # author of the text may indicate this as the text having the syntax "userdata+json" - when a checker is looked up it is # first checked if there is a checker for "userdata+json", if none is found, a lookup is made for "json" (since the text # must at least be valid json). The given identifier is passed to the checker (to allow the same checker to check for # several dialects/specializations). # # Use in Puppet DSL # ----------------- # The Puppet DSL Heredoc support makes use of the syntax checker extension. A user of a # heredoc can specify the syntax in the heredoc tag, e.g.`@(END:userdata+json)`. # # # @abstract # class SyntaxChecker # Checks the text for syntax issues and reports them to the given acceptor. # This implementation is abstract, it raises {NotImplementedError} since a subclass should have implemented the # method. # # @param text [String] The text to check # @param syntax_identifier [String] The syntax identifier in mime style (e.g. 'json', 'json-patch+json', 'xml', 'myapp+xml' # @option location_info [String] :file The filename where the string originates # @option location_info [Integer] :line The line number identifying the location where the string is being used/checked # @option location_info [Integer] :position The position on the line identifying the location where the string is being used/checked # @return [Boolean] Whether the checked string had issues (warnings and/or errors) or not. # @api public # def check(text, syntax_identifier, acceptor, location_info) raise NotImplementedError, "The class #{self.class.name} should have implemented the method check()" end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/plugins/configuration.rb
lib/puppet/plugins/configuration.rb
# frozen_string_literal: true # Configures the Puppet Plugins, by registering extension points # and default implementations. # # See the respective configured services for more information. # # @api private # module Puppet::Plugins module Configuration require_relative '../../puppet/plugins/syntax_checkers' require_relative '../../puppet/syntax_checkers/base64' require_relative '../../puppet/syntax_checkers/json' require_relative '../../puppet/syntax_checkers/pp' require_relative '../../puppet/syntax_checkers/epp' def self.load_plugins # Register extensions # ------------------- { SyntaxCheckers::SYNTAX_CHECKERS_KEY => { 'json' => Puppet::SyntaxCheckers::Json.new, 'base64' => Puppet::SyntaxCheckers::Base64.new, 'pp' => Puppet::SyntaxCheckers::PP.new, 'epp' => Puppet::SyntaxCheckers::EPP.new } } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/feature/libuser.rb
lib/puppet/feature/libuser.rb
# frozen_string_literal: true require_relative '../../puppet/util/feature' require_relative '../../puppet/util/libuser' Puppet.features.add(:libuser) { File.executable?("/usr/sbin/lgroupadd") and File.executable?("/usr/sbin/luseradd") and Puppet::FileSystem.exist?(Puppet::Util::Libuser.getconf) }
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/feature/hiera_eyaml.rb
lib/puppet/feature/hiera_eyaml.rb
# frozen_string_literal: true require_relative '../../puppet/util/feature' Puppet.features.add(:hiera_eyaml, :libs => ['hiera/backend/eyaml/parser/parser'])
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/feature/eventlog.rb
lib/puppet/feature/eventlog.rb
# frozen_string_literal: true require_relative '../../puppet/util/feature' if Puppet::Util::Platform.windows? Puppet.features.add(:eventlog) end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/feature/cfpropertylist.rb
lib/puppet/feature/cfpropertylist.rb
# frozen_string_literal: true require_relative '../../puppet/util/feature' Puppet.features.add(:cfpropertylist, :libs => ['cfpropertylist'])
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/feature/msgpack.rb
lib/puppet/feature/msgpack.rb
# frozen_string_literal: true require_relative '../../puppet/util/feature' Puppet.features.add(:msgpack, :libs => ["msgpack"])
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/feature/selinux.rb
lib/puppet/feature/selinux.rb
# frozen_string_literal: true require_relative '../../puppet/util/feature' Puppet.features.add(:selinux, :libs => ["selinux"])
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/feature/ssh.rb
lib/puppet/feature/ssh.rb
# frozen_string_literal: true require_relative '../../puppet/util/feature' Puppet.features.add(:ssh, :libs => %(net/ssh))
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/feature/base.rb
lib/puppet/feature/base.rb
# frozen_string_literal: true require_relative '../../puppet/util/feature' # Add the simple features, all in one file. # Order is important as some features depend on others # We have a syslog implementation Puppet.features.add(:syslog, :libs => ["syslog"]) # We can use POSIX user functions Puppet.features.add(:posix) do require 'etc' !Etc.getpwuid(0).nil? && Puppet.features.syslog? end # We can use Microsoft Windows functions Puppet.features.add(:microsoft_windows) { Puppet::Util::Platform.windows? } raise Puppet::Error, _("Cannot determine basic system flavour") unless Puppet.features.posix? or Puppet.features.microsoft_windows? # We've got LDAP available. Puppet.features.add(:ldap, :libs => ["ldap"]) # We have the Rdoc::Usage library. Puppet.features.add(:usage, :libs => %w[rdoc/ri/ri_paths rdoc/usage]) # We have libshadow, useful for managing passwords. Puppet.features.add(:libshadow, :libs => ["shadow"]) # We're running as root. Puppet.features.add(:root) do require_relative '../../puppet/util/suidmanager' Puppet::Util::SUIDManager.root? end # We have lcs diff Puppet.features.add :diff, :libs => %w[diff/lcs diff/lcs/hunk] # We have OpenSSL Puppet.features.add(:openssl, :libs => ["openssl"]) # We have sqlite Puppet.features.add(:sqlite, :libs => ["sqlite3"]) # We have Hiera Puppet.features.add(:hiera, :libs => ["hiera"]) Puppet.features.add(:minitar, :libs => ["archive/tar/minitar"]) # We can manage symlinks Puppet.features.add(:manages_symlinks) do if !Puppet::Util::Platform.windows? true else module WindowsSymlink require 'ffi' extend FFI::Library def self.is_implemented # rubocop:disable Naming/PredicateName ffi_lib :kernel32 attach_function :CreateSymbolicLinkW, [:lpwstr, :lpwstr, :dword], :boolean true rescue LoadError Puppet.debug { "CreateSymbolicLink is not available" } false end end WindowsSymlink.is_implemented end end Puppet.features.add(:puppetserver_ca, libs: ['puppetserver/ca', 'puppetserver/ca/action/clean'])
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/feature/telnet.rb
lib/puppet/feature/telnet.rb
# frozen_string_literal: true require_relative '../../puppet/util/feature' Puppet.features.add(:telnet, :libs => %(net/telnet))
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/feature/bolt.rb
lib/puppet/feature/bolt.rb
# frozen_string_literal: true require_relative '../../puppet/util/feature' Puppet.features.add(:bolt, :libs => ['bolt'])
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/feature/pe_license.rb
lib/puppet/feature/pe_license.rb
# frozen_string_literal: true require_relative '../../puppet/util/feature' # Is the pe license library installed providing the ability to read licenses. Puppet.features.add(:pe_license, :libs => %(pe_license))
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/feature/pson.rb
lib/puppet/feature/pson.rb
# frozen_string_literal: true require_relative '../../puppet/util/feature' # PSON is deprecated, use JSON instead Puppet.features.add(:pson, :libs => ['puppet/external/pson'])
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/feature/hocon.rb
lib/puppet/feature/hocon.rb
# frozen_string_literal: true require_relative '../../puppet/util/feature' Puppet.features.add(:hocon, :libs => ['hocon'])
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/feature/zlib.rb
lib/puppet/feature/zlib.rb
# frozen_string_literal: true require_relative '../../puppet/util/feature' # We want this to load if possible, but it's not automatically # required. Puppet.features.add(:zlib, :libs => %(zlib))
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/reports/log.rb
lib/puppet/reports/log.rb
# frozen_string_literal: true require_relative '../../puppet/reports' Puppet::Reports.register_report(:log) do desc "Send all received logs to the local log destinations. Usually the log destination is syslog." def process logs.each do |log| log.source = "//#{host}/#{log.source}" Puppet::Util::Log.newmessage(log) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/reports/store.rb
lib/puppet/reports/store.rb
# frozen_string_literal: true require_relative '../../puppet' require 'fileutils' require_relative '../../puppet/util' SEPARATOR = [Regexp.escape(File::SEPARATOR.to_s), Regexp.escape(File::ALT_SEPARATOR.to_s)].join Puppet::Reports.register_report(:store) do desc "Store the yaml report on disk. Each host sends its report as a YAML dump and this just stores the file on disk, in the `reportdir` directory. These files collect quickly -- one every half hour -- so it is a good idea to perform some maintenance on them if you use this report (it's the only default report)." def process validate_host(host) dir = File.join(Puppet[:reportdir], host) unless Puppet::FileSystem.exist?(dir) FileUtils.mkdir_p(dir) FileUtils.chmod_R(0o750, dir) end # Now store the report. now = Time.now.gmtime name = %w[year month day hour min].collect do |method| # Make sure we're at least two digits everywhere "%02d" % now.send(method).to_s end.join("") + ".yaml" file = File.join(dir, name) begin Puppet::FileSystem.replace_file(file, 0o640) do |fh| fh.print to_yaml end rescue => detail Puppet.log_exception(detail, "Could not write report for #{host} at #{file}: #{detail}") end # Only testing cares about the return value file end # removes all reports for a given host? def self.destroy(host) validate_host(host) dir = File.join(Puppet[:reportdir], host) if Puppet::FileSystem.exist?(dir) Dir.entries(dir).each do |file| next if ['.', '..'].include?(file) file = File.join(dir, file) Puppet::FileSystem.unlink(file) if File.file?(file) end Dir.rmdir(dir) end end def validate_host(host) if host =~ Regexp.union(/[#{SEPARATOR}]/, /\A\.\.?\Z/) raise ArgumentError, _("Invalid node name %{host}") % { host: host.inspect } end end module_function :validate_host end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/reports/http.rb
lib/puppet/reports/http.rb
# frozen_string_literal: true require_relative '../../puppet' require_relative '../../puppet/network/http_pool' require 'uri' Puppet::Reports.register_report(:http) do desc <<-DESC Send reports via HTTP or HTTPS. This report processor submits reports as POST requests to the address in the `reporturl` setting. When a HTTPS URL is used, the remote server must present a certificate issued by the Puppet CA or the connection will fail validation. The body of each POST request is the YAML dump of a Puppet::Transaction::Report object, and the Content-Type is set as `application/x-yaml`. DESC def process url = URI.parse(Puppet[:reporturl]) headers = { "Content-Type" => "application/x-yaml" } # This metric_id option is silently ignored by Puppet's http client # (Puppet::Network::HTTP) but is used by Puppet Server's http client # (Puppet::Server::HttpClient) to track metrics on the request made to the # `reporturl` to store a report. options = { :metric_id => [:puppet, :report, :http], :include_system_store => Puppet[:report_include_system_store], } # Puppet's http client implementation accepts userinfo in the URL # but puppetserver's does not. So pass credentials explicitly. if url.user && url.password options[:basic_auth] = { user: url.user, password: url.password } end client = Puppet.runtime[:http] client.post(url, to_yaml, headers: headers, options: options) do |response| unless response.success? Puppet.err _("Unable to submit report to %{url} [%{code}] %{message}") % { url: Puppet[:reporturl].to_s, code: response.code, message: response.reason } end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/property/boolean.rb
lib/puppet/property/boolean.rb
# frozen_string_literal: true require_relative '../../puppet/coercion' class Puppet::Property::Boolean < Puppet::Property def unsafe_munge(value) Puppet::Coercion.boolean(value) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/property/ordered_list.rb
lib/puppet/property/ordered_list.rb
# frozen_string_literal: true require_relative '../../puppet/property/list' module Puppet class Property # This subclass of {Puppet::Property} manages an ordered list of values. # The maintained order is the order defined by the 'current' set of values (i.e. the # original order is not disrupted). Any additions are added after the current values # in their given order). # # For an unordered list see {Puppet::Property::List}. # class OrderedList < List def add_should_with_current(should, current) if current.is_a?(Array) # tricky trick # Preserve all the current items in the list # but move them to the back of the line should += (current - should) end should end def dearrayify(array) array.join(delimiter) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/property/keyvalue.rb
lib/puppet/property/keyvalue.rb
# frozen_string_literal: true require_relative '../../puppet/property' module Puppet class Property # This subclass of {Puppet::Property} manages string key value pairs. # In order to use this property: # # * the _should_ value must be an array of key-value pairs separated by the 'separator' # * the retrieve method should return a hash with the keys as symbols # @note **IMPORTANT**: In order for this property to work there must also be a 'membership' parameter # The class that inherits from property should override that method with the symbol for the membership # @todo The node with an important message is not very clear. # class KeyValue < Property class << self # This is a class-level variable that child properties can override # if they wish. attr_accessor :log_only_changed_or_new_keys end self.log_only_changed_or_new_keys = false def hash_to_key_value_s(hash) if self.class.log_only_changed_or_new_keys hash = hash.select { |k, _| @changed_or_new_keys.include?(k) } end hash.map { |*pair| pair.join(separator) }.join(delimiter) end def should_to_s(should_value) hash_to_key_value_s(should_value) end def is_to_s(current_value) # rubocop:disable Naming/PredicateName hash_to_key_value_s(current_value) end def membership :key_value_membership end def inclusive? @resource[membership] == :inclusive end def hashify_should # Puppet casts all should values to arrays. Thus, if the user # passed in a hash for our property's should value, the should_value # parameter will be a single element array so we just extract our value # directly. if !@should.empty? && @should.first.is_a?(Hash) return @should.first end # Here, should is an array of key/value pairs. @should.each_with_object({}) do |key_value, hash| tmp = key_value.split(separator) hash[tmp[0].strip.intern] = tmp[1] end end def process_current_hash(current) return {} if current == :absent # inclusive means we are managing everything so if it isn't in should, its gone current.each_key { |key| current[key] = nil } if inclusive? current end def should return nil unless @should members = hashify_should current = process_current_hash(retrieve) # shared keys will get overwritten by members should_value = current.merge(members) # Figure out the keys that will actually change in our Puppet run. # This lets us reduce the verbosity of Puppet's logging for instances # of this class when we want to. # # NOTE: We use ||= here because we only need to compute the # changed_or_new_keys once (since this property will only be synced once). # @changed_or_new_keys ||= should_value.keys.select do |key| !current.key?(key) || current[key] != should_value[key] end should_value end # @return [String] Returns a default separator of "=" def separator "=" end # @return [String] Returns a default delimiter of ";" def delimiter ";" end # Retrieves the key-hash from the provider by invoking its method named the same as this property. # @return [Hash] the hash from the provider, or `:absent` # def retrieve # ok, some 'convention' if the keyvalue property is named properties, provider should implement a properties method key_hash = provider.send(name) if provider if key_hash && key_hash != :absent key_hash else :absent end end # Returns true if there is no _is_ value, else returns if _is_ is equal to _should_ using == as comparison. # @return [Boolean] whether the property is in sync or not. def insync?(is) return true unless is (is == should) end # We only accept an array of key/value pairs (strings), a single # key/value pair (string) or a Hash as valid values for our property. # Note that for an array property value, the 'value' passed into the # block corresponds to the array element. validate do |value| unless value.is_a?(String) || value.is_a?(Hash) raise ArgumentError, _("The %{name} property must be specified as a hash or an array of key/value pairs (strings)!") % { name: name } end next if value.is_a?(Hash) unless value.include?(separator.to_s) raise ArgumentError, _("Key/value pairs must be separated by '%{separator}'") % { separator: separator } end end # The validate step ensures that our passed-in value is # either a String or a Hash. If our value's a string, # then nothing else needs to be done. Otherwise, we need # to stringify the hash's keys and values to match our # internal representation of the property's value. munge do |value| next value if value.is_a?(String) munged_value = value.to_a.map! do |hash_key, hash_value| [hash_key.to_s.strip.to_sym, hash_value.to_s] end munged_value.to_h end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/property/ensure.rb
lib/puppet/property/ensure.rb
# frozen_string_literal: true require_relative '../../puppet/property' # This property is automatically added to any {Puppet::Type} that responds # to the methods 'exists?', 'create', and 'destroy'. # # Ensure defaults to having the wanted _(should)_ value `:present`. # # @api public # class Puppet::Property::Ensure < Puppet::Property @name = :ensure def self.defaultvalues newvalue(:present) do if @resource.provider and @resource.provider.respond_to?(:create) @resource.provider.create else @resource.create end nil # return nil so the event is autogenerated end newvalue(:absent) do if @resource.provider and @resource.provider.respond_to?(:destroy) @resource.provider.destroy else @resource.destroy end nil # return nil so the event is autogenerated end defaultto do if @resource.managed? :present else nil end end # This doc will probably get overridden # rubocop:disable Naming/MemoizedInstanceVariableName @doc ||= "The basic property that the resource should be in." # rubocop:enable Naming/MemoizedInstanceVariableName end def self.inherited(sub) # Add in the two properties that everyone will have. sub.class_eval do end end def change_to_s(currentvalue, newvalue) if currentvalue == :absent || currentvalue.nil? _("created") elsif newvalue == :absent _("removed") else _('%{name} changed %{is} to %{should}') % { name: name, is: is_to_s(currentvalue), should: should_to_s(newvalue) } end rescue Puppet::Error raise rescue => detail raise Puppet::DevError, _("Could not convert change %{name} to string: %{detail}") % { name: name, detail: detail }, detail.backtrace end # Retrieves the _is_ value for the ensure property. # The existence of the resource is checked by first consulting the provider (if it responds to # `:exists`), and secondly the resource. A a value of `:present` or `:absent` is returned # depending on if the managed entity exists or not. # # @return [Symbol] a value of `:present` or `:absent` depending on if it exists or not # @raise [Puppet::DevError] if neither the provider nor the resource responds to `:exists` # def retrieve # XXX This is a problem -- whether the object exists or not often # depends on the results of other properties, yet we're the first property # to get checked, which means that those other properties do not have # @is values set. This seems to be the source of quite a few bugs, # although they're mostly logging bugs, not functional ones. prov = @resource.provider if prov && prov.respond_to?(:exists?) result = prov.exists? elsif @resource.respond_to?(:exists?) result = @resource.exists? else raise Puppet::DevError, _("No ability to determine if %{name} exists") % { name: @resource.class.name } end if result :present else :absent end end # If they're talking about the thing at all, they generally want to # say it should exist. # defaultto :present defaultto do if @resource.managed? :present else nil end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/property/list.rb
lib/puppet/property/list.rb
# frozen_string_literal: true require_relative '../../puppet/property' module Puppet class Property # This subclass of {Puppet::Property} manages an unordered list of values. # For an ordered list see {Puppet::Property::OrderedList}. # class List < Property def is_to_s(currentvalue) # rubocop:disable Naming/PredicateName currentvalue == :absent ? super(currentvalue) : currentvalue.join(delimiter) end def membership :membership end def add_should_with_current(should, current) should += current if current.is_a?(Array) should.uniq end def inclusive? @resource[membership] == :inclusive end # dearrayify was motivated because to simplify the implementation of the OrderedList property def dearrayify(array) array.sort.join(delimiter) end def should return nil unless @should members = @should # inclusive means we are managing everything so if it isn't in should, its gone members = add_should_with_current(members, retrieve) unless inclusive? dearrayify(members) end def delimiter "," end def retrieve # ok, some 'convention' if the list property is named groups, provider should implement a groups method tmp = provider.send(name) if provider if tmp && tmp != :absent tmp.instance_of?(Array) ? tmp : tmp.split(delimiter) else :absent end end def prepare_is_for_comparison(is) if is == :absent is = [] end dearrayify(is) end def insync?(is) return true unless is (prepare_is_for_comparison(is) == should) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/datatypes/error.rb
lib/puppet/datatypes/error.rb
# frozen_string_literal: true Puppet::DataTypes.create_type('Error') do interface <<-PUPPET type_parameters => { kind => Optional[Variant[String,Regexp,Type[Enum],Type[Pattern],Type[NotUndef],Type[Undef]]], issue_code => Optional[Variant[String,Regexp,Type[Enum],Type[Pattern],Type[NotUndef],Type[Undef]]] }, attributes => { msg => String[1], kind => { type => Optional[String[1]], value => undef }, details => { type => Optional[Hash[String[1],Data]], value => undef }, issue_code => { type => Optional[String[1]], value => undef }, }, functions => { message => Callable[[], String[1]] } PUPPET require_relative '../../puppet/datatypes/impl/error' implementation_class Puppet::DataTypes::Error end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/datatypes/impl/error.rb
lib/puppet/datatypes/impl/error.rb
# frozen_string_literal: true class Puppet::DataTypes::Error attr_reader :msg, :kind, :issue_code, :details alias message msg def self.from_asserted_hash(hash) new(hash['msg'], hash['kind'], hash['details'], hash['issue_code']) end def _pcore_init_hash result = { 'msg' => @msg } result['kind'] = @kind unless @kind.nil? result['details'] = @details unless @details.nil? result['issue_code'] = @issue_code unless @issue_code.nil? result end def initialize(msg, kind = nil, details = nil, issue_code = nil) @msg = msg @kind = kind @details = details @issue_code = issue_code end def eql?(o) self.class.equal?(o.class) && @msg == o.msg && @kind == o.kind && @issue_code == o.issue_code && @details == o.details end alias == eql? def hash @msg.hash ^ @kind.hash ^ @issue_code.hash end def to_s Puppet::Pops::Types::StringConverter.singleton.convert(self) end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/file_system/uniquefile.rb
lib/puppet/file_system/uniquefile.rb
# frozen_string_literal: true require 'English' require_relative '../../puppet/file_system' require 'delegate' require 'tmpdir' # A class that provides `Tempfile`-like capabilities, but does not attempt to # manage the deletion of the file for you. API is identical to the # normal `Tempfile` class. # # @api public class Puppet::FileSystem::Uniquefile < DelegateClass(File) # Convenience method which ensures that the file is closed and # unlinked before returning # # @param identifier [String] additional part of generated pathname # @yieldparam file [File] the temporary file object # @return result of the passed block # @api private def self.open_tmp(identifier) f = new(identifier) yield f ensure if f f.close! end end def initialize(basename, *rest) create_tmpname(basename, *rest) do |tmpname, _n, opts| mode = File::RDWR | File::CREAT | File::EXCL perm = 0o600 if opts mode |= opts.delete(:mode) || 0 opts[:perm] = perm perm = nil else opts = perm end self.class.locking(tmpname) do @tmpfile = File.open(tmpname, mode, opts) @tmpname = tmpname end @mode = mode & ~(File::CREAT | File::EXCL) perm or opts.freeze @opts = opts end super(@tmpfile) end # Opens or reopens the file with mode "r+". def open @tmpfile.close if @tmpfile @tmpfile = File.open(@tmpname, @mode, @opts) __setobj__(@tmpfile) end def _close @tmpfile.close if @tmpfile ensure @tmpfile = nil end protected :_close def close(unlink_now = false) if unlink_now close! else _close end end def close! _close unlink end def unlink return unless @tmpname begin File.unlink(@tmpname) rescue Errno::ENOENT rescue Errno::EACCES # may not be able to unlink on Windows; just ignore return end @tmpname = nil end alias delete unlink # Returns the full path name of the temporary file. # This will be nil if #unlink has been called. def path @tmpname end private def make_tmpname(prefix_suffix, n) case prefix_suffix when String prefix = prefix_suffix suffix = "" when Array prefix = prefix_suffix[0] suffix = prefix_suffix[1] else raise ArgumentError, _("unexpected prefix_suffix: %{value}") % { value: prefix_suffix.inspect } end t = Time.now.strftime("%Y%m%d") path = "#{prefix}#{t}-#{$PROCESS_ID}-#{rand(0x100000000).to_s(36)}" path << "-#{n}" if n path << suffix end def create_tmpname(basename, *rest) opts = try_convert_to_hash(rest[-1]) if opts opts = opts.dup if rest.pop.equal?(opts) max_try = opts.delete(:max_try) opts = [opts] else opts = [] end tmpdir, = *rest tmpdir ||= tmpdir() n = nil begin path = File.join(tmpdir, make_tmpname(basename, n)) yield(path, n, *opts) rescue Errno::EEXIST n ||= 0 n += 1 retry if !max_try or n < max_try raise _("cannot generate temporary name using `%{basename}' under `%{tmpdir}'") % { basename: basename, tmpdir: tmpdir } end path end def try_convert_to_hash(h) h.to_hash rescue NoMethodError nil end @@systmpdir ||= defined?(Etc.systmpdir) ? Etc.systmpdir : '/tmp' def tmpdir tmp = '.' [ENV.fetch('TMPDIR', nil), ENV.fetch('TMP', nil), ENV.fetch('TEMP', nil), @@systmpdir, '/tmp'].each do |dir| stat = File.stat(dir) if dir begin if stat && stat.directory? && stat.writable? tmp = dir break end rescue nil end end File.expand_path(tmp) end class << self # yields with locking for +tmpname+ and returns the result of the # block. def locking(tmpname) lock = tmpname + '.lock' mkdir(lock) yield rescue Errno::ENOENT => e ex = Errno::ENOENT.new("A directory component in #{lock} does not exist or is a dangling symbolic link") ex.set_backtrace(e.backtrace) raise ex ensure rmdir(lock) if Puppet::FileSystem.exist?(lock) end def mkdir(*args) Dir.mkdir(*args) end def rmdir(*args) Dir.rmdir(*args) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/file_system/memory_impl.rb
lib/puppet/file_system/memory_impl.rb
# frozen_string_literal: true class Puppet::FileSystem::MemoryImpl def initialize(*files) @files = files + all_children_of(files) end def expand_path(path, dir_string = nil) File.expand_path(path, dir_string) end def exist?(path) path.exist? end def directory?(path) path.directory? end def file?(path) path.file? end def executable?(path) path.executable? end def symlink?(path) path.symlink? end def readlink(path) path = path.path link = find(path) return Puppet::FileSystem::MemoryFile.a_missing_file(path) unless link source = link.source_path return Puppet::FileSystem::MemoryFile.a_missing_file(link) unless source find(source) || Puppet::FileSystem::MemoryFile.a_missing_file(source) end def children(path) path.children end def each_line(path, &block) path.each_line(&block) end def pathname(path) find(path) || Puppet::FileSystem::MemoryFile.a_missing_file(path) end def basename(path) path.duplicate_as(File.basename(path_string(path))) end def path_string(object) object.path end def read(path, opts = {}) handle = assert_path(path).handle handle.read end def read_preserve_line_endings(path) read(path) end def open(path, *args, &block) handle = assert_path(path).handle if block_given? yield handle else handle end end def assert_path(path) if path.is_a?(Puppet::FileSystem::MemoryFile) path else find(path) or raise ArgumentError, _("Unable to find registered object for %{path}") % { path: path.inspect } end end private def find(path) @files.find { |file| file.path == path } end def all_children_of(files) children = files.collect(&:children).flatten if children.empty? [] else children + all_children_of(children) end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/file_system/jruby.rb
lib/puppet/file_system/jruby.rb
# frozen_string_literal: true require_relative '../../puppet/file_system/posix' class Puppet::FileSystem::JRuby < Puppet::FileSystem::Posix def unlink(*paths) File.unlink(*paths) rescue Errno::ENOENT # JRuby raises ENOENT if the path doesn't exist or the parent directory # doesn't allow execute/traverse. If it's the former, `stat` will raise # ENOENT, if it's the later, it'll raise EACCES # See https://github.com/jruby/jruby/issues/5617 stat(*paths) end def replace_file(path, mode = nil, &block) # MRI Ruby rename checks if destination is a directory and raises, while # JRuby removes the directory and replaces the file. if directory?(path) raise Errno::EISDIR, _("Is a directory: %{directory}") % { directory: path } end super end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/file_system/path_pattern.rb
lib/puppet/file_system/path_pattern.rb
# frozen_string_literal: true require 'pathname' require_relative '../../puppet/error' module Puppet::FileSystem class PathPattern class InvalidPattern < Puppet::Error; end DOTDOT = '..' ABSOLUTE_UNIX = %r{^/} ABSOLUTE_WINDOWS = /^[a-z]:/i CURRENT_DRIVE_RELATIVE_WINDOWS = /^\\/ def self.relative(pattern) RelativePathPattern.new(pattern) end def self.absolute(pattern) AbsolutePathPattern.new(pattern) end class << self protected :new end # @param prefix [AbsolutePathPattern] An absolute path pattern instance # @return [AbsolutePathPattern] A new AbsolutePathPattern prepended with # the passed prefix's pattern. def prefix_with(prefix) new_pathname = prefix.pathname + pathname self.class.absolute(new_pathname.to_s) end def glob Dir.glob(@pathstr) end def to_s @pathstr end protected attr_reader :pathname private def validate if @pathstr.split(Pathname::SEPARATOR_PAT).any? { |f| f == DOTDOT } raise(InvalidPattern, _("PathPatterns cannot be created with directory traversals.")) elsif @pathstr.match?(CURRENT_DRIVE_RELATIVE_WINDOWS) raise(InvalidPattern, _("A PathPattern cannot be a Windows current drive relative path.")) end end def initialize(pattern) begin @pathname = Pathname.new(pattern.strip) @pathstr = @pathname.to_s rescue ArgumentError => error raise InvalidPattern.new(_("PathPatterns cannot be created with a zero byte."), error) end validate end end class RelativePathPattern < PathPattern def absolute? false end def validate super if @pathstr.match?(ABSOLUTE_WINDOWS) raise(InvalidPattern, _("A relative PathPattern cannot be prefixed with a drive.")) elsif @pathstr.match?(ABSOLUTE_UNIX) raise(InvalidPattern, _("A relative PathPattern cannot be an absolute path.")) end end end class AbsolutePathPattern < PathPattern def absolute? true end def validate super if !@pathstr.match?(ABSOLUTE_UNIX) && !@pathstr.match?(ABSOLUTE_WINDOWS) raise(InvalidPattern, _("An absolute PathPattern cannot be a relative path.")) end end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/file_system/file_impl.rb
lib/puppet/file_system/file_impl.rb
# frozen_string_literal: true # Abstract implementation of the Puppet::FileSystem # class Puppet::FileSystem::FileImpl def pathname(path) path.is_a?(Pathname) ? path : Pathname.new(path) end def assert_path(path) return path if path.is_a?(Pathname) # Some paths are string, or in the case of WatchedFile, it pretends to be # one by implementing to_str. if path.respond_to?(:to_str) Pathname.new(path) else raise ArgumentError, _("FileSystem implementation expected Pathname, got: '%{klass}'") % { klass: path.class } end end def path_string(path) path.to_s end def expand_path(path, dir_string = nil) # ensure `nil` values behave like underlying File.expand_path ::File.expand_path(path.nil? ? nil : path_string(path), dir_string) end def open(path, mode, options, &block) ::File.open(path, options, mode, &block) end def dir(path) path.dirname end def basename(path) path.basename.to_s end def size(path) path.size end def exclusive_create(path, mode, &block) opt = File::CREAT | File::EXCL | File::WRONLY self.open(path, mode, opt, &block) end def exclusive_open(path, mode, options = 'r', timeout = 300, &block) wait = 0.001 + (Kernel.rand / 1000) written = false until written ::File.open(path, options, mode) do |rf| if rf.flock(::File::LOCK_EX | ::File::LOCK_NB) Puppet.debug { _("Locked '%{path}'") % { path: path } } yield rf written = true Puppet.debug { _("Unlocked '%{path}'") % { path: path } } else Puppet.debug { "Failed to lock '%s' retrying in %.2f milliseconds" % [path, wait * 1000] } sleep wait timeout -= wait wait *= 2 if timeout < 0 raise Timeout::Error, _("Timeout waiting for exclusive lock on %{path}") % { path: path } end end end end end def each_line(path, &block) ::File.open(path) do |f| f.each_line do |line| yield line end end end def read(path, opts = {}) path.read(**opts) end def read_preserve_line_endings(path) default_encoding = Encoding.default_external.name encoding = default_encoding.downcase.start_with?('utf-') ? "bom|#{default_encoding}" : default_encoding read(path, encoding: encoding) end def binread(path) raise NotImplementedError end def exist?(path) ::File.exist?(path) end def directory?(path) ::File.directory?(path) end def file?(path) ::File.file?(path) end def executable?(path) ::File.executable?(path) end def writable?(path) path.writable? end def touch(path, mtime: nil) ::FileUtils.touch(path, mtime: mtime) end def mkpath(path) path.mkpath end def children(path) path.children end def symlink(path, dest, options = {}) FileUtils.symlink(path, dest, **options) end def symlink?(path) ::File.symlink?(path) end def readlink(path) ::File.readlink(path) end def unlink(*paths) ::File.unlink(*paths) end def stat(path) ::File.stat(path) end def lstat(path) ::File.lstat(path) end def compare_stream(path, stream) ::File.open(path, 0, 'rb') { |this| FileUtils.compare_stream(this, stream) } end def chmod(mode, path) FileUtils.chmod(mode, path) end def replace_file(path, mode = nil) begin stat = lstat(path) gid = stat.gid uid = stat.uid mode ||= stat.mode & 0o7777 rescue Errno::ENOENT mode ||= 0o640 end tempfile = Puppet::FileSystem::Uniquefile.new(Puppet::FileSystem.basename_string(path), Puppet::FileSystem.dir_string(path)) begin begin yield tempfile tempfile.flush tempfile.fsync ensure tempfile.close end tempfile_path = tempfile.path FileUtils.chown(uid, gid, tempfile_path) if uid && gid chmod(mode, tempfile_path) ::File.rename(tempfile_path, path_string(path)) ensure tempfile.close! end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/file_system/posix.rb
lib/puppet/file_system/posix.rb
# frozen_string_literal: true class Puppet::FileSystem::Posix < Puppet::FileSystem::FileImpl def binread(path) path.binread end # Provide an encoding agnostic version of compare_stream # # The FileUtils implementation in Ruby 2.0+ was modified in a manner where # it cannot properly compare File and StringIO instances. To sidestep that # issue this method reimplements the faster 2.0 version that will correctly # compare binary File and StringIO streams. def compare_stream(path, stream) ::File.open(path, 'rb') do |this| bsize = stream_blksize(this, stream) sa = String.new.force_encoding('ASCII-8BIT') sb = String.new.force_encoding('ASCII-8BIT') loop do this.read(bsize, sa) stream.read(bsize, sb) return true if sa.empty? && sb.empty? break if sa != sb end false end end private def stream_blksize(*streams) streams.each do |s| next unless s.respond_to?(:stat) size = blksize(s.stat) return size if size end default_blksize() end def blksize(st) s = st.blksize return nil unless s return nil if s == 0 s end def default_blksize 1024 end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/file_system/windows.rb
lib/puppet/file_system/windows.rb
# frozen_string_literal: true require_relative '../../puppet/file_system/posix' require_relative '../../puppet/util/windows' class Puppet::FileSystem::Windows < Puppet::FileSystem::Posix FULL_CONTROL = Puppet::Util::Windows::File::FILE_ALL_ACCESS FILE_READ = Puppet::Util::Windows::File::FILE_GENERIC_READ def open(path, mode, options, &block) # PUP-6959 mode is explicitly ignored until it can be implemented # Ruby on Windows uses mode for setting file attributes like read-only and # archived, not for setting permissions like POSIX raise TypeError, 'mode must be specified as an Integer' if mode && !mode.is_a?(Numeric) ::File.open(path, options, nil, &block) end def expand_path(path, dir_string = nil) # ensure `nil` values behave like underlying File.expand_path string_path = ::File.expand_path(path.nil? ? nil : path_string(path), dir_string) # if no tildes, nothing to expand, no need to call Windows API, return original string return string_path unless string_path.index('~') begin # no need to do existence check up front as GetLongPathName implies that check is performed # and it should be the exception that files aren't actually present string_path = Puppet::Util::Windows::File.get_long_pathname(string_path) rescue Puppet::Util::Windows::Error => e # preserve original File.expand_path behavior for file / path not found by returning string raise if e.code != Puppet::Util::Windows::File::ERROR_FILE_NOT_FOUND && e.code != Puppet::Util::Windows::File::ERROR_PATH_NOT_FOUND end string_path end def exist?(path) Puppet::Util::Windows::File.exist?(path) end def symlink(path, dest, options = {}) raise_if_symlinks_unsupported dest_exists = exist?(dest) # returns false on dangling symlink dest_stat = Puppet::Util::Windows::File.stat(dest) if dest_exists # silent fail to preserve semantics of original FileUtils return 0 if dest_exists && dest_stat.ftype == 'directory' if dest_exists && dest_stat.ftype == 'file' && options[:force] != true raise(Errno::EEXIST, _("%{dest} already exists and the :force option was not specified") % { dest: dest }) end if options[:noop] != true ::File.delete(dest) if dest_exists # can only be file Puppet::Util::Windows::File.symlink(path, dest) end 0 end def symlink?(path) return false unless Puppet.features.manages_symlinks? Puppet::Util::Windows::File.symlink?(path) end def readlink(path) raise_if_symlinks_unsupported Puppet::Util::Windows::File.readlink(path) end def unlink(*file_names) unless Puppet.features.manages_symlinks? return ::File.unlink(*file_names) end file_names.each do |file_name| file_name = file_name.to_s # handle PathName stat = begin Puppet::Util::Windows::File.stat(file_name) rescue nil end # sigh, Ruby + Windows :( if !stat begin ::File.unlink(file_name) rescue Dir.rmdir(file_name) end elsif stat.ftype == 'directory' if Puppet::Util::Windows::File.symlink?(file_name) Dir.rmdir(file_name) else raise Errno::EPERM, file_name end else ::File.unlink(file_name) end end file_names.length end def stat(path) Puppet::Util::Windows::File.stat(path) end def lstat(path) unless Puppet.features.manages_symlinks? return Puppet::Util::Windows::File.stat(path) end Puppet::Util::Windows::File.lstat(path) end def chmod(mode, path) Puppet::Util::Windows::Security.set_mode(mode, path.to_s) end def read_preserve_line_endings(path) contents = path.read(:mode => 'rb', :encoding => 'bom|utf-8') contents = path.read(:mode => 'rb', :encoding => "bom|#{Encoding.default_external.name}") unless contents.valid_encoding? contents = path.read unless contents.valid_encoding? contents end # https://docs.microsoft.com/en-us/windows/desktop/debug/system-error-codes--0-499- FILE_NOT_FOUND = 2 ACCESS_DENIED = 5 SHARING_VIOLATION = 32 LOCK_VIOLATION = 33 def replace_file(path, mode = nil) if directory?(path) raise Errno::EISDIR, _("Is a directory: %{directory}") % { directory: path } end current_sid = Puppet::Util::Windows::SID.name_to_sid(Puppet::Util::Windows::ADSI::User.current_user_name) current_sid ||= Puppet::Util::Windows::SID.name_to_sid(Puppet::Util::Windows::ADSI::User.current_sam_compatible_user_name) dacl = case mode when 0o644 dacl = secure_dacl(current_sid) dacl.allow(Puppet::Util::Windows::SID::BuiltinUsers, FILE_READ) dacl when 0o660, 0o640, 0o600, 0o440 secure_dacl(current_sid) when nil get_dacl_from_file(path) || secure_dacl(current_sid) else raise ArgumentError, "#{mode} is invalid: Only modes 0644, 0640, 0660, and 0440 are allowed" end tempfile = Puppet::FileSystem::Uniquefile.new(Puppet::FileSystem.basename_string(path), Puppet::FileSystem.dir_string(path)) begin tempdacl = Puppet::Util::Windows::AccessControlList.new tempdacl.allow(current_sid, FULL_CONTROL) set_dacl(tempfile.path, tempdacl) begin yield tempfile tempfile.flush tempfile.fsync ensure tempfile.close end set_dacl(tempfile.path, dacl) if dacl ::File.rename(tempfile.path, path_string(path)) ensure tempfile.close! end rescue Puppet::Util::Windows::Error => e case e.code when ACCESS_DENIED, SHARING_VIOLATION, LOCK_VIOLATION raise Errno::EACCES.new(path_string(path), e) else raise SystemCallError, e.message end end private def set_dacl(path, dacl) sd = Puppet::Util::Windows::Security.get_security_descriptor(path) new_sd = Puppet::Util::Windows::SecurityDescriptor.new(sd.owner, sd.group, dacl, true) Puppet::Util::Windows::Security.set_security_descriptor(path, new_sd) end def secure_dacl(current_sid) dacl = Puppet::Util::Windows::AccessControlList.new [ Puppet::Util::Windows::SID::LocalSystem, Puppet::Util::Windows::SID::BuiltinAdministrators, current_sid ].uniq.map do |sid| dacl.allow(sid, FULL_CONTROL) end dacl end def get_dacl_from_file(path) sd = Puppet::Util::Windows::Security.get_security_descriptor(path_string(path)) sd.dacl rescue Puppet::Util::Windows::Error => e raise e unless e.code == FILE_NOT_FOUND end def raise_if_symlinks_unsupported unless Puppet.features.manages_symlinks? msg = _("This version of Windows does not support symlinks. Windows Vista / 2008 or higher is required.") raise Puppet::Util::Windows::Error, msg end unless Puppet::Util::Windows::Process.process_privilege_symlink? Puppet.warning _("The current user does not have the necessary permission to manage symlinks.") end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/file_system/memory_file.rb
lib/puppet/file_system/memory_file.rb
# frozen_string_literal: true # An in-memory file abstraction. Commonly used with Puppet::FileSystem::File#overlay # @api private class Puppet::FileSystem::MemoryFile attr_reader :path, :children def self.a_missing_file(path) new(path, :exist? => false, :executable? => false) end def self.a_missing_directory(path) new(path, :exist? => false, :executable? => false, :directory? => true) end def self.a_regular_file_containing(path, content) new(path, :exist? => true, :executable? => false, :content => content) end def self.an_executable(path) new(path, :exist? => true, :executable? => true) end def self.a_directory(path, children = []) new(path, :exist? => true, :executable? => true, :directory? => true, :children => children) end def self.a_symlink(target_path, source_path) new(target_path, :exist? => true, :symlink? => true, :source_path => source_path) end def initialize(path, properties) @path = path @properties = properties @children = (properties[:children] || []).collect do |child| child.duplicate_as(File.join(@path, child.path)) end end def directory?; @properties[:directory?]; end def exist?; @properties[:exist?]; end def executable?; @properties[:executable?]; end def symlink?; @properties[:symlink?]; end def source_path; @properties[:source_path]; end def each_line(&block) handle.each_line(&block) end def handle raise Errno::ENOENT unless exist? StringIO.new(@properties[:content] || '') end def duplicate_as(other_path) self.class.new(other_path, @properties) end def absolute? Pathname.new(path).absolute? end def to_path path end def to_s to_path end def inspect "<Puppet::FileSystem::MemoryFile:#{self}>" end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/reference/report.rb
lib/puppet/reference/report.rb
# frozen_string_literal: true require_relative '../../puppet/reports' report = Puppet::Util::Reference.newreference :report, :doc => "All available transaction reports" do Puppet::Reports.reportdocs end report.header = " Puppet can generate a report after applying a catalog. This report includes events, log messages, resource statuses, and metrics and metadata about the run. Puppet agent sends its report to a Puppet master server, and Puppet apply processes its own reports. Puppet master and Puppet apply will handle every report with a set of report processors, configurable with the `reports` setting in puppet.conf. This page documents the built-in report processors. See [About Reporting](https://puppet.com/docs/puppet/latest/reporting_about.html) for more details. "
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/reference/type.rb
lib/puppet/reference/type.rb
# frozen_string_literal: true Puppet::Util::Reference.newreference :type, :doc => "All Puppet resource types and all their details" do types = {} Puppet::Type.loadall Puppet::Type.eachtype { |type| next if type.name == :component next if type.name == :whit types[type.name] = type } str = %{ ## Resource Types - The *namevar* is the parameter used to uniquely identify a type instance. This is the parameter that gets assigned when a string is provided before the colon in a type declaration. In general, only developers will need to worry about which parameter is the `namevar`. In the following code: file { "/etc/passwd": owner => "root", group => "root", mode => "0644" } `/etc/passwd` is considered the title of the file object (used for things like dependency handling), and because `path` is the namevar for `file`, that string is assigned to the `path` parameter. - *Parameters* determine the specific configuration of the instance. They either directly modify the system (internally, these are called properties) or they affect how the instance behaves (e.g., adding a search path for `exec` instances or determining recursion on `file` instances). - *Providers* provide low-level functionality for a given resource type. This is usually in the form of calling out to external commands. When required binaries are specified for providers, fully qualified paths indicate that the binary must exist at that specific path and unqualified binaries indicate that Puppet will search for the binary using the shell path. - *Features* are abilities that some providers might not support. You can use the list of supported features to determine how a given provider can be used. Resource types define features they can use, and providers can be tested to see which features they provide. }.dup types.sort_by(&:to_s).each { |name, type| str << " ---------------- " str << markdown_header(name, 3) str << scrub(type.doc) + "\n\n" # Handle the feature docs. featuredocs = type.featuredocs if featuredocs str << markdown_header("Features", 4) str << featuredocs end docs = {} type.validproperties.sort_by(&:to_s).reject { |sname| property = type.propertybyname(sname) property.nodoc }.each { |sname| property = type.propertybyname(sname) raise _("Could not retrieve property %{sname} on type %{type_name}") % { sname: sname, type_name: type.name } unless property doc = property.doc unless doc $stderr.puts _("No docs for %{type}[%{sname}]") % { type: type, sname: sname } next end doc = doc.dup tmp = doc tmp = scrub(tmp) docs[sname] = tmp } str << markdown_header("Parameters", 4) + "\n" type.parameters.sort_by(&:to_s).each { |type_name, _param| docs[type_name] = scrub(type.paramdoc(type_name)) } additional_key_attributes = type.key_attributes - [:name] docs.sort { |a, b| a[0].to_s <=> b[0].to_s }.each { |type_name, doc| if additional_key_attributes.include?(type_name) doc = "(**Namevar:** If omitted, this parameter's value defaults to the resource's title.)\n\n" + doc end str << markdown_definitionlist(type_name, doc) } str << "\n" } str end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/reference/providers.rb
lib/puppet/reference/providers.rb
# frozen_string_literal: true providers = Puppet::Util::Reference.newreference :providers, :title => "Provider Suitability Report", :depth => 1, :dynamic => true, :doc => "Which providers are valid for this machine" do types = [] Puppet::Type.loadall Puppet::Type.eachtype do |klass| next unless klass && klass.providers.length > 0 types << klass end types.sort! { |a, b| a.name.to_s <=> b.name.to_s } command_line = Puppet::Util::CommandLine.new types.reject! { |type| !command_line.args.include?(type.name.to_s) } unless command_line.args.empty? ret = "Details about this host:\n\n".dup # Throw some facts in there, so we know where the report is from. ret << option('Ruby Version', Facter.value('ruby.version')) ret << option('Puppet Version', Facter.value('puppetversion')) ret << option('Operating System', Facter.value('os.name')) ret << option('Operating System Release', Facter.value('os.release.full')) ret << "\n" count = 1 # Produce output for each type. types.each do |type| features = type.features ret << "\n" # add a trailing newline # Now build up a table of provider suitability. headers = %w[Provider Suitable?] + features.collect(&:to_s).sort table_data = {} notes = [] default = type.defaultprovider ? type.defaultprovider.name : 'none' type.providers.sort_by(&:to_s).each do |pname| data = [] table_data[pname] = data provider = type.provider(pname) # Add the suitability note missing = provider.suitable?(false) if missing && missing.empty? data << "*X*" suit = true else data << "[#{count}]_" # A pointer to the appropriate footnote suit = false end # Add a footnote with the details about why this provider is unsuitable, if that's the case unless suit details = ".. [#{count}]\n" missing.each do |test, values| case test when :exists details << _(" - Missing files %{files}\n") % { files: values.join(", ") } when :variable values.each do |name, facts| if Puppet.settings.valid?(name) details << _(" - Setting %{name} (currently %{value}) not in list %{facts}\n") % { name: name, value: Puppet.settings.value(name).inspect, facts: facts.join(", ") } else details << _(" - Fact %{name} (currently %{value}) not in list %{facts}\n") % { name: name, value: Puppet.runtime[:facter].value(name).inspect, facts: facts.join(", ") } end end when :true details << _(" - Got %{values} true tests that should have been false\n") % { values: values } when :false details << _(" - Got %{values} false tests that should have been true\n") % { values: values } when :feature details << _(" - Missing features %{values}\n") % { values: values.collect(&:to_s).join(",") } end end notes << details count += 1 end # Add a note for every feature features.each do |feature| if provider.features.include?(feature) data << "*X*" else data << "" end end end ret << markdown_header(type.name.to_s + "_", 2) ret << "[#{type.name}](https://puppet.com/docs/puppet/latest/type.html##{type.name})\n\n" ret << option("Default provider", default) ret << doctable(headers, table_data) notes.each do |note| ret << note + "\n" end ret << "\n" end ret << "\n" ret end providers.header = " Puppet resource types are usually backed by multiple implementations called `providers`, which handle variance between platforms and tools. Different providers are suitable or unsuitable on different platforms based on things like the presence of a given tool. Here are all of the provider-backed types and their different providers. Any unmentioned types do not use providers yet. "
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/reference/metaparameter.rb
lib/puppet/reference/metaparameter.rb
# frozen_string_literal: true Puppet::Util::Reference.newreference :metaparameter, :doc => "All Puppet metaparameters and all their details" do str = %{ Metaparameters are attributes that work with any resource type, including custom types and defined types. In general, they affect _Puppet's_ behavior rather than the desired state of the resource. Metaparameters do things like add metadata to a resource (`alias`, `tag`), set limits on when the resource should be synced (`require`, `schedule`, etc.), prevent Puppet from making changes (`noop`), and change logging verbosity (`loglevel`). ## Available Metaparameters }.dup begin params = [] Puppet::Type.eachmetaparam { |param| params << param } params.sort_by(&:to_s).each { |param| str << markdown_header(param.to_s, 3) str << scrub(Puppet::Type.metaparamdoc(param)) str << "\n\n" } rescue => detail Puppet.log_exception(detail, _("incorrect metaparams: %{detail}") % { detail: detail }) exit(1) end str end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/reference/configuration.rb
lib/puppet/reference/configuration.rb
# frozen_string_literal: true config = Puppet::Util::Reference.newreference(:configuration, :depth => 1, :doc => "A reference for all settings") do docs = {} Puppet.settings.each do |name, object| docs[name] = object end str = ''.dup docs.sort { |a, b| a[0].to_s <=> b[0].to_s }.each do |name, object| # Make each name an anchor header = name.to_s str << markdown_header(header, 3) # Print the doc string itself begin str << Puppet::Util::Docs.scrub(object.desc) rescue => detail Puppet.log_exception(detail) end str << "\n\n" # Now print the data about the item. val = object.default case name.to_s when 'vardir' val = 'Unix/Linux: /opt/puppetlabs/puppet/cache -- Windows: C:\ProgramData\PuppetLabs\puppet\cache -- Non-root user: ~/.puppetlabs/opt/puppet/cache' when 'publicdir' val = 'Unix/Linux: /opt/puppetlabs/puppet/public -- Windows: C:\ProgramData\PuppetLabs\puppet\public -- Non-root user: ~/.puppetlabs/opt/puppet/public' when 'confdir' val = 'Unix/Linux: /etc/puppetlabs/puppet -- Windows: C:\ProgramData\PuppetLabs\puppet\etc -- Non-root user: ~/.puppetlabs/etc/puppet' when 'codedir' val = 'Unix/Linux: /etc/puppetlabs/code -- Windows: C:\ProgramData\PuppetLabs\code -- Non-root user: ~/.puppetlabs/etc/code' when 'rundir' val = 'Unix/Linux: /var/run/puppetlabs -- Windows: C:\ProgramData\PuppetLabs\puppet\var\run -- Non-root user: ~/.puppetlabs/var/run' when 'logdir' val = 'Unix/Linux: /var/log/puppetlabs/puppet -- Windows: C:\ProgramData\PuppetLabs\puppet\var\log -- Non-root user: ~/.puppetlabs/var/log' when 'hiera_config' val = '$confdir/hiera.yaml. However, for backwards compatibility, if a file exists at $codedir/hiera.yaml, Puppet uses that instead.' when 'certname' val = "the Host's fully qualified domain name, as determined by Facter" when 'hostname' val = "(the system's fully qualified hostname)" when 'domain' val = "(the system's own domain)" when 'srv_domain' val = 'example.com' when 'http_user_agent' val = 'Puppet/<version> Ruby/<version> (<architecture>)' end # Leave out the section information; it was apparently confusing people. # str << "- **Section**: #{object.section}\n" unless val == "" str << "- *Default*: `#{val}`\n" end str << "\n" end return str end config.header = <<~EOT ## Configuration settings * Each of these settings can be specified in `puppet.conf` or on the command line. * Puppet Enterprise (PE) and open source Puppet share the configuration settings documented here. However, PE defaults differ from open source defaults for some settings, such as `node_terminus`, `storeconfigs`, `always_retry_plugins`, `disable18n`, `environment_timeout` (when Code Manager is enabled), and the Puppet Server JRuby `max-active-instances` setting. To verify PE configuration defaults, check the `puppet.conf` or `pe-puppet-server.conf` file after installation. * When using boolean settings on the command line, use `--setting` and `--no-setting` instead of `--setting (true|false)`. (Using `--setting false` results in "Error: Could not parse application options: needless argument".) * Settings can be interpolated as `$variables` in other settings; `$environment` is special, in that puppet master will interpolate each agent node's environment instead of its own. * Multiple values should be specified as comma-separated lists; multiple directories should be separated with the system path separator (usually a colon). * Settings that represent time intervals should be specified in duration format: an integer immediately followed by one of the units 'y' (years of 365 days), 'd' (days), 'h' (hours), 'm' (minutes), or 's' (seconds). The unit cannot be combined with other units, and defaults to seconds when omitted. Examples are '3600' which is equivalent to '1h' (one hour), and '1825d' which is equivalent to '5y' (5 years). * If you use the `splay` setting, note that the period that it waits changes each time the Puppet agent is restarted. * Settings that take a single file or directory can optionally set the owner, group, and mode for their value: `rundir = $vardir/run { owner = puppet, group = puppet, mode = 644 }` * The Puppet executables ignores any setting that isn't relevant to their function. See the [configuration guide][confguide] for more details. [confguide]: https://puppet.com/docs/puppet/latest/config_about_settings.html EOT
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/reference/function.rb
lib/puppet/reference/function.rb
# frozen_string_literal: true function = Puppet::Util::Reference.newreference :function, :doc => "All functions available in the parser" do Puppet::Parser::Functions.functiondocs end function.header = " There are two types of functions in Puppet: Statements and rvalues. Statements stand on their own and do not return arguments; they are used for performing stand-alone work like importing. Rvalues return values and can only be used in a statement requiring a value, such as an assignment or a case statement. Functions execute on the Puppet master. They do not execute on the Puppet agent. Hence they only have access to the commands and data available on the Puppet master host. Here are the functions available in Puppet: "
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/reference/indirection.rb
lib/puppet/reference/indirection.rb
# frozen_string_literal: true require_relative '../../puppet/indirector/indirection' require_relative '../../puppet/util/checksums' require_relative '../../puppet/file_serving/content' require_relative '../../puppet/file_serving/metadata' reference = Puppet::Util::Reference.newreference :indirection, :doc => "Indirection types and their terminus classes" do text = ''.dup Puppet::Indirector::Indirection.instances.sort_by(&:to_s).each do |indirection| ind = Puppet::Indirector::Indirection.instance(indirection) name = indirection.to_s.capitalize text << "## " + indirection.to_s + "\n\n" text << Puppet::Util::Docs.scrub(ind.doc) + "\n\n" Puppet::Indirector::Terminus.terminus_classes(ind.name).sort_by(&:to_s).each do |terminus| # this is an "abstract" terminus, ignore it next if ind.name == :resource && terminus == :validator terminus_name = terminus.to_s term_class = Puppet::Indirector::Terminus.terminus_class(ind.name, terminus) if term_class terminus_doc = Puppet::Util::Docs.scrub(term_class.doc) text << markdown_header("`#{terminus_name}` terminus", 3) << terminus_doc << "\n\n" else Puppet.warning _("Could not build docs for indirector %{name}, terminus %{terminus}: could not locate terminus.") % { name: name.inspect, terminus: terminus_name.inspect } end end end text end reference.header = <<~HEADER ## About Indirection Puppet's indirector support pluggable backends (termini) for a variety of key-value stores (indirections). Each indirection type corresponds to a particular Ruby class (the "Indirected Class" below) and values are instances of that class. Each instance's key is available from its `name` method. The termini can be local (e.g., on-disk files) or remote (e.g., using a REST interface to talk to a puppet master). An indirector has five methods, which are mapped into HTTP verbs for the REST interface: * `find(key)` - get a single value (mapped to GET or POST with a singular endpoint) * `search(key)` - get a list of matching values (mapped to GET with a plural endpoint) * `head(key)` - return true if the key exists (mapped to HEAD) * `destroy(key)` - remove the key and value (mapped to DELETE) * `save(instance)` - write the instance to the store, using the instance's name as the key (mapped to PUT) These methods are available via the `indirection` class method on the indirected classes. For example: node = Puppet::Node.indirection.find('foo.example.com') At startup, each indirection is configured with a terminus. In most cases, this is the default terminus defined by the indirected class, but it can be overridden by the application or face, or overridden with the `route_file` configuration. The available termini differ for each indirection, and are listed below. Indirections can also have a cache, represented by a second terminus. This is a write-through cache: modifications are written both to the cache and to the primary terminus. Values fetched from the terminus are written to the cache. ### Interaction with REST REST endpoints have the form `/{prefix}/{version}/{indirection}/{key}?environment={environment}`, where the indirection can be singular or plural, following normal English spelling rules. On the server side, REST responses are generated from the locally-configured endpoints. ### Indirections and Termini Below is the list of all indirections, their associated terminus classes, and how you select between them. In general, the appropriate terminus class is selected by the application for you (e.g., `puppet agent` would always use the `rest` terminus for most of its indirected classes), but some classes are tunable via normal settings. These will have `terminus setting` documentation listed with them. HEADER
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/configurer/fact_handler.rb
lib/puppet/configurer/fact_handler.rb
# frozen_string_literal: true require_relative '../../puppet/indirector/facts/facter' require_relative '../../puppet/configurer' require_relative '../../puppet/configurer/downloader' # Break out the code related to facts. This module is # just included into the agent, but having it here makes it # easier to test. module Puppet::Configurer::FactHandler def find_facts # This works because puppet agent configures Facts to use 'facter' for # finding facts and the 'rest' terminus for caching them. Thus, we'll # compile them and then "cache" them on the server. facts = Puppet::Node::Facts.indirection.find(Puppet[:node_name_value], :environment => Puppet::Node::Environment.remote(@environment)) unless Puppet[:node_name_fact].empty? Puppet[:node_name_value] = facts.values[Puppet[:node_name_fact]] facts.name = Puppet[:node_name_value] end facts rescue SystemExit, NoMemoryError raise rescue Exception => detail message = _("Could not retrieve local facts: %{detail}") % { detail: detail } Puppet.log_exception(detail, message) raise Puppet::Error, message, detail.backtrace end def facts_for_uploading encode_facts(find_facts) end def encode_facts(facts) # facts = find_facts # NOTE: :facts specified as parameters are URI encoded here, # then encoded for a second time depending on their length: # # <= 1024 characters sent via query string of a HTTP GET, additionally query string encoded # > 1024 characters sent in POST data, additionally x-www-form-urlencoded # so it's only important that encoding method here return original values # correctly when CGI.unescape called against it (in compiler code) if Puppet[:preferred_serialization_format] == "pson" { :facts_format => :pson, :facts => Puppet::Util.uri_query_encode(facts.render(:pson)) } else { :facts_format => 'application/json', :facts => Puppet::Util.uri_query_encode(facts.render(:json)) } end end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/configurer/plugin_handler.rb
lib/puppet/configurer/plugin_handler.rb
# frozen_string_literal: true # Break out the code related to plugins. This module is # just included into the agent, but having it here makes it # easier to test. require_relative '../../puppet/configurer' class Puppet::Configurer::PluginHandler SUPPORTED_LOCALES_MOUNT_AGENT_VERSION = Gem::Version.new("5.3.4") def download_plugins(environment) source_permissions = Puppet::Util::Platform.windows? ? :ignore : :use plugin_downloader = Puppet::Configurer::Downloader.new( "plugin", Puppet[:plugindest], Puppet[:pluginsource], Puppet[:pluginsignore], environment ) plugin_fact_downloader = Puppet::Configurer::Downloader.new( "pluginfacts", Puppet[:pluginfactdest], Puppet[:pluginfactsource], Puppet[:pluginsignore], environment, source_permissions ) result = [] result += plugin_fact_downloader.evaluate result += plugin_downloader.evaluate unless Puppet[:disable_i18n] # until file metadata/content are using the rest client, we need to check # both :server_agent_version and the session to see if the server supports # the "locales" mount server_agent_version = Puppet.lookup(:server_agent_version) { "0.0" } locales = Gem::Version.new(server_agent_version) >= SUPPORTED_LOCALES_MOUNT_AGENT_VERSION unless locales session = Puppet.lookup(:http_session) locales = session.supports?(:fileserver, 'locales') || session.supports?(:puppet, 'locales') end if locales locales_downloader = Puppet::Configurer::Downloader.new( "locales", Puppet[:localedest], Puppet[:localesource], Puppet[:pluginsignore] + " *.pot config.yaml", environment ) result += locales_downloader.evaluate end end Puppet::Util::Autoload.reload_changed(Puppet.lookup(:current_environment)) result end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false
puppetlabs/puppet
https://github.com/puppetlabs/puppet/blob/e227c27540975c25aa22d533a52424a9d2fc886a/lib/puppet/configurer/downloader.rb
lib/puppet/configurer/downloader.rb
# frozen_string_literal: true require_relative '../../puppet/configurer' require_relative '../../puppet/resource/catalog' class Puppet::Configurer::Downloader attr_reader :name, :path, :source, :ignore # Evaluate our download, returning the list of changed values. def evaluate Puppet.info _("Retrieving %{name}") % { name: name } files = [] begin catalog.apply do |trans| unless Puppet[:ignore_plugin_errors] # Propagate the first failure associated with the transaction. The any_failed? # method returns the first resource status that failed or nil, not a boolean. first_failure = trans.any_failed? if first_failure event = (first_failure.events || []).first detail = event ? event.message : 'unknown' raise Puppet::Error, _("Failed to retrieve %{name}: %{detail}") % { name: name, detail: detail } end end trans.changed?.each do |resource| yield resource if block_given? files << resource[:path] end end rescue Puppet::Error => detail if Puppet[:ignore_plugin_errors] Puppet.log_exception(detail, _("Could not retrieve %{name}: %{detail}") % { name: name, detail: detail }) else raise detail end end files end def initialize(name, path, source, ignore = nil, environment = nil, source_permissions = :ignore) @name = name @path = path @source = source @ignore = ignore @environment = environment @source_permissions = source_permissions end def file unless @file args = default_arguments.merge(:path => path, :source => source) args[:ignore] = ignore.split if ignore @file = Puppet::Type.type(:file).new(args) end @file end def catalog unless @catalog @catalog = Puppet::Resource::Catalog.new("PluginSync", @environment) @catalog.host_config = false @catalog.add_resource(file) end @catalog end private def default_arguments defargs = { :path => path, :recurse => true, :links => :follow, :source => source, :source_permissions => @source_permissions, :tag => name, :purge => true, :force => true, :backup => false, :noop => false, :max_files => -1 } unless Puppet::Util::Platform.windows? defargs[:owner] = Process.uid defargs[:group] = Process.gid end defargs end end
ruby
Apache-2.0
e227c27540975c25aa22d533a52424a9d2fc886a
2026-01-04T15:39:26.576514Z
false