Imported Upstream version 3.2.1
[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::Interactive;
25 use POSIX qw( :errno_h );
26 use Amanda::MainLoop qw( :GIOCondition );
27 use vars qw( @ISA );
28 @ISA = qw( Amanda::Interactive );
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{'finished_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{'finished_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{'finished_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     # interactive, 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->{'interactive'} = main::Interactive->new();
190
191     $src->{'scan'} = Amanda::Recovery::Scan->new(
192             chg => $src->{'chg'},
193             interactive => $src->{'interactive'});
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
345     $dst->{'label'} = undef;
346     $dst->{'tape_num'} = 0;
347
348     my $chg = Amanda::Changer->new($self->{'dst_changer'});
349     return $self->failure("Error opening destination changer: $chg")
350         if $chg->isa('Amanda::Changer::Error');
351     $dst->{'chg'} = $chg;
352
353     $dst->{'scan'} = Amanda::Taper::Scan->new(
354         changer => $dst->{'chg'},
355         labelstr => getconf($CNF_LABELSTR),
356         autolabel => $self->{'dst_autolabel'});
357
358     $dst->{'scribe'} = Amanda::Taper::Scribe->new(
359         taperscan => $dst->{'scan'},
360         feedback => $self);
361
362     $dst->{'scribe'}->start(
363         write_timestamp => $self->{'dst_write_timestamp'},
364         finished_cb => sub { $self->scribe_started(@_); })
365 }
366
367 sub scribe_started {
368     my $self = shift;
369     my ($err) = @_;
370
371     return $self->failure($err) if $err;
372
373     $self->{'cleanup'}{'quit_scribe'} = 1;
374
375     my $xfers_finished = sub {
376         my ($err) = @_;
377         $self->failure($err) if $err;
378         $self->quit(0);
379     };
380
381     $self->xfer_dumps($xfers_finished);
382 }
383
384 sub xfer_dumps {
385     my $self = shift;
386     my ($finished_cb) = @_;
387
388     my $src = $self->{'src'};
389     my $dst = $self->{'dst'};
390     my ($xfer_src, $xfer_dst, $xfer, $n_threads, $last_partnum);
391     my $current;
392
393     my $steps = define_steps
394             cb_ref => \$finished_cb;
395
396     step get_dump => sub {
397         # reset tracking for teh current dump
398         $self->{'current'} = $current = {
399             src_result => undef,
400             src_errors => undef,
401
402             dst_result => undef,
403             dst_errors => undef,
404
405             size => 0,
406             duration => 0.0,
407             total_duration => 0.0,
408             nparts => 0,
409             header => undef,
410             dump => undef,
411         };
412
413         my $dump = $src->{'plan'}->shift_dump();
414         if (!$dump) {
415             return $finished_cb->();
416         }
417
418         $current->{'dump'} = $dump;
419
420         $steps->{'get_xfer_src'}->();
421     };
422
423     step get_xfer_src => sub {
424         $src->{'clerk'}->get_xfer_src(
425             dump => $current->{'dump'},
426             xfer_src_cb => $steps->{'got_xfer_src'})
427     };
428
429     step got_xfer_src => sub {
430         my ($errors, $header, $xfer_src_, $directtcp_supported) = @_;
431         $xfer_src = $xfer_src_;
432
433         return $finished_cb->(join("\n", @$errors))
434             if $errors;
435
436         $current->{'header'} = $header;
437
438         # set up splitting args from the tapetype only, since we have no DLEs
439         my $tt = lookup_tapetype(getconf($CNF_TAPETYPE));
440         sub empty2undef { $_[0]? $_[0] : undef }
441         my %xfer_dest_args;
442         if ($tt) {
443             %xfer_dest_args = get_splitting_args_from_config(
444                 part_size_kb =>
445                     empty2undef(tapetype_getconf($tt, $TAPETYPE_PART_SIZE)),
446                 part_cache_type_enum =>
447                     empty2undef(tapetype_getconf($tt, $TAPETYPE_PART_CACHE_TYPE)),
448                 part_cache_dir =>
449                     empty2undef(tapetype_getconf($tt, $TAPETYPE_PART_CACHE_DIR)),
450                 part_cache_max_size =>
451                     empty2undef(tapetype_getconf($tt, $TAPETYPE_PART_CACHE_MAX_SIZE)),
452             );
453         }
454         # (else leave %xfer_dest_args empty, for no splitting)
455
456         $xfer_dst = $dst->{'scribe'}->get_xfer_dest(
457             max_memory => getconf($CNF_DEVICE_OUTPUT_BUFFER_SIZE),
458             can_cache_inform => 0,
459             %xfer_dest_args,
460         );
461
462         # create and start the transfer
463         $xfer = Amanda::Xfer->new([ $xfer_src, $xfer_dst ]);
464         $xfer->start($steps->{'handle_xmsg'});
465
466         # count the "threads" running here (clerk and scribe)
467         $n_threads = 2;
468
469         # and let both the scribe and the clerk know that data is in motion
470         $src->{'clerk'}->start_recovery(
471             xfer => $xfer,
472             recovery_cb => $steps->{'recovery_cb'});
473         $dst->{'scribe'}->start_dump(
474             xfer => $xfer,
475             dump_header => $header,
476             dump_cb => $steps->{'dump_cb'});
477     };
478
479     step handle_xmsg => sub {
480         $src->{'clerk'}->handle_xmsg(@_);
481         $dst->{'scribe'}->handle_xmsg(@_);
482     };
483
484     step recovery_cb => sub {
485         my %params = @_;
486         $current->{'src_result'} = $params{'result'};
487         $current->{'src_errors'} = $params{'errors'};
488         $steps->{'maybe_done'}->();
489     };
490
491     step dump_cb => sub {
492         my %params = @_;
493         $current->{'dst_result'} = $params{'result'};
494         $current->{'dst_errors'} = $params{'device_errors'};
495         $current->{'size'} = $params{'size'};
496         $current->{'duration'} = $params{'duration'};
497         $current->{'nparts'} = $params{'nparts'};
498         $current->{'total_duration'} = $params{'total_duration'};
499         $steps->{'maybe_done'}->();
500     };
501
502     step maybe_done => sub {
503         return unless --$n_threads == 0;
504         my @errors = (@{$current->{'src_errors'}}, @{$current->{'dst_errors'}});
505
506         # figure out how to log this, based on the results from the clerk (src)
507         # and scribe (dst)
508         my $logtype;
509         if ($current->{'src_result'} eq 'DONE') {
510             if ($current->{'dst_result'} eq 'DONE') {
511                 $logtype = $L_DONE;
512             } elsif ($current->{'dst_result'} eq 'PARTIAL') {
513                 $logtype = $L_PARTIAL;
514             } else { # ($current->{'dst_result'} eq 'FAILED')
515                 $logtype = $L_FAIL;
516             }
517         } else {
518             if ($current->{'size'} > 0) {
519                 $logtype = $L_PARTIAL;
520             } else {
521                 $logtype = $L_FAIL;
522             }
523         }
524
525         my $dump = $current->{'dump'};
526         my $stats = make_stats($current->{'size'}, $current->{'total_duration'},
527                                 $dump->{'orig_kb'});
528         my $msg = quote_string(join("; ", @errors));
529
530         # write a DONE/PARTIAL/FAIL log line
531         if ($logtype == $L_FAIL) {
532             log_add_full($L_FAIL, "taper", sprintf("%s %s %s %s %s %s",
533                 quote_string($dump->{'hostname'}.""), # " is required for SWIG..
534                 quote_string($dump->{'diskname'}.""),
535                 $dump->{'dump_timestamp'},
536                 $dump->{'level'},
537                 'error',
538                 $msg));
539         } else {
540             log_add_full($logtype, "taper", sprintf("%s %s %s %s %s %s%s",
541                 quote_string($dump->{'hostname'}.""), # " is required for SWIG..
542                 quote_string($dump->{'diskname'}.""),
543                 $dump->{'dump_timestamp'},
544                 $current->{'nparts'},
545                 $dump->{'level'},
546                 $stats,
547                 ($logtype == $L_PARTIAL and @errors)? " $msg" : ""));
548         }
549
550         if (@errors) {
551             return $finished_cb->("transfer failed: " .  join("; ", @errors));
552         } else {
553             # rinse, wash, and repeat
554             return $steps->{'get_dump'}->();
555         }
556     };
557 }
558
559 sub quit {
560     my $self = shift;
561     my ($exit_status) = @_;
562     my $exit_cb = $self->{'exit_cb'};
563
564     my $steps = define_steps
565             cb_ref => \$exit_cb;
566
567     # we may have several resources to clean up..
568     step quit_scribe => sub {
569         if ($self->{'cleanup'}{'quit_scribe'}) {
570             debug("quitting scribe..");
571             $self->{'dst'}{'scribe'}->quit(
572                 finished_cb => $steps->{'quit_scribe_finished'});
573         } else {
574             $steps->{'check_exporting'}->();
575         }
576     };
577
578     step quit_scribe_finished => sub {
579         my ($err) = @_;
580         if ($err) {
581             print STDERR "$err\n";
582             $exit_status = 1;
583         }
584
585         $steps->{'check_exporting'}->();
586     };
587
588     # the export may not start until we quit the scribe, so wait for it now..
589     step check_exporting => sub {
590         # if we're exporting the final volume, wait for that to complete
591         if ($self->{'exporting'}) {
592             $self->{'call_after_export'} = $steps->{'quit_clerk'};
593         } else {
594             $steps->{'quit_clerk'}->();
595         }
596     };
597
598     step quit_clerk => sub {
599         if ($self->{'cleanup'}{'quit_clerk'}) {
600             debug("quitting clerk..");
601             $self->{'src'}{'clerk'}->quit(
602                 finished_cb => $steps->{'quit_clerk_finished'});
603         } else {
604             $steps->{'roll_log'}->();
605         }
606     };
607
608     step quit_clerk_finished => sub {
609         my ($err) = @_;
610         if ($err) {
611             print STDERR "$err\n";
612             $exit_status = 1;
613         }
614
615         $steps->{'roll_log'}->();
616     };
617
618     step roll_log => sub {
619         if ($self->{'cleanup'}{'roll_trace_log'}) {
620             log_add_full($L_FINISH, "driver", "fake driver finish");
621             log_add($L_INFO, "pid-done $$");
622
623             my @amreport_cmd = ("$sbindir/amreport", $self->{'config_name'}, "--from-amdump",
624                                  @{$self->{'config_overrides_opts'}});
625             debug("invoking amreport (" . join(" ", @amreport_cmd) . ")");
626             system(@amreport_cmd);
627
628             debug("rolling logfile..");
629             log_rename($self->{'dst_write_timestamp'});
630         }
631
632         $exit_cb->($exit_status);
633     };
634 }
635
636 ## utilities
637
638 sub failure {
639     my $self = shift;
640     my ($msg) = @_;
641     print STDERR "$msg\n";
642
643     debug("failure: $msg");
644
645     # if we've got a logfile open that will be rolled, we might as well log
646     # an error.
647     if ($self->{'cleanup'}{'roll_trace_log'}) {
648         log_add($L_FATAL, "$msg");
649     }
650     $self->quit(1);
651 }
652
653 sub vlog {
654     my $self = shift;
655     if (!$self->{'quiet'}) {
656         print @_, "\n";
657     }
658 }
659
660 ## scribe feedback methods
661
662 # note that the trace log calls here all add "taper", as we're dry_runing
663 # to be the taper in the logfiles.
664
665 sub request_volume_permission {
666     my $self = shift;
667     my %params = @_;
668
669     # sure, use all the volumes you want, no problem!
670     # TODO: limit to a vaulting-specific value of runtapes
671     $self->{'dst'}->{'scribe'}->start_scan();
672     $params{'perm_cb'}->(allow => 1);
673 }
674
675 sub scribe_notif_new_tape {
676     my $self = shift;
677     my %params = @_;
678
679     if ($params{'volume_label'}) {
680         $self->{'dst'}->{'label'} = $params{'volume_label'};
681
682         # add to the trace log
683         log_add_full($L_START, "taper", sprintf("datestamp %s label %s tape %s",
684                 $self->{'dst_write_timestamp'},
685                 quote_string($self->{'dst'}->{'label'}),
686                 ++$self->{'dst'}->{'tape_num'}));
687     } else {
688         $self->{'dst'}->{'label'} = undef;
689
690         print STDERR "Could not start new destination volume: $params{error}";
691     }
692 }
693
694 sub scribe_notif_part_done {
695     my $self = shift;
696     my %params = @_;
697
698     $self->{'last_partnum'} = $params{'partnum'};
699
700     my $stats = make_stats($params{'size'}, $params{'duration'}, $self->{'orig_kb'});
701
702     # log the part, using PART or PARTPARTIAL
703     my $hdr = $self->{'current'}->{'header'};
704     my $logbase = sprintf("%s %s %s %s %s %s/%s %s %s",
705         quote_string($self->{'dst'}->{'label'}),
706         $params{'fileno'},
707         quote_string($hdr->{'name'}.""), # " is required for SWIG..
708         quote_string($hdr->{'disk'}.""),
709         $hdr->{'datestamp'}."",
710         $params{'partnum'}, -1, # totalparts is always -1
711         $hdr->{'dumplevel'},
712         $stats);
713     if ($params{'successful'}) {
714         log_add_full($L_PART, "taper", $logbase);
715     } else {
716         log_add_full($L_PARTPARTIAL, "taper",
717                 "$logbase \"No space left on device\"");
718     }
719
720     if ($params{'successful'}) {
721         $self->vlog("Wrote $self->{dst}->{label}:$params{'fileno'}: " . $hdr->summary());
722     }
723 }
724
725 sub scribe_notif_log_info {
726     my $self = shift;
727     my %params = @_;
728
729     log_add_full($L_INFO, "taper", $params{'message'});
730 }
731
732 sub scribe_notif_tape_done {
733     my $self = shift;
734     my %params = @_;
735
736     # immediately flag that we are busy exporting, to prevent amvault from
737     # quitting too soon.  The 'done' step will clear this flag.  We increment
738     # and decrement this to allow for the (unlikely) situation that multiple
739     # exports are going on simultaneously.
740     $self->{'exporting'}++;
741
742     my $finished_cb = sub {};
743     my $steps = define_steps
744         cb_ref => \$finished_cb;
745
746     step check_option => sub {
747         if (!$self->{'opt_export'}) {
748             return $steps->{'done'}->();
749         }
750
751         $steps->{'get_inventory'}->();
752     };
753     step get_inventory => sub {
754         $self->{'dst'}->{'chg'}->inventory(
755             inventory_cb => $steps->{'inventory_cb'});
756     };
757
758     step inventory_cb => sub {
759         my ($err, $inventory) = @_;
760         if ($err) {
761             print STDERR "Could not get destination inventory: $err\n";
762             return $steps->{'done'}->();
763         }
764
765         # find the slots we want in the inventory
766         my ($ie_slot, $from_slot);
767         for my $info (@$inventory) {
768             if (defined $info->{'state'}
769                 && $info->{'state'} != Amanda::Changer::SLOT_FULL
770                 && $info->{'import_export'}) {
771                 $ie_slot = $info->{'slot'};
772             }
773             if ($info->{'label'} and $info->{'label'} eq $params{'volume_label'}) {
774                 $from_slot = $info->{'slot'};
775             }
776         }
777
778         if (!$ie_slot) {
779             print STDERR "No import/export slots available; skipping export\n";
780             return $steps->{'done'}->();
781         } elsif (!$from_slot) {
782             print STDERR "Could not find the just-written tape; skipping export\n";
783             return $steps->{'done'}->();
784         } else {
785             return $steps->{'do_move'}->($ie_slot, $from_slot);
786         }
787     };
788
789     step do_move => sub {
790         my ($ie_slot, $from_slot) = @_;
791
792         # TODO: there is a risk here that the volume is no longer in the slot
793         # where we expect it to be, because the taperscan has moved it.  A
794         # failure from move() is not fatal, though, so this will only cause the
795         # volume to be left un-exported.
796
797         $self->{'dst'}->{'chg'}->move(
798             from_slot => $from_slot,
799             to_slot => $ie_slot,
800             finished_cb => $steps->{'moved'});
801     };
802
803     step moved => sub {
804         my ($err) = @_;
805         if ($err) {
806             print STDERR "While exporting just-written tape: $err (ignored)\n";
807         }
808         $steps->{'done'}->();
809     };
810
811     step done => sub {
812         if (--$self->{'exporting'} == 0) {
813             if ($self->{'call_after_export'}) {
814                 my $cae = $self->{'call_after_export'};
815                 $self->{'call_after_export'} = undef;
816                 $cae->();
817             }
818         }
819         $finished_cb->();
820     };
821 }
822
823 ## clerk feedback methods
824
825 sub clerk_notif_part {
826     my $self = shift;
827     my ($label, $fileno, $header) = @_;
828
829     # see if this is a new label
830     if (!exists $self->{'src'}->{'seen_labels'}->{$label}) {
831         $self->{'src'}->{'seen_labels'}->{$label} = 1;
832         log_add($L_INFO, "reading from source volume '$label'");
833     }
834
835     $self->vlog("Reading $label:$fileno: ", $header->summary());
836 }
837
838 sub clerk_notif_holding {
839     my $self = shift;
840     my ($filename, $header) = @_;
841
842     # this used to give the fd from which the holding file was being read.. why??
843     $self->vlog("Reading '$filename'", $header->summary());
844 }
845
846 ## Application initialization
847 package main;
848
849 use Amanda::Config qw( :init :getconf );
850 use Amanda::Debug qw( :logging );
851 use Amanda::Util qw( :constants );
852 use Getopt::Long;
853 use Amanda::Cmdline qw( :constants parse_dumpspecs );
854
855 sub usage {
856     my ($msg) = @_;
857
858     print STDERR <<EOF;
859 **NOTE** this interface is under development and will change in future releases!
860
861 Usage: amvault [-o configoption...] [-q] [--quiet] [-n] [--dry-run]
862            [--fulls-only] [--export] [--src-timestamp src-timestamp]
863            --label-template label-template --dst-changer dst-changer
864            [--autolabel autolabel-arg...]
865            config
866            [hostname [ disk [ date [ level [ hostname [...] ] ] ] ]]
867
868     -o: configuration override (see amanda(8))
869     -q: quiet progress messages
870     --fulls-only: only copy full (level-0) dumps
871     --export: move completed destination volumes to import/export slots
872     --src-timestamp: the timestamp of the Amanda run that should be vaulted
873     --label-template: the template to use for new volume labels
874     --dst-changer: the changer to which dumps should be written
875     --autolabel: similar to the amanda.conf parameter; may be repeated (default: empty)
876
877 Copies data from the run with timestamp <src-timestamp> onto volumes using
878 the changer <dst-changer>, labeling new volumes with <label-template>.  If
879 <src-timestamp> is "latest", then the most recent run of amdump or amflush
880 will be used.  If any dumpspecs are included (<host-expr> and so on), then only
881 dumps matching those dumpspecs will be dumped.  At least one of --fulls-only,
882 --src-timestamp, or a dumpspec must be specified.
883
884 EOF
885     if ($msg) {
886         print STDERR "ERROR: $msg\n";
887     }
888     exit(1);
889 }
890
891 Amanda::Util::setup_application("amvault", "server", $CONTEXT_CMDLINE);
892
893 my $config_overrides = new_config_overrides($#ARGV+1);
894 my @config_overrides_opts;
895 my $opt_quiet = 0;
896 my $opt_dry_run = 0;
897 my $opt_fulls_only = 0;
898 my $opt_export = 0;
899 my $opt_autolabel = {};
900 my $opt_autolabel_seen = 0;
901 my $opt_src_write_timestamp;
902 my $opt_dst_changer;
903
904 sub set_label_template {
905     usage("only one --label-template allowed") if $opt_autolabel->{'template'};
906     $opt_autolabel->{'template'} = $_[1];
907 }
908
909 sub add_autolabel {
910     my ($opt, $val) = @_;
911     $val = lc($val);
912     $val =~ s/-/_/g;
913
914     $opt_autolabel_seen = 1;
915     my @ok = qw(other_config non_amanda volume_error empty);
916     for (@ok) {
917         if ($val eq $_) {
918             $opt_autolabel->{$_} = 1;
919             return;
920         }
921     }
922     if ($val eq 'any') {
923         for (@ok) {
924             $opt_autolabel->{$_} = 1;
925         }
926         return;
927     }
928     usage("unknown --autolabel value '$val'");
929 }
930
931 Getopt::Long::Configure(qw{ bundling });
932 GetOptions(
933     'o=s' => sub {
934         push @config_overrides_opts, "-o" . $_[1];
935         add_config_override_opt($config_overrides, $_[1]);
936     },
937     'q|quiet' => \$opt_quiet,
938     'n|dry-run' => \$opt_dry_run,
939     'fulls-only' => \$opt_fulls_only,
940     'export' => \$opt_export,
941     'label-template=s' => \&set_label_template,
942     'autolabel=s' => \&add_autolabel,
943     'src-timestamp=s' => \$opt_src_write_timestamp,
944     'dst-changer=s' => \$opt_dst_changer,
945     'version' => \&Amanda::Util::version_opt,
946     'help' => \&usage,
947 ) or usage("usage error");
948 $opt_autolabel->{'empty'} = 1 unless $opt_autolabel_seen;
949
950 usage("not enough arguments") unless (@ARGV >= 1);
951
952 my $config_name = shift @ARGV;
953 my @opt_dumpspecs = parse_dumpspecs(\@ARGV, $CMDLINE_PARSE_DATESTAMP|$CMDLINE_PARSE_LEVEL)
954     if (@ARGV);
955
956 usage("no --label-template given") unless $opt_autolabel->{'template'};
957 usage("no --dst-changer given") unless $opt_dst_changer;
958 usage("specify something to select the source dumps") unless
959     $opt_src_write_timestamp or $opt_fulls_only or @opt_dumpspecs;
960
961 set_config_overrides($config_overrides);
962 config_init($CONFIG_INIT_EXPLICIT_NAME, $config_name);
963 my ($cfgerr_level, @cfgerr_errors) = config_errors();
964 if ($cfgerr_level >= $CFGERR_WARNINGS) {
965     config_print_errors();
966     if ($cfgerr_level >= $CFGERR_ERRORS) {
967         print STDERR "errors processing config file\n";
968         exit(1);
969     }
970 }
971
972 Amanda::Util::finish_setup($RUNNING_AS_DUMPUSER);
973
974 my $exit_status;
975 my $exit_cb = sub {
976     ($exit_status) = @_;
977     Amanda::MainLoop::quit();
978 };
979
980 my $vault = Amvault->new(
981     config_name => $config_name,
982     src_write_timestamp => $opt_src_write_timestamp,
983     dst_changer => $opt_dst_changer,
984     dst_autolabel => $opt_autolabel,
985     dst_write_timestamp => Amanda::Util::generate_timestamp(),
986     opt_dumpspecs => @opt_dumpspecs? \@opt_dumpspecs : undef,
987     opt_dry_run => $opt_dry_run,
988     quiet => $opt_quiet,
989     fulls_only => $opt_fulls_only,
990     opt_export => $opt_export,
991     config_overrides_opts => \@config_overrides_opts);
992 Amanda::MainLoop::call_later(sub { $vault->run($exit_cb) });
993 Amanda::MainLoop::run();
994
995 Amanda::Util::finish_application();
996 exit($exit_status);