Imported Upstream version 3.3.0
[debian/amanda] / server-src / amvault.pl
1 #! @PERL@
2 # Copyright (c) 2008, 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 package main::Interactivity;
25 use POSIX qw( :errno_h );
26 use Amanda::MainLoop qw( :GIOCondition );
27 use vars qw( @ISA );
28 @ISA = qw( Amanda::Interactivity );
29
30 sub new {
31     my $class = shift;
32
33     my $self = {
34         input_src => undef};
35     return bless ($self, $class);
36 }
37
38 sub abort() {
39     my $self = shift;
40
41     if ($self->{'input_src'}) {
42         $self->{'input_src'}->remove();
43         $self->{'input_src'} = undef;
44     }
45 }
46
47 sub user_request {
48     my $self = shift;
49     my %params = @_;
50     my %subs;
51     my $buffer = "";
52
53     my $message  = $params{'message'};
54     my $label    = $params{'label'};
55     my $err      = $params{'err'};
56     my $chg_name = $params{'chg_name'};
57
58     $subs{'data_in'} = sub {
59         my $b;
60         my $n_read = POSIX::read(0, $b, 1);
61         if (!defined $n_read) {
62             return if ($! == EINTR);
63             $self->abort();
64             return $params{'request_cb'}->(
65                 Amanda::Changer::Error->new('fatal',
66                         message => "Fail to read from stdin"));
67         } elsif ($n_read == 0) {
68             $self->abort();
69             return $params{'request_cb'}->(
70                 Amanda::Changer::Error->new('fatal',
71                         message => "Aborted by user"));
72         } else {
73             $buffer .= $b;
74             if ($b eq "\n") {
75                 my $line = $buffer;
76                 chomp $line;
77                 $buffer = "";
78                 $self->abort();
79                 return $params{'request_cb'}->(undef, $line);
80             }
81         }
82     };
83
84     print STDERR "$err\n";
85     print STDERR "Insert volume labeled '$label' in $chg_name\n";
86     print STDERR "and press enter, or ^D to abort.\n";
87
88     $self->{'input_src'} = Amanda::MainLoop::fd_source(0, $G_IO_IN|$G_IO_HUP|$G_IO_ERR);
89     $self->{'input_src'}->set_callback($subs{'data_in'});
90     return;
91 };
92
93 package Amvault;
94
95 use Amanda::Config qw( :getconf config_dir_relative );
96 use Amanda::Debug qw( :logging );
97 use Amanda::Xfer qw( :constants );
98 use Amanda::Header qw( :constants );
99 use Amanda::MainLoop;
100 use Amanda::Util qw( quote_string );
101 use Amanda::DB::Catalog;
102 use Amanda::Recovery::Planner;
103 use Amanda::Recovery::Scan;
104 use Amanda::Recovery::Clerk;
105 use Amanda::Taper::Scan;
106 use Amanda::Taper::Scribe qw( get_splitting_args_from_config );
107 use Amanda::Changer qw( :constants );
108 use Amanda::Cmdline;
109 use Amanda::Paths;
110 use Amanda::Logfile qw( :logtype_t log_add log_add_full
111                         log_rename $amanda_log_trace_log make_stats
112                         match_datestamp match_level );
113
114 use base qw(
115     Amanda::Recovery::Clerk::Feedback
116     Amanda::Taper::Scribe::Feedback
117 );
118
119 sub new {
120     my $class = shift;
121     my %params = @_;
122
123     bless {
124         quiet => $params{'quiet'},
125         fulls_only => $params{'fulls_only'},
126         opt_export => $params{'opt_export'},
127         opt_dumpspecs => $params{'opt_dumpspecs'},
128         opt_dry_run => $params{'opt_dry_run'},
129         config_name => $params{'config_name'},
130
131         src_write_timestamp => $params{'src_write_timestamp'},
132
133         dst_changer => $params{'dst_changer'},
134         dst_autolabel => $params{'dst_autolabel'},
135         dst_write_timestamp => $params{'dst_write_timestamp'},
136
137         src => undef,
138         dst => undef,
139         cleanup => {},
140
141         exporting => 0, # is an export in progress?
142         call_after_export => undef, # call this when export complete
143         config_overrides_opts => $params{'config_overrides_opts'},
144
145         # called when the operation is complete, with the exit
146         # status
147         exit_cb => undef,
148     }, $class;
149 }
150
151 sub run {
152     my $self = shift;
153     my ($exit_cb) = @_;
154
155     die "already called" if $self->{'exit_cb'};
156     $self->{'exit_cb'} = $exit_cb;
157
158     # check that the label template is valid
159     my $dst_label_template = $self->{'dst_autolabel'}->{'template'};
160     return $self->failure("Invalid label template '$dst_label_template'")
161         if ($dst_label_template =~ /%[^%]+%/
162             or $dst_label_template =~ /^[^%]+$/);
163
164     # open up a trace log file and put our imprimatur on it, unless dry_runing
165     if (!$self->{'opt_dry_run'}) {
166         log_add($L_INFO, "amvault pid $$");
167         log_add($L_START, "date " . $self->{'dst_write_timestamp'});
168         Amanda::Debug::add_amanda_log_handler($amanda_log_trace_log);
169         $self->{'cleanup'}{'roll_trace_log'} = 1;
170     }
171
172     $self->setup_src();
173 }
174
175 sub setup_src {
176     my $self = shift;
177
178     my $src = $self->{'src'} = {};
179
180     # put together a clerk, which of course requires a changer, scan,
181     # interactivity, and feedback
182     my $chg = Amanda::Changer->new();
183     return $self->failure("Error opening source changer: $chg")
184         if $chg->isa('Amanda::Changer::Error');
185     $src->{'chg'} = $chg;
186
187     $src->{'seen_labels'} = {};
188
189     $src->{'interactivity'} = main::Interactivity->new();
190
191     $src->{'scan'} = Amanda::Recovery::Scan->new(
192             chg => $src->{'chg'},
193             interactivity => $src->{'interactivity'});
194
195     $src->{'clerk'} = Amanda::Recovery::Clerk->new(
196             changer => $src->{'chg'},
197             feedback => $self,
198             scan => $src->{'scan'});
199     $self->{'cleanup'}{'quit_clerk'} = 1;
200
201     # translate "latest" into the most recent timestamp that wasn't created by amvault
202     if (defined $self->{'src_write_timestamp'} && $self->{'src_write_timestamp'} eq "latest") {
203         my $ts = $self->{'src_write_timestamp'} =
204             Amanda::DB::Catalog::get_latest_write_timestamp(types => ['amdump', 'amflush']);
205         return $self->failure("No dumps found")
206             unless defined $ts;
207
208         $self->vlog("Using latest timestamp: $ts");
209     }
210
211     # we need to combine fulls_only, src_write_timestamp, and the set
212     # of dumpspecs.  If they contradict one another, then drop the
213     # non-matching dumpspec with a warning.
214     my @dumpspecs;
215     if ($self->{'opt_dumpspecs'}) {
216         my $level = $self->{'fulls_only'}? "0" : undef;
217         my $swt = $self->{'src_write_timestamp'};
218
219         # filter and adjust the dumpspecs
220         for my $ds (@{$self->{'opt_dumpspecs'}}) {
221             my $ds_host = $ds->{'host'};
222             my $ds_disk = $ds->{'disk'};
223             my $ds_datestamp = $ds->{'datestamp'};
224             my $ds_level = $ds->{'level'};
225             my $ds_write_timestamp = $ds->{'write_timestamp'};
226
227             if ($swt) {
228                 # it's impossible for parse_dumpspecs to set write_timestamp,
229                 # so there's no risk of overlap here
230                 $ds_write_timestamp = $swt;
231             }
232
233             if (defined $level) {
234                 if (defined $ds_level &&
235                     !match_level($ds_level, $level)) {
236                     $self->vlog("WARNING: dumpspec " . $ds->format() .
237                             " specifies non-full dumps, contradicting --fulls-only;" .
238                             " ignoring dumpspec");
239                     next;
240                 }
241                 $ds_level = $level;
242             }
243
244             # create a new dumpspec, since dumpspecs are immutable
245             push @dumpspecs, Amanda::Cmdline::dumpspec_t->new(
246                 $ds_host, $ds_disk, $ds_datestamp, $ds_level, $ds_write_timestamp);
247         }
248     } else {
249         # convert the timestamp and level to a dumpspec
250         my $level = $self->{'fulls_only'}? "0" : undef;
251         push @dumpspecs, Amanda::Cmdline::dumpspec_t->new(
252                 undef, undef, $self->{'src_write_timestamp'}, $level, undef);
253     }
254
255     # if we ignored all of the dumpspecs and didn't create any, then dump
256     # nothing.  We do *not* want the wildcard "vault it all!" behavior.
257     if (!@dumpspecs) {
258         return $self->failure("No dumps to vault");
259     }
260
261     if (!$self->{'opt_dry_run'}) {
262         # summarize the requested dumps
263         my $request;
264         if ($self->{'src_write_timestamp'}) {
265             $request = "vaulting from volumes written " . $self->{'src_write_timestamp'};
266         } else {
267             $request = "vaulting";
268         }
269         if ($self->{'opt_dumpspecs'}) {
270             $request .= " dumps matching dumpspecs:";
271         }
272         if ($self->{'fulls_only'}) {
273             $request .= " (fulls only)";
274         }
275         log_add($L_INFO, $request);
276
277         # and log the dumpspecs if they were given
278         if ($self->{'opt_dumpspecs'}) {
279             for my $ds (@{$self->{'opt_dumpspecs'}}) {
280                 log_add($L_INFO, "  " . $ds->format());
281             }
282         }
283     }
284
285     Amanda::Recovery::Planner::make_plan(
286             dumpspecs => \@dumpspecs,
287             changer => $src->{'chg'},
288             plan_cb => sub { $self->plan_cb(@_) });
289 }
290
291 sub plan_cb {
292     my $self = shift;
293     my ($err, $plan) = @_;
294     my $src = $self->{'src'};
295
296     return $self->failure($err) if $err;
297
298     $src->{'plan'} = $plan;
299
300     if ($self->{'opt_dry_run'}) {
301         my $total_kb = Math::BigInt->new(0);
302
303         # iterate over each part of each dump, printing out the basic information
304         for my $dump (@{$plan->{'dumps'}}) {
305             my @parts = @{$dump->{'parts'}};
306             shift @parts; # skip partnum 0
307             for my $part (@parts) {
308                 print STDOUT
309                       ($part->{'label'} || $part->{'holding_file'}) . " " .
310                       ($part->{'filenum'} || '') . " " .
311                       $dump->{'hostname'} . " " .
312                       $dump->{'diskname'} . " " .
313                       $dump->{'dump_timestamp'} . " " .
314                       $dump->{'level'} . "\n";
315             }
316             $total_kb += $dump->{'kb'};
317         }
318
319         print STDOUT "Total Size: $total_kb KB\n";
320
321         return $self->quit(0);
322     }
323
324     # output some 'DISK amvault' lines to indicate the disks we will be vaulting
325     my %seen;
326     for my $dump (@{$plan->{'dumps'}}) {
327         my $key = $dump->{'hostname'}."\0".$dump->{'diskname'};
328         next if $seen{$key};
329         $seen{$key} = 1;
330         log_add($L_DISK, quote_string($dump->{'hostname'})
331                  . " " . quote_string($dump->{'diskname'}));
332     }
333
334     if (@{$plan->{'dumps'}} == 0) {
335         return $self->failure("No dumps to vault");
336     }
337
338     $self->setup_dst();
339 }
340
341 sub setup_dst {
342     my $self = shift;
343     my $dst = $self->{'dst'} = {};
344     my $tlf = Amanda::Config::config_dir_relative(getconf($CNF_TAPELIST));
345     my $tl = Amanda::Tapelist->new($tlf);
346
347     $dst->{'label'} = undef;
348     $dst->{'tape_num'} = 0;
349
350     my $chg = Amanda::Changer->new($self->{'dst_changer'},
351                                    tapelist => $tl,
352                                    labelstr => getconf($CNF_LABELSTR),
353                                    autolabel => $self->{'dst_autolabel'});
354     return $self->failure("Error opening destination changer: $chg")
355         if $chg->isa('Amanda::Changer::Error');
356     $dst->{'chg'} = $chg;
357
358     my $interactivity = Amanda::Interactivity->new(
359                                         name => getconf($CNF_INTERACTIVITY));
360     my $scan_name = getconf($CNF_TAPERSCAN);
361     $dst->{'scan'} = Amanda::Taper::Scan->new(
362         algorithm => $scan_name,
363         changer => $dst->{'chg'},
364         interactivity => $interactivity,
365         tapelist => $tl,
366         labelstr => getconf($CNF_LABELSTR),
367         autolabel => $self->{'dst_autolabel'});
368
369     $dst->{'scribe'} = Amanda::Taper::Scribe->new(
370         taperscan => $dst->{'scan'},
371         feedback => $self);
372
373     $dst->{'scribe'}->start(
374         write_timestamp => $self->{'dst_write_timestamp'},
375         finished_cb => sub { $self->scribe_started(@_); })
376 }
377
378 sub scribe_started {
379     my $self = shift;
380     my ($err) = @_;
381
382     return $self->failure($err) if $err;
383
384     $self->{'cleanup'}{'quit_scribe'} = 1;
385
386     my $xfers_finished = sub {
387         my ($err) = @_;
388         $self->failure($err) if $err;
389         $self->quit(0);
390     };
391
392     $self->xfer_dumps($xfers_finished);
393 }
394
395 sub xfer_dumps {
396     my $self = shift;
397     my ($finished_cb) = @_;
398
399     my $src = $self->{'src'};
400     my $dst = $self->{'dst'};
401     my ($xfer_src, $xfer_dst, $xfer, $n_threads, $last_partnum);
402     my $current;
403
404     my $steps = define_steps
405             cb_ref => \$finished_cb;
406
407     step get_dump => sub {
408         # reset tracking for teh current dump
409         $self->{'current'} = $current = {
410             src_result => undef,
411             src_errors => undef,
412
413             dst_result => undef,
414             dst_errors => undef,
415
416             size => 0,
417             duration => 0.0,
418             total_duration => 0.0,
419             nparts => 0,
420             header => undef,
421             dump => undef,
422         };
423
424         my $dump = $src->{'plan'}->shift_dump();
425         if (!$dump) {
426             return $finished_cb->();
427         }
428
429         $current->{'dump'} = $dump;
430
431         $steps->{'get_xfer_src'}->();
432     };
433
434     step get_xfer_src => sub {
435         $src->{'clerk'}->get_xfer_src(
436             dump => $current->{'dump'},
437             xfer_src_cb => $steps->{'got_xfer_src'})
438     };
439
440     step got_xfer_src => sub {
441         my ($errors, $header, $xfer_src_, $directtcp_supported) = @_;
442         $xfer_src = $xfer_src_;
443
444         return $finished_cb->(join("\n", @$errors))
445             if $errors;
446
447         $current->{'header'} = $header;
448
449         # set up splitting args from the tapetype only, since we have no DLEs
450         my $tt = lookup_tapetype(getconf($CNF_TAPETYPE));
451         sub empty2undef { $_[0]? $_[0] : undef }
452         my %xfer_dest_args;
453         if ($tt) {
454             %xfer_dest_args = get_splitting_args_from_config(
455                 part_size_kb =>
456                     empty2undef(tapetype_getconf($tt, $TAPETYPE_PART_SIZE)),
457                 part_cache_type_enum =>
458                     empty2undef(tapetype_getconf($tt, $TAPETYPE_PART_CACHE_TYPE)),
459                 part_cache_dir =>
460                     empty2undef(tapetype_getconf($tt, $TAPETYPE_PART_CACHE_DIR)),
461                 part_cache_max_size =>
462                     empty2undef(tapetype_getconf($tt, $TAPETYPE_PART_CACHE_MAX_SIZE)),
463             );
464         }
465         # (else leave %xfer_dest_args empty, for no splitting)
466
467         $xfer_dst = $dst->{'scribe'}->get_xfer_dest(
468             max_memory => getconf($CNF_DEVICE_OUTPUT_BUFFER_SIZE),
469             can_cache_inform => 0,
470             %xfer_dest_args,
471         );
472
473         # create and start the transfer
474         $xfer = Amanda::Xfer->new([ $xfer_src, $xfer_dst ]);
475         my $size = 0;
476         $size = $current->{'dump'}->{'bytes'} if exists $current->{'dump'}->{'bytes'};
477         $xfer->start($steps->{'handle_xmsg'}, 0, $size);
478
479         # count the "threads" running here (clerk and scribe)
480         $n_threads = 2;
481
482         # and let both the scribe and the clerk know that data is in motion
483         $src->{'clerk'}->start_recovery(
484             xfer => $xfer,
485             recovery_cb => $steps->{'recovery_cb'});
486         $dst->{'scribe'}->start_dump(
487             xfer => $xfer,
488             dump_header => $header,
489             dump_cb => $steps->{'dump_cb'});
490     };
491
492     step handle_xmsg => sub {
493         $src->{'clerk'}->handle_xmsg(@_);
494         $dst->{'scribe'}->handle_xmsg(@_);
495     };
496
497     step recovery_cb => sub {
498         my %params = @_;
499         $current->{'src_result'} = $params{'result'};
500         $current->{'src_errors'} = $params{'errors'};
501         $steps->{'maybe_done'}->();
502     };
503
504     step dump_cb => sub {
505         my %params = @_;
506         $current->{'dst_result'} = $params{'result'};
507         $current->{'dst_errors'} = $params{'device_errors'};
508         $current->{'size'} = $params{'size'};
509         $current->{'duration'} = $params{'duration'};
510         $current->{'nparts'} = $params{'nparts'};
511         $current->{'total_duration'} = $params{'total_duration'};
512         $steps->{'maybe_done'}->();
513     };
514
515     step maybe_done => sub {
516         return unless --$n_threads == 0;
517         my @errors = (@{$current->{'src_errors'}}, @{$current->{'dst_errors'}});
518
519         # figure out how to log this, based on the results from the clerk (src)
520         # and scribe (dst)
521         my $logtype;
522         if ($current->{'src_result'} eq 'DONE') {
523             if ($current->{'dst_result'} eq 'DONE') {
524                 $logtype = $L_DONE;
525             } elsif ($current->{'dst_result'} eq 'PARTIAL') {
526                 $logtype = $L_PARTIAL;
527             } else { # ($current->{'dst_result'} eq 'FAILED')
528                 $logtype = $L_FAIL;
529             }
530         } else {
531             if ($current->{'size'} > 0) {
532                 $logtype = $L_PARTIAL;
533             } else {
534                 $logtype = $L_FAIL;
535             }
536         }
537
538         my $dump = $current->{'dump'};
539         my $stats = make_stats($current->{'size'}, $current->{'total_duration'},
540                                 $dump->{'orig_kb'});
541         my $msg = quote_string(join("; ", @errors));
542
543         # write a DONE/PARTIAL/FAIL log line
544         if ($logtype == $L_FAIL) {
545             log_add_full($L_FAIL, "taper", sprintf("%s %s %s %s %s %s",
546                 quote_string($dump->{'hostname'}.""), # " is required for SWIG..
547                 quote_string($dump->{'diskname'}.""),
548                 $dump->{'dump_timestamp'},
549                 $dump->{'level'},
550                 'error',
551                 $msg));
552         } else {
553             log_add_full($logtype, "taper", sprintf("%s %s %s %s %s %s%s",
554                 quote_string($dump->{'hostname'}.""), # " is required for SWIG..
555                 quote_string($dump->{'diskname'}.""),
556                 $dump->{'dump_timestamp'},
557                 $current->{'nparts'},
558                 $dump->{'level'},
559                 $stats,
560                 ($logtype == $L_PARTIAL and @errors)? " $msg" : ""));
561         }
562
563         if (@errors) {
564             return $finished_cb->("transfer failed: " .  join("; ", @errors));
565         } else {
566             # rinse, wash, and repeat
567             return $steps->{'get_dump'}->();
568         }
569     };
570 }
571
572 sub quit {
573     my $self = shift;
574     my ($exit_status) = @_;
575     my $exit_cb = $self->{'exit_cb'};
576
577     my $steps = define_steps
578             cb_ref => \$exit_cb;
579
580     # the export may not start until we quit the scribe, so wait for it now..
581     step check_exporting => sub {
582         # if we're exporting the final volume, wait for that to complete
583         if ($self->{'exporting'}) {
584             $self->{'call_after_export'} = $steps->{'quit_scribe'};
585         } else {
586             $steps->{'quit_scribe'}->();
587         }
588     };
589
590     # we may have several resources to clean up..
591     step quit_scribe => sub {
592         if ($self->{'cleanup'}{'quit_scribe'}) {
593             debug("quitting scribe..");
594             $self->{'dst'}{'scribe'}->quit(
595                 finished_cb => $steps->{'quit_scribe_finished'});
596         } else {
597             $steps->{'quit_clerk'}->();
598         }
599     };
600
601     step quit_scribe_finished => sub {
602         $self->{'dst'}{'scan'}->quit();
603         my ($err) = @_;
604         if ($err) {
605             print STDERR "$err\n";
606             $exit_status = 1;
607         }
608
609         $steps->{'quit_clerk'}->();
610     };
611
612     step quit_clerk => sub {
613         if ($self->{'cleanup'}{'quit_clerk'}) {
614             debug("quitting clerk..");
615             $self->{'src'}{'clerk'}->quit(
616                 finished_cb => $steps->{'quit_clerk_finished'});
617         } else {
618             $steps->{'roll_log'}->();
619         }
620     };
621
622     step quit_clerk_finished => sub {
623         my ($err) = @_;
624         if ($err) {
625             print STDERR "$err\n";
626             $exit_status = 1;
627         }
628
629         $steps->{'roll_log'}->();
630     };
631
632     step roll_log => sub {
633         if ($self->{'cleanup'}{'roll_trace_log'}) {
634             log_add_full($L_FINISH, "driver", "fake driver finish");
635             log_add($L_INFO, "pid-done $$");
636
637             my @amreport_cmd = ("$sbindir/amreport", $self->{'config_name'}, "--from-amdump",
638                                  @{$self->{'config_overrides_opts'}});
639             debug("invoking amreport (" . join(" ", @amreport_cmd) . ")");
640             system(@amreport_cmd);
641
642             debug("rolling logfile..");
643             log_rename($self->{'dst_write_timestamp'});
644         }
645
646         $exit_cb->($exit_status);
647     };
648 }
649
650 ## utilities
651
652 sub failure {
653     my $self = shift;
654     my ($msg) = @_;
655     print STDERR "$msg\n";
656
657     debug("failure: $msg");
658
659     # if we've got a logfile open that will be rolled, we might as well log
660     # an error.
661     if ($self->{'cleanup'}{'roll_trace_log'}) {
662         log_add($L_FATAL, "$msg");
663     }
664     $self->quit(1);
665 }
666
667 sub vlog {
668     my $self = shift;
669     if (!$self->{'quiet'}) {
670         print @_, "\n";
671     }
672 }
673
674 ## scribe feedback methods
675
676 # note that the trace log calls here all add "taper", as we're dry_runing
677 # to be the taper in the logfiles.
678
679 sub request_volume_permission {
680     my $self = shift;
681     my %params = @_;
682
683     # sure, use all the volumes you want, no problem!
684     # TODO: limit to a vaulting-specific value of runtapes
685     $self->{'dst'}->{'scribe'}->start_scan();
686     $params{'perm_cb'}->(allow => 1);
687 }
688
689 sub scribe_notif_new_tape {
690     my $self = shift;
691     my %params = @_;
692
693     if ($params{'volume_label'}) {
694         $self->{'dst'}->{'label'} = $params{'volume_label'};
695
696         # add to the trace log
697         log_add_full($L_START, "taper", sprintf("datestamp %s label %s tape %s",
698                 $self->{'dst_write_timestamp'},
699                 quote_string($self->{'dst'}->{'label'}),
700                 ++$self->{'dst'}->{'tape_num'}));
701     } else {
702         $self->{'dst'}->{'label'} = undef;
703
704         print STDERR "Could not start new destination volume: $params{error}";
705     }
706 }
707
708 sub scribe_notif_part_done {
709     my $self = shift;
710     my %params = @_;
711
712     $self->{'last_partnum'} = $params{'partnum'};
713
714     my $stats = make_stats($params{'size'}, $params{'duration'}, $self->{'orig_kb'});
715
716     # log the part, using PART or PARTPARTIAL
717     my $hdr = $self->{'current'}->{'header'};
718     my $logbase = sprintf("%s %s %s %s %s %s/%s %s %s",
719         quote_string($self->{'dst'}->{'label'}),
720         $params{'fileno'},
721         quote_string($hdr->{'name'}.""), # " is required for SWIG..
722         quote_string($hdr->{'disk'}.""),
723         $hdr->{'datestamp'}."",
724         $params{'partnum'}, -1, # totalparts is always -1
725         $hdr->{'dumplevel'},
726         $stats);
727     if ($params{'successful'}) {
728         log_add_full($L_PART, "taper", $logbase);
729     } else {
730         log_add_full($L_PARTPARTIAL, "taper",
731                 "$logbase \"No space left on device\"");
732     }
733
734     if ($params{'successful'}) {
735         $self->vlog("Wrote $self->{dst}->{label}:$params{'fileno'}: " . $hdr->summary());
736     }
737 }
738
739 sub scribe_notif_log_info {
740     my $self = shift;
741     my %params = @_;
742
743     log_add_full($L_INFO, "taper", $params{'message'});
744 }
745
746 sub scribe_notif_tape_done {
747     my $self = shift;
748     my %params = @_;
749
750     # immediately flag that we are busy exporting, to prevent amvault from
751     # quitting too soon.  The 'done' step will clear this flag.  We increment
752     # and decrement this to allow for the (unlikely) situation that multiple
753     # exports are going on simultaneously.
754     $self->{'exporting'}++;
755
756     my $finished_cb = $params{'finished_cb'};
757     my $steps = define_steps
758         cb_ref => \$finished_cb;
759
760     step check_option => sub {
761         if (!$self->{'opt_export'}) {
762             return $steps->{'done'}->();
763         }
764
765         $steps->{'get_inventory'}->();
766     };
767     step get_inventory => sub {
768         $self->{'dst'}->{'chg'}->inventory(
769             inventory_cb => $steps->{'inventory_cb'});
770     };
771
772     step inventory_cb => sub {
773         my ($err, $inventory) = @_;
774         if ($err) {
775             print STDERR "Could not get destination inventory: $err\n";
776             return $steps->{'done'}->();
777         }
778
779         # find the slots we want in the inventory
780         my ($ie_slot, $from_slot);
781         for my $info (@$inventory) {
782             if (defined $info->{'state'}
783                 && $info->{'state'} != Amanda::Changer::SLOT_FULL
784                 && $info->{'import_export'}) {
785                 $ie_slot = $info->{'slot'};
786             }
787             if ($info->{'label'} and $info->{'label'} eq $params{'volume_label'}) {
788                 $from_slot = $info->{'slot'};
789             }
790         }
791
792         if (!$ie_slot) {
793             print STDERR "No import/export slots available; skipping export\n";
794             return $steps->{'done'}->();
795         } elsif (!$from_slot) {
796             print STDERR "Could not find the just-written tape; skipping export\n";
797             return $steps->{'done'}->();
798         } else {
799             return $steps->{'do_move'}->($ie_slot, $from_slot);
800         }
801     };
802
803     step do_move => sub {
804         my ($ie_slot, $from_slot) = @_;
805
806         # TODO: there is a risk here that the volume is no longer in the slot
807         # where we expect it to be, because the taperscan has moved it.  A
808         # failure from move() is not fatal, though, so this will only cause the
809         # volume to be left un-exported.
810
811         $self->{'dst'}->{'chg'}->move(
812             from_slot => $from_slot,
813             to_slot => $ie_slot,
814             finished_cb => $steps->{'moved'});
815     };
816
817     step moved => sub {
818         my ($err) = @_;
819         if ($err) {
820             print STDERR "While exporting just-written tape: $err (ignored)\n";
821         }
822         $steps->{'done'}->();
823     };
824
825     step done => sub {
826         if (--$self->{'exporting'} == 0) {
827             if ($self->{'call_after_export'}) {
828                 my $cae = $self->{'call_after_export'};
829                 $self->{'call_after_export'} = undef;
830                 $cae->();
831             }
832         }
833         $finished_cb->();
834     };
835 }
836
837 ## clerk feedback methods
838
839 sub clerk_notif_part {
840     my $self = shift;
841     my ($label, $fileno, $header) = @_;
842
843     # see if this is a new label
844     if (!exists $self->{'src'}->{'seen_labels'}->{$label}) {
845         $self->{'src'}->{'seen_labels'}->{$label} = 1;
846         log_add($L_INFO, "reading from source volume '$label'");
847     }
848
849     $self->vlog("Reading $label:$fileno: ", $header->summary());
850 }
851
852 sub clerk_notif_holding {
853     my $self = shift;
854     my ($filename, $header) = @_;
855
856     # this used to give the fd from which the holding file was being read.. why??
857     $self->vlog("Reading '$filename'", $header->summary());
858 }
859
860 ## Application initialization
861 package main;
862
863 use Amanda::Config qw( :init :getconf );
864 use Amanda::Debug qw( :logging );
865 use Amanda::Util qw( :constants );
866 use Getopt::Long;
867 use Amanda::Cmdline qw( :constants parse_dumpspecs );
868
869 sub usage {
870     my ($msg) = @_;
871
872     print STDERR <<EOF;
873 **NOTE** this interface is under development and will change in future releases!
874
875 Usage: amvault [-o configoption...] [-q] [--quiet] [-n] [--dry-run]
876            [--fulls-only] [--export] [--src-timestamp src-timestamp]
877            --label-template label-template --dst-changer dst-changer
878            [--autolabel autolabel-arg...]
879            config
880            [hostname [ disk [ date [ level [ hostname [...] ] ] ] ]]
881
882     -o: configuration override (see amanda(8))
883     -q: quiet progress messages
884     --fulls-only: only copy full (level-0) dumps
885     --export: move completed destination volumes to import/export slots
886     --src-timestamp: the timestamp of the Amanda run that should be vaulted
887     --label-template: the template to use for new volume labels
888     --dst-changer: the changer to which dumps should be written
889     --autolabel: similar to the amanda.conf parameter; may be repeated (default: empty)
890
891 Copies data from the run with timestamp <src-timestamp> onto volumes using
892 the changer <dst-changer>, labeling new volumes with <label-template>.  If
893 <src-timestamp> is "latest", then the most recent run of amdump or amflush
894 will be used.  If any dumpspecs are included (<host-expr> and so on), then only
895 dumps matching those dumpspecs will be dumped.  At least one of --fulls-only,
896 --src-timestamp, or a dumpspec must be specified.
897
898 EOF
899     if ($msg) {
900         print STDERR "ERROR: $msg\n";
901     }
902     exit(1);
903 }
904
905 Amanda::Util::setup_application("amvault", "server", $CONTEXT_CMDLINE);
906
907 my $config_overrides = new_config_overrides($#ARGV+1);
908 my @config_overrides_opts;
909 my $opt_quiet = 0;
910 my $opt_dry_run = 0;
911 my $opt_fulls_only = 0;
912 my $opt_export = 0;
913 my $opt_autolabel = {};
914 my $opt_autolabel_seen = 0;
915 my $opt_src_write_timestamp;
916 my $opt_dst_changer;
917
918 sub set_label_template {
919     usage("only one --label-template allowed") if $opt_autolabel->{'template'};
920     $opt_autolabel->{'template'} = $_[1];
921 }
922
923 sub add_autolabel {
924     my ($opt, $val) = @_;
925     $val = lc($val);
926     $val =~ s/-/_/g;
927
928     $opt_autolabel_seen = 1;
929     my @ok = qw(other_config non_amanda volume_error empty);
930     for (@ok) {
931         if ($val eq $_) {
932             $opt_autolabel->{$_} = 1;
933             return;
934         }
935     }
936     if ($val eq 'any') {
937         for (@ok) {
938             $opt_autolabel->{$_} = 1;
939         }
940         return;
941     }
942     usage("unknown --autolabel value '$val'");
943 }
944
945 Getopt::Long::Configure(qw{ bundling });
946 GetOptions(
947     'o=s' => sub {
948         push @config_overrides_opts, "-o" . $_[1];
949         add_config_override_opt($config_overrides, $_[1]);
950     },
951     'q|quiet' => \$opt_quiet,
952     'n|dry-run' => \$opt_dry_run,
953     'fulls-only' => \$opt_fulls_only,
954     'export' => \$opt_export,
955     'label-template=s' => \&set_label_template,
956     'autolabel=s' => \&add_autolabel,
957     'src-timestamp=s' => \$opt_src_write_timestamp,
958     'dst-changer=s' => \$opt_dst_changer,
959     'version' => \&Amanda::Util::version_opt,
960     'help' => \&usage,
961 ) or usage("usage error");
962 $opt_autolabel->{'empty'} = 1 unless $opt_autolabel_seen;
963
964 usage("not enough arguments") unless (@ARGV >= 1);
965
966 my $config_name = shift @ARGV;
967 my @opt_dumpspecs = parse_dumpspecs(\@ARGV, $CMDLINE_PARSE_DATESTAMP|$CMDLINE_PARSE_LEVEL)
968     if (@ARGV);
969
970 usage("no --label-template given") unless $opt_autolabel->{'template'};
971 usage("no --dst-changer given") unless $opt_dst_changer;
972 usage("specify something to select the source dumps") unless
973     $opt_src_write_timestamp or $opt_fulls_only or @opt_dumpspecs;
974
975 set_config_overrides($config_overrides);
976 config_init($CONFIG_INIT_EXPLICIT_NAME, $config_name);
977 my ($cfgerr_level, @cfgerr_errors) = config_errors();
978 if ($cfgerr_level >= $CFGERR_WARNINGS) {
979     config_print_errors();
980     if ($cfgerr_level >= $CFGERR_ERRORS) {
981         print STDERR "errors processing config file\n";
982         exit(1);
983     }
984 }
985
986 Amanda::Util::finish_setup($RUNNING_AS_DUMPUSER);
987
988 my $exit_status;
989 my $exit_cb = sub {
990     ($exit_status) = @_;
991     Amanda::MainLoop::quit();
992 };
993
994 my $vault = Amvault->new(
995     config_name => $config_name,
996     src_write_timestamp => $opt_src_write_timestamp,
997     dst_changer => $opt_dst_changer,
998     dst_autolabel => $opt_autolabel,
999     dst_write_timestamp => Amanda::Util::generate_timestamp(),
1000     opt_dumpspecs => @opt_dumpspecs? \@opt_dumpspecs : undef,
1001     opt_dry_run => $opt_dry_run,
1002     quiet => $opt_quiet,
1003     fulls_only => $opt_fulls_only,
1004     opt_export => $opt_export,
1005     config_overrides_opts => \@config_overrides_opts);
1006 Amanda::MainLoop::call_later(sub { $vault->run($exit_cb) });
1007 Amanda::MainLoop::run();
1008
1009 Amanda::Util::finish_application();
1010 exit($exit_status);