Subversion Repositories sysadmin_scripts

Rev

Go to most recent revision | Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
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
#
103 rodolico 24
# Warning, this script requires non-standard Perl modules YAML::Tiny and Hash::Merge
98 rodolico 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
103 rodolico 100
# $command is one of zfs list or zfs list -t snapshot
101
# In other words, get all datasets/volumes or get all snapshots
96 rodolico 102
sub getListing {
103
   my ($configuration, $regex, $command )  = @_;
104
   my %dataSets;
105
 
103 rodolico 106
   # get all datasets/volumes or snapshots
96 rodolico 107
   my @zfsList = `$command`;
108
   foreach my $thisSet ( @zfsList ) {
103 rodolico 109
      # parse the line into its portions. The only one we use right now is name
96 rodolico 110
      my $temp = &parseListing( $thisSet, $configuration->{'listingKeys'} );
103 rodolico 111
      if (  $temp->{'name'} =~ m/^($regex)$/ ) { # it matches the regex we're using, so save it
96 rodolico 112
         $dataSets{$temp->{'name'}} = $temp;
113
      }
114
   }
103 rodolico 115
   return \%dataSets; # return all entries we are looking for
96 rodolico 116
}
117
 
118
# will convert something like 1 day to the number of seconds (86400) for math.
119
# month and year are approximations (30.5 day = a month, 365.2425 days is a year)
101 rodolico 120
# For month and year, use the int function to convert back to integer
96 rodolico 121
sub period2seconds {
122
   my ($count, $unit) = ( shift =~ m/\s*(\d+)\s*([a-z]+)\s*/i );
123
   $unit = lc $unit;
97 rodolico 124
   if ( $unit eq 'hour' ) {
96 rodolico 125
      $count *= 3600;
126
   } elsif ( $unit eq 'day' ) {
127
      $count *= 86400;
128
   } elsif ( $unit eq 'week' ) {
129
      $count *= 864000 * 7;
130
   } elsif ( $unit eq 'month' ) {
101 rodolico 131
      $count *= int( 864000 * 30.5 );
96 rodolico 132
   } elsif ( $unit eq 'year' ) {
101 rodolico 133
      $count *= int( 86400 * 365.2425 );
96 rodolico 134
   } else {
135
      die "Unknown units [$unit] in period2seconds\n";
136
   }
137
   return $count;
138
}
139
 
140
# Merges datasets, snapshots and some stuff from the configuration into the datasets
103 rodolico 141
# hash. After this, $config and $snapshots should no longer be necessary
97 rodolico 142
sub mergeData {
96 rodolico 143
   my ($datasets,$snapshots,$config) = @_;
144
   my $confKeys = $config->{'datasets'};
145
   foreach my $thisDataset ( keys %$datasets ) {
103 rodolico 146
      # go through each configuration entry and see if we match the current dataset
96 rodolico 147
      foreach my $conf (keys %$confKeys ) {
103 rodolico 148
         if ( $thisDataset =~ m/^$conf$/ ) { # found it, so store the configuration values into the dataset
96 rodolico 149
            $datasets->{$thisDataset}->{'recursive'} = $confKeys->{$conf}->{'recursive'};
150
            $datasets->{$thisDataset}->{'frequency'} = &period2seconds( $confKeys->{$conf}->{'frequency'} );
151
            $datasets->{$thisDataset}->{'retention'} = &period2seconds( $confKeys->{$conf}->{'retention'} );
103 rodolico 152
            last; # there is only one, so no need to process any more for this configuration key
96 rodolico 153
         } # if
154
      } # foreach
103 rodolico 155
      # do the same for the snapshots we found; bind them to the data set
96 rodolico 156
      foreach my $snapshot ( keys %$snapshots ) {
157
         if ( $snapshot =~ m/^$thisDataset@/ ) { # this is a match
158
            # copy the snapshot into the dataset
159
            $datasets->{$thisDataset}->{'snapshots'}->{$snapshot} = $snapshots->{$snapshot};
103 rodolico 160
            # track the latest snapshot (we use this to decide whether it is time to add a new one)
96 rodolico 161
            $datasets->{$thisDataset}->{'lastSnap'} = $snapshots->{$snapshot}->{'date'}->{'unix'}
162
               if ! defined( $datasets->{$thisDataset}->{'lastSnap'} ) || $datasets->{$thisDataset}->{'lastSnap'} < $snapshots->{$snapshot}->{'date'}->{'unix'};
103 rodolico 163
            # delete the snapshot, to free up memory
96 rodolico 164
            delete $snapshots->{$snapshot};
165
         } # if
166
      } # foreach
167
   } # foreach
97 rodolico 168
} # sub mergeData
96 rodolico 169
 
103 rodolico 170
 
171
# check to see if a particular snapshot is ready to be destroyed, ie right now is greater than the retention period
172
# if $recurive is true, add the '-r' to the command to do a recursive destroy
96 rodolico 173
sub checkRetention {
174
   my ( $retentionPeriod, $recursive, $snapshots, $now ) = @_;
103 rodolico 175
   my @toDelete; # an array of destroy commands
96 rodolico 176
   foreach my $thisSnapshot ( keys %$snapshots ) {
177
      # print "checking $thisSnapshot\n\tNow: $now\n\tDate: $snapshots->{$thisSnapshot}->{date}->{unix}\n\tRetention: $retentionPeriod\n\n";
103 rodolico 178
      if ( $now - $snapshots->{$thisSnapshot}->{'date'}->{'unix'} > $retentionPeriod ) { # it is too old
179
         push ( @toDelete, ( 'zfs destroy ' . ($recursive ? '-r ' : '') . $thisSnapshot ) ); # list it to be destroyed
96 rodolico 180
      }
181
   }
103 rodolico 182
   return @toDelete; # just return the list of destroy commands to be executed
96 rodolico 183
}   
184
 
103 rodolico 185
 
186
# just return the command to create a new snapshot. Very simple, but I wanted the code to be isolated in case something needed
187
# to change. Basically, zfs snapshot [-r] datasetname@template
96 rodolico 188
sub makeSnapshot {
189
   my ( $datasetName, $recursive, $snapshotName ) = @_;
190
   return 
191
      'zfs snapshot ' . 
192
      ($recursive ? '-r ' : '') . 
193
      $datasetName . $snapshotName;
194
}
195
 
103 rodolico 196
# this is the biggie; everything leads to here. We will take every dataset/volume we found, and decide whether some old snapshots
197
# need to be destroyed, and whether a new snapshot needs to be created.
96 rodolico 198
sub process {
199
   my ( $datasets, $now, $snapshotName, $slop ) = @_;
103 rodolico 200
   my @toDelete; # will hold all the destroy commands
201
   my @toAdd; # will hold all the create commands
96 rodolico 202
 
103 rodolico 203
   foreach my $thisDataset ( keys %$datasets ) { # Look at each dataset/volume in turn
204
      # if any snapshots need to be destroyed, add them to @toDelete
96 rodolico 205
      push( @toDelete, 
206
         &checkRetention( 
207
         $datasets->{$thisDataset}->{'retention'}, 
208
         $datasets->{$thisDataset}->{'recursive'}, 
209
         $datasets->{$thisDataset}->{'snapshots'}, 
210
         $now )
211
         );
103 rodolico 212
      # if it is time to add a new snapshot, add it to @toAdd
102 rodolico 213
      if ( $datasets->{$thisDataset}->{'lastSnap'} + $datasets->{$thisDataset}->{'frequency'} - $slop < $now ) {
96 rodolico 214
         push @toAdd, &makeSnapshot( $thisDataset, $datasets->{$thisDataset}->{'recursive'}, $snapshotName )
215
      }
216
   }
103 rodolico 217
   # return the actions, deletions first, adds second (executed in that order)
96 rodolico 218
   return ( @toDelete, @toAdd );
219
}   
220
 
103 rodolico 221
# Run 0 or more commands
222
# the first thing on the stack is a flag for testing
223
# everything after that is an ordered list of commands to be executed.
224
# If any command fails, all subsequent commands abort
96 rodolico 225
sub run {
226
   my $testing = shift;
103 rodolico 227
   return 0 unless @_; # bail if there are no commands to run
228
   if ( $testing ) { # don't do it, just dump the commands to /tmp/snapShot
96 rodolico 229
      open LOG, ">/tmp/snapShot" or die "could not write to /tmp/snapShot: $!\n";
230
      print LOG join( "\n", @_ ) . "\n";
231
      close LOG;
103 rodolico 232
   } else { # actually execute the commands
233
      my $out; # capture all output
234
      return 'Not running right now'; # temp while testing
235
      while ( my $command = shift ) { # for each command on the stack
236
         $out .= `$command` . "\n"; # add it to $out
237
         if ( $? ) { # we had an error, add debugging text, the end program
96 rodolico 238
            $out .= "Error executing command\n\t$command\n\t";
239
            if ($? == -1) {
240
                $out .= "failed to execute $command: $!";
241
            } elsif ($? & 127) {
242
                $out .= sprintf( "child died with signal %d, %s coredump", ($? & 127),  ($? & 128) ? 'with' : 'without' );
243
            } else {
244
                $out .= sprintf( "child exited with value %d", $? >> 8 );
245
            }
246
            $out .= "\n";
247
            return $out;
248
         }
249
      }
250
   }
103 rodolico 251
   return 0; # we succeeded
96 rodolico 252
}
253
 
99 rodolico 254
&readConfig() or die "Could not read config file: $!\n";
97 rodolico 255
 
103 rodolico 256
# we're pre-calculating some things so we don't do it over and over for each entry
96 rodolico 257
# grab the time once
258
my $now = time;
259
# create the string to be used for all snapshots, using $now and the template provided
260
my $snapshotName = '@' . strftime($config->{'snapshot'}->{'template'},localtime $now);
103 rodolico 261
# Create the dataset regex by joing all of the regexes defined.
96 rodolico 262
$config->{'dataset_regex'} = '(' . join( ')|(', keys %{ $config->{'datasets'} }  ) . ')' unless $config->{'dataset_regex'};
263
#print $config{'dataset_regex'} . "\n";
264
$config->{'snapshot_regex'} = '(' . $config->{'dataset_regex'} . ')@' . $config->{'snapshot'}->{'parse'};
265
#print $config->{'snapshot_regex'} . "\n\n";
266
 
267
#die Dumper( $config ) . "\n";   
268
# first, find all datasets which match our keys
269
my $dataSets = &getListing( $config, $config->{'dataset_regex'}, 'zfs list'  );
270
# and, find all snapshots that match
271
my $snapshots = &getListing( $config, $config->{'snapshot_regex'}, 'zfs list -t snapshot'  );
272
# get the date/time of the snapshots and store them in the hash
273
&parseSnapshots($snapshots, $config );
97 rodolico 274
# mergeData the snapshots into the datasets for convenience
275
&mergeData( $dataSets, $snapshots, $config );
96 rodolico 276
# Now, let's do the actual processing
277
my @commands  = &process( $dataSets, $now, $snapshotName, &period2seconds( $config->{'slop'} ) );
99 rodolico 278
#print join ( "\n", @commands ) . "\n";
96 rodolico 279
my $errors;
99 rodolico 280
print "Error: $errors\n" if $errors = &run( $config->{'TESTING'}, @commands );
96 rodolico 281
 
99 rodolico 282
# print Dumper( $dataSets );
96 rodolico 283
#print Dumper( $snapshots );
284
 
285
#print join ("\n", sort keys( %$dataSets ) ) . "\n\n";
286
#print join( "\n", sort keys( %$snapshots ) ) . "\n";
287
 
288
1;