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