8 =head1 NAME $RCSfile: cleantmp.pl,v $
10 Keep /tmp clean based on filesets
18 Andrew DeFaria <Andrew@DeFaria.com>
26 Wed Feb 21 20:43:58 PST 2018
36 Usage: cleantmp.pl [-u|sage] [-h|elp] [-v|erbose] [-d|ebug]
37 [-t|mp <dir>] [-c|onf <file>] [-l|ogpath <path>]
41 -u|sage Print this usage
43 -v|erbose: Verbose mode
44 -d|ebug: Print debug messages
45 -t|mp <dir>: Tmp directory to monitor (Default: /tmp)
46 -c|onf <file>: Config file holding patterns to match (Default:
47 .../etc/cleantmp.conf)
48 -l|ogpath <path>: Path to logfile (Default: /var/log)
49 -s|leep <secs>: How many seconds to sleep between polls (Default: 60)
53 This script will run in the background and keep /tmp clean. It will read in a
54 list of Perl regexs from the config file. When new files are created in tmp they
55 will be compared against the list of regexs and if there's a match the file or
56 directory will be removed.
58 The sleep parameter tells us how long to wait before polling for changes again
67 use File::Path qw/remove_tree/;
69 use lib "$FindBin::Bin/../lib";
75 my ($script) = ($FindBin::Script =~ /^(.*)\.pl/);
79 usage => sub { pod2usage },
80 help => sub { pod2usage(-verbose => 2)},
81 verbose => sub { set_verbose },
82 debug => sub { set_debug },
83 tmp => File::Spec->tmpdir(),
84 conf => "$FindBin::Bin/../etc/$script.conf",
85 logpath => '/var/log',
92 open my $patterns, '<', $opts{conf}
93 or $log->err("Unable to open $opts{conf} - $!", 1);
96 next if /^\s*#/; # Skip comments
109 my ($name, $event, $change) = @_;
111 opendir my $dir, $opts{tmp}
112 or $log->err("Unable to open $opts{tmp} - $!", 1);
114 while (my $createdFile = readdir $dir) {
115 next if $createdFile =~ /^\./; # Skip all hidden files
117 for my $pattern (loadConfig) {
118 debug "Processing pattern $pattern";
120 if ($createdFile =~ /$pattern/) {
121 debug "Matched $createdFile to $pattern";
123 if (-d "$opts{tmp}/$createdFile") {
124 remove_tree ("$opts{tmp}/$createdFile", {error => \my $err});
127 for my $diag (@$err) {
128 my ($file, $message) = %$diag;
131 $log->err("General error: $message");
133 $log->err("Unable to delete $file: $message");
137 $log->msg("$opts{tmp}/$createdFile removed");
140 unless (unlink "$opts{tmp}/$createdFile") {
141 $log->err("Unable to remove $opts{tmp}/$createdFile - $!");
143 $log->msg("$opts{tmp}/$createdFile removed");
169 $log = Logger->new(path => $opts{logpath}, timestamped => 1);
171 $log->msg("Starting $FindBin::Script");
173 # First run through whatever junk is in /tmp
174 for (glob "$opts{tmp}/*") {
178 my $monitor = File::Monitor->new;
183 callback => {files_created => \&FileCreated}
186 set_debug if $DB::OUT;
188 EnterDaemonMode unless $DB::OUT or get_debug;