zfs list -t snapshot fix for newer zfs versions which don't return snapshots by default
[sysadmin-cookbook] / recepies / zfs / zfs-expire-snapshot.pl
1 #!/usr/bin/perl
2
3 use warnings;
4 use strict;
5
6 use DateTime;
7 use Data::Dump qw/dump/;
8
9 my $debug = $ENV{DEBUG} || 0;
10
11 my $config = {
12         'default' => {
13                 21 => 5,
14                 30 => 10,
15                 90 => 30,
16         },
17         '212052' => {   # koha-dev
18                 7 => 10,
19                 14 => 30,
20         },
21         '212056' => {   # webpac2
22                 7 => 5,
23                 14 => 30,
24         }
25 };
26
27 my $now = DateTime->now();
28
29 my $last_backup;
30
31 open(my $fs, '-|', 'zfs list -t snapshot -H');
32 while(<$fs>) {
33         chomp;
34         my ( $name, $used, $avail, $refer, $mountpoint ) = split(/\t/,$_,6);
35
36         next unless $name =~ m{(.+)@(\d\d\d\d)-(\d\d)-(\d\d)};
37
38         my $host = $1;
39
40         my $date = DateTime->new( year => $2, month => $3, day => $4 );
41
42         my $age = $now->delta_days( $date )->delta_days;
43
44         my $op = ' ';
45         my $last = 0;
46
47         my $c = (grep { $host =~ m{\Q$_\E} } keys %$config)[0];
48         $c = 'default' unless defined $c;
49
50         warn "# config: $c\n" if $debug;
51
52         my $h = $host;
53         $h =~ s{,+/([^/]+)$}{}; # just hostname without path
54
55         $c = $config->{$c} || die "can't find config for $c";
56
57         warn "# c = ",dump($c) if $debug;
58
59         my $keep_every_days;
60         my $older_than_days;
61         foreach ( sort { $b <=> $a } keys %$c ) {
62                 $older_than_days = $_;
63                 $keep_every_days = $c->{$_};
64                 warn "## $host $age > $older_than_days" if $debug;
65                 last if $age > $older_than_days;
66         }
67
68         my $config_applied = '';
69
70         if ( $age > $older_than_days ) {
71
72                 $config_applied = "> $older_than_days keep $keep_every_days";
73
74                 $last_backup->{$host} ||= $date;
75                 $last = $last_backup->{$host}->delta_days( $date )->delta_days;
76
77                 if ( $last && $last < $keep_every_days ) {
78                         $op = 'D';
79                 } else {
80                         $op = ' ';
81                         $last_backup->{$host} = $date;
82                 }
83         } else {
84                 $config_applied = 'none';
85         }
86
87         print "$op $name\t$used\t$refer\t$age\t$last\t$config_applied\n";
88
89         system "zfs destroy $name" if $op eq 'D' && @ARGV;
90 }