Imported Upstream version 3.3.1
[debian/amanda] / server-src / amrestore.pl
1 #! @PERL@
2 # Copyright (c) 2009, 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
26 use Amanda::Device qw( :constants );
27 use Amanda::Debug qw( :logging );
28 use Amanda::Config qw( :init :getconf config_dir_relative );
29 use Amanda::Util qw( :constants );
30 use Amanda::Changer;
31 use Amanda::Constants;
32 use Amanda::MainLoop;
33 use Amanda::MainLoop qw( :GIOCondition );
34 use Amanda::Header;
35 use Amanda::Holding;
36 use Amanda::Cmdline;
37 use Amanda::Tapelist;
38 use Amanda::Xfer qw( :constants );
39
40 sub usage {
41     my ($msg) = @_;
42     print STDERR "$msg\n" if $msg;
43     print STDERR <<EOF;
44 Usage: amrestore [--config config] [-b blocksize] [-r|-c|-C] [-p] [-h]
45     [-f filenum] [-l label] [-o configoption]*
46     {device | [--holding] holdingfile}
47     [hostname [diskname [datestamp [hostname [diskname [datestamp ... ]]]]]]"));
48 EOF
49     exit(1);
50 }
51
52 ##
53 # main
54
55 Amanda::Util::setup_application("amrestore", "server", $CONTEXT_CMDLINE);
56
57 my $config_overrides = new_config_overrides($#ARGV+1);
58
59 my ($opt_config, $opt_blocksize, $opt_raw, $opt_compress, $opt_compress_best,
60     $opt_pipe, $opt_header, $opt_filenum, $opt_label, $opt_holding, $opt_restore_src);
61
62 debug("Arguments: " . join(' ', @ARGV));
63 Getopt::Long::Configure(qw(bundling));
64 GetOptions(
65     'version' => \&Amanda::Util::version_opt,
66     'help|usage|?' => \&usage,
67     'config=s' => \$opt_config,
68     'holding' => \$opt_holding,
69     'b=i' => \$opt_blocksize,
70     'r' => \$opt_raw,
71     'c' => \$opt_compress,
72     'C' => \$opt_compress_best,
73     'p' => \$opt_pipe,
74     'h' => \$opt_header,
75     'f=i' => \$opt_filenum,
76     'l=s' => \$opt_label,
77     'o=s' => sub { add_config_override_opt($config_overrides, $_[1]); },
78 ) or usage();
79
80 $opt_compress = 1 if $opt_compress_best;
81
82 # see if we have a holding file or a device
83 usage("Must specify a device or holding-disk file") unless (@ARGV);
84 $opt_restore_src = shift @ARGV;
85 if (!$opt_holding) {
86     $opt_holding = 1
87         if (Amanda::Holding::get_header($opt_restore_src));
88 }
89
90 my @opt_dumpspecs = Amanda::Cmdline::parse_dumpspecs([@ARGV],
91     $Amanda::Cmdline::CMDLINE_PARSE_DATESTAMP);
92
93 usage("Cannot check a label on a holding-disk file")
94     if ($opt_holding and $opt_label);
95 usage("Cannot use both -r (raw) and -c/-C (compression) -- use -h instead")
96     if ($opt_raw and $opt_compress);
97
98 # -r implies -h, plus appending ".RAW" to filenames
99 $opt_header = 1 if $opt_raw;
100
101 set_config_overrides($config_overrides);
102 if ($opt_config) {
103     config_init($CONFIG_INIT_EXPLICIT_NAME, $opt_config);
104 } else {
105     config_init(0, undef);
106 }
107 my ($cfgerr_level, @cfgerr_errors) = config_errors();
108 if ($cfgerr_level >= $CFGERR_WARNINGS) {
109     config_print_errors();
110     if ($cfgerr_level >= $CFGERR_ERRORS) {
111         die("errors processing config file");
112     }
113 }
114
115 Amanda::Util::finish_setup($RUNNING_AS_DUMPUSER);
116
117 my $exit_status = 0;
118 my $res;
119
120 sub failure {
121     my ($msg, $finished_cb) = @_;
122     print STDERR "ERROR: $msg\n";
123     $exit_status = 1;
124     if ($res) {
125         $res->release(finished_cb => sub {
126             # ignore error
127             $finished_cb->();
128         });
129     } else {
130         $finished_cb->();
131     }
132 }
133
134 sub main {
135     my ($finished_cb) = @_;
136
137     my $dev;
138     my $hdr;
139     my $chg;
140     my $filenum = $opt_filenum;
141     $filenum = 1 if (!$filenum);
142     $filenum = 0 + "$filenum"; # convert to integer
143     my %all_filter;
144     my $restore_done;
145
146     my $steps = define_steps
147         cb_ref => \$finished_cb,
148         finalize => sub { $chg->quit() if defined $chg };
149
150     step start => sub {
151         # first, return to the original working directory we were started in
152         if (!chdir Amanda::Util::get_original_cwd()) {
153             return failure("Cannot chdir to original working directory", $finished_cb);
154         }
155
156         if ($opt_holding) {
157             $steps->{'read_header'}->();
158         } else {
159             my $tlf = Amanda::Config::config_dir_relative(getconf($CNF_TAPELIST));
160             my $tl = Amanda::Tapelist->new($tlf);
161             $chg = Amanda::Changer->new($opt_restore_src, tapelist => $tl);
162             if ($chg->isa("Amanda::Changer::Error")) {
163                 return failure($chg, $finished_cb);
164             }
165
166             $chg->load(relative_slot => "current", mode => "read",
167                 res_cb => $steps->{'slot_loaded'});
168         }
169     };
170
171     step slot_loaded => sub {
172         (my $err, $res) = @_;
173         return failure($err, $finished_cb) if $err;
174
175         $dev = $res->{'device'};
176         if ($dev->status != $DEVICE_STATUS_SUCCESS) {
177             return failure($dev->error_or_status, $finished_cb);
178         }
179
180         $steps->{'check_label'}->();
181     };
182
183     step check_label => sub {
184         if ($dev->status != $DEVICE_STATUS_SUCCESS) {
185             return failure($dev->error_or_status, $finished_cb);
186         }
187
188         if ($opt_label) {
189             if ($dev->volume_label ne $opt_label) {
190                 my $got = $dev->volume_label;
191                 return failure("Found unexpected label '$got'", $finished_cb);
192             }
193         }
194
195         my $lbl = $dev->volume_label;
196         print STDERR "Restoring from tape $lbl starting with file $filenum.\n";
197
198         $steps->{'start_device'}->();
199     };
200
201     step start_device => sub {
202         if (!$dev->start($ACCESS_READ, undef, undef)) {
203             return failure($dev->error_or_status(), $finished_cb);
204         }
205
206         $steps->{'read_header'}->();
207     };
208
209     step read_header => sub {
210         if ($opt_holding) {
211             print STDERR "Reading from '$opt_restore_src'\n";
212             $hdr = Amanda::Holding::get_header($opt_restore_src);
213         } else {
214             $hdr = $dev->seek_file($filenum);
215             if (!$hdr) {
216                 return failure("while reading next header: " . $dev->error_or_status(),
217                             $finished_cb);
218             } elsif ($hdr->{'type'} == $Amanda::Header::F_TAPEEND) {
219                 return $steps->{'finished'}->();
220             }
221
222             # seek_file may have skipped ahead; plan accordingly
223             $filenum = $dev->file + 1;
224         }
225
226         $steps->{'filter_dumpspecs'}->();
227     };
228
229     step filter_dumpspecs => sub {
230         if (@opt_dumpspecs and not $hdr->matches_dumpspecs([@opt_dumpspecs])) {
231             if (!$opt_holding) {
232                 my $dev_filenum = $dev->file;
233                 print STDERR "amrestore: $dev_filenum: skipping ",
234                         $hdr->summary(), "\n";
235             }
236
237             # skip to the next file without restoring this one
238             return $steps->{'next_file'}->();
239         }
240
241         if (!$opt_holding) {
242             my $dev_filenum = $dev->file;
243             print STDERR "amrestore: $dev_filenum: restoring ";
244         }
245         print STDERR $hdr->summary(), "\n";
246
247         $steps->{'xfer_dumpfile'}->();
248     };
249
250     step xfer_dumpfile => sub {
251         my ($src, $dest);
252
253         # set up the source..
254         if ($opt_holding) {
255             $src = Amanda::Xfer::Source::Holding->new($opt_restore_src);
256         } else {
257             $src = Amanda::Xfer::Source::Device->new($dev);
258         }
259
260         # and set up the destination..
261         my $dest_fh;
262         if ($opt_pipe) {
263             $dest_fh = \*STDOUT;
264         } else {
265             my $filename = sprintf("%s.%s.%s.%d",
266                     $hdr->{'name'},
267                     Amanda::Util::sanitise_filename("".$hdr->{'disk'}), # workaround SWIG bug
268                     $hdr->{'datestamp'},
269                     $hdr->{'dumplevel'});
270             if ($hdr->{'partnum'} > 0) {
271                 $filename .= sprintf(".%07d", $hdr->{'partnum'});
272             }
273
274             # add an appropriate suffix
275             if ($opt_raw) {
276                 $filename .= ".RAW";
277             } elsif ($opt_compress) {
278                 $filename .= ($hdr->{'compressed'} && $hdr->{'comp_suffix'})?
279                     $hdr->{'comp_suffix'} : $Amanda::Constants::COMPRESS_SUFFIX;
280             }
281
282             if (!open($dest_fh, ">", $filename)) {
283                 return failure("Could not open '$filename' for writing: $!", $finished_cb);
284             }
285         }
286         $dest = Amanda::Xfer::Dest::Fd->new($dest_fh);
287
288         # set up any filters that need to be applied, decryption first
289         my @filters;
290         if ($hdr->{'encrypted'} and not $opt_raw) {
291             if ($hdr->{'srv_encrypt'}) {
292                 push @filters,
293                     Amanda::Xfer::Filter::Process->new(
294                         [ $hdr->{'srv_encrypt'}, $hdr->{'srv_decrypt_opt'} ], 0);
295             } elsif ($hdr->{'clnt_encrypt'}) {
296                 push @filters,
297                     Amanda::Xfer::Filter::Process->new(
298                         [ $hdr->{'clnt_encrypt'}, $hdr->{'clnt_decrypt_opt'} ], 0);
299             } else {
300                 return failure("could not decrypt encrypted dump: no program specified",
301                             $finished_cb);
302             }
303
304             $hdr->{'encrypted'} = 0;
305             $hdr->{'srv_encrypt'} = '';
306             $hdr->{'srv_decrypt_opt'} = '';
307             $hdr->{'clnt_encrypt'} = '';
308             $hdr->{'clnt_decrypt_opt'} = '';
309             $hdr->{'encrypt_suffix'} = 'N';
310         }
311         if (!$opt_raw and $hdr->{'compressed'} and not $opt_compress) {
312             # need to uncompress this file
313
314             if ($hdr->{'srvcompprog'}) {
315                 # TODO: this assumes that srvcompprog takes "-d" to decompress
316                 push @filters,
317                     Amanda::Xfer::Filter::Process->new(
318                         [ $hdr->{'srvcompprog'}, "-d" ], 0);
319             } elsif ($hdr->{'clntcompprog'}) {
320                 # TODO: this assumes that clntcompprog takes "-d" to decompress
321                 push @filters,
322                     Amanda::Xfer::Filter::Process->new(
323                         [ $hdr->{'clntcompprog'}, "-d" ], 0);
324             } else {
325                 push @filters,
326                     Amanda::Xfer::Filter::Process->new(
327                         [ $Amanda::Constants::UNCOMPRESS_PATH,
328                           $Amanda::Constants::UNCOMPRESS_OPT ], 0);
329             }
330             
331             # adjust the header
332             $hdr->{'compressed'} = 0;
333             $hdr->{'uncompress_cmd'} = '';
334         } elsif (!$opt_raw and !$hdr->{'compressed'} and $opt_compress) {
335             # need to compress this file
336
337             my $compress_opt = $opt_compress_best?
338                 $Amanda::Constants::COMPRESS_BEST_OPT :
339                 $Amanda::Constants::COMPRESS_FAST_OPT;
340             @filters = (
341                 Amanda::Xfer::Filter::Process->new(
342                     [ $Amanda::Constants::COMPRESS_PATH,
343                       $compress_opt ], 0),
344             );
345             
346             # adjust the header
347             $hdr->{'compressed'} = 1;
348             $hdr->{'uncompress_cmd'} = " $Amanda::Constants::UNCOMPRESS_PATH " .
349                 "$Amanda::Constants::UNCOMPRESS_OPT |";
350             $hdr->{'comp_suffix'} = $Amanda::Constants::COMPRESS_SUFFIX;
351         }
352
353         # write the header to the destination if requested
354         if ($opt_header) {
355             $hdr->{'blocksize'} = Amanda::Holding::DISK_BLOCK_BYTES;
356             $dest_fh->syswrite($hdr->to_string(32768, 32768));
357         }
358
359         # start reading all filter stderr
360         foreach my $filter (@filters) {
361             my $fd = $filter->get_stderr_fd();
362             $fd.="";
363             $fd = int($fd);
364             my $src = Amanda::MainLoop::fd_source($fd,
365                                                   $G_IO_IN|$G_IO_HUP|$G_IO_ERR);
366             my $buffer = "";
367             $all_filter{$src} = 1;
368             $src->set_callback( sub {
369                 my $b;
370                 my $n_read = POSIX::read($fd, $b, 1);
371                 if (!defined $n_read) {
372                     return;
373                 } elsif ($n_read == 0) {
374                     delete $all_filter{$src};
375                     $src->remove();
376                     POSIX::close($fd);
377                     if (!%all_filter and $restore_done) {
378                         $finished_cb->();
379                     }
380                 } else {
381                     $buffer .= $b;
382                     if ($b eq "\n") {
383                         my $line = $buffer;
384                         print STDERR "filter stderr: $line";
385                         chomp $line;
386                         debug("filter stderr: $line");
387                         $buffer = "";
388                     }
389                 }
390             });
391         }
392         
393         my $xfer = Amanda::Xfer->new([ $src, @filters, $dest ]);
394         my $got_err = undef;
395         $xfer->get_source()->set_callback(sub {
396             my ($src, $msg, $xfer) = @_;
397
398             if ($msg->{'type'} == $XMSG_INFO) {
399                 Amanda::Debug::info($msg->{'message'});
400             } elsif ($msg->{'type'} == $XMSG_ERROR) {
401                 $got_err = $msg->{'message'};
402             } elsif ($msg->{'type'} == $XMSG_DONE) {
403                 $src->remove();
404                 $steps->{'xfer_done'}->($got_err);
405             }
406         });
407         $xfer->start();
408     };
409
410     step xfer_done => sub {
411         my ($err) = @_;
412         return failure($err, $finished_cb) if $err;
413
414         $steps->{'next_file'}->('extracted');
415     };
416
417     step next_file => sub {
418         my ($extracted) = @_;
419         # amrestore does not loop over multiple files when reading from holding
420         # when outputting to a pipe amrestore extracts only the first file
421         if ($opt_holding or ($opt_pipe and $extracted)) {
422             return $steps->{'finished'}->();
423         }
424
425         # otherwise, try to read the next header from the device
426         $steps->{'read_header'}->();
427     };
428
429     step finished => sub {
430         if ($res) {
431             $res->release(finished_cb => $steps->{'quit'});
432         } else {
433             $steps->{'quit'}->();
434         }
435     };
436
437     step quit => sub {
438         my ($err) = @_;
439         $res = undef;
440         $restore_done = 1;
441         return failure($err, $finished_cb) if $err;
442
443         if (!%all_filter) {
444             $finished_cb->();
445         }
446     };
447 }
448 main(\&Amanda::MainLoop::quit);
449 Amanda::MainLoop::run();
450 Amanda::Util::finish_application();
451 exit $exit_status;