Subversion Repositories zfs_utils

Rev

Rev 14 | Rev 18 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 rodolico 1
#! /usr/bin/env perl
2
 
3
use strict;
4
use warnings;
5
 
6
 
7
BEGIN {
8
   use FindBin;
9
   use File::Spec;
10
   # use libraries from the directory this script is in
11
   use Cwd 'abs_path';
12
   use File::Basename;
13
   use lib dirname( abs_path( __FILE__ ) );
14
}
15
 
16
use YAML::Tiny; # pkg install p5-YAML-Tiny-1.74
17
use Data::Dumper;
18
 
19
my $cwd = $FindBin::RealBin;
20
my $configFileName = $cwd . '/sync.yaml';
21
my $replicateScript = $cwd . '/replicate';
22
 
23
my $configuration;
24
 
25
 
26
# load Configuration File
27
# read the config file and return it
28
sub readConfig {
29
   my $filename = shift;
30
   die "Config file $filename not found: $!" unless -f $filename;
31
   my $yaml = YAML::Tiny->new( {} );
32
   if ( -f $filename ) {
33
      $yaml = YAML::Tiny->read( $filename );
34
   }
35
   return $yaml->[0];
36
}
37
 
10 rodolico 38
sub logit {
39
   open LOG, ">>/tmp/replicate.log" or die "Could not open replicate.log: $!\n";
40
   print LOG join( "\n", @_ ) . "\n";
41
   close LOG;
42
}
2 rodolico 43
 
44
 
45
# this calls gshred which will overwrite the file 3 times, then
46
# remove it.
47
# NOTE: this will not work on ZFS, since ZFS is CopyOnWrite (COW)
48
# so assuming /tmp is a ramdisk
49
sub shredFile {
50
   my $filename = shift;
51
   `/usr/local/bin/gshred -u -f -s 32 $filename`;
52
}
53
 
54
 
55
# runs a command, redirecting stderr to stdout (which it ignores)
56
# then returns 0 on success.
57
# if error, returns string describing error
58
sub runCommand {
59
   my $command = shift;
10 rodolico 60
   #logit( $command );
2 rodolico 61
   my $output = qx/$command 2>&1/;
62
   if ($? == -1) {
63
      return (-1, "failed to execute: $!" );
64
   } elsif ($? & 127) {
65
      return (-1,sprintf "child died with signal %d, %s coredump",
66
        ($? & 127),  ($? & 128) ? 'with' : 'without');
67
   } else {
68
      return ( $?>>8, sprintf "child exited with value %d", $? >> 8 ) if $? >> 8;
69
   }
70
   return (0, $output);
71
}
72
 
73
# grabs the encryption key from the remote server, and uses it to unlock the 
74
# datasets, then mount the drives.
75
# a return of '' is success, anything else is an error
76
sub mountDrives {
77
   my $configuration = shift;
78
   return (0, 'No encrypted target found' ) unless defined( $configuration->{'target'}->{'encryptionKeyPath'} ) && $configuration->{'target'}->{'encryptionKeyPath'};
79
   # try to grab the file from the remote machine
80
   &runCommand( "scp $configuration->{remoteMachine}->{ip}:$configuration->{remoteMachine}->{encryptionKeyPath} $configuration->{localMachine}->{encryptionKeyPath}" );
81
   # If we do not have the encryption key, we need to abort
82
   return "Could not copy file $configuration->{remoteMachine}->{ip}:$configuration->{remoteMachine}->{encryptionKeyPath}, aborting" 
83
      unless -f $configuration->{'target'}->{'encryptionKeyPath'};
84
   my $error = '';
85
   my $output = '';
86
   # load the key into zfs and unlock all volumes
87
   ($error,$output) = &runCommand( "zfs load-key -a" );
88
   # finally, remount all of the zfs shares which need the key
89
   ($error,$output) = &runCommand( "zfs mount -a" ) unless $error;
90
   # if we succeeded, we want to shred the keyfile
91
   &shredFile( $configuration->{localMachine}->{encryptionKeyPath} ) if -f $configuration->{localMachine}->{encryptionKeyPath};
92
   return $error;
93
}
94
 
10 rodolico 95
# a very simple mailer, just send information to sendmail
2 rodolico 96
sub sendMail {
97
   my ($message, $configuration, $subject ) = @_;
10 rodolico 98
   if ( $message ) {
99
      open MAIL,"|sendmail -t" or die "Could not open sendmail: $!\n";
100
      print MAIL "To: $configuration->{email}->{notify}\n";
101
      print MAIL "From: $configuration->{email}->{from}\n";
102
      print MAIL "Subject: " . 
103
                 ($configuration->{'email'}->{'subject'} . ( $subject ? " - $subject" : '' ) ) .
104
                 "\n\n";
105
      print MAIL $message;
106
      close MAIL;
2 rodolico 107
   } else {
10 rodolico 108
      warn "no message in outgoing email\n";
2 rodolico 109
   }
110
}
111
 
112
# checks to see if we should be in maintenance mode
113
# if $remoteMachine->{'maintenanceMode'} exists, set mode
114
# otherwise, wait localMachine->{'waittime'} minutes, then check
115
# $localMachine->{'maintenanceMode'}.
116
# if neither exists, begin sync
117
sub checkMaintenance {
118
   my $configuration = shift;
119
   return 0 unless # exit if maintenanceFlag has not been set at all
120
     ( defined( $configuration->{'target'}->{'maintenanceFlag'} ) && $configuration->{'target'}->{'maintenanceFlag'} ) ||
121
     ( defined( $configuration->{'source'}->{'maintenanceFlag'} ) && $configuration->{'source'}->{'maintenanceFlag'} );
122
   # see if maintenance is set on remote. If so, simply return the message
123
   if ( $configuration->{'source'}->{'up'} ) {
124
      my ($error, $output) = &runCommand( "ssh $configuration->{remoteMachine}->{ip} 'ls $configuration->{remoteMachine}->{maintenanceFlag}'" );
125
      if ( ! $error ) {
126
         # remove the file from the remote server
127
         &runCommand( "ssh $configuration->{remoteMachine}->{ip} 'rm $configuration->{remoteMachine}->{maintenanceFlag}'" );
128
         # create a valid return, which will exit the program
129
         return "Maintenance Flag found on remote machine";
130
      }
131
   }
132
   # not on remote machine, so give them waitTime seconds to put it here
133
   # we'll loop, checking every $sleepTime seconds until our wait time
134
   # ($configuration->{'target'}->{'waitTime'}) has expired
135
   my $sleepTime = 60;
136
   for ( my $i = $configuration->{'target'}->{'waitTime'}; $i > 0; $i -= $sleepTime ) {
137
      sleep $sleepTime;
138
      # then look for the maintenance flag file on the local machine
139
      return "Maintenance Flag found on local machine" if -f $configuration->{'target'}->{'maintenanceFlag'};
140
   }
141
   # no maintenance flags found, so return false
142
   return 0;
143
}
144
 
145
sub shutdownMachine {
146
   my $configuration = shift;
10 rodolico 147
   exit unless $configuration->{'shutdown'};
2 rodolico 148
   # do not actually shut down the server unless we are told to
149
   &runCommand( "poweroff" ) unless $configuration->{'testing'};
150
}
151
 
152
# returns the current time as a string
153
sub currentTime {
154
   my $format = shift;
155
   # default to YY-MM-DD HH-MM-SS
16 rodolico 156
   $format = '%Y-%m-%d %H:%M:%S' unless $format;
2 rodolico 157
   use POSIX;
158
   return POSIX::strftime( $format, localtime() );
159
}
160
 
7 rodolico 161
# verify a remote machine is up and running
2 rodolico 162
sub checkRemoteUp {
163
   my $configuration = shift;
164
   my $ip;
165
   if ( defined( $configuration->{'target'}->{'server'} ) && $configuration->{'target'}->{'server'} ) {
166
      $ip = $configuration->{'target'}->{'server'};
167
   } else {
168
      $ip = $configuration->{'source'}->{'server'};
169
   }
170
   my ($error, $message ) =  $ip ? &runCommand( "ping -c 1 -t 5 $ip" ) : (0,'No address defined for either target or server' );
7 rodolico 171
#   $message = "Checking IP $ip\n"  . $message;
2 rodolico 172
   #die "error is $error, message is $message for $ip\n";
173
   return ($error, $message);
174
}
175
 
12 rodolico 176
sub updateStats {
177
   my ( $label, $filename, $output ) = @_;
178
   if ( $output =~ m/bytes\t(\d+).*seconds\t(\d+)/gms ) { # global, multiline, . matches newlines
179
      my $seconds = $2;
180
      my $bytes = $1;
181
      open STATS,">>$filename" or warn "Could not create file $filename: $!\n";
16 rodolico 182
      print STATS &currentTime('') . "\t$label\t$seconds\t$bytes\n";
12 rodolico 183
      close STATS
184
   } else {
185
      warn "updateStats called with invalid report\n";
186
   }
187
}
188
 
2 rodolico 189
my @status;   
190
my $error = 0;
191
my $output = '';
192
 
193
$configuration = &readConfig($configFileName);
194
 
195
# die Dumper( $configuration ) . "\n";
196
 
197
my $servername = `hostname`;
198
chomp $servername;
199
 
7 rodolico 200
push @status, "Replication on $servername has been started at " . &currentTime();
2 rodolico 201
&sendMail( "Replication on $servername has been started, " . &currentTime(), $configuration, "Replication on $servername started" );
202
 
203
# see if remote machine is up by sending one ping. Expect response in 5 seconds
204
( $error,$output) = &checkRemoteUp( $configuration );
205
$configuration->{'up'} = ! $error;
206
push @status, "remote machine is " . ( $configuration->{'up'} ? 'Up' : 'Down' ) . "\n";
10 rodolico 207
if ( ! $configuration->{'up'} ) {
208
   # we can not connect to the remote server, so just shut down
209
   sendMail( join( "\n", @status ), $configuration, "No connection to remote machine" );
210
   &shutdownMachine( $configuration );
211
}
2 rodolico 212
 
213
# check for maintenance flags, exit if we should go into mainteance mode
214
if ( my $result = &checkMaintenance( $configuration ) ) {
215
   push @status,$result;
216
   &sendMail( join( "\n", @status), $configuration, "Maintenance Mode" );
217
   die;
218
}
219
 
220
# try to mount the datasets if they are encrypted
221
($error,$output) = &mountDrives( $configuration );
222
if ( $error ) { # could not mount datasets
10 rodolico 223
   push @status, $output;
224
   &sendMail( join( "\n", @status ), $configuration, "Mount Drive Error: [$output]" );
225
   &shutdownMachine( $configuration );
2 rodolico 226
}
227
 
10 rodolico 228
#&sendMail( "Backup has been started at " . &currentTime(), $configuration, "Backup Starting" );
7 rodolico 229
push @status, &currentTime() . ' Backup started';
2 rodolico 230
 
231
$configuration->{'source'}->{'server'} = $configuration->{'source'}->{'server'} ? $configuration->{'source'}->{'server'} . ':' : '';
232
$configuration->{'target'}->{'server'} = $configuration->{'target'}->{'server'} ? $configuration->{'target'}->{'server'} . ':' : '';
233
 
7 rodolico 234
my @flags;
235
push @flags, '--dryrun' if $configuration->{'dryrun'};
236
push @flags, '--recurse' if $configuration->{'recurse'};
16 rodolico 237
push @flags, '-' . 'v'x$configuration->{verbose} if $configuration->{'verbose'};
10 rodolico 238
push @flags, "--bwlimit=$configuration->{bandwidth}" if $configuration->{'bandwidth'};
7 rodolico 239
push @flags, "--filter='$configuration->{filter}'" if $configuration->{'filter'};
240
 
16 rodolico 241
# die join( ' ', @flags ) . "\n";
242
 
12 rodolico 243
# prepend the current working directory to stats if it does not have a path
244
$configuration->{'stats'} = $cwd . "/" . $configuration->{'stats'}
245
   if $configuration->{'stats'} && $configuration->{'stats'} !~ m/\//;
246
 
2 rodolico 247
# For each dataset, let's find the snapshots we need
248
foreach my $sourceDir ( keys %{$configuration->{'source'}->{'dataset'}} ) {
10 rodolico 249
   #print "Working on $sourceDir\n";
7 rodolico 250
   print "Looking for $sourceDir\n" if $configuration->{'testing'} > 2;
251
   print "syncing to $configuration->{target}->{dataset}\n" if $configuration->{'testing'} > 2;
252
   my $command = $replicateScript . ' ' . join( ' ', @flags ) . ' ' .
253
                 '--source=' .
2 rodolico 254
                 $configuration->{'source'}->{'server'} . 
255
                 $configuration->{'source'}->{'dataset'}->{$sourceDir} . '/' . $sourceDir . ' ' .
7 rodolico 256
                 '--target=' .
2 rodolico 257
                 $configuration->{'target'}->{'server'} . 
7 rodolico 258
                 $configuration->{'target'}->{'dataset'} . '/' . $sourceDir;
10 rodolico 259
   #print "Command is $command\n";
7 rodolico 260
   push @status, &currentTime() . " Running $command";
261
   if ( ! $configuration->{'testing'} ) {
262
      ($error, $output) = &runCommand( $command );
16 rodolico 263
      push @status, "Dataset\t$sourceDir\n$output";
12 rodolico 264
      # update stats file if they have requested it
265
      &updateStats( $sourceDir, $configuration->{'stats'}, $output ) if $configuration->{'stats'};
7 rodolico 266
   }
267
   push @status, &currentTime() . " Completed command, with status $error";
2 rodolico 268
}
269
 
10 rodolico 270
#print "Finished processing\n";
271
#print "testing is " . $configuration->{'testing'} . "\n";
272
 
7 rodolico 273
push @status, &currentTime() . ' Backup finished';
2 rodolico 274
 
275
if ($configuration->{'testing'}) {
276
   print join( "\n", @status ) . "\n";
277
} else {
10 rodolico 278
   #print "Sending final email\n";
279
   &sendMail( join( "\n", @status ), $configuration, "Backup Complete" );
280
   #print "Running shutdown\n";
281
   &shutdownMachine( $configuration ) if $configuration->{'shutdown'};
2 rodolico 282
}
283
 
284
1;