PostgreSQL Source Code  git master
basebackup.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * basebackup.c
4  * code for taking a base backup and streaming it to a standby
5  *
6  * Portions Copyright (c) 2010-2022, PostgreSQL Global Development Group
7  *
8  * IDENTIFICATION
9  * src/backend/backup/basebackup.c
10  *
11  *-------------------------------------------------------------------------
12  */
13 #include "postgres.h"
14 
15 #include <sys/stat.h>
16 #include <unistd.h>
17 #include <time.h>
18 
19 #include "access/xlog_internal.h"
20 #include "access/xlogbackup.h"
21 #include "backup/backup_manifest.h"
22 #include "backup/basebackup.h"
23 #include "backup/basebackup_sink.h"
25 #include "commands/defrem.h"
26 #include "common/compression.h"
27 #include "common/file_perm.h"
28 #include "lib/stringinfo.h"
29 #include "miscadmin.h"
30 #include "nodes/pg_list.h"
31 #include "pgstat.h"
32 #include "pgtar.h"
33 #include "port.h"
34 #include "postmaster/syslogger.h"
35 #include "replication/walsender.h"
37 #include "storage/bufpage.h"
38 #include "storage/checksum.h"
39 #include "storage/dsm_impl.h"
40 #include "storage/fd.h"
41 #include "storage/ipc.h"
42 #include "storage/reinit.h"
43 #include "utils/builtins.h"
44 #include "utils/guc.h"
45 #include "utils/ps_status.h"
46 #include "utils/relcache.h"
47 #include "utils/resowner.h"
48 #include "utils/timestamp.h"
49 
50 /*
51  * How much data do we want to send in one CopyData message? Note that
52  * this may also result in reading the underlying files in chunks of this
53  * size.
54  *
55  * NB: The buffer size is required to be a multiple of the system block
56  * size, so use that value instead if it's bigger than our preference.
57  */
58 #define SINK_BUFFER_LENGTH Max(32768, BLCKSZ)
59 
60 typedef struct
61 {
62  const char *label;
63  bool progress;
65  bool nowait;
66  bool includewal;
77 
78 static int64 sendTablespace(bbsink *sink, char *path, char *spcoid, bool sizeonly,
80 static int64 sendDir(bbsink *sink, const char *path, int basepathlen, bool sizeonly,
81  List *tablespaces, bool sendtblspclinks,
82  backup_manifest_info *manifest, const char *spcoid);
83 static bool sendFile(bbsink *sink, const char *readfilename, const char *tarfilename,
84  struct stat *statbuf, bool missing_ok, Oid dboid,
85  backup_manifest_info *manifest, const char *spcoid);
86 static void sendFileWithContent(bbsink *sink, const char *filename,
87  const char *content,
89 static int64 _tarWriteHeader(bbsink *sink, const char *filename,
90  const char *linktarget, struct stat *statbuf,
91  bool sizeonly);
92 static void _tarWritePadding(bbsink *sink, int len);
93 static void convert_link_to_directory(const char *pathbuf, struct stat *statbuf);
94 static void perform_base_backup(basebackup_options *opt, bbsink *sink);
96 static int compareWalFileNames(const ListCell *a, const ListCell *b);
97 static bool is_checksummed_file(const char *fullpath, const char *filename);
98 static int basebackup_read_file(int fd, char *buf, size_t nbytes, off_t offset,
99  const char *filename, bool partial_read_ok);
100 
101 /* Was the backup currently in-progress initiated in recovery mode? */
102 static bool backup_started_in_recovery = false;
103 
104 /* Total number of checksum failures during base backup. */
105 static long long int total_checksum_failures;
106 
107 /* Do not verify checksums. */
108 static bool noverify_checksums = false;
109 
110 /*
111  * Definition of one element part of an exclusion list, used for paths part
112  * of checksum validation or base backups. "name" is the name of the file
113  * or path to check for exclusion. If "match_prefix" is true, any items
114  * matching the name as prefix are excluded.
115  */
117 {
118  const char *name;
120 };
121 
122 /*
123  * The contents of these directories are removed or recreated during server
124  * start so they are not included in backups. The directories themselves are
125  * kept and included as empty to preserve access permissions.
126  *
127  * Note: this list should be kept in sync with the filter lists in pg_rewind's
128  * filemap.c.
129  */
130 static const char *const excludeDirContents[] =
131 {
132  /*
133  * Skip temporary statistics files. PG_STAT_TMP_DIR must be skipped
134  * because extensions like pg_stat_statements store data there.
135  */
137 
138  /*
139  * It is generally not useful to backup the contents of this directory
140  * even if the intention is to restore to another primary. See backup.sgml
141  * for a more detailed description.
142  */
143  "pg_replslot",
144 
145  /* Contents removed on startup, see dsm_cleanup_for_mmap(). */
147 
148  /* Contents removed on startup, see AsyncShmemInit(). */
149  "pg_notify",
150 
151  /*
152  * Old contents are loaded for possible debugging but are not required for
153  * normal operation, see SerialInit().
154  */
155  "pg_serial",
156 
157  /* Contents removed on startup, see DeleteAllExportedSnapshotFiles(). */
158  "pg_snapshots",
159 
160  /* Contents zeroed on startup, see StartupSUBTRANS(). */
161  "pg_subtrans",
162 
163  /* end of list */
164  NULL
165 };
166 
167 /*
168  * List of files excluded from backups.
169  */
170 static const struct exclude_list_item excludeFiles[] =
171 {
172  /* Skip auto conf temporary file. */
173  {PG_AUTOCONF_FILENAME ".tmp", false},
174 
175  /* Skip current log file temporary file */
176  {LOG_METAINFO_DATAFILE_TMP, false},
177 
178  /*
179  * Skip relation cache because it is rebuilt on startup. This includes
180  * temporary files.
181  */
182  {RELCACHE_INIT_FILENAME, true},
183 
184  /*
185  * backup_label and tablespace_map should not exist in a running cluster
186  * capable of doing an online backup, but exclude them just in case.
187  */
188  {BACKUP_LABEL_FILE, false},
189  {TABLESPACE_MAP, false},
190 
191  /*
192  * If there's a backup_manifest, it belongs to a backup that was used to
193  * start this server. It is *not* correct for this backup. Our
194  * backup_manifest is injected into the backup separately if users want
195  * it.
196  */
197  {"backup_manifest", false},
198 
199  {"postmaster.pid", false},
200  {"postmaster.opts", false},
201 
202  /* end of list */
203  {NULL, false}
204 };
205 
206 /*
207  * List of files excluded from checksum validation.
208  *
209  * Note: this list should be kept in sync with what pg_checksums.c
210  * includes.
211  */
212 static const struct exclude_list_item noChecksumFiles[] = {
213  {"pg_control", false},
214  {"pg_filenode.map", false},
215  {"pg_internal.init", true},
216  {"PG_VERSION", false},
217 #ifdef EXEC_BACKEND
218  {"config_exec_params", true},
219 #endif
220  {NULL, false}
221 };
222 
223 /*
224  * Actually do a base backup for the specified tablespaces.
225  *
226  * This is split out mainly to avoid complaints about "variable might be
227  * clobbered by longjmp" from stupider versions of gcc.
228  */
229 static void
231 {
233  XLogRecPtr endptr;
234  TimeLineID endtli;
238 
239  /* Initial backup state, insofar as we know it now. */
240  state.tablespaces = NIL;
241  state.tablespace_num = 0;
242  state.bytes_done = 0;
243  state.bytes_total = 0;
244  state.bytes_total_is_valid = false;
245 
246  /* we're going to use a BufFile, so we need a ResourceOwner */
247  Assert(CurrentResourceOwner == NULL);
248  CurrentResourceOwner = ResourceOwnerCreate(NULL, "base backup");
249 
251 
254 
256 
257  /* Allocate backup related varilables. */
260 
262  do_pg_backup_start(opt->label, opt->fastcheckpoint, &state.tablespaces,
264 
265  state.startptr = backup_state->startpoint;
266  state.starttli = backup_state->starttli;
267 
268  /*
269  * Once do_pg_backup_start has been called, ensure that any failure causes
270  * us to abort the backup so we don't "leak" a backup counter. For this
271  * reason, *all* functionality between do_pg_backup_start() and the end of
272  * do_pg_backup_stop() should be inside the error cleanup block!
273  */
274 
276  {
277  ListCell *lc;
278  tablespaceinfo *newti;
279 
280  /* Add a node for the base directory at the end */
281  newti = palloc0(sizeof(tablespaceinfo));
282  newti->size = -1;
283  state.tablespaces = lappend(state.tablespaces, newti);
284 
285  /*
286  * Calculate the total backup size by summing up the size of each
287  * tablespace
288  */
289  if (opt->progress)
290  {
292 
293  foreach(lc, state.tablespaces)
294  {
295  tablespaceinfo *tmp = (tablespaceinfo *) lfirst(lc);
296 
297  if (tmp->path == NULL)
298  tmp->size = sendDir(sink, ".", 1, true, state.tablespaces,
299  true, NULL, NULL);
300  else
301  tmp->size = sendTablespace(sink, tmp->path, tmp->oid, true,
302  NULL);
303  state.bytes_total += tmp->size;
304  }
305  state.bytes_total_is_valid = true;
306  }
307 
308  /* notify basebackup sink about start of backup */
310 
311  /* Send off our tablespaces one by one */
312  foreach(lc, state.tablespaces)
313  {
314  tablespaceinfo *ti = (tablespaceinfo *) lfirst(lc);
315 
316  if (ti->path == NULL)
317  {
318  struct stat statbuf;
319  bool sendtblspclinks = true;
320  char *backup_label;
321 
322  bbsink_begin_archive(sink, "base.tar");
323 
324  /* In the main tar, include the backup_label first... */
325  backup_label = build_backup_content(backup_state, false);
327  backup_label, &manifest);
328  pfree(backup_label);
329 
330  /* Then the tablespace_map file, if required... */
331  if (opt->sendtblspcmapfile)
332  {
335  sendtblspclinks = false;
336  }
337 
338  /* Then the bulk of the files... */
339  sendDir(sink, ".", 1, false, state.tablespaces,
340  sendtblspclinks, &manifest, NULL);
341 
342  /* ... and pg_control after everything else. */
343  if (lstat(XLOG_CONTROL_FILE, &statbuf) != 0)
344  ereport(ERROR,
346  errmsg("could not stat file \"%s\": %m",
349  false, InvalidOid, &manifest, NULL);
350  }
351  else
352  {
353  char *archive_name = psprintf("%s.tar", ti->oid);
354 
355  bbsink_begin_archive(sink, archive_name);
356 
357  sendTablespace(sink, ti->path, ti->oid, false, &manifest);
358  }
359 
360  /*
361  * If we're including WAL, and this is the main data directory we
362  * don't treat this as the end of the tablespace. Instead, we will
363  * include the xlog files below and stop afterwards. This is safe
364  * since the main data directory is always sent *last*.
365  */
366  if (opt->includewal && ti->path == NULL)
367  {
368  Assert(lnext(state.tablespaces, lc) == NULL);
369  }
370  else
371  {
372  /* Properly terminate the tarfile. */
373  StaticAssertStmt(2 * TAR_BLOCK_SIZE <= BLCKSZ,
374  "BLCKSZ too small for 2 tar blocks");
375  memset(sink->bbs_buffer, 0, 2 * TAR_BLOCK_SIZE);
377 
378  /* OK, that's the end of the archive. */
379  bbsink_end_archive(sink);
380  }
381  }
382 
385 
386  endptr = backup_state->stoppoint;
387  endtli = backup_state->stoptli;
388 
389  /* Deallocate backup-related variables. */
393  }
395 
396 
397  if (opt->includewal)
398  {
399  /*
400  * We've left the last tar file "open", so we can now append the
401  * required WAL files to it.
402  */
403  char pathbuf[MAXPGPATH];
404  XLogSegNo segno;
405  XLogSegNo startsegno;
406  XLogSegNo endsegno;
407  struct stat statbuf;
408  List *historyFileList = NIL;
409  List *walFileList = NIL;
410  char firstoff[MAXFNAMELEN];
411  char lastoff[MAXFNAMELEN];
412  DIR *dir;
413  struct dirent *de;
414  ListCell *lc;
415  TimeLineID tli;
416 
418 
419  /*
420  * I'd rather not worry about timelines here, so scan pg_wal and
421  * include all WAL files in the range between 'startptr' and 'endptr',
422  * regardless of the timeline the file is stamped with. If there are
423  * some spurious WAL files belonging to timelines that don't belong in
424  * this server's history, they will be included too. Normally there
425  * shouldn't be such files, but if there are, there's little harm in
426  * including them.
427  */
428  XLByteToSeg(state.startptr, startsegno, wal_segment_size);
429  XLogFileName(firstoff, state.starttli, startsegno, wal_segment_size);
430  XLByteToPrevSeg(endptr, endsegno, wal_segment_size);
431  XLogFileName(lastoff, endtli, endsegno, wal_segment_size);
432 
433  dir = AllocateDir("pg_wal");
434  while ((de = ReadDir(dir, "pg_wal")) != NULL)
435  {
436  /* Does it look like a WAL segment, and is it in the range? */
437  if (IsXLogFileName(de->d_name) &&
438  strcmp(de->d_name + 8, firstoff + 8) >= 0 &&
439  strcmp(de->d_name + 8, lastoff + 8) <= 0)
440  {
441  walFileList = lappend(walFileList, pstrdup(de->d_name));
442  }
443  /* Does it look like a timeline history file? */
444  else if (IsTLHistoryFileName(de->d_name))
445  {
446  historyFileList = lappend(historyFileList, pstrdup(de->d_name));
447  }
448  }
449  FreeDir(dir);
450 
451  /*
452  * Before we go any further, check that none of the WAL segments we
453  * need were removed.
454  */
455  CheckXLogRemoved(startsegno, state.starttli);
456 
457  /*
458  * Sort the WAL filenames. We want to send the files in order from
459  * oldest to newest, to reduce the chance that a file is recycled
460  * before we get a chance to send it over.
461  */
462  list_sort(walFileList, compareWalFileNames);
463 
464  /*
465  * There must be at least one xlog file in the pg_wal directory, since
466  * we are doing backup-including-xlog.
467  */
468  if (walFileList == NIL)
469  ereport(ERROR,
470  (errmsg("could not find any WAL files")));
471 
472  /*
473  * Sanity check: the first and last segment should cover startptr and
474  * endptr, with no gaps in between.
475  */
476  XLogFromFileName((char *) linitial(walFileList),
477  &tli, &segno, wal_segment_size);
478  if (segno != startsegno)
479  {
480  char startfname[MAXFNAMELEN];
481 
482  XLogFileName(startfname, state.starttli, startsegno,
484  ereport(ERROR,
485  (errmsg("could not find WAL file \"%s\"", startfname)));
486  }
487  foreach(lc, walFileList)
488  {
489  char *walFileName = (char *) lfirst(lc);
490  XLogSegNo currsegno = segno;
491  XLogSegNo nextsegno = segno + 1;
492 
493  XLogFromFileName(walFileName, &tli, &segno, wal_segment_size);
494  if (!(nextsegno == segno || currsegno == segno))
495  {
496  char nextfname[MAXFNAMELEN];
497 
498  XLogFileName(nextfname, tli, nextsegno, wal_segment_size);
499  ereport(ERROR,
500  (errmsg("could not find WAL file \"%s\"", nextfname)));
501  }
502  }
503  if (segno != endsegno)
504  {
505  char endfname[MAXFNAMELEN];
506 
507  XLogFileName(endfname, endtli, endsegno, wal_segment_size);
508  ereport(ERROR,
509  (errmsg("could not find WAL file \"%s\"", endfname)));
510  }
511 
512  /* Ok, we have everything we need. Send the WAL files. */
513  foreach(lc, walFileList)
514  {
515  char *walFileName = (char *) lfirst(lc);
516  int fd;
517  size_t cnt;
518  pgoff_t len = 0;
519 
520  snprintf(pathbuf, MAXPGPATH, XLOGDIR "/%s", walFileName);
521  XLogFromFileName(walFileName, &tli, &segno, wal_segment_size);
522 
523  fd = OpenTransientFile(pathbuf, O_RDONLY | PG_BINARY);
524  if (fd < 0)
525  {
526  int save_errno = errno;
527 
528  /*
529  * Most likely reason for this is that the file was already
530  * removed by a checkpoint, so check for that to get a better
531  * error message.
532  */
533  CheckXLogRemoved(segno, tli);
534 
535  errno = save_errno;
536  ereport(ERROR,
538  errmsg("could not open file \"%s\": %m", pathbuf)));
539  }
540 
541  if (fstat(fd, &statbuf) != 0)
542  ereport(ERROR,
544  errmsg("could not stat file \"%s\": %m",
545  pathbuf)));
546  if (statbuf.st_size != wal_segment_size)
547  {
548  CheckXLogRemoved(segno, tli);
549  ereport(ERROR,
551  errmsg("unexpected WAL file size \"%s\"", walFileName)));
552  }
553 
554  /* send the WAL file itself */
555  _tarWriteHeader(sink, pathbuf, NULL, &statbuf, false);
556 
557  while ((cnt = basebackup_read_file(fd, sink->bbs_buffer,
558  Min(sink->bbs_buffer_length,
560  len, pathbuf, true)) > 0)
561  {
562  CheckXLogRemoved(segno, tli);
563  bbsink_archive_contents(sink, cnt);
564 
565  len += cnt;
566 
567  if (len == wal_segment_size)
568  break;
569  }
570 
571  if (len != wal_segment_size)
572  {
573  CheckXLogRemoved(segno, tli);
574  ereport(ERROR,
576  errmsg("unexpected WAL file size \"%s\"", walFileName)));
577  }
578 
579  /*
580  * wal_segment_size is a multiple of TAR_BLOCK_SIZE, so no need
581  * for padding.
582  */
584 
586 
587  /*
588  * Mark file as archived, otherwise files can get archived again
589  * after promotion of a new node. This is in line with
590  * walreceiver.c always doing an XLogArchiveForceDone() after a
591  * complete segment.
592  */
593  StatusFilePath(pathbuf, walFileName, ".done");
594  sendFileWithContent(sink, pathbuf, "", &manifest);
595  }
596 
597  /*
598  * Send timeline history files too. Only the latest timeline history
599  * file is required for recovery, and even that only if there happens
600  * to be a timeline switch in the first WAL segment that contains the
601  * checkpoint record, or if we're taking a base backup from a standby
602  * server and the target timeline changes while the backup is taken.
603  * But they are small and highly useful for debugging purposes, so
604  * better include them all, always.
605  */
606  foreach(lc, historyFileList)
607  {
608  char *fname = lfirst(lc);
609 
610  snprintf(pathbuf, MAXPGPATH, XLOGDIR "/%s", fname);
611 
612  if (lstat(pathbuf, &statbuf) != 0)
613  ereport(ERROR,
615  errmsg("could not stat file \"%s\": %m", pathbuf)));
616 
617  sendFile(sink, pathbuf, pathbuf, &statbuf, false, InvalidOid,
618  &manifest, NULL);
619 
620  /* unconditionally mark file as archived */
621  StatusFilePath(pathbuf, fname, ".done");
622  sendFileWithContent(sink, pathbuf, "", &manifest);
623  }
624 
625  /* Properly terminate the tar file. */
626  StaticAssertStmt(2 * TAR_BLOCK_SIZE <= BLCKSZ,
627  "BLCKSZ too small for 2 tar blocks");
628  memset(sink->bbs_buffer, 0, 2 * TAR_BLOCK_SIZE);
630 
631  /* OK, that's the end of the archive. */
632  bbsink_end_archive(sink);
633  }
634 
635  AddWALInfoToBackupManifest(&manifest, state.startptr, state.starttli,
636  endptr, endtli);
637 
639 
640  bbsink_end_backup(sink, endptr, endtli);
641 
643  {
644  if (total_checksum_failures > 1)
646  (errmsg_plural("%lld total checksum verification failure",
647  "%lld total checksum verification failures",
650 
651  ereport(ERROR,
653  errmsg("checksum verification failure during base backup")));
654  }
655 
656  /*
657  * Make sure to free the manifest before the resource owners as manifests
658  * use cryptohash contexts that may depend on resource owners (like
659  * OpenSSL).
660  */
662 
663  /* clean up the resource owner we created */
664  WalSndResourceCleanup(true);
665 
667 }
668 
669 /*
670  * list_sort comparison function, to compare log/seg portion of WAL segment
671  * filenames, ignoring the timeline portion.
672  */
673 static int
675 {
676  char *fna = (char *) lfirst(a);
677  char *fnb = (char *) lfirst(b);
678 
679  return strcmp(fna + 8, fnb + 8);
680 }
681 
682 /*
683  * Parse the base backup options passed down by the parser
684  */
685 static void
687 {
688  ListCell *lopt;
689  bool o_label = false;
690  bool o_progress = false;
691  bool o_checkpoint = false;
692  bool o_nowait = false;
693  bool o_wal = false;
694  bool o_maxrate = false;
695  bool o_tablespace_map = false;
696  bool o_noverify_checksums = false;
697  bool o_manifest = false;
698  bool o_manifest_checksums = false;
699  bool o_target = false;
700  bool o_target_detail = false;
701  char *target_str = NULL;
702  char *target_detail_str = NULL;
703  bool o_compression = false;
704  bool o_compression_detail = false;
705  char *compression_detail_str = NULL;
706 
707  MemSet(opt, 0, sizeof(*opt));
712 
713  foreach(lopt, options)
714  {
715  DefElem *defel = (DefElem *) lfirst(lopt);
716 
717  if (strcmp(defel->defname, "label") == 0)
718  {
719  if (o_label)
720  ereport(ERROR,
721  (errcode(ERRCODE_SYNTAX_ERROR),
722  errmsg("duplicate option \"%s\"", defel->defname)));
723  opt->label = defGetString(defel);
724  o_label = true;
725  }
726  else if (strcmp(defel->defname, "progress") == 0)
727  {
728  if (o_progress)
729  ereport(ERROR,
730  (errcode(ERRCODE_SYNTAX_ERROR),
731  errmsg("duplicate option \"%s\"", defel->defname)));
732  opt->progress = defGetBoolean(defel);
733  o_progress = true;
734  }
735  else if (strcmp(defel->defname, "checkpoint") == 0)
736  {
737  char *optval = defGetString(defel);
738 
739  if (o_checkpoint)
740  ereport(ERROR,
741  (errcode(ERRCODE_SYNTAX_ERROR),
742  errmsg("duplicate option \"%s\"", defel->defname)));
743  if (pg_strcasecmp(optval, "fast") == 0)
744  opt->fastcheckpoint = true;
745  else if (pg_strcasecmp(optval, "spread") == 0)
746  opt->fastcheckpoint = false;
747  else
748  ereport(ERROR,
749  (errcode(ERRCODE_SYNTAX_ERROR),
750  errmsg("unrecognized checkpoint type: \"%s\"",
751  optval)));
752  o_checkpoint = true;
753  }
754  else if (strcmp(defel->defname, "wait") == 0)
755  {
756  if (o_nowait)
757  ereport(ERROR,
758  (errcode(ERRCODE_SYNTAX_ERROR),
759  errmsg("duplicate option \"%s\"", defel->defname)));
760  opt->nowait = !defGetBoolean(defel);
761  o_nowait = true;
762  }
763  else if (strcmp(defel->defname, "wal") == 0)
764  {
765  if (o_wal)
766  ereport(ERROR,
767  (errcode(ERRCODE_SYNTAX_ERROR),
768  errmsg("duplicate option \"%s\"", defel->defname)));
769  opt->includewal = defGetBoolean(defel);
770  o_wal = true;
771  }
772  else if (strcmp(defel->defname, "max_rate") == 0)
773  {
774  int64 maxrate;
775 
776  if (o_maxrate)
777  ereport(ERROR,
778  (errcode(ERRCODE_SYNTAX_ERROR),
779  errmsg("duplicate option \"%s\"", defel->defname)));
780 
781  maxrate = defGetInt64(defel);
782  if (maxrate < MAX_RATE_LOWER || maxrate > MAX_RATE_UPPER)
783  ereport(ERROR,
784  (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
785  errmsg("%d is outside the valid range for parameter \"%s\" (%d .. %d)",
786  (int) maxrate, "MAX_RATE", MAX_RATE_LOWER, MAX_RATE_UPPER)));
787 
788  opt->maxrate = (uint32) maxrate;
789  o_maxrate = true;
790  }
791  else if (strcmp(defel->defname, "tablespace_map") == 0)
792  {
793  if (o_tablespace_map)
794  ereport(ERROR,
795  (errcode(ERRCODE_SYNTAX_ERROR),
796  errmsg("duplicate option \"%s\"", defel->defname)));
797  opt->sendtblspcmapfile = defGetBoolean(defel);
798  o_tablespace_map = true;
799  }
800  else if (strcmp(defel->defname, "verify_checksums") == 0)
801  {
802  if (o_noverify_checksums)
803  ereport(ERROR,
804  (errcode(ERRCODE_SYNTAX_ERROR),
805  errmsg("duplicate option \"%s\"", defel->defname)));
807  o_noverify_checksums = true;
808  }
809  else if (strcmp(defel->defname, "manifest") == 0)
810  {
811  char *optval = defGetString(defel);
812  bool manifest_bool;
813 
814  if (o_manifest)
815  ereport(ERROR,
816  (errcode(ERRCODE_SYNTAX_ERROR),
817  errmsg("duplicate option \"%s\"", defel->defname)));
818  if (parse_bool(optval, &manifest_bool))
819  {
820  if (manifest_bool)
822  else
824  }
825  else if (pg_strcasecmp(optval, "force-encode") == 0)
827  else
828  ereport(ERROR,
829  (errcode(ERRCODE_SYNTAX_ERROR),
830  errmsg("unrecognized manifest option: \"%s\"",
831  optval)));
832  o_manifest = true;
833  }
834  else if (strcmp(defel->defname, "manifest_checksums") == 0)
835  {
836  char *optval = defGetString(defel);
837 
838  if (o_manifest_checksums)
839  ereport(ERROR,
840  (errcode(ERRCODE_SYNTAX_ERROR),
841  errmsg("duplicate option \"%s\"", defel->defname)));
842  if (!pg_checksum_parse_type(optval,
843  &opt->manifest_checksum_type))
844  ereport(ERROR,
845  (errcode(ERRCODE_SYNTAX_ERROR),
846  errmsg("unrecognized checksum algorithm: \"%s\"",
847  optval)));
848  o_manifest_checksums = true;
849  }
850  else if (strcmp(defel->defname, "target") == 0)
851  {
852  if (o_target)
853  ereport(ERROR,
854  (errcode(ERRCODE_SYNTAX_ERROR),
855  errmsg("duplicate option \"%s\"", defel->defname)));
856  target_str = defGetString(defel);
857  o_target = true;
858  }
859  else if (strcmp(defel->defname, "target_detail") == 0)
860  {
861  char *optval = defGetString(defel);
862 
863  if (o_target_detail)
864  ereport(ERROR,
865  (errcode(ERRCODE_SYNTAX_ERROR),
866  errmsg("duplicate option \"%s\"", defel->defname)));
867  target_detail_str = optval;
868  o_target_detail = true;
869  }
870  else if (strcmp(defel->defname, "compression") == 0)
871  {
872  char *optval = defGetString(defel);
873 
874  if (o_compression)
875  ereport(ERROR,
876  (errcode(ERRCODE_SYNTAX_ERROR),
877  errmsg("duplicate option \"%s\"", defel->defname)));
878  if (!parse_compress_algorithm(optval, &opt->compression))
879  ereport(ERROR,
880  (errcode(ERRCODE_SYNTAX_ERROR),
881  errmsg("unrecognized compression algorithm: \"%s\"",
882  optval)));
883  o_compression = true;
884  }
885  else if (strcmp(defel->defname, "compression_detail") == 0)
886  {
887  if (o_compression_detail)
888  ereport(ERROR,
889  (errcode(ERRCODE_SYNTAX_ERROR),
890  errmsg("duplicate option \"%s\"", defel->defname)));
891  compression_detail_str = defGetString(defel);
892  o_compression_detail = true;
893  }
894  else
895  ereport(ERROR,
896  (errcode(ERRCODE_SYNTAX_ERROR),
897  errmsg("unrecognized base backup option: \"%s\"",
898  defel->defname)));
899  }
900 
901  if (opt->label == NULL)
902  opt->label = "base backup";
903  if (opt->manifest == MANIFEST_OPTION_NO)
904  {
905  if (o_manifest_checksums)
906  ereport(ERROR,
907  (errcode(ERRCODE_SYNTAX_ERROR),
908  errmsg("manifest checksums require a backup manifest")));
910  }
911 
912  if (target_str == NULL)
913  {
914  if (target_detail_str != NULL)
915  ereport(ERROR,
916  (errcode(ERRCODE_SYNTAX_ERROR),
917  errmsg("target detail cannot be used without target")));
918  opt->use_copytblspc = true;
919  opt->send_to_client = true;
920  }
921  else if (strcmp(target_str, "client") == 0)
922  {
923  if (target_detail_str != NULL)
924  ereport(ERROR,
925  (errcode(ERRCODE_SYNTAX_ERROR),
926  errmsg("target \"%s\" does not accept a target detail",
927  target_str)));
928  opt->send_to_client = true;
929  }
930  else
931  opt->target_handle =
932  BaseBackupGetTargetHandle(target_str, target_detail_str);
933 
934  if (o_compression_detail && !o_compression)
935  ereport(ERROR,
936  (errcode(ERRCODE_SYNTAX_ERROR),
937  errmsg("compression detail cannot be specified unless compression is enabled")));
938 
939  if (o_compression)
940  {
941  char *error_detail;
942 
943  parse_compress_specification(opt->compression, compression_detail_str,
945  error_detail =
947  if (error_detail != NULL)
948  ereport(ERROR,
949  errcode(ERRCODE_SYNTAX_ERROR),
950  errmsg("invalid compression specification: %s",
951  error_detail));
952  }
953 }
954 
955 
956 /*
957  * SendBaseBackup() - send a complete base backup.
958  *
959  * The function will put the system into backup mode like pg_backup_start()
960  * does, so that the backup is consistent even though we read directly from
961  * the filesystem, bypassing the buffer cache.
962  */
963 void
965 {
966  basebackup_options opt;
967  bbsink *sink;
969 
971  ereport(ERROR,
972  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
973  errmsg("a backup is already in progress in this session")));
974 
975  parse_basebackup_options(cmd->options, &opt);
976 
978 
980  {
981  char activitymsg[50];
982 
983  snprintf(activitymsg, sizeof(activitymsg), "sending backup \"%s\"",
984  opt.label);
985  set_ps_display(activitymsg);
986  }
987 
988  /*
989  * If the target is specifically 'client' then set up to stream the backup
990  * to the client; otherwise, it's being sent someplace else and should not
991  * be sent to the client. BaseBackupGetSink has the job of setting up a
992  * sink to send the backup data wherever it needs to go.
993  */
995  if (opt.target_handle != NULL)
996  sink = BaseBackupGetSink(opt.target_handle, sink);
997 
998  /* Set up network throttling, if client requested it */
999  if (opt.maxrate > 0)
1000  sink = bbsink_throttle_new(sink, opt.maxrate);
1001 
1002  /* Set up server-side compression, if client requested it */
1003  if (opt.compression == PG_COMPRESSION_GZIP)
1004  sink = bbsink_gzip_new(sink, &opt.compression_specification);
1005  else if (opt.compression == PG_COMPRESSION_LZ4)
1006  sink = bbsink_lz4_new(sink, &opt.compression_specification);
1007  else if (opt.compression == PG_COMPRESSION_ZSTD)
1008  sink = bbsink_zstd_new(sink, &opt.compression_specification);
1009 
1010  /* Set up progress reporting. */
1011  sink = bbsink_progress_new(sink, opt.progress);
1012 
1013  /*
1014  * Perform the base backup, but make sure we clean up the bbsink even if
1015  * an error occurs.
1016  */
1017  PG_TRY();
1018  {
1019  perform_base_backup(&opt, sink);
1020  }
1021  PG_FINALLY();
1022  {
1023  bbsink_cleanup(sink);
1024  }
1025  PG_END_TRY();
1026 }
1027 
1028 /*
1029  * Inject a file with given name and content in the output tar stream.
1030  */
1031 static void
1032 sendFileWithContent(bbsink *sink, const char *filename, const char *content,
1034 {
1035  struct stat statbuf;
1036  int bytes_done = 0,
1037  len;
1038  pg_checksum_context checksum_ctx;
1039 
1040  if (pg_checksum_init(&checksum_ctx, manifest->checksum_type) < 0)
1041  elog(ERROR, "could not initialize checksum of file \"%s\"",
1042  filename);
1043 
1044  len = strlen(content);
1045 
1046  /*
1047  * Construct a stat struct for the backup_label file we're injecting in
1048  * the tar.
1049  */
1050  /* Windows doesn't have the concept of uid and gid */
1051 #ifdef WIN32
1052  statbuf.st_uid = 0;
1053  statbuf.st_gid = 0;
1054 #else
1055  statbuf.st_uid = geteuid();
1056  statbuf.st_gid = getegid();
1057 #endif
1058  statbuf.st_mtime = time(NULL);
1059  statbuf.st_mode = pg_file_create_mode;
1060  statbuf.st_size = len;
1061 
1062  _tarWriteHeader(sink, filename, NULL, &statbuf, false);
1063 
1064  if (pg_checksum_update(&checksum_ctx, (uint8 *) content, len) < 0)
1065  elog(ERROR, "could not update checksum of file \"%s\"",
1066  filename);
1067 
1068  while (bytes_done < len)
1069  {
1070  size_t remaining = len - bytes_done;
1071  size_t nbytes = Min(sink->bbs_buffer_length, remaining);
1072 
1073  memcpy(sink->bbs_buffer, content, nbytes);
1074  bbsink_archive_contents(sink, nbytes);
1075  bytes_done += nbytes;
1076  }
1077 
1078  _tarWritePadding(sink, len);
1079 
1081  (pg_time_t) statbuf.st_mtime, &checksum_ctx);
1082 }
1083 
1084 /*
1085  * Include the tablespace directory pointed to by 'path' in the output tar
1086  * stream. If 'sizeonly' is true, we just calculate a total length and return
1087  * it, without actually sending anything.
1088  *
1089  * Only used to send auxiliary tablespaces, not PGDATA.
1090  */
1091 static int64
1092 sendTablespace(bbsink *sink, char *path, char *spcoid, bool sizeonly,
1094 {
1095  int64 size;
1096  char pathbuf[MAXPGPATH];
1097  struct stat statbuf;
1098 
1099  /*
1100  * 'path' points to the tablespace location, but we only want to include
1101  * the version directory in it that belongs to us.
1102  */
1103  snprintf(pathbuf, sizeof(pathbuf), "%s/%s", path,
1105 
1106  /*
1107  * Store a directory entry in the tar file so we get the permissions
1108  * right.
1109  */
1110  if (lstat(pathbuf, &statbuf) != 0)
1111  {
1112  if (errno != ENOENT)
1113  ereport(ERROR,
1115  errmsg("could not stat file or directory \"%s\": %m",
1116  pathbuf)));
1117 
1118  /* If the tablespace went away while scanning, it's no error. */
1119  return 0;
1120  }
1121 
1122  size = _tarWriteHeader(sink, TABLESPACE_VERSION_DIRECTORY, NULL, &statbuf,
1123  sizeonly);
1124 
1125  /* Send all the files in the tablespace version directory */
1126  size += sendDir(sink, pathbuf, strlen(path), sizeonly, NIL, true, manifest,
1127  spcoid);
1128 
1129  return size;
1130 }
1131 
1132 /*
1133  * Include all files from the given directory in the output tar stream. If
1134  * 'sizeonly' is true, we just calculate a total length and return it, without
1135  * actually sending anything.
1136  *
1137  * Omit any directory in the tablespaces list, to avoid backing up
1138  * tablespaces twice when they were created inside PGDATA.
1139  *
1140  * If sendtblspclinks is true, we need to include symlink
1141  * information in the tar file. If not, we can skip that
1142  * as it will be sent separately in the tablespace_map file.
1143  */
1144 static int64
1145 sendDir(bbsink *sink, const char *path, int basepathlen, bool sizeonly,
1146  List *tablespaces, bool sendtblspclinks, backup_manifest_info *manifest,
1147  const char *spcoid)
1148 {
1149  DIR *dir;
1150  struct dirent *de;
1151  char pathbuf[MAXPGPATH * 2];
1152  struct stat statbuf;
1153  int64 size = 0;
1154  const char *lastDir; /* Split last dir from parent path. */
1155  bool isDbDir = false; /* Does this directory contain relations? */
1156 
1157  /*
1158  * Determine if the current path is a database directory that can contain
1159  * relations.
1160  *
1161  * Start by finding the location of the delimiter between the parent path
1162  * and the current path.
1163  */
1164  lastDir = last_dir_separator(path);
1165 
1166  /* Does this path look like a database path (i.e. all digits)? */
1167  if (lastDir != NULL &&
1168  strspn(lastDir + 1, "0123456789") == strlen(lastDir + 1))
1169  {
1170  /* Part of path that contains the parent directory. */
1171  int parentPathLen = lastDir - path;
1172 
1173  /*
1174  * Mark path as a database directory if the parent path is either
1175  * $PGDATA/base or a tablespace version path.
1176  */
1177  if (strncmp(path, "./base", parentPathLen) == 0 ||
1178  (parentPathLen >= (sizeof(TABLESPACE_VERSION_DIRECTORY) - 1) &&
1179  strncmp(lastDir - (sizeof(TABLESPACE_VERSION_DIRECTORY) - 1),
1181  sizeof(TABLESPACE_VERSION_DIRECTORY) - 1) == 0))
1182  isDbDir = true;
1183  }
1184 
1185  dir = AllocateDir(path);
1186  while ((de = ReadDir(dir, path)) != NULL)
1187  {
1188  int excludeIdx;
1189  bool excludeFound;
1190  ForkNumber relForkNum; /* Type of fork if file is a relation */
1191  int relnumchars; /* Chars in filename that are the
1192  * relnumber */
1193 
1194  /* Skip special stuff */
1195  if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
1196  continue;
1197 
1198  /* Skip temporary files */
1199  if (strncmp(de->d_name,
1201  strlen(PG_TEMP_FILE_PREFIX)) == 0)
1202  continue;
1203 
1204  /*
1205  * Check if the postmaster has signaled us to exit, and abort with an
1206  * error in that case. The error handler further up will call
1207  * do_pg_abort_backup() for us. Also check that if the backup was
1208  * started while still in recovery, the server wasn't promoted.
1209  * do_pg_backup_stop() will check that too, but it's better to stop
1210  * the backup early than continue to the end and fail there.
1211  */
1214  ereport(ERROR,
1215  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1216  errmsg("the standby was promoted during online backup"),
1217  errhint("This means that the backup being taken is corrupt "
1218  "and should not be used. "
1219  "Try taking another online backup.")));
1220 
1221  /* Scan for files that should be excluded */
1222  excludeFound = false;
1223  for (excludeIdx = 0; excludeFiles[excludeIdx].name != NULL; excludeIdx++)
1224  {
1225  int cmplen = strlen(excludeFiles[excludeIdx].name);
1226 
1227  if (!excludeFiles[excludeIdx].match_prefix)
1228  cmplen++;
1229  if (strncmp(de->d_name, excludeFiles[excludeIdx].name, cmplen) == 0)
1230  {
1231  elog(DEBUG1, "file \"%s\" excluded from backup", de->d_name);
1232  excludeFound = true;
1233  break;
1234  }
1235  }
1236 
1237  if (excludeFound)
1238  continue;
1239 
1240  /* Exclude all forks for unlogged tables except the init fork */
1241  if (isDbDir &&
1242  parse_filename_for_nontemp_relation(de->d_name, &relnumchars,
1243  &relForkNum))
1244  {
1245  /* Never exclude init forks */
1246  if (relForkNum != INIT_FORKNUM)
1247  {
1248  char initForkFile[MAXPGPATH];
1249  char relNumber[OIDCHARS + 1];
1250 
1251  /*
1252  * If any other type of fork, check if there is an init fork
1253  * with the same RelFileNumber. If so, the file can be
1254  * excluded.
1255  */
1256  memcpy(relNumber, de->d_name, relnumchars);
1257  relNumber[relnumchars] = '\0';
1258  snprintf(initForkFile, sizeof(initForkFile), "%s/%s_init",
1259  path, relNumber);
1260 
1261  if (lstat(initForkFile, &statbuf) == 0)
1262  {
1263  elog(DEBUG2,
1264  "unlogged relation file \"%s\" excluded from backup",
1265  de->d_name);
1266 
1267  continue;
1268  }
1269  }
1270  }
1271 
1272  /* Exclude temporary relations */
1273  if (isDbDir && looks_like_temp_rel_name(de->d_name))
1274  {
1275  elog(DEBUG2,
1276  "temporary relation file \"%s\" excluded from backup",
1277  de->d_name);
1278 
1279  continue;
1280  }
1281 
1282  snprintf(pathbuf, sizeof(pathbuf), "%s/%s", path, de->d_name);
1283 
1284  /* Skip pg_control here to back up it last */
1285  if (strcmp(pathbuf, "./global/pg_control") == 0)
1286  continue;
1287 
1288  if (lstat(pathbuf, &statbuf) != 0)
1289  {
1290  if (errno != ENOENT)
1291  ereport(ERROR,
1293  errmsg("could not stat file or directory \"%s\": %m",
1294  pathbuf)));
1295 
1296  /* If the file went away while scanning, it's not an error. */
1297  continue;
1298  }
1299 
1300  /* Scan for directories whose contents should be excluded */
1301  excludeFound = false;
1302  for (excludeIdx = 0; excludeDirContents[excludeIdx] != NULL; excludeIdx++)
1303  {
1304  if (strcmp(de->d_name, excludeDirContents[excludeIdx]) == 0)
1305  {
1306  elog(DEBUG1, "contents of directory \"%s\" excluded from backup", de->d_name);
1307  convert_link_to_directory(pathbuf, &statbuf);
1308  size += _tarWriteHeader(sink, pathbuf + basepathlen + 1, NULL,
1309  &statbuf, sizeonly);
1310  excludeFound = true;
1311  break;
1312  }
1313  }
1314 
1315  if (excludeFound)
1316  continue;
1317 
1318  /*
1319  * We can skip pg_wal, the WAL segments need to be fetched from the
1320  * WAL archive anyway. But include it as an empty directory anyway, so
1321  * we get permissions right.
1322  */
1323  if (strcmp(pathbuf, "./pg_wal") == 0)
1324  {
1325  /* If pg_wal is a symlink, write it as a directory anyway */
1326  convert_link_to_directory(pathbuf, &statbuf);
1327  size += _tarWriteHeader(sink, pathbuf + basepathlen + 1, NULL,
1328  &statbuf, sizeonly);
1329 
1330  /*
1331  * Also send archive_status directory (by hackishly reusing
1332  * statbuf from above ...).
1333  */
1334  size += _tarWriteHeader(sink, "./pg_wal/archive_status", NULL,
1335  &statbuf, sizeonly);
1336 
1337  continue; /* don't recurse into pg_wal */
1338  }
1339 
1340  /* Allow symbolic links in pg_tblspc only */
1341  if (strcmp(path, "./pg_tblspc") == 0 && S_ISLNK(statbuf.st_mode))
1342  {
1343  char linkpath[MAXPGPATH];
1344  int rllen;
1345 
1346  rllen = readlink(pathbuf, linkpath, sizeof(linkpath));
1347  if (rllen < 0)
1348  ereport(ERROR,
1350  errmsg("could not read symbolic link \"%s\": %m",
1351  pathbuf)));
1352  if (rllen >= sizeof(linkpath))
1353  ereport(ERROR,
1354  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1355  errmsg("symbolic link \"%s\" target is too long",
1356  pathbuf)));
1357  linkpath[rllen] = '\0';
1358 
1359  size += _tarWriteHeader(sink, pathbuf + basepathlen + 1, linkpath,
1360  &statbuf, sizeonly);
1361  }
1362  else if (S_ISDIR(statbuf.st_mode))
1363  {
1364  bool skip_this_dir = false;
1365  ListCell *lc;
1366 
1367  /*
1368  * Store a directory entry in the tar file so we can get the
1369  * permissions right.
1370  */
1371  size += _tarWriteHeader(sink, pathbuf + basepathlen + 1, NULL, &statbuf,
1372  sizeonly);
1373 
1374  /*
1375  * Call ourselves recursively for a directory, unless it happens
1376  * to be a separate tablespace located within PGDATA.
1377  */
1378  foreach(lc, tablespaces)
1379  {
1380  tablespaceinfo *ti = (tablespaceinfo *) lfirst(lc);
1381 
1382  /*
1383  * ti->rpath is the tablespace relative path within PGDATA, or
1384  * NULL if the tablespace has been properly located somewhere
1385  * else.
1386  *
1387  * Skip past the leading "./" in pathbuf when comparing.
1388  */
1389  if (ti->rpath && strcmp(ti->rpath, pathbuf + 2) == 0)
1390  {
1391  skip_this_dir = true;
1392  break;
1393  }
1394  }
1395 
1396  /*
1397  * skip sending directories inside pg_tblspc, if not required.
1398  */
1399  if (strcmp(pathbuf, "./pg_tblspc") == 0 && !sendtblspclinks)
1400  skip_this_dir = true;
1401 
1402  if (!skip_this_dir)
1403  size += sendDir(sink, pathbuf, basepathlen, sizeonly, tablespaces,
1404  sendtblspclinks, manifest, spcoid);
1405  }
1406  else if (S_ISREG(statbuf.st_mode))
1407  {
1408  bool sent = false;
1409 
1410  if (!sizeonly)
1411  sent = sendFile(sink, pathbuf, pathbuf + basepathlen + 1, &statbuf,
1412  true, isDbDir ? atooid(lastDir + 1) : InvalidOid,
1413  manifest, spcoid);
1414 
1415  if (sent || sizeonly)
1416  {
1417  /* Add size. */
1418  size += statbuf.st_size;
1419 
1420  /* Pad to a multiple of the tar block size. */
1421  size += tarPaddingBytesRequired(statbuf.st_size);
1422 
1423  /* Size of the header for the file. */
1424  size += TAR_BLOCK_SIZE;
1425  }
1426  }
1427  else
1428  ereport(WARNING,
1429  (errmsg("skipping special file \"%s\"", pathbuf)));
1430  }
1431  FreeDir(dir);
1432  return size;
1433 }
1434 
1435 /*
1436  * Check if a file should have its checksum validated.
1437  * We validate checksums on files in regular tablespaces
1438  * (including global and default) only, and in those there
1439  * are some files that are explicitly excluded.
1440  */
1441 static bool
1442 is_checksummed_file(const char *fullpath, const char *filename)
1443 {
1444  /* Check that the file is in a tablespace */
1445  if (strncmp(fullpath, "./global/", 9) == 0 ||
1446  strncmp(fullpath, "./base/", 7) == 0 ||
1447  strncmp(fullpath, "/", 1) == 0)
1448  {
1449  int excludeIdx;
1450 
1451  /* Compare file against noChecksumFiles skip list */
1452  for (excludeIdx = 0; noChecksumFiles[excludeIdx].name != NULL; excludeIdx++)
1453  {
1454  int cmplen = strlen(noChecksumFiles[excludeIdx].name);
1455 
1456  if (!noChecksumFiles[excludeIdx].match_prefix)
1457  cmplen++;
1458  if (strncmp(filename, noChecksumFiles[excludeIdx].name,
1459  cmplen) == 0)
1460  return false;
1461  }
1462 
1463  return true;
1464  }
1465  else
1466  return false;
1467 }
1468 
1469 /*****
1470  * Functions for handling tar file format
1471  *
1472  * Copied from pg_dump, but modified to work with libpq for sending
1473  */
1474 
1475 
1476 /*
1477  * Given the member, write the TAR header & send the file.
1478  *
1479  * If 'missing_ok' is true, will not throw an error if the file is not found.
1480  *
1481  * If dboid is anything other than InvalidOid then any checksum failures
1482  * detected will get reported to the cumulative stats system.
1483  *
1484  * Returns true if the file was successfully sent, false if 'missing_ok',
1485  * and the file did not exist.
1486  */
1487 static bool
1488 sendFile(bbsink *sink, const char *readfilename, const char *tarfilename,
1489  struct stat *statbuf, bool missing_ok, Oid dboid,
1490  backup_manifest_info *manifest, const char *spcoid)
1491 {
1492  int fd;
1493  BlockNumber blkno = 0;
1494  bool block_retry = false;
1495  uint16 checksum;
1496  int checksum_failures = 0;
1497  off_t cnt;
1498  int i;
1499  pgoff_t len = 0;
1500  char *page;
1501  PageHeader phdr;
1502  int segmentno = 0;
1503  char *segmentpath;
1504  bool verify_checksum = false;
1505  pg_checksum_context checksum_ctx;
1506 
1507  if (pg_checksum_init(&checksum_ctx, manifest->checksum_type) < 0)
1508  elog(ERROR, "could not initialize checksum of file \"%s\"",
1509  readfilename);
1510 
1511  fd = OpenTransientFile(readfilename, O_RDONLY | PG_BINARY);
1512  if (fd < 0)
1513  {
1514  if (errno == ENOENT && missing_ok)
1515  return false;
1516  ereport(ERROR,
1518  errmsg("could not open file \"%s\": %m", readfilename)));
1519  }
1520 
1521  _tarWriteHeader(sink, tarfilename, NULL, statbuf, false);
1522 
1524  {
1525  char *filename;
1526 
1527  /*
1528  * Get the filename (excluding path). As last_dir_separator()
1529  * includes the last directory separator, we chop that off by
1530  * incrementing the pointer.
1531  */
1532  filename = last_dir_separator(readfilename) + 1;
1533 
1534  if (is_checksummed_file(readfilename, filename))
1535  {
1536  verify_checksum = true;
1537 
1538  /*
1539  * Cut off at the segment boundary (".") to get the segment number
1540  * in order to mix it into the checksum.
1541  */
1542  segmentpath = strstr(filename, ".");
1543  if (segmentpath != NULL)
1544  {
1545  segmentno = atoi(segmentpath + 1);
1546  if (segmentno == 0)
1547  ereport(ERROR,
1548  (errmsg("invalid segment number %d in file \"%s\"",
1549  segmentno, filename)));
1550  }
1551  }
1552  }
1553 
1554  /*
1555  * Loop until we read the amount of data the caller told us to expect. The
1556  * file could be longer, if it was extended while we were sending it, but
1557  * for a base backup we can ignore such extended data. It will be restored
1558  * from WAL.
1559  */
1560  while (len < statbuf->st_size)
1561  {
1562  size_t remaining = statbuf->st_size - len;
1563 
1564  /* Try to read some more data. */
1565  cnt = basebackup_read_file(fd, sink->bbs_buffer,
1567  len, readfilename, true);
1568 
1569  /*
1570  * If we hit end-of-file, a concurrent truncation must have occurred.
1571  * That's not an error condition, because WAL replay will fix things
1572  * up.
1573  */
1574  if (cnt == 0)
1575  break;
1576 
1577  /*
1578  * The checksums are verified at block level, so we iterate over the
1579  * buffer in chunks of BLCKSZ, after making sure that
1580  * TAR_SEND_SIZE/buf is divisible by BLCKSZ and we read a multiple of
1581  * BLCKSZ bytes.
1582  */
1583  Assert((sink->bbs_buffer_length % BLCKSZ) == 0);
1584 
1585  if (verify_checksum && (cnt % BLCKSZ != 0))
1586  {
1587  ereport(WARNING,
1588  (errmsg("could not verify checksum in file \"%s\", block "
1589  "%u: read buffer size %d and page size %d "
1590  "differ",
1591  readfilename, blkno, (int) cnt, BLCKSZ)));
1592  verify_checksum = false;
1593  }
1594 
1595  if (verify_checksum)
1596  {
1597  for (i = 0; i < cnt / BLCKSZ; i++)
1598  {
1599  page = sink->bbs_buffer + BLCKSZ * i;
1600 
1601  /*
1602  * Only check pages which have not been modified since the
1603  * start of the base backup. Otherwise, they might have been
1604  * written only halfway and the checksum would not be valid.
1605  * However, replaying WAL would reinstate the correct page in
1606  * this case. We also skip completely new pages, since they
1607  * don't have a checksum yet.
1608  */
1609  if (!PageIsNew(page) && PageGetLSN(page) < sink->bbs_state->startptr)
1610  {
1611  checksum = pg_checksum_page((char *) page, blkno + segmentno * RELSEG_SIZE);
1612  phdr = (PageHeader) page;
1613  if (phdr->pd_checksum != checksum)
1614  {
1615  /*
1616  * Retry the block on the first failure. It's
1617  * possible that we read the first 4K page of the
1618  * block just before postgres updated the entire block
1619  * so it ends up looking torn to us. We only need to
1620  * retry once because the LSN should be updated to
1621  * something we can ignore on the next pass. If the
1622  * error happens again then it is a true validation
1623  * failure.
1624  */
1625  if (block_retry == false)
1626  {
1627  int reread_cnt;
1628 
1629  /* Reread the failed block */
1630  reread_cnt =
1632  sink->bbs_buffer + BLCKSZ * i,
1633  BLCKSZ, len + BLCKSZ * i,
1634  readfilename,
1635  false);
1636  if (reread_cnt == 0)
1637  {
1638  /*
1639  * If we hit end-of-file, a concurrent
1640  * truncation must have occurred, so break out
1641  * of this loop just as if the initial fread()
1642  * returned 0. We'll drop through to the same
1643  * code that handles that case. (We must fix
1644  * up cnt first, though.)
1645  */
1646  cnt = BLCKSZ * i;
1647  break;
1648  }
1649 
1650  /* Set flag so we know a retry was attempted */
1651  block_retry = true;
1652 
1653  /* Reset loop to validate the block again */
1654  i--;
1655  continue;
1656  }
1657 
1658  checksum_failures++;
1659 
1660  if (checksum_failures <= 5)
1661  ereport(WARNING,
1662  (errmsg("checksum verification failed in "
1663  "file \"%s\", block %u: calculated "
1664  "%X but expected %X",
1665  readfilename, blkno, checksum,
1666  phdr->pd_checksum)));
1667  if (checksum_failures == 5)
1668  ereport(WARNING,
1669  (errmsg("further checksum verification "
1670  "failures in file \"%s\" will not "
1671  "be reported", readfilename)));
1672  }
1673  }
1674  block_retry = false;
1675  blkno++;
1676  }
1677  }
1678 
1679  bbsink_archive_contents(sink, cnt);
1680 
1681  /* Also feed it to the checksum machinery. */
1682  if (pg_checksum_update(&checksum_ctx,
1683  (uint8 *) sink->bbs_buffer, cnt) < 0)
1684  elog(ERROR, "could not update checksum of base backup");
1685 
1686  len += cnt;
1687  }
1688 
1689  /* If the file was truncated while we were sending it, pad it with zeros */
1690  while (len < statbuf->st_size)
1691  {
1692  size_t remaining = statbuf->st_size - len;
1693  size_t nbytes = Min(sink->bbs_buffer_length, remaining);
1694 
1695  MemSet(sink->bbs_buffer, 0, nbytes);
1696  if (pg_checksum_update(&checksum_ctx,
1697  (uint8 *) sink->bbs_buffer,
1698  nbytes) < 0)
1699  elog(ERROR, "could not update checksum of base backup");
1700  bbsink_archive_contents(sink, nbytes);
1701  len += nbytes;
1702  }
1703 
1704  /*
1705  * Pad to a block boundary, per tar format requirements. (This small piece
1706  * of data is probably not worth throttling, and is not checksummed
1707  * because it's not actually part of the file.)
1708  */
1709  _tarWritePadding(sink, len);
1710 
1712 
1713  if (checksum_failures > 1)
1714  {
1715  ereport(WARNING,
1716  (errmsg_plural("file \"%s\" has a total of %d checksum verification failure",
1717  "file \"%s\" has a total of %d checksum verification failures",
1718  checksum_failures,
1719  readfilename, checksum_failures)));
1720 
1721  pgstat_report_checksum_failures_in_db(dboid, checksum_failures);
1722  }
1723 
1724  total_checksum_failures += checksum_failures;
1725 
1726  AddFileToBackupManifest(manifest, spcoid, tarfilename, statbuf->st_size,
1727  (pg_time_t) statbuf->st_mtime, &checksum_ctx);
1728 
1729  return true;
1730 }
1731 
1732 static int64
1733 _tarWriteHeader(bbsink *sink, const char *filename, const char *linktarget,
1734  struct stat *statbuf, bool sizeonly)
1735 {
1736  enum tarError rc;
1737 
1738  if (!sizeonly)
1739  {
1740  /*
1741  * As of this writing, the smallest supported block size is 1kB, which
1742  * is twice TAR_BLOCK_SIZE. Since the buffer size is required to be a
1743  * multiple of BLCKSZ, it should be safe to assume that the buffer is
1744  * large enough to fit an entire tar block. We double-check by means
1745  * of these assertions.
1746  */
1747  StaticAssertStmt(TAR_BLOCK_SIZE <= BLCKSZ,
1748  "BLCKSZ too small for tar block");
1750 
1751  rc = tarCreateHeader(sink->bbs_buffer, filename, linktarget,
1752  statbuf->st_size, statbuf->st_mode,
1753  statbuf->st_uid, statbuf->st_gid,
1754  statbuf->st_mtime);
1755 
1756  switch (rc)
1757  {
1758  case TAR_OK:
1759  break;
1760  case TAR_NAME_TOO_LONG:
1761  ereport(ERROR,
1762  (errmsg("file name too long for tar format: \"%s\"",
1763  filename)));
1764  break;
1765  case TAR_SYMLINK_TOO_LONG:
1766  ereport(ERROR,
1767  (errmsg("symbolic link target too long for tar format: "
1768  "file name \"%s\", target \"%s\"",
1769  filename, linktarget)));
1770  break;
1771  default:
1772  elog(ERROR, "unrecognized tar error: %d", rc);
1773  }
1774 
1776  }
1777 
1778  return TAR_BLOCK_SIZE;
1779 }
1780 
1781 /*
1782  * Pad with zero bytes out to a multiple of TAR_BLOCK_SIZE.
1783  */
1784 static void
1786 {
1787  int pad = tarPaddingBytesRequired(len);
1788 
1789  /*
1790  * As in _tarWriteHeader, it should be safe to assume that the buffer is
1791  * large enough that we don't need to do this in multiple chunks.
1792  */
1794  Assert(pad <= TAR_BLOCK_SIZE);
1795 
1796  if (pad > 0)
1797  {
1798  MemSet(sink->bbs_buffer, 0, pad);
1799  bbsink_archive_contents(sink, pad);
1800  }
1801 }
1802 
1803 /*
1804  * If the entry in statbuf is a link, then adjust statbuf to make it look like a
1805  * directory, so that it will be written that way.
1806  */
1807 static void
1808 convert_link_to_directory(const char *pathbuf, struct stat *statbuf)
1809 {
1810  /* If symlink, write it as a directory anyway */
1811  if (S_ISLNK(statbuf->st_mode))
1812  statbuf->st_mode = S_IFDIR | pg_dir_create_mode;
1813 }
1814 
1815 /*
1816  * Read some data from a file, setting a wait event and reporting any error
1817  * encountered.
1818  *
1819  * If partial_read_ok is false, also report an error if the number of bytes
1820  * read is not equal to the number of bytes requested.
1821  *
1822  * Returns the number of bytes read.
1823  */
1824 static int
1825 basebackup_read_file(int fd, char *buf, size_t nbytes, off_t offset,
1826  const char *filename, bool partial_read_ok)
1827 {
1828  int rc;
1829 
1831  rc = pg_pread(fd, buf, nbytes, offset);
1833 
1834  if (rc < 0)
1835  ereport(ERROR,
1837  errmsg("could not read file \"%s\": %m", filename)));
1838  if (!partial_read_ok && rc > 0 && rc != nbytes)
1839  ereport(ERROR,
1841  errmsg("could not read file \"%s\": read %d of %zu",
1842  filename, rc, nbytes)));
1843 
1844  return rc;
1845 }
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)
void AddFileToBackupManifest(backup_manifest_info *manifest, const char *spcoid, const char *pathname, size_t size, pg_time_t mtime, pg_checksum_context *checksum_ctx)
@ MANIFEST_OPTION_NO
@ MANIFEST_OPTION_FORCE_ENCODE
@ MANIFEST_OPTION_YES
enum manifest_option backup_manifest_option
static const struct exclude_list_item excludeFiles[]
Definition: basebackup.c:170
static const struct exclude_list_item noChecksumFiles[]
Definition: basebackup.c:212
void SendBaseBackup(BaseBackupCmd *cmd)
Definition: basebackup.c:964
static void sendFileWithContent(bbsink *sink, const char *filename, const char *content, backup_manifest_info *manifest)
Definition: basebackup.c:1032
static int compareWalFileNames(const ListCell *a, const ListCell *b)
Definition: basebackup.c:674
#define SINK_BUFFER_LENGTH
Definition: basebackup.c:58
static void parse_basebackup_options(List *options, basebackup_options *opt)
Definition: basebackup.c:686
static const char *const excludeDirContents[]
Definition: basebackup.c:130
static void convert_link_to_directory(const char *pathbuf, struct stat *statbuf)
Definition: basebackup.c:1808
static void perform_base_backup(basebackup_options *opt, bbsink *sink)
Definition: basebackup.c:230
static bool is_checksummed_file(const char *fullpath, const char *filename)
Definition: basebackup.c:1442
static bool backup_started_in_recovery
Definition: basebackup.c:102
static int64 _tarWriteHeader(bbsink *sink, const char *filename, const char *linktarget, struct stat *statbuf, bool sizeonly)
Definition: basebackup.c:1733
static bool sendFile(bbsink *sink, const char *readfilename, const char *tarfilename, struct stat *statbuf, bool missing_ok, Oid dboid, backup_manifest_info *manifest, const char *spcoid)
Definition: basebackup.c:1488
static int64 sendTablespace(bbsink *sink, char *path, char *spcoid, bool sizeonly, struct backup_manifest_info *manifest)
Definition: basebackup.c:1092
static int basebackup_read_file(int fd, char *buf, size_t nbytes, off_t offset, const char *filename, bool partial_read_ok)
Definition: basebackup.c:1825
static bool noverify_checksums
Definition: basebackup.c:108
static int64 sendDir(bbsink *sink, const char *path, int basepathlen, bool sizeonly, List *tablespaces, bool sendtblspclinks, backup_manifest_info *manifest, const char *spcoid)
Definition: basebackup.c:1145
static void _tarWritePadding(bbsink *sink, int len)
Definition: basebackup.c:1785
static long long int total_checksum_failures
Definition: basebackup.c:105
#define MAX_RATE_UPPER
Definition: basebackup.h:21
#define MAX_RATE_LOWER
Definition: basebackup.h:20
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)
void basebackup_progress_wait_checkpoint(void)
void basebackup_progress_wait_wal_archive(bbsink_state *state)
bbsink * bbsink_progress_new(bbsink *next, bool estimate_backup_size)
void basebackup_progress_done(void)
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)
static void bbsink_cleanup(bbsink *sink)
static void bbsink_archive_contents(bbsink *sink, size_t len)
bbsink * BaseBackupGetSink(BaseBackupTargetHandle *handle, bbsink *next_sink)
BaseBackupTargetHandle * BaseBackupGetTargetHandle(char *target, char *target_detail)
bbsink * bbsink_throttle_new(bbsink *next, uint32 maxrate)
bbsink * bbsink_zstd_new(bbsink *next, pg_compress_specification *compress)
uint32 BlockNumber
Definition: block.h:31
bool parse_bool(const char *value, bool *result)
Definition: bool.c:30
PageHeaderData * PageHeader
Definition: bufpage.h:170
static bool PageIsNew(Page page)
Definition: bufpage.h:230
static XLogRecPtr PageGetLSN(Page page)
Definition: bufpage.h:383
unsigned short uint16
Definition: c.h:441
unsigned int uint32
Definition: c.h:442
#define Min(x, y)
Definition: c.h:937
#define PG_BINARY
Definition: c.h:1209
unsigned char uint8
Definition: c.h:440
#define MemSet(start, val, len)
Definition: c.h:953
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:869
uint16 pg_checksum_page(char *page, BlockNumber blkno)
bool pg_checksum_parse_type(char *name, pg_checksum_type *type)
int pg_checksum_update(pg_checksum_context *context, const uint8 *input, size_t len)
int pg_checksum_init(pg_checksum_context *context, pg_checksum_type type)
pg_checksum_type
@ CHECKSUM_TYPE_NONE
@ CHECKSUM_TYPE_CRC32C
bool parse_compress_algorithm(char *name, pg_compress_algorithm *algorithm)
Definition: compression.c:47
void parse_compress_specification(pg_compress_algorithm algorithm, char *specification, pg_compress_specification *result)
Definition: compression.c:105
char * validate_compress_specification(pg_compress_specification *spec)
Definition: compression.c:300
pg_compress_algorithm
Definition: compression.h:18
@ PG_COMPRESSION_GZIP
Definition: compression.h:20
@ PG_COMPRESSION_LZ4
Definition: compression.h:21
@ PG_COMPRESSION_NONE
Definition: compression.h:19
@ PG_COMPRESSION_ZSTD
Definition: compression.h:22
bool defGetBoolean(DefElem *def)
Definition: define.c:108
char * defGetString(DefElem *def)
Definition: define.c:49
int64 defGetInt64(DefElem *def)
Definition: define.c:187
#define PG_DYNSHMEM_DIR
Definition: dsm_impl.h:51
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1016
int errcode_for_file_access(void)
Definition: elog.c:718
int errhint(const char *fmt,...)
Definition: elog.c:1153
int errcode(int sqlerrcode)
Definition: elog.c:695
int errmsg(const char *fmt,...)
Definition: elog.c:906
#define PG_TRY(...)
Definition: elog.h:309
#define WARNING
Definition: elog.h:32
#define DEBUG2
Definition: elog.h:25
#define PG_END_TRY(...)
Definition: elog.h:334
#define DEBUG1
Definition: elog.h:26
#define ERROR
Definition: elog.h:35
#define PG_FINALLY(...)
Definition: elog.h:326
#define ereport(elevel,...)
Definition: elog.h:145
const char * name
Definition: encode.c:561
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2709
int FreeDir(DIR *dir)
Definition: fd.c:2761
int CloseTransientFile(int fd)
Definition: fd.c:2609
bool looks_like_temp_rel_name(const char *name)
Definition: fd.c:3249
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2433
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2643
int pg_file_create_mode
Definition: file_perm.c:19
int pg_dir_create_mode
Definition: file_perm.c:18
#define PG_AUTOCONF_FILENAME
Definition: guc.h:33
int remaining
Definition: informix.c:667
#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
int b
Definition: isn.c:70
int a
Definition: isn.c:69
int i
Definition: isn.c:73
Assert(fmt[strlen(fmt) - 1] !='\n')
void list_sort(List *list, list_sort_comparator cmp)
Definition: list.c:1673
List * lappend(List *list, void *datum)
Definition: list.c:338
char * pstrdup(const char *in)
Definition: mcxt.c:1483
void pfree(void *pointer)
Definition: mcxt.c:1306
void * palloc0(Size size)
Definition: mcxt.c:1230
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
static bool manifest
static int32 maxrate
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:41
#define PG_TEMP_FILE_PREFIX
Definition: pg_checksums.c:63
#define MAXPGPATH
const void size_t len
static char * filename
Definition: pg_dumpall.c:119
#define lfirst(lc)
Definition: pg_list.h:170
#define NIL
Definition: pg_list.h:66
#define linitial(l)
Definition: pg_list.h:176
static ListCell * lnext(const List *l, const ListCell *c)
Definition: pg_list.h:341
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225
static char * buf
Definition: pg_test_fsync.c:67
#define PG_STAT_TMP_DIR
Definition: pgstat.h:32
void pgstat_report_checksum_failures_in_db(Oid dboid, int failurecount)
static size_t tarPaddingBytesRequired(size_t len)
Definition: pgtar.h:40
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:114
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
int64 pg_time_t
Definition: pgtime.h:23
char * last_dir_separator(const char *filename)
Definition: path.c:139
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
#define pg_pread
Definition: port.h:225
#define snprintf
Definition: port.h:238
static Datum BoolGetDatum(bool X)
Definition: postgres.h:450
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
#define atooid(x)
Definition: postgres_ext.h:42
static int fd(const char *x, int i)
Definition: preproc-init.c:105
bool update_process_title
Definition: ps_status.c:35
void set_ps_display(const char *activity)
Definition: ps_status.c:342
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
bool parse_filename_for_nontemp_relation(const char *name, int *relnumchars, ForkNumber *fork)
Definition: reinit.c:381
#define RELCACHE_INIT_FILENAME
Definition: relcache.h:25
ForkNumber
Definition: relpath.h:48
@ INIT_FORKNUM
Definition: relpath.h:53
#define OIDCHARS
Definition: relpath.h:37
#define TABLESPACE_VERSION_DIRECTORY
Definition: relpath.h:33
ResourceOwner ResourceOwnerCreate(ResourceOwner parent, const char *name)
Definition: resowner.c:428
ResourceOwner CurrentResourceOwner
Definition: resowner.c:146
StringInfo makeStringInfo(void)
Definition: stringinfo.c:41
TimeLineID starttli
Definition: xlogbackup.h:27
XLogRecPtr startpoint
Definition: xlogbackup.h:26
TimeLineID stoptli
Definition: xlogbackup.h:34
XLogRecPtr stoppoint
Definition: xlogbackup.h:33
List * options
Definition: replnodes.h:44
Definition: dirent.c:26
char * defname
Definition: parsenodes.h:775
Definition: pg_list.h:52
uint16 pd_checksum
Definition: bufpage.h:160
pg_compress_specification compression_specification
Definition: basebackup.c:74
pg_checksum_type manifest_checksum_type
Definition: basebackup.c:75
const char * label
Definition: basebackup.c:62
pg_compress_algorithm compression
Definition: basebackup.c:73
backup_manifest_option manifest
Definition: basebackup.c:72
BaseBackupTargetHandle * target_handle
Definition: basebackup.c:71
XLogRecPtr startptr
bbsink_state * bbs_state
char * bbs_buffer
size_t bbs_buffer_length
Definition: dirent.h:10
char d_name[MAX_PATH]
Definition: dirent.h:15
const char * name
Definition: basebackup.c:118
pg_compress_algorithm algorithm
Definition: compression.h:29
__time64_t st_mtime
Definition: win32_port.h:277
__int64 st_size
Definition: win32_port.h:275
short st_gid
Definition: win32_port.h:273
unsigned short st_mode
Definition: win32_port.h:270
short st_uid
Definition: win32_port.h:272
Definition: regguts.h:318
char * rpath
Definition: basebackup.h:32
#define LOG_METAINFO_DATAFILE_TMP
Definition: syslogger.h:101
@ WAIT_EVENT_BASEBACKUP_READ
Definition: wait_event.h:161
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:268
static void pgstat_report_wait_end(void)
Definition: wait_event.h:284
void WalSndSetState(WalSndState state)
Definition: walsender.c:3405
void WalSndResourceCleanup(bool isCommit)
Definition: walsender.c:350
@ WALSNDSTATE_BACKUP
#define lstat(path, sb)
Definition: win32_port.h:287
#define S_ISDIR(m)
Definition: win32_port.h:327
#define S_ISLNK(m)
Definition: win32_port.h:346
#define fstat
Definition: win32_port.h:285
#define readlink(path, buf, size)
Definition: win32_port.h:238
#define S_ISREG(m)
Definition: win32_port.h:330
#define pgoff_t
Definition: win32_port.h:211
bool RecoveryInProgress(void)
Definition: xlog.c:5912
void do_pg_abort_backup(int code, Datum arg)
Definition: xlog.c:8817
SessionBackupState get_backup_status(void)
Definition: xlog.c:8524
void CheckXLogRemoved(XLogSegNo segno, TimeLineID tli)
Definition: xlog.c:3430
int wal_segment_size
Definition: xlog.c:146
bool DataChecksumsEnabled(void)
Definition: xlog.c:4201
void do_pg_backup_start(const char *backupidstr, bool fast, List **tablespaces, BackupState *state, StringInfo tblspcmapfile)
Definition: xlog.c:8244
void do_pg_backup_stop(BackupState *state, bool waitforarchive)
Definition: xlog.c:8543
#define TABLESPACE_MAP
Definition: xlog.h:293
#define BACKUP_LABEL_FILE
Definition: xlog.h:290
SessionBackupState
Definition: xlog.h:274
@ SESSION_BACKUP_RUNNING
Definition: xlog.h:276
#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:59
uint64 XLogSegNo
Definition: xlogdefs.h:48
static BackupState * backup_state
Definition: xlogfuncs.c:45
static StringInfo tablespace_map
Definition: xlogfuncs.c:46