Debian Codegraph @

pg_backupcluster

raw
1 #!/usr/bin/perl -wT
2
3 # simple pg_basebackup front-end
4 #
5 # Copyright (C) 2021-2025 Christoph Berg <[email protected]>
6 #
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 2 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16
17 use strict;
18 use warnings;
19 use Fcntl qw(:flock);
20 use Getopt::Long;
21 use JSON;
22 use PgCommon;
23 use POSIX qw(strftime);
24
25 my ($version, $cluster);
26
27 # untaint environment
28 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
29 delete @ENV{'IFS', 'CDPATH', 'ENV', 'BASH_ENV'};
30 chdir '/';
31 umask 027;
32
33 sub help ($) {
34 print "Syntax: $0 [options] <version> <cluster> <action>
35 Actions:
36 createdirectory Create /var/backups/postgresql/version-cluster
37 basebackup Backup using pg_basebackup
38 dump Backup using pg_dump
39 expiredumps <N> Remove all but last N dumps
40 expirebasebackups <N> Remove all but last N basebackups
41 deletebroken Remove broken backups
42
43 receivewal Launch pg_receivewal
44 compresswal Compress WAL files in archive
45 archivecleanup Remove obsolete WAL files from archive
46
47 list Show dumps, basebackups, and WAL
48 Options:
49 -c --checkpoint <spread|fast> Passed to pg_basebackup
50 -k --keep-on-error Keep broken backup directory on error
51 -v --verbose Verbose output
52 -Z --compress=level Passed to pg_dump, pg_basebackup and pg_receivewal
53 ";
54 exit (shift);
55 }
56
57 my $checkpoint = 'spread';
58 my $keep_on_error;
59 my $verbose;
60 my $compress;
61
62 unless (GetOptions (
63 'c|checkpoint=s' => sub { $checkpoint = $_[1] =~ /^f/ ? "fast" : "spread" },
64 'k|keep-on-error' => \$keep_on_error,
65 'v|verbose' => \$verbose,
66 'Z|compress=s' => sub { ($compress) = $_[1] =~ /([\w\d:-]+)/; }, # untaint
67 'help' => sub { help(0); },
68 )) {
69 help(1);
70 }
71
72 $verbose = 1 if (-t 1); # verbose output when running on terminal
73
74 # accept both "version cluster action" and "version[-/]cluster action"
75 if (@ARGV >= 2 and $ARGV[0] =~ m!^(\d+\.?\d)[-/]([^/]+)$!) {
76 ($version, $cluster) = ($1, $2);
77 shift @ARGV;
78 } elsif (@ARGV >= 3 and $ARGV[0] =~ /^(\d+\.?\d)$/) {
79 $version = $1;
80 ($cluster) = ($ARGV[1]) =~ m!^([^/]+)$!;
81 shift @ARGV;
82 shift @ARGV;
83 } else {
84 help(1);
85 }
86 my $action = $ARGV[0];
87
88 error "specified cluster $version $cluster does not exist" unless $version && $cluster && cluster_exists $version, $cluster;
89
90 my %info = cluster_info($version, $cluster);
91 validate_cluster_owner \%info;
92
93 my $rootdir = "/var/backups/postgresql";
94 my $clusterdir = "$rootdir/$version-$cluster";
95 my $waldir = "$clusterdir/wal";
96 my $backupdirfh; # global so it doesn't get deallocated
97
98 # functions to be run as root
99
100 sub create_directory() {
101 if (! -d $rootdir) {
102 my ($pg_uid, $pg_gid) = (getpwnam 'postgres')[2,3];
103 ($pg_uid and $pg_gid) or error "getpwnam postgres: $!";
104 mkdir $rootdir, 0755 or error "mkdir $rootdir: $!";
105 chown $pg_uid, $pg_gid, $rootdir or error "chown $rootdir: $!";
106 }
107 if (! -d $clusterdir) {
108 mkdir($clusterdir, 0750) or error "mkdir $clusterdir: $!";
109 chown $info{owneruid}, $info{ownergid}, $clusterdir or error "chown $clusterdir: $!";
110 }
111 }
112
113 sub switch_to_cluster_owner() {
114 change_ugid $info{owneruid}, $info{ownergid};
115 }
116
117 # helper functions
118
119 sub can_lock_dir($) {
120 my ($dir) = @_;
121
122 open my $dirfh, $dir or error "could not open $dir";
123 my $ret = flock $dirfh, LOCK_SH | LOCK_NB;
124 flock $dirfh, LOCK_UN;
125 close $dirfh;
126
127 return $ret;
128 }
129
130 # backup functions
131
132 sub get_backupdir($$) {
133 my ($starttime, $suffix) = @_;
134
135 my $timestamp = strftime("%FT%H%M%SZ", gmtime($starttime));
136 my $backupdir = "$clusterdir/$timestamp.$suffix";
137 error "$backupdir already exists" if (-d $backupdir);
138 mkdir($backupdir, 0700) or error "mkdir $backupdir: $!";
139
140 # lock the directory to signal backup is running
141 open $backupdirfh, $backupdir;
142 flock $backupdirfh, LOCK_EX or error "flock $backupdir: $!";
143
144 print "Creating $suffix in $backupdir\n" if ($verbose);
145 return $backupdir;
146 }
147
148 sub remove_backup_on_error($) {
149 my $backupdir = shift;
150 if ($keep_on_error) {
151 print "Not removing $backupdir (--keep-on-error)\n";
152 } else {
153 print "Removing $backupdir ...\n" if ($verbose);
154 system_or_error "rm", "-rf", $backupdir;
155 }
156 }
157
158 sub create_basebackup($) {
159 my $backupdir = shift;
160
161 my @cmd = ("pg_basebackup",
162 "--cluster", "$version/$cluster",
163 "--verbose",
164 "--checkpoint=$checkpoint",
165 "--format=tar");
166 if ($compress) {
167 push @cmd, "--compress=$compress";
168 } else {
169 push @cmd, "--gzip";
170 }
171 push @cmd, "--xlog" if ($version < 10);
172 push @cmd, "--progress" if (-t 2);
173 push @cmd, "-D", $backupdir;
174 system_or_error @cmd;
175 }
176
177 sub create_dumpall($) {
178 my $backupdir = shift;
179
180 my $icu = "";
181 if ($version >= 15) {
182 $icu = "CASE datlocprovider::text
183 WHEN 'c' THEN '--locale-provider libc'
184 WHEN 'b' THEN '--locale-provider builtin'
185 WHEN 'i' THEN '--locale-provider icu'";
186 if ($version < 17) {
187 $icu .= " || ' --icu-locale ' || daticulocale";
188 }
189 if ($version >= 16) {
190 $icu .= " || ' --icu-rules ' || daticurules";
191 }
192 $icu .= "\nEND,";
193 }
194 my $clusterquery = "SELECT
195 '--encoding', pg_catalog.pg_encoding_to_char(encoding),
196 '--lc-collate', datcollate,
197 '--lc-ctype', datctype,
198 $icu
199 CASE WHEN current_setting('data_checksums')::boolean THEN '--data-checksums'
200 WHEN current_setting('server_version_num')::int >= 180000 THEN '--no-data-checksums'
201 END
202 FROM pg_database WHERE datname = 'template0'";
203 system_or_error "psql",
204 "--cluster", "$version/$cluster",
205 "-XAtF", " ", "-c", $clusterquery,
206 "-o", "$backupdir/createcluster.opts";
207
208 system_or_error "pg_dumpall",
209 "--cluster", "$version/$cluster",
210 "--globals-only",
211 "--file", "$backupdir/globals.sql";
212
213 my $dblist = 'SELECT datname FROM pg_database WHERE datallowconn ORDER BY datname';
214 my $databases = `psql --cluster '$version/$cluster' -XAtc '$dblist'`;
215 for my $datname ($databases =~ /(.+)/g) {
216 print "Dumping $datname to $backupdir/$datname.dump ...\n" if ($verbose);
217 system_or_error "pg_dump",
218 "--cluster", "$version/$cluster",
219 "--format=custom",
220 "--file", "$backupdir/$datname.dump",
221 ($compress ? "--compress=$compress" : ()),
222 $datname;
223 }
224 }
225
226 sub create_configbackup($) {
227 my $backupdir = shift;
228 $info{configdir} or error "cluster has no configdir";
229 system_or_error "tar",
230 "-C", $info{configdir},
231 "-cz", "-f", "$backupdir/config.tar.gz",
232 ".";
233 }
234
235 sub create_status($$$$) {
236 my ($type, $starttime, $backupdir, $status) = @_;
237 my $statusfile = "$backupdir/status";
238 my $endtime = time;
239 my $statusjson = {
240 cluster => $cluster,
241 duration => $endtime - $starttime,
242 end => strftime("%FT%H%M%SZ", gmtime($endtime)),
243 start => strftime("%FT%H%M%SZ", gmtime($starttime)),
244 status => $status,
245 type => $type,
246 version => $version,
247 };
248 if (my $hostname = `hostname`) {
249 chomp $hostname;
250 $statusjson->{hostname} = $hostname;
251 }
252 if (-e '/etc/machine-id') {
253 open my $fh, '/etc/machine-id';
254 my $machine_id = <$fh>;
255 close $fh;
256 if ($machine_id) {
257 chomp $machine_id;
258 $statusjson->{'machine-id'} = $machine_id;
259 }
260 }
261 if (-e '/etc/machine-info') {
262 open my $fh, '/etc/machine-info';
263 while (<$fh>) {
264 if (/^DEPLOYMENT=(.*)/) {
265 $statusjson->{'machine-deployment'} = $1;
266 }
267 }
268 close $fh;
269 }
270
271 my $json = JSON->new->canonical;
272 open F, '>', $statusfile or error "$statusfile: $!";
273 print F $json->encode($statusjson) . "\n" or error "$statusfile: $!";
274 close F or error "$$statusfile: $!";
275 }
276
277 sub sync($) {
278 my $backupdir = shift;
279 system_or_error "sync $backupdir/*";
280 }
281
282 sub expire_backups($$) {
283 my ($suffix, $number) = @_;
284 my @backups = glob("$clusterdir/*.$suffix");
285 my $found = 0;
286 for my $backup (reverse @backups) {
287 # iterate reversely over backups until we have found enough valid ones
288 if ($found >= $number and can_lock_dir($backup)) {
289 print "Removing $backup ...\n" if ($verbose);
290 $backup =~ /(.*)/; # untaint
291 system_or_error "rm", "-rf", $1;
292 } else {
293 if (-f "$backup/status" and can_lock_dir($backup)) {
294 $found++;
295 }
296 }
297 }
298 }
299
300 sub delete_broken() {
301 my @backups = (glob("$clusterdir/*.backup"), glob("$clusterdir/*.dump"));
302 for my $backup (@backups) {
303 if (! -f "$backup/status" and can_lock_dir($backup)) {
304 print "Removing $backup ...\n" if ($verbose);
305 $backup =~ /(.*)/; # untaint
306 system_or_error "rm", "-rf", $1;
307 }
308 }
309 }
310
311 # wal handling
312
313 sub create_wal_directory() {
314 if (! -d $waldir) {
315 mkdir($waldir, 0750) or error "mkdir $waldir: $!";
316 }
317 }
318
319 sub receivewal() {
320 my $pg_receivewal = $version >= 10 ? 'pg_receivewal' : 'pg_receivexlog';
321
322 # create slot
323 system_or_error $pg_receivewal, "--cluster=$version/$cluster", "--slot", "pg_receivewal_service", "--create-slot", "--if-not-exists";
324
325 # launch pg_receivewal
326 $ENV{PGAPPNAME} = "pg_receivewal\@$version-$cluster.service";
327 my @cmd = ($pg_receivewal, "--cluster", "$version/$cluster",
328 "-D", $waldir, "--slot", "pg_receivewal_service");
329 if ($compress) {
330 push @cmd, "--compress=$compress";
331 } elsif ($version >= 10) {
332 push @cmd, "--compress=5";
333 }
334 exec {$pg_receivewal} @cmd or error "exec $pg_receivewal: $!";
335 }
336
337 sub compresswal() {
338 chdir $waldir or return; # ok if not yet created
339 open my $lock, $waldir or error "open $waldir: $!"; # protect against concurrent runs
340 flock $lock, LOCK_EX or error "flock $waldir: $!";
341
342 for my $wal (glob "0???????????????????????") {
343 $wal =~ /^([0-9A-F]+)$/ or continue;
344 $wal = $1; # untaint
345 if (-f "$wal.gz") {
346 print STDERR "$waldir/$wal.gz already exists, skipping compression\n";
347 next;
348 }
349 system_or_error "if ! gzip < $wal > $wal.tmp.gz; then rm -f $wal.tmp.gz; exit 1; fi";
350 system_or_error "touch --reference=$wal $wal.tmp.gz";
351 system_or_error "mv $wal.tmp.gz $wal.gz";
352 system_or_error "sync", "$wal.gz";
353 unlink $wal;
354 }
355
356 close $lock;
357 }
358
359 sub archivecleanup() {
360 chdir $waldir or return; # ok if not yet created
361 my @backups = sort glob "$clusterdir/*.backup";
362 for my $backup (@backups) {
363 next unless (-f "$backup/status");
364
365 $backup =~ /(.*)/; # untaint
366 my $basetar = "$1/base.tar.gz";
367 my $backup_label = `tar --extract --occurrence=1 --to-stdout --file '$basetar' backup_label` or error "failed to extract backup_label from $basetar";
368
369 # START WAL LOCATION: 0/2B000028 (file 00000001000000000000002B)
370 $backup_label =~ /^START WAL LOCATION: .* \(file ([0-9A-F]+)\)/ or error "no start wal location in $basetar";
371 my $keep_file = $1;
372 system_or_error "pg_archivecleanup", "-x", ".gz", $waldir, $keep_file;
373
374 return 0; # process first backup only
375 }
376 error "no valid basebackups found in $clusterdir";
377 }
378
379 # info functions
380
381 sub dirsize($) {
382 my $dir = shift;
383 my $size = 0;
384 my $files = 0;
385 for my $f (glob "$dir/*") {
386 $size += (stat $f)[7];
387 $files++;
388 }
389 return $size, $files;
390 }
391
392 sub get_status($) {
393 my ($dir) = @_;
394
395 # if status is present, the backup is ok
396 return "" if (-f "$dir/status");
397
398 # if we can get the lock, the backup failed
399 return " BROKEN" if (can_lock_dir($dir));
400
401 return " RUNNING";
402 }
403
404 sub list() {
405 print "Cluster $version $cluster backups in $clusterdir:\n";
406 my $totalsize = 0;
407 print "Dumps:\n";
408 for my $dir (sort glob "$clusterdir/*.dump") {
409 my ($size, $files) = dirsize($dir);
410 my $status = get_status($dir);
411 print " $dir: $size Bytes$status\n";
412 $totalsize += $size;
413 }
414 print "Basebackups:\n";
415 for my $dir (sort glob "$clusterdir/*.backup") {
416 my ($size, $files) = dirsize($dir);
417 my $status = get_status($dir);
418 print " $dir: $size Bytes$status\n";
419 $totalsize += $size;
420 }
421 if (-d "$clusterdir/wal") {
422 print "WAL:\n";
423 my ($size, $files) = dirsize("$clusterdir/wal");
424 print " $clusterdir/wal: $size Bytes, $files Files\n";
425 $totalsize += $size;
426 }
427 print "Total: $totalsize Bytes\n";
428 }
429
430 # main
431
432 if ($action eq 'createdirectory') {
433 create_directory();
434
435 } elsif ($action eq 'basebackup') {
436 error "basebackups of pre-9.1 servers are not supported" if ($version < 9.1);
437 my $starttime = time;
438 create_directory();
439 switch_to_cluster_owner();
440 my $backupdir = get_backupdir($starttime, 'backup');
441 $SIG{__DIE__} = sub { remove_backup_on_error($backupdir) };
442 create_basebackup($backupdir);
443 create_configbackup($backupdir);
444 create_status($action, $starttime, $backupdir, 'ok');
445 $SIG{__DIE__} = undef;
446 sync($backupdir);
447 compresswal();
448
449 } elsif ($action eq 'dump') {
450 error "dumps of pre-9.3 servers are not supported" if ($version < 9.3);
451 my $starttime = time;
452 create_directory();
453 switch_to_cluster_owner();
454 my $backupdir = get_backupdir($starttime, 'dump');
455 $SIG{__DIE__} = sub { remove_backup_on_error($backupdir) };
456 create_dumpall($backupdir);
457 create_configbackup($backupdir);
458 create_status($action, $starttime, $backupdir, 'ok');
459 $SIG{__DIE__} = undef;
460 sync($backupdir);
461
462 } elsif ($action eq 'expiredumps' and @ARGV == 2 and $ARGV[1] =~ /^(\d+)$/) {
463 switch_to_cluster_owner();
464 expire_backups('dump', $1);
465
466 } elsif ($action eq 'expirebasebackups' and @ARGV == 2 and $ARGV[1] =~ /^(\d+)$/) {
467 switch_to_cluster_owner();
468 expire_backups('backup', $1);
469 archivecleanup();
470 compresswal();
471
472 } elsif ($action eq 'deletebroken') {
473 switch_to_cluster_owner();
474 delete_broken();
475
476 } elsif ($action eq 'receivewal') {
477 create_directory();
478 switch_to_cluster_owner();
479 create_wal_directory();
480 compresswal();
481 receivewal();
482
483 } elsif ($action eq 'compresswal') {
484 switch_to_cluster_owner();
485 compresswal();
486
487 } elsif ($action eq 'archivecleanup') {
488 switch_to_cluster_owner();
489 archivecleanup();
490 compresswal();
491
492 } elsif ($action eq 'list') {
493 switch_to_cluster_owner();
494 list();
495
496 } else {
497 help(1);
498 }
499
500 __END__
501
502 =head1 NAME
503
504 pg_backupcluster - simple pg_basebackup and pg_dump front-end
505
506 =head1 SYNOPSIS
507
508 B<pg_backupcluster> [I<options>] I<version> I<cluster> I<action>
509
510 =head1 DESCRIPTION
511
512 B<pg_backupcluster> provides a simple interface to create PostgreSQL cluster
513 backups using L<pg_basebackup(1)> and L<pg_dump(1)>.
514
515 To ease integration with B<systemd> operation, the alternative syntax
516 "B<pg_basebackup> I<version>B<->I<cluster> I<action>" is also supported.
517
518 =head1 ACTIONS
519
520 =over 4
521
522 =item B<createdirectory>
523
524 Create /var/backups/postgresql and /var/backups/postgresql/I<version>-I<cluster>.
525 This action can be run as root to create the directories required for backups.
526 All other actions will also attempt to create the directories when missing, but
527 can of course only do that when running as root. They will switch to the
528 cluster owner after this step.
529
530 =item B<basebackup>
531
532 Backup using L<pg_basebackup(1)>. The resulting basebackup contains the WAL
533 files required to run recovery on startup.
534
535 =item B<dump>
536
537 Backup using L<pg_dump(1)>. Global objects (users, tablespaces) are dumped
538 using L<pg_dumpall(1)> B<--globals-only>. Individual databases are dumped into
539 PostgreSQL's custom format.
540
541 =item B<expirebasebackups> I<N>
542
543 Remove all but last the I<N> basebackups.
544
545 =item B<expiredumps> I<N>
546
547 Remove all but last the I<N> dumps.
548
549 =item B<deletebroken>
550
551 Remove all broken backups.
552
553 =item B<receivewal>
554
555 Launch pg_receivewal. WAL files are gzip-compressed in PG 10+.
556
557 =item B<compresswal>
558
559 Compress WAL files in archive.
560
561 =item B<archivecleanup>
562
563 Remove obsolete WAL files from archive using L<pg_archivecleanup(1)>.
564
565 =item B<list>
566
567 Show dumps, basebackups, and WAL, with size.
568
569 =back
570
571 =head1 OPTIONS
572
573 =over 4
574
575 =item B<-c --checkpoint=spread|fast>
576
577 Passed to B<pg_basebackup>. Default is B<spread>.
578
579 =item B<-k --keep-on-error>
580
581 Keep broken backup directory on error. By default backups are deleted on error.
582 Broken backups can be cleaned up using the B<deletebroken> action.
583
584 =item B<-v --verbose>
585
586 Verbose output, even when not running on a terminal.
587
588 =item B<-Z> I<level> B<--compress=>I<level>
589
590 Passed to B<pg_dump>, B<pg_basebackup> and B<pg_receivewal>.
591 Default is pg_dump's default compression, B<gzip> for pg_basebackup, and B<5> for pg_receivewal.
592
593 =back
594
595 =head1 FILES
596
597 =over 4
598
599 =item /var/backups/postgresql
600
601 Default root directory for cluster backup directories.
602
603 =item /var/backups/postgresql/I<version>-I<cluster>
604
605 Default directory for cluster backups.
606
607 =item /var/backups/postgresql/I<version>-I<cluster>/I<timestamp>B<.basebackup>
608
609 Backup from B<pg_backupcluster ... basebackup>.
610
611 =over 4
612
613 =item C<config.tar.gz>
614
615 Tarball of cluster configuration directory (postgresql.conf, pg_hba.conf, ...)
616 in /etc/postgresql.
617
618 =item I<tablespace>C<.tar.gz>, C<pg_wal.tar.gz>, C<backup_manifest>
619
620 Tablespace and WAL tarballs and backup info written by B<pg_basebackup>.
621
622 =item C<status>
623
624 Completion timestamp of backup run.
625
626 =back
627
628 =item /var/backups/postgresql/I<version>-I<cluster>/I<timestamp>B<.dump>
629
630 Backup from B<pg_backupcluster ... dump>.
631
632 =over 4
633
634 =item C<config.tar.gz>
635
636 Tarball of cluster configuration directory (postgresql.conf, pg_hba.conf, ...)
637 in /etc/postgresql.
638
639 =item C<createcluster.opts>
640
641 Options (encoding, locale, data checksums) to be passed to B<pg_createcluster>
642 for restoring this cluster.
643
644 =item C<globals.sql>
645
646 Global objects (roles, tablespaces) from B<pg_dumpall --globals-only>.
647
648 =item C<databases.sql>
649
650 SQL commands to create databases and restore database-level options.
651
652 =item I<database>C<.dump>
653
654 Database dumps from B<pg_dump --format=custom>.
655
656 =item C<status>
657
658 Completion timestamp of backup run.
659
660 =back
661
662 =item /var/backups/postgresql/I<version>-I<cluster>/B<wal>
663
664 WAL files from B<pg_receivewal>.
665
666 =back
667
668 =head1 CAVEATS
669
670 For dump-style backups, not all properties of the original cluster are preserved:
671
672 =over 2
673
674 =item * In PostgreSQL 10 and earlier, ALTER ROLE ... IN DATABASE is not supported.
675
676 =item * Not all B<initdb> options are carried over. Currently supported are B<--encoding>,
677 B<--lc-collate>, B<--lc-collate>, and B<-k --data-checksums>.
678
679 =back
680
681 The earliest PostgreSQL version supported for dumps is 9.3.
682 For basebackups, the earliest supported version is 9.1.
683 B<receivewal> (and hence archive recovery) are supported in 9.5 and later.
684
685 =head1 SEE ALSO
686
687 L<pg_restorecluster(1)>,
688 L<pg_dump(1)>, L<pg_dumpall(1)>,
689 L<pg_basebackup(1)>, L<pg_receivewal(1)>, L<pg_archivecleanup(1)>.
690
691 =head1 AUTHOR
692
693 Christoph Berg L<E<lt>[email protected]<gt>>