Subversion Repositories zfs_utils

Rev

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