chiark / gitweb /
expire-iso8601: clean up old .rm
[chiark-utils.git] / scripts / expire-iso8601
1 #!/usr/bin/perl -w
2 #
3 # Copyright 2006 Ian Jackson <ijackson@chiark.greenend.org.uk>
4 #
5 # This script and its documentation (if any) are free software; you
6 # can redistribute it and/or modify them under the terms of the GNU
7 # General Public License as published by the Free Software Foundation;
8 # either version 3, or (at your option) any later version.
9
10 # chiark-named-conf and its manpage are distributed in the hope that
11 # it will be useful, but WITHOUT ANY WARRANTY; without even the
12 # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
13 # PURPOSE.  See the GNU General Public License for more details.
14
15 # You should have received a copy of the GNU General Public License along
16 # with this program; if not, consult the Free Software Foundation's
17 # website at www.fsf.org, or the GNU Project website at www.gnu.org.
18
19 use strict;
20
21 our $usage = <<'END';
22 usage:
23   expire-iso8601 [<options>] <number>x<interval> [<number>x<interval> ...]
24 options:
25    -u<unitlen>  <interval> is measured in units of <unitlen> seconds
26                    (default is 86400, so <interval> is in days)
27    -s<slop>     allow kept items to be <slop> seconds shorter apart than
28                    specified; default is 10% of <unitlen>
29    -n           do not really delete
30    -r           recursive removal (rm -r)
31 example:
32    /home/ian/junk/expire-iso8601 14x1 4x7
33       uses units of 86400s (1 day) with a slop of 8640
34       it keeps 14 daily items
35        (that is 14 items, dated no less than 86400-8640 apart)
36       and 4 weekly items
37        (that is 4 items, dated no less than 7*86400-8640 apart)
38       the 14 daily and 7 weekly items may be the same, or not
39    There is no need to sort the list of <number>x<interval> pairs.
40 exit status:
41    0                   ok
42    4                   rm failed
43    8                   bad usage
44    16                  catastrophic failure
45 END
46
47 use POSIX;
48 use Carp;
49 use Data::Dumper;
50 use Date::Parse;
51 use DateTime::Format::Strptime;
52
53 $|=1;
54
55 our @oldfiles;
56 our @files;
57 our $rm = 1;
58 our $recurse = 1;
59 our $unit = 86400;
60 our $slop;
61 our $debug = 0;
62 our @intervals;
63
64 sub badusage ($) {
65   print STDERR "bad usage: $_[0]\n$usage" or die $!;
66   exit 8;
67 }
68
69 sub scan () {
70 #  my $strp = DateTime::Format::Strptime->new();
71   foreach my $f (<[0-9]*>) {
72     if ($f  !~ m/^ \d\d\d\d - \d\d - \d\d 
73                  (?: T \d\d \: \d\d (?: \: \d\d )?
74                    (?: [-+] \d{1,2} \:? \d\d )? )? 
75                  ( \.rm )? $/x) {
76       print STDERR "ignoring $f\n";
77     }
78
79     if ($1) {
80       push @oldfiles, $f;
81       next;
82     }
83
84     my @t = Date::Parse::strptime($f);
85     @t = map { $_ // 0 } @t;
86     my $t = mktime @t;
87 #    m
88 #    my $t = $strp->parse_datetime($f);
89 #    $t = $t->epoch();
90 #    my @t = Date::Parse::strptime($f);
91 #print STDERR Dumper(\@t);
92 #    my $t = mktime(@t);
93 #    $!=0; $?=0; my $t = `date -d '$&' +%s`;
94 #    die "date(!) failed on $&: $? $!" if $! || $?;
95 #    chomp $t or confess;
96     push @files, { F => $f, T => $t, U => [] };
97   }
98 }
99
100 sub precomp () {
101   if (!@files) {
102     print STDERR "none at all yet!\n";
103     exit 0;
104   }
105
106   # newest first, which means biggest T
107   @files = sort { $b->{T} <=> $a->{T} || $b->{F} cmp $a->{F} } @files;
108   my $newest_t = $files[0]{T};
109   $_->{A} = ($newest_t - $_->{T}) / $unit foreach @files;
110   $slop /= $unit;
111
112   push @{$files[0]{U}}, "newest";
113
114   print DEBUG Dumper(scalar(@files), \@files, \@intervals) if $debug >= 2;
115 }
116
117 sub flag ($) {
118   my ($int) = @_;
119   my $n = $int->{N};
120   my $d = $int->{D};
121   my $dmin = $d - $slop;
122   my $dmax = $d + $slop;
123   my $spec = $int->{Spec};
124   my $start_age = ($n-1) * $d - $slop;
125   my $i = 0;
126   my $insufficiently_old = 0;
127
128   print DEBUG "FLAG $spec sa=$start_age dmin=$dmin dmax=$dmax\n";
129
130   # find $i, the youngest which is at least $start_age
131   for (;;) {
132     print DEBUG "i #$i $files[$i]{A}\n";
133     last if $files[$i]{A} >= $start_age;
134     if ($i == $#files) {
135       $insufficiently_old = 1;
136       print STDERR "insufficiently old for $spec\n";
137       last;
138     }
139     $i++;
140   }
141
142   my $oldest = $i;
143   my $count = 0;
144
145   my $use = sub {
146     my ($i, $spec) = @_;
147     push @{ $files[$i]{U} }, $spec;
148     $count++;
149   };
150
151   for (;;) {
152     $use->($i, $spec);
153
154     # find $j, the closest to $i, preferably no more than $dmax younger
155     my $j = $i;
156     for (;;) {
157       $j--;
158       # at each point in this loop $j is the next candidate
159       last if $j < 0;
160       my $dt = $files[$i]{A} - $files[$j]{A};
161       print DEBUG "j #$j $files[$j]{A} dt=$dt\n";
162       last if $dt > $dmax;
163     }
164     $j++;
165     if ($j == $i) {
166       $j--;
167       print STDERR "insufficiently dense for $spec after $files[$j]{F}\n";
168       last if $j < 0;
169     }
170     print DEBUG "i #$j\n";
171
172     $i = $j;
173   }
174
175   $i = $oldest;
176   while ($count < $n) {
177     for (;;) {
178       $i++;
179       if ($i > $#files) {
180         if (!$insufficiently_old) {
181           print STDERR
182             "insufficiently old for $spec (density compensation)\n";
183         }
184         return;
185       }
186       my $dt = $files[$i]{A} - $files[$oldest]{A};
187       print DEBUG "o #$i $files[$i]{A} dt=$dt\n";
188       last if $dt >= $dmin;
189     }
190     $use->($i, "$spec+");
191   }
192 }
193
194 sub do_rm ($) {
195   my ($fn) = @_;
196   if ($rm) {
197     my $r= system 'rm', ($recurse ? ('-r') : ()), "--", $fn;
198     die "run rm: $!\n" unless defined($r) && $r >= 0;
199     exit 12 if $r;
200   }
201 }
202
203 sub implement () {
204   foreach (reverse sort @oldfiles) {
205     printf "remove %s - old\n", $_;
206     do_rm($_);
207   }
208   foreach (reverse @files) {
209     next unless @{$_->{U}};
210     printf "keep %s for %s - age %.1f\n",
211       $_->{F}, "@{$_->{U}}", $_->{A};
212   }
213   foreach (reverse @files) {
214     next if @{$_->{U}};
215     printf "remove %s - age %.1f\n",
216       $_->{F}, $_->{A};
217     if ($rm) {
218       my $tmp = "$_->{F}.rm";
219       rename $_->{F}, $tmp or die "rename $_->{F} to $tmp: $!\n";
220       do_rm($tmp);
221     }
222   }
223 }
224
225 open DEBUG, ">/dev/null" or die $!;
226
227 while (@ARGV && $ARGV[0] =~ m/^-/) {
228   $_ = shift @ARGV;
229   last if $_ eq '-' || $_ eq '--';
230   if (m/^-[^-]/) {
231     while (m/^-./) {
232       if (s/^-n/-/) { $rm=0; }
233       elsif (s/-r/-/) { $recurse=1; }
234       elsif (s/-D/-/) { $debug++; }
235       elsif (s/-u(\d+)$//) { $unit=$1; }
236       elsif (s/-s(\d+)$//) { $slop=$1; }
237       else { badusage "unknown short option $_" }
238     }
239   } elsif (m/^--help$/) {
240     print $usage or die $!;
241     exit 0;
242   } else {
243     badusage "unknown long option $_"
244   }
245 }
246
247 badusage "too few arguments" unless @ARGV;
248
249 if ($debug) {
250   open DEBUG, ">&STDERR" or die $!;
251   DEBUG->autoflush(1);
252 }
253
254 $slop //= $unit * 0.1;
255
256 foreach (@ARGV) {
257   m/^(\d+)x(\d+)$/ or badusage "bad <number>x<interval> $_";
258   push @intervals, { Spec => $&, N => $1, D => $2 };
259 }
260
261 scan();
262 precomp();
263 foreach (@intervals) { flag $_ }
264 implement();