2 # Copyright (c) 2009, 2010 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/) {
277 $self->print_to_server("psql stderr: $line",
278 $Amanda::Script_App::GOOD);
283 Amanda::MainLoop::run();
290 $ENV{'PGPASSWORD'} = $orig_pgpassword || '';
291 $ENV{'PGPASSFILE'} = $orig_pgpassfile || '';
293 return 0 == ($status >> 8)
296 sub command_selfcheck {
299 # set up to handle errors correctly
300 $self->{'die_cb'} = sub {
307 $self->print_to_server("disk " . quote_string($self->{args}->{disk}));
309 $self->print_to_server("ampgsql version " . $Amanda::Constants::VERSION,
310 $Amanda::Script_App::GOOD);
312 for my $k (keys %{$self->{'args'}}) {
313 print "OK application property: $k = $self->{'args'}->{$k}\n";
316 _check("GNUTAR-PATH $self->{'args'}->{'gnutar-path'}",
317 "is executable", "is NOT executable",
318 sub {-x $_[0]}, $self->{'args'}->{'gnutar-path'});
319 _check("GNUTAR-PATH $self->{'args'}->{'gnutar-path'}",
320 "is not a directory (okay)", "is a directory (it shouldn't be)",
321 sub {!(-d $_[0])}, $self->{'args'}->{'gnutar-path'});
322 _check_parent_dirs($self->{'args'}->{'gnutar-path'});
324 _check("GNUTAR $Amanda::Constants::GNUTAR",
325 "is executable", "is NOT executable",
326 sub {-x $_[0]}, $Amanda::Constants::GNUTAR);
327 _check("GNUTAR $Amanda::Constants::GNUTAR",
328 "is not a directory (okay)", "is a directory (it shouldn't be)",
329 sub {!(-d $_[0])}, $Amanda::Constants::GNUTAR);
330 _check_parent_dirs($Amanda::Constants::GNUTAR);
332 _check("TMPDIR '$self->{'args'}->{'tmpdir'}'",
333 "is an acessible directory", "is NOT an acessible directory",
334 sub {$_[0] && -d $_[0] && -r $_[0] && -w $_[0] && -x $_[0]},
335 $self->{'args'}->{'tmpdir'});
337 if (exists $self->{'props'}->{'pg-datadir'}) {
338 _check("PG-DATADIR property is",
339 "same as diskdevice", "differrent than diskdevice",
340 sub { $_[0] eq $_[1] },
341 $self->{'props'}->{'pg-datadir'}, $self->{'args'}->{'device'});
343 $self->{'props'}->{'pg-datadir'} = $self->{'args'}->{'device'};
346 _check("PG-DATADIR property", "is set", "is NOT set",
347 sub { $_[0] }, $self->{'props'}->{'pg-datadir'});
348 # note that the backup user need not be able ot read this dir
350 _check("STATEDIR '$self->{'args'}->{'statedir'}'",
351 "is an acessible directory", "is NOT an acessible directory",
352 sub {$_[0] && -d $_[0] && -r $_[0] && -w $_[0] && -x $_[0]},
353 $self->{'args'}->{'statedir'});
354 _check_parent_dirs($self->{'args'}->{'statedir'});
356 if ($self->{'args'}->{'device'}) {
359 for my $k (keys %{$self->{'props'}}) {
360 print "OK client property: $k = $self->{'props'}->{$k}\n";
363 if (_check("PG-ARCHIVEDIR property", "is set", "is NOT set",
364 sub { $_[0] }, $self->{'props'}->{'pg-archivedir'})) {
365 _check("PG-ARCHIVEDIR $self->{'props'}->{'pg-archivedir'}",
366 "is a directory", "is NOT a directory",
367 sub {-d $_[0]}, $self->{'props'}->{'pg-archivedir'});
368 _check("PG-ARCHIVEDIR $self->{'props'}->{'pg-archivedir'}",
369 "is readable", "is NOT readable",
370 sub {-r $_[0]}, $self->{'props'}->{'pg-archivedir'});
371 _check("PG-ARCHIVEDIR $self->{'props'}->{'pg-archivedir'}",
372 "is executable", "is NOT executable",
373 sub {-x $_[0]}, $self->{'props'}->{'pg-archivedir'});
374 _check_parent_dirs($self->{'props'}->{'pg-archivedir'});
378 _check("Are both PG-PASSFILE and PG-PASSWORD set?",
380 "Yes. Please set only one or the other",
381 sub {!($self->{'props'}->{'pg-passfile'} and
382 $self->{'props'}->{'pg-password'})});
384 if ($self->{'props'}->{'pg-passfile'}) {
386 _check("PG-PASSFILE $self->{'props'}->{'pg-passfile'}",
387 "has correct permissions", "does not have correct permissions",
388 \&_ok_passfile_perms, $self->{'props'}->{'pg-passfile'});
390 _check_parent_dirs($self->{'props'}->{'pg-passfile'});
393 if (_check("PSQL-PATH property", "is set", "is NOT set and psql is not in \$PATH",
394 sub { $_[0] }, $self->{'props'}->{'psql-path'})) {
396 _check("PSQL-PATH $self->{'props'}->{'psql-path'}",
397 "is executable", "is NOT executable",
398 sub {-x $_[0]}, $self->{'props'}->{'psql-path'});
400 _check("PSQL-PATH $self->{'props'}->{'psql-path'}",
401 "is not a directory (okay)", "is a directory (it shouldn't be)",
402 sub {!(-d $_[0])}, $self->{'props'}->{'psql-path'});
404 _check_parent_dirs($self->{'props'}->{'psql-path'});
410 my @pv = `$self->{'props'}->{'psql-path'} --version`;
412 $pv[0] =~ /^[^0-9]*([0-9.]*)[^0-9]*$/;
414 $self->print_to_server("ampgsql psql-version $pv",
415 $Amanda::Script_App::GOOD);
417 $self->print_to_server(
418 "[Can't get " . $self->{'props'}->{'psql-path'} . " version]\n",
419 $Amanda::Script_App::ERROR);
425 _check("Connecting to database server", "succeeded", "failed",
426 \&_run_psql_command, $self, '');
430 my $label = "$self->{'label-prefix'}-selfcheck-" . time();
431 if (_check("Call pg_start_backup", "succeeded",
432 "failed (is another backup running?)",
433 \&_run_psql_command, $self, "SELECT pg_start_backup('$label')")
434 and _check("Call pg_stop_backup", "succeeded", "failed",
435 \&_run_psql_command, $self, "SELECT pg_stop_backup()")) {
437 _check("Get info from .backup file", "succeeded", "failed",
438 sub {my ($start, $end) = _get_backup_info($self, $label); $start and $end});
443 my @gv = `$self->{'args'}->{'gnutar-path'} --version`;
445 $gv[0] =~ /^[^0-9]*([0-9.]*)[^0-9]*$/;
447 $self->print_to_server("ampgsql gtar-version $gv",
448 $Amanda::Script_App::GOOD);
450 $self->print_to_server(
451 "[Can't get " . $self->{'props'}->{'gnutar-path'} . " version]\n",
452 $Amanda::Script_App::ERROR);
458 sub _state_filename {
459 my ($self, $level) = @_;
461 my @parts = ("ampgsql", hexencode($self->{'args'}->{'host'}), hexencode($self->{'args'}->{'disk'}), $level);
462 my $statefile = $self->{'args'}->{'statedir'} . '/' . join("-", @parts);
463 debug("statefile: $statefile");
467 sub _write_state_file {
468 my ($self, $end_wal) = @_;
470 my $h = new IO::File(_state_filename($self, $self->{'args'}->{'level'}), "w");
473 debug("writing state file");
474 $h->print("VERSION: 0\n");
475 $h->print("LAST WAL FILE: $end_wal\n");
480 sub _get_prev_state {
484 for (my $level = $self->{'args'}->{'level'} - 1; $level >= 0; $level--) {
485 my $fn = _state_filename($self, $level);
486 debug("reading state file: $fn");
487 my $h = new IO::File($fn, "r");
489 while (my $l = <$h>) {
492 if ($l =~ /^VERSION: (\d+)/) {
497 } elsif ($l =~ /^LAST WAL FILE: ($_WAL_FILE_PAT)/) {
507 sub _make_dummy_dir_base {
510 my $dummydir = "$self->{'args'}->{'tmpdir'}/ampgsql-dummy-$$";
511 mkpath("$dummydir/$_ARCHIVE_DIR_RESTORE");
516 sub _make_dummy_dir {
519 my $dummydir = "$self->{'args'}->{'tmpdir'}/ampgsql-dummy-$$";
521 open(my $fh, ">$dummydir/empty-incremental");
527 sub _run_tar_totals {
528 my ($self, @other_args) = @_;
531 @cmd = ($self->{'runtar'}, $self->{'args'}->{'config'},
532 $Amanda::Constants::GNUTAR, '--create', '--totals', @other_args);
533 debug("running: " . join(" ", @cmd));
535 local (*TAR_IN, *TAR_OUT, *TAR_ERR);
536 open TAR_OUT, ">&", $self->{'out_h'};
538 eval { $pid = open3(\*TAR_IN, ">&TAR_OUT", \*TAR_ERR, @cmd); 1;} or
539 $self->{'die_cb'}->("failed to run tar. error was $@");
544 while (my $l = <TAR_ERR>) {
545 if ($l =~ /^Total bytes written: (\d+)/) {
549 $self->print_to_server($l, $Amanda::Script_App::ERROR);
550 debug("TAR_ERR: $l");
554 my $status = POSIX::WEXITSTATUS($?);
557 debug("size of generated tar file: " . (defined($size)? $size : "undef"));
559 debug("ignored non-fatal tar exit status of 1");
561 $self->{'die_cb'}->("Tar failed (exit status $status)");
566 sub command_estimate {
569 $self->{'out_h'} = new IO::File("/dev/null", "w");
570 $self->{'out_h'} or die("Could not open /dev/null");
571 $self->{'index_h'} = new IO::File("/dev/null", "w");
572 $self->{'index_h'} or die("Could not open /dev/null");
574 $self->{'done_cb'} = sub {
576 debug("done. size $size");
577 $size = ceil($size/1024);
578 debug("sending $self->{'args'}->{'level'} $size 1");
579 print("$self->{'args'}->{'level'} $size 1\n");
581 $self->{'die_cb'} = sub {
584 $self->{'done_cb'}->(-1);
587 $self->{'state_cb'} = sub {
590 $self->{'unlink_cb'} = sub {
594 if ($self->{'args'}->{'level'} > 0) {
601 sub _get_backup_info {
602 my ($self, $label) = @_;
604 my ($fname, $bfile, $start_wal, $end_wal);
605 # wait up to 60s for the .backup file to be copied
606 for (my $count = 0; $count < 60; $count++) {
607 my $adir = new IO::Dir($self->{'props'}->{'pg-archivedir'});
608 $adir or $self->{'die_cb'}->("Could not open archive WAL directory");
609 while (defined($fname = $adir->read())) {
610 if ($fname =~ /\.backup$/) {
612 # use runtar to read a protected file, then grep the resulting tarfile (yes,
615 my $conf = $self->{'args'}->{'config'} || 'NOCONFIG';
616 my $cmd = "$self->{'runtar'} $conf $Amanda::Constants::GNUTAR --create --file - --directory $self->{'props'}->{'pg-archivedir'} $fname | $Amanda::Constants::GNUTAR --file - --extract --to-stdout";
617 debug("running: $cmd");
618 open(TAROUT, "$cmd |");
619 my ($start, $end, $lab);
620 while (my $l = <TAROUT>) {
622 if ($l =~ /^START WAL LOCATION:.*?\(file ($_WAL_FILE_PAT)\)$/) {
624 } elsif($l =~ /^STOP WAL LOCATION:.*?\(file ($_WAL_FILE_PAT)\)$/) {
626 } elsif ($l =~ /^LABEL: (.*)$/) {
631 if ($lab and $lab eq $label) {
637 debug("logfile had non-matching label");
642 if ($start_wal and $end_wal) {
643 debug("$bfile named WALs $start_wal .. $end_wal");
645 # try to cleanup a bit, although this may fail and that's ok
646 my $filename = "$self->{'props'}->{'pg-archivedir'}/$bfile";
647 if (unlink($filename) == 0) {
648 debug("Failed to unlink '$filename': $!");
649 $self->print_to_server("Failed to unlink '$filename': $!",
650 $Amanda::Script_App::ERROR);
657 ($start_wal, $end_wal);
660 # return the postgres version as an integer
661 sub _get_pg_version {
666 my @cmd = ($self->{'props'}->{'psql-path'});
668 push @cmd, "--version";
669 my $pid = open3('>&STDIN', \*VERSOUT, '>&STDERR', @cmd)
670 or $self->{'die_cb'}->("could not open psql to determine version");
671 my @lines = <VERSOUT>;
673 $self->{'die_cb'}->("could not run psql to determine version") if (($? >> 8) != 0);
675 my ($maj, $min, $pat) = ($lines[0] =~ / ([0-9]+)\.([0-9]+)\.([0-9]+)$/);
676 return $maj * 10000 + $min * 100 + $pat;
679 # create a large table and immediately drop it; this can help to push a WAL file out
680 sub _write_garbage_to_db {
683 debug("writing garbage to database to force a WAL archive");
685 # note: lest ye be tempted to add "if exists" to the drop table here, note that
686 # the clause was not supported in 8.1
687 _run_psql_command($self, <<EOF) or
688 CREATE TABLE _ampgsql_garbage AS SELECT * FROM GENERATE_SERIES(1, 500000);
689 DROP TABLE _ampgsql_garbage;
691 $self->{'die_cb'}->("Failed to create or drop table _ampgsql_garbage");
694 # wait up to pg-max-wal-wait seconds for a WAL file to appear
696 my ($self, $wal) = @_;
697 my $pg_version = $self->_get_pg_version();
699 my $archive_dir = $self->{'props'}->{'pg-archivedir'};
700 my $maxwait = 0+$self->{'props'}->{'pg-max-wal-wait'};
703 debug("waiting $maxwait s for WAL $wal to be archived..");
705 debug("waiting forever for WAL $wal to be archived..");
708 my $count = 0; # try at least 4 cycles
709 my $stoptime = time() + $maxwait;
710 while ($maxwait == 0 || time < $stoptime || $count++ < 4) {
711 return if -f "$archive_dir/$wal";
713 # for versions 8.0 or 8.1, the only way to "force" a WAL archive is to write
714 # garbage to the database.
715 if ($pg_version < 80200) {
716 $self->_write_garbage_to_db();
722 $self->{'die_cb'}->("WAL file $wal was not archived in $maxwait seconds");
728 debug("running _base_backup");
730 my $label = "$self->{'label-prefix'}-" . time();
732 -d $self->{'props'}->{'pg-archivedir'} or
733 die("WAL file archive directory does not exist (or is not a directory)");
735 _run_psql_command($self, "SELECT pg_start_backup('$label')") or
736 $self->{'die_cb'}->("Failed to call pg_start_backup");
738 # tar data dir, using symlink to prefix
739 # XXX: tablespaces and their symlinks?
740 # See: http://www.postgresql.org/docs/8.0/static/manage-ag-tablespaces.html
741 my $old_die_cb = $self->{'die_cb'};
742 $self->{'die_cb'} = sub {
744 unless(_run_psql_command($self, "SELECT pg_stop_backup()")) {
745 $msg .= " and failed to call pg_stop_backup";
749 my $size = _run_tar_totals($self, '--file', "-",
750 '--directory', $self->{'props'}->{'pg-datadir'},
751 '--exclude', 'postmaster.pid',
752 '--exclude', 'pg_xlog/*', # contains WAL files; will be handled below
753 '--transform', "s,^,$_DATA_DIR_RESTORE/,S",
755 $self->{'die_cb'} = $old_die_cb;
757 unless (_run_psql_command($self, "SELECT pg_stop_backup()")) {
758 $self->{'die_cb'}->("Failed to call pg_stop_backup");
761 # determine WAL files and append and create their tar file
762 my ($start_wal, $end_wal) = _get_backup_info($self, $label);
764 ($start_wal and $end_wal)
765 or $self->{'die_cb'}->("A .backup file was never found in the archive "
766 . "dir $self->{'props'}->{'pg-archivedir'}");
768 $self->_wait_for_wal($end_wal);
770 # now grab all of the WAL files, *inclusive* of $start_wal
772 my $adir = new IO::Dir($self->{'props'}->{'pg-archivedir'});
773 while (defined(my $fname = $adir->read())) {
774 if ($fname =~ /^$_WAL_FILE_PAT$/) {
775 if (($fname ge $start_wal) and ($fname le $end_wal)) {
776 push @wal_files, $fname;
777 debug("will store: $fname");
778 } elsif ($fname lt $start_wal) {
779 $self->{'unlink_cb'}->("$self->{'props'}->{'pg-archivedir'}/$fname");
786 $size += _run_tar_totals($self, '--file', "-",
787 '--directory', $self->{'props'}->{'pg-archivedir'},
788 '--transform', "s,^,$_ARCHIVE_DIR_RESTORE/,S",
791 my $dummydir = $self->_make_dummy_dir_base();
792 $self->{'done_cb'}->(_run_tar_totals($self, '--file', '-',
793 '--directory', $dummydir, "$_ARCHIVE_DIR_RESTORE"));
797 $self->{'state_cb'}->($self, $end_wal);
799 $self->{'done_cb'}->($size);
805 debug("running _incr_backup");
807 if ($self->{'action'} eq 'backup') {
808 _run_psql_command($self, "SELECT file_name from pg_xlogfile_name_offset(pg_switch_xlog())");
809 if (defined($self->{'switch_xlog_filename'})) {
810 $self->_wait_for_wal($self->{'switch_xlog_filename'});
814 my $end_wal = _get_prev_state($self);
816 debug("previously ended at: $end_wal");
818 debug("no previous state found!");
819 return _base_backup(@_);
822 my $adir = new IO::Dir($self->{'props'}->{'pg-archivedir'});
823 $adir or $self->{'die_cb'}->("Could not open archive WAL directory");
825 my ($fname, @wal_files);
826 while (defined($fname = $adir->read())) {
827 if (($fname =~ /^$_WAL_FILE_PAT$/) and ($fname gt $end_wal)) {
828 $max_wal = $fname if $fname gt $max_wal;
829 push @wal_files, $fname;
830 debug("will store: $fname");
834 $self->{'state_cb'}->($self, $max_wal ? $max_wal : $end_wal);
837 $self->{'done_cb'}->(_run_tar_totals($self, '--file', '-',
838 '--directory', $self->{'props'}->{'pg-archivedir'}, @wal_files));
840 my $dummydir = $self->_make_dummy_dir();
841 $self->{'done_cb'}->(_run_tar_totals($self, '--file', '-',
842 '--directory', $dummydir, "empty-incremental"));
850 $self->{'out_h'} = IO::Handle->new_from_fd(1, 'w');
851 $self->{'out_h'} or die("Could not open data fd");
852 my $msg_fd = IO::Handle->new_from_fd(3, 'w');
853 $msg_fd or die("Could not open message fd");
854 $self->{'index_h'} = IO::Handle->new_from_fd(4, 'w');
855 $self->{'index_h'} or die("Could not open index fd");
857 $self->{'done_cb'} = sub {
859 debug("done. size $size");
860 $size = ceil($size/1024);
861 debug("sending size $size");
862 $msg_fd->print("sendbackup: size $size\n");
864 $self->{'index_h'}->print("/PostgreSQL-Database-$self->{'args'}->{'level'}\n");
866 $msg_fd->print("sendbackup: end\n");
868 $self->{'die_cb'} = sub {
871 $msg_fd->print("! $msg\n");
872 $self->{'done_cb'}->(0);
875 $self->{'state_cb'} = sub {
876 my ($self, $end_wal) = @_;
877 _write_state_file($self, $end_wal) or $self->{'die_cb'}->("Failed to write state file");
879 my $cleanup_wal_val = $self->{'props'}->{'pg-cleanupwal'} || 'yes';
880 my $cleanup_wal = string_to_boolean($cleanup_wal_val);
881 if (!defined($cleanup_wal)) {
882 $self->{'die_cb'}->("couldn't interpret PG-CLEANUPWAL value '$cleanup_wal_val' as a boolean");
883 } elsif ($cleanup_wal) {
884 $self->{'unlink_cb'} = sub {
885 my $filename = shift @_;
886 debug("unlinking WAL file $filename");
887 if (unlink($filename) == 0) {
888 debug("Failed to unlink '$filename': $!");
889 $self->print_to_server("Failed to unlink '$filename': $!",
890 $Amanda::Script_App::ERROR);
894 $self->{'unlink_cb'} = sub {
899 if ($self->{'args'}->{'level'} > 0) {
900 _incr_backup($self, \*STDOUT);
902 _base_backup($self, \*STDOUT);
906 sub command_restore {
909 chdir(Amanda::Util::get_original_cwd());
910 if (defined $self->{'args'}->{directory}) {
911 if (!-d $self->{'args'}->{directory}) {
912 $self->print_to_server_and_die("Directory $self->{directory}: $!",
913 $Amanda::Script_App::ERROR);
915 if (!-w $self->{'args'}->{directory}) {
916 $self->print_to_server_and_die("Directory $self->{directory}: $!",
917 $Amanda::Script_App::ERROR);
919 chdir($self->{'args'}->{directory});
921 my $cur_dir = POSIX::getcwd();
923 if (!-d $_ARCHIVE_DIR_RESTORE) {
924 mkdir($_ARCHIVE_DIR_RESTORE) or die("could not create archive WAL directory: $!");
927 if ($self->{'args'}->{'level'} > 0) {
928 debug("extracting incremental backup to $cur_dir/$_ARCHIVE_DIR_RESTORE");
929 $status = system($self->{'args'}->{'gnutar-path'},
933 '--exclude', 'empty-incremental',
934 '--directory', $_ARCHIVE_DIR_RESTORE) >> 8;
935 (0 == $status) or die("Failed to extract level $self->{'args'}->{'level'} backup (exit status: $status)");
937 debug("extracting base of full backup to $cur_dir/$_DATA_DIR_RESTORE");
938 debug("extracting archive dir to $cur_dir/$_ARCHIVE_DIR_RESTORE");
939 if (!-d $_DATA_DIR_RESTORE) {
940 mkdir($_DATA_DIR_RESTORE) or die("could not create archive WAL directory: $!");
942 my @cmd = ($self->{'args'}->{'gnutar-path'}, '--extract',
945 '--transform', "s,^DATA/,$_DATA_DIR_RESTORE/,S",
946 '--transform', "s,^WAL/,$_ARCHIVE_DIR_RESTORE/,S");
947 debug("run: " . join ' ',@cmd);
948 $status = system(@cmd) >> 8;
949 (0 == $status) or die("Failed to extract base backup (exit status: $status)");
951 if (-f $_ARCHIVE_DIR_TAR) {
952 debug("extracting archive dir to $cur_dir/$_ARCHIVE_DIR_RESTORE");
953 my @cmd = ($self->{'args'}->{'gnutar-path'}, '--extract',
954 '--exclude', 'empty-incremental',
955 '--file', $_ARCHIVE_DIR_TAR, '--directory',
956 $_ARCHIVE_DIR_RESTORE);
957 debug("run: " . join ' ',@cmd);
958 $status = system(@cmd) >> 8;
959 (0 == $status) or die("Failed to extract archived WAL files from base backup (exit status: $status)");
960 if (unlink($_ARCHIVE_DIR_TAR) == 0) {
961 debug("Failed to unlink '$_ARCHIVE_DIR_TAR': $!");
962 $self->print_to_server(
963 "Failed to unlink '$_ARCHIVE_DIR_TAR': $!",
964 $Amanda::Script_App::ERROR);
968 if (-f $_DATA_DIR_TAR) {
969 debug("extracting data dir to $cur_dir/$_DATA_DIR_RESTORE");
970 my @cmd = ($self->{'args'}->{'gnutar-path'}, '--extract',
971 '--file', $_DATA_DIR_TAR,
972 '--directory', $_DATA_DIR_RESTORE);
973 debug("run: " . join ' ',@cmd);
974 $status = system(@cmd) >> 8;
975 (0 == $status) or die("Failed to extract data directory from base backup (exit status: $status)");
976 if (unlink($_DATA_DIR_TAR) == 0) {
977 debug("Failed to unlink '$_DATA_DIR_TAR': $!");
978 $self->print_to_server("Failed to unlink '$_DATA_DIR_TAR': $!",
979 $Amanda::Script_App::ERROR);
985 sub command_validate {
988 # set up to handle errors correctly
989 $self->{'die_cb'} = sub {
996 if (!defined($self->{'args'}->{'gnutar-path'}) ||
997 !-x $self->{'args'}->{'gnutar-path'}) {
998 return $self->default_validate();
1001 my(@cmd) = ($self->{'args'}->{'gnutar-path'}, "--ignore-zeros", "-tf", "-");
1002 debug("cmd:" . join(" ", @cmd));
1003 my $pid = open3('>&STDIN', '>&STDOUT', '>&STDERR', @cmd) ||
1004 $self->print_to_server_and_die("Unable to run @cmd",
1005 $Amanda::Application::ERROR);
1008 $self->print_to_server_and_die("$self->{gnutar} returned error",
1009 $Amanda::Application::ERROR);
1011 exit($self->{error_status});
1018 Usage: ampgsql <command> --config=<config> --host=<host> --disk=<disk> --device=<device> --level=<level> --index=<yes|no> --message=<text> --collection=<no> --record=<yes|no> --calcsize.
1028 'version' => \$opt_version,
1057 if (defined $opt_version) {
1058 print "ampgsql-" . $Amanda::Constants::VERSION , "\n";
1062 my $application = Amanda::Application::ampgsql->new($opts);
1064 $application->do($ARGV[0]);