PostgreSQL Source Code git master
Loading...
Searching...
No Matches
basebackup.c File Reference
#include "postgres.h"
#include <sys/stat.h>
#include <unistd.h>
#include <time.h>
#include "access/xlog_internal.h"
#include "access/xlogbackup.h"
#include "backup/backup_manifest.h"
#include "backup/basebackup.h"
#include "backup/basebackup_incremental.h"
#include "backup/basebackup_sink.h"
#include "backup/basebackup_target.h"
#include "catalog/pg_tablespace_d.h"
#include "commands/defrem.h"
#include "common/compression.h"
#include "common/file_perm.h"
#include "common/file_utils.h"
#include "lib/stringinfo.h"
#include "miscadmin.h"
#include "nodes/pg_list.h"
#include "pgstat.h"
#include "pgtar.h"
#include "postmaster/syslogger.h"
#include "postmaster/walsummarizer.h"
#include "replication/slot.h"
#include "replication/walsender.h"
#include "replication/walsender_private.h"
#include "storage/bufpage.h"
#include "storage/checksum.h"
#include "storage/dsm_impl.h"
#include "storage/ipc.h"
#include "storage/reinit.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/ps_status.h"
#include "utils/relcache.h"
#include "utils/resowner.h"
#include "utils/wait_event.h"
Include dependency graph for basebackup.c:

Go to the source code of this file.

Data Structures

struct  basebackup_options
 
struct  exclude_list_item
 

Macros

#define SINK_BUFFER_LENGTH   Max(32768, BLCKSZ)
 
#define TAR_NUM_TERMINATION_BLOCKS   2
 

Functions

 StaticAssertDecl (TAR_NUM_TERMINATION_BLOCKS *TAR_BLOCK_SIZE<=BLCKSZ, "BLCKSZ too small for " CppAsString2(TAR_NUM_TERMINATION_BLOCKS) " tar termination blocks")
 
static int64 sendTablespace (bbsink *sink, char *path, Oid spcoid, bool sizeonly, struct backup_manifest_info *manifest, IncrementalBackupInfo *ib)
 
static int64 sendDir (bbsink *sink, const char *path, int basepathlen, bool sizeonly, List *tablespaces, bool sendtblspclinks, backup_manifest_info *manifest, Oid spcoid, IncrementalBackupInfo *ib)
 
static bool sendFile (bbsink *sink, const char *readfilename, const char *tarfilename, struct stat *statbuf, bool missing_ok, Oid dboid, Oid spcoid, RelFileNumber relfilenumber, unsigned segno, backup_manifest_info *manifest, unsigned num_incremental_blocks, BlockNumber *incremental_blocks, unsigned truncation_block_length)
 
static off_t read_file_data_into_buffer (bbsink *sink, const char *readfilename, int fd, off_t offset, size_t length, BlockNumber blkno, bool verify_checksum, int *checksum_failures)
 
static void push_to_sink (bbsink *sink, pg_checksum_context *checksum_ctx, size_t *bytes_done, void *data, size_t length)
 
static bool verify_page_checksum (Page page, XLogRecPtr start_lsn, BlockNumber blkno, uint16 *expected_checksum)
 
static void sendFileWithContent (bbsink *sink, const char *filename, const char *content, int len, backup_manifest_info *manifest)
 
static int64 _tarWriteHeader (bbsink *sink, const char *filename, const char *linktarget, struct stat *statbuf, bool sizeonly)
 
static void _tarWritePadding (bbsink *sink, int len)
 
static void convert_link_to_directory (const char *pathbuf, struct stat *statbuf)
 
static void perform_base_backup (basebackup_options *opt, bbsink *sink, IncrementalBackupInfo *ib)
 
static void parse_basebackup_options (List *options, basebackup_options *opt)
 
static int compareWalFileNames (const ListCell *a, const ListCell *b)
 
static ssize_t basebackup_read_file (int fd, char *buf, size_t nbytes, off_t offset, const char *filename, bool partial_read_ok)
 
void SendBaseBackup (BaseBackupCmd *cmd, IncrementalBackupInfo *ib)
 

Variables

static bool backup_started_in_recovery = false
 
static long long int total_checksum_failures
 
static bool noverify_checksums = false
 
static const char *const excludeDirContents []
 
static const struct exclude_list_item excludeFiles []
 

Macro Definition Documentation

◆ SINK_BUFFER_LENGTH

#define SINK_BUFFER_LENGTH   Max(32768, BLCKSZ)

Definition at line 61 of file basebackup.c.

◆ TAR_NUM_TERMINATION_BLOCKS

#define TAR_NUM_TERMINATION_BLOCKS   2

Definition at line 82 of file basebackup.c.

Function Documentation

◆ _tarWriteHeader()

static int64 _tarWriteHeader ( bbsink sink,
const char filename,
const char linktarget,
struct stat statbuf,
bool  sizeonly 
)
static

Definition at line 2039 of file basebackup.c.

2041{
2042 enum tarError rc;
2043
2044 if (!sizeonly)
2045 {
2046 /*
2047 * As of this writing, the smallest supported block size is 1kB, which
2048 * is twice TAR_BLOCK_SIZE. Since the buffer size is required to be a
2049 * multiple of BLCKSZ, it should be safe to assume that the buffer is
2050 * large enough to fit an entire tar block. We double-check by means
2051 * of these assertions.
2052 */
2054 "BLCKSZ too small for tar block");
2055 Assert(sink->bbs_buffer_length >= TAR_BLOCK_SIZE);
2056
2057 rc = tarCreateHeader(sink->bbs_buffer, filename, linktarget,
2058 statbuf->st_size, statbuf->st_mode,
2059 statbuf->st_uid, statbuf->st_gid,
2060 statbuf->st_mtime);
2061
2062 switch (rc)
2063 {
2064 case TAR_OK:
2065 break;
2066 case TAR_NAME_TOO_LONG:
2067 ereport(ERROR,
2069 errmsg("file name too long for tar format: \"%s\"",
2070 filename)));
2071 break;
2073 ereport(ERROR,
2075 errmsg("symbolic link target too long for tar format: "
2076 "file name \"%s\", target \"%s\"",
2077 filename, linktarget)));
2078 break;
2079 default:
2080 elog(ERROR, "unrecognized tar error: %d", rc);
2081 }
2082
2084 }
2085
2086 return TAR_BLOCK_SIZE;
2087}
static void bbsink_archive_contents(bbsink *sink, size_t len)
#define Assert(condition)
Definition c.h:1002
#define StaticAssertDecl(condition, errmessage)
Definition c.h:1067
int errcode(int sqlerrcode)
Definition elog.c:875
#define ERROR
Definition elog.h:40
#define elog(elevel,...)
Definition elog.h:228
#define ereport(elevel,...)
Definition elog.h:152
static char * errmsg
static char * filename
Definition pg_dumpall.c:120
enum tarError tarCreateHeader(char *h, const char *filename, const char *linktarget, pgoff_t size, mode_t mode, uid_t uid, gid_t gid, time_t mtime)
Definition tar.c:143
tarError
Definition pgtar.h:20
@ TAR_SYMLINK_TOO_LONG
Definition pgtar.h:23
@ TAR_OK
Definition pgtar.h:21
@ TAR_NAME_TOO_LONG
Definition pgtar.h:22
#define TAR_BLOCK_SIZE
Definition pgtar.h:17
static int fb(int x)

References Assert, bbsink_archive_contents(), elog, ereport, errcode(), errmsg, ERROR, fb(), filename, StaticAssertDecl, TAR_BLOCK_SIZE, TAR_NAME_TOO_LONG, TAR_OK, TAR_SYMLINK_TOO_LONG, and tarCreateHeader().

Referenced by perform_base_backup(), sendDir(), sendFile(), sendFileWithContent(), and sendTablespace().

◆ _tarWritePadding()

static void _tarWritePadding ( bbsink sink,
int  len 
)
static

Definition at line 2093 of file basebackup.c.

2094{
2095 int pad = tarPaddingBytesRequired(len);
2096
2097 /*
2098 * As in _tarWriteHeader, it should be safe to assume that the buffer is
2099 * large enough that we don't need to do this in multiple chunks.
2100 */
2101 Assert(sink->bbs_buffer_length >= TAR_BLOCK_SIZE);
2102 Assert(pad <= TAR_BLOCK_SIZE);
2103
2104 if (pad > 0)
2105 {
2106 MemSet(sink->bbs_buffer, 0, pad);
2108 }
2109}
#define MemSet(start, val, len)
Definition c.h:1166
const void size_t len
static size_t tarPaddingBytesRequired(size_t len)
Definition pgtar.h:84

References Assert, bbsink_archive_contents(), fb(), len, MemSet, TAR_BLOCK_SIZE, and tarPaddingBytesRequired().

Referenced by sendFile(), and sendFileWithContent().

◆ basebackup_read_file()

static ssize_t basebackup_read_file ( int  fd,
char buf,
size_t  nbytes,
off_t  offset,
const char filename,
bool  partial_read_ok 
)
static

Definition at line 2133 of file basebackup.c.

2135{
2136 ssize_t rc;
2137
2139 rc = pg_pread(fd, buf, nbytes, offset);
2141
2142 if (rc < 0)
2143 ereport(ERROR,
2145 errmsg("could not read file \"%s\": %m", filename)));
2146 if (!partial_read_ok && rc > 0 && rc != nbytes)
2147 ereport(ERROR,
2149 errmsg("could not read file \"%s\": read %zd of %zu",
2150 filename, rc, nbytes)));
2151
2152 return rc;
2153}
int errcode_for_file_access(void)
Definition elog.c:898
static char buf[DEFAULT_XLOG_SEG_SIZE]
#define pg_pread
Definition port.h:248
static int fd(const char *x, int i)
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition wait_event.h:67
static void pgstat_report_wait_end(void)
Definition wait_event.h:83

References buf, ereport, errcode_for_file_access(), errmsg, ERROR, fb(), fd(), filename, pg_pread, pgstat_report_wait_end(), and pgstat_report_wait_start().

Referenced by perform_base_backup(), and read_file_data_into_buffer().

◆ compareWalFileNames()

static int compareWalFileNames ( const ListCell a,
const ListCell b 
)
static

Definition at line 686 of file basebackup.c.

687{
688 char *fna = (char *) lfirst(a);
689 char *fnb = (char *) lfirst(b);
690
691 return strcmp(fna + 8, fnb + 8);
692}
int b
Definition isn.c:74
int a
Definition isn.c:73
#define lfirst(lc)
Definition pg_list.h:172

References a, b, fb(), and lfirst.

Referenced by perform_base_backup().

◆ convert_link_to_directory()

static void convert_link_to_directory ( const char pathbuf,
struct stat statbuf 
)
static

Definition at line 2116 of file basebackup.c.

2117{
2118 /* If symlink, write it as a directory anyway */
2119 if (S_ISLNK(statbuf->st_mode))
2120 statbuf->st_mode = S_IFDIR | pg_dir_create_mode;
2121}
int pg_dir_create_mode
Definition file_perm.c:18
#define S_ISLNK(m)
Definition win32_port.h:334

References fb(), pg_dir_create_mode, and S_ISLNK.

Referenced by sendDir().

◆ parse_basebackup_options()

static void parse_basebackup_options ( List options,
basebackup_options opt 
)
static

Definition at line 698 of file basebackup.c.

699{
700 ListCell *lopt;
701 bool o_label = false;
702 bool o_progress = false;
703 bool o_checkpoint = false;
704 bool o_nowait = false;
705 bool o_wal = false;
706 bool o_incremental = false;
707 bool o_maxrate = false;
708 bool o_tablespace_map = false;
709 bool o_noverify_checksums = false;
710 bool o_manifest = false;
711 bool o_manifest_checksums = false;
712 bool o_target = false;
713 bool o_target_detail = false;
714 char *target_str = NULL;
715 char *target_detail_str = NULL;
716 bool o_compression = false;
717 bool o_compression_detail = false;
719
720 MemSet(opt, 0, sizeof(*opt));
725
726 foreach(lopt, options)
727 {
729
730 if (strcmp(defel->defname, "label") == 0)
731 {
732 if (o_label)
735 errmsg("duplicate option \"%s\"", defel->defname)));
736 opt->label = defGetString(defel);
737 o_label = true;
738 }
739 else if (strcmp(defel->defname, "progress") == 0)
740 {
741 if (o_progress)
744 errmsg("duplicate option \"%s\"", defel->defname)));
746 o_progress = true;
747 }
748 else if (strcmp(defel->defname, "checkpoint") == 0)
749 {
750 char *optval = defGetString(defel);
751
752 if (o_checkpoint)
755 errmsg("duplicate option \"%s\"", defel->defname)));
756 if (pg_strcasecmp(optval, "fast") == 0)
757 opt->fastcheckpoint = true;
758 else if (pg_strcasecmp(optval, "spread") == 0)
759 opt->fastcheckpoint = false;
760 else
763 errmsg("unrecognized checkpoint type: \"%s\"",
764 optval)));
765 o_checkpoint = true;
766 }
767 else if (strcmp(defel->defname, "wait") == 0)
768 {
769 if (o_nowait)
772 errmsg("duplicate option \"%s\"", defel->defname)));
773 opt->nowait = !defGetBoolean(defel);
774 o_nowait = true;
775 }
776 else if (strcmp(defel->defname, "wal") == 0)
777 {
778 if (o_wal)
781 errmsg("duplicate option \"%s\"", defel->defname)));
783 o_wal = true;
784 }
785 else if (strcmp(defel->defname, "incremental") == 0)
786 {
787 if (o_incremental)
790 errmsg("duplicate option \"%s\"", defel->defname)));
792 if (opt->incremental && !summarize_wal)
795 errmsg("incremental backups cannot be taken unless WAL summarization is enabled")));
796 o_incremental = true;
797 }
798 else if (strcmp(defel->defname, "max_rate") == 0)
799 {
801
802 if (o_maxrate)
805 errmsg("duplicate option \"%s\"", defel->defname)));
806
811 errmsg("%" PRId64 " is outside the valid range for parameter \"%s\" (%d .. %d)",
812 maxrate, "MAX_RATE", MAX_RATE_LOWER, MAX_RATE_UPPER)));
813
814 opt->maxrate = (uint32) maxrate;
815 o_maxrate = true;
816 }
817 else if (strcmp(defel->defname, "tablespace_map") == 0)
818 {
822 errmsg("duplicate option \"%s\"", defel->defname)));
824 o_tablespace_map = true;
825 }
826 else if (strcmp(defel->defname, "verify_checksums") == 0)
827 {
831 errmsg("duplicate option \"%s\"", defel->defname)));
834 }
835 else if (strcmp(defel->defname, "manifest") == 0)
836 {
837 char *optval = defGetString(defel);
838 bool manifest_bool;
839
840 if (o_manifest)
843 errmsg("duplicate option \"%s\"", defel->defname)));
845 {
846 if (manifest_bool)
848 else
850 }
851 else if (pg_strcasecmp(optval, "force-encode") == 0)
853 else
856 errmsg("unrecognized manifest option: \"%s\"",
857 optval)));
858 o_manifest = true;
859 }
860 else if (strcmp(defel->defname, "manifest_checksums") == 0)
861 {
862 char *optval = defGetString(defel);
863
867 errmsg("duplicate option \"%s\"", defel->defname)));
872 errmsg("unrecognized checksum algorithm: \"%s\"",
873 optval)));
875 }
876 else if (strcmp(defel->defname, "target") == 0)
877 {
878 if (o_target)
881 errmsg("duplicate option \"%s\"", defel->defname)));
883 o_target = true;
884 }
885 else if (strcmp(defel->defname, "target_detail") == 0)
886 {
887 char *optval = defGetString(defel);
888
889 if (o_target_detail)
892 errmsg("duplicate option \"%s\"", defel->defname)));
894 o_target_detail = true;
895 }
896 else if (strcmp(defel->defname, "compression") == 0)
897 {
898 char *optval = defGetString(defel);
899
900 if (o_compression)
903 errmsg("duplicate option \"%s\"", defel->defname)));
907 errmsg("unrecognized compression algorithm: \"%s\"",
908 optval)));
909 o_compression = true;
910 }
911 else if (strcmp(defel->defname, "compression_detail") == 0)
912 {
916 errmsg("duplicate option \"%s\"", defel->defname)));
919 }
920 else
923 errmsg("unrecognized base backup option: \"%s\"",
924 defel->defname)));
925 }
926
927 if (opt->label == NULL)
928 opt->label = "base backup";
929 if (opt->manifest == MANIFEST_OPTION_NO)
930 {
934 errmsg("manifest checksums require a backup manifest")));
936 }
937
938 if (target_str == NULL)
939 {
940 if (target_detail_str != NULL)
943 errmsg("target detail cannot be used without target")));
944 opt->use_copytblspc = true;
945 opt->send_to_client = true;
946 }
947 else if (strcmp(target_str, "client") == 0)
948 {
949 if (target_detail_str != NULL)
952 errmsg("target \"%s\" does not accept a target detail",
953 target_str)));
954 opt->send_to_client = true;
955 }
956 else
957 opt->target_handle =
959
963 errmsg("compression detail cannot be specified unless compression is enabled")));
964
965 if (o_compression)
966 {
967 char *error_detail;
968
973 if (error_detail != NULL)
976 errmsg("invalid compression specification: %s",
977 error_detail));
978 }
979}
@ MANIFEST_OPTION_NO
@ MANIFEST_OPTION_FORCE_ENCODE
@ MANIFEST_OPTION_YES
static bool noverify_checksums
Definition basebackup.c:135
#define MAX_RATE_UPPER
Definition basebackup.h:21
#define MAX_RATE_LOWER
Definition basebackup.h:20
BaseBackupTargetHandle * BaseBackupGetTargetHandle(char *target, char *target_detail)
bool parse_bool(const char *value, bool *result)
Definition bool.c:31
int64_t int64
Definition c.h:680
uint32_t uint32
Definition c.h:683
bool pg_checksum_parse_type(char *name, pg_checksum_type *type)
@ CHECKSUM_TYPE_NONE
@ CHECKSUM_TYPE_CRC32C
char * validate_compress_specification(pg_compress_specification *spec)
bool parse_compress_algorithm(char *name, pg_compress_algorithm *algorithm)
Definition compression.c:79
void parse_compress_specification(pg_compress_algorithm algorithm, char *specification, pg_compress_specification *result)
@ PG_COMPRESSION_NONE
Definition compression.h:23
char * defGetString(DefElem *def)
Definition define.c:34
bool defGetBoolean(DefElem *def)
Definition define.c:93
int64 defGetInt64(DefElem *def)
Definition define.c:172
static int32 maxrate
int pg_strcasecmp(const char *s1, const char *s2)
pg_compress_specification compression_specification
Definition basebackup.c:78
pg_checksum_type manifest_checksum_type
Definition basebackup.c:79
const char * label
Definition basebackup.c:65
pg_compress_algorithm compression
Definition basebackup.c:77
backup_manifest_option manifest
Definition basebackup.c:76
BaseBackupTargetHandle * target_handle
Definition basebackup.c:75
pg_compress_algorithm algorithm
Definition compression.h:34
static char * error_detail
Definition validator.c:43
bool summarize_wal

References pg_compress_specification::algorithm, BaseBackupGetTargetHandle(), CHECKSUM_TYPE_CRC32C, CHECKSUM_TYPE_NONE, basebackup_options::compression, basebackup_options::compression_specification, defGetBoolean(), defGetInt64(), defGetString(), ereport, errcode(), errmsg, ERROR, error_detail, basebackup_options::fastcheckpoint, fb(), basebackup_options::includewal, basebackup_options::incremental, basebackup_options::label, lfirst, basebackup_options::manifest, basebackup_options::manifest_checksum_type, MANIFEST_OPTION_FORCE_ENCODE, MANIFEST_OPTION_NO, MANIFEST_OPTION_YES, MAX_RATE_LOWER, MAX_RATE_UPPER, basebackup_options::maxrate, maxrate, MemSet, noverify_checksums, basebackup_options::nowait, parse_bool(), parse_compress_algorithm(), parse_compress_specification(), pg_checksum_parse_type(), PG_COMPRESSION_NONE, pg_strcasecmp(), basebackup_options::progress, basebackup_options::send_to_client, basebackup_options::sendtblspcmapfile, summarize_wal, basebackup_options::target_handle, basebackup_options::use_copytblspc, and validate_compress_specification().

Referenced by SendBaseBackup().

◆ perform_base_backup()

static void perform_base_backup ( basebackup_options opt,
bbsink sink,
IncrementalBackupInfo ib 
)
static

Definition at line 240 of file basebackup.c.

242{
244 XLogRecPtr endptr;
249
250 /* Initial backup state, insofar as we know it now. */
251 state.tablespaces = NIL;
252 state.tablespace_num = 0;
253 state.bytes_done = 0;
254 state.bytes_total = 0;
255 state.bytes_total_is_valid = false;
256
257 /* we're going to use a BufFile, so we need a ResourceOwner */
262
264
267
269
270 /* Allocate backup related variables. */
273
275 do_pg_backup_start(opt->label, opt->fastcheckpoint, &state.tablespaces,
277
278 state.startptr = backup_state->startpoint;
279 state.starttli = backup_state->starttli;
280
281 /*
282 * Once do_pg_backup_start has been called, ensure that any failure causes
283 * us to abort the backup so we don't "leak" a backup counter. For this
284 * reason, *all* functionality between do_pg_backup_start() and the end of
285 * do_pg_backup_stop() should be inside the error cleanup block!
286 */
287
289 {
290 ListCell *lc;
292
293 /* If this is an incremental backup, execute preparatory steps. */
294 if (ib != NULL)
296
297 /* Add a node for the base directory at the end */
299 newti->size = -1;
300 state.tablespaces = lappend(state.tablespaces, newti);
301
302 /*
303 * Calculate the total backup size by summing up the size of each
304 * tablespace
305 */
306 if (opt->progress)
307 {
309
310 foreach(lc, state.tablespaces)
311 {
313
314 if (tmp->path == NULL)
315 tmp->size = sendDir(sink, ".", 1, true, state.tablespaces,
316 true, NULL, InvalidOid, NULL);
317 else
318 tmp->size = sendTablespace(sink, tmp->path, tmp->oid, true,
319 NULL, NULL);
320 state.bytes_total += tmp->size;
321 }
322 state.bytes_total_is_valid = true;
323 }
324
325 /* notify basebackup sink about start of backup */
327
328 /* Send off our tablespaces one by one */
329 foreach(lc, state.tablespaces)
330 {
332
333 if (ti->path == NULL)
334 {
335 struct stat statbuf;
336 bool sendtblspclinks = true;
337 char *backup_label;
338
339 bbsink_begin_archive(sink, "base.tar");
340
341 /* In the main tar, include the backup_label first... */
344 backup_label, -1, &manifest);
346
347 /* Then the tablespace_map file, if required... */
348 if (opt->sendtblspcmapfile)
349 {
352 sendtblspclinks = false;
353 }
354
355 /* Then the bulk of the files... */
356 sendDir(sink, ".", 1, false, state.tablespaces,
358
359 /* ... and pg_control after everything else. */
360 if (lstat(XLOG_CONTROL_FILE, &statbuf) != 0)
363 errmsg("could not stat file \"%s\": %m",
366 false, InvalidOid, InvalidOid,
368 }
369 else
370 {
371 char *archive_name = psprintf("%u.tar", ti->oid);
372
373 bbsink_begin_archive(sink, archive_name);
374
375 sendTablespace(sink, ti->path, ti->oid, false, &manifest, ib);
376 }
377
378 /*
379 * If we're including WAL, and this is the main data directory we
380 * don't treat this as the end of the tablespace. Instead, we will
381 * include the xlog files below and stop afterwards. This is safe
382 * since the main data directory is always sent *last*.
383 */
384 if (opt->includewal && ti->path == NULL)
385 {
386 Assert(lnext(state.tablespaces, lc) == NULL);
387 }
388 else
389 {
390 /* Properly terminate the tarfile. */
393
394 /* OK, that's the end of the archive. */
396 }
397 }
398
401
402 endptr = backup_state->stoppoint;
404
405 /* Deallocate backup-related variables. */
408 }
410
411
412 if (opt->includewal)
413 {
414 /*
415 * We've left the last tar file "open", so we can now append the
416 * required WAL files to it.
417 */
418 char pathbuf[MAXPGPATH];
419 XLogSegNo segno;
422 struct stat statbuf;
425 char firstoff[MAXFNAMELEN];
426 char lastoff[MAXFNAMELEN];
427 DIR *dir;
428 struct dirent *de;
429 ListCell *lc;
430 TimeLineID tli;
431
433
434 /*
435 * I'd rather not worry about timelines here, so scan pg_wal and
436 * include all WAL files in the range between 'startptr' and 'endptr',
437 * regardless of the timeline the file is stamped with. If there are
438 * some spurious WAL files belonging to timelines that don't belong in
439 * this server's history, they will be included too. Normally there
440 * shouldn't be such files, but if there are, there's little harm in
441 * including them.
442 */
447
448 dir = AllocateDir("pg_wal");
449 while ((de = ReadDir(dir, "pg_wal")) != NULL)
450 {
451 /* Does it look like a WAL segment, and is it in the range? */
452 if (IsXLogFileName(de->d_name) &&
453 strcmp(de->d_name + 8, firstoff + 8) >= 0 &&
454 strcmp(de->d_name + 8, lastoff + 8) <= 0)
455 {
457 }
458 /* Does it look like a timeline history file? */
459 else if (IsTLHistoryFileName(de->d_name))
460 {
462 }
463 }
464 FreeDir(dir);
465
466 /*
467 * Before we go any further, check that none of the WAL segments we
468 * need were removed.
469 */
471
472 /*
473 * Sort the WAL filenames. We want to send the files in order from
474 * oldest to newest, to reduce the chance that a file is recycled
475 * before we get a chance to send it over.
476 */
478
479 /*
480 * There must be at least one xlog file in the pg_wal directory, since
481 * we are doing backup-including-xlog.
482 */
483 if (walFileList == NIL)
485 (errmsg("could not find any WAL files")));
486
487 /*
488 * Sanity check: the first and last segment should cover startptr and
489 * endptr, with no gaps in between.
490 */
492 &tli, &segno, wal_segment_size);
493 if (segno != startsegno)
494 {
496
500 (errmsg("could not find WAL file \"%s\"", startfname)));
501 }
502 foreach(lc, walFileList)
503 {
504 char *walFileName = (char *) lfirst(lc);
505 XLogSegNo currsegno = segno;
506 XLogSegNo nextsegno = segno + 1;
507
509 if (!(nextsegno == segno || currsegno == segno))
510 {
512
515 (errmsg("could not find WAL file \"%s\"", nextfname)));
516 }
517 }
518 if (segno != endsegno)
519 {
520 char endfname[MAXFNAMELEN];
521
524 (errmsg("could not find WAL file \"%s\"", endfname)));
525 }
526
527 /* Ok, we have everything we need. Send the WAL files. */
528 foreach(lc, walFileList)
529 {
530 char *walFileName = (char *) lfirst(lc);
531 int fd;
532 ssize_t cnt;
533 pgoff_t len = 0;
534
537
539 if (fd < 0)
540 {
541 int save_errno = errno;
542
543 /*
544 * Most likely reason for this is that the file was already
545 * removed by a checkpoint, so check for that to get a better
546 * error message.
547 */
548 CheckXLogRemoved(segno, tli);
549
553 errmsg("could not open file \"%s\": %m", pathbuf)));
554 }
555
556 if (fstat(fd, &statbuf) != 0)
559 errmsg("could not stat file \"%s\": %m",
560 pathbuf)));
561 if (statbuf.st_size != wal_segment_size)
562 {
563 CheckXLogRemoved(segno, tli);
566 errmsg("unexpected WAL file size \"%s\"", walFileName)));
567 }
568
569 /* send the WAL file itself */
571
572 while ((cnt = basebackup_read_file(fd, sink->bbs_buffer,
573 Min(sink->bbs_buffer_length,
575 len, pathbuf, true)) > 0)
576 {
577 CheckXLogRemoved(segno, tli);
579
580 len += cnt;
581
582 if (len == wal_segment_size)
583 break;
584 }
585
586 if (len != wal_segment_size)
587 {
588 CheckXLogRemoved(segno, tli);
591 errmsg("unexpected WAL file size \"%s\"", walFileName)));
592 }
593
594 /*
595 * wal_segment_size is a multiple of TAR_BLOCK_SIZE, so no need
596 * for padding.
597 */
599
601
602 /*
603 * Mark file as archived, otherwise files can get archived again
604 * after promotion of a new node. This is in line with
605 * walreceiver.c always doing an XLogArchiveForceDone() after a
606 * complete segment.
607 */
610 }
611
612 /*
613 * Send timeline history files too. Only the latest timeline history
614 * file is required for recovery, and even that only if there happens
615 * to be a timeline switch in the first WAL segment that contains the
616 * checkpoint record, or if we're taking a base backup from a standby
617 * server and the target timeline changes while the backup is taken.
618 * But they are small and highly useful for debugging purposes, so
619 * better include them all, always.
620 */
621 foreach(lc, historyFileList)
622 {
623 char *fname = lfirst(lc);
624
625 snprintf(pathbuf, MAXPGPATH, XLOGDIR "/%s", fname);
626
627 if (lstat(pathbuf, &statbuf) != 0)
630 errmsg("could not stat file \"%s\": %m", pathbuf)));
631
634 &manifest, 0, NULL, 0);
635
636 /* unconditionally mark file as archived */
637 StatusFilePath(pathbuf, fname, ".done");
639 }
640
641 /* Properly terminate the tar file. */
644
645 /* OK, that's the end of the archive. */
647 }
648
649 AddWALInfoToBackupManifest(&manifest, state.startptr, state.starttli,
650 endptr, endtli);
651
653
654 bbsink_end_backup(sink, endptr, endtli);
655
657 {
660 (errmsg_plural("%lld total checksum verification failure",
661 "%lld total checksum verification failures",
664
667 errmsg("checksum verification failure during base backup")));
668 }
669
670 /*
671 * Make sure to free the manifest before the resource owners as manifests
672 * use cryptohash contexts that may depend on resource owners (like
673 * OpenSSL).
674 */
676
677 /* clean up the resource owner we created */
679}
void InitializeBackupManifest(backup_manifest_info *manifest, backup_manifest_option want_manifest, pg_checksum_type manifest_checksum_type)
void AddWALInfoToBackupManifest(backup_manifest_info *manifest, XLogRecPtr startptr, TimeLineID starttli, XLogRecPtr endptr, TimeLineID endtli)
void SendBackupManifest(backup_manifest_info *manifest, bbsink *sink)
void FreeBackupManifest(backup_manifest_info *manifest)
static bool sendFile(bbsink *sink, const char *readfilename, const char *tarfilename, struct stat *statbuf, bool missing_ok, Oid dboid, Oid spcoid, RelFileNumber relfilenumber, unsigned segno, backup_manifest_info *manifest, unsigned num_incremental_blocks, BlockNumber *incremental_blocks, unsigned truncation_block_length)
static int compareWalFileNames(const ListCell *a, const ListCell *b)
Definition basebackup.c:686
static void sendFileWithContent(bbsink *sink, const char *filename, const char *content, int len, backup_manifest_info *manifest)
static int64 sendDir(bbsink *sink, const char *path, int basepathlen, bool sizeonly, List *tablespaces, bool sendtblspclinks, backup_manifest_info *manifest, Oid spcoid, IncrementalBackupInfo *ib)
#define SINK_BUFFER_LENGTH
Definition basebackup.c:61
static bool backup_started_in_recovery
Definition basebackup.c:129
static int64 _tarWriteHeader(bbsink *sink, const char *filename, const char *linktarget, struct stat *statbuf, bool sizeonly)
static int64 sendTablespace(bbsink *sink, char *path, Oid spcoid, bool sizeonly, struct backup_manifest_info *manifest, IncrementalBackupInfo *ib)
static ssize_t basebackup_read_file(int fd, char *buf, size_t nbytes, off_t offset, const char *filename, bool partial_read_ok)
#define TAR_NUM_TERMINATION_BLOCKS
Definition basebackup.c:82
static long long int total_checksum_failures
Definition basebackup.c:132
void PrepareForIncrementalBackup(IncrementalBackupInfo *ib, BackupState *backup_state)
void basebackup_progress_wait_checkpoint(void)
void basebackup_progress_wait_wal_archive(bbsink_state *state)
void basebackup_progress_transfer_wal(void)
void basebackup_progress_estimate_backup_size(void)
static void bbsink_begin_backup(bbsink *sink, bbsink_state *state, int buffer_length)
static void bbsink_begin_archive(bbsink *sink, const char *archive_name)
static void bbsink_end_archive(bbsink *sink)
static void bbsink_end_backup(bbsink *sink, XLogRecPtr endptr, TimeLineID endtli)
#define Min(x, y)
Definition c.h:1150
#define PG_BINARY
Definition c.h:1445
#define WARNING
Definition elog.h:37
int int int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...) pg_attribute_printf(1
int FreeDir(DIR *dir)
Definition fd.c:3009
int CloseTransientFile(int fd)
Definition fd.c:2855
DIR * AllocateDir(const char *dirname)
Definition fd.c:2891
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition fd.c:2957
int OpenTransientFile(const char *fileName, int fileFlags)
Definition fd.c:2678
#define palloc0_object(type)
Definition fe_memutils.h:90
#define PG_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition ipc.h:47
#define PG_END_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition ipc.h:52
List * lappend(List *list, void *datum)
Definition list.c:339
void list_sort(List *list, list_sort_comparator cmp)
Definition list.c:1674
char * pstrdup(const char *in)
Definition mcxt.c:1910
void pfree(void *pointer)
Definition mcxt.c:1619
static bool manifest
#define ERRCODE_DATA_CORRUPTED
#define MAXPGPATH
#define NIL
Definition pg_list.h:68
#define linitial(l)
Definition pg_list.h:178
static ListCell * lnext(const List *l, const ListCell *c)
Definition pg_list.h:375
#define snprintf
Definition port.h:261
off_t pgoff_t
Definition port.h:422
static Datum BoolGetDatum(bool X)
Definition postgres.h:112
#define InvalidOid
char * psprintf(const char *fmt,...)
Definition psprintf.c:43
#define InvalidRelFileNumber
Definition relpath.h:26
void ReleaseAuxProcessResources(bool isCommit)
Definition resowner.c:1026
ResourceOwner CurrentResourceOwner
Definition resowner.c:173
ResourceOwner AuxProcessResourceOwner
Definition resowner.c:176
void initStringInfo(StringInfo str)
Definition stringinfo.c:97
TimeLineID starttli
Definition xlogbackup.h:27
XLogRecPtr startpoint
Definition xlogbackup.h:26
TimeLineID stoptli
Definition xlogbackup.h:36
XLogRecPtr stoppoint
Definition xlogbackup.h:35
Definition dirent.c:26
Definition pg_list.h:54
#define lstat(path, sb)
Definition win32_port.h:275
#define fstat
Definition win32_port.h:73
bool RecoveryInProgress(void)
Definition xlog.c:6836
void do_pg_abort_backup(int code, Datum arg)
Definition xlog.c:10055
void CheckXLogRemoved(XLogSegNo segno, TimeLineID tli)
Definition xlog.c:3778
int wal_segment_size
Definition xlog.c:150
void do_pg_backup_start(const char *backupidstr, bool fast, List **tablespaces, BackupState *state, StringInfo tblspcmapfile)
Definition xlog.c:9459
void do_pg_backup_stop(BackupState *state, bool waitforarchive)
Definition xlog.c:9781
#define TABLESPACE_MAP
Definition xlog.h:337
#define BACKUP_LABEL_FILE
Definition xlog.h:334
#define XLOG_CONTROL_FILE
static bool IsXLogFileName(const char *fname)
static void XLogFromFileName(const char *fname, TimeLineID *tli, XLogSegNo *logSegNo, int wal_segsz_bytes)
#define XLByteToPrevSeg(xlrp, logSegNo, wal_segsz_bytes)
static bool IsTLHistoryFileName(const char *fname)
#define MAXFNAMELEN
#define XLOGDIR
static void StatusFilePath(char *path, const char *xlog, const char *suffix)
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)
static void XLogFileName(char *fname, TimeLineID tli, XLogSegNo logSegNo, int wal_segsz_bytes)
char * build_backup_content(BackupState *state, bool ishistoryfile)
Definition xlogbackup.c:29
uint64 XLogRecPtr
Definition xlogdefs.h:21
uint32 TimeLineID
Definition xlogdefs.h:63
uint64 XLogSegNo
Definition xlogdefs.h:52
static BackupState * backup_state
Definition xlogfuncs.c:44
static StringInfo tablespace_map
Definition xlogfuncs.c:45

References _tarWriteHeader(), AddWALInfoToBackupManifest(), AllocateDir(), Assert, AuxProcessResourceOwner, BACKUP_LABEL_FILE, backup_started_in_recovery, backup_state, basebackup_progress_estimate_backup_size(), basebackup_progress_transfer_wal(), basebackup_progress_wait_checkpoint(), basebackup_progress_wait_wal_archive(), basebackup_read_file(), bbsink_archive_contents(), bbsink_begin_archive(), bbsink_begin_backup(), bbsink_end_archive(), bbsink_end_backup(), BoolGetDatum(), build_backup_content(), CheckXLogRemoved(), CloseTransientFile(), compareWalFileNames(), CurrentResourceOwner, StringInfoData::data, do_pg_abort_backup(), do_pg_backup_start(), do_pg_backup_stop(), ereport, errcode(), ERRCODE_DATA_CORRUPTED, errcode_for_file_access(), errmsg, errmsg_plural(), ERROR, basebackup_options::fastcheckpoint, fb(), fd(), FreeBackupManifest(), FreeDir(), fstat, basebackup_options::includewal, InitializeBackupManifest(), initStringInfo(), InvalidOid, InvalidRelFileNumber, IsTLHistoryFileName(), IsXLogFileName(), basebackup_options::label, lappend(), len, lfirst, linitial, list_sort(), lnext(), lstat, basebackup_options::manifest, manifest, basebackup_options::manifest_checksum_type, MAXFNAMELEN, MAXPGPATH, Min, NIL, basebackup_options::nowait, tablespaceinfo::oid, OpenTransientFile(), palloc0_object, tablespaceinfo::path, pfree(), PG_BINARY, PG_END_ENSURE_ERROR_CLEANUP, PG_ENSURE_ERROR_CLEANUP, PrepareForIncrementalBackup(), basebackup_options::progress, psprintf(), pstrdup(), ReadDir(), RecoveryInProgress(), ReleaseAuxProcessResources(), SendBackupManifest(), sendDir(), sendFile(), sendFileWithContent(), sendTablespace(), basebackup_options::sendtblspcmapfile, SINK_BUFFER_LENGTH, tablespaceinfo::size, snprintf, BackupState::startpoint, BackupState::starttli, StatusFilePath(), BackupState::stoppoint, BackupState::stoptli, tablespace_map, TABLESPACE_MAP, TAR_BLOCK_SIZE, TAR_NUM_TERMINATION_BLOCKS, total_checksum_failures, wal_segment_size, WARNING, XLByteToPrevSeg, XLByteToSeg, XLOG_CONTROL_FILE, XLOGDIR, XLogFileName(), and XLogFromFileName().

Referenced by SendBaseBackup().

◆ push_to_sink()

static void push_to_sink ( bbsink sink,
pg_checksum_context checksum_ctx,
size_t bytes_done,
void data,
size_t  length 
)
static

Definition at line 1967 of file basebackup.c.

1969{
1970 while (length > 0)
1971 {
1972 size_t bytes_to_copy;
1973
1974 /*
1975 * We use < here rather than <= so that if the data exactly fills the
1976 * remaining buffer space, we trigger a flush now.
1977 */
1978 if (length < sink->bbs_buffer_length - *bytes_done)
1979 {
1980 /* Append remaining data to buffer. */
1981 memcpy(sink->bbs_buffer + *bytes_done, data, length);
1982 *bytes_done += length;
1983 return;
1984 }
1985
1986 /* Copy until buffer is full and flush it. */
1987 bytes_to_copy = sink->bbs_buffer_length - *bytes_done;
1988 memcpy(sink->bbs_buffer + *bytes_done, data, bytes_to_copy);
1989 data = ((char *) data) + bytes_to_copy;
1990 length -= bytes_to_copy;
1991 bbsink_archive_contents(sink, sink->bbs_buffer_length);
1992 if (pg_checksum_update(checksum_ctx, (uint8 *) sink->bbs_buffer,
1993 sink->bbs_buffer_length) < 0)
1994 elog(ERROR, "could not update checksum");
1995 *bytes_done = 0;
1996 }
1997}
uint8_t uint8
Definition c.h:681
memcpy(sums, checksumBaseOffsets, sizeof(checksumBaseOffsets))
int pg_checksum_update(pg_checksum_context *context, const uint8 *input, size_t len)
const void * data

References bbsink_archive_contents(), data, elog, ERROR, fb(), memcpy(), and pg_checksum_update().

Referenced by sendFile().

◆ read_file_data_into_buffer()

static off_t read_file_data_into_buffer ( bbsink sink,
const char readfilename,
int  fd,
off_t  offset,
size_t  length,
BlockNumber  blkno,
bool  verify_checksum,
int checksum_failures 
)
static

Definition at line 1852 of file basebackup.c.

1855{
1856 off_t cnt;
1857 int i;
1858 char *page;
1859
1860 /* Try to read some more data. */
1861 cnt = basebackup_read_file(fd, sink->bbs_buffer,
1862 Min(sink->bbs_buffer_length, length),
1863 offset, readfilename, true);
1864
1865 /* Can't verify checksums if read length is not a multiple of BLCKSZ. */
1866 if (!verify_checksum || (cnt % BLCKSZ) != 0)
1867 return cnt;
1868
1869 /* Verify checksum for each block. */
1870 for (i = 0; i < cnt / BLCKSZ; i++)
1871 {
1872 int reread_cnt;
1874
1875 /*
1876 * The data checksum state can change at any point, so we need to
1877 * re-check before each page.
1878 */
1880 return cnt;
1881
1882 page = sink->bbs_buffer + BLCKSZ * i;
1883
1884 /* If the page is OK, go on to the next one. */
1885 if (verify_page_checksum(page, sink->bbs_state->startptr, blkno + i,
1887 continue;
1888
1889 /*
1890 * Retry the block on the first failure. It's possible that we read
1891 * the first 4K page of the block just before postgres updated the
1892 * entire block so it ends up looking torn to us. If, before we retry
1893 * the read, the concurrent write of the block finishes, the page LSN
1894 * will be updated and we'll realize that we should ignore this block.
1895 *
1896 * There's no guarantee that this will actually happen, though: the
1897 * torn write could take an arbitrarily long time to complete.
1898 * Retrying multiple times wouldn't fix this problem, either, though
1899 * it would reduce the chances of it happening in practice. The only
1900 * real fix here seems to be to have some kind of interlock that
1901 * allows us to wait until we can be certain that no write to the
1902 * block is in progress. Since we don't have any such thing right now,
1903 * we just do this and hope for the best.
1904 *
1905 * The data checksum state may also have changed concurrently so check
1906 * again.
1907 */
1909 return cnt;
1910 reread_cnt =
1911 basebackup_read_file(fd, sink->bbs_buffer + BLCKSZ * i,
1912 BLCKSZ, offset + BLCKSZ * i,
1913 readfilename, false);
1914 if (reread_cnt == 0)
1915 {
1916 /*
1917 * If we hit end-of-file, a concurrent truncation must have
1918 * occurred, so reduce cnt to reflect only the blocks already
1919 * processed and break out of this loop.
1920 */
1921 cnt = BLCKSZ * i;
1922 break;
1923 }
1924
1925 /* If the page now looks OK, go on to the next one. */
1926 if (verify_page_checksum(page, sink->bbs_state->startptr, blkno + i,
1928 continue;
1929
1930 /* Handle checksum failure. */
1931 (*checksum_failures)++;
1932 if (*checksum_failures <= 5)
1934 (errmsg("checksum verification failed in "
1935 "file \"%s\", block %u: calculated "
1936 "%X but expected %X",
1938 ((PageHeader) page)->pd_checksum)));
1939 if (*checksum_failures == 5)
1941 (errmsg("further checksum verification "
1942 "failures in file \"%s\" will not "
1943 "be reported", readfilename)));
1944 }
1945
1946 return cnt;
1947}
static bool verify_page_checksum(Page page, XLogRecPtr start_lsn, BlockNumber blkno, uint16 *expected_checksum)
uint16_t uint16
Definition c.h:682
int i
Definition isn.c:77
bool DataChecksumsNeedVerify(void)
Definition xlog.c:4733

References basebackup_read_file(), DataChecksumsNeedVerify(), ereport, errmsg, fb(), fd(), i, Min, verify_page_checksum(), and WARNING.

Referenced by sendFile().

◆ SendBaseBackup()

void SendBaseBackup ( BaseBackupCmd cmd,
IncrementalBackupInfo ib 
)

Definition at line 990 of file basebackup.c.

991{
993 bbsink *sink;
995
996 if (status == SESSION_BACKUP_RUNNING)
999 errmsg("a backup is already in progress in this session")));
1000
1002
1004
1006 {
1007 char activitymsg[50];
1008
1009 snprintf(activitymsg, sizeof(activitymsg), "sending backup \"%s\"",
1010 opt.label);
1012 }
1013
1014 /*
1015 * If we're asked to perform an incremental backup and the user has not
1016 * supplied a manifest, that's an ERROR.
1017 *
1018 * If we're asked to perform a full backup and the user did supply a
1019 * manifest, just ignore it.
1020 */
1021 if (!opt.incremental)
1022 ib = NULL;
1023 else if (ib == NULL)
1024 ereport(ERROR,
1026 errmsg("must UPLOAD_MANIFEST before performing an incremental BASE_BACKUP")));
1027
1028 /*
1029 * If the target is specifically 'client' then set up to stream the backup
1030 * to the client; otherwise, it's being sent someplace else and should not
1031 * be sent to the client. BaseBackupGetSink has the job of setting up a
1032 * sink to send the backup data wherever it needs to go.
1033 */
1035 if (opt.target_handle != NULL)
1037
1038 /* Set up network throttling, if client requested it */
1039 if (opt.maxrate > 0)
1041
1042 /* Set up server-side compression, if client requested it */
1045 else if (opt.compression == PG_COMPRESSION_LZ4)
1047 else if (opt.compression == PG_COMPRESSION_ZSTD)
1049
1050 /* Set up progress reporting. */
1052
1053 /*
1054 * Perform the base backup, but make sure we clean up the bbsink even if
1055 * an error occurs.
1056 */
1057 PG_TRY();
1058 {
1059 perform_base_backup(&opt, sink, ib);
1060 }
1061 PG_FINALLY();
1062 {
1064 }
1065 PG_END_TRY();
1066}
static void parse_basebackup_options(List *options, basebackup_options *opt)
Definition basebackup.c:698
static void perform_base_backup(basebackup_options *opt, bbsink *sink, IncrementalBackupInfo *ib)
Definition basebackup.c:240
bbsink * bbsink_copystream_new(bool send_to_client)
bbsink * bbsink_gzip_new(bbsink *next, pg_compress_specification *compress)
bbsink * bbsink_lz4_new(bbsink *next, pg_compress_specification *compress)
bbsink * bbsink_progress_new(bbsink *next, bool estimate_backup_size, bool incremental)
static void bbsink_cleanup(bbsink *sink)
bbsink * BaseBackupGetSink(BaseBackupTargetHandle *handle, bbsink *next_sink)
bbsink * bbsink_throttle_new(bbsink *next, uint32 maxrate)
bbsink * bbsink_zstd_new(bbsink *next, pg_compress_specification *compress)
@ PG_COMPRESSION_GZIP
Definition compression.h:24
@ PG_COMPRESSION_LZ4
Definition compression.h:25
@ PG_COMPRESSION_ZSTD
Definition compression.h:26
#define PG_TRY(...)
Definition elog.h:374
#define PG_END_TRY(...)
Definition elog.h:399
#define PG_FINALLY(...)
Definition elog.h:391
bool update_process_title
Definition ps_status.c:31
static void set_ps_display(const char *activity)
Definition ps_status.h:40
List * options
Definition replnodes.h:44
void WalSndSetState(WalSndState state)
Definition walsender.c:4177
@ WALSNDSTATE_BACKUP
SessionBackupState get_backup_status(void)
Definition xlog.c:9762
SessionBackupState
Definition xlog.h:318
@ SESSION_BACKUP_RUNNING
Definition xlog.h:320

References BaseBackupGetSink(), bbsink_cleanup(), bbsink_copystream_new(), bbsink_gzip_new(), bbsink_lz4_new(), bbsink_progress_new(), bbsink_throttle_new(), bbsink_zstd_new(), basebackup_options::compression, basebackup_options::compression_specification, ereport, errcode(), errmsg, ERROR, fb(), get_backup_status(), basebackup_options::incremental, basebackup_options::label, basebackup_options::maxrate, BaseBackupCmd::options, parse_basebackup_options(), perform_base_backup(), PG_COMPRESSION_GZIP, PG_COMPRESSION_LZ4, PG_COMPRESSION_ZSTD, PG_END_TRY, PG_FINALLY, PG_TRY, basebackup_options::progress, basebackup_options::send_to_client, SESSION_BACKUP_RUNNING, set_ps_display(), snprintf, basebackup_options::target_handle, update_process_title, WalSndSetState(), and WALSNDSTATE_BACKUP.

Referenced by exec_replication_command().

◆ sendDir()

static int64 sendDir ( bbsink sink,
const char path,
int  basepathlen,
bool  sizeonly,
List tablespaces,
bool  sendtblspclinks,
backup_manifest_info manifest,
Oid  spcoid,
IncrementalBackupInfo ib 
)
static

Definition at line 1189 of file basebackup.c.

1192{
1193 DIR *dir;
1194 struct dirent *de;
1195 char pathbuf[MAXPGPATH * 2];
1196 struct stat statbuf;
1197 int64 size = 0;
1198 const char *lastDir; /* Split last dir from parent path. */
1199 bool isRelationDir = false; /* Does directory contain relations? */
1200 bool isGlobalDir = false;
1201 Oid dboid = InvalidOid;
1202 BlockNumber *relative_block_numbers = NULL;
1203
1204 /*
1205 * Since this array is relatively large, avoid putting it on the stack.
1206 * But we don't need it at all if this is not an incremental backup.
1207 */
1208 if (ib != NULL)
1209 relative_block_numbers = palloc_array(BlockNumber, RELSEG_SIZE);
1210
1211 /*
1212 * Determine if the current path is a database directory that can contain
1213 * relations.
1214 *
1215 * Start by finding the location of the delimiter between the parent path
1216 * and the current path.
1217 */
1219
1220 /* Does this path look like a database path (i.e. all digits)? */
1221 if (lastDir != NULL &&
1222 strspn(lastDir + 1, "0123456789") == strlen(lastDir + 1))
1223 {
1224 /* Part of path that contains the parent directory. */
1225 int parentPathLen = lastDir - path;
1226
1227 /*
1228 * Mark path as a database directory if the parent path is either
1229 * $PGDATA/base or a tablespace version path.
1230 */
1231 if (strncmp(path, "./base", parentPathLen) == 0 ||
1232 (parentPathLen >= (sizeof(TABLESPACE_VERSION_DIRECTORY) - 1) &&
1235 sizeof(TABLESPACE_VERSION_DIRECTORY) - 1) == 0))
1236 {
1237 isRelationDir = true;
1238 dboid = atooid(lastDir + 1);
1239 }
1240 }
1241 else if (strcmp(path, "./global") == 0)
1242 {
1243 isRelationDir = true;
1244 isGlobalDir = true;
1245 }
1246
1247 dir = AllocateDir(path);
1248 while ((de = ReadDir(dir, path)) != NULL)
1249 {
1250 int excludeIdx;
1251 bool excludeFound;
1252 RelFileNumber relfilenumber = InvalidRelFileNumber;
1254 unsigned segno = 0;
1255 bool isRelationFile = false;
1256
1257 /* Skip special stuff */
1258 if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
1259 continue;
1260
1261 /* Skip temporary files */
1262 if (strncmp(de->d_name,
1265 continue;
1266
1267 /* Skip macOS system files */
1268 if (strcmp(de->d_name, ".DS_Store") == 0)
1269 continue;
1270
1271 /*
1272 * Check if the postmaster has signaled us to exit, and abort with an
1273 * error in that case. The error handler further up will call
1274 * do_pg_abort_backup() for us. Also check that if the backup was
1275 * started while still in recovery, the server wasn't promoted.
1276 * do_pg_backup_stop() will check that too, but it's better to stop
1277 * the backup early than continue to the end and fail there.
1278 */
1281 ereport(ERROR,
1283 errmsg("the standby was promoted during online backup"),
1284 errhint("This means that the backup being taken is corrupt "
1285 "and should not be used. "
1286 "Try taking another online backup.")));
1287
1288 /* Scan for files that should be excluded */
1289 excludeFound = false;
1291 {
1293
1294 if (!excludeFiles[excludeIdx].match_prefix)
1295 cmplen++;
1296 if (strncmp(de->d_name, excludeFiles[excludeIdx].name, cmplen) == 0)
1297 {
1298 elog(DEBUG1, "file \"%s\" excluded from backup", de->d_name);
1299 excludeFound = true;
1300 break;
1301 }
1302 }
1303
1304 if (excludeFound)
1305 continue;
1306
1307 /*
1308 * If there could be non-temporary relation files in this directory,
1309 * try to parse the filename.
1310 */
1311 if (isRelationDir)
1314 &relfilenumber,
1315 &relForkNum, &segno);
1316
1317 /* Exclude all forks for unlogged tables except the init fork */
1319 {
1320 char initForkFile[MAXPGPATH];
1321
1322 /*
1323 * If any other type of fork, check if there is an init fork with
1324 * the same RelFileNumber. If so, the file can be excluded.
1325 */
1326 snprintf(initForkFile, sizeof(initForkFile), "%s/%u_init",
1327 path, relfilenumber);
1328
1329 if (lstat(initForkFile, &statbuf) == 0)
1330 {
1331 elog(DEBUG2,
1332 "unlogged relation file \"%s\" excluded from backup",
1333 de->d_name);
1334
1335 continue;
1336 }
1337 }
1338
1339 /* Exclude temporary relations */
1340 if (OidIsValid(dboid) && looks_like_temp_rel_name(de->d_name))
1341 {
1342 elog(DEBUG2,
1343 "temporary relation file \"%s\" excluded from backup",
1344 de->d_name);
1345
1346 continue;
1347 }
1348
1349 snprintf(pathbuf, sizeof(pathbuf), "%s/%s", path, de->d_name);
1350
1351 /* Skip pg_control here to back up it last */
1352 if (strcmp(pathbuf, "./" XLOG_CONTROL_FILE) == 0)
1353 continue;
1354
1355 if (lstat(pathbuf, &statbuf) != 0)
1356 {
1357 if (errno != ENOENT)
1358 ereport(ERROR,
1360 errmsg("could not stat file or directory \"%s\": %m",
1361 pathbuf)));
1362
1363 /* If the file went away while scanning, it's not an error. */
1364 continue;
1365 }
1366
1367 /* Scan for directories whose contents should be excluded */
1368 excludeFound = false;
1370 {
1371 if (strcmp(de->d_name, excludeDirContents[excludeIdx]) == 0)
1372 {
1373 elog(DEBUG1, "contents of directory \"%s\" excluded from backup", de->d_name);
1376 &statbuf, sizeonly);
1377 excludeFound = true;
1378 break;
1379 }
1380 }
1381
1382 if (excludeFound)
1383 continue;
1384
1385 /*
1386 * We can skip pg_wal, the WAL segments need to be fetched from the
1387 * WAL archive anyway. But include it as an empty directory anyway, so
1388 * we get permissions right.
1389 */
1390 if (strcmp(pathbuf, "./pg_wal") == 0)
1391 {
1392 /* If pg_wal is a symlink, write it as a directory anyway */
1395 &statbuf, sizeonly);
1396
1397 /*
1398 * Also send archive_status and summaries directories (by
1399 * hackishly reusing statbuf from above ...).
1400 */
1401 size += _tarWriteHeader(sink, "./pg_wal/archive_status", NULL,
1402 &statbuf, sizeonly);
1403 size += _tarWriteHeader(sink, "./pg_wal/summaries", NULL,
1404 &statbuf, sizeonly);
1405
1406 continue; /* don't recurse into pg_wal */
1407 }
1408
1409 /* Allow symbolic links in pg_tblspc only */
1410 if (strcmp(path, "./pg_tblspc") == 0 && S_ISLNK(statbuf.st_mode))
1411 {
1412 char linkpath[MAXPGPATH];
1413 int rllen;
1414
1415 rllen = readlink(pathbuf, linkpath, sizeof(linkpath));
1416 if (rllen < 0)
1417 ereport(ERROR,
1419 errmsg("could not read symbolic link \"%s\": %m",
1420 pathbuf)));
1421 if (rllen >= sizeof(linkpath))
1422 ereport(ERROR,
1424 errmsg("symbolic link \"%s\" target is too long",
1425 pathbuf)));
1426 linkpath[rllen] = '\0';
1427
1429 &statbuf, sizeonly);
1430 }
1431 else if (S_ISDIR(statbuf.st_mode))
1432 {
1433 bool skip_this_dir = false;
1434 ListCell *lc;
1435
1436 /*
1437 * Store a directory entry in the tar file so we can get the
1438 * permissions right.
1439 */
1441 sizeonly);
1442
1443 /*
1444 * Call ourselves recursively for a directory, unless it happens
1445 * to be a separate tablespace located within PGDATA.
1446 */
1447 foreach(lc, tablespaces)
1448 {
1450
1451 /*
1452 * ti->rpath is the tablespace relative path within PGDATA, or
1453 * NULL if the tablespace has been properly located somewhere
1454 * else.
1455 *
1456 * Skip past the leading "./" in pathbuf when comparing.
1457 */
1458 if (ti->rpath && strcmp(ti->rpath, pathbuf + 2) == 0)
1459 {
1460 skip_this_dir = true;
1461 break;
1462 }
1463 }
1464
1465 /*
1466 * skip sending directories inside pg_tblspc, if not required.
1467 */
1468 if (strcmp(pathbuf, "./pg_tblspc") == 0 && !sendtblspclinks)
1469 skip_this_dir = true;
1470
1471 if (!skip_this_dir)
1472 size += sendDir(sink, pathbuf, basepathlen, sizeonly, tablespaces,
1474 }
1475 else if (S_ISREG(statbuf.st_mode))
1476 {
1477 bool sent = false;
1478 unsigned num_blocks_required = 0;
1479 unsigned truncation_block_length = 0;
1480 char tarfilenamebuf[MAXPGPATH * 2];
1481 char *tarfilename = pathbuf + basepathlen + 1;
1483
1484 if (ib != NULL && isRelationFile)
1485 {
1486 Oid relspcoid;
1487 char *lookup_path;
1488
1489 if (OidIsValid(spcoid))
1490 {
1491 relspcoid = spcoid;
1493 tarfilename);
1494 }
1495 else
1496 {
1497 if (isGlobalDir)
1499 else
1501 lookup_path = pstrdup(tarfilename);
1502 }
1503
1504 method = GetFileBackupMethod(ib, lookup_path, dboid, relspcoid,
1505 relfilenumber, relForkNum,
1506 segno, statbuf.st_size,
1508 relative_block_numbers,
1509 &truncation_block_length);
1510 if (method == BACK_UP_FILE_INCREMENTALLY)
1511 {
1512 statbuf.st_size =
1515 "%s/INCREMENTAL.%s",
1516 path + basepathlen + 1,
1517 de->d_name);
1518 tarfilename = tarfilenamebuf;
1519 }
1520
1522 }
1523
1524 if (!sizeonly)
1525 sent = sendFile(sink, pathbuf, tarfilename, &statbuf,
1526 true, dboid, spcoid,
1527 relfilenumber, segno, manifest,
1529 method == BACK_UP_FILE_INCREMENTALLY ? relative_block_numbers : NULL,
1530 truncation_block_length);
1531
1532 if (sent || sizeonly)
1533 {
1534 /* Add size. */
1535 size += statbuf.st_size;
1536
1537 /* Pad to a multiple of the tar block size. */
1538 size += tarPaddingBytesRequired(statbuf.st_size);
1539
1540 /* Size of the header for the file. */
1541 size += TAR_BLOCK_SIZE;
1542 }
1543 }
1544 else
1546 (errmsg("skipping special file \"%s\"", pathbuf)));
1547 }
1548
1549 if (relative_block_numbers != NULL)
1550 pfree(relative_block_numbers);
1551
1552 FreeDir(dir);
1553 return size;
1554}
static const struct exclude_list_item excludeFiles[]
Definition basebackup.c:197
static const char *const excludeDirContents[]
Definition basebackup.c:157
static void convert_link_to_directory(const char *pathbuf, struct stat *statbuf)
size_t GetIncrementalFileSize(unsigned num_blocks_required)
FileBackupMethod GetFileBackupMethod(IncrementalBackupInfo *ib, const char *path, Oid dboid, Oid spcoid, RelFileNumber relfilenumber, ForkNumber forknum, unsigned segno, size_t size, unsigned *num_blocks_required, BlockNumber *relative_block_numbers, unsigned *truncation_block_length)
@ BACK_UP_FILE_INCREMENTALLY
@ BACK_UP_FILE_FULLY
uint32 BlockNumber
Definition block.h:31
#define OidIsValid(objectId)
Definition c.h:917
int errhint(const char *fmt,...) pg_attribute_printf(1
#define DEBUG2
Definition elog.h:30
#define DEBUG1
Definition elog.h:31
bool looks_like_temp_rel_name(const char *name)
Definition fd.c:3499
#define palloc_array(type, count)
Definition fe_memutils.h:91
#define PG_TEMP_FILE_PREFIX
Definition file_utils.h:64
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:125
char * last_dir_separator(const char *filename)
Definition path.c:145
unsigned int Oid
#define atooid(x)
bool parse_filename_for_nontemp_relation(const char *name, RelFileNumber *relnumber, ForkNumber *fork, unsigned *segno)
Definition reinit.c:380
Oid RelFileNumber
Definition relpath.h:25
ForkNumber
Definition relpath.h:56
@ InvalidForkNumber
Definition relpath.h:57
@ INIT_FORKNUM
Definition relpath.h:61
#define PG_TBLSPC_DIR
Definition relpath.h:41
#define TABLESPACE_VERSION_DIRECTORY
Definition relpath.h:33
const char * name
Definition basebackup.c:145
const char * name
#define S_ISDIR(m)
Definition win32_port.h:315
#define readlink(path, buf, size)
Definition win32_port.h:226
#define S_ISREG(m)
Definition win32_port.h:318

References _tarWriteHeader(), AllocateDir(), atooid, BACK_UP_FILE_FULLY, BACK_UP_FILE_INCREMENTALLY, backup_started_in_recovery, CHECK_FOR_INTERRUPTS, convert_link_to_directory(), DEBUG1, DEBUG2, elog, ereport, errcode(), errcode_for_file_access(), errhint(), errmsg, ERROR, excludeDirContents, excludeFiles, fb(), FreeDir(), GetFileBackupMethod(), GetIncrementalFileSize(), INIT_FORKNUM, InvalidForkNumber, InvalidOid, InvalidRelFileNumber, last_dir_separator(), lfirst, looks_like_temp_rel_name(), lstat, manifest, MAXPGPATH, exclude_list_item::name, name, OidIsValid, palloc_array, parse_filename_for_nontemp_relation(), pfree(), PG_TBLSPC_DIR, PG_TEMP_FILE_PREFIX, psprintf(), pstrdup(), ReadDir(), readlink, RecoveryInProgress(), S_ISDIR, S_ISLNK, S_ISREG, sendDir(), sendFile(), snprintf, TABLESPACE_VERSION_DIRECTORY, TAR_BLOCK_SIZE, tarPaddingBytesRequired(), WARNING, and XLOG_CONTROL_FILE.

Referenced by perform_base_backup(), sendDir(), and sendTablespace().

◆ sendFile()

static bool sendFile ( bbsink sink,
const char readfilename,
const char tarfilename,
struct stat statbuf,
bool  missing_ok,
Oid  dboid,
Oid  spcoid,
RelFileNumber  relfilenumber,
unsigned  segno,
backup_manifest_info manifest,
unsigned  num_incremental_blocks,
BlockNumber incremental_blocks,
unsigned  truncation_block_length 
)
static

Definition at line 1574 of file basebackup.c.

1579{
1580 int fd;
1581 BlockNumber blkno = 0;
1582 int checksum_failures = 0;
1583 off_t cnt;
1584 pgoff_t bytes_done = 0;
1585 bool verify_checksum = false;
1586 pg_checksum_context checksum_ctx;
1587 int ibindex = 0;
1588
1589 if (pg_checksum_init(&checksum_ctx, manifest->checksum_type) < 0)
1590 elog(ERROR, "could not initialize checksum of file \"%s\"",
1591 readfilename);
1592
1594 if (fd < 0)
1595 {
1596 if (errno == ENOENT && missing_ok)
1597 return false;
1598 ereport(ERROR,
1600 errmsg("could not open file \"%s\": %m", readfilename)));
1601 }
1602
1603 _tarWriteHeader(sink, tarfilename, NULL, statbuf, false);
1604
1605 /*
1606 * Checksums are verified in multiples of BLCKSZ, so the buffer length
1607 * should be a multiple of the block size as well.
1608 */
1609 Assert((sink->bbs_buffer_length % BLCKSZ) == 0);
1610
1611 /*
1612 * If we weren't told not to verify checksums, and if checksums are
1613 * enabled for this cluster, and if this is a relation file, then verify
1614 * the checksum. We cannot at this point check if checksums are enabled
1615 * or disabled as that might change, thus we check at each point where we
1616 * could be validating a checksum.
1617 */
1618 if (!noverify_checksums && RelFileNumberIsValid(relfilenumber))
1619 verify_checksum = true;
1620
1621 /*
1622 * If we're sending an incremental file, write the file header.
1623 */
1624 if (incremental_blocks != NULL)
1625 {
1626 unsigned magic = INCREMENTAL_MAGIC;
1627 size_t header_bytes_done = 0;
1628 char padding[BLCKSZ];
1629 size_t paddinglen;
1630
1631 /* Emit header data. */
1632 push_to_sink(sink, &checksum_ctx, &header_bytes_done,
1633 &magic, sizeof(magic));
1634 push_to_sink(sink, &checksum_ctx, &header_bytes_done,
1636 push_to_sink(sink, &checksum_ctx, &header_bytes_done,
1637 &truncation_block_length, sizeof(truncation_block_length));
1638 push_to_sink(sink, &checksum_ctx, &header_bytes_done,
1641
1642 /*
1643 * Add padding to align header to a multiple of BLCKSZ, but only if
1644 * the incremental file has some blocks, and the alignment is actually
1645 * needed (i.e. header is not already a multiple of BLCKSZ). If there
1646 * are no blocks we don't want to make the file unnecessarily large,
1647 * as that might make some filesystem optimizations impossible.
1648 */
1649 if ((num_incremental_blocks > 0) && (header_bytes_done % BLCKSZ != 0))
1650 {
1652
1653 memset(padding, 0, paddinglen);
1654 bytes_done += paddinglen;
1655
1656 push_to_sink(sink, &checksum_ctx, &header_bytes_done,
1657 padding, paddinglen);
1658 }
1659
1660 /* Flush out any data still in the buffer so it's again empty. */
1661 if (header_bytes_done > 0)
1662 {
1664 if (pg_checksum_update(&checksum_ctx,
1665 (uint8 *) sink->bbs_buffer,
1666 header_bytes_done) < 0)
1667 elog(ERROR, "could not update checksum of base backup");
1668 }
1669
1670 /* Update our notion of file position. */
1671 bytes_done += sizeof(magic);
1672 bytes_done += sizeof(num_incremental_blocks);
1673 bytes_done += sizeof(truncation_block_length);
1674 bytes_done += sizeof(BlockNumber) * num_incremental_blocks;
1675 }
1676
1677 /*
1678 * Loop until we read the amount of data the caller told us to expect. The
1679 * file could be longer, if it was extended while we were sending it, but
1680 * for a base backup we can ignore such extended data. It will be restored
1681 * from WAL.
1682 */
1683 while (1)
1684 {
1685 /*
1686 * Determine whether we've read all the data that we need, and if not,
1687 * read some more.
1688 */
1689 if (incremental_blocks == NULL)
1690 {
1691 size_t remaining = statbuf->st_size - bytes_done;
1692
1693 /*
1694 * If we've read the required number of bytes, then it's time to
1695 * stop.
1696 */
1697 if (bytes_done >= statbuf->st_size)
1698 break;
1699
1700 /*
1701 * Read as many bytes as will fit in the buffer, or however many
1702 * are left to read, whichever is less.
1703 */
1705 bytes_done, remaining,
1706 blkno + segno * RELSEG_SIZE,
1707 verify_checksum,
1708 &checksum_failures);
1709 }
1710 else
1711 {
1713
1714 /*
1715 * If we've read all the blocks, then it's time to stop.
1716 */
1718 break;
1719
1720 /*
1721 * Read just one block, whichever one is the next that we're
1722 * supposed to include.
1723 */
1727 BLCKSZ,
1728 relative_blkno + segno * RELSEG_SIZE,
1729 verify_checksum,
1730 &checksum_failures);
1731
1732 /*
1733 * If we get a partial read, that must mean that the relation is
1734 * being truncated. Ultimately, it should be truncated to a
1735 * multiple of BLCKSZ, since this path should only be reached for
1736 * relation files, but we might transiently observe an
1737 * intermediate value.
1738 *
1739 * It should be fine to treat this just as if the entire block had
1740 * been truncated away - i.e. fill this and all later blocks with
1741 * zeroes. WAL replay will fix things up.
1742 */
1743 if (cnt < BLCKSZ)
1744 break;
1745 }
1746
1747 /*
1748 * If the amount of data we were able to read was not a multiple of
1749 * BLCKSZ, we cannot verify checksums, which are block-level.
1750 */
1751 if (verify_checksum && DataChecksumsNeedVerify() && (cnt % BLCKSZ != 0))
1752 {
1754 (errmsg("could not verify checksum in file \"%s\", block "
1755 "%u: read buffer size %d and page size %d "
1756 "differ",
1757 readfilename, blkno, (int) cnt, BLCKSZ)));
1758 verify_checksum = false;
1759 }
1760
1761 /*
1762 * If we hit end-of-file, a concurrent truncation must have occurred.
1763 * That's not an error condition, because WAL replay will fix things
1764 * up.
1765 */
1766 if (cnt == 0)
1767 break;
1768
1769 /* Update block number and # of bytes done for next loop iteration. */
1770 blkno += cnt / BLCKSZ;
1771 bytes_done += cnt;
1772
1773 /*
1774 * Make sure incremental files with block data are properly aligned
1775 * (header is a multiple of BLCKSZ, blocks are BLCKSZ too).
1776 */
1778 (bytes_done % BLCKSZ != 0)));
1779
1780 /* Archive the data we just read. */
1782
1783 /* Also feed it to the checksum machinery. */
1784 if (pg_checksum_update(&checksum_ctx,
1785 (uint8 *) sink->bbs_buffer, cnt) < 0)
1786 elog(ERROR, "could not update checksum of base backup");
1787 }
1788
1789 /* If the file was truncated while we were sending it, pad it with zeros */
1790 while (bytes_done < statbuf->st_size)
1791 {
1792 size_t remaining = statbuf->st_size - bytes_done;
1793 size_t nbytes = Min(sink->bbs_buffer_length, remaining);
1794
1795 MemSet(sink->bbs_buffer, 0, nbytes);
1796 if (pg_checksum_update(&checksum_ctx,
1797 (uint8 *) sink->bbs_buffer,
1798 nbytes) < 0)
1799 elog(ERROR, "could not update checksum of base backup");
1801 bytes_done += nbytes;
1802 }
1803
1804 /*
1805 * Pad to a block boundary, per tar format requirements. (This small piece
1806 * of data is probably not worth throttling, and is not checksummed
1807 * because it's not actually part of the file.)
1808 */
1809 _tarWritePadding(sink, bytes_done);
1810
1812
1813 if (checksum_failures > 1)
1814 {
1816 (errmsg_plural("file \"%s\" has a total of %d checksum verification failure",
1817 "file \"%s\" has a total of %d checksum verification failures",
1818 checksum_failures,
1819 readfilename, checksum_failures)));
1820
1822 pgstat_report_checksum_failures_in_db(dboid, checksum_failures);
1823 }
1824
1825 total_checksum_failures += checksum_failures;
1826
1827 AddFileToBackupManifest(manifest, spcoid, tarfilename, statbuf->st_size,
1828 (pg_time_t) statbuf->st_mtime, &checksum_ctx);
1829
1830 return true;
1831}
void AddFileToBackupManifest(backup_manifest_info *manifest, Oid spcoid, const char *pathname, size_t size, pg_time_t mtime, pg_checksum_context *checksum_ctx)
static off_t read_file_data_into_buffer(bbsink *sink, const char *readfilename, int fd, off_t offset, size_t length, BlockNumber blkno, bool verify_checksum, int *checksum_failures)
static void push_to_sink(bbsink *sink, pg_checksum_context *checksum_ctx, size_t *bytes_done, void *data, size_t length)
static void _tarWritePadding(bbsink *sink, int len)
#define INCREMENTAL_MAGIC
int pg_checksum_init(pg_checksum_context *context, pg_checksum_type type)
int remaining
Definition informix.c:692
void pgstat_prepare_report_checksum_failure(Oid dboid)
void pgstat_report_checksum_failures_in_db(Oid dboid, int failurecount)
int64 pg_time_t
Definition pgtime.h:23
#define RelFileNumberIsValid(relnumber)
Definition relpath.h:27

References _tarWriteHeader(), _tarWritePadding(), AddFileToBackupManifest(), Assert, bbsink_archive_contents(), CloseTransientFile(), DataChecksumsNeedVerify(), elog, ereport, errcode_for_file_access(), errmsg, errmsg_plural(), ERROR, fb(), fd(), INCREMENTAL_MAGIC, manifest, MemSet, Min, noverify_checksums, OpenTransientFile(), PG_BINARY, pg_checksum_init(), pg_checksum_update(), pgstat_prepare_report_checksum_failure(), pgstat_report_checksum_failures_in_db(), push_to_sink(), read_file_data_into_buffer(), RelFileNumberIsValid, remaining, total_checksum_failures, and WARNING.

Referenced by perform_base_backup(), and sendDir().

◆ sendFileWithContent()

static void sendFileWithContent ( bbsink sink,
const char filename,
const char content,
int  len,
backup_manifest_info manifest 
)
static

Definition at line 1075 of file basebackup.c.

1077{
1078 struct stat statbuf;
1079 int bytes_done = 0;
1080 pg_checksum_context checksum_ctx;
1081
1082 if (pg_checksum_init(&checksum_ctx, manifest->checksum_type) < 0)
1083 elog(ERROR, "could not initialize checksum of file \"%s\"",
1084 filename);
1085
1086 if (len < 0)
1087 len = strlen(content);
1088
1089 /*
1090 * Construct a stat struct for the file we're injecting in the tar.
1091 */
1092
1093 /* Windows doesn't have the concept of uid and gid */
1094#ifdef WIN32
1095 statbuf.st_uid = 0;
1096 statbuf.st_gid = 0;
1097#else
1098 statbuf.st_uid = geteuid();
1099 statbuf.st_gid = getegid();
1100#endif
1101 statbuf.st_mtime = time(NULL);
1102 statbuf.st_mode = pg_file_create_mode;
1103 statbuf.st_size = len;
1104
1106
1107 if (pg_checksum_update(&checksum_ctx, (const uint8 *) content, len) < 0)
1108 elog(ERROR, "could not update checksum of file \"%s\"",
1109 filename);
1110
1111 while (bytes_done < len)
1112 {
1113 size_t remaining = len - bytes_done;
1114 size_t nbytes = Min(sink->bbs_buffer_length, remaining);
1115
1116 memcpy(sink->bbs_buffer, content, nbytes);
1118 bytes_done += nbytes;
1119 content += nbytes;
1120 }
1121
1123
1125 (pg_time_t) statbuf.st_mtime, &checksum_ctx);
1126}
int pg_file_create_mode
Definition file_perm.c:19

References _tarWriteHeader(), _tarWritePadding(), AddFileToBackupManifest(), bbsink_archive_contents(), elog, ERROR, fb(), filename, InvalidOid, len, manifest, memcpy(), Min, pg_checksum_init(), pg_checksum_update(), pg_file_create_mode, and remaining.

Referenced by perform_base_backup().

◆ sendTablespace()

static int64 sendTablespace ( bbsink sink,
char path,
Oid  spcoid,
bool  sizeonly,
struct backup_manifest_info manifest,
IncrementalBackupInfo ib 
)
static

Definition at line 1136 of file basebackup.c.

1138{
1139 int64 size;
1140 char pathbuf[MAXPGPATH];
1141 struct stat statbuf;
1142
1143 /*
1144 * 'path' points to the tablespace location, but we only want to include
1145 * the version directory in it that belongs to us.
1146 */
1147 snprintf(pathbuf, sizeof(pathbuf), "%s/%s", path,
1149
1150 /*
1151 * Store a directory entry in the tar file so we get the permissions
1152 * right.
1153 */
1154 if (lstat(pathbuf, &statbuf) != 0)
1155 {
1156 if (errno != ENOENT)
1157 ereport(ERROR,
1159 errmsg("could not stat file or directory \"%s\": %m",
1160 pathbuf)));
1161
1162 /* If the tablespace went away while scanning, it's no error. */
1163 return 0;
1164 }
1165
1167 sizeonly);
1168
1169 /* Send all the files in the tablespace version directory */
1170 size += sendDir(sink, pathbuf, strlen(path), sizeonly, NIL, true, manifest,
1171 spcoid, ib);
1172
1173 return size;
1174}

References _tarWriteHeader(), ereport, errcode_for_file_access(), errmsg, ERROR, fb(), lstat, manifest, MAXPGPATH, NIL, sendDir(), snprintf, and TABLESPACE_VERSION_DIRECTORY.

Referenced by perform_base_backup().

◆ StaticAssertDecl()

StaticAssertDecl ( TAR_NUM_TERMINATION_BLOCKS *TAR_BLOCK_SIZE<=  BLCKSZ,
"BLCKSZ too small for " CppAsString2(TAR_NUM_TERMINATION_BLOCKS) " tar termination blocks"   
)

◆ verify_page_checksum()

static bool verify_page_checksum ( Page  page,
XLogRecPtr  start_lsn,
BlockNumber  blkno,
uint16 expected_checksum 
)
static

Definition at line 2008 of file basebackup.c.

2010{
2011 PageHeader phdr;
2012 uint16 checksum;
2013
2014 /*
2015 * Only check pages which have not been modified since the start of the
2016 * base backup. Otherwise, they might have been written only halfway and
2017 * the checksum would not be valid. However, replaying WAL would
2018 * reinstate the correct page in this case. We also skip completely new
2019 * pages, since they don't have a checksum yet.
2020 */
2021 if (PageIsNew(page) || PageGetLSN(page) >= start_lsn)
2022 return true;
2023
2025 return true;
2026
2027 /* Perform the actual checksum calculation. */
2028 checksum = pg_checksum_page(page, blkno);
2029
2030 /* See whether it matches the value from the page. */
2031 phdr = (PageHeader) page;
2032 if (phdr->pd_checksum == checksum)
2033 return true;
2034 *expected_checksum = checksum;
2035 return false;
2036}
PageHeaderData * PageHeader
Definition bufpage.h:199
static bool PageIsNew(const PageData *page)
Definition bufpage.h:258
static XLogRecPtr PageGetLSN(const PageData *page)
Definition bufpage.h:410
uint16 pg_checksum_page(char *page, BlockNumber blkno)
uint16 pd_checksum
Definition bufpage.h:189

References DataChecksumsNeedVerify(), fb(), PageGetLSN(), PageIsNew(), PageHeaderData::pd_checksum, and pg_checksum_page().

Referenced by read_file_data_into_buffer().

Variable Documentation

◆ backup_started_in_recovery

bool backup_started_in_recovery = false
static

Definition at line 129 of file basebackup.c.

Referenced by do_pg_backup_start(), perform_base_backup(), and sendDir().

◆ excludeDirContents

const char* const excludeDirContents[]
static
Initial value:
=
{
"pg_notify",
"pg_serial",
"pg_snapshots",
"pg_subtrans",
}
#define PG_DYNSHMEM_DIR
Definition dsm_impl.h:51
#define PG_STAT_TMP_DIR
Definition pgstat.h:40
#define PG_REPLSLOT_DIR
Definition slot.h:21

Definition at line 157 of file basebackup.c.

158{
159 /*
160 * Skip temporary statistics files. PG_STAT_TMP_DIR must be skipped
161 * because extensions like pg_stat_statements store data there.
162 */
164
165 /*
166 * It is generally not useful to backup the contents of this directory
167 * even if the intention is to restore to another primary. See backup.sgml
168 * for a more detailed description.
169 */
171
172 /* Contents removed on startup, see dsm_cleanup_for_mmap(). */
174
175 /* Contents removed on startup, see AsyncShmemInit(). */
176 "pg_notify",
177
178 /*
179 * Old contents are loaded for possible debugging but are not required for
180 * normal operation, see SerialInit().
181 */
182 "pg_serial",
183
184 /* Contents removed on startup, see DeleteAllExportedSnapshotFiles(). */
185 "pg_snapshots",
186
187 /* Contents zeroed on startup, see StartupSUBTRANS(). */
188 "pg_subtrans",
189
190 /* end of list */
191 NULL
192};

Referenced by sendDir().

◆ excludeFiles

const struct exclude_list_item excludeFiles[]
static
Initial value:
=
{
{PG_AUTOCONF_FILENAME ".tmp", false},
{TABLESPACE_MAP, false},
{"backup_manifest", false},
{"postmaster.pid", false},
{"postmaster.opts", false},
{NULL, false}
}
#define PG_AUTOCONF_FILENAME
#define RELCACHE_INIT_FILENAME
Definition relcache.h:25
#define LOG_METAINFO_DATAFILE_TMP
Definition syslogger.h:104

Definition at line 197 of file basebackup.c.

198{
199 /* Skip auto conf temporary file. */
200 {PG_AUTOCONF_FILENAME ".tmp", false},
201
202 /* Skip current log file temporary file */
204
205 /*
206 * Skip relation cache because it is rebuilt on startup. This includes
207 * temporary files.
208 */
210
211 /*
212 * backup_label and tablespace_map should not exist in a running cluster
213 * capable of doing an online backup, but exclude them just in case.
214 */
215 {BACKUP_LABEL_FILE, false},
216 {TABLESPACE_MAP, false},
217
218 /*
219 * If there's a backup_manifest, it belongs to a backup that was used to
220 * start this server. It is *not* correct for this backup. Our
221 * backup_manifest is injected into the backup separately if users want
222 * it.
223 */
224 {"backup_manifest", false},
225
226 {"postmaster.pid", false},
227 {"postmaster.opts", false},
228
229 /* end of list */
230 {NULL, false}
231};

Referenced by sendDir().

◆ noverify_checksums

bool noverify_checksums = false
static

Definition at line 135 of file basebackup.c.

Referenced by parse_basebackup_options(), and sendFile().

◆ total_checksum_failures

long long int total_checksum_failures
static

Definition at line 132 of file basebackup.c.

Referenced by perform_base_backup(), and sendFile().