+sub hkfail ($) { my ($msg) = @_; fail "housekeeping: $msg"; }
+
+sub housekeeping () {
+ logm 'info', "housekeeping started";
+ foreach $lock (<[a-z]*\\.lock>) {
+ my $subdir = $lock; $subdir =~ s/\\.lock$//;
+ if (!lstat $lock) {
+ $! == ENOENT or hkfail "$lock: lstat: $!";
+ next;
+ }
+ if (-M _ <= $treeexpiredays) {
+ logm 'debug', "housekeeping: subdirs $subdir: touched recently";
+ next;
+ }
+ if (!lockfile \*LOCK, $lock, LOCK_EX|LOCK_NB) {
+ logm 'info', "housekeeping: subdirs $subdir: lock busy, skipping";
+ next;
+ }
+ logm 'info', "housekeeping: subdirs $subdir: cleaning";
+ eval {
+ foreach my $suffix (qw(tmp git)) {
+ my $dir = "${subdir}\\.$suffix";
+ my $tdir = "${subdir}\\.tmp";
+ if ($dir ne $tdir) {
+ if (!rename $dir,$tdir) {
+ next if $! == ENOENT;
+ die "$dir: cannot rename to $tdir: $!\n";
+ }
+ }
+ system qw(rm -rf --), $tdir;
+ if (stat $tdir) {
+ die "$dir: problem deleting file(s), rm exited $?\n";
+ } elsif ($! != ENOENT) {
+ die "$tdir: cannot stat after deletion: $!\n";
+ }
+ }
+ };
+ if (length $@) {
+ chomp $@;
+ logm 'warning', "housekeeping: $subdir: cleanup prevented: $@";
+ } else {
+ unlink $lock or hkfail "remove $lock: $!";
+ }
+ }
+ open HS, ">", "Housekeeping.stamp" or hkfail "touch Housekeeping.stamp: $!";
+ close HS or hkfail "close Housekeeping.stamp: $!";
+ logm 'info', "housekeeping finished";
+}
+
+sub housekeepingcheck ($$) {
+ my ($dofork, $force) = @_;
+ if (!$force) {
+ if (!lockfile \*HLOCK, "Housekeeping.lock", LOCK_EX|LOCK_NB) {
+ logm 'debug', "housekeeping lock taken, not running";
+ close HLOCK;
+ return 0;
+ }
+ }
+ if ($force) {
+ logm 'info', "housekeeping forced";
+ } elsif (!lstat "Housekeeping.stamp") {
+ $! == ENOENT or fail "lstat Housekeeping.stamp: $!";
+ logm 'info', "housekeeping not done yet, will run";
+ } elsif (-M _ <= $housekeepingeverydays) {
+ logm 'debug', "housekeeping done recently";
+ close HLOCK;
+ return 0;
+ }
+ if ($dofork) {
+ my $child = fork;
+ defined $child or fail "fork: $!";
+ if (!$child) {
+ open STDERR, "|logger -p daemon.warning -t '$us(housekeeping)'"
+ or die "fork: logger $!";
+ housekeeping();
+ exit 0;
+ }
+ } else {
+ housekeeping();
+ }
+ close HLOCK;
+ return 1;
+}
+