2 # Copyright (c) 2009-2012 Zmanda, Inc. All Rights Reserved.
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.
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
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
17 # Contact information: Zmanda Inc., 465 S. Mathilda Ave., Suite 300
18 # Sunnyvale, CA 94086, USA, or: http://www.zmanda.com
20 use lib '@amperldir@';
25 package Amanda::Application::ampgsql;
26 use base qw(Amanda::Application);
37 use Amanda::Constants;
38 use Amanda::Config qw( :init :getconf config_dir_relative string_to_boolean );
39 use Amanda::Debug qw( :logging );
41 use Amanda::Util qw( :constants :encoding quote_string );
42 use Amanda::MainLoop qw( :GIOCondition );
44 my $_DATA_DIR_TAR = "data_dir.tar";
45 my $_ARCHIVE_DIR_TAR = "archive_dir.tar";
46 my $_WAL_FILE_PAT = qr/\w{24}/;
48 my $_DATA_DIR_RESTORE = "data";
49 my $_ARCHIVE_DIR_RESTORE = "archive";
54 my $self = $class->SUPER::new($args->{'config'});
55 $self->{'args'} = $args;
56 $self->{'label-prefix'} = 'amanda';
57 $self->{'runtar'} = "$Amanda::Paths::amlibexecdir/runtar";
59 # default arguments (application properties)
60 $self->{'args'}->{'statedir'} ||= $Amanda::Paths::GNUTAR_LISTED_INCREMENTAL_DIR;
61 $self->{'args'}->{'tmpdir'} ||= $AMANDA_TMPDIR;
62 # XXX: when using runtar, this is not actually honored.
63 # So, this only works for restore at the moment
64 $self->{'args'}->{'gnutar-path'} ||= $Amanda::Constants::GNUTAR;
66 if (!defined $self->{'args'}->{'disk'}) {
67 $self->{'args'}->{'disk'} = $self->{'args'}->{'device'};
69 if (!defined $self->{'args'}->{'device'}) {
70 $self->{'args'}->{'device'} = $self->{'args'}->{'disk'};
74 'pg-db' => 'template1',
75 'pg-cleanupwal' => 'yes',
76 'pg-max-wal-wait' => 60,
79 my @PROP_NAMES = qw(pg-host pg-port pg-db pg-user pg-password pg-passfile
80 psql-path pg-datadir pg-archivedir pg-cleanupwal
83 # config is loaded by Amanda::Application (and Amanda::Script_App)
84 my $conf_props = getconf($CNF_PROPERTY);
85 # check for properties like 'pg-host'
86 foreach my $pname (@PROP_NAMES) {
87 if ($conf_props->{$pname}) {
88 debug("More than one value for $pname. Using the first.")
89 if scalar(@{$conf_props->{$pname}->{'values'}}) > 1;
90 $self->{'props'}->{$pname} = $conf_props->{$pname}->{'values'}->[0];
94 # check for properties like 'foo-pg-host' where the diskname is 'foo'
95 if ($self->{'args'}->{'disk'}) {
96 foreach my $pname (@PROP_NAMES) {
97 my $tmp = "$self->{'args'}->{'disk'}-$pname";
98 if ($conf_props->{$tmp}) {
99 debug("More than one value for $tmp. Using the first.")
100 if scalar(@{$conf_props->{$tmp}->{'values'}}) > 1;
101 $self->{'props'}->{$pname} = $conf_props->{$tmp}->{'values'}->[0];
106 # overwrite with dumptype properties if they are set.
107 foreach my $pname (@PROP_NAMES) {
108 my $pdumpname = $pname;
109 $pdumpname =~ s/^pg-//g;
110 $self->{'props'}->{$pname} = $self->{'args'}->{$pdumpname}
111 if defined $self->{'args'}->{$pdumpname};
112 debug("prop $pname set from dumpname $pdumpname: $self->{'args'}->{$pdumpname}")
113 if defined $self->{'args'}->{$pdumpname};
116 unless ($self->{'props'}->{'psql-path'}) {
117 foreach my $pre (split(/:/, $ENV{PATH})) {
118 my $psql = "$pre/psql";
120 $self->{'props'}{'psql-path'} = $psql;
126 foreach my $aname (keys %{$self->{'args'}}) {
127 if (defined($self->{'args'}->{$aname})) {
128 debug("app property: $aname $self->{'args'}->{$aname}");
130 debug("app property: $aname (undef)");
134 foreach my $pname (keys %{$self->{'props'}}) {
135 if (defined($self->{'props'}->{$pname})) {
136 debug("client property: $pname $self->{'props'}->{$pname}");
138 debug("client property: $pname (undef)");
142 if (!exists $self->{'props'}->{'pg-datadir'}) {
143 $self->{'props'}->{'pg-datadir'} = $self->{'args'}->{'device'};
149 sub command_support {
170 my ($desc, $succ_suf, $err_suf, $check, @check_args) = @_;
171 my $ret = $check->(@check_args);
172 my $msg = $ret? "OK $desc $succ_suf" : "ERROR $desc $err_suf";
178 sub _check_parent_dirs {
181 my $is_abs = substr($dir, 0, 1) eq "/";
182 _check("$dir is an absolute path?", "Yes", "No. It should start with '/'",
185 my @parts = split('/', $dir);
186 pop @parts; # don't test the last part
187 my $partial_path = '';
188 for my $path_part (@parts) {
189 $partial_path .= $path_part . (($partial_path || $is_abs)? '/' : '');
191 _check("$partial_path is executable?", "Yes", "No",
192 sub {-x $_[0]}, $partial_path);
194 _check("$partial_path is a directory?", "Yes", "No",
195 sub {-d $_[0]}, $partial_path);
200 sub _ok_passfile_perms {
201 my $passfile = shift @_;
202 # libpq uses stat, so we use stat
203 my @fstat = stat($passfile);
204 return 0 unless @fstat;
205 return 0 if 077 & $fstat[2];
209 sub _run_psql_command {
210 my ($self, $cmd) = @_;
212 # n.b. deprecated, passfile recommended for better security
213 my $orig_pgpassword = $ENV{'PGPASSWORD'};
214 $ENV{'PGPASSWORD'} = $self->{'props'}->{'pg-password'} if $self->{'props'}->{'pg-password'};
215 # n.b. supported in 8.1+
216 my $orig_pgpassfile = $ENV{'PGPASSFILE'};
217 $ENV{'PGPASSFILE'} = $self->{'props'}->{'pg-passfile'} if $self->{'props'}->{'pg-passfile'};
219 my @cmd = ($self->{'props'}->{'psql-path'});
221 push @cmd, "-h", $self->{'props'}->{'pg-host'} if ($self->{'props'}->{'pg-host'});
222 push @cmd, "-p", $self->{'props'}->{'pg-port'} if ($self->{'props'}->{'pg-port'});
223 push @cmd, "-U", $self->{'props'}->{'pg-user'} if ($self->{'props'}->{'pg-user'});
225 push @cmd, '--quiet', '--output', '/dev/null' if (!($cmd =~ /pg_xlogfile_name_offset/));
226 push @cmd, '--command', $cmd, $self->{'props'}->{'pg-db'};
227 debug("running " . join(" ", @cmd));
230 my $err = Symbol::gensym;
231 my $pid = open3($wtr, $rdr, $err, @cmd);
234 my $file_to_close = 2;
235 my $psql_stdout_src = Amanda::MainLoop::fd_source($rdr,
236 $G_IO_IN|$G_IO_HUP|$G_IO_ERR);
237 my $psql_stderr_src = Amanda::MainLoop::fd_source($err,
238 $G_IO_IN|$G_IO_HUP|$G_IO_ERR);
239 $psql_stdout_src->set_callback(sub {
241 if (!defined $line) {
243 $psql_stdout_src->remove();
244 Amanda::MainLoop::quit() if $file_to_close == 0;
248 return if $line =~ /^\s*$/;
249 debug("psql stdout: $line");
250 if ($cmd =~ /pg_xlogfile_name_offset/) {
251 return if $line =~ /file_name/;
252 return if $line =~ /------/;
253 return if $line =~ /\(1 row\)/;
254 if ($line =~ /^ ($_WAL_FILE_PAT)/) {
255 $self->{'switch_xlog_filename'} = $1;
259 if ($line =~ /NOTICE: pg_stop_backup complete, all required WAL segments have been archived/) {
261 $self->print_to_server("psql stdout: $line",
262 $Amanda::Script_App::GOOD);
265 $psql_stderr_src->set_callback(sub {
267 if (!defined $line) {
269 $psql_stderr_src->remove();
270 Amanda::MainLoop::quit() if $file_to_close == 0;
274 debug("psql stderr: $line");
275 if ($line =~ /NOTICE: pg_stop_backup complete, all required WAL segments have been archived/) {
276 } elsif ($line =~ /could not connect to server/) {
277 $self->print_to_server("psql stderr: $line",
278 $Amanda::Script_App::ERROR);
280 $self->print_to_server("psql stderr: $line",
281 $Amanda::Script_App::GOOD);
286 Amanda::MainLoop::run();
293 $ENV{'PGPASSWORD'} = $orig_pgpassword || '';
294 $ENV{'PGPASSFILE'} = $orig_pgpassfile || '';
296 return 0 == ($status >> 8)
299 sub command_selfcheck {
302 # set up to handle errors correctly
303 $self->{'die_cb'} = sub {
310 $self->print_to_server("disk " . quote_string($self->{args}->{disk}));
312 $self->print_to_server("ampgsql version " . $Amanda::Constants::VERSION,
313 $Amanda::Script_App::GOOD);
315 for my $k (keys %{$self->{'args'}}) {
316 print "OK application property: $k = $self->{'args'}->{$k}\n";
319 _check("GNUTAR-PATH $self->{'args'}->{'gnutar-path'}",
320 "is executable", "is NOT executable",
321 sub {-x $_[0]}, $self->{'args'}->{'gnutar-path'});
322 _check("GNUTAR-PATH $self->{'args'}->{'gnutar-path'}",
323 "is not a directory (okay)", "is a directory (it shouldn't be)",
324 sub {!(-d $_[0])}, $self->{'args'}->{'gnutar-path'});
325 _check_parent_dirs($self->{'args'}->{'gnutar-path'});
327 _check("GNUTAR $Amanda::Constants::GNUTAR",
328 "is executable", "is NOT executable",
329 sub {-x $_[0]}, $Amanda::Constants::GNUTAR);
330 _check("GNUTAR $Amanda::Constants::GNUTAR",
331 "is not a directory (okay)", "is a directory (it shouldn't be)",
332 sub {!(-d $_[0])}, $Amanda::Constants::GNUTAR);
333 _check_parent_dirs($Amanda::Constants::GNUTAR);
335 _check("TMPDIR '$self->{'args'}->{'tmpdir'}'",
336 "is an acessible directory", "is NOT an acessible directory",
337 sub {$_[0] && -d $_[0] && -r $_[0] && -w $_[0] && -x $_[0]},
338 $self->{'args'}->{'tmpdir'});
340 if (exists $self->{'props'}->{'pg-datadir'}) {
341 _check("PG-DATADIR property is",
342 "same as diskdevice", "differrent than diskdevice",
343 sub { $_[0] eq $_[1] },
344 $self->{'props'}->{'pg-datadir'}, $self->{'args'}->{'device'});
346 $self->{'props'}->{'pg-datadir'} = $self->{'args'}->{'device'};
349 _check("PG-DATADIR property", "is set", "is NOT set",
350 sub { $_[0] }, $self->{'props'}->{'pg-datadir'});
351 # note that the backup user need not be able ot read this dir
353 _check("STATEDIR '$self->{'args'}->{'statedir'}'",
354 "is an acessible directory", "is NOT an acessible directory",
355 sub {$_[0] && -d $_[0] && -r $_[0] && -w $_[0] && -x $_[0]},
356 $self->{'args'}->{'statedir'});
357 _check_parent_dirs($self->{'args'}->{'statedir'});
359 if ($self->{'args'}->{'device'}) {
362 for my $k (keys %{$self->{'props'}}) {
363 print "OK client property: $k = $self->{'props'}->{$k}\n";
366 if (_check("PG-ARCHIVEDIR property", "is set", "is NOT set",
367 sub { $_[0] }, $self->{'props'}->{'pg-archivedir'})) {
368 _check("PG-ARCHIVEDIR $self->{'props'}->{'pg-archivedir'}",
369 "is a directory", "is NOT a directory",
370 sub {-d $_[0]}, $self->{'props'}->{'pg-archivedir'});
371 _check("PG-ARCHIVEDIR $self->{'props'}->{'pg-archivedir'}",
372 "is readable", "is NOT readable",
373 sub {-r $_[0]}, $self->{'props'}->{'pg-archivedir'});
374 _check("PG-ARCHIVEDIR $self->{'props'}->{'pg-archivedir'}",
375 "is executable", "is NOT executable",
376 sub {-x $_[0]}, $self->{'props'}->{'pg-archivedir'});
377 _check_parent_dirs($self->{'props'}->{'pg-archivedir'});
381 _check("Are both PG-PASSFILE and PG-PASSWORD set?",
383 "Yes. Please set only one or the other",
384 sub {!($self->{'props'}->{'pg-passfile'} and
385 $self->{'props'}->{'pg-password'})});
387 if ($self->{'props'}->{'pg-passfile'}) {
389 _check("PG-PASSFILE $self->{'props'}->{'pg-passfile'}",
390 "has correct permissions", "does not have correct permissions",
391 \&_ok_passfile_perms, $self->{'props'}->{'pg-passfile'});
393 _check_parent_dirs($self->{'props'}->{'pg-passfile'});
396 if (_check("PSQL-PATH property", "is set", "is NOT set and psql is not in \$PATH",
397 sub { $_[0] }, $self->{'props'}->{'psql-path'})) {
399 _check("PSQL-PATH $self->{'props'}->{'psql-path'}",
400 "is executable", "is NOT executable",
401 sub {-x $_[0]}, $self->{'props'}->{'psql-path'});
403 _check("PSQL-PATH $self->{'props'}->{'psql-path'}",
404 "is not a directory (okay)", "is a directory (it shouldn't be)",
405 sub {!(-d $_[0])}, $self->{'props'}->{'psql-path'});
407 _check_parent_dirs($self->{'props'}->{'psql-path'});
413 my @pv = `$self->{'props'}->{'psql-path'} --version`;
415 $pv[0] =~ /^[^0-9]*([0-9.]*)[^0-9]*$/;
417 $self->print_to_server("ampgsql psql-version $pv",
418 $Amanda::Script_App::GOOD);
420 $self->print_to_server(
421 "[Can't get " . $self->{'props'}->{'psql-path'} . " version]\n",
422 $Amanda::Script_App::ERROR);
428 _check("Connecting to database server", "succeeded", "failed",
429 \&_run_psql_command, $self, '');
433 my @gv = `$self->{'args'}->{'gnutar-path'} --version`;
435 $gv[0] =~ /^[^0-9]*([0-9.]*)[^0-9]*$/;
437 $self->print_to_server("ampgsql gtar-version $gv",
438 $Amanda::Script_App::GOOD);
440 $self->print_to_server(
441 "[Can't get " . $self->{'props'}->{'gnutar-path'} . " version]\n",
442 $Amanda::Script_App::ERROR);
448 sub _state_filename {
449 my ($self, $level) = @_;
451 my @parts = ("ampgsql", hexencode($self->{'args'}->{'host'}), hexencode($self->{'args'}->{'disk'}), $level);
452 my $statefile = $self->{'args'}->{'statedir'} . '/' . join("-", @parts);
453 debug("statefile: $statefile");
457 sub _write_state_file {
458 my ($self, $end_wal) = @_;
460 my $h = new IO::File(_state_filename($self, $self->{'args'}->{'level'}), "w");
463 debug("writing state file");
464 $h->print("VERSION: 0\n");
465 $h->print("LAST WAL FILE: $end_wal\n");
470 sub _get_prev_state {
472 my $initial_level = shift;
473 $initial_level = $self->{'args'}->{'level'} - 1 if !defined $initial_level;
476 for (my $level = $initial_level; $level >= 0; $level--) {
477 my $fn = _state_filename($self, $level);
478 debug("reading state file: $fn");
479 my $h = new IO::File($fn, "r");
481 while (my $l = <$h>) {
484 if ($l =~ /^VERSION: (\d+)/) {
489 } elsif ($l =~ /^LAST WAL FILE: ($_WAL_FILE_PAT)/) {
499 sub _make_dummy_dir_base {
502 my $dummydir = "$self->{'args'}->{'tmpdir'}/ampgsql-dummy-$$";
503 mkpath("$dummydir/$_ARCHIVE_DIR_RESTORE");
508 sub _make_dummy_dir {
511 my $dummydir = "$self->{'args'}->{'tmpdir'}/ampgsql-dummy-$$";
513 open(my $fh, ">$dummydir/empty-incremental");
519 sub _run_tar_totals {
520 my ($self, @other_args) = @_;
523 @cmd = ($self->{'runtar'}, $self->{'args'}->{'config'},
524 $Amanda::Constants::GNUTAR, '--create', '--totals', @other_args);
525 debug("running: " . join(" ", @cmd));
527 local (*TAR_IN, *TAR_OUT, *TAR_ERR);
528 open TAR_OUT, ">&", $self->{'out_h'};
530 eval { $pid = open3(\*TAR_IN, ">&TAR_OUT", \*TAR_ERR, @cmd); 1;} or
531 $self->{'die_cb'}->("failed to run tar. error was $@");
536 while (my $l = <TAR_ERR>) {
537 if ($l =~ /^Total bytes written: (\d+)/) {
541 $self->print_to_server($l, $Amanda::Script_App::ERROR);
542 debug("TAR_ERR: $l");
546 my $status = POSIX::WEXITSTATUS($?);
549 debug("size of generated tar file: " . (defined($size)? $size : "undef"));
551 debug("ignored non-fatal tar exit status of 1");
553 $self->{'die_cb'}->("Tar failed (exit status $status)");
558 sub command_estimate {
561 $self->{'out_h'} = new IO::File("/dev/null", "w");
562 $self->{'out_h'} or die("Could not open /dev/null");
563 $self->{'index_h'} = new IO::File("/dev/null", "w");
564 $self->{'index_h'} or die("Could not open /dev/null");
566 $self->{'done_cb'} = sub {
568 debug("done. size $size");
569 $size = ceil($size/1024);
570 debug("sending $self->{'args'}->{'level'} $size 1");
571 print("$self->{'args'}->{'level'} $size 1\n");
573 $self->{'die_cb'} = sub {
576 $self->{'done_cb'}->(-1);
579 $self->{'state_cb'} = sub {
582 $self->{'unlink_cb'} = sub {
586 if ($self->{'args'}->{'level'} > 0) {
593 sub _get_backup_info {
594 my ($self, $label) = @_;
596 my ($fname, $bfile, $start_wal, $end_wal);
597 # wait up to 60s for the .backup file to be copied
598 for (my $count = 0; $count < 60; $count++) {
599 my $adir = new IO::Dir($self->{'props'}->{'pg-archivedir'});
600 $adir or $self->{'die_cb'}->("Could not open archive WAL directory");
601 while (defined($fname = $adir->read())) {
602 if ($fname =~ /\.backup$/) {
604 # use runtar to read a protected file, then grep the resulting tarfile (yes,
607 my $conf = $self->{'args'}->{'config'} || 'NOCONFIG';
608 my $cmd = "$self->{'runtar'} $conf $Amanda::Constants::GNUTAR --create --file - --directory $self->{'props'}->{'pg-archivedir'} $fname | $Amanda::Constants::GNUTAR --file - --extract --to-stdout";
609 debug("running: $cmd");
610 open(TAROUT, "$cmd |");
611 my ($start, $end, $lab);
612 while (my $l = <TAROUT>) {
614 if ($l =~ /^START WAL LOCATION:.*?\(file ($_WAL_FILE_PAT)\)$/) {
616 } elsif($l =~ /^STOP WAL LOCATION:.*?\(file ($_WAL_FILE_PAT)\)$/) {
618 } elsif ($l =~ /^LABEL: (.*)$/) {
623 if ($lab and $lab eq $label) {
629 debug("logfile had non-matching label");
634 if ($start_wal and $end_wal) {
635 debug("$bfile named WALs $start_wal .. $end_wal");
637 # try to cleanup a bit, although this may fail and that's ok
638 my $filename = "$self->{'props'}->{'pg-archivedir'}/$bfile";
639 if (unlink($filename) == 0) {
640 debug("Failed to unlink '$filename': $!");
641 $self->print_to_server("Failed to unlink '$filename': $!",
642 $Amanda::Script_App::ERROR);
649 ($start_wal, $end_wal);
652 # return the postgres version as an integer
653 sub _get_pg_version {
658 my @cmd = ($self->{'props'}->{'psql-path'});
660 push @cmd, "--version";
661 my $pid = open3('>&STDIN', \*VERSOUT, '>&STDERR', @cmd)
662 or $self->{'die_cb'}->("could not open psql to determine version");
663 my @lines = <VERSOUT>;
665 $self->{'die_cb'}->("could not run psql to determine version") if (($? >> 8) != 0);
667 my ($maj, $min, $pat) = ($lines[0] =~ / ([0-9]+)\.([0-9]+)\.([0-9]+)$/);
668 return $maj * 10000 + $min * 100 + $pat;
671 # create a large table and immediately drop it; this can help to push a WAL file out
672 sub _write_garbage_to_db {
675 debug("writing garbage to database to force a WAL archive");
677 # note: lest ye be tempted to add "if exists" to the drop table here, note that
678 # the clause was not supported in 8.1
679 _run_psql_command($self, <<EOF) or
680 CREATE TABLE _ampgsql_garbage AS SELECT * FROM GENERATE_SERIES(1, 500000);
681 DROP TABLE _ampgsql_garbage;
683 $self->{'die_cb'}->("Failed to create or drop table _ampgsql_garbage");
686 # wait up to pg-max-wal-wait seconds for a WAL file to appear
688 my ($self, $wal) = @_;
689 my $pg_version = $self->_get_pg_version();
691 my $archive_dir = $self->{'props'}->{'pg-archivedir'};
692 my $maxwait = 0+$self->{'props'}->{'pg-max-wal-wait'};
695 debug("waiting $maxwait s for WAL $wal to be archived..");
697 debug("waiting forever for WAL $wal to be archived..");
700 my $count = 0; # try at least 4 cycles
701 my $stoptime = time() + $maxwait;
702 while ($maxwait == 0 || time < $stoptime || $count++ < 4) {
703 if (-f "$archive_dir/$wal") {
708 # for versions 8.0 or 8.1, the only way to "force" a WAL archive is to write
709 # garbage to the database.
710 if ($pg_version < 80200) {
711 $self->_write_garbage_to_db();
717 $self->{'die_cb'}->("WAL file $wal was not archived in $maxwait seconds");
723 debug("running _base_backup");
725 my $label = "$self->{'label-prefix'}-" . time();
727 -d $self->{'props'}->{'pg-archivedir'} or
728 die("WAL file archive directory does not exist (or is not a directory)");
730 if ($self->{'action'} eq 'backup') {
731 _run_psql_command($self, "SELECT pg_start_backup('$label')") or
732 $self->{'die_cb'}->("Failed to call pg_start_backup");
735 # tar data dir, using symlink to prefix
736 # XXX: tablespaces and their symlinks?
737 # See: http://www.postgresql.org/docs/8.0/static/manage-ag-tablespaces.html
738 my $old_die_cb = $self->{'die_cb'};
739 $self->{'die_cb'} = sub {
741 if ($self->{'action'} eq 'backup') {
742 unless(_run_psql_command($self, "SELECT pg_stop_backup()")) {
743 $msg .= " and failed to call pg_stop_backup";
748 my $size = _run_tar_totals($self, '--file', "-",
749 '--directory', $self->{'props'}->{'pg-datadir'},
750 '--exclude', 'postmaster.pid',
751 '--exclude', 'pg_xlog/*', # contains WAL files; will be handled below
752 '--transform', "s,^,$_DATA_DIR_RESTORE/,S",
754 $self->{'die_cb'} = $old_die_cb;
756 if ($self->{'action'} eq 'backup') {
757 unless (_run_psql_command($self, "SELECT pg_stop_backup()")) {
758 $self->{'die_cb'}->("Failed to call pg_stop_backup");
762 # determine WAL files and append and create their tar file
766 if ($self->{'action'} eq 'backup') {
767 ($start_wal, $end_wal) = _get_backup_info($self, $label);
768 ($start_wal and $end_wal)
769 or $self->{'die_cb'}->("A .backup file was never found in the archive "
770 . "dir $self->{'props'}->{'pg-archivedir'}");
771 $self->_wait_for_wal($end_wal);
774 $end_wal = _get_prev_state($self, 0);
777 # now grab all of the WAL files, *inclusive* of $start_wal
779 my $adir = new IO::Dir($self->{'props'}->{'pg-archivedir'});
780 while (defined(my $fname = $adir->read())) {
781 if ($fname =~ /^$_WAL_FILE_PAT$/) {
782 if (!defined $end_wal ||
783 (!defined $start_wal and ($fname le $end_wal)) ||
784 (defined $start_wal and ($fname ge $start_wal) and
785 ($fname le $end_wal))) {
786 push @wal_files, $fname;
787 debug("will store: $fname");
788 } elsif (defined $start_wal and $fname lt $start_wal) {
789 $self->{'unlink_cb'}->("$self->{'props'}->{'pg-archivedir'}/$fname");
796 $size += _run_tar_totals($self, '--file', "-",
797 '--directory', $self->{'props'}->{'pg-archivedir'},
798 '--transform', "s,^,$_ARCHIVE_DIR_RESTORE/,S",
801 my $dummydir = $self->_make_dummy_dir_base();
802 $self->{'done_cb'}->(_run_tar_totals($self, '--file', '-',
803 '--directory', $dummydir, "$_ARCHIVE_DIR_RESTORE"));
807 $self->{'state_cb'}->($self, $end_wal);
809 $self->{'done_cb'}->($size);
815 debug("running _incr_backup");
817 if ($self->{'action'} eq 'backup') {
818 _run_psql_command($self, "SELECT file_name from pg_xlogfile_name_offset(pg_switch_xlog())");
819 if (defined($self->{'switch_xlog_filename'})) {
820 $self->_wait_for_wal($self->{'switch_xlog_filename'});
824 my $end_wal = _get_prev_state($self);
826 debug("previously ended at: $end_wal");
828 debug("no previous state found!");
829 return _base_backup(@_);
832 my $adir = new IO::Dir($self->{'props'}->{'pg-archivedir'});
833 $adir or $self->{'die_cb'}->("Could not open archive WAL directory");
835 my ($fname, @wal_files);
836 while (defined($fname = $adir->read())) {
837 if (($fname =~ /^$_WAL_FILE_PAT$/) and ($fname gt $end_wal)) {
838 $max_wal = $fname if $fname gt $max_wal;
839 push @wal_files, $fname;
840 debug("will store: $fname");
844 $self->{'state_cb'}->($self, $max_wal ? $max_wal : $end_wal);
847 $self->{'done_cb'}->(_run_tar_totals($self, '--file', '-',
848 '--directory', $self->{'props'}->{'pg-archivedir'}, @wal_files));
850 my $dummydir = $self->_make_dummy_dir();
851 $self->{'done_cb'}->(_run_tar_totals($self, '--file', '-',
852 '--directory', $dummydir, "empty-incremental"));
860 $self->{'out_h'} = IO::Handle->new_from_fd(1, 'w');
861 $self->{'out_h'} or die("Could not open data fd");
862 my $msg_fd = IO::Handle->new_from_fd(3, 'w');
863 $msg_fd or die("Could not open message fd");
864 $self->{'index_h'} = IO::Handle->new_from_fd(4, 'w');
865 $self->{'index_h'} or die("Could not open index fd");
867 $self->{'done_cb'} = sub {
869 debug("done. size $size");
870 $size = ceil($size/1024);
871 debug("sending size $size");
872 $msg_fd->print("sendbackup: size $size\n");
874 $self->{'index_h'}->print("/PostgreSQL-Database-$self->{'args'}->{'level'}\n");
876 $msg_fd->print("sendbackup: end\n");
878 $self->{'die_cb'} = sub {
881 $msg_fd->print("! $msg\n");
882 $self->{'done_cb'}->(0);
885 $self->{'state_cb'} = sub {
886 my ($self, $end_wal) = @_;
887 _write_state_file($self, $end_wal) or $self->{'die_cb'}->("Failed to write state file");
889 my $cleanup_wal_val = $self->{'props'}->{'pg-cleanupwal'} || 'yes';
890 my $cleanup_wal = string_to_boolean($cleanup_wal_val);
891 if (!defined($cleanup_wal)) {
892 $self->{'die_cb'}->("couldn't interpret PG-CLEANUPWAL value '$cleanup_wal_val' as a boolean");
893 } elsif ($cleanup_wal) {
894 $self->{'unlink_cb'} = sub {
895 my $filename = shift @_;
896 debug("unlinking WAL file $filename");
897 if (unlink($filename) == 0) {
898 debug("Failed to unlink '$filename': $!");
899 $self->print_to_server("Failed to unlink '$filename': $!",
900 $Amanda::Script_App::ERROR);
904 $self->{'unlink_cb'} = sub {
909 if ($self->{'args'}->{'level'} > 0) {
910 _incr_backup($self, \*STDOUT);
912 _base_backup($self, \*STDOUT);
916 sub command_restore {
919 chdir(Amanda::Util::get_original_cwd());
920 if (defined $self->{'args'}->{directory}) {
921 if (!-d $self->{'args'}->{directory}) {
922 $self->print_to_server_and_die("Directory $self->{directory}: $!",
923 $Amanda::Script_App::ERROR);
925 if (!-w $self->{'args'}->{directory}) {
926 $self->print_to_server_and_die("Directory $self->{directory}: $!",
927 $Amanda::Script_App::ERROR);
929 chdir($self->{'args'}->{directory});
931 my $cur_dir = POSIX::getcwd();
933 if (!-d $_ARCHIVE_DIR_RESTORE) {
934 mkdir($_ARCHIVE_DIR_RESTORE) or die("could not create archive WAL directory: $!");
937 if ($self->{'args'}->{'level'} > 0) {
938 debug("extracting incremental backup to $cur_dir/$_ARCHIVE_DIR_RESTORE");
939 $status = system($self->{'args'}->{'gnutar-path'},
943 '--exclude', 'empty-incremental',
944 '--directory', $_ARCHIVE_DIR_RESTORE) >> 8;
945 (0 == $status) or die("Failed to extract level $self->{'args'}->{'level'} backup (exit status: $status)");
947 debug("extracting base of full backup to $cur_dir/$_DATA_DIR_RESTORE");
948 debug("extracting archive dir to $cur_dir/$_ARCHIVE_DIR_RESTORE");
949 if (!-d $_DATA_DIR_RESTORE) {
950 mkdir($_DATA_DIR_RESTORE) or die("could not create archive WAL directory: $!");
952 my @cmd = ($self->{'args'}->{'gnutar-path'}, '--extract',
955 '--transform', "s,^DATA/,$_DATA_DIR_RESTORE/,S",
956 '--transform', "s,^WAL/,$_ARCHIVE_DIR_RESTORE/,S");
957 debug("run: " . join ' ',@cmd);
958 $status = system(@cmd) >> 8;
959 (0 == $status) or die("Failed to extract base backup (exit status: $status)");
961 if (-f $_ARCHIVE_DIR_TAR) {
962 debug("extracting archive dir to $cur_dir/$_ARCHIVE_DIR_RESTORE");
963 my @cmd = ($self->{'args'}->{'gnutar-path'}, '--extract',
964 '--exclude', 'empty-incremental',
965 '--file', $_ARCHIVE_DIR_TAR, '--directory',
966 $_ARCHIVE_DIR_RESTORE);
967 debug("run: " . join ' ',@cmd);
968 $status = system(@cmd) >> 8;
969 (0 == $status) or die("Failed to extract archived WAL files from base backup (exit status: $status)");
970 if (unlink($_ARCHIVE_DIR_TAR) == 0) {
971 debug("Failed to unlink '$_ARCHIVE_DIR_TAR': $!");
972 $self->print_to_server(
973 "Failed to unlink '$_ARCHIVE_DIR_TAR': $!",
974 $Amanda::Script_App::ERROR);
978 if (-f $_DATA_DIR_TAR) {
979 debug("extracting data dir to $cur_dir/$_DATA_DIR_RESTORE");
980 my @cmd = ($self->{'args'}->{'gnutar-path'}, '--extract',
981 '--file', $_DATA_DIR_TAR,
982 '--directory', $_DATA_DIR_RESTORE);
983 debug("run: " . join ' ',@cmd);
984 $status = system(@cmd) >> 8;
985 (0 == $status) or die("Failed to extract data directory from base backup (exit status: $status)");
986 if (unlink($_DATA_DIR_TAR) == 0) {
987 debug("Failed to unlink '$_DATA_DIR_TAR': $!");
988 $self->print_to_server("Failed to unlink '$_DATA_DIR_TAR': $!",
989 $Amanda::Script_App::ERROR);
995 sub command_validate {
998 # set up to handle errors correctly
999 $self->{'die_cb'} = sub {
1006 if (!defined($self->{'args'}->{'gnutar-path'}) ||
1007 !-x $self->{'args'}->{'gnutar-path'}) {
1008 return $self->default_validate();
1011 my(@cmd) = ($self->{'args'}->{'gnutar-path'}, "--ignore-zeros", "-tf", "-");
1012 debug("cmd:" . join(" ", @cmd));
1013 my $pid = open3('>&STDIN', '>&STDOUT', '>&STDERR', @cmd) ||
1014 $self->print_to_server_and_die("Unable to run @cmd",
1015 $Amanda::Application::ERROR);
1018 $self->print_to_server_and_die("$self->{gnutar} returned error",
1019 $Amanda::Application::ERROR);
1021 exit($self->{error_status});
1028 Usage: ampgsql <command> --config=<config> --host=<host> --disk=<disk> --device=<device> --level=<level> --index=<yes|no> --message=<text> --collection=<no> --record=<yes|no> --calcsize.
1038 'version' => \$opt_version,
1067 if (defined $opt_version) {
1068 print "ampgsql-" . $Amanda::Constants::VERSION , "\n";
1072 my $application = Amanda::Application::ampgsql->new($opts);
1074 $application->do($ARGV[0]);