Subversion Repositories zfs_utils

Rev

Rev 12 | Rev 16 | 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
14 rodolico 76
# THIS IS SERIOUSLY BROKEN. DON'T USE
2 rodolico 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
14 rodolico 118
# THIS IS BROKEN, DON'T USE
2 rodolico 119
sub checkMaintenance {
120
   my $configuration = shift;
121
   return 0 unless # exit if maintenanceFlag has not been set at all
122
     ( defined( $configuration->{'target'}->{'maintenanceFlag'} ) && $configuration->{'target'}->{'maintenanceFlag'} ) ||
123
     ( defined( $configuration->{'source'}->{'maintenanceFlag'} ) && $configuration->{'source'}->{'maintenanceFlag'} );
124
   # see if maintenance is set on remote. If so, simply return the message
125
   if ( $configuration->{'source'}->{'up'} ) {
126
      my ($error, $output) = &runCommand( "ssh $configuration->{remoteMachine}->{ip} 'ls $configuration->{remoteMachine}->{maintenanceFlag}'" );
127
      if ( ! $error ) {
128
         # remove the file from the remote server
129
         &runCommand( "ssh $configuration->{remoteMachine}->{ip} 'rm $configuration->{remoteMachine}->{maintenanceFlag}'" );
130
         # create a valid return, which will exit the program
131
         return "Maintenance Flag found on remote machine";
132
      }
133
   }
134
   # not on remote machine, so give them waitTime seconds to put it here
135
   # we'll loop, checking every $sleepTime seconds until our wait time
136
   # ($configuration->{'target'}->{'waitTime'}) has expired
137
   my $sleepTime = 60;
138
   for ( my $i = $configuration->{'target'}->{'waitTime'}; $i > 0; $i -= $sleepTime ) {
139
      sleep $sleepTime;
140
      # then look for the maintenance flag file on the local machine
141
      return "Maintenance Flag found on local machine" if -f $configuration->{'target'}->{'maintenanceFlag'};
142
   }
143
   # no maintenance flags found, so return false
144
   return 0;
145
}
146
 
147
sub shutdownMachine {
148
   my $configuration = shift;
10 rodolico 149
   exit unless $configuration->{'shutdown'};
2 rodolico 150
   # do not actually shut down the server unless we are told to
151
   &runCommand( "poweroff" ) unless $configuration->{'testing'};
152
}
153
 
154
# returns the current time as a string
155
sub currentTime {
156
   my $format = shift;
157
   # default to YY-MM-DD HH-MM-SS
158
   $format = '%Y-%m-%d %H-%M-%S' unless $format;
159
   use POSIX;
160
   return POSIX::strftime( $format, localtime() );
161
}
162
 
7 rodolico 163
# verify a remote machine is up and running
2 rodolico 164
sub checkRemoteUp {
165
   my $configuration = shift;
166
   my $ip;
167
   if ( defined( $configuration->{'target'}->{'server'} ) && $configuration->{'target'}->{'server'} ) {
168
      $ip = $configuration->{'target'}->{'server'};
169
   } else {
170
      $ip = $configuration->{'source'}->{'server'};
171
   }
172
   my ($error, $message ) =  $ip ? &runCommand( "ping -c 1 -t 5 $ip" ) : (0,'No address defined for either target or server' );
7 rodolico 173
#   $message = "Checking IP $ip\n"  . $message;
2 rodolico 174
   #die "error is $error, message is $message for $ip\n";
175
   return ($error, $message);
176
}
177
 
12 rodolico 178
sub updateStats {
179
   my ( $label, $filename, $output ) = @_;
180
   if ( $output =~ m/bytes\t(\d+).*seconds\t(\d+)/gms ) { # global, multiline, . matches newlines
181
      my $seconds = $2;
182
      my $bytes = $1;
183
      open STATS,">>$filename" or warn "Could not create file $filename: $!\n";
184
      print STATS &currentTime . "\t$label\t$seconds\t$bytes\n";
185
      close STATS
186
   } else {
187
      warn "updateStats called with invalid report\n";
188
   }
189
}
190
 
2 rodolico 191
my @status;   
192
my $error = 0;
193
my $output = '';
194
 
195
$configuration = &readConfig($configFileName);
196
 
197
# die Dumper( $configuration ) . "\n";
198
 
199
my $servername = `hostname`;
200
chomp $servername;
201
 
7 rodolico 202
push @status, "Replication on $servername has been started at " . &currentTime();
2 rodolico 203
&sendMail( "Replication on $servername has been started, " . &currentTime(), $configuration, "Replication on $servername started" );
204
 
205
# see if remote machine is up by sending one ping. Expect response in 5 seconds
206
( $error,$output) = &checkRemoteUp( $configuration );
207
$configuration->{'up'} = ! $error;
208
push @status, "remote machine is " . ( $configuration->{'up'} ? 'Up' : 'Down' ) . "\n";
10 rodolico 209
if ( ! $configuration->{'up'} ) {
210
   # we can not connect to the remote server, so just shut down
211
   sendMail( join( "\n", @status ), $configuration, "No connection to remote machine" );
212
   &shutdownMachine( $configuration );
213
}
2 rodolico 214
 
215
# check for maintenance flags, exit if we should go into mainteance mode
216
if ( my $result = &checkMaintenance( $configuration ) ) {
217
   push @status,$result;
218
   &sendMail( join( "\n", @status), $configuration, "Maintenance Mode" );
219
   die;
220
}
221
 
222
# try to mount the datasets if they are encrypted
223
($error,$output) = &mountDrives( $configuration );
224
if ( $error ) { # could not mount datasets
10 rodolico 225
   push @status, $output;
226
   &sendMail( join( "\n", @status ), $configuration, "Mount Drive Error: [$output]" );
227
   &shutdownMachine( $configuration );
2 rodolico 228
}
229
 
10 rodolico 230
#&sendMail( "Backup has been started at " . &currentTime(), $configuration, "Backup Starting" );
7 rodolico 231
push @status, &currentTime() . ' Backup started';
2 rodolico 232
 
233
$configuration->{'source'}->{'server'} = $configuration->{'source'}->{'server'} ? $configuration->{'source'}->{'server'} . ':' : '';
234
$configuration->{'target'}->{'server'} = $configuration->{'target'}->{'server'} ? $configuration->{'target'}->{'server'} . ':' : '';
235
 
7 rodolico 236
my @flags;
237
push @flags, '--dryrun' if $configuration->{'dryrun'};
238
push @flags, '--recurse' if $configuration->{'recurse'};
239
push @flags, '--verbose' if $configuration->{'verbose'};
240
push @flags, '--verbose' if $configuration->{'verbose'} > 1;
10 rodolico 241
push @flags, "--bwlimit=$configuration->{bandwidth}" if $configuration->{'bandwidth'};
7 rodolico 242
push @flags, "--filter='$configuration->{filter}'" if $configuration->{'filter'};
243
 
12 rodolico 244
# prepend the current working directory to stats if it does not have a path
245
$configuration->{'stats'} = $cwd . "/" . $configuration->{'stats'}
246
   if $configuration->{'stats'} && $configuration->{'stats'} !~ m/\//;
247
 
2 rodolico 248
# For each dataset, let's find the snapshots we need
249
foreach my $sourceDir ( keys %{$configuration->{'source'}->{'dataset'}} ) {
10 rodolico 250
   #print "Working on $sourceDir\n";
7 rodolico 251
   print "Looking for $sourceDir\n" if $configuration->{'testing'} > 2;
252
   print "syncing to $configuration->{target}->{dataset}\n" if $configuration->{'testing'} > 2;
253
   my $command = $replicateScript . ' ' . join( ' ', @flags ) . ' ' .
254
                 '--source=' .
2 rodolico 255
                 $configuration->{'source'}->{'server'} . 
256
                 $configuration->{'source'}->{'dataset'}->{$sourceDir} . '/' . $sourceDir . ' ' .
7 rodolico 257
                 '--target=' .
2 rodolico 258
                 $configuration->{'target'}->{'server'} . 
7 rodolico 259
                 $configuration->{'target'}->{'dataset'} . '/' . $sourceDir;
10 rodolico 260
   #print "Command is $command\n";
7 rodolico 261
   push @status, &currentTime() . " Running $command";
262
   if ( ! $configuration->{'testing'} ) {
263
      ($error, $output) = &runCommand( $command );
264
      push @status, $output;
12 rodolico 265
      # update stats file if they have requested it
266
      &updateStats( $sourceDir, $configuration->{'stats'}, $output ) if $configuration->{'stats'};
7 rodolico 267
   }
268
   push @status, &currentTime() . " Completed command, with status $error";
2 rodolico 269
}
270
 
10 rodolico 271
#print "Finished processing\n";
272
#print "testing is " . $configuration->{'testing'} . "\n";
273
 
7 rodolico 274
push @status, &currentTime() . ' Backup finished';
2 rodolico 275
 
276
if ($configuration->{'testing'}) {
277
   print join( "\n", @status ) . "\n";
278
} else {
10 rodolico 279
   #print "Sending final email\n";
280
   &sendMail( join( "\n", @status ), $configuration, "Backup Complete" );
281
   #print "Running shutdown\n";
282
   &shutdownMachine( $configuration ) if $configuration->{'shutdown'};
2 rodolico 283
}
284
 
285
1;