0150af1bd18331e82b4043ad2ddee9b4f6082623
[debian/amanda] / application-src / ampgsql.pl
1 #!@PERL@
2 # Copyright (c) 2009, 2010 Zmanda, Inc.  All Rights Reserved.
3 #
4 # This program is free software; you can redistribute it and/or modify it
5 # under the terms of the GNU General Public License version 2 as published
6 # by the Free Software Foundation.
7 #
8 # This program is distributed in the hope that it will be useful, but
9 # WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
10 # or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
11 # for more details.
12 #
13 # You should have received a copy of the GNU General Public License along
14 # with this program; if not, write to the Free Software Foundation, Inc.,
15 # 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
16 #
17 # Contact information: Zmanda Inc., 465 S. Mathilda Ave., Suite 300
18 # Sunnyvale, CA 94086, USA, or: http://www.zmanda.com
19
20 use lib '@amperldir@';
21 use strict;
22 use warnings;
23 use Getopt::Long;
24
25 package Amanda::Application::ampgsql;
26 use base qw(Amanda::Application);
27 use Carp;
28 use File::Copy;
29 use File::Path;
30 use IO::Dir;
31 use IO::File;
32 use IPC::Open3;
33 use POSIX;
34 use POSIX qw( ceil );
35 use Sys::Hostname;
36 use Symbol;
37 use Amanda::Constants;
38 use Amanda::Config qw( :init :getconf  config_dir_relative string_to_boolean );
39 use Amanda::Debug qw( :logging );
40 use Amanda::Paths;
41 use Amanda::Util qw( :constants :encoding quote_string );
42 use Amanda::MainLoop qw( :GIOCondition );
43
44 my $_DATA_DIR_TAR = "data_dir.tar";
45 my $_ARCHIVE_DIR_TAR = "archive_dir.tar";
46 my $_WAL_FILE_PAT = qr/\w{24}/;
47
48 my $_DATA_DIR_RESTORE = "data";
49 my $_ARCHIVE_DIR_RESTORE = "archive";
50
51 sub new {
52     my $class = shift @_;
53     my $args = shift @_;
54     my $self = $class->SUPER::new($args->{'config'});
55     $self->{'args'} = $args;
56     $self->{'label-prefix'} = 'amanda';
57     $self->{'runtar'}  = "$Amanda::Paths::amlibexecdir/runtar";
58
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;
65
66     if (!defined $self->{'args'}->{'disk'}) {
67         $self->{'args'}->{'disk'} = $self->{'args'}->{'device'};
68     }
69     if (!defined $self->{'args'}->{'device'}) {
70         $self->{'args'}->{'device'} = $self->{'args'}->{'disk'};
71     }
72     # default properties
73     $self->{'props'} = {
74         'pg-db' => 'template1',
75         'pg-cleanupwal' => 'yes',
76         'pg-max-wal-wait' => 60,
77     };
78
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
81                         pg-max-wal-wait);
82
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];
91         }
92     }
93
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];
102             }
103         }
104     }
105
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};
114     }
115
116     unless ($self->{'props'}->{'psql-path'}) {
117         foreach my $pre (split(/:/, $ENV{PATH})) {
118             my $psql = "$pre/psql";
119             if (-x $psql) {
120                 $self->{'props'}{'psql-path'} = $psql;
121                 last;
122             }
123         }
124     }
125
126     foreach my $aname (keys %{$self->{'args'}}) {
127         if (defined($self->{'args'}->{$aname})) {
128             debug("app property: $aname $self->{'args'}->{$aname}");
129         } else {
130             debug("app property: $aname (undef)");
131         }
132     }
133
134     foreach my $pname (keys %{$self->{'props'}}) {
135         if (defined($self->{'props'}->{$pname})) {
136             debug("client property: $pname $self->{'props'}->{$pname}");
137         } else {
138             debug("client property: $pname (undef)");
139         }
140     }
141
142     if (!exists $self->{'props'}->{'pg-datadir'}) {
143         $self->{'props'}->{'pg-datadir'} =  $self->{'args'}->{'device'};
144     }
145
146     return $self;
147 }
148
149 sub command_support {
150    my $self = shift;
151
152    print <<EOF;
153 CONFIG YES
154 HOST YES
155 DISK YES
156 MAX-LEVEL 9
157 INDEX-LINE YES
158 INDEX-XML NO
159 MESSAGE-LINE YES
160 MESSAGE-XML NO
161 RECORD YES
162 COLLECTION NO
163 CLIENT-ESTIMATE YES
164 MULTI-ESTIMATE NO
165 CALCSIZE NO
166 EOF
167 }
168
169 sub _check {
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";
173     debug($msg);
174     print "$msg\n";
175     $ret;
176 }
177
178 sub _check_parent_dirs {
179     my ($dir) = @_;
180     my $ok = 1;
181     my $is_abs = substr($dir, 0, 1) eq "/";
182     _check("$dir is an absolute path?", "Yes", "No. It should start with '/'",
183        sub {$is_abs});
184
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)? '/' : '');
190         $ok &&=
191             _check("$partial_path is executable?", "Yes", "No",
192                sub {-x $_[0]}, $partial_path);
193         $ok &&=
194             _check("$partial_path is a directory?", "Yes", "No",
195                sub {-d $_[0]}, $partial_path);
196     }
197     $ok;
198 }
199
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];
206     return -r $passfile;
207 }
208
209 sub _run_psql_command {
210     my ($self, $cmd) = @_;
211
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'};
218
219     my @cmd = ($self->{'props'}->{'psql-path'});
220     push @cmd, "-X";
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'});
224
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));
228
229     my ($wtr, $rdr);
230     my $err = Symbol::gensym;
231     my $pid = open3($wtr, $rdr, $err, @cmd);
232     close($wtr);
233
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 {
240         my $line = <$rdr>;
241         if (!defined $line) {
242             $file_to_close--;
243             $psql_stdout_src->remove();
244             Amanda::MainLoop::quit() if $file_to_close == 0;
245             return;
246         }
247         chomp $line;
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;
256                 return;
257             }
258         }
259         if ($line =~ /NOTICE: pg_stop_backup complete, all required WAL segments have been archived/) {
260         } else {
261             $self->print_to_server("psql stdout: $line",
262                                    $Amanda::Script_App::GOOD);
263         }
264     });
265     $psql_stderr_src->set_callback(sub {
266         my $line = <$err>;
267         if (!defined $line) {
268             $file_to_close--;
269             $psql_stderr_src->remove();
270             Amanda::MainLoop::quit() if $file_to_close == 0;
271             return;
272         }
273         chomp $line;
274         debug("psql stderr: $line");
275         if ($line =~ /NOTICE: pg_stop_backup complete, all required WAL segments have been archived/) {
276         } else {
277             $self->print_to_server("psql stderr: $line",
278                                    $Amanda::Script_App::GOOD);
279         }
280     });
281
282     close($wtr);
283     Amanda::MainLoop::run();
284     close($rdr);
285     close($err);
286
287     waitpid $pid, 0;
288     my $status = $?;
289
290     $ENV{'PGPASSWORD'} = $orig_pgpassword || '';
291     $ENV{'PGPASSFILE'} = $orig_pgpassfile || '';
292
293     return 0 == ($status >> 8)
294 }
295
296 sub command_selfcheck {
297     my $self = shift;
298
299    # set up to handle errors correctly
300    $self->{'die_cb'} = sub {
301        my ($msg) = @_;
302        debug("$msg");
303        print "$msg\n";
304        exit(1);
305    };
306
307     $self->print_to_server("disk " . quote_string($self->{args}->{disk}));
308
309     $self->print_to_server("ampgsql version " . $Amanda::Constants::VERSION,
310                            $Amanda::Script_App::GOOD);
311
312     for my $k (keys %{$self->{'args'}}) {
313         print "OK application property: $k = $self->{'args'}->{$k}\n";
314     }
315
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'});
323
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);
331
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'});
336
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'});
342     } else {
343         $self->{'props'}->{'pg-datadir'} = $self->{'args'}->{'device'};
344     }
345
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
349
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'});
355
356     if ($self->{'args'}->{'device'}) {
357         my $try_connect = 1;
358
359         for my $k (keys %{$self->{'props'}}) {
360             print "OK client property: $k = $self->{'props'}->{$k}\n";
361         }
362
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'});
375         }
376
377         $try_connect &&=
378             _check("Are both PG-PASSFILE and PG-PASSWORD set?",
379                    "No (okay)",
380                    "Yes. Please set only one or the other",
381                    sub {!($self->{'props'}->{'pg-passfile'} and
382                           $self->{'props'}->{'pg-password'})});
383
384         if ($self->{'props'}->{'pg-passfile'}) {
385             $try_connect &&=
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'});
389             $try_connect &&=
390                 _check_parent_dirs($self->{'props'}->{'pg-passfile'});
391         }
392
393         if (_check("PSQL-PATH property", "is set", "is NOT set and psql is not in \$PATH",
394                sub { $_[0] }, $self->{'props'}->{'psql-path'})) {
395             $try_connect &&=
396                 _check("PSQL-PATH $self->{'props'}->{'psql-path'}",
397                        "is executable", "is NOT executable",
398                        sub {-x $_[0]}, $self->{'props'}->{'psql-path'});
399             $try_connect &&=
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'});
403             $try_connect &&=
404                 _check_parent_dirs($self->{'props'}->{'psql-path'});
405         } else {
406             $try_connect = 0;
407         }
408
409         if ($try_connect) {
410             my @pv = `$self->{'props'}->{'psql-path'} --version`;
411             if ($? >> 8 == 0) {
412                 $pv[0] =~ /^[^0-9]*([0-9.]*)[^0-9]*$/;
413                 my $pv = $1;
414                 $self->print_to_server("ampgsql psql-version $pv",
415                                        $Amanda::Script_App::GOOD);
416             } else {
417                 $self->print_to_server(
418                 "[Can't get " . $self->{'props'}->{'psql-path'} . " version]\n",
419                 $Amanda::Script_App::ERROR);
420             }
421         }
422
423         if ($try_connect) {
424             $try_connect &&=
425                 _check("Connecting to database server", "succeeded", "failed",
426                    \&_run_psql_command, $self, '');
427         }
428         
429         if ($try_connect) {
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()")) {
436
437                 _check("Get info from .backup file", "succeeded", "failed",
438                        sub {my ($start, $end) = _get_backup_info($self, $label); $start and $end});
439             }
440         }
441
442         {
443             my @gv = `$self->{'args'}->{'gnutar-path'} --version`;
444             if ($? >> 8 == 0) {
445                 $gv[0] =~ /^[^0-9]*([0-9.]*)[^0-9]*$/;
446                 my $gv = $1;
447                 $self->print_to_server("ampgsql gtar-version $gv",
448                                        $Amanda::Script_App::GOOD);
449             } else {
450                 $self->print_to_server(
451                 "[Can't get " . $self->{'props'}->{'gnutar-path'} . " version]\n",
452                 $Amanda::Script_App::ERROR);
453             }
454         }
455     }
456 }
457
458 sub _state_filename {
459     my ($self, $level) = @_;
460
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");
464     return $statefile;
465 }
466
467 sub _write_state_file {
468     my ($self, $end_wal) = @_;
469
470     my $h = new IO::File(_state_filename($self, $self->{'args'}->{'level'}), "w");
471     $h or return undef;
472
473     debug("writing state file");
474     $h->print("VERSION: 0\n");
475     $h->print("LAST WAL FILE: $end_wal\n");
476     $h->close();
477     1;
478 }
479
480 sub _get_prev_state {
481     my $self = shift @_;
482
483     my $end_wal;
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");
488         next unless $h;
489         while (my $l = <$h>) {
490             chomp $l;
491             debug("  $l");
492             if ($l =~ /^VERSION: (\d+)/) {
493                 unless (0 == $1) {
494                     $end_wal = undef;
495                     last;
496                 }
497             } elsif ($l =~ /^LAST WAL FILE: ($_WAL_FILE_PAT)/) {
498                 $end_wal = $1;
499             }
500         }
501         $h->close();
502         last if $end_wal;
503     }
504     $end_wal;
505 }
506
507 sub _make_dummy_dir_base {
508     my ($self) = @_;
509
510    my $dummydir = "$self->{'args'}->{'tmpdir'}/ampgsql-dummy-$$";
511    mkpath("$dummydir/$_ARCHIVE_DIR_RESTORE");
512
513    return $dummydir;
514 }
515
516 sub _make_dummy_dir {
517     my ($self) = @_;
518
519    my $dummydir = "$self->{'args'}->{'tmpdir'}/ampgsql-dummy-$$";
520    mkpath($dummydir);
521    open(my $fh, ">$dummydir/empty-incremental");
522    close($fh);
523
524    return $dummydir;
525 }
526
527 sub _run_tar_totals {
528     my ($self, @other_args) = @_;
529
530     my @cmd;
531     @cmd = ($self->{'runtar'}, $self->{'args'}->{'config'},
532         $Amanda::Constants::GNUTAR, '--create', '--totals', @other_args);
533     debug("running: " . join(" ", @cmd));
534
535     local (*TAR_IN, *TAR_OUT, *TAR_ERR);
536     open TAR_OUT, ">&", $self->{'out_h'};
537     my $pid;
538     eval { $pid = open3(\*TAR_IN, ">&TAR_OUT", \*TAR_ERR, @cmd); 1;} or
539         $self->{'die_cb'}->("failed to run tar. error was $@");
540     close(TAR_IN);
541
542     # read stderr
543     my $size;
544     while (my $l = <TAR_ERR>) {
545         if ($l =~ /^Total bytes written: (\d+)/) {
546             $size = $1;
547         } else {
548             chomp $l;
549             $self->print_to_server($l, $Amanda::Script_App::ERROR);
550             debug("TAR_ERR: $l");
551         }
552     }
553     waitpid($pid, 0);
554     my $status = POSIX::WEXITSTATUS($?);
555
556     close(TAR_ERR);
557     debug("size of generated tar file: " . (defined($size)? $size : "undef"));
558     if ($status == 1) {
559         debug("ignored non-fatal tar exit status of 1");
560     } elsif ($status) {
561         $self->{'die_cb'}->("Tar failed (exit status $status)");
562     }
563     $size;
564 }
565
566 sub command_estimate {
567    my $self = shift;
568
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");
573
574    $self->{'done_cb'} = sub {
575        my $size = shift @_;
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");
580    };
581    $self->{'die_cb'} = sub {
582        my $msg = shift @_;
583        debug("$msg");
584        $self->{'done_cb'}->(-1);
585        die($msg);
586    };
587    $self->{'state_cb'} = sub {
588        # do nothing
589    };
590    $self->{'unlink_cb'} = sub {
591        # do nothing
592    };
593
594    if ($self->{'args'}->{'level'} > 0) {
595        _incr_backup($self);
596    } else {
597        _base_backup($self);
598    }
599 }
600
601 sub _get_backup_info {
602     my ($self, $label) = @_;
603
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$/) {
611                my $blabel;
612                # use runtar to read a protected file, then grep the resulting tarfile (yes,
613                # this works!)
614                local *TAROUT;
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>) {
621                    chomp($l);
622                    if ($l =~ /^START WAL LOCATION:.*?\(file ($_WAL_FILE_PAT)\)$/) {
623                        $start = $1;
624                    } elsif($l =~ /^STOP WAL LOCATION:.*?\(file ($_WAL_FILE_PAT)\)$/) {
625                        $end = $1;
626                    } elsif ($l =~ /^LABEL: (.*)$/) {
627                        $lab = $1;
628                    }
629                }
630                close TAROUT;
631                if ($lab and $lab eq $label) {
632                    $start_wal = $start;
633                    $end_wal = $end;
634                    $bfile = $fname;
635                    last;
636                } else {
637                    debug("logfile had non-matching label");
638                }
639            }
640        }
641        $adir->close();
642        if ($start_wal and $end_wal) {
643            debug("$bfile named WALs $start_wal .. $end_wal");
644
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);
651            }
652            last;
653        }
654        sleep(1);
655    }
656
657    ($start_wal, $end_wal);
658 }
659
660 # return the postgres version as an integer
661 sub _get_pg_version {
662     my $self = shift;
663
664     local *VERSOUT;
665
666     my @cmd = ($self->{'props'}->{'psql-path'});
667     push @cmd, "-X";
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>;
672     waitpid($pid, 0);
673     $self->{'die_cb'}->("could not run psql to determine version") if (($? >> 8) != 0);
674
675     my ($maj, $min, $pat) = ($lines[0] =~ / ([0-9]+)\.([0-9]+)\.([0-9]+)$/);
676     return $maj * 10000 + $min * 100 + $pat;
677 }
678
679 # create a large table and immediately drop it; this can help to push a WAL file out
680 sub _write_garbage_to_db {
681     my $self = shift;
682
683     debug("writing garbage to database to force a WAL archive");
684
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;
690 EOF
691         $self->{'die_cb'}->("Failed to create or drop table _ampgsql_garbage");
692 }
693
694 # wait up to pg-max-wal-wait seconds for a WAL file to appear
695 sub _wait_for_wal {
696     my ($self, $wal) = @_;
697     my $pg_version = $self->_get_pg_version();
698
699     my $archive_dir = $self->{'props'}->{'pg-archivedir'};
700     my $maxwait = 0+$self->{'props'}->{'pg-max-wal-wait'};
701
702     if ($maxwait) {
703         debug("waiting $maxwait s for WAL $wal to be archived..");
704     } else {
705         debug("waiting forever for WAL $wal to be archived..");
706     }
707
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";
712
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();
717         } else {
718             sleep(1);
719         }
720     }
721
722     $self->{'die_cb'}->("WAL file $wal was not archived in $maxwait seconds");
723 }
724
725 sub _base_backup {
726    my ($self) = @_;
727
728    debug("running _base_backup");
729
730    my $label = "$self->{'label-prefix'}-" . time();
731
732    -d $self->{'props'}->{'pg-archivedir'} or
733         die("WAL file archive directory does not exist (or is not a directory)");
734
735    _run_psql_command($self, "SELECT pg_start_backup('$label')") or
736        $self->{'die_cb'}->("Failed to call pg_start_backup");
737
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 {
743        my $msg = shift @_;
744        unless(_run_psql_command($self, "SELECT pg_stop_backup()")) {
745            $msg .= " and failed to call pg_stop_backup";
746        }
747        $old_die_cb->($msg);
748    };
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",
754        ".");
755    $self->{'die_cb'} = $old_die_cb;
756
757    unless (_run_psql_command($self, "SELECT pg_stop_backup()")) {
758        $self->{'die_cb'}->("Failed to call pg_stop_backup");
759    }
760
761    # determine WAL files and append and create their tar file
762    my ($start_wal, $end_wal) = _get_backup_info($self, $label);
763
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'}");
767
768    $self->_wait_for_wal($end_wal);
769
770    # now grab all of the WAL files, *inclusive* of $start_wal
771    my @wal_files;
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");
780            }
781        }
782    }
783    $adir->close();
784
785    if (@wal_files) {
786        $size += _run_tar_totals($self, '--file', "-",
787            '--directory', $self->{'props'}->{'pg-archivedir'},
788            '--transform', "s,^,$_ARCHIVE_DIR_RESTORE/,S",
789            @wal_files);
790    } else {
791        my $dummydir = $self->_make_dummy_dir_base();
792        $self->{'done_cb'}->(_run_tar_totals($self, '--file', '-',
793            '--directory', $dummydir, "$_ARCHIVE_DIR_RESTORE"));
794        rmtree($dummydir);
795    }
796
797    $self->{'state_cb'}->($self, $end_wal);
798
799    $self->{'done_cb'}->($size);
800 }
801
802 sub _incr_backup {
803    my ($self) = @_;
804
805    debug("running _incr_backup");
806
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'});
811       }
812    }
813
814    my $end_wal = _get_prev_state($self);
815    if ($end_wal) {
816        debug("previously ended at: $end_wal");
817    } else {
818        debug("no previous state found!");
819        return _base_backup(@_);
820    }
821
822    my $adir = new IO::Dir($self->{'props'}->{'pg-archivedir'});
823    $adir or $self->{'die_cb'}->("Could not open archive WAL directory");
824    my $max_wal = "";
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");
831        }
832    }
833
834    $self->{'state_cb'}->($self, $max_wal ? $max_wal : $end_wal);
835
836    if (@wal_files) {
837        $self->{'done_cb'}->(_run_tar_totals($self, '--file', '-',
838            '--directory', $self->{'props'}->{'pg-archivedir'}, @wal_files));
839    } else {
840        my $dummydir = $self->_make_dummy_dir();
841        $self->{'done_cb'}->(_run_tar_totals($self, '--file', '-',
842            '--directory', $dummydir, "empty-incremental"));
843        rmtree($dummydir);
844    }
845 }
846
847 sub command_backup {
848    my $self = shift;
849
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");
856
857    $self->{'done_cb'} = sub {
858        my $size = shift @_;
859        debug("done. size $size");
860        $size = ceil($size/1024);
861        debug("sending size $size");
862        $msg_fd->print("sendbackup: size $size\n");
863
864        $self->{'index_h'}->print("/PostgreSQL-Database-$self->{'args'}->{'level'}\n");
865
866        $msg_fd->print("sendbackup: end\n");
867    };
868    $self->{'die_cb'} = sub {
869        my $msg = shift @_;
870        debug("$msg");
871        $msg_fd->print("! $msg\n");
872        $self->{'done_cb'}->(0);
873        exit(1);
874    };
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");
878    };
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);
891            }
892        };
893    } else {
894        $self->{'unlink_cb'} = sub {
895            # do nothing
896        };
897    }
898
899    if ($self->{'args'}->{'level'} > 0) {
900        _incr_backup($self, \*STDOUT);
901    } else {
902        _base_backup($self, \*STDOUT);
903    }
904 }
905
906 sub command_restore {
907     my $self = shift;
908
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);
914         }
915         if (!-w $self->{'args'}->{directory}) {
916             $self->print_to_server_and_die("Directory $self->{directory}: $!",
917                                            $Amanda::Script_App::ERROR);
918         }
919         chdir($self->{'args'}->{directory});
920     }
921     my $cur_dir = POSIX::getcwd();
922
923     if (!-d $_ARCHIVE_DIR_RESTORE) {
924         mkdir($_ARCHIVE_DIR_RESTORE) or die("could not create archive WAL directory: $!");
925     }
926     my $status;
927     if ($self->{'args'}->{'level'} > 0) {
928         debug("extracting incremental backup to $cur_dir/$_ARCHIVE_DIR_RESTORE");
929         $status = system($self->{'args'}->{'gnutar-path'},
930                 '--extract',
931                 '--file', '-',
932                 '--ignore-zeros',
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)");
936     } else {
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: $!");
941         }
942         my @cmd = ($self->{'args'}->{'gnutar-path'}, '--extract',
943                 '--file', '-',
944                 '--ignore-zero',
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)");
950
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);
965             }
966         }
967
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);
980             }
981         }
982     }
983 }
984
985 sub command_validate {
986    my $self = shift;
987
988    # set up to handle errors correctly
989    $self->{'die_cb'} = sub {
990        my ($msg) = @_;
991        debug("$msg");
992        print "$msg\n";
993        exit(1);
994    };
995
996    if (!defined($self->{'args'}->{'gnutar-path'}) ||
997        !-x $self->{'args'}->{'gnutar-path'}) {
998       return $self->default_validate();
999    }
1000
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);
1006    waitpid $pid, 0;
1007    if ($? != 0){
1008        $self->print_to_server_and_die("$self->{gnutar} returned error",
1009                                       $Amanda::Application::ERROR);
1010    }
1011    exit($self->{error_status});
1012 }
1013
1014 package main;
1015
1016 sub usage {
1017     print <<EOF;
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.
1019 EOF
1020     exit(1);
1021 }
1022
1023 my $opts = {};
1024 my $opt_version;
1025
1026 GetOptions(
1027     $opts,
1028     'version' => \$opt_version,
1029     'config=s',
1030     'host=s',
1031     'disk=s',
1032     'device=s',
1033     'level=s',
1034     'index=s',
1035     'message=s',
1036     'collection=s',
1037     'record',
1038     'calcsize',
1039     'exclude-list=s@',
1040     'include-list=s@',
1041     'directory=s',
1042     # ampgsql-specific
1043     'statedir=s',
1044     'tmpdir=s',
1045     'gnutar-path=s',
1046     'cleanupwal=s',
1047     'archivedir=s',
1048     'db=s',
1049     'host=s',
1050     'max-wal-wait=s',
1051     'passfile=s',
1052     'port=s',
1053     'user=s',
1054     'psql-path=s'
1055 ) or usage();
1056
1057 if (defined $opt_version) {
1058     print "ampgsql-" . $Amanda::Constants::VERSION , "\n";
1059     exit(0);
1060 }
1061
1062 my $application = Amanda::Application::ampgsql->new($opts);
1063
1064 $application->do($ARGV[0]);