Subversion Repositories sysadmin_scripts

Rev

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

Rev Author Line No. Line
166 rodolico 1
#! /usr/bin/env perl
2
 
3
use strict;
4
use warnings;
5
 
6
use YAML::Tiny; # pkg install p5-YAML-Tiny-1.74
7
 
8
BEGIN {
9
   use FindBin;
10
   use File::Spec;
11
   # use libraries from the directory this script is in
12
   use Cwd 'abs_path';
13
   use File::Basename;
14
   use lib dirname( abs_path( __FILE__ ) );
15
}
16
 
17
my $cwd = $FindBin::RealBin;
18
my $configFileName = $cwd . '/sync.yaml';
19
my $replicateScript = $cwd . '/replicate';
20
 
21
my $TESTING=1;
22
 
23
my $configuration;
24
 
25
use Data::Dumper;
26
use Email::Simple; # cpan install Email::Simple
27
 
28
# load Configuration File
29
# read the config file and return it
30
sub readConfig {
31
   my $filename = shift;
32
   my $yaml = YAML::Tiny->new( {} );
33
   if ( -f $filename ) {
34
      $yaml = YAML::Tiny->read( $filename );
35
   }
36
   return $yaml->[0];
37
}
38
 
39
 
40
 
41
# this calls gshred which will overwrite the file 3 times, then
42
# remove it.
43
# NOTE: this will not work on ZFS, since ZFS is CopyOnWrite (COW)
44
# so assuming /tmp is a ramdisk
45
sub shredFile {
46
   my $filename = shift;
47
   `/usr/local/bin/gshred -u -f -s 32 $filename`;
48
}
49
 
50
 
51
# runs a command, redirecting stderr to stdout (which it ignores)
52
# then returns 0 on success.
53
# if error, returns string describing error
54
sub runCommand {
55
   my $command = shift;
56
   qx/$command 2>&1/;
57
   if ($? == -1) {
58
      return "failed to execute: $!";
59
   } elsif ($? & 127) {
60
      return sprintf "child died with signal %d, %s coredump",
61
        ($? & 127),  ($? & 128) ? 'with' : 'without';
62
   } else {
63
      return sprintf "child exited with value %d", $? >> 8 if $? >> 8;
64
   }
65
   return 0;
66
}
67
 
68
# grabs the encryption key from the remote server, and uses it to unlock the 
69
# datasets, then mount the drives.
70
# a return of '' is success, anything else is an error
71
sub mountDrives {
72
   my $config = shift;
73
   # try to grab the file from the remote machine
74
   &runCommand( "scp $config->{remoteMachine}->{ip}:$config->{remoteMachine}->{encryptionKeyPath} $config->{localMachine}->{encryptionKeyPath}" );
75
   # If we do not have the encryption key, we need to abort
76
   return "Could not copy file $config->{remoteMachine}->{ip}:$config->{remoteMachine}->{encryptionKeyPath}, aborting" 
77
      unless -f $config->{'localMachine'}->{'encryptionKeyPath'};
78
   my $error = '';
79
   # load the key into zfs and unlock all volumes
80
   $error = &runCommand( "zfs load-key -a" );
81
   # finally, remount all of the zfs shares which need the key
82
   $error = &runCommand( "zfs mount -a" ) unless $error;
83
   # if we succeeded, we want to shred the keyfile
84
   &shredFile( $config->{localMachine}->{encryptionKeyPath} ) if -f $config->{localMachine}->{encryptionKeyPath};
85
   return $error;
86
}
87
 
88
# a very simple mailer, using Email::Simple to just get status messages out
89
sub sendMail {
90
   my ($message, $config, $subject ) = @_;
91
   $config->{'email'}->{'notify'} = 'root' unless $config->{'email'}->{'notify'};
92
   die "No message in outgoing message\n" unless $message;
93
   my $email = Email::Simple->create(
94
      header => [
95
         To     => $config->{'email'}->{'notify'},
96
         Subject=> $config->{'email'}->{'subject'} . ( $subject ? " - $subject" : '' ),
97
         From   => $config->{'email'}->{'from'}
98
      ],
99
      body => $message
100
   );
101
   $message = $email->as_string;
102
   `echo '$message' | sendmail $config->{'email'}->{'notify'}`;
103
}
104
 
105
# checks to see if we should be in maintenance mode
106
# if $remoteMachine->{'maintenanceMode'} exists, set mode
107
# otherwise, wait localMachine->{'waittime'} minutes, then check
108
# $localMachine->{'maintenanceMode'}.
109
# if neither exists, begin sync
110
sub checkMaintenance {
111
   my $config = shift;
112
   # see if maintenance is set on remote. If so, simply return the message
113
   if ( $config->{'remoteMachine'}->{'up'} ) {
114
      if ( ! &runCommand( "ssh $configuration->{remoteMachine}->{ip} 'ls $configuration->{remoteMachine}->{maintenanceFlag}'" ) ) {
115
         # remove the file from the remote server
116
         &runCommand( "ssh $configuration->{remoteMachine}->{ip} 'rm $configuration->{remoteMachine}->{maintenanceFlag}'" );
117
         # create a valid return, which will exit the program
118
         return "Maintenance Flag found on remote machine";
119
      }
120
   }
121
   # not on remote machine, so give them waitTime seconds to put it here
122
   # we'll loop, checking every $sleepTime seconds until our wait time
123
   # ($config->{'localMachine'}->{'waitTime'}) has expired
124
   my $sleepTime = 60;
125
   for ( my $i = $config->{'localMachine'}->{'waitTime'}; $i > 0; $i -= $sleepTime ) {
126
      sleep $sleepTime;
127
      # then look for the maintenance flag file on the local machine
128
      return "Maintenance Flag found on local machine" if -f $config->{'localMachine'}->{'maintenanceFlag'};
129
   }
130
   # no maintenance flags found, so return false
131
   return 0;
132
}
133
 
134
sub shutdownMachine {
135
   my $config = shift;
136
   my $subject = shift;
137
   push @_, "Shutting down";
138
   &sendMail( join( "\n", @_), $configuration, $subject );   
139
   &runCommand( "poweroff" ) unless $TESTING;
140
   die "Shutting down machine now\n";
141
}
142
 
143
# returns the current time as a string
144
sub currentTime {
145
   my $format = shift;
146
   # default to YY-MM-DD HH-MM-SS
147
   $format = '%Y-%m-%d %H-%M-%S' unless $format;
148
   use POSIX;
149
   return POSIX::strftime( $format, localtime() );
150
}
151
 
152
my @status;   
153
 
154
$configuration = &readConfig($configFileName);
155
 
156
&sendMail( "mc-009 has been started, " . &currentTime() . " checking for maintenance mode", $configuration );
157
# see if remote machine is up by sending one ping. Expect response in 5 seconds
158
$configuration->{'remoteMachine'}->{'up'} = 
159
   ! &runCommand( "ping -c 1 -t 5 " . $configuration->{'remoteMachine'}->{'ip'} );
160
 
161
push @status, "remote machine ($configuration->{'remoteMachine'}->{'ip'}) is " . ( $configuration->{'remoteMachine'}->{'up'} ? 'Up' : 'Down' ) . "\n";
162
# check for maintenance flags, exit if we should go into mainteannce mode
163
#if ( my $result = &checkMaintenance( $configuration ) ) {
164
#   push @status,$result;
165
#   &sendMail( join( "\n", @status), $configuration, "Maintenance Mode" );
166
#   exit;
167
#}
168
 
169
# we can not connect to the remote server, so just shut down
170
&shutdownMachine( $configuration, "No connection to remote machine", @status ) unless $configuration->{'remoteMachine'}->{'up'};
171
 
172
# try to mount the datasets
173
my $error = &mountDrives( $configuration );
174
if ( $error ) { # could not mount datasets
175
   push @status, $error;
176
   &shutdownMachine( $configuration, "Mount Drive Error", @status );
177
}
178
 
179
&sendMail( "Backup has been started at " . &currentTime(), $configuration, "Backup Starting" );
180
push @status, "Backup started at: " . &currentTime();
181
 
182
 
183
# For each dataset, let's find the snapshots we need
184
foreach my $sourceDir ( keys %{$configuration->{'remoteMachine'}->{'dataset'}} ) {
185
   my $command = $replicateScript . ' ' .
186
                 $configuration->{'remoteMachine'}->{'ip'} . ':' . 
187
                 $configuration->{'remoteMachine'}->{'dataset'}->{$sourceDir} . '/' . $sourceDir . ' ' .
188
                 $configuration->{'localMachine'}->{'targetDataset'} . '/' . $sourceDir;
189
   print "$command\n";
190
}
191
 
192
push @status, "Backup finished at: " . &currentTime();
193
 
194
&shutdownMachine( $configuration, "Backup Complete", @status );
195
 
196
1;