04499f5b89318fe808c3d8e42ab0df02b36b57b8
[debian/amanda] / server-src / amdump.pl
1 #! @PERL@
2 # Copyright (c) 2010 Zmanda Inc.  All Rights Reserved.
3 #
4 # This program is free software; you can redistribute it and/or modify it
5 # under the terms of the GNU General Public License version 2 as published
6 # by the Free Software Foundation.
7 #
8 # This program is distributed in the hope that it will be useful, but
9 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
10 # or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
11 # for more details.
12 #
13 # You should have received a copy of the GNU General Public License along
14 # with this program; if not, write to the Free Software Foundation, Inc.,
15 # 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 #
17 # Contact information: Zmanda Inc., 465 S. Mathilda Ave., Suite 300
18 # Sunnyvale, CA 94086, USA, or: http://www.zmanda.com
19
20 use lib '@amperldir@';
21 use strict;
22 use warnings;
23
24 use Getopt::Long;
25 use POSIX qw(WIFEXITED WEXITSTATUS strftime);
26
27 use Amanda::Config qw( :init :getconf );
28 use Amanda::Util qw( :constants );
29 use Amanda::Logfile qw( :logtype_t log_add );
30 use Amanda::Debug qw( debug );
31 use Amanda::Paths;
32
33 ##
34 # Main
35
36 sub usage {
37     my ($msg) = @_;
38     print STDERR <<EOF;
39 Usage: amdump <conf> [--no-taper] [--from-client] [-o configoption]* [host/disk]*
40 EOF
41     print STDERR "$msg\n" if $msg;
42     exit 1;
43 }
44
45 Amanda::Util::setup_application("amdump", "server", $CONTEXT_DAEMON);
46
47 my $config_overrides = new_config_overrides($#ARGV+1);
48 my @config_overrides_opts;
49
50 my $opt_no_taper = 0;
51 my $opt_from_client = 0;
52
53 debug("Arguments: " . join(' ', @ARGV));
54 Getopt::Long::Configure(qw(bundling));
55 GetOptions(
56     'version' => \&Amanda::Util::version_opt,
57     'help|usage|?' => \&usage,
58     'no-taper' => \$opt_no_taper,
59     'from-client' => \$opt_from_client,
60     'o=s' => sub {
61         push @config_overrides_opts, "-o" . $_[1];
62         add_config_override_opt($config_overrides, $_[1]);
63     },
64 ) or usage();
65
66 usage("No config specified") if (@ARGV < 1);
67
68 my $config_name = shift @ARGV;
69 set_config_overrides($config_overrides);
70 config_init($CONFIG_INIT_EXPLICIT_NAME, $config_name);
71 my ($cfgerr_level, @cfgerr_errors) = config_errors();
72 if ($cfgerr_level >= $CFGERR_WARNINGS) {
73     config_print_errors();
74     if ($cfgerr_level >= $CFGERR_ERRORS) {
75         die("errors processing config file");
76     }
77 }
78
79 Amanda::Util::finish_setup($RUNNING_AS_DUMPUSER);
80
81 # useful info for below
82 my @hostdisk = @ARGV;
83 my $logdir = getconf($CNF_LOGDIR);
84 my @now = localtime;
85 my $longdate = strftime "%a %b %e %H:%M:%S %Z %Y", @now;
86 my $timestamp = strftime "%Y%m%d%H%M%S", @now;
87 my $datestamp = strftime "%Y%m%d", @now;
88 my $starttime_locale_independent = strftime "%Y-%m-%d %H:%M:%S %Z", @now;
89 my $trace_log_filename = "$logdir/log";
90 my $amdump_log_filename = "$logdir/amdump";
91 my $exit_code = 0;
92 my $amdump_log = \*STDERR;
93
94 ##
95 # subs for below
96
97 sub amdump_log {
98     print $amdump_log "amdump: ", @_, "\n";
99 }
100
101 sub check_exec {
102     my ($prog) = @_;
103     return if -x $prog;
104
105     log_add($L_ERROR, "Can't execute $prog");
106 }
107
108 sub run_subprocess {
109     my ($proc, @args) = @_;
110     check_exec($proc);
111
112     my $pid = POSIX::fork();
113     if ($pid == 0) {
114         my $null = POSIX::open("/dev/null", POSIX::O_RDWR);
115         POSIX::dup2($null, 0);
116         POSIX::dup2($null, 1);
117         POSIX::dup2(fileno($amdump_log), 2);
118         close($amdump_log);
119         exec $proc, @args;
120         die "Could not exec $proc: $!";
121     }
122     waitpid($pid, 0);
123     my $s = $? >> 8;
124     debug("$proc exited with code $s");
125     if ($?) {
126         if ($exit_code == 0) {
127             debug("ignoring failing exit code $s from $proc");
128         } else {
129             debug("recording failing exit code $s from $proc for amdump exit");
130             $exit_code = $s;
131         }
132     }
133 }
134
135 sub wait_for_hold {
136     my $holdfile = "$CONFIG_DIR/$config_name/hold";
137     if (-f $holdfile) {
138         debug("waiting for hold file '$holdfile' to be removed");
139         while (-f $holdfile) {
140             sleep(60);
141         }
142     }
143 }
144
145 sub bail_already_running {
146     my $msg = "An Amanda process is already running - please run amcleanup manually";
147     debug($msg);
148     amdump_log($msg);
149
150     # put together a fake logfile and send an amreport
151     my $fakelogfile = "$AMANDA_TMPDIR/fakelog.$$";
152     open(my $fakelog, ">", $fakelogfile)
153         or die("cannot open a fake log to send an report - situation is dire");
154     print $fakelog <<EOF;
155 INFO amdump amdump pid $$
156 START planner date $timestamp
157 START driver date $timestamp
158 ERROR amdump $msg
159 EOF
160     run_subprocess("$sbindir/amreport", $config_name, '--from-amdump', '-l', $fakelogfile, @config_overrides_opts);
161     unlink($fakelogfile);
162
163     # and we're done here
164     exit 1;
165 }
166
167 sub do_amcleanup {
168     return unless -f $amdump_log_filename || -f $trace_log_filename;
169
170     # logfiles are still around.  First, try an amcleanup -p to see if
171     # the actual processes are already dead
172     debug("runing amcleanup -p");
173     run_subprocess("$sbindir/amcleanup", '-p', $config_name, @config_overrides_opts);
174
175     # and check again
176     return unless -f $amdump_log_filename || -f $trace_log_filename;
177
178     bail_already_running();
179 }
180
181 sub start_logfiles {
182     debug("beginning trace log");
183     # start the trace log by simply writing an INFO line to it
184     log_add($L_INFO, "amdump pid $$");
185
186     # but not so fast!  What if another process has also appended such a line?
187     open(my $tl, "<", $trace_log_filename)
188         or die("could not open trace log file '$trace_log_filename': $!");
189     if (<$tl> !~ /^INFO amdump amdump pid $$/) {
190         # we didn't get there first, so bail out
191         debug("another amdump raced with this one, and won");
192         bail_already_running();
193     }
194     close($tl);
195
196     # redirect the amdump_log to the proper filename instead of stderr
197     # note that perl will overwrite STDERR if we don't set $amdump_log to
198     # undef first.. stupid perl.
199     debug("beginning amdump log");
200     $amdump_log = undef;
201     # Must be opened in append so that all subprocess can write to it.
202     open($amdump_log, ">>", $amdump_log_filename)
203         or die("could not open amdump log file '$amdump_log_filename': $!");
204 }
205
206 sub planner_driver_pipeline {
207     my $planner = "$amlibexecdir/planner";
208     my $driver = "$amlibexecdir/driver";
209     my @no_taper = $opt_no_taper? ('--no-taper'):();
210     my @from_client = $opt_from_client? ('--from-client'):();
211
212     check_exec($planner);
213     check_exec($driver);
214
215     # Perl's open3 is an embarassment to the language.  We'll do this manually.
216     debug("invoking planner | driver");
217     my ($rpipe, $wpipe) = POSIX::pipe();
218
219     my $pl_pid = POSIX::fork();
220     if ($pl_pid == 0) {
221         ## child
222         my $null = POSIX::open("/dev/null", POSIX::O_RDWR);
223         POSIX::dup2($null, 0);
224         POSIX::close($null);
225         POSIX::dup2($wpipe, 1);
226         POSIX::close($rpipe);
227         POSIX::close($wpipe);
228         POSIX::dup2(fileno($amdump_log), 2);
229         close($amdump_log);
230         exec $planner,
231             # note that @no_taper must follow --starttime
232             $config_name, '--starttime', $timestamp, @no_taper, @from_client, @config_overrides_opts, @hostdisk;
233         die "Could not exec $planner: $!";
234     }
235     debug(" planner: $pl_pid");
236
237     my $dr_pid = POSIX::fork();
238     if ($dr_pid == 0) {
239         ## child
240         my $null = POSIX::open("/dev/null", POSIX::O_RDWR);
241         POSIX::dup2($rpipe, 0);
242         POSIX::close($rpipe);
243         POSIX::close($wpipe);
244         POSIX::dup2(fileno($amdump_log), 1); # driver does lots of logging to stdout..
245         POSIX::close($null);
246         POSIX::dup2(fileno($amdump_log), 2);
247         close($amdump_log);
248         exec $driver,
249             $config_name, @no_taper, @from_client, @config_overrides_opts;
250         die "Could not exec $driver: $!";
251     }
252     debug(" driver: $dr_pid");
253
254     POSIX::close($rpipe);
255     POSIX::close($wpipe);
256
257     my $first_bad_exit = 0;
258     for (my $i = 0; $i < 2; $i++) {
259         my $dead = wait();
260         die("Error waiting: $!") if ($dead <= 0);
261         my $s = $? >> 8;
262         debug("planner finished with exit code $s") if $dead == $pl_pid;
263         debug("driver finished with exit code $s") if $dead == $dr_pid;
264         my $exit = WIFEXITED($?)? WEXITSTATUS($?) : 1;
265         $first_bad_exit = $exit if ($exit && !$first_bad_exit)
266     }
267     $exit_code |= $first_bad_exit;
268 }
269
270 sub do_amreport {
271     debug("running amreport");
272     run_subprocess("$sbindir/amreport", $config_name, '--from-amdump', @config_overrides_opts);
273 }
274
275 sub roll_trace_logs {
276     my $t = getconf($CNF_USETIMESTAMPS)? $timestamp : $datestamp;
277     debug("renaming trace log");
278     Amanda::Logfile::log_rename($t)
279 }
280
281 sub trim_trace_logs {
282     debug("trimming old trace logs");
283     run_subprocess("$amlibexecdir/amtrmlog", $config_name, @config_overrides_opts);
284 }
285
286 sub trim_indexes {
287     debug("trimming old indexes");
288     run_subprocess("$amlibexecdir/amtrmidx", $config_name, @config_overrides_opts);
289 }
290
291 sub roll_amdump_logs {
292     debug("renaming amdump log and trimming old amdump logs (beyond tapecycle+2)");
293
294     # rename all the way along the tapecycle
295     my $days = getconf($CNF_TAPECYCLE) + 2;
296     for (my $i = $days-1; $i >= 1; $i--) {
297         next unless -f "$amdump_log_filename.$i";
298         rename("$amdump_log_filename.$i", "$amdump_log_filename.".($i+1));
299     }
300
301     # now swap the current logfile in
302     rename("$amdump_log_filename", "$amdump_log_filename.1");
303 }
304
305 # now do the meat of the amdump work; these operations are ported directly
306 # from the old amdump.sh script
307
308 # wait for $confdir/hold to disappear
309 wait_for_hold();
310
311 # look for a current logfile, and if found run amcleanup -p, and if that fails
312 # bail out
313 do_amcleanup();
314
315 my $crtl_c = 0;
316 $SIG{INT} = \&interrupt;
317
318 sub interrupt {
319     $crtl_c = 1;
320 }
321
322 # start up the log file
323 start_logfiles();
324
325 # amstatus needs a lot of forms of the time, I guess
326 amdump_log("start at $longdate");
327 amdump_log("datestamp $datestamp");
328 amdump_log("starttime $timestamp");
329 amdump_log("starttime-locale-independent $starttime_locale_independent");
330
331 # run the planner and driver, the one piped to the other
332 planner_driver_pipeline();
333
334 if ($crtl_c == 1) {
335     print "Caught a ctrl-c\n";
336     log_add($L_FATAL, "amdump killed by ctrl-c");
337     debug("Caught a ctrl-c");
338     $exit_code = 1;
339 }
340 $SIG{INT} = 'DEFAULT';
341
342 my $end_longdate = strftime "%a %b %e %H:%M:%S %Z %Y", localtime;
343 amdump_log("end at $end_longdate");
344
345 # send the dump report
346 do_amreport();
347
348 # do some house-keeping
349 roll_trace_logs();
350 trim_trace_logs();
351 trim_indexes();
352 roll_amdump_logs();
353
354 debug("exiting with code $exit_code");
355 exit($exit_code);