| 96 | rodolico | 1 | #! /usr/bin/env perl
 | 
        
           |  |  | 2 |   | 
        
           | 98 | rodolico | 3 | #    snapShot: Manage ZFS snapshots
 | 
        
           |  |  | 4 | #    see http://wiki.linuxservertech.com for additional information
 | 
        
           |  |  | 5 | #    Copyright (C) 2022  R. W. Rodolico
 | 
        
           |  |  | 6 | #
 | 
        
           |  |  | 7 | #    version 1.0, 20220423
 | 
        
           |  |  | 8 | #       Initial Release
 | 
        
           |  |  | 9 | #
 | 
        
           |  |  | 10 | #
 | 
        
           |  |  | 11 | #    This program is free software: you can redistribute it and/or modify
 | 
        
           |  |  | 12 | #    it under the terms of the GNU General Public License as published by
 | 
        
           |  |  | 13 | #    the Free Software Foundation, either version 3 of the License, or
 | 
        
           |  |  | 14 | #    (at your option) any later version.
 | 
        
           |  |  | 15 | #
 | 
        
           |  |  | 16 | #    This program is distributed in the hope that it will be useful,
 | 
        
           |  |  | 17 | #    but WITHOUT ANY WARRANTY; without even the implied warranty of
 | 
        
           |  |  | 18 | #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 | 
        
           |  |  | 19 | #    GNU General Public License for more details.
 | 
        
           |  |  | 20 | #
 | 
        
           |  |  | 21 | #    You should have received a copy of the GNU General Public License
 | 
        
           |  |  | 22 | #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 | 
        
           |  |  | 23 | #
 | 
        
           |  |  | 24 | # Warning, this script requires YAML::Tiny and Hash::Merge Perl Modules to be installed
 | 
        
           |  |  | 25 | # Under Debian:  apt install libyaml-tiny-perl libhash-merge-simple-perl
 | 
        
           |  |  | 26 | # Under FreeBSD: cpan -i Hash::Merge::Simple YAML::Tiny
 | 
        
           |  |  | 27 |   | 
        
           |  |  | 28 |   | 
        
           | 96 | rodolico | 29 | use strict;
 | 
        
           |  |  | 30 | use warnings;
 | 
        
           |  |  | 31 |   | 
        
           |  |  | 32 | use Data::Dumper;
 | 
        
           |  |  | 33 | use Time::Local;
 | 
        
           |  |  | 34 | use POSIX qw(strftime);
 | 
        
           |  |  | 35 | use YAML::Tiny; # apt-get libyaml-tiny-perl under debian, BSD Systems: cpan -i YAML::Tiny
 | 
        
           | 98 | rodolico | 36 | use Hash::Merge::Simple qw/ merge clone_merge /; # apt install libhash-merge-simple-perl or cpan -i Hash::Merge::Simple
 | 
        
           | 96 | rodolico | 37 |   | 
        
           |  |  | 38 |   | 
        
           |  |  | 39 | # globals
 | 
        
           |  |  | 40 | my $CONFIG_FILE_NAME = 'snapShot.yaml';
 | 
        
           |  |  | 41 |   | 
        
           |  |  | 42 | # This will be read in from snapShot.yaml
 | 
        
           |  |  | 43 | my $config;
 | 
        
           |  |  | 44 |   | 
        
           |  |  | 45 | #
 | 
        
           |  |  | 46 | # find where the script is actually located as cfg should be there
 | 
        
           |  |  | 47 | #
 | 
        
           |  |  | 48 | sub getScriptLocation {
 | 
        
           |  |  | 49 |    use strict;
 | 
        
           |  |  | 50 |    use File::Spec::Functions qw(rel2abs);
 | 
        
           |  |  | 51 |    use File::Basename;
 | 
        
           |  |  | 52 |    return dirname(rel2abs($0));
 | 
        
           |  |  | 53 | }
 | 
        
           |  |  | 54 |   | 
        
           |  |  | 55 | #
 | 
        
           |  |  | 56 | # Read the configuration file from current location 
 | 
        
           |  |  | 57 | # and return it as a string
 | 
        
           |  |  | 58 | #
 | 
        
           |  |  | 59 | sub readConfig {
 | 
        
           |  |  | 60 |    my $scriptLocation = &getScriptLocation();
 | 
        
           |  |  | 61 |    if ( -e "$scriptLocation/$CONFIG_FILE_NAME" ) {
 | 
        
           |  |  | 62 |       my $yaml = YAML::Tiny->read( "$scriptLocation/$CONFIG_FILE_NAME" );
 | 
        
           |  |  | 63 |       # use clone_merge to merge conf file into $config
 | 
        
           |  |  | 64 |       # overwrites anything in $config if it exists in the config file
 | 
        
           |  |  | 65 |       $config = clone_merge( $config, $yaml->[0] );
 | 
        
           |  |  | 66 |       return 1;
 | 
        
           |  |  | 67 |    }
 | 
        
           |  |  | 68 |    return 0;
 | 
        
           |  |  | 69 | }
 | 
        
           |  |  | 70 |   | 
        
           |  |  | 71 |   | 
        
           |  |  | 72 | # parse one single line from the output of `zfs list [-t snapshot]`
 | 
        
           |  |  | 73 | sub parseListing {
 | 
        
           |  |  | 74 |    my ($line,$keys) = @_;
 | 
        
           |  |  | 75 |    chomp $line;
 | 
        
           |  |  | 76 |    my %values;
 | 
        
           |  |  | 77 |    @values{@$keys} = split( /\s+/, $line );
 | 
        
           |  |  | 78 |    return \%values;
 | 
        
           |  |  | 79 | }      
 | 
        
           |  |  | 80 |   | 
        
           |  |  | 81 |   | 
        
           |  |  | 82 | # this will parse the date out of the snapshots and put the values into
 | 
        
           |  |  | 83 | # the hash {'date'}
 | 
        
           |  |  | 84 | sub parseSnapshots {
 | 
        
           |  |  | 85 |    my ( $snapShots, $config) = @_;
 | 
        
           |  |  | 86 |    my $keys = $config->{'snapshot'}->{'parseFields'};
 | 
        
           |  |  | 87 |    foreach my $snapShot ( keys %$snapShots ) {
 | 
        
           |  |  | 88 |       my %temp;
 | 
        
           |  |  | 89 |       # run the regex, capture the output to an array, then populate the hash %temp
 | 
        
           |  |  | 90 |       # using the regex results as the values, and $keys as the keys
 | 
        
           |  |  | 91 |       @temp{@$keys} = ( $snapShot =~ m/$config->{'snapshot'}->{'parse'}/ );
 | 
        
           |  |  | 92 |       # while we're here, calculate the unix time (epoch). NOTE: month is 0 based
 | 
        
           |  |  | 93 |       $temp{'unix'} = timelocal( 0,$temp{'minute'},$temp{'hour'},$temp{'day'},$temp{'month'}-1,$temp{'year'} );
 | 
        
           |  |  | 94 |       # put this into our record
 | 
        
           |  |  | 95 |       $snapShots->{$snapShot}->{'date'} = \%temp;
 | 
        
           |  |  | 96 |    }
 | 
        
           |  |  | 97 | }
 | 
        
           |  |  | 98 |   | 
        
           |  |  | 99 | # run $command, then parse its output and return the results as a hashref
 | 
        
           |  |  | 100 | sub getListing {
 | 
        
           |  |  | 101 |    my ($configuration, $regex, $command )  = @_;
 | 
        
           |  |  | 102 |    my %dataSets;
 | 
        
           |  |  | 103 |   | 
        
           |  |  | 104 |    # get all datasets
 | 
        
           |  |  | 105 |    my @zfsList = `$command`;
 | 
        
           |  |  | 106 |    foreach my $thisSet ( @zfsList ) {
 | 
        
           |  |  | 107 |       my $temp = &parseListing( $thisSet, $configuration->{'listingKeys'} );
 | 
        
           |  |  | 108 |       if (  $temp->{'name'} =~ m/^($regex)$/ ) {
 | 
        
           |  |  | 109 |          $dataSets{$temp->{'name'}} = $temp;
 | 
        
           |  |  | 110 |       }
 | 
        
           |  |  | 111 |    }
 | 
        
           |  |  | 112 |    return \%dataSets;
 | 
        
           |  |  | 113 | }
 | 
        
           |  |  | 114 |   | 
        
           |  |  | 115 | # will convert something like 1 day to the number of seconds (86400) for math.
 | 
        
           |  |  | 116 | # month and year are approximations (30.5 day = a month, 365.2425 days is a year)
 | 
        
           |  |  | 117 | sub period2seconds {
 | 
        
           |  |  | 118 |    my ($count, $unit) = ( shift =~ m/\s*(\d+)\s*([a-z]+)\s*/i );
 | 
        
           |  |  | 119 |    $unit = lc $unit;
 | 
        
           | 97 | rodolico | 120 |    if ( $unit eq 'hour' ) {
 | 
        
           | 96 | rodolico | 121 |       $count *= 3600;
 | 
        
           |  |  | 122 |    } elsif ( $unit eq 'day' ) {
 | 
        
           |  |  | 123 |       $count *= 86400;
 | 
        
           |  |  | 124 |    } elsif ( $unit eq 'week' ) {
 | 
        
           |  |  | 125 |       $count *= 864000 * 7;
 | 
        
           |  |  | 126 |    } elsif ( $unit eq 'month' ) {
 | 
        
           |  |  | 127 |       $count *= 864000 * 30.5;
 | 
        
           |  |  | 128 |    } elsif ( $unit eq 'year' ) {
 | 
        
           |  |  | 129 |       $count *= 86400 * 365.2425;
 | 
        
           |  |  | 130 |    } else {
 | 
        
           |  |  | 131 |       die "Unknown units [$unit] in period2seconds\n";
 | 
        
           |  |  | 132 |    }
 | 
        
           |  |  | 133 |    return $count;
 | 
        
           |  |  | 134 | }
 | 
        
           |  |  | 135 |   | 
        
           |  |  | 136 | # Merges datasets, snapshots and some stuff from the configuration into the datasets
 | 
        
           |  |  | 137 | # hash
 | 
        
           | 97 | rodolico | 138 | sub mergeData {
 | 
        
           | 96 | rodolico | 139 |    my ($datasets,$snapshots,$config) = @_;
 | 
        
           |  |  | 140 |    my $confKeys = $config->{'datasets'};
 | 
        
           |  |  | 141 |    foreach my $thisDataset ( keys %$datasets ) {
 | 
        
           |  |  | 142 |       foreach my $conf (keys %$confKeys ) {
 | 
        
           |  |  | 143 |          if ( $thisDataset =~ m/^$conf$/ ) {
 | 
        
           |  |  | 144 |             $datasets->{$thisDataset}->{'recursive'} = $confKeys->{$conf}->{'recursive'};
 | 
        
           |  |  | 145 |             $datasets->{$thisDataset}->{'frequency'} = &period2seconds( $confKeys->{$conf}->{'frequency'} );
 | 
        
           |  |  | 146 |             $datasets->{$thisDataset}->{'retention'} = &period2seconds( $confKeys->{$conf}->{'retention'} );
 | 
        
           |  |  | 147 |             last;
 | 
        
           |  |  | 148 |          } # if
 | 
        
           |  |  | 149 |       } # foreach
 | 
        
           |  |  | 150 |       foreach my $snapshot ( keys %$snapshots ) {
 | 
        
           |  |  | 151 |          if ( $snapshot =~ m/^$thisDataset@/ ) { # this is a match
 | 
        
           |  |  | 152 |             # copy the snapshot into the dataset
 | 
        
           |  |  | 153 |             $datasets->{$thisDataset}->{'snapshots'}->{$snapshot} = $snapshots->{$snapshot};
 | 
        
           |  |  | 154 |             # track the latest snapshot
 | 
        
           |  |  | 155 |             $datasets->{$thisDataset}->{'lastSnap'} = $snapshots->{$snapshot}->{'date'}->{'unix'}
 | 
        
           |  |  | 156 |                if ! defined( $datasets->{$thisDataset}->{'lastSnap'} ) || $datasets->{$thisDataset}->{'lastSnap'} < $snapshots->{$snapshot}->{'date'}->{'unix'};
 | 
        
           |  |  | 157 |             # delete the snapshot
 | 
        
           |  |  | 158 |             delete $snapshots->{$snapshot};
 | 
        
           |  |  | 159 |          } # if
 | 
        
           |  |  | 160 |       } # foreach
 | 
        
           |  |  | 161 |    } # foreach
 | 
        
           | 97 | rodolico | 162 | } # sub mergeData
 | 
        
           | 96 | rodolico | 163 |   | 
        
           |  |  | 164 | sub checkRetention {
 | 
        
           |  |  | 165 |    my ( $retentionPeriod, $recursive, $snapshots, $now ) = @_;
 | 
        
           |  |  | 166 |    my @toDelete;
 | 
        
           |  |  | 167 |    foreach my $thisSnapshot ( keys %$snapshots ) {
 | 
        
           |  |  | 168 |       # print "checking $thisSnapshot\n\tNow: $now\n\tDate: $snapshots->{$thisSnapshot}->{date}->{unix}\n\tRetention: $retentionPeriod\n\n";
 | 
        
           |  |  | 169 |       if ( $now - $snapshots->{$thisSnapshot}->{'date'}->{'unix'} > $retentionPeriod ) {
 | 
        
           |  |  | 170 |          my $command = 'zfs destroy ' . ($recursive ? '-r ' : '') . $thisSnapshot;
 | 
        
           |  |  | 171 |          push @toDelete, $command;
 | 
        
           |  |  | 172 |       }
 | 
        
           |  |  | 173 |    }
 | 
        
           |  |  | 174 |    return @toDelete;
 | 
        
           |  |  | 175 | }   
 | 
        
           |  |  | 176 |   | 
        
           |  |  | 177 | sub makeSnapshot {
 | 
        
           |  |  | 178 |    my ( $datasetName, $recursive, $snapshotName ) = @_;
 | 
        
           |  |  | 179 |    return 
 | 
        
           |  |  | 180 |       'zfs snapshot ' . 
 | 
        
           |  |  | 181 |       ($recursive ? '-r ' : '') . 
 | 
        
           |  |  | 182 |       $datasetName . $snapshotName;
 | 
        
           |  |  | 183 | }
 | 
        
           |  |  | 184 |   | 
        
           |  |  | 185 |   | 
        
           |  |  | 186 | sub process {
 | 
        
           |  |  | 187 |    my ( $datasets, $now, $snapshotName, $slop ) = @_;
 | 
        
           |  |  | 188 |    my @actions;
 | 
        
           |  |  | 189 |    my @toDelete;
 | 
        
           |  |  | 190 |    my @toAdd;
 | 
        
           |  |  | 191 |   | 
        
           |  |  | 192 |    foreach my $thisDataset ( keys %$datasets ) {
 | 
        
           |  |  | 193 |       push( @toDelete, 
 | 
        
           |  |  | 194 |          &checkRetention( 
 | 
        
           |  |  | 195 |          $datasets->{$thisDataset}->{'retention'}, 
 | 
        
           |  |  | 196 |          $datasets->{$thisDataset}->{'recursive'}, 
 | 
        
           |  |  | 197 |          $datasets->{$thisDataset}->{'snapshots'}, 
 | 
        
           |  |  | 198 |          $now )
 | 
        
           |  |  | 199 |          );
 | 
        
           |  |  | 200 |       if ( $datasets->{$thisDataset}->{'lastSnap'} + $datasets->{$thisDataset}->{'frequency'} < $now + $slop ) {
 | 
        
           |  |  | 201 |          push @toAdd, &makeSnapshot( $thisDataset, $datasets->{$thisDataset}->{'recursive'}, $snapshotName )
 | 
        
           |  |  | 202 |       }
 | 
        
           |  |  | 203 |    }
 | 
        
           |  |  | 204 |    return ( @toDelete, @toAdd );
 | 
        
           |  |  | 205 | }   
 | 
        
           |  |  | 206 |   | 
        
           |  |  | 207 | sub run {
 | 
        
           |  |  | 208 |    my $testing = shift;
 | 
        
           |  |  | 209 |    # bail if there are no commands to run
 | 
        
           | 99 | rodolico | 210 |    return 0 unless @_;
 | 
        
           | 96 | rodolico | 211 |    if ( $testing ) { # don't do it, just dump the commands
 | 
        
           |  |  | 212 |       open LOG, ">/tmp/snapShot" or die "could not write to /tmp/snapShot: $!\n";
 | 
        
           |  |  | 213 |       print LOG join( "\n", @_ ) . "\n";
 | 
        
           |  |  | 214 |       close LOG;
 | 
        
           |  |  | 215 |    } else {
 | 
        
           |  |  | 216 |       my $out;
 | 
        
           |  |  | 217 |       return 'Not running right now';
 | 
        
           |  |  | 218 |       while ( my $command = shift ) {
 | 
        
           |  |  | 219 |          $out .= `$command` . "\n";
 | 
        
           |  |  | 220 |          if ( $? ) { # we had an error
 | 
        
           |  |  | 221 |             $out .= "Error executing command\n\t$command\n\t";
 | 
        
           |  |  | 222 |             if ($? == -1) {
 | 
        
           |  |  | 223 |                 $out .= "failed to execute $command: $!";
 | 
        
           |  |  | 224 |             } elsif ($? & 127) {
 | 
        
           |  |  | 225 |                 $out .= sprintf( "child died with signal %d, %s coredump", ($? & 127),  ($? & 128) ? 'with' : 'without' );
 | 
        
           |  |  | 226 |             } else {
 | 
        
           |  |  | 227 |                 $out .= sprintf( "child exited with value %d", $? >> 8 );
 | 
        
           |  |  | 228 |             }
 | 
        
           |  |  | 229 |             $out .= "\n";
 | 
        
           |  |  | 230 |             return $out;
 | 
        
           |  |  | 231 |          }
 | 
        
           |  |  | 232 |       }
 | 
        
           |  |  | 233 |    }
 | 
        
           |  |  | 234 |    return 0;
 | 
        
           |  |  | 235 | }
 | 
        
           |  |  | 236 |   | 
        
           | 99 | rodolico | 237 | &readConfig() or die "Could not read config file: $!\n";
 | 
        
           | 97 | rodolico | 238 |   | 
        
           | 96 | rodolico | 239 | # grab the time once
 | 
        
           |  |  | 240 | my $now = time;
 | 
        
           |  |  | 241 | # create the string to be used for all snapshots, using $now and the template provided
 | 
        
           |  |  | 242 | my $snapshotName = '@' . strftime($config->{'snapshot'}->{'template'},localtime $now);
 | 
        
           |  |  | 243 | # Create the dataset regex for later use 
 | 
        
           |  |  | 244 | $config->{'dataset_regex'} = '(' . join( ')|(', keys %{ $config->{'datasets'} }  ) . ')' unless $config->{'dataset_regex'};
 | 
        
           |  |  | 245 | #print $config{'dataset_regex'} . "\n";
 | 
        
           |  |  | 246 | $config->{'snapshot_regex'} = '(' . $config->{'dataset_regex'} . ')@' . $config->{'snapshot'}->{'parse'};
 | 
        
           |  |  | 247 | #print $config->{'snapshot_regex'} . "\n\n";
 | 
        
           |  |  | 248 |   | 
        
           |  |  | 249 | #die Dumper( $config ) . "\n";   
 | 
        
           |  |  | 250 | # first, find all datasets which match our keys
 | 
        
           |  |  | 251 | my $dataSets = &getListing( $config, $config->{'dataset_regex'}, 'zfs list'  );
 | 
        
           |  |  | 252 | # and, find all snapshots that match
 | 
        
           |  |  | 253 | my $snapshots = &getListing( $config, $config->{'snapshot_regex'}, 'zfs list -t snapshot'  );
 | 
        
           |  |  | 254 | # get the date/time of the snapshots and store them in the hash
 | 
        
           |  |  | 255 | &parseSnapshots($snapshots, $config );
 | 
        
           | 97 | rodolico | 256 | # mergeData the snapshots into the datasets for convenience
 | 
        
           |  |  | 257 | &mergeData( $dataSets, $snapshots, $config );
 | 
        
           | 96 | rodolico | 258 | # Now, let's do the actual processing
 | 
        
           |  |  | 259 | my @commands  = &process( $dataSets, $now, $snapshotName, &period2seconds( $config->{'slop'} ) );
 | 
        
           | 99 | rodolico | 260 | #print join ( "\n", @commands ) . "\n";
 | 
        
           | 96 | rodolico | 261 | my $errors;
 | 
        
           | 99 | rodolico | 262 | print "Error: $errors\n" if $errors = &run( $config->{'TESTING'}, @commands );
 | 
        
           | 96 | rodolico | 263 |   | 
        
           |  |  | 264 |   | 
        
           | 99 | rodolico | 265 | # print Dumper( $dataSets );
 | 
        
           | 96 | rodolico | 266 | #print Dumper( $snapshots );
 | 
        
           |  |  | 267 |   | 
        
           |  |  | 268 | #print join ("\n", sort keys( %$dataSets ) ) . "\n\n";
 | 
        
           |  |  | 269 | #print join( "\n", sort keys( %$snapshots ) ) . "\n";
 | 
        
           |  |  | 270 |   | 
        
           |  |  | 271 | 1;
 |