summaryrefslogtreecommitdiffstats
path: root/pg_restorecluster
blob: b3335ca65d657e0fee178fc493859d0104b3fbe0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
#!/usr/bin/perl -wT

# pg_restorecluster: restore from a pg_backupcluster backup
#
# Copyright (C) 2021-2024 Christoph Berg <myon@debian.org>
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.

use strict;
use warnings;
use Cwd 'abs_path';
use Getopt::Long;
use PgCommon;

my ($version, $cluster);

# untaint environment
$ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
umask 022;

sub help () {
    print "Syntax: $0 [options] <version> <cluster> <backup>
Options:
  -d --datadir DIR  Data directory for restored cluster (default per createcluster.conf)
  -p --port PORT    Use port PORT for restored cluster (default is next free port)
  -s --start        Start cluster after restoring (default for restore from dump)
     --archive      Configure recovery from WAL archive
     --pitr TIMEST  Configure point-in-time recovery to TIMESTAMP from WAL archive
     --wal-archive DIR  Read WAL from archive DIR (default <backup>/../wal)
";
}

my $createclusterconf = "$PgCommon::common_confdir/createcluster.conf";
my ($datadir, $port, $start, $recovery_target_time, $archive_recovery, $wal_archive);

exit 1 unless GetOptions (
    'd|datadir=s' => \$datadir,
    'p|port=s' => \$port,
    's|start' => \$start,
    'archive' => \$archive_recovery,
    'pitr=s' => \$recovery_target_time,
    'recovery-target-time=s' => \$recovery_target_time,
    'wal-archive=s' => \$wal_archive,
    'createclusterconf=s' => \$createclusterconf,
);
if ($recovery_target_time) {
    ($recovery_target_time) = $recovery_target_time =~ /(.*)/; # untaint
}

# accept both "version cluster" and "version[-/]cluster"
if (@ARGV >= 2 and $ARGV[0] =~ m!^(\d+\.?\d)[-/]([^/]+)$!) {
    ($version, $cluster) = ($1, $2);
    shift @ARGV;
} elsif (@ARGV >= 3 and $ARGV[0] =~ /^(\d+\.?\d)$/) {
    $version = $1;
    ($cluster) = ($ARGV[1]) =~ m!^([^/]+)$!;
    shift @ARGV;
    shift @ARGV;
} else {
    help();
    exit 1;
}

error "cluster $version $cluster already exists" if cluster_exists $version, $cluster;

my %defaultconf = PgCommon::read_conf_file ($createclusterconf);

# functions to be run as root

sub create_cluster_directories($$$$) {
    my ($owneruid, $ownergid, $configdir, $datadir) = @_;
    my @postgres_user = getpwnam 'postgres';
    my ($pg_uid, $pg_gid) = (getpwnam 'postgres')[2, 3];

    for my $pgdir ("/etc/postgresql", "/etc/postgresql/$version", "/var/lib/postgresql", "/var/lib/postgresql/$version") {
        if (! -e $pgdir) {
            mkdir $pgdir or error "mkdir $pgdir: $!";
            chown $pg_uid, $pg_gid, $pgdir or error "chown $pgdir: $!";
        }
    }
    mkdir $configdir or error "mkdir $configdir: $!";
    chown $owneruid, $ownergid, $configdir or error "chown $configdir: $!";
    mkdir $datadir, 0700 or error "mkdir $datadir: $!";
    chown $owneruid, $ownergid, $datadir or error "chown $datadir: $!";
}

sub create_cluster($$$$$) {
    my ($backup, $owneruid, $ownergid, $configdir, $datadir) = @_;

    my @createclusteropts = ();
    if (-f "$backup/createcluster.opts") {
        open my $fh, "$backup/createcluster.opts" or error "$backup/createcluster.opts: $!";
        local $/; # slurp mode
        my ($opts) = <$fh> =~ /(.*)/; # untaint
        @createclusteropts = split /\s+/, $opts;
        close $fh;
    }

    system_or_error "pg_createcluster",
        "--datadir", $datadir,
        "--user", $owneruid, "--group", $ownergid,
        $version, $cluster,
        "--",
        @createclusteropts;
}

sub start_cluster() {
    print "Starting cluster $version $cluster ...\n";
    system_or_error "pg_ctlcluster", $version, $cluster, "start";
}

sub switch_to_cluster_owner($$) {
    my ($owneruid, $ownergid) = @_;
    change_ugid $owneruid, $ownergid;
}

# restore functions

sub unpack_tar($$$) {
    my ($backup, $tar, $dir) = @_;

    if (-f "$backup/$tar.gz") {
        $tar = "$tar.gz";
    } elsif (-f "$backup/$tar.bz2") {
        $tar = "$tar.bz2";
    } elsif (-f "$backup/$tar.xz") {
        $tar = "$tar.xz";
    } elsif (-f "$backup/$tar") {
        # do nothing
    } else {
        error "$backup/config.tar* is missing";
    }

    print "Restoring $backup/$tar to $dir ...\n";
    system_or_error "tar", "-C", $dir, "-xf", "$backup/$tar";
}

sub restore_config($$) {
    my ($backup, $configdir) = @_;
    unpack_tar($backup, "config.tar", $configdir);
}

sub update_config($$$) {
    my ($configdir, $datadir, $port) = @_;
    my %settings = (
        data_directory => $datadir,
        hba_file => "$configdir/pg_hba.conf",
        ident_file => "$configdir/pg_ident.conf",
        external_pid_file => "/var/run/postgresql/$version-$cluster.pid",
        port => $port,
    );
    $settings{cluster_name} = "$version/$cluster" if ($version >= 9.5);
    $settings{stats_temp_directory} = "/var/run/postgresql/$version-$cluster.pg_stat_tmp" if ($version < 15);
    my %config = PgCommon::read_conf_file("$configdir/postgresql.conf");
    for my $guc (sort keys %settings) {
        if (not exists $config{$guc} or $config{$guc} ne $settings{$guc}) {
            print "Setting $guc = $settings{$guc}\n";
            PgCommon::set_conffile_value("$configdir/postgresql.conf", $guc, $settings{$guc});
        }
    }
}

sub restore_basebackup($$) {
    my ($backup, $datadir) = @_;
    unpack_tar($backup, "base.tar", $datadir);
}

sub restore_wal($$) {
    my ($backup, $datadir) = @_;
    return if ($version < 10); # WAL contained in base.tar.gz in PG 9.x
    unpack_tar($backup, "pg_wal.tar", "$datadir/pg_wal");
}

sub archive_recovery_options($$$) {
    my ($backup, $datadir, $wal_archive) = @_;

    $wal_archive = abs_path($wal_archive) or error "$wal_archive: $!";
    -d $wal_archive or error "$wal_archive is not a directory";

    print "Setting archive recovery options";
    my $recovery_options = "restore_command = '/usr/share/postgresql-common/pg_getwal $wal_archive/%f %p'\n";
    if ($recovery_target_time) {
        $recovery_options .= "recovery_target_time = '$recovery_target_time'\n";
        $recovery_options .= "recovery_target_action = 'promote'\n";
    }

    if ($version >= 12) {
        my $autoconf = "$datadir/postgresql.auto.conf";
        open my $fh, ">>", $autoconf or error "$autoconf: $!";
        print $fh $recovery_options or error "$autoconf: $!";
        close $fh or error "$autoconf: $!";

        my $recoverysignal = "$datadir/recovery.signal";
        open my $fh2, ">", $recoverysignal or error "$recoverysignal: $!";
        close $fh2 or error "$recoverysignal: $!";

    } else {
        my $recoveryconf = "$datadir/recovery.conf";
        open my $fh, ">>", $recoveryconf or error "$recoveryconf: $!";
        print $fh $recovery_options or error "$recoveryconf: $!";
        close $fh or error "$recoveryconf: $!";
    }
}

sub reset_archive_recovery_options() {
    if ($version >= 12) {
        system_or_error "psql",
            "--cluster", "$version/$cluster",
            "-XAtqc", "ALTER SYSTEM RESET restore_command";
        system_or_error "psql",
            "--cluster", "$version/$cluster",
            "-XAtqc", "ALTER SYSTEM RESET recovery_target_time"
                if ($recovery_target_time);
        system_or_error "psql",
            "--cluster", "$version/$cluster",
            "-XAtqc", "ALTER SYSTEM RESET recovery_target_action"
                if ($recovery_target_time);
    }
}

sub restore_globals($$) {
    my ($backup, $owneruid) = @_;
    my $owner = (getpwuid $owneruid)[0] or error "UID $owneruid has no name";

    print "Restoring $backup/globals.sql ...\n";
    open my $globals, "$backup/globals.sql" or error "$backup/globals.sql: $!";
    open my $psql, "|-", "psql", "--cluster", "$version/$cluster", "-vON_ERROR_STOP=1", "-Xq" or error "psql: $!";
    while (my $line = <$globals>) {
        next if ($line eq "CREATE ROLE $owner;\n");
        print $psql $line or error "psql: $!";
    }
    close $globals;
    close $psql;
    error "psql failed" if ($?);
}

sub restore_dumps($) {
    my ($backup) = @_;

    for my $dump (sort glob "$backup/*.dump") {
        $dump =~ m!(.*/([^/]*).dump)$!;
        $dump = $1; # untaint
        my $db = $2;
        print "Restoring $dump to database $db ...\n";
        my @create = ($db eq "postgres" or $db eq "template1") ? () : ("--create");
        system_or_error "pg_restore", "--cluster", "$version/$cluster", @create, "-d", "postgres", $dump;
    }
}

sub wait_for_recovery() {
    my $sleep = 1;

    print "Waiting for end of recovery ...\n";
    while (1) {
        open my $psql, "-|", "psql", "--cluster", "$version/$cluster", "-XAtc", "SELECT pg_is_in_recovery()" or error "psql: $!";
        my $status = <$psql>;
        error "psql: $!" unless (defined $status);
        close $psql or error "psql: $!";
        last if ($status eq "f\n");
        sleep($sleep++);
    }
}

sub analyze() {
    system_or_error "vacuumdb",
        "--cluster", "$version/$cluster",
        "--analyze-only",
        ($version >= 9.4 ? "--analyze-in-stages" : ()),
        "--all";
}

sub lscluster() {
    system_or_error "pg_lsclusters", $version, $cluster;
}

# main

my ($backup) = $ARGV[0] =~ /(.*)/; # untaint
error "$backup is not a directory" unless (-d $backup);
$backup =~ s/\/$//; # strip trailing slash
my ($owneruid, $ownergid) = (stat $backup)[4, 5];
my $configdir = "/etc/postgresql/$version/$cluster";
$datadir //= replace_v_c($defaultconf{data_directory} // "/var/lib/postgresql/%v/%c", $version, $cluster);
($datadir) = $datadir =~ /(.*)/; # untaint
$wal_archive //= "$backup/../wal";
$port //= next_free_port();

if ($backup =~ /\.backup$/) {
    create_cluster_directories($owneruid, $ownergid, $configdir, $datadir);
    if (fork == 0) {
        switch_to_cluster_owner($owneruid, $ownergid);
        restore_config($backup, $configdir);
        update_config($configdir, $datadir, $port);
        restore_basebackup($backup, $datadir);
        restore_wal($backup, $datadir);
        archive_recovery_options($backup, $datadir, $wal_archive)
            if ($archive_recovery or $recovery_target_time);
        exit(0);
    }
    wait;
    exit(1) if ($?);
    if ($start) {
        print "\n";
        start_cluster();
        switch_to_cluster_owner($owneruid, $ownergid);
        wait_for_recovery();
        reset_archive_recovery_options() if ($archive_recovery or $recovery_target_time);
        analyze();
    }
    print "\n";
    lscluster();

} elsif ($backup =~ /\.dump$/) {
    create_cluster($backup, $owneruid, $ownergid, $configdir, $datadir);
    print "\n";
    if (fork == 0) {
        switch_to_cluster_owner($owneruid, $ownergid);
        restore_config($backup, $configdir);
        update_config($configdir, $datadir, $port);
        exit(0);
    }
    wait;
    exit(1) if ($?);
    start_cluster();
    switch_to_cluster_owner($owneruid, $ownergid);
    restore_globals($backup, $owneruid);
    restore_dumps($backup);
    analyze();
    print "\n";
    lscluster();

} else {
    error "$backup must end in either .backup or .dump";
}

__END__

=head1 NAME

pg_restorecluster - Restore from a pg_backupcluster backup

=head1 SYNOPSIS

B<pg_restorecluster> [I<options>] I<version> I<cluster> I<backup>

=head1 DESCRIPTION

B<pg_restorecluster> restores a PostgreSQL cluster from a backup created by
B<pg_backupcluster>. The cluster will be newly created in the system using the
name provided on the command line; this allows renaming a cluster on restore.
The restored cluster configuration will be updated to reflect the new name and
location.

The I<backup> name passed must end in either B<.basebackup> or B<.dump>;
usually this will be the full path to a backup directory in
C</var/backups/postgresql/version-cluster/> as reported by
B<pg_backupcluster ... list>.

Basebackups are restored as-is. For dumps, B<pg_createcluster> is used to
create a new cluster, and schema and data are restored via B<pg_restore>.

=head1 OPTIONS

=over 4

=item B<-d --datadir> I<DIR>

Use I<DIR> as data directory for the restored cluster (default per
createcluster.conf, by default /var/lib/postgresql/I<version>/I<cluster>).

=item B<-p --port> I<N>

Use port I<N> for restored cluster (default is next free port).

=item B<-s --start>

Start cluster after restoring (default for restore from dump; off for
basebackup restores).

After the cluster has been started, B<ANALYZE> is run on all databases.

=item B<--archive>

Configure cluster for recovery from WAL archive. This sets B<restore_command>
to retrieve WAL files from I<backup>B</../wal>.

=item B<--pitr> I<TIMESTAMP>

=item B<--recovery-target-time> I<TIMESTAMP>

Additionally to setting B<restore_command>, set B<recovery_target_time> to
I<TIMESTAMP> for point-in-time recovery. Also sets
B<recovery_target_action='promote'>.

=item B<--wal-archive> I<DIR>

For archive recovery, read WAL from archive I<DIR> (default is
I<backup>B</../wal>).

=back

=head1 FILES

=over 4

=item /var/backups

Default root directory for cluster backup directories.

=back

See L<pg_backupcluster(1)> for a description of files.

=head1 SEE ALSO

L<pg_backupcluster(1)>, L<pg_restore(1)>, L<vacuumdb(1)>.

=head1 AUTHOR

Christoph Berg L<E<lt>myon@debian.orgE<gt>>