Class: Puppet::Application::Lookup

Inherits:
Puppet::Application show all
Defined in:
lib/puppet/application/lookup.rb

Constant Summary collapse

RUN_HELP =
"Run 'puppet lookup --help' for more details".freeze
DEEP_MERGE_OPTIONS =
'--knock-out-prefix, --sort-merged-arrays, and --merge-hash-arrays'.freeze

Constants inherited from Puppet::Application

DOCPATTERN

Constants included from Util

Util::AbsolutePathPosix, Util::AbsolutePathWindows, Util::DEFAULT_POSIX_MODE, Util::DEFAULT_WINDOWS_MODE

Constants included from Util::POSIX

Util::POSIX::LOCALE_ENV_VARS, Util::POSIX::USER_ENV_VARS

Constants included from Util::SymbolicFileMode

Util::SymbolicFileMode::SetGIDBit, Util::SymbolicFileMode::SetUIDBit, Util::SymbolicFileMode::StickyBit, Util::SymbolicFileMode::SymbolicMode, Util::SymbolicFileMode::SymbolicSpecialToBit

Instance Attribute Summary

Attributes inherited from Puppet::Application

#command_line, #options

Instance Method Summary collapse

Methods inherited from Puppet::Application

[], available_application_names, banner, clear!, clear?, clear_everything_for_tests, #configure_indirector_routes, controlled_run, exit, find, #handle_logdest_arg, #handlearg, #initialize, #initialize_app_defaults, interrupted?, #log_runtime_environment, #name, option, option_parser_commands, #parse_options, #preinit, restart!, restart_requested?, #run, #run_command, run_mode, #set_log_level, stop!, stop_requested?, try_load_class

Methods included from Util

absolute_path?, benchmark, chuser, clear_environment, default_env, deterministic_rand, deterministic_rand_int, exit_on_fail, get_env, get_environment, logmethods, merge_environment, path_to_uri, pretty_backtrace, replace_file, safe_posix_fork, set_env, symbolizehash, thinmark, uri_to_path, which, withenv, withumask

Methods included from Util::POSIX

#get_posix_field, #gid, #idfield, #methodbyid, #methodbyname, #search_posix_field, #uid

Methods included from Util::SymbolicFileMode

#normalize_symbolic_mode, #symbolic_mode_to_int, #valid_symbolic_mode?

Constructor Details

This class inherits a constructor from Puppet::Application

Instance Method Details

#app_defaultsObject

Sets up the ‘node_cache_terminus’ default to use the Write Only Yaml terminus :write_only_yaml. If this is not wanted, the setting ´node_cache_terminus´ should be set to nil.

See Also:



70
71
72
73
74
75
# File 'lib/puppet/application/lookup.rb', line 70

def app_defaults
  super.merge({
    :node_cache_terminus => :write_only_yaml,
    :facts_terminus => 'yaml'
  })
end

#generate_scopeObject



307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
# File 'lib/puppet/application/lookup.rb', line 307

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'
    Puppet.settings[:node_cache_terminus] = nil
  end

  node = Puppet::Node.indirection.find(node) unless node.is_a?(Puppet::Node) # to allow unit tests to pass a node instance

  fact_file = options[:fact_file]

  if fact_file
    original_facts = node.parameters
    if fact_file.end_with?("json")
      given_facts = JSON.parse(Puppet::FileSystem.read(fact_file, :encoding => 'utf-8'))
    else
      given_facts = YAML.load(Puppet::FileSystem.read(fact_file, :encoding => 'utf-8'))
    end

    unless given_facts.instance_of?(Hash)
      raise "Incorrect formatted data in #{fact_file} given via the --facts flag"
    end

    node.parameters = original_facts.merge(given_facts)
  end

  Puppet[:code] = 'undef' unless options[:compile]
  compiler = Puppet::Parser::Compiler.new(node)
  compiler.compile { |catalog| yield(compiler.topscope); catalog }
end

#helpObject



105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# File 'lib/puppet/application/lookup.rb', line 105

def help
  "\npuppet-lookup(8) -- Data in modules lookup function\n========\n\nSYNOPSIS\n--------\nThe lookup command is used for debugging and testing a given data\nconfiguration. For a given data key, lookup will produce either a\nvalue or an explanation of how that value was obtained on the standard\noutput stream with the specified rendering format. Lookup is designed\nto be run on a puppet master or a node in a masterless setup.\n\nUSAGE\n-----\npuppet lookup [--help] [--type <TYPESTRING>] [--merge unique|hash|deep]\n[--knock-out-prefix <PREFIX-STRING>] [--sort-merged-arrays]\n[--merge-hash-arrays] [--explain]\n[--default <VALUE>] [--node <NODE-NAME>] [--facts <FILE>]\n[--compile]\n[--render-as s|json|yaml|binary|msgpack] <keys>\n\nDESCRIPTION\n-----------\nThe lookup command is a CLI interface for the puppet lookup function.\nWhen given one or more keys, the lookup command will return the first\nvalue found when run from the puppet master or a masterless node.\n\nWhen an explanation has not been requested and\nlookup is simply looking up a value, the application will exit with 0\nif a value was found and 1 otherwise. When an explanation is requested,\nlookup will always exit with 0 unless there is a major error.\n\nThe other options are as passed into the lookup function, and the effect\nthey have on the lookup is described in more detail in the header\nfor the lookup function:\n\nhttp://links.puppetlabs.com/lookup-docs\n\nOPTIONS\n-------\nThese options and their effects are described in more detail in\nthe puppet lookup function linked to above.\n\n* --help:\nPrint this help message.\n\n* --type <TYPESTRING>:\nAssert that the value has the specified type.\n\n* --merge unique|hash|deep:\nSpecify the merge strategy. 'hash' performs a simple hash-merge by\noverwriting keys of lower lookup priority. 'unique' appends everything\nto an array containing no nested arrays and where all duplicates have been\nremoved. 'deep' Performs a deep merge on values of Array and Hash type. There\nare additional option flags that can be used with 'deep'.\n\n* --knock-out-prefix <PREFIX-STRING>\nCan be used with the 'deep' merge strategy. Specify string value to signify\nprefix which deletes elements from existing element.\n\n* --sort-merged-arrays\nCan be used with the 'deep' merge strategy. When this flag is used all\nmerged arrays will be sorted.\n\n* --merge-hash-arrays\nCan be used with the 'deep' merge strategy. When this flag is used arrays\nand hashes will be merged.\n\n* --explain\nPrint an explanation for the details of how the lookup performed rather\nthan the value returned for the key. The explanation will describe how\nthe result was obtained or why lookup failed to obtain the result.\n\n* --explain-options\nExplain if a lookup_options hash will be used and how it was assembled\nwhen performing a lookup.\n\n* --default <VALUE>\nA value produced if no value was found in the lookup.\n\n* --node <NODE-NAME>\nSpecify node which defines the scope in which the lookup will be performed.\nIf a node is not given, lookup will default to the machine from which the\nlookup is being run (which should be the master).\n\n* --facts <FILE>\nSpecify a .json, or .yaml file holding key => value mappings that will\noverride the facts for the current node. Any facts not specified by the\nuser will maintain their original value.\n\n* --compile\nPerform a full catalog compilation prior to the lookup. This is meaningful when\nthe catalog changes global variables that are referenced in interpolated values.\nNo catalog compilation takes place unless this flag is given.\n\n* --render-as s|json|yaml|binary|msgpack\nDetermines how the results will be rendered to the standard output where\ns means plain text. The default when lookup is producing a value is yaml\nand the default when producing an explanation is s.\n\nEXAMPLE\n-------\nIf you wanted to lookup 'key_name' within the scope of the master, you would\ncall lookup like this:\n$ puppet lookup key_name\n\nIf you wanted to lookup 'key_name' within the scope of the agent.local node,\nyou would call lookup like this:\n$ puppet lookup --node agent.local key_name\n\nIf you wanted to get the first value found for 'key_name_one' and 'key_name_two'\nwithin the scope of the agent.local node while merging values and knocking out\nthe prefix 'foo' while merging, you would call lookup like this:\n$ puppet lookup --node agent.local --merge deep --knock-out-prefix foo key_name_one key_name_two\n\nIf you wanted to lookup 'key_name' within the scope of the agent.local node,\nand return a default value of 'bar' if nothing was found, you would call\nlookup like this:\n$ puppet lookup --node agent.local --default bar key_name\n\nIf you wanted to see an explanation of how the value for 'key_name' would be\nobtained in the context of the agent.local node, you would call lookup like this:\n$ puppet lookup --node agent.local --explain key_name\n\nCOPYRIGHT\n---------\nCopyright (c) 2015 Puppet Labs, LLC Licensed under the Apache 2.0 License\n\n\n  HELP\nend\n"

#mainObject



239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/puppet/application/lookup.rb', line 239

def main
  keys = command_line.args

  #unless options[:node]
  #  raise "No node was given via the '--node' flag for the scope of the lookup.\n#{RUN_HELP}"
  #end

  if (options[:sort_merge_arrays] || options[:merge_hash_arrays] || options[:prefix]) && options[:merge] != 'deep'
    raise "The options #{DEEP_MERGE_OPTIONS} are only available with '--merge deep'\n#{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[0...-1].join(', ')}, or #{strategies.last}\n#{RUN_HELP}"
    end

    if merge == 'deep'
      merge_options = {'strategy' => 'deep',
        'sort_merge_arrays' => !options[:sort_merge_arrays].nil?,
        'merge_hash_arrays' => !options[:merge_hash_arrays].nil?}

      if options[:prefix]
        merge_options.merge!({'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 == :json ? :pson : format)
  raise "Unknown rendering 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
      exit(1) unless explain
    end
    puts format == :s ? lookup_invocation.explainer.to_s : renderer.render(lookup_invocation.explainer.to_hash) if explain
  end
end

#setupObject



95
96
97
98
99
100
101
102
103
# File 'lib/puppet/application/lookup.rb', line 95

def setup
  setup_logs

  exit(Puppet.settings.print_configs ? 0 : 1) if Puppet.settings.print_configs?

  Puppet.settings.use :main, :master, :ssl, :metrics

  setup_terminuses
end

#setup_logsObject



77
78
79
80
81
82
83
# File 'lib/puppet/application/lookup.rb', line 77

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

#setup_terminusesObject



85
86
87
88
89
90
91
92
93
# File 'lib/puppet/application/lookup.rb', line 85

def setup_terminuses
  require 'puppet/file_serving/content'
  require 'puppet/file_serving/metadata'

  Puppet::FileServing::Content.indirection.terminus_class = :file_server
  Puppet::FileServing::.indirection.terminus_class = :file_server

  Puppet::FileBucket::File.indirection.terminus_class = :file
end