1+ # frozen_string_literal: true
2+
3+ require 'puppet'
4+ require 'fileutils'
5+
6+ SEPARATOR = [ Regexp . escape ( File ::SEPARATOR . to_s ) , Regexp . escape ( File ::ALT_SEPARATOR . to_s ) ] . join
7+
8+ Puppet ::Reports . register_report ( :store_latest ) do
9+ desc "Store the yaml report on disk. Each host sends its report as a YAML dump
10+ and this just stores the file on disk, in the `reportdir` directory.
11+
12+ Only keep the latest available."
13+
14+ def process
15+ validate_host ( host )
16+
17+ dir = File . join ( Puppet [ :reportdir ] , host )
18+
19+ unless Puppet ::FileSystem . exist? ( dir )
20+ FileUtils . mkdir_p ( dir )
21+ FileUtils . chmod_R ( 0o750 , dir )
22+ end
23+
24+ # Now store the report.
25+ name = "latest.yaml"
26+
27+ file = File . join ( dir , name )
28+
29+ begin
30+ Puppet ::FileSystem . replace_file ( file , 0o640 ) do |fh |
31+ fh . print to_yaml
32+ end
33+ rescue => detail
34+ Puppet . log_exception ( detail , "Could not write report for #{ host } at #{ file } : #{ detail } " )
35+ end
36+
37+ # Only testing cares about the return value
38+ file
39+ end
40+
41+ # removes all reports for a given host?
42+ def self . destroy ( host )
43+ validate_host ( host )
44+
45+ dir = File . join ( Puppet [ :reportdir ] , host )
46+
47+ if Puppet ::FileSystem . exist? ( dir )
48+ Dir . entries ( dir ) . each do |file |
49+ next if [ '.' , '..' ] . include? ( file )
50+
51+ file = File . join ( dir , file )
52+ Puppet ::FileSystem . unlink ( file ) if File . file? ( file )
53+ end
54+ Dir . rmdir ( dir )
55+ end
56+ end
57+
58+ def validate_host ( host )
59+ if host =~ Regexp . union ( /[#{ SEPARATOR } ]/ , /\A \. \. ?\Z / )
60+ raise ArgumentError , _ ( "Invalid node name %{host}" ) % { host : host . inspect }
61+ end
62+ end
63+ module_function :validate_host
64+ end
0 commit comments