Class: Puppet::Application::Preview

Inherits:
Puppet::Application
  • Object
show all
Includes:
PuppetX::Puppetlabs::Migration
Defined in:
lib/puppet/application/preview.rb

Defined Under Namespace

Classes: Colorizer, UsageError

Constant Summary collapse

NOT_EQUAL =
4
NOT_COMPLIANT =
5
MIGRATION_3to4 =
'3.8/4.0'.freeze
RUNHELP =
"Run 'puppet preview --help for more details".freeze
API_BASE =
::File.expand_path(::File.join('..', '..', '..', 'puppet_x', 'puppetlabs', 'preview', 'api'), __FILE__)

Constants included from PuppetX::Puppetlabs::Migration

PuppetX::Puppetlabs::Migration::BASELINE_FAILED, PuppetX::Puppetlabs::Migration::CATALOG_DELTA, PuppetX::Puppetlabs::Migration::DOUBLE_COLON, PuppetX::Puppetlabs::Migration::EMPTY_ARRAY, PuppetX::Puppetlabs::Migration::EMPTY_HASH, PuppetX::Puppetlabs::Migration::GENERAL_ERROR, PuppetX::Puppetlabs::Migration::PREVIEW_FAILED, PuppetX::Puppetlabs::Migration::TRANSIENT_PREFIX, PuppetX::Puppetlabs::Migration::UNDEFINED_ID

Instance Method Summary collapse

Instance Method Details

#api_path(*segments) ⇒ Object



952
953
954
# File 'lib/puppet/application/preview.rb', line 952

def api_path(*segments)
  ::File.join(API_BASE, *segments)
end

#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:



114
115
116
117
118
119
# File 'lib/puppet/application/preview.rb', line 114

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

#assert_and_set_exit_codeObject



246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
# File 'lib/puppet/application/preview.rb', line 246

def assert_and_set_exit_code
  nodes = @overview.of_class(OverviewModel::Node)
  @exit_code =  nodes.reduce(0) do |result, node|
    exit_code = node.exit_code
    break exit_code if exit_code == BASELINE_FAILED
    exit_code > result ? exit_code : result
  end

  if @exit_code == CATALOG_DELTA
    case options[:assert]
    when :equal
      @exit_code = NOT_EQUAL if nodes.any? { |node| node.severity != :equal }
    when :compliant
      @exit_code = NOT_COMPLIANT if nodes.any? { |node| node.severity != :equal && node.severity != :compliant }
    end
  end
end

#catalog_diff(node, timestamp, baseline_hash, preview_hash) ⇒ Object



521
522
523
524
525
526
527
528
529
530
531
532
533
# File 'lib/puppet/application/preview.rb', line 521

def catalog_diff(node, timestamp, baseline_hash, preview_hash)
  excl_file = options[:excludes]
  excludes = excl_file.nil? ? [] : CatalogDeltaModel::Exclude.parse_file(excl_file)
  # Puppet 3 (Before PUP-3355) used a catalog format where the real data was under a
  # 'data' tag. After PUP-3355, the content outside 'data' was removed, and everything in
  # 'data' move up to the main body of "the hash".
  # Here this is normalized in order to support a mix of 3.x and 4.x catalogs.
  #
  baseline_hash = baseline_hash['data'] if baseline_hash.has_key?('data')
  preview_hash  = preview_hash['data']  if preview_hash.has_key?('data')
  delta_options = options.merge({:node => node})
  CatalogDeltaModel::CatalogDelta.new(baseline_hash, preview_hash, delta_options, timestamp, excludes)
end

#cleanObject



407
408
409
410
411
# File 'lib/puppet/application/preview.rb', line 407

def clean
  output_dir = Puppet[:preview_outputdir]
  node_names.each { |node| FileUtils.remove_entry_secure(File.join(output_dir, node)) }
  @exit_code = 0
end

#compileObject



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
306
307
308
309
310
311
312
313
314
315
316
317
318
# File 'lib/puppet/application/preview.rb', line 264

def compile
  # COMPILE
  #
  Puppet[:catalog_terminus] = :diff_compiler

  # Ensure that the baseline and preview catalogs are not stored via the
  # catalog indirection (may go to puppet-db)- The preview application
  # has its own output directory (and purpose).
  #
  # TODO: Is there a better way to disable the cache ?
  #
  Puppet::Resource::Catalog.indirection.cache_class = false

  factory = OverviewModel::Factory.new

  # Hash where the DiffCompiler can propagate things like the name of the compiled baseline_environment even if the
  # compilation fails.
  #
  options[:back_channel] = {}

  node_names.each do |node|

    begin
      # This call produces a catalog_delta, or sets @exit_code to something other than 0
      #
      timestamp = Time.now.iso8601(9)
      catalog_delta = compile_diff(node, timestamp)

      baseline_env = options[:back_channel][:baseline_environment]
      preview_env = options[:back_channel][:preview_environment]
      if baseline_env.to_s == preview_env.to_s && !options[:migrate]
        raise UsageError, "The baseline and preview environments for node '#{node}' are the same: '#{baseline_env}'"
      end

      if @exit_code == CATALOG_DELTA
        baseline_log = read_json(node, :baseline_log)
        preview_log = read_json(node, :preview_log)
        factory.merge(catalog_delta, baseline_log, preview_log)
        @latest_catalog_delta = catalog_delta
      else
        case @exit_code
        when BASELINE_FAILED
          display_log(options[:baseline_log])
          log = read_json(node, :baseline_log)
          factory.merge_failure(node, baseline_env, timestamp, @exit_code, log)
        when PREVIEW_FAILED
          display_log(options[:preview_log])
          log = read_json(node, :preview_log)
          factory.merge_failure(node, preview_env, timestamp, @exit_code, log)
        end
      end
    end
    @overview = factory.create_overview
  end
end

#compile_diff(node, timestamp) ⇒ Object



320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
# File 'lib/puppet/application/preview.rb', line 320

def compile_diff(node, timestamp)
  prepare_output(node)

  # Compilation start time
  @exit_code = 0

  begin

    # Do the compilations and get the catalogs
    unless result = Puppet::Resource::Catalog.indirection.find(node, options)
      # TODO: Should always produce a result and give better error depending on what failed
      #
      raise GeneralError, "Could not compile catalogs for #{node}"
    end

    # WRITE the two catalogs to output files
    baseline_as_resource = result[:baseline].to_resource
    preview_as_resource = result[:preview].to_resource

    Puppet::FileSystem.open(options[:baseline_catalog], 0640, 'wb') do |of|
      of.write(PSON::pretty_generate(baseline_as_resource, :allow_nan => true, :max_nesting => false))
    end
    Puppet::FileSystem.open(options[:preview_catalog], 0640, 'wb') do |of|
      of.write(PSON::pretty_generate(preview_as_resource, :allow_nan => true, :max_nesting => false))
    end

    # Make paths real/absolute
    options[:baseline_catalog] = options[:baseline_catalog].realpath
    options[:preview_catalog]  = options[:preview_catalog].realpath

    # DIFF
    #
    # Take the two catalogs and produce pure hash (no class information).
    # Produce a diff hash using the diff utility.
    #
    baseline_hash = JSON::parse(baseline_as_resource.to_pson)
    preview_hash  = JSON::parse(preview_as_resource.to_pson)

    catalog_delta = catalog_diff(node, timestamp, baseline_hash, preview_hash)

    Puppet::FileSystem.open(options[:catalog_diff], 0640, 'wb') do |of|
      of.write(PSON::pretty_generate(catalog_delta.to_hash, :allow_nan => true, :max_nesting => false))
    end

    catalog_delta

  rescue PuppetX::Puppetlabs::Preview::BaselineCompileError => e
    @exit_code = BASELINE_FAILED
    @exception = e

  rescue PuppetX::Puppetlabs::Preview::PreviewCompileError => e
    @exit_code = PREVIEW_FAILED
    @exception = e

  ensure
    terminate_logs
    Puppet::FileSystem.open(options[:compile_info], 0640, 'wb') do |of|
      compile_info = {
        :exit_code => @exit_code,
        :baseline_environment => options[:back_channel][:baseline_environment].to_s,
        :preview_environment => options[:back_channel][:preview_environment].to_s,
        :time => timestamp
      }
      of.write(PSON::pretty_generate(compile_info))
    end
    Puppet::Util::Log.close_all
    Puppet::Util::Log.newdestination(:console)
  end
end

#configure_indirector_routesObject



742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
# File 'lib/puppet/application/preview.rb', line 742

def configure_indirector_routes
  # Same implementation as the base Application class, except this loads
  # routes configured for the "master" application in order to conform with
  # the behavior of `puppet master --compile`
  #
  # TODO: In 4.0, this block can be replaced with:
  #     Puppet::ApplicationSupport.configure_indirector_routes('master')
  route_file = Puppet[:route_file]
  if Puppet::FileSystem.exist?(route_file)
    routes = YAML.load_file(route_file)
    application_routes = routes['master'] # <-- This line is the actual change.
    Puppet::Indirector.configure_routes(application_routes) if application_routes
  end

  # NOTE: PE 3.x ships PuppetDB 2.x and uses the v3 PuppetDB API endpoints.
  # These return stringified, non-structured facts. However, many Future
  # parser comparisons are type-sensitive. For example, a variable holding a
  # stringified fact will fail to compare against an integer.
  #
  # So, if PuppetDB is in use, we swap in a copy of the 2.x terminus which
  # uses the v4 API which returns properly structured and typed facts.
  if Puppet::Node::Facts.indirection.terminus_class.to_s == 'puppetdb'
    # Versions prior to pdb 3 uses the v3 REST API, but there is not easy
    # way to figure out which version is in use that works for both old
    # and new versions. The method 'Puppet::Util::Puppetdb.url_path' has
    # been removed in pdb 3 and is therefore used as a test. This means
    # that on pdb 3 catalog preview uses the default fact indirection.
    #
    require 'puppet/util/puppetdb'
    if Puppet::Util::Puppetdb.respond_to?(:url_path)
      Puppet::Node::Facts.indirection.terminus_class = :diff_puppetdb
    end
    # Ensure we don't accidentally use any facts that were cached from the
    # PuppetDB v3 API.
    Puppet::Node::Facts.indirection.cache_class = false
  end
end

#count_of(elements) ⇒ Object



716
717
718
719
# File 'lib/puppet/application/preview.rb', line 716

def count_of(elements)
  return 0 if elements.nil?
  elements.size
end

#display_existing_file(file, pretty_json) ⇒ Object



548
549
550
551
552
553
554
555
556
557
558
559
560
561
# File 'lib/puppet/application/preview.rb', line 548

def display_existing_file(file, pretty_json)
  out = output_stream
  if pretty_json
    Puppet::FileSystem.open(file, nil, 'rb') do |input|
      json = JSON.load(input)
      out.puts(PSON::pretty_generate(json, :allow_nan => true, :max_nesting => false))
    end
  else
    Puppet::FileSystem.open(file, nil, 'rb') do |source|
      FileUtils.copy_stream(source, out)
      out.puts '' # ensure a new line at the end
    end
  end
end

#display_file(file, pretty_json = false) ⇒ Object

Displays a file, and if the argument pretty_json is truthy the file is loaded and displayed as pretty json

Raises:



538
539
540
541
# File 'lib/puppet/application/preview.rb', line 538

def display_file(file, pretty_json=false)
  raise UsageError, "File '#{file} does not exist" unless File.exists?(file)
  display_existing_file(file, pretty_json)
end

#display_log(file_name) ⇒ Object

Displays colorized essential information from the log (severity, message, and location)



574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
# File 'lib/puppet/application/preview.rb', line 574

def display_log(file_name)
  data = JSON.load(file_name)
  # Output only the bare essentials
  # TODO: PRE-16 (the stacktrace is in the message)
  data.each do |entry|
    message = "#{level_label(entry['level'])}: #{entry['message']}"
    file = entry['file']
    line = entry['line']
    pos = entry['pos']
    if file && line && pos
      message << "at #{entry['file']}:#{entry['line']}:#{entry['pos']}"
    elsif file && line
      message << "at #{entry['file']}:#{entry['line']}"
    elsif file
      message << "at #{entry['file']}"
    end
    error_stream.puts  Colorizer.new.colorize(:hred, message)
  end
end

#display_node_file(node, file, pretty_json = false) ⇒ Object

Raises:



543
544
545
546
# File 'lib/puppet/application/preview.rb', line 543

def display_node_file(node, file, pretty_json=false)
  raise UsageError, "Preview data for node '#{node}' does not exist" unless File.exists?(file)
  display_existing_file(file, pretty_json)
end

#display_overview(overview, as_json) ⇒ Object

Outputs the given overview on ‘$stdout` or configured `:output_stream`. The output is either in JSON format or in textual form as determined by as_json.

Parameters:

  • overview (OverviewModel::Overview)

    the model to output

  • as_json (Boolean)

    true for JSON output, false for textual output



654
655
656
657
# File 'lib/puppet/application/preview.rb', line 654

def display_overview(overview, as_json)
  report = OverviewModel::Report.new(overview)
  output_stream.puts(as_json ? report.to_json : report.to_s)
end

#display_statusObject



693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
# File 'lib/puppet/application/preview.rb', line 693

def display_status

  node = @overview.of_class(OverviewModel::Node)[0]
  out = output_stream

  colorizer = Colorizer.new
  case node.exit_code
  when BASELINE_FAILED
    out.puts colorizer.colorize(:hred, "Node #{node.name} failed baseline compilation.")
  when PREVIEW_FAILED
    out.puts colorizer.colorize(:hred, "Node #{node.name} failed preview compilation.")
  when CATALOG_DELTA

    if node.severity == :equal
      out.puts colorizer.colorize(:green, "Catalogs for node '#{node}' are equal.")
    elsif node.severity == :compliant
      out.puts "Catalogs for '#{node.name}' are not equal but compliant."
    else
      out.puts "Catalogs for '#{node.name}' are neither equal nor compliant."
    end
  end
end

#display_summary(node, delta) ⇒ Object



598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
# File 'lib/puppet/application/preview.rb', line 598

def display_summary(node, delta)
  out = output_stream

  if delta
    compliant_count = delta.conflicting_resources.count {|r| r.compliant? }
    compliant_attr_count = delta.conflicting_resources.reduce(0) do |memo, r|
      memo + r.conflicting_attributes.count {|a| a.compliant? }
    end

    out.puts <<-TEXT

Catalog:
Versions......: #{delta.version_equal? ? 'equal' : 'different' }
Preview.......: #{delta.preview_equal? ? 'equal' : delta.preview_compliant? ? 'compliant' : 'conflicting'}
Tags..........: #{delta.tags_ignored? ? 'ignored' : 'compared'}
String/Numeric: #{delta.string_numeric_diff_ignored? ? 'numerically compared' : 'type significant compare'}

Resources:
Baseline......: #{delta.baseline_resource_count}
Preview.......: #{delta.preview_resource_count}
Equal.........: #{delta.equal_resource_count}
Compliant.....: #{compliant_count}
Missing.......: #{delta.missing_resource_count}
Added.........: #{delta.added_resource_count}
Conflicting...: #{delta.conflicting_resource_count - compliant_count}

Attributes:
Equal.........: #{delta.equal_attribute_count}
Compliant.....: #{compliant_attr_count}
Missing.......: #{delta.missing_attribute_count}
Added.........: #{delta.added_attribute_count}
Conflicting...: #{delta.conflicting_attribute_count - compliant_attr_count}

Edges:
Baseline......: #{delta.baseline_edge_count}
Preview.......: #{delta.preview_edge_count}
Missing.......: #{count_of(delta.missing_edges)}
Added.........: #{count_of(delta.added_edges)}

TEXT
  end

  out.puts <<-TEXT
Output:
For node......: #{Puppet[:preview_outputdir]}/#{node}

TEXT

end

#error_streamObject



956
957
958
# File 'lib/puppet/application/preview.rb', line 956

def error_stream
  options[:error_stream] || $stderr
end

#generate_last_overviewObject



673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
# File 'lib/puppet/application/preview.rb', line 673

def generate_last_overview
  factory = OverviewModel::Factory.new
  node_names.each do |node|
    prepare_output_options(node)

    compile_info = read_json(node, :compile_info)
    case compile_info['exit_code']
    when CATALOG_DELTA
      catalog_delta = CatalogDeltaModel::CatalogDelta.from_hash(read_json(node, :catalog_diff))
      factory.merge(catalog_delta, read_json(node, :baseline_log), read_json(node, :preview_log))
      @latest_catalog_delta = catalog_delta
    when BASELINE_FAILED
      factory.merge_failure(node, compile_info['time'], compile_info['baseline_environment'], 2, read_json(node, :baseline_log))
    when PREVIEW_FAILED
      factory.merge_failure(node, compile_info['time'], compile_info['preview_environment'], 3, read_json(node, :preview_log))
    end
  end
  @overview = factory.create_overview
end

#generate_statsObject



839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
# File 'lib/puppet/application/preview.rb', line 839

def generate_stats
  @overview.of_class(OverviewModel::Node).reduce(Hash.new(0)) do | result, node |
    case node.exit_code
    when BASELINE_FAILED
      result[:baseline_failed] += 1
    when PREVIEW_FAILED
      result[:preview_failed] += 1
    when CATALOG_DELTA
      result[:catalog_diff] += 1

      if node.severity == :equal
        result[:equal] += 1
      elsif node.severity == :compliant
        result[:compliant] += 1
      end
    end
  result
  end
end

#helpObject



104
105
106
# File 'lib/puppet/application/preview.rb', line 104

def help
  Puppet::FileSystem.read(api_path('documentation', 'preview-help.md'))
end

#lastObject



390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
# File 'lib/puppet/application/preview.rb', line 390

def last
  node_directories = Dir["#{Puppet[:preview_outputdir]}/*"]
  if node_directories.empty?
    raise UsageError, "There is no preview data in the specified output directory "\
      "'#{Puppet[:preview_outputdir]}', you must have data from a previous preview run to use --last"
  else
    available_nodes = node_directories.map { |dir| dir.match(/^.*\/([^\/]*)$/)[1] }

    unless (missing_nodes = node_names - available_nodes).empty?
      raise UsageError, "No preview data available for node(s) '#{missing_nodes.join(", ")}'"
    end

    generate_last_overview
    view
  end
end

#latest_catalog_delta=(catalog_delta) ⇒ Object



155
156
157
# File 'lib/puppet/application/preview.rb', line 155

def latest_catalog_delta=(catalog_delta)
  @latest_catalog_delta = catalog_delta
end

#level_label(level) ⇒ Object



563
564
565
566
567
568
569
570
# File 'lib/puppet/application/preview.rb', line 563

def level_label(level)
  case level
  when :err, 'err'
    'ERROR'
  else
    level.to_s.upcase
  end
end

#mainObject



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
238
239
240
241
242
243
244
# File 'lib/puppet/application/preview.rb', line 159

def main
  if options[:clean]
    unless (options.keys - [:clean, :node, :nodes, :debug]).empty?
      raise UsageError, '--clean can only be used with options --nodes and --debug'
    end
    clean
    return @exit_code
  end

  if options[:excludes]
    raise UsageError, '--excludes cannot be used with --schema or --last' if options[:last] || options[:schema]
  end

  # Issue a deprecation warning unless JSON output is expected to avoid that the warning invalidates the output
  if options.include?(:trusted) && ![:overview_json, :baseline_log, :preview_log].include?(options[:view])
    Puppet.deprecation_warning('The --trusted option is deprecated and has no effect')
  end

  if options[:schema]
    unless options[:nodes].empty?
      raise UsageError,
        'One or more nodes were given but no compilation will be done when running with the --schema option'
    end

    case options[:schema]
    when :catalog
      catalog_path = api_path('schemas', 'catalog.json')
      display_file(catalog_path)
    when :catalog_delta
      delta_path = api_path('schemas', 'catalog-delta.json')
      display_file(delta_path)
    when :log
      log_path = api_path('schemas', 'log.json')
      display_file(log_path)
    when :excludes
      excludes_path = api_path('schemas', 'excludes.json')
      display_file(excludes_path)
    else
      help_path = api_path('documentation', 'catalog-delta.md')
      display_file(help_path)
    end
    @exit_code = 0
  else
    if options[:nodes].nil? || options[:nodes].empty? && !options[:last]
      raise UsageError, 'No node(s) given to perform preview compilation for'
    end

    if node_names.size > 1 && [:diff, :baseline, :preview, :baseline_log, :preview_log].include?(options[:view])
      raise UsageError, "The --view option '#{options[:view].to_s.gsub(/_/, '-')}' is not supported for multiple nodes"
    end

    if options[:last]
      last
      @exit_code = 0
    else
      unless options[:preview_environment] || options[:migrate]
        raise UsageError, 'Neither --preview_environment or --migrate given - cannot compile and produce a diff "\
              "when only the environment of the node is known'
      end

      if options.include?(:diff_string_numeric)
        if options[:migrate] != MIGRATION_3to4
          raise UsageError, '--diff-string-numeric can only be used in combination with --migrate 3.8/4.0'
        end
      else
        # the string/numeric diff is ignored when migrating from 3 to 4
        options[:diff_string_numeric] = options[:migrate] != MIGRATION_3to4
      end

      if options.include?(:diff_array_value)
        if options[:migrate] != MIGRATION_3to4
          raise UsageError, '--diff-array-value can only be used in combination with --migrate 3.8/4.0'
        end
      else
        options[:diff_array_value] = true # this is the default
      end

      compile

      view

      assert_and_set_exit_code
    end
  end
  @exit_code
end

#multi_node_status(stats) ⇒ Object



900
901
902
903
904
905
906
907
908
909
910
911
912
# File 'lib/puppet/application/preview.rb', line 900

def multi_node_status(stats)
  output_stream.puts <<-TEXT

Summary:
Total Number of Nodes...: #{@overview.of_class(OverviewModel::Node).length}
Baseline Failed.........: #{stats[:baseline_failed]}
Preview Failed..........: #{stats[:preview_failed]}
Catalogs with Difference: #{stats[:catalog_diff]}
Compliant Catalogs......: #{stats[:compliant]}
Equal Catalogs..........: #{stats[:equal]}

TEXT
end

#multi_node_summaryObject



859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
# File 'lib/puppet/application/preview.rb', line 859

def multi_node_summary
  summary = Hash[[ :equal, :compliant, :conflicting, :error ].map do |severity|
    [severity, @overview.of_class(OverviewModel::Node).select { |n| n.severity == severity }.sort.map do |n|
      { :name => n.name,
        :baseline_env => n.baseline_env.name,
        :preview_env => n.preview_env.name,
        :exit_code => n.exit_code
      }
    end]
  end]

  out = output_stream

  summary.each do |category, nodes|
    case category
    when :error
      nodes.each do |node|
        if node[:exit_code] == BASELINE_FAILED
          out.puts Colorizer.new.colorize(:red, "baseline failed (#{node[:baseline_env]}): #{node[:name]}")
        elsif node[:exit_code] == PREVIEW_FAILED
          out.puts Colorizer.new.colorize(:red, "preview failed (#{node[:preview_env]}): #{node[:name]}")
        else
          out.puts Colorizer.new.colorize(:red, "general error (#{node[:preview_env]}): #{node[:name]}")
        end
      end
    when :conflicting
      nodes.each do |node|
        out.puts "catalog delta: #{node[:name]}"
      end
    when :compliant
      nodes.each do |node|
        out.puts "compliant: #{node[:name]}"
      end
    when :equal
      nodes.each do |node|
        out.puts Colorizer.new.colorize(:green, "equal: #{node[:name]}")
      end
    end
  end
end

#node_namesObject



413
414
415
416
417
418
419
420
421
422
423
424
425
# File 'lib/puppet/application/preview.rb', line 413

def node_names
  # If no nodes were specified, print everything we have
  if @node_names.nil?
    given_names = options[:nodes]
    @node_names = if given_names.nil? || given_names.empty?
      # Use the directories in preview_outputdir to get the list of nodes
      Dir.glob(File.join(Puppet[:preview_outputdir], '*')).select { |f| File.directory?(f) }.map { |f| File.basename(f) }
    else
      given_names
    end
  end
  @node_names
end

#output_streamObject



960
961
962
# File 'lib/puppet/application/preview.rb', line 960

def output_stream
  options[:output_stream] || $stdout
end

#preinitObject



121
122
123
124
125
126
127
128
129
# File 'lib/puppet/application/preview.rb', line 121

def preinit
  Signal.trap(:INT) do
    $stderr.puts 'Canceling startup'
    exit(0)
  end

  # save ARGV to protect us from it being smashed later by something
  @argv = ARGV.dup
end

#prepare_output(node) ⇒ Object



505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
# File 'lib/puppet/application/preview.rb', line 505

def prepare_output(node)
  prepare_output_options(node)

  # Truncate all output files to ensure output is not a mismatch of old and new
  Puppet::FileSystem.open(options[:baseline_log], 0660, 'wb') { |of| of.write('') }
  Puppet::FileSystem.open(options[:preview_log],  0660, 'wb') { |of| of.write('') }
  Puppet::FileSystem.open(options[:baseline_catalog], 0660, 'wb') { |of| of.write('') }
  Puppet::FileSystem.open(options[:preview_catalog],  0660, 'wb') { |of| of.write('') }
  Puppet::FileSystem.open(options[:catalog_diff], 0660, 'wb') { |of| of.write('') }
  Puppet::FileSystem.open(options[:compile_info], 0660, 'wb') { |of| of.write('') }

  # make the log paths absolute (required to use them as log destinations).
  options[:preview_log]      = options[:preview_log].realpath
  options[:baseline_log]     = options[:baseline_log].realpath
end

#prepare_output_options(node) ⇒ Object



484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
# File 'lib/puppet/application/preview.rb', line 484

def prepare_output_options(node)
  # TODO: Deal with the output directory
  # It should come from a puppet setting which user can override - that currently does not exist
  # while developing simply write files to CWD
  options[:output_dir] = Puppet[:preview_outputdir] # "./PREVIEW_OUTPUT"

  # Make sure the output directory for the node exists
  node_output_dir = Puppet::FileSystem.pathname(File.join(options[:output_dir], node))
  options[:node_output_dir] = node_output_dir
  Puppet::FileSystem.mkpath(options[:node_output_dir])
  Puppet::FileSystem.chmod(0750, options[:node_output_dir])

  # Construct file name for this diff
  options[:baseline_catalog] = Puppet::FileSystem.pathname(File.join(node_output_dir, 'baseline_catalog.json'))
  options[:baseline_log]     = Puppet::FileSystem.pathname(File.join(node_output_dir, 'baseline_log.json'))
  options[:preview_catalog]  = Puppet::FileSystem.pathname(File.join(node_output_dir, 'preview_catalog.json'))
  options[:preview_log]      = Puppet::FileSystem.pathname(File.join(node_output_dir, 'preview_log.json'))
  options[:catalog_diff]     = Puppet::FileSystem.pathname(File.join(node_output_dir, 'catalog_diff.json'))
  options[:compile_info]     = Puppet::FileSystem.pathname(File.join(node_output_dir, 'compile_info.json'))
end


914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
# File 'lib/puppet/application/preview.rb', line 914

def print_node_list
  nodes = Hash[[ :equal, :compliant, :conflicting, :error ].map do |severity|
    [severity, @overview.of_class(OverviewModel::Node).select { |n| n.severity == severity }.sort.map do |n|
      n.name
    end]
  end]

  out = output_stream
  if options[:view] == :equal_nodes
    nodes[:equal].each do |node|
      out.puts node
    end
  elsif options[:view] == :compliant_nodes
    nodes[:compliant].each do |node|
      out.puts node
    end
    nodes[:equal].each do |node|
      out.puts node
    end
  else
    nodes[:error].each do |node|
      out.puts node
    end
    if options[:view] == :diff_nodes
      nodes[:conflicting].each do |node|
        out.puts node
      end
      if options[:assert] == :equal
        nodes[:compliant].each do |node|
          out.puts node
        end
      end
    end
  end
end

#read_json(node, type) ⇒ Object

Raises:

  • (Puppet::Error)


659
660
661
662
663
664
665
666
667
668
669
670
671
# File 'lib/puppet/application/preview.rb', line 659

def read_json(node, type)
  filename = options[type]
  json = nil
  source = File.read(filename)
  unless source.nil? || source.empty?
    begin
      json = JSON.load(source)
    rescue JSON::ParserError
    end
  end
  raise Puppet::Error, "Output for node #{node} is invalid - use --clean and/or recompile" if json.nil?
  json
end

#run_commandObject



131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
# File 'lib/puppet/application/preview.rb', line 131

def run_command
  nodes = options[:nodes]
  if nodes.nil?
    nodes = command_line.args
  else
    nodes += command_line.args
  end
  options[:nodes] = nodes.uniq

  begin
    main
  rescue UsageError => err
    raise RuntimeError, err.message
  rescue Exception => err
    ## NOTE: when debugging spec failures, these two lines can be very useful
    #puts err.inspect
    #puts Puppet::Util.pretty_backtrace(err.backtrace)
    Puppet.log_exception(err)
    Puppet::Util::Log.force_flushqueue()
    @exit_code = GENERAL_ERROR
  end
  exit(@exit_code)
end

#setupObject

Raises:

  • (Puppet::Error)


815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
# File 'lib/puppet/application/preview.rb', line 815

def setup
  raise Puppet::Error, 'Puppet preview is not supported on Microsoft Windows' if Puppet.features.microsoft_windows?

  # Make process owner current user unless process owner is 'root'
  unless Puppet.features.root?
    Puppet[:user] = Etc.getpwuid(Process.uid).name
    Puppet[:group] = Etc.getgrgid(Process.gid).name
  end

  setup_logs

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

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

  setup_terminuses

  # TODO: Do we need this in preview? It sets up a write only cache
  setup_node_cache

  setup_ssl
end

#setup_logsObject



721
722
723
724
725
726
727
# File 'lib/puppet/application/preview.rb', line 721

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_node_cachevoid

This method returns an undefined value.

Sets up a special node cache “write only yaml” that collects and stores node data in yaml but never finds or reads anything (this since a real cache causes stale data to be served in circumstances when the cache can not be cleared).

See Also:

  • issue 16753
  • Node::WriteOnlyYaml


811
812
813
# File 'lib/puppet/application/preview.rb', line 811

def setup_node_cache
  Puppet::Node.indirection.cache_class = Puppet[:node_cache_terminus]
end

#setup_sslObject



790
791
792
793
794
795
796
797
798
799
800
801
802
803
# File 'lib/puppet/application/preview.rb', line 790

def setup_ssl
  # Configure all of the SSL stuff.
  if Puppet::SSL::CertificateAuthority.ca?
    Puppet::SSL::Host.ca_location = :local
    Puppet.settings.use :ca
    Puppet::SSL::CertificateAuthority.instance
  else
    Puppet::SSL::Host.ca_location = :none
  end
  # These lines are not on stable (seems like a copy was made from master)
  #
  # Puppet::SSL::Oids.register_puppet_oids
  # Puppet::SSL::Oids.load_custom_oid_file(Puppet[:trusted_oid_mapping_file])
end

#setup_terminusesObject



780
781
782
783
784
785
786
787
788
# File 'lib/puppet/application/preview.rb', line 780

def setup_terminuses
  require 'puppet/file_serving/content'
  require '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

#terminate_log(filename) ⇒ Object



734
735
736
737
738
739
740
# File 'lib/puppet/application/preview.rb', line 734

def terminate_log(filename)
  # Terminate a JSON log (the final ] is missing, and it must be provided to produce correct JSON)
  # Also, if nothing was logged, the opening [ is required, or the file will not be valid JSON
  #
  endtext = Puppet::FileSystem.size(filename) == 0 ? "[\n]\n" : "\n]\n"
  Puppet::FileSystem.open(filename, nil, 'ab') { |of| of.write(endtext) }
end

#terminate_logsObject



729
730
731
732
# File 'lib/puppet/application/preview.rb', line 729

def terminate_logs
  terminate_log(options[:baseline_log])
  terminate_log(options[:preview_log])
end

#viewObject



444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
# File 'lib/puppet/application/preview.rb', line 444

def view
  # Produce output as directed by the :view option
  #
  case options[:view]
  when :diff, :baseline_log, :preview_log, :baseline, :preview
    node_names.each do |node|
      prepare_output_options(node)
      view_node(node)
    end
  when :status
    if node_names.size > 1
      multi_node_status(generate_stats)
    else
      display_status
    end
  when :failed_nodes
    print_node_list
  when :diff_nodes
    print_node_list
  when :equal_nodes
    print_node_list
  when :compliant_nodes
    print_node_list
  when :overview
    display_overview(@overview, false)
  when :overview_json
    display_overview(@overview, true)
  when :none
    # print nothing
  else
    if node_names.size > 1
      multi_node_status(generate_stats)
      multi_node_summary
    else
      display_summary(node_names[0], @latest_catalog_delta) unless @latest_catalog_delta.nil?
      display_status
    end
  end
end

#view_node(node) ⇒ Object



427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
# File 'lib/puppet/application/preview.rb', line 427

def view_node(node)
  # Produce output as directed by the :view option
  #
  case options[:view]
  when :diff
    display_node_file(node, options[:catalog_diff])
  when :baseline_log
    display_node_file(node, options[:baseline_log], true)
  when :preview_log
    display_node_file(node, options[:preview_log], true)
  when :baseline
    display_node_file(node, options[:baseline_catalog])
  when :preview
    display_node_file(node, options[:preview_catalog])
  end
end