PostgreSQL Source Code  git master
pg_basebackup.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * pg_basebackup.c - receive a base backup using streaming replication protocol
4  *
5  * Author: Magnus Hagander <magnus@hagander.net>
6  *
7  * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
8  *
9  * IDENTIFICATION
10  * src/bin/pg_basebackup/pg_basebackup.c
11  *-------------------------------------------------------------------------
12  */
13 
14 #include "postgres_fe.h"
15 
16 #include <unistd.h>
17 #include <dirent.h>
18 #include <limits.h>
19 #include <sys/select.h>
20 #include <sys/stat.h>
21 #include <sys/wait.h>
22 #include <signal.h>
23 #include <time.h>
24 #ifdef HAVE_LIBZ
25 #include <zlib.h>
26 #endif
27 
28 #include "access/xlog_internal.h"
29 #include "backup/basebackup.h"
30 #include "bbstreamer.h"
31 #include "common/compression.h"
32 #include "common/file_perm.h"
33 #include "common/file_utils.h"
34 #include "common/logging.h"
35 #include "fe_utils/option_utils.h"
36 #include "fe_utils/recovery_gen.h"
37 #include "getopt_long.h"
38 #include "receivelog.h"
39 #include "streamutil.h"
40 
41 #define ERRCODE_DATA_CORRUPTED "XX001"
42 
43 typedef struct TablespaceListCell
44 {
49 
50 typedef struct TablespaceList
51 {
55 
56 typedef struct ArchiveStreamState
57 {
66 
67 typedef struct WriteTarState
68 {
72 
73 typedef struct WriteManifestState
74 {
76  FILE *file;
78 
79 typedef void (*WriteDataCallback) (size_t nbytes, char *buf,
80  void *callback_data);
81 
82 /*
83  * pg_xlog has been renamed to pg_wal in version 10. This version number
84  * should be compared with PQserverVersion().
85  */
86 #define MINIMUM_VERSION_FOR_PG_WAL 100000
87 
88 /*
89  * Temporary replication slots are supported from version 10.
90  */
91 #define MINIMUM_VERSION_FOR_TEMP_SLOTS 100000
92 
93 /*
94  * Backup manifests are supported from version 13.
95  */
96 #define MINIMUM_VERSION_FOR_MANIFESTS 130000
97 
98 /*
99  * Before v15, tar files received from the server will be improperly
100  * terminated.
101  */
102 #define MINIMUM_VERSION_FOR_TERMINATED_TARFILE 150000
103 
104 /*
105  * Different ways to include WAL
106  */
107 typedef enum
108 {
112 } IncludeWal;
113 
114 /*
115  * Different places to perform compression
116  */
117 typedef enum
118 {
123 
124 /* Global options */
125 static char *basedir = NULL;
126 static TablespaceList tablespace_dirs = {NULL, NULL};
127 static char *xlog_dir = NULL;
128 static char format = '\0'; /* p(lain)/t(ar) */
129 static char *label = "pg_basebackup base backup";
130 static bool noclean = false;
131 static bool checksum_failure = false;
132 static bool showprogress = false;
133 static bool estimatesize = true;
134 static int verbose = 0;
136 static bool fastcheckpoint = false;
137 static bool writerecoveryconf = false;
138 static bool do_sync = true;
139 static int standby_message_timeout = 10 * 1000; /* 10 sec = default */
141 static int32 maxrate = 0; /* no limit by default */
142 static char *replication_slot = NULL;
143 static bool temp_replication_slot = true;
144 static char *backup_target = NULL;
145 static bool create_slot = false;
146 static bool no_slot = false;
147 static bool verify_checksums = true;
148 static bool manifest = true;
149 static bool manifest_force_encode = false;
150 static char *manifest_checksums = NULL;
152 
153 static bool success = false;
154 static bool made_new_pgdata = false;
155 static bool found_existing_pgdata = false;
156 static bool made_new_xlogdir = false;
157 static bool found_existing_xlogdir = false;
158 static bool made_tablespace_dirs = false;
159 static bool found_tablespace_dirs = false;
160 
161 /* Progress indicators */
162 static uint64 totalsize_kb;
163 static uint64 totaldone;
164 static int tablespacecount;
165 static char *progress_filename = NULL;
166 
167 /* Pipe to communicate with background wal receiver process */
168 #ifndef WIN32
169 static int bgpipe[2] = {-1, -1};
170 #endif
171 
172 /* Handle to child process */
173 static pid_t bgchild = -1;
174 static bool in_log_streamer = false;
175 
176 /* Flag to indicate if child process exited unexpectedly */
177 static volatile sig_atomic_t bgchild_exited = false;
178 
179 /* End position for xlog streaming, empty string if unknown yet */
181 
182 #ifndef WIN32
183 static int has_xlogendptr = 0;
184 #else
185 static volatile LONG has_xlogendptr = 0;
186 #endif
187 
188 /* Contents of configuration file to be generated */
190 
191 /* Function headers */
192 static void usage(void);
193 static void verify_dir_is_empty_or_create(char *dirname, bool *created, bool *found);
194 static void progress_update_filename(const char *filename);
195 static void progress_report(int tablespacenum, bool force, bool finished);
196 
197 static bbstreamer *CreateBackupStreamer(char *archive_name, char *spclocation,
198  bbstreamer **manifest_inject_streamer_p,
199  bool is_recovery_guc_supported,
200  bool expect_unterminated_tarfile,
201  pg_compress_specification *compress);
202 static void ReceiveArchiveStreamChunk(size_t r, char *copybuf,
203  void *callback_data);
204 static char GetCopyDataByte(size_t r, char *copybuf, size_t *cursor);
205 static char *GetCopyDataString(size_t r, char *copybuf, size_t *cursor);
206 static uint64 GetCopyDataUInt64(size_t r, char *copybuf, size_t *cursor);
207 static void GetCopyDataEnd(size_t r, char *copybuf, size_t cursor);
208 static void ReportCopyDataParseError(size_t r, char *copybuf);
209 static void ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
210  bool tablespacenum, pg_compress_specification *compress);
211 static void ReceiveTarCopyChunk(size_t r, char *copybuf, void *callback_data);
212 static void ReceiveBackupManifest(PGconn *conn);
213 static void ReceiveBackupManifestChunk(size_t r, char *copybuf,
214  void *callback_data);
216 static void ReceiveBackupManifestInMemoryChunk(size_t r, char *copybuf,
217  void *callback_data);
218 static void BaseBackup(char *compression_algorithm, char *compression_detail,
219  CompressionLocation compressloc,
220  pg_compress_specification *client_compress);
221 
222 static bool reached_end_position(XLogRecPtr segendpos, uint32 timeline,
223  bool segment_finished);
224 
225 static const char *get_tablespace_mapping(const char *dir);
226 static void tablespace_list_append(const char *arg);
227 
228 
229 static void
231 {
232  if (success || in_log_streamer)
233  return;
234 
235  if (!noclean && !checksum_failure)
236  {
237  if (made_new_pgdata)
238  {
239  pg_log_info("removing data directory \"%s\"", basedir);
240  if (!rmtree(basedir, true))
241  pg_log_error("failed to remove data directory");
242  }
243  else if (found_existing_pgdata)
244  {
245  pg_log_info("removing contents of data directory \"%s\"", basedir);
246  if (!rmtree(basedir, false))
247  pg_log_error("failed to remove contents of data directory");
248  }
249 
250  if (made_new_xlogdir)
251  {
252  pg_log_info("removing WAL directory \"%s\"", xlog_dir);
253  if (!rmtree(xlog_dir, true))
254  pg_log_error("failed to remove WAL directory");
255  }
256  else if (found_existing_xlogdir)
257  {
258  pg_log_info("removing contents of WAL directory \"%s\"", xlog_dir);
259  if (!rmtree(xlog_dir, false))
260  pg_log_error("failed to remove contents of WAL directory");
261  }
262  }
263  else
264  {
266  pg_log_info("data directory \"%s\" not removed at user's request", basedir);
267 
269  pg_log_info("WAL directory \"%s\" not removed at user's request", xlog_dir);
270  }
271 
273  pg_log_info("changes to tablespace directories will not be undone");
274 }
275 
276 static void
278 {
279  if (conn != NULL)
280  PQfinish(conn);
281 }
282 
283 #ifndef WIN32
284 /*
285  * If the bgchild exits prematurely and raises a SIGCHLD signal, we can abort
286  * processing rather than wait until the backup has finished and error out at
287  * that time. On Windows, we use a background thread which can communicate
288  * without the need for a signal handler.
289  */
290 static void
292 {
293  bgchild_exited = true;
294 }
295 
296 /*
297  * On windows, our background thread dies along with the process. But on
298  * Unix, if we have started a subprocess, we want to kill it off so it
299  * doesn't remain running trying to stream data.
300  */
301 static void
303 {
304  if (bgchild > 0 && !bgchild_exited)
305  kill(bgchild, SIGTERM);
306 }
307 #endif
308 
309 /*
310  * Split argument into old_dir and new_dir and append to tablespace mapping
311  * list.
312  */
313 static void
315 {
317  char *dst;
318  char *dst_ptr;
319  const char *arg_ptr;
320 
321  dst_ptr = dst = cell->old_dir;
322  for (arg_ptr = arg; *arg_ptr; arg_ptr++)
323  {
324  if (dst_ptr - dst >= MAXPGPATH)
325  pg_fatal("directory name too long");
326 
327  if (*arg_ptr == '\\' && *(arg_ptr + 1) == '=')
328  ; /* skip backslash escaping = */
329  else if (*arg_ptr == '=' && (arg_ptr == arg || *(arg_ptr - 1) != '\\'))
330  {
331  if (*cell->new_dir)
332  pg_fatal("multiple \"=\" signs in tablespace mapping");
333  else
334  dst = dst_ptr = cell->new_dir;
335  }
336  else
337  *dst_ptr++ = *arg_ptr;
338  }
339 
340  if (!*cell->old_dir || !*cell->new_dir)
341  pg_fatal("invalid tablespace mapping format \"%s\", must be \"OLDDIR=NEWDIR\"", arg);
342 
343  /*
344  * All tablespaces are created with absolute directories, so specifying a
345  * non-absolute path here would just never match, possibly confusing
346  * users. Since we don't know whether the remote side is Windows or not,
347  * and it might be different than the local side, permit any path that
348  * could be absolute under either set of rules.
349  *
350  * (There is little practical risk of confusion here, because someone
351  * running entirely on Linux isn't likely to have a relative path that
352  * begins with a backslash or something that looks like a drive
353  * specification. If they do, and they also incorrectly believe that a
354  * relative path is acceptable here, we'll silently fail to warn them of
355  * their mistake, and the -T option will just not get applied, same as if
356  * they'd specified -T for a nonexistent tablespace.)
357  */
358  if (!is_nonwindows_absolute_path(cell->old_dir) &&
360  pg_fatal("old directory is not an absolute path in tablespace mapping: %s",
361  cell->old_dir);
362 
363  if (!is_absolute_path(cell->new_dir))
364  pg_fatal("new directory is not an absolute path in tablespace mapping: %s",
365  cell->new_dir);
366 
367  /*
368  * Comparisons done with these values should involve similarly
369  * canonicalized path values. This is particularly sensitive on Windows
370  * where path values may not necessarily use Unix slashes.
371  */
372  canonicalize_path(cell->old_dir);
373  canonicalize_path(cell->new_dir);
374 
375  if (tablespace_dirs.tail)
376  tablespace_dirs.tail->next = cell;
377  else
378  tablespace_dirs.head = cell;
379  tablespace_dirs.tail = cell;
380 }
381 
382 
383 static void
384 usage(void)
385 {
386  printf(_("%s takes a base backup of a running PostgreSQL server.\n\n"),
387  progname);
388  printf(_("Usage:\n"));
389  printf(_(" %s [OPTION]...\n"), progname);
390  printf(_("\nOptions controlling the output:\n"));
391  printf(_(" -D, --pgdata=DIRECTORY receive base backup into directory\n"));
392  printf(_(" -F, --format=p|t output format (plain (default), tar)\n"));
393  printf(_(" -r, --max-rate=RATE maximum transfer rate to transfer data directory\n"
394  " (in kB/s, or use suffix \"k\" or \"M\")\n"));
395  printf(_(" -R, --write-recovery-conf\n"
396  " write configuration for replication\n"));
397  printf(_(" -t, --target=TARGET[:DETAIL]\n"
398  " backup target (if other than client)\n"));
399  printf(_(" -T, --tablespace-mapping=OLDDIR=NEWDIR\n"
400  " relocate tablespace in OLDDIR to NEWDIR\n"));
401  printf(_(" --waldir=WALDIR location for the write-ahead log directory\n"));
402  printf(_(" -X, --wal-method=none|fetch|stream\n"
403  " include required WAL files with specified method\n"));
404  printf(_(" -z, --gzip compress tar output\n"));
405  printf(_(" -Z, --compress=[{client|server}-]METHOD[:DETAIL]\n"
406  " compress on client or server as specified\n"));
407  printf(_(" -Z, --compress=none do not compress tar output\n"));
408  printf(_("\nGeneral options:\n"));
409  printf(_(" -c, --checkpoint=fast|spread\n"
410  " set fast or spread checkpointing\n"));
411  printf(_(" -C, --create-slot create replication slot\n"));
412  printf(_(" -l, --label=LABEL set backup label\n"));
413  printf(_(" -n, --no-clean do not clean up after errors\n"));
414  printf(_(" -N, --no-sync do not wait for changes to be written safely to disk\n"));
415  printf(_(" -P, --progress show progress information\n"));
416  printf(_(" -S, --slot=SLOTNAME replication slot to use\n"));
417  printf(_(" -v, --verbose output verbose messages\n"));
418  printf(_(" -V, --version output version information, then exit\n"));
419  printf(_(" --manifest-checksums=SHA{224,256,384,512}|CRC32C|NONE\n"
420  " use algorithm for manifest checksums\n"));
421  printf(_(" --manifest-force-encode\n"
422  " hex encode all file names in manifest\n"));
423  printf(_(" --no-estimate-size do not estimate backup size in server side\n"));
424  printf(_(" --no-manifest suppress generation of backup manifest\n"));
425  printf(_(" --no-slot prevent creation of temporary replication slot\n"));
426  printf(_(" --no-verify-checksums\n"
427  " do not verify checksums\n"));
428  printf(_(" --sync-method=METHOD\n"
429  " set method for syncing files to disk\n"));
430  printf(_(" -?, --help show this help, then exit\n"));
431  printf(_("\nConnection options:\n"));
432  printf(_(" -d, --dbname=CONNSTR connection string\n"));
433  printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
434  printf(_(" -p, --port=PORT database server port number\n"));
435  printf(_(" -s, --status-interval=INTERVAL\n"
436  " time between status packets sent to server (in seconds)\n"));
437  printf(_(" -U, --username=NAME connect as specified database user\n"));
438  printf(_(" -w, --no-password never prompt for password\n"));
439  printf(_(" -W, --password force password prompt (should happen automatically)\n"));
440  printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
441  printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
442 }
443 
444 
445 /*
446  * Called in the background process every time data is received.
447  * On Unix, we check to see if there is any data on our pipe
448  * (which would mean we have a stop position), and if it is, check if
449  * it is time to stop.
450  * On Windows, we are in a single process, so we can just check if it's
451  * time to stop.
452  */
453 static bool
455  bool segment_finished)
456 {
457  if (!has_xlogendptr)
458  {
459 #ifndef WIN32
460  fd_set fds;
461  struct timeval tv = {0};
462  int r;
463 
464  /*
465  * Don't have the end pointer yet - check our pipe to see if it has
466  * been sent yet.
467  */
468  FD_ZERO(&fds);
469  FD_SET(bgpipe[0], &fds);
470 
471  r = select(bgpipe[0] + 1, &fds, NULL, NULL, &tv);
472  if (r == 1)
473  {
474  char xlogend[64] = {0};
475  uint32 hi,
476  lo;
477 
478  r = read(bgpipe[0], xlogend, sizeof(xlogend) - 1);
479  if (r < 0)
480  pg_fatal("could not read from ready pipe: %m");
481 
482  if (sscanf(xlogend, "%X/%X", &hi, &lo) != 2)
483  pg_fatal("could not parse write-ahead log location \"%s\"",
484  xlogend);
485  xlogendptr = ((uint64) hi) << 32 | lo;
486  has_xlogendptr = 1;
487 
488  /*
489  * Fall through to check if we've reached the point further
490  * already.
491  */
492  }
493  else
494  {
495  /*
496  * No data received on the pipe means we don't know the end
497  * position yet - so just say it's not time to stop yet.
498  */
499  return false;
500  }
501 #else
502 
503  /*
504  * On win32, has_xlogendptr is set by the main thread, so if it's not
505  * set here, we just go back and wait until it shows up.
506  */
507  return false;
508 #endif
509  }
510 
511  /*
512  * At this point we have an end pointer, so compare it to the current
513  * position to figure out if it's time to stop.
514  */
515  if (segendpos >= xlogendptr)
516  return true;
517 
518  /*
519  * Have end pointer, but haven't reached it yet - so tell the caller to
520  * keep streaming.
521  */
522  return false;
523 }
524 
525 typedef struct
526 {
529  char xlog[MAXPGPATH]; /* directory or tarfile depending on mode */
531  int timeline;
535 
536 static int
538 {
539  StreamCtl stream = {0};
540 
541  in_log_streamer = true;
542 
543  stream.startpos = param->startptr;
544  stream.timeline = param->timeline;
545  stream.sysidentifier = param->sysidentifier;
547 #ifndef WIN32
548  stream.stop_socket = bgpipe[0];
549 #else
550  stream.stop_socket = PGINVALID_SOCKET;
551 #endif
553  stream.synchronous = false;
554  /* fsync happens at the end of pg_basebackup for all data */
555  stream.do_sync = false;
556  stream.mark_done = true;
557  stream.partial_suffix = NULL;
559  if (format == 'p')
560  stream.walmethod = CreateWalDirectoryMethod(param->xlog,
562  stream.do_sync);
563  else
564  stream.walmethod = CreateWalTarMethod(param->xlog,
565  param->wal_compress_algorithm,
566  param->wal_compress_level,
567  stream.do_sync);
568 
569  if (!ReceiveXlogStream(param->bgconn, &stream))
570  {
571  /*
572  * Any errors will already have been reported in the function process,
573  * but we need to tell the parent that we didn't shutdown in a nice
574  * way.
575  */
576 #ifdef WIN32
577  /*
578  * In order to signal the main thread of an ungraceful exit we set the
579  * same flag that we use on Unix to signal SIGCHLD.
580  */
581  bgchild_exited = true;
582 #endif
583  return 1;
584  }
585 
586  if (!stream.walmethod->ops->finish(stream.walmethod))
587  {
588  pg_log_error("could not finish writing WAL files: %m");
589 #ifdef WIN32
590  bgchild_exited = true;
591 #endif
592  return 1;
593  }
594 
595  PQfinish(param->bgconn);
596 
597  stream.walmethod->ops->free(stream.walmethod);
598 
599  return 0;
600 }
601 
602 /*
603  * Initiate background process for receiving xlog during the backup.
604  * The background stream will use its own database connection so we can
605  * stream the logfile in parallel with the backups.
606  */
607 static void
608 StartLogStreamer(char *startpos, uint32 timeline, char *sysidentifier,
609  pg_compress_algorithm wal_compress_algorithm,
610  int wal_compress_level)
611 {
612  logstreamer_param *param;
613  uint32 hi,
614  lo;
615  char statusdir[MAXPGPATH];
616 
617  param = pg_malloc0(sizeof(logstreamer_param));
618  param->timeline = timeline;
619  param->sysidentifier = sysidentifier;
620  param->wal_compress_algorithm = wal_compress_algorithm;
621  param->wal_compress_level = wal_compress_level;
622 
623  /* Convert the starting position */
624  if (sscanf(startpos, "%X/%X", &hi, &lo) != 2)
625  pg_fatal("could not parse write-ahead log location \"%s\"",
626  startpos);
627  param->startptr = ((uint64) hi) << 32 | lo;
628  /* Round off to even segment position */
629  param->startptr -= XLogSegmentOffset(param->startptr, WalSegSz);
630 
631 #ifndef WIN32
632  /* Create our background pipe */
633  if (pipe(bgpipe) < 0)
634  pg_fatal("could not create pipe for background process: %m");
635 #endif
636 
637  /* Get a second connection */
638  param->bgconn = GetConnection();
639  if (!param->bgconn)
640  /* Error message already written in GetConnection() */
641  exit(1);
642 
643  /* In post-10 cluster, pg_xlog has been renamed to pg_wal */
644  snprintf(param->xlog, sizeof(param->xlog), "%s/%s",
645  basedir,
647  "pg_xlog" : "pg_wal");
648 
649  /* Temporary replication slots are only supported in 10 and newer */
651  temp_replication_slot = false;
652 
653  /*
654  * Create replication slot if requested
655  */
657  replication_slot = psprintf("pg_basebackup_%u",
658  (unsigned int) PQbackendPID(param->bgconn));
660  {
661  if (!CreateReplicationSlot(param->bgconn, replication_slot, NULL,
662  temp_replication_slot, true, true, false, false))
663  exit(1);
664 
665  if (verbose)
666  {
668  pg_log_info("created temporary replication slot \"%s\"",
670  else
671  pg_log_info("created replication slot \"%s\"",
673  }
674  }
675 
676  if (format == 'p')
677  {
678  /*
679  * Create pg_wal/archive_status or pg_xlog/archive_status (and thus
680  * pg_wal or pg_xlog) depending on the target server so we can write
681  * to basedir/pg_wal or basedir/pg_xlog as the directory entry in the
682  * tar file may arrive later.
683  */
684  snprintf(statusdir, sizeof(statusdir), "%s/%s/archive_status",
685  basedir,
687  "pg_xlog" : "pg_wal");
688 
689  if (pg_mkdir_p(statusdir, pg_dir_create_mode) != 0 && errno != EEXIST)
690  pg_fatal("could not create directory \"%s\": %m", statusdir);
691  }
692 
693  /*
694  * Start a child process and tell it to start streaming. On Unix, this is
695  * a fork(). On Windows, we create a thread.
696  */
697 #ifndef WIN32
698  bgchild = fork();
699  if (bgchild == 0)
700  {
701  /* in child process */
702  exit(LogStreamerMain(param));
703  }
704  else if (bgchild < 0)
705  pg_fatal("could not create background process: %m");
706 
707  /*
708  * Else we are in the parent process and all is well.
709  */
710  atexit(kill_bgchild_atexit);
711 #else /* WIN32 */
712  bgchild = _beginthreadex(NULL, 0, (void *) LogStreamerMain, param, 0, NULL);
713  if (bgchild == 0)
714  pg_fatal("could not create background thread: %m");
715 #endif
716 }
717 
718 /*
719  * Verify that the given directory exists and is empty. If it does not
720  * exist, it is created. If it exists but is not empty, an error will
721  * be given and the process ended.
722  */
723 static void
724 verify_dir_is_empty_or_create(char *dirname, bool *created, bool *found)
725 {
726  switch (pg_check_dir(dirname))
727  {
728  case 0:
729 
730  /*
731  * Does not exist, so create
732  */
733  if (pg_mkdir_p(dirname, pg_dir_create_mode) == -1)
734  pg_fatal("could not create directory \"%s\": %m", dirname);
735  if (created)
736  *created = true;
737  return;
738  case 1:
739 
740  /*
741  * Exists, empty
742  */
743  if (found)
744  *found = true;
745  return;
746  case 2:
747  case 3:
748  case 4:
749 
750  /*
751  * Exists, not empty
752  */
753  pg_fatal("directory \"%s\" exists but is not empty", dirname);
754  case -1:
755 
756  /*
757  * Access problem
758  */
759  pg_fatal("could not access directory \"%s\": %m", dirname);
760  }
761 }
762 
763 /*
764  * Callback to update our notion of the current filename.
765  *
766  * No other code should modify progress_filename!
767  */
768 static void
770 {
771  /* We needn't maintain this variable if not doing verbose reports. */
772  if (showprogress && verbose)
773  {
775  if (filename)
777  else
778  progress_filename = NULL;
779  }
780 }
781 
782 /*
783  * Print a progress report based on the global variables. If verbose output
784  * is enabled, also print the current file name.
785  *
786  * Progress report is written at maximum once per second, unless the force
787  * parameter is set to true.
788  *
789  * If finished is set to true, this is the last progress report. The cursor
790  * is moved to the next line.
791  */
792 static void
793 progress_report(int tablespacenum, bool force, bool finished)
794 {
795  int percent;
796  char totaldone_str[32];
797  char totalsize_str[32];
798  pg_time_t now;
799 
800  if (!showprogress)
801  return;
802 
803  now = time(NULL);
804  if (now == last_progress_report && !force && !finished)
805  return; /* Max once per second */
806 
808  percent = totalsize_kb ? (int) ((totaldone / 1024) * 100 / totalsize_kb) : 0;
809 
810  /*
811  * Avoid overflowing past 100% or the full size. This may make the total
812  * size number change as we approach the end of the backup (the estimate
813  * will always be wrong if WAL is included), but that's better than having
814  * the done column be bigger than the total.
815  */
816  if (percent > 100)
817  percent = 100;
818  if (totaldone / 1024 > totalsize_kb)
819  totalsize_kb = totaldone / 1024;
820 
821  snprintf(totaldone_str, sizeof(totaldone_str), UINT64_FORMAT,
822  totaldone / 1024);
823  snprintf(totalsize_str, sizeof(totalsize_str), UINT64_FORMAT, totalsize_kb);
824 
825 #define VERBOSE_FILENAME_LENGTH 35
826  if (verbose)
827  {
828  if (!progress_filename)
829 
830  /*
831  * No filename given, so clear the status line (used for last
832  * call)
833  */
834  fprintf(stderr,
835  ngettext("%*s/%s kB (100%%), %d/%d tablespace %*s",
836  "%*s/%s kB (100%%), %d/%d tablespaces %*s",
838  (int) strlen(totalsize_str),
839  totaldone_str, totalsize_str,
840  tablespacenum, tablespacecount,
841  VERBOSE_FILENAME_LENGTH + 5, "");
842  else
843  {
844  bool truncate = (strlen(progress_filename) > VERBOSE_FILENAME_LENGTH);
845 
846  fprintf(stderr,
847  ngettext("%*s/%s kB (%d%%), %d/%d tablespace (%s%-*.*s)",
848  "%*s/%s kB (%d%%), %d/%d tablespaces (%s%-*.*s)",
850  (int) strlen(totalsize_str),
851  totaldone_str, totalsize_str, percent,
852  tablespacenum, tablespacecount,
853  /* Prefix with "..." if we do leading truncation */
854  truncate ? "..." : "",
857  /* Truncate filename at beginning if it's too long */
859  }
860  }
861  else
862  fprintf(stderr,
863  ngettext("%*s/%s kB (%d%%), %d/%d tablespace",
864  "%*s/%s kB (%d%%), %d/%d tablespaces",
866  (int) strlen(totalsize_str),
867  totaldone_str, totalsize_str, percent,
868  tablespacenum, tablespacecount);
869 
870  /*
871  * Stay on the same line if reporting to a terminal and we're not done
872  * yet.
873  */
874  fputc((!finished && isatty(fileno(stderr))) ? '\r' : '\n', stderr);
875 }
876 
877 static int32
878 parse_max_rate(char *src)
879 {
880  double result;
881  char *after_num;
882  char *suffix = NULL;
883 
884  errno = 0;
885  result = strtod(src, &after_num);
886  if (src == after_num)
887  pg_fatal("transfer rate \"%s\" is not a valid value", src);
888  if (errno != 0)
889  pg_fatal("invalid transfer rate \"%s\": %m", src);
890 
891  if (result <= 0)
892  {
893  /*
894  * Reject obviously wrong values here.
895  */
896  pg_fatal("transfer rate must be greater than zero");
897  }
898 
899  /*
900  * Evaluate suffix, after skipping over possible whitespace. Lack of
901  * suffix means kilobytes.
902  */
903  while (*after_num != '\0' && isspace((unsigned char) *after_num))
904  after_num++;
905 
906  if (*after_num != '\0')
907  {
908  suffix = after_num;
909  if (*after_num == 'k')
910  {
911  /* kilobyte is the expected unit. */
912  after_num++;
913  }
914  else if (*after_num == 'M')
915  {
916  after_num++;
917  result *= 1024.0;
918  }
919  }
920 
921  /* The rest can only consist of white space. */
922  while (*after_num != '\0' && isspace((unsigned char) *after_num))
923  after_num++;
924 
925  if (*after_num != '\0')
926  pg_fatal("invalid --max-rate unit: \"%s\"", suffix);
927 
928  /* Valid integer? */
929  if ((uint64) result != (uint64) ((uint32) result))
930  pg_fatal("transfer rate \"%s\" exceeds integer range", src);
931 
932  /*
933  * The range is checked on the server side too, but avoid the server
934  * connection if a nonsensical value was passed.
935  */
936  if (result < MAX_RATE_LOWER || result > MAX_RATE_UPPER)
937  pg_fatal("transfer rate \"%s\" is out of range", src);
938 
939  return (int32) result;
940 }
941 
942 /*
943  * Basic parsing of a value specified for -Z/--compress.
944  *
945  * We're not concerned here with understanding exactly what behavior the
946  * user wants, but we do need to know whether the user is requesting client
947  * or server side compression or leaving it unspecified, and we need to
948  * separate the name of the compression algorithm from the detail string.
949  *
950  * For instance, if the user writes --compress client-lz4:6, we want to
951  * separate that into (a) client-side compression, (b) algorithm "lz4",
952  * and (c) detail "6". Note, however, that all the client/server prefix is
953  * optional, and so is the detail. The algorithm name is required, unless
954  * the whole string is an integer, in which case we assume "gzip" as the
955  * algorithm and use the integer as the detail.
956  *
957  * We're not concerned with validation at this stage, so if the user writes
958  * --compress client-turkey:sandwich, the requested algorithm is "turkey"
959  * and the detail string is "sandwich". We'll sort out whether that's legal
960  * at a later stage.
961  */
962 static void
963 backup_parse_compress_options(char *option, char **algorithm, char **detail,
964  CompressionLocation *locationres)
965 {
966  /*
967  * Strip off any "client-" or "server-" prefix, calculating the location.
968  */
969  if (strncmp(option, "server-", 7) == 0)
970  {
971  *locationres = COMPRESS_LOCATION_SERVER;
972  option += 7;
973  }
974  else if (strncmp(option, "client-", 7) == 0)
975  {
976  *locationres = COMPRESS_LOCATION_CLIENT;
977  option += 7;
978  }
979  else
980  *locationres = COMPRESS_LOCATION_UNSPECIFIED;
981 
982  /* fallback to the common parsing for the algorithm and detail */
983  parse_compress_options(option, algorithm, detail);
984 }
985 
986 /*
987  * Read a stream of COPY data and invoke the provided callback for each
988  * chunk.
989  */
990 static void
992  void *callback_data)
993 {
994  PGresult *res;
995 
996  /* Get the COPY data stream. */
997  res = PQgetResult(conn);
999  pg_fatal("could not get COPY data stream: %s",
1000  PQerrorMessage(conn));
1001  PQclear(res);
1002 
1003  /* Loop over chunks until done. */
1004  while (1)
1005  {
1006  int r;
1007  char *copybuf;
1008 
1009  r = PQgetCopyData(conn, &copybuf, 0);
1010  if (r == -1)
1011  {
1012  /* End of chunk. */
1013  break;
1014  }
1015  else if (r == -2)
1016  pg_fatal("could not read COPY data: %s",
1017  PQerrorMessage(conn));
1018 
1019  if (bgchild_exited)
1020  pg_fatal("background process terminated unexpectedly");
1021 
1022  (*callback) (r, copybuf, callback_data);
1023 
1024  PQfreemem(copybuf);
1025  }
1026 }
1027 
1028 /*
1029  * Figure out what to do with an archive received from the server based on
1030  * the options selected by the user. We may just write the results directly
1031  * to a file, or we might compress first, or we might extract the tar file
1032  * and write each member separately. This function doesn't do any of that
1033  * directly, but it works out what kind of bbstreamer we need to create so
1034  * that the right stuff happens when, down the road, we actually receive
1035  * the data.
1036  */
1037 static bbstreamer *
1038 CreateBackupStreamer(char *archive_name, char *spclocation,
1039  bbstreamer **manifest_inject_streamer_p,
1040  bool is_recovery_guc_supported,
1041  bool expect_unterminated_tarfile,
1042  pg_compress_specification *compress)
1043 {
1044  bbstreamer *streamer = NULL;
1045  bbstreamer *manifest_inject_streamer = NULL;
1046  bool inject_manifest;
1047  bool is_tar,
1048  is_tar_gz,
1049  is_tar_lz4,
1050  is_tar_zstd,
1051  is_compressed_tar;
1052  bool must_parse_archive;
1053  int archive_name_len = strlen(archive_name);
1054 
1055  /*
1056  * Normally, we emit the backup manifest as a separate file, but when
1057  * we're writing a tarfile to stdout, we don't have that option, so
1058  * include it in the one tarfile we've got.
1059  */
1060  inject_manifest = (format == 't' && strcmp(basedir, "-") == 0 && manifest);
1061 
1062  /* Is this a tar archive? */
1063  is_tar = (archive_name_len > 4 &&
1064  strcmp(archive_name + archive_name_len - 4, ".tar") == 0);
1065 
1066  /* Is this a .tar.gz archive? */
1067  is_tar_gz = (archive_name_len > 7 &&
1068  strcmp(archive_name + archive_name_len - 7, ".tar.gz") == 0);
1069 
1070  /* Is this a .tar.lz4 archive? */
1071  is_tar_lz4 = (archive_name_len > 8 &&
1072  strcmp(archive_name + archive_name_len - 8, ".tar.lz4") == 0);
1073 
1074  /* Is this a .tar.zst archive? */
1075  is_tar_zstd = (archive_name_len > 8 &&
1076  strcmp(archive_name + archive_name_len - 8, ".tar.zst") == 0);
1077 
1078  /* Is this any kind of compressed tar? */
1079  is_compressed_tar = is_tar_gz || is_tar_lz4 || is_tar_zstd;
1080 
1081  /*
1082  * Injecting the manifest into a compressed tar file would be possible if
1083  * we decompressed it, parsed the tarfile, generated a new tarfile, and
1084  * recompressed it, but compressing and decompressing multiple times just
1085  * to inject the manifest seems inefficient enough that it's probably not
1086  * what the user wants. So, instead, reject the request and tell the user
1087  * to specify something more reasonable.
1088  */
1089  if (inject_manifest && is_compressed_tar)
1090  {
1091  pg_log_error("cannot inject manifest into a compressed tar file");
1092  pg_log_error_hint("Use client-side compression, send the output to a directory rather than standard output, or use %s.",
1093  "--no-manifest");
1094  exit(1);
1095  }
1096 
1097  /*
1098  * We have to parse the archive if (1) we're suppose to extract it, or if
1099  * (2) we need to inject backup_manifest or recovery configuration into
1100  * it. However, we only know how to parse tar archives.
1101  */
1102  must_parse_archive = (format == 'p' || inject_manifest ||
1103  (spclocation == NULL && writerecoveryconf));
1104 
1105  /* At present, we only know how to parse tar archives. */
1106  if (must_parse_archive && !is_tar && !is_compressed_tar)
1107  {
1108  pg_log_error("cannot parse archive \"%s\"", archive_name);
1109  pg_log_error_detail("Only tar archives can be parsed.");
1110  if (format == 'p')
1111  pg_log_error_detail("Plain format requires pg_basebackup to parse the archive.");
1112  if (inject_manifest)
1113  pg_log_error_detail("Using - as the output directory requires pg_basebackup to parse the archive.");
1114  if (writerecoveryconf)
1115  pg_log_error_detail("The -R option requires pg_basebackup to parse the archive.");
1116  exit(1);
1117  }
1118 
1119  if (format == 'p')
1120  {
1121  const char *directory;
1122 
1123  /*
1124  * In plain format, we must extract the archive. The data for the main
1125  * tablespace will be written to the base directory, and the data for
1126  * other tablespaces will be written to the directory where they're
1127  * located on the server, after applying any user-specified tablespace
1128  * mappings.
1129  *
1130  * In the case of an in-place tablespace, spclocation will be a
1131  * relative path. We just convert it to an absolute path by prepending
1132  * basedir.
1133  */
1134  if (spclocation == NULL)
1135  directory = basedir;
1136  else if (!is_absolute_path(spclocation))
1137  directory = psprintf("%s/%s", basedir, spclocation);
1138  else
1139  directory = get_tablespace_mapping(spclocation);
1143  }
1144  else
1145  {
1146  FILE *archive_file;
1147  char archive_filename[MAXPGPATH];
1148 
1149  /*
1150  * In tar format, we just write the archive without extracting it.
1151  * Normally, we write it to the archive name provided by the caller,
1152  * but when the base directory is "-" that means we need to write to
1153  * standard output.
1154  */
1155  if (strcmp(basedir, "-") == 0)
1156  {
1157  snprintf(archive_filename, sizeof(archive_filename), "-");
1158  archive_file = stdout;
1159  }
1160  else
1161  {
1162  snprintf(archive_filename, sizeof(archive_filename),
1163  "%s/%s", basedir, archive_name);
1164  archive_file = NULL;
1165  }
1166 
1167  if (compress->algorithm == PG_COMPRESSION_NONE)
1168  streamer = bbstreamer_plain_writer_new(archive_filename,
1169  archive_file);
1170  else if (compress->algorithm == PG_COMPRESSION_GZIP)
1171  {
1172  strlcat(archive_filename, ".gz", sizeof(archive_filename));
1173  streamer = bbstreamer_gzip_writer_new(archive_filename,
1174  archive_file, compress);
1175  }
1176  else if (compress->algorithm == PG_COMPRESSION_LZ4)
1177  {
1178  strlcat(archive_filename, ".lz4", sizeof(archive_filename));
1179  streamer = bbstreamer_plain_writer_new(archive_filename,
1180  archive_file);
1181  streamer = bbstreamer_lz4_compressor_new(streamer, compress);
1182  }
1183  else if (compress->algorithm == PG_COMPRESSION_ZSTD)
1184  {
1185  strlcat(archive_filename, ".zst", sizeof(archive_filename));
1186  streamer = bbstreamer_plain_writer_new(archive_filename,
1187  archive_file);
1188  streamer = bbstreamer_zstd_compressor_new(streamer, compress);
1189  }
1190  else
1191  {
1192  Assert(false); /* not reachable */
1193  }
1194 
1195  /*
1196  * If we need to parse the archive for whatever reason, then we'll
1197  * also need to re-archive, because, if the output format is tar, the
1198  * only point of parsing the archive is to be able to inject stuff
1199  * into it.
1200  */
1201  if (must_parse_archive)
1202  streamer = bbstreamer_tar_archiver_new(streamer);
1203  progress_update_filename(archive_filename);
1204  }
1205 
1206  /*
1207  * If we're supposed to inject the backup manifest into the results, it
1208  * should be done here, so that the file content can be injected directly,
1209  * without worrying about the details of the tar format.
1210  */
1211  if (inject_manifest)
1212  manifest_inject_streamer = streamer;
1213 
1214  /*
1215  * If this is the main tablespace and we're supposed to write recovery
1216  * information, arrange to do that.
1217  */
1218  if (spclocation == NULL && writerecoveryconf)
1219  {
1220  Assert(must_parse_archive);
1221  streamer = bbstreamer_recovery_injector_new(streamer,
1222  is_recovery_guc_supported,
1224  }
1225 
1226  /*
1227  * If we're doing anything that involves understanding the contents of the
1228  * archive, we'll need to parse it. If not, we can skip parsing it, but
1229  * old versions of the server send improperly terminated tarfiles, so if
1230  * we're talking to such a server we'll need to add the terminator here.
1231  */
1232  if (must_parse_archive)
1233  streamer = bbstreamer_tar_parser_new(streamer);
1234  else if (expect_unterminated_tarfile)
1235  streamer = bbstreamer_tar_terminator_new(streamer);
1236 
1237  /*
1238  * If the user has requested a server compressed archive along with
1239  * archive extraction at client then we need to decompress it.
1240  */
1241  if (format == 'p')
1242  {
1243  if (is_tar_gz)
1244  streamer = bbstreamer_gzip_decompressor_new(streamer);
1245  else if (is_tar_lz4)
1246  streamer = bbstreamer_lz4_decompressor_new(streamer);
1247  else if (is_tar_zstd)
1248  streamer = bbstreamer_zstd_decompressor_new(streamer);
1249  }
1250 
1251  /* Return the results. */
1252  *manifest_inject_streamer_p = manifest_inject_streamer;
1253  return streamer;
1254 }
1255 
1256 /*
1257  * Receive all of the archives the server wants to send - and the backup
1258  * manifest if present - as a single COPY stream.
1259  */
1260 static void
1262 {
1264 
1265  /* Set up initial state. */
1266  memset(&state, 0, sizeof(state));
1267  state.tablespacenum = -1;
1268  state.compress = compress;
1269 
1270  /* All the real work happens in ReceiveArchiveStreamChunk. */
1272 
1273  /* If we wrote the backup manifest to a file, close the file. */
1274  if (state.manifest_file !=NULL)
1275  {
1276  fclose(state.manifest_file);
1277  state.manifest_file = NULL;
1278  }
1279 
1280  /*
1281  * If we buffered the backup manifest in order to inject it into the
1282  * output tarfile, do that now.
1283  */
1284  if (state.manifest_inject_streamer != NULL &&
1285  state.manifest_buffer != NULL)
1286  {
1287  bbstreamer_inject_file(state.manifest_inject_streamer,
1288  "backup_manifest",
1289  state.manifest_buffer->data,
1290  state.manifest_buffer->len);
1291  destroyPQExpBuffer(state.manifest_buffer);
1292  state.manifest_buffer = NULL;
1293  }
1294 
1295  /* If there's still an archive in progress, end processing. */
1296  if (state.streamer != NULL)
1297  {
1298  bbstreamer_finalize(state.streamer);
1299  bbstreamer_free(state.streamer);
1300  state.streamer = NULL;
1301  }
1302 }
1303 
1304 /*
1305  * Receive one chunk of data sent by the server as part of a single COPY
1306  * stream that includes all archives and the manifest.
1307  */
1308 static void
1309 ReceiveArchiveStreamChunk(size_t r, char *copybuf, void *callback_data)
1310 {
1311  ArchiveStreamState *state = callback_data;
1312  size_t cursor = 0;
1313 
1314  /* Each CopyData message begins with a type byte. */
1315  switch (GetCopyDataByte(r, copybuf, &cursor))
1316  {
1317  case 'n':
1318  {
1319  /* New archive. */
1320  char *archive_name;
1321  char *spclocation;
1322 
1323  /*
1324  * We force a progress report at the end of each tablespace. A
1325  * new tablespace starts when the previous one ends, except in
1326  * the case of the very first one.
1327  */
1328  if (++state->tablespacenum > 0)
1329  progress_report(state->tablespacenum, true, false);
1330 
1331  /* Sanity check. */
1332  if (state->manifest_buffer != NULL ||
1333  state->manifest_file !=NULL)
1334  pg_fatal("archives must precede manifest");
1335 
1336  /* Parse the rest of the CopyData message. */
1337  archive_name = GetCopyDataString(r, copybuf, &cursor);
1338  spclocation = GetCopyDataString(r, copybuf, &cursor);
1340 
1341  /*
1342  * Basic sanity checks on the archive name: it shouldn't be
1343  * empty, it shouldn't start with a dot, and it shouldn't
1344  * contain a path separator.
1345  */
1346  if (archive_name[0] == '\0' || archive_name[0] == '.' ||
1347  strchr(archive_name, '/') != NULL ||
1348  strchr(archive_name, '\\') != NULL)
1349  pg_fatal("invalid archive name: \"%s\"",
1350  archive_name);
1351 
1352  /*
1353  * An empty spclocation is treated as NULL. We expect this
1354  * case to occur for the data directory itself, but not for
1355  * any archives that correspond to tablespaces.
1356  */
1357  if (spclocation[0] == '\0')
1358  spclocation = NULL;
1359 
1360  /* End processing of any prior archive. */
1361  if (state->streamer != NULL)
1362  {
1363  bbstreamer_finalize(state->streamer);
1364  bbstreamer_free(state->streamer);
1365  state->streamer = NULL;
1366  }
1367 
1368  /*
1369  * Create an appropriate backup streamer, unless a backup
1370  * target was specified. In that case, it's up to the server
1371  * to put the backup wherever it needs to go.
1372  */
1373  if (backup_target == NULL)
1374  {
1375  /*
1376  * We know that recovery GUCs are supported, because this
1377  * protocol can only be used on v15+.
1378  */
1379  state->streamer =
1380  CreateBackupStreamer(archive_name,
1381  spclocation,
1382  &state->manifest_inject_streamer,
1383  true, false,
1384  state->compress);
1385  }
1386  break;
1387  }
1388 
1389  case 'd':
1390  {
1391  /* Archive or manifest data. */
1392  if (state->manifest_buffer != NULL)
1393  {
1394  /* Manifest data, buffer in memory. */
1395  appendPQExpBuffer(state->manifest_buffer, copybuf + 1,
1396  r - 1);
1397  }
1398  else if (state->manifest_file !=NULL)
1399  {
1400  /* Manifest data, write to disk. */
1401  if (fwrite(copybuf + 1, r - 1, 1,
1402  state->manifest_file) != 1)
1403  {
1404  /*
1405  * If fwrite() didn't set errno, assume that the
1406  * problem is that we're out of disk space.
1407  */
1408  if (errno == 0)
1409  errno = ENOSPC;
1410  pg_fatal("could not write to file \"%s\": %m",
1411  state->manifest_filename);
1412  }
1413  }
1414  else if (state->streamer != NULL)
1415  {
1416  /* Archive data. */
1417  bbstreamer_content(state->streamer, NULL, copybuf + 1,
1418  r - 1, BBSTREAMER_UNKNOWN);
1419  }
1420  else
1421  pg_fatal("unexpected payload data");
1422  break;
1423  }
1424 
1425  case 'p':
1426  {
1427  /*
1428  * Progress report.
1429  *
1430  * The remainder of the message is expected to be an 8-byte
1431  * count of bytes completed.
1432  */
1435 
1436  /*
1437  * The server shouldn't send progress report messages too
1438  * often, so we force an update each time we receive one.
1439  */
1440  progress_report(state->tablespacenum, true, false);
1441  break;
1442  }
1443 
1444  case 'm':
1445  {
1446  /*
1447  * Manifest data will be sent next. This message is not
1448  * expected to have any further payload data.
1449  */
1451 
1452  /*
1453  * If a backup target was specified, figuring out where to put
1454  * the manifest is the server's problem. Otherwise, we need to
1455  * deal with it.
1456  */
1457  if (backup_target == NULL)
1458  {
1459  /*
1460  * If we're supposed inject the manifest into the archive,
1461  * we prepare to buffer it in memory; otherwise, we
1462  * prepare to write it to a temporary file.
1463  */
1464  if (state->manifest_inject_streamer != NULL)
1465  state->manifest_buffer = createPQExpBuffer();
1466  else
1467  {
1468  snprintf(state->manifest_filename,
1469  sizeof(state->manifest_filename),
1470  "%s/backup_manifest.tmp", basedir);
1471  state->manifest_file =
1472  fopen(state->manifest_filename, "wb");
1473  if (state->manifest_file == NULL)
1474  pg_fatal("could not create file \"%s\": %m",
1475  state->manifest_filename);
1476  }
1477  }
1478  break;
1479  }
1480 
1481  default:
1483  break;
1484  }
1485 }
1486 
1487 /*
1488  * Get a single byte from a CopyData message.
1489  *
1490  * Bail out if none remain.
1491  */
1492 static char
1493 GetCopyDataByte(size_t r, char *copybuf, size_t *cursor)
1494 {
1495  if (*cursor >= r)
1497 
1498  return copybuf[(*cursor)++];
1499 }
1500 
1501 /*
1502  * Get a NUL-terminated string from a CopyData message.
1503  *
1504  * Bail out if the terminating NUL cannot be found.
1505  */
1506 static char *
1507 GetCopyDataString(size_t r, char *copybuf, size_t *cursor)
1508 {
1509  size_t startpos = *cursor;
1510  size_t endpos = startpos;
1511 
1512  while (1)
1513  {
1514  if (endpos >= r)
1516  if (copybuf[endpos] == '\0')
1517  break;
1518  ++endpos;
1519  }
1520 
1521  *cursor = endpos + 1;
1522  return &copybuf[startpos];
1523 }
1524 
1525 /*
1526  * Get an unsigned 64-bit integer from a CopyData message.
1527  *
1528  * Bail out if there are not at least 8 bytes remaining.
1529  */
1530 static uint64
1531 GetCopyDataUInt64(size_t r, char *copybuf, size_t *cursor)
1532 {
1533  uint64 result;
1534 
1535  if (*cursor + sizeof(uint64) > r)
1537  memcpy(&result, &copybuf[*cursor], sizeof(uint64));
1538  *cursor += sizeof(uint64);
1539  return pg_ntoh64(result);
1540 }
1541 
1542 /*
1543  * Bail out if we didn't parse the whole message.
1544  */
1545 static void
1546 GetCopyDataEnd(size_t r, char *copybuf, size_t cursor)
1547 {
1548  if (r != cursor)
1550 }
1551 
1552 /*
1553  * Report failure to parse a CopyData message from the server. Then exit.
1554  *
1555  * As a debugging aid, we try to give some hint about what kind of message
1556  * provoked the failure. Perhaps this is not detailed enough, but it's not
1557  * clear that it's worth expending any more code on what should be a
1558  * can't-happen case.
1559  */
1560 static void
1562 {
1563  if (r == 0)
1564  pg_fatal("empty COPY message");
1565  else
1566  pg_fatal("malformed COPY message of type %d, length %zu",
1567  copybuf[0], r);
1568 }
1569 
1570 /*
1571  * Receive raw tar data from the server, and stream it to the appropriate
1572  * location. If we're writing a single tarfile to standard output, also
1573  * receive the backup manifest and inject it into that tarfile.
1574  */
1575 static void
1576 ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
1577  bool tablespacenum, pg_compress_specification *compress)
1578 {
1580  bbstreamer *manifest_inject_streamer;
1581  bool is_recovery_guc_supported;
1582  bool expect_unterminated_tarfile;
1583 
1584  /* Pass all COPY data through to the backup streamer. */
1585  memset(&state, 0, sizeof(state));
1586  is_recovery_guc_supported =
1588  expect_unterminated_tarfile =
1590  state.streamer = CreateBackupStreamer(archive_name, spclocation,
1591  &manifest_inject_streamer,
1592  is_recovery_guc_supported,
1593  expect_unterminated_tarfile,
1594  compress);
1595  state.tablespacenum = tablespacenum;
1598 
1599  /*
1600  * The decision as to whether we need to inject the backup manifest into
1601  * the output at this stage is made by CreateBackupStreamer; if that is
1602  * needed, manifest_inject_streamer will be non-NULL; otherwise, it will
1603  * be NULL.
1604  */
1605  if (manifest_inject_streamer != NULL)
1606  {
1608 
1609  /* Slurp the entire backup manifest into a buffer. */
1610  initPQExpBuffer(&buf);
1613  pg_fatal("out of memory");
1614 
1615  /* Inject it into the output tarfile. */
1616  bbstreamer_inject_file(manifest_inject_streamer, "backup_manifest",
1617  buf.data, buf.len);
1618 
1619  /* Free memory. */
1620  termPQExpBuffer(&buf);
1621  }
1622 
1623  /* Cleanup. */
1624  bbstreamer_finalize(state.streamer);
1625  bbstreamer_free(state.streamer);
1626 
1627  progress_report(tablespacenum, true, false);
1628 
1629  /*
1630  * Do not sync the resulting tar file yet, all files are synced once at
1631  * the end.
1632  */
1633 }
1634 
1635 /*
1636  * Receive one chunk of tar-format data from the server.
1637  */
1638 static void
1639 ReceiveTarCopyChunk(size_t r, char *copybuf, void *callback_data)
1640 {
1641  WriteTarState *state = callback_data;
1642 
1643  bbstreamer_content(state->streamer, NULL, copybuf, r, BBSTREAMER_UNKNOWN);
1644 
1645  totaldone += r;
1646  progress_report(state->tablespacenum, false, false);
1647 }
1648 
1649 
1650 /*
1651  * Retrieve tablespace path, either relocated or original depending on whether
1652  * -T was passed or not.
1653  */
1654 static const char *
1655 get_tablespace_mapping(const char *dir)
1656 {
1657  TablespaceListCell *cell;
1658  char canon_dir[MAXPGPATH];
1659 
1660  /* Canonicalize path for comparison consistency */
1661  strlcpy(canon_dir, dir, sizeof(canon_dir));
1662  canonicalize_path(canon_dir);
1663 
1664  for (cell = tablespace_dirs.head; cell; cell = cell->next)
1665  if (strcmp(canon_dir, cell->old_dir) == 0)
1666  return cell->new_dir;
1667 
1668  return dir;
1669 }
1670 
1671 /*
1672  * Receive the backup manifest file and write it out to a file.
1673  */
1674 static void
1676 {
1678 
1679  snprintf(state.filename, sizeof(state.filename),
1680  "%s/backup_manifest.tmp", basedir);
1681  state.file = fopen(state.filename, "wb");
1682  if (state.file == NULL)
1683  pg_fatal("could not create file \"%s\": %m", state.filename);
1684 
1686 
1687  fclose(state.file);
1688 }
1689 
1690 /*
1691  * Receive one chunk of the backup manifest file and write it out to a file.
1692  */
1693 static void
1694 ReceiveBackupManifestChunk(size_t r, char *copybuf, void *callback_data)
1695 {
1696  WriteManifestState *state = callback_data;
1697 
1698  errno = 0;
1699  if (fwrite(copybuf, r, 1, state->file) != 1)
1700  {
1701  /* if write didn't set errno, assume problem is no disk space */
1702  if (errno == 0)
1703  errno = ENOSPC;
1704  pg_fatal("could not write to file \"%s\": %m", state->filename);
1705  }
1706 }
1707 
1708 /*
1709  * Receive the backup manifest file and write it out to a file.
1710  */
1711 static void
1713 {
1715 }
1716 
1717 /*
1718  * Receive one chunk of the backup manifest file and write it out to a file.
1719  */
1720 static void
1722  void *callback_data)
1723 {
1724  PQExpBuffer buf = callback_data;
1725 
1727 }
1728 
1729 static void
1730 BaseBackup(char *compression_algorithm, char *compression_detail,
1731  CompressionLocation compressloc, pg_compress_specification *client_compress)
1732 {
1733  PGresult *res;
1734  char *sysidentifier;
1735  TimeLineID latesttli;
1736  TimeLineID starttli;
1737  char *basebkp;
1738  int i;
1739  char xlogstart[64];
1740  char xlogend[64] = {0};
1741  int minServerMajor,
1742  maxServerMajor;
1743  int serverVersion,
1744  serverMajor;
1745  int writing_to_stdout;
1746  bool use_new_option_syntax = false;
1748 
1749  Assert(conn != NULL);
1750  initPQExpBuffer(&buf);
1751 
1752  /*
1753  * Check server version. BASE_BACKUP command was introduced in 9.1, so we
1754  * can't work with servers older than 9.1.
1755  */
1756  minServerMajor = 901;
1757  maxServerMajor = PG_VERSION_NUM / 100;
1758  serverVersion = PQserverVersion(conn);
1759  serverMajor = serverVersion / 100;
1760  if (serverMajor < minServerMajor || serverMajor > maxServerMajor)
1761  {
1762  const char *serverver = PQparameterStatus(conn, "server_version");
1763 
1764  pg_fatal("incompatible server version %s",
1765  serverver ? serverver : "'unknown'");
1766  }
1767  if (serverMajor >= 1500)
1768  use_new_option_syntax = true;
1769 
1770  /*
1771  * If WAL streaming was requested, also check that the server is new
1772  * enough for that.
1773  */
1775  {
1776  /*
1777  * Error message already written in CheckServerVersionForStreaming(),
1778  * but add a hint about using -X none.
1779  */
1780  pg_log_error_hint("Use -X none or -X fetch to disable log streaming.");
1781  exit(1);
1782  }
1783 
1784  /*
1785  * Build contents of configuration file if requested
1786  */
1787  if (writerecoveryconf)
1789 
1790  /*
1791  * Run IDENTIFY_SYSTEM so we can get the timeline
1792  */
1793  if (!RunIdentifySystem(conn, &sysidentifier, &latesttli, NULL, NULL))
1794  exit(1);
1795 
1796  /*
1797  * Start the actual backup
1798  */
1799  AppendStringCommandOption(&buf, use_new_option_syntax, "LABEL", label);
1800  if (estimatesize)
1801  AppendPlainCommandOption(&buf, use_new_option_syntax, "PROGRESS");
1802  if (includewal == FETCH_WAL)
1803  AppendPlainCommandOption(&buf, use_new_option_syntax, "WAL");
1804  if (fastcheckpoint)
1805  {
1806  if (use_new_option_syntax)
1807  AppendStringCommandOption(&buf, use_new_option_syntax,
1808  "CHECKPOINT", "fast");
1809  else
1810  AppendPlainCommandOption(&buf, use_new_option_syntax, "FAST");
1811  }
1812  if (includewal != NO_WAL)
1813  {
1814  if (use_new_option_syntax)
1815  AppendIntegerCommandOption(&buf, use_new_option_syntax, "WAIT", 0);
1816  else
1817  AppendPlainCommandOption(&buf, use_new_option_syntax, "NOWAIT");
1818  }
1819  if (maxrate > 0)
1820  AppendIntegerCommandOption(&buf, use_new_option_syntax, "MAX_RATE",
1821  maxrate);
1822  if (format == 't')
1823  AppendPlainCommandOption(&buf, use_new_option_syntax, "TABLESPACE_MAP");
1824  if (!verify_checksums)
1825  {
1826  if (use_new_option_syntax)
1827  AppendIntegerCommandOption(&buf, use_new_option_syntax,
1828  "VERIFY_CHECKSUMS", 0);
1829  else
1830  AppendPlainCommandOption(&buf, use_new_option_syntax,
1831  "NOVERIFY_CHECKSUMS");
1832  }
1833 
1834  if (manifest)
1835  {
1836  AppendStringCommandOption(&buf, use_new_option_syntax, "MANIFEST",
1837  manifest_force_encode ? "force-encode" : "yes");
1838  if (manifest_checksums != NULL)
1839  AppendStringCommandOption(&buf, use_new_option_syntax,
1840  "MANIFEST_CHECKSUMS", manifest_checksums);
1841  }
1842 
1843  if (backup_target != NULL)
1844  {
1845  char *colon;
1846 
1847  if (serverMajor < 1500)
1848  pg_fatal("backup targets are not supported by this server version");
1849 
1850  if (writerecoveryconf)
1851  pg_fatal("recovery configuration cannot be written when a backup target is used");
1852 
1853  AppendPlainCommandOption(&buf, use_new_option_syntax, "TABLESPACE_MAP");
1854 
1855  if ((colon = strchr(backup_target, ':')) == NULL)
1856  {
1857  AppendStringCommandOption(&buf, use_new_option_syntax,
1858  "TARGET", backup_target);
1859  }
1860  else
1861  {
1862  char *target;
1863 
1865  AppendStringCommandOption(&buf, use_new_option_syntax,
1866  "TARGET", target);
1867  AppendStringCommandOption(&buf, use_new_option_syntax,
1868  "TARGET_DETAIL", colon + 1);
1869  }
1870  }
1871  else if (serverMajor >= 1500)
1872  AppendStringCommandOption(&buf, use_new_option_syntax,
1873  "TARGET", "client");
1874 
1875  if (compressloc == COMPRESS_LOCATION_SERVER)
1876  {
1877  if (!use_new_option_syntax)
1878  pg_fatal("server does not support server-side compression");
1879  AppendStringCommandOption(&buf, use_new_option_syntax,
1880  "COMPRESSION", compression_algorithm);
1881  if (compression_detail != NULL)
1882  AppendStringCommandOption(&buf, use_new_option_syntax,
1883  "COMPRESSION_DETAIL",
1884  compression_detail);
1885  }
1886 
1887  if (verbose)
1888  pg_log_info("initiating base backup, waiting for checkpoint to complete");
1889 
1890  if (showprogress && !verbose)
1891  {
1892  fprintf(stderr, _("waiting for checkpoint"));
1893  if (isatty(fileno(stderr)))
1894  fprintf(stderr, "\r");
1895  else
1896  fprintf(stderr, "\n");
1897  }
1898 
1899  if (use_new_option_syntax && buf.len > 0)
1900  basebkp = psprintf("BASE_BACKUP (%s)", buf.data);
1901  else
1902  basebkp = psprintf("BASE_BACKUP %s", buf.data);
1903 
1904  if (PQsendQuery(conn, basebkp) == 0)
1905  pg_fatal("could not send replication command \"%s\": %s",
1906  "BASE_BACKUP", PQerrorMessage(conn));
1907 
1908  /*
1909  * Get the starting WAL location
1910  */
1911  res = PQgetResult(conn);
1913  pg_fatal("could not initiate base backup: %s",
1914  PQerrorMessage(conn));
1915  if (PQntuples(res) != 1)
1916  pg_fatal("server returned unexpected response to BASE_BACKUP command; got %d rows and %d fields, expected %d rows and %d fields",
1917  PQntuples(res), PQnfields(res), 1, 2);
1918 
1919  strlcpy(xlogstart, PQgetvalue(res, 0, 0), sizeof(xlogstart));
1920 
1921  if (verbose)
1922  pg_log_info("checkpoint completed");
1923 
1924  /*
1925  * 9.3 and later sends the TLI of the starting point. With older servers,
1926  * assume it's the same as the latest timeline reported by
1927  * IDENTIFY_SYSTEM.
1928  */
1929  if (PQnfields(res) >= 2)
1930  starttli = atoi(PQgetvalue(res, 0, 1));
1931  else
1932  starttli = latesttli;
1933  PQclear(res);
1934 
1935  if (verbose && includewal != NO_WAL)
1936  pg_log_info("write-ahead log start point: %s on timeline %u",
1937  xlogstart, starttli);
1938 
1939  /*
1940  * Get the header
1941  */
1942  res = PQgetResult(conn);
1944  pg_fatal("could not get backup header: %s",
1945  PQerrorMessage(conn));
1946  if (PQntuples(res) < 1)
1947  pg_fatal("no data returned from server");
1948 
1949  /*
1950  * Sum up the total size, for progress reporting
1951  */
1952  totalsize_kb = totaldone = 0;
1954  for (i = 0; i < PQntuples(res); i++)
1955  {
1956  totalsize_kb += atol(PQgetvalue(res, i, 2));
1957 
1958  /*
1959  * Verify tablespace directories are empty. Don't bother with the
1960  * first once since it can be relocated, and it will be checked before
1961  * we do anything anyway.
1962  *
1963  * Note that this is skipped for tar format backups and backups that
1964  * the server is storing to a target location, since in that case we
1965  * won't be storing anything into these directories and thus should
1966  * not create them.
1967  */
1968  if (backup_target == NULL && format == 'p' && !PQgetisnull(res, i, 1))
1969  {
1970  char *path = PQgetvalue(res, i, 1);
1971 
1972  if (is_absolute_path(path))
1973  path = unconstify(char *, get_tablespace_mapping(path));
1974  else
1975  {
1976  /* This is an in-place tablespace, so prepend basedir. */
1977  path = psprintf("%s/%s", basedir, path);
1978  }
1979 
1981  }
1982  }
1983 
1984  /*
1985  * When writing to stdout, require a single tablespace
1986  */
1987  writing_to_stdout = format == 't' && basedir != NULL &&
1988  strcmp(basedir, "-") == 0;
1989  if (writing_to_stdout && PQntuples(res) > 1)
1990  pg_fatal("can only write single tablespace to stdout, database has %d",
1991  PQntuples(res));
1992 
1993  /*
1994  * If we're streaming WAL, start the streaming session before we start
1995  * receiving the actual data chunks.
1996  */
1997  if (includewal == STREAM_WAL)
1998  {
1999  pg_compress_algorithm wal_compress_algorithm;
2000  int wal_compress_level;
2001 
2002  if (verbose)
2003  pg_log_info("starting background WAL receiver");
2004 
2005  if (client_compress->algorithm == PG_COMPRESSION_GZIP)
2006  {
2007  wal_compress_algorithm = PG_COMPRESSION_GZIP;
2008  wal_compress_level = client_compress->level;
2009  }
2010  else
2011  {
2012  wal_compress_algorithm = PG_COMPRESSION_NONE;
2013  wal_compress_level = 0;
2014  }
2015 
2016  StartLogStreamer(xlogstart, starttli, sysidentifier,
2017  wal_compress_algorithm,
2018  wal_compress_level);
2019  }
2020 
2021  if (serverMajor >= 1500)
2022  {
2023  /* Receive a single tar stream with everything. */
2024  ReceiveArchiveStream(conn, client_compress);
2025  }
2026  else
2027  {
2028  /* Receive a tar file for each tablespace in turn */
2029  for (i = 0; i < PQntuples(res); i++)
2030  {
2031  char archive_name[MAXPGPATH];
2032  char *spclocation;
2033 
2034  /*
2035  * If we write the data out to a tar file, it will be named
2036  * base.tar if it's the main data directory or <tablespaceoid>.tar
2037  * if it's for another tablespace. CreateBackupStreamer() will
2038  * arrange to add an extension to the archive name if
2039  * pg_basebackup is performing compression, depending on the
2040  * compression type.
2041  */
2042  if (PQgetisnull(res, i, 0))
2043  {
2044  strlcpy(archive_name, "base.tar", sizeof(archive_name));
2045  spclocation = NULL;
2046  }
2047  else
2048  {
2049  snprintf(archive_name, sizeof(archive_name),
2050  "%s.tar", PQgetvalue(res, i, 0));
2051  spclocation = PQgetvalue(res, i, 1);
2052  }
2053 
2054  ReceiveTarFile(conn, archive_name, spclocation, i,
2055  client_compress);
2056  }
2057 
2058  /*
2059  * Now receive backup manifest, if appropriate.
2060  *
2061  * If we're writing a tarfile to stdout, ReceiveTarFile will have
2062  * already processed the backup manifest and included it in the output
2063  * tarfile. Such a configuration doesn't allow for writing multiple
2064  * files.
2065  *
2066  * If we're talking to an older server, it won't send a backup
2067  * manifest, so don't try to receive one.
2068  */
2069  if (!writing_to_stdout && manifest)
2071  }
2072 
2073  if (showprogress)
2074  {
2076  progress_report(PQntuples(res), true, true);
2077  }
2078 
2079  PQclear(res);
2080 
2081  /*
2082  * Get the stop position
2083  */
2084  res = PQgetResult(conn);
2086  pg_fatal("backup failed: %s",
2087  PQerrorMessage(conn));
2088  if (PQntuples(res) != 1)
2089  pg_fatal("no write-ahead log end position returned from server");
2090  strlcpy(xlogend, PQgetvalue(res, 0, 0), sizeof(xlogend));
2091  if (verbose && includewal != NO_WAL)
2092  pg_log_info("write-ahead log end point: %s", xlogend);
2093  PQclear(res);
2094 
2095  res = PQgetResult(conn);
2097  {
2098  const char *sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
2099 
2100  if (sqlstate &&
2101  strcmp(sqlstate, ERRCODE_DATA_CORRUPTED) == 0)
2102  {
2103  pg_log_error("checksum error occurred");
2104  checksum_failure = true;
2105  }
2106  else
2107  {
2108  pg_log_error("final receive failed: %s",
2109  PQerrorMessage(conn));
2110  }
2111  exit(1);
2112  }
2113 
2114  if (bgchild > 0)
2115  {
2116 #ifndef WIN32
2117  int status;
2118  pid_t r;
2119 #else
2120  DWORD status;
2121 
2122  /*
2123  * get a pointer sized version of bgchild to avoid warnings about
2124  * casting to a different size on WIN64.
2125  */
2126  intptr_t bgchild_handle = bgchild;
2127  uint32 hi,
2128  lo;
2129 #endif
2130 
2131  if (verbose)
2132  pg_log_info("waiting for background process to finish streaming ...");
2133 
2134 #ifndef WIN32
2135  if (write(bgpipe[1], xlogend, strlen(xlogend)) != strlen(xlogend))
2136  pg_fatal("could not send command to background pipe: %m");
2137 
2138  /* Just wait for the background process to exit */
2139  r = waitpid(bgchild, &status, 0);
2140  if (r == (pid_t) -1)
2141  pg_fatal("could not wait for child process: %m");
2142  if (r != bgchild)
2143  pg_fatal("child %d died, expected %d", (int) r, (int) bgchild);
2144  if (status != 0)
2145  pg_fatal("%s", wait_result_to_str(status));
2146  /* Exited normally, we're happy! */
2147 #else /* WIN32 */
2148 
2149  /*
2150  * On Windows, since we are in the same process, we can just store the
2151  * value directly in the variable, and then set the flag that says
2152  * it's there.
2153  */
2154  if (sscanf(xlogend, "%X/%X", &hi, &lo) != 2)
2155  pg_fatal("could not parse write-ahead log location \"%s\"",
2156  xlogend);
2157  xlogendptr = ((uint64) hi) << 32 | lo;
2158  InterlockedIncrement(&has_xlogendptr);
2159 
2160  /* First wait for the thread to exit */
2161  if (WaitForSingleObjectEx((HANDLE) bgchild_handle, INFINITE, FALSE) !=
2162  WAIT_OBJECT_0)
2163  {
2164  _dosmaperr(GetLastError());
2165  pg_fatal("could not wait for child thread: %m");
2166  }
2167  if (GetExitCodeThread((HANDLE) bgchild_handle, &status) == 0)
2168  {
2169  _dosmaperr(GetLastError());
2170  pg_fatal("could not get child thread exit status: %m");
2171  }
2172  if (status != 0)
2173  pg_fatal("child thread exited with error %u",
2174  (unsigned int) status);
2175  /* Exited normally, we're happy */
2176 #endif
2177  }
2178 
2179  /* Free the configuration file contents */
2181 
2182  /*
2183  * End of copy data. Final result is already checked inside the loop.
2184  */
2185  PQclear(res);
2186  PQfinish(conn);
2187  conn = NULL;
2188 
2189  /*
2190  * Make data persistent on disk once backup is completed. For tar format
2191  * sync the parent directory and all its contents as each tar file was not
2192  * synced after being completed. In plain format, all the data of the
2193  * base directory is synced, taking into account all the tablespaces.
2194  * Errors are not considered fatal.
2195  *
2196  * If, however, there's a backup target, we're not writing anything
2197  * locally, so in that case we skip this step.
2198  */
2199  if (do_sync && backup_target == NULL)
2200  {
2201  if (verbose)
2202  pg_log_info("syncing data to disk ...");
2203  if (format == 't')
2204  {
2205  if (strcmp(basedir, "-") != 0)
2206  (void) sync_dir_recurse(basedir, sync_method);
2207  }
2208  else
2209  {
2210  (void) sync_pgdata(basedir, serverVersion, sync_method);
2211  }
2212  }
2213 
2214  /*
2215  * After synchronizing data to disk, perform a durable rename of
2216  * backup_manifest.tmp to backup_manifest, if we wrote such a file. This
2217  * way, a failure or system crash before we reach this point will leave us
2218  * without a backup_manifest file, decreasing the chances that a directory
2219  * we leave behind will be mistaken for a valid backup.
2220  */
2221  if (!writing_to_stdout && manifest && backup_target == NULL)
2222  {
2223  char tmp_filename[MAXPGPATH];
2224  char filename[MAXPGPATH];
2225 
2226  if (verbose)
2227  pg_log_info("renaming backup_manifest.tmp to backup_manifest");
2228 
2229  snprintf(tmp_filename, MAXPGPATH, "%s/backup_manifest.tmp", basedir);
2230  snprintf(filename, MAXPGPATH, "%s/backup_manifest", basedir);
2231 
2232  if (do_sync)
2233  {
2234  /* durable_rename emits its own log message in case of failure */
2235  if (durable_rename(tmp_filename, filename) != 0)
2236  exit(1);
2237  }
2238  else
2239  {
2240  if (rename(tmp_filename, filename) != 0)
2241  pg_fatal("could not rename file \"%s\" to \"%s\": %m",
2242  tmp_filename, filename);
2243  }
2244  }
2245 
2246  if (verbose)
2247  pg_log_info("base backup completed");
2248 }
2249 
2250 
2251 int
2252 main(int argc, char **argv)
2253 {
2254  static struct option long_options[] = {
2255  {"help", no_argument, NULL, '?'},
2256  {"version", no_argument, NULL, 'V'},
2257  {"pgdata", required_argument, NULL, 'D'},
2258  {"format", required_argument, NULL, 'F'},
2259  {"checkpoint", required_argument, NULL, 'c'},
2260  {"create-slot", no_argument, NULL, 'C'},
2261  {"max-rate", required_argument, NULL, 'r'},
2262  {"write-recovery-conf", no_argument, NULL, 'R'},
2263  {"slot", required_argument, NULL, 'S'},
2264  {"target", required_argument, NULL, 't'},
2265  {"tablespace-mapping", required_argument, NULL, 'T'},
2266  {"wal-method", required_argument, NULL, 'X'},
2267  {"gzip", no_argument, NULL, 'z'},
2268  {"compress", required_argument, NULL, 'Z'},
2269  {"label", required_argument, NULL, 'l'},
2270  {"no-clean", no_argument, NULL, 'n'},
2271  {"no-sync", no_argument, NULL, 'N'},
2272  {"dbname", required_argument, NULL, 'd'},
2273  {"host", required_argument, NULL, 'h'},
2274  {"port", required_argument, NULL, 'p'},
2275  {"username", required_argument, NULL, 'U'},
2276  {"no-password", no_argument, NULL, 'w'},
2277  {"password", no_argument, NULL, 'W'},
2278  {"status-interval", required_argument, NULL, 's'},
2279  {"verbose", no_argument, NULL, 'v'},
2280  {"progress", no_argument, NULL, 'P'},
2281  {"waldir", required_argument, NULL, 1},
2282  {"no-slot", no_argument, NULL, 2},
2283  {"no-verify-checksums", no_argument, NULL, 3},
2284  {"no-estimate-size", no_argument, NULL, 4},
2285  {"no-manifest", no_argument, NULL, 5},
2286  {"manifest-force-encode", no_argument, NULL, 6},
2287  {"manifest-checksums", required_argument, NULL, 7},
2288  {"sync-method", required_argument, NULL, 8},
2289  {NULL, 0, NULL, 0}
2290  };
2291  int c;
2292 
2293  int option_index;
2294  char *compression_algorithm = "none";
2295  char *compression_detail = NULL;
2297  pg_compress_specification client_compress;
2298 
2299  pg_logging_init(argv[0]);
2300  progname = get_progname(argv[0]);
2301  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_basebackup"));
2302 
2303  if (argc > 1)
2304  {
2305  if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2306  {
2307  usage();
2308  exit(0);
2309  }
2310  else if (strcmp(argv[1], "-V") == 0
2311  || strcmp(argv[1], "--version") == 0)
2312  {
2313  puts("pg_basebackup (PostgreSQL) " PG_VERSION);
2314  exit(0);
2315  }
2316  }
2317 
2319 
2320  while ((c = getopt_long(argc, argv, "c:Cd:D:F:h:l:nNp:Pr:Rs:S:t:T:U:vwWX:zZ:",
2321  long_options, &option_index)) != -1)
2322  {
2323  switch (c)
2324  {
2325  case 'c':
2326  if (pg_strcasecmp(optarg, "fast") == 0)
2327  fastcheckpoint = true;
2328  else if (pg_strcasecmp(optarg, "spread") == 0)
2329  fastcheckpoint = false;
2330  else
2331  pg_fatal("invalid checkpoint argument \"%s\", must be \"fast\" or \"spread\"",
2332  optarg);
2333  break;
2334  case 'C':
2335  create_slot = true;
2336  break;
2337  case 'd':
2339  break;
2340  case 'D':
2342  break;
2343  case 'F':
2344  if (strcmp(optarg, "p") == 0 || strcmp(optarg, "plain") == 0)
2345  format = 'p';
2346  else if (strcmp(optarg, "t") == 0 || strcmp(optarg, "tar") == 0)
2347  format = 't';
2348  else
2349  pg_fatal("invalid output format \"%s\", must be \"plain\" or \"tar\"",
2350  optarg);
2351  break;
2352  case 'h':
2353  dbhost = pg_strdup(optarg);
2354  break;
2355  case 'l':
2356  label = pg_strdup(optarg);
2357  break;
2358  case 'n':
2359  noclean = true;
2360  break;
2361  case 'N':
2362  do_sync = false;
2363  break;
2364  case 'p':
2365  dbport = pg_strdup(optarg);
2366  break;
2367  case 'P':
2368  showprogress = true;
2369  break;
2370  case 'r':
2372  break;
2373  case 'R':
2374  writerecoveryconf = true;
2375  break;
2376  case 's':
2377  if (!option_parse_int(optarg, "-s/--status-interval", 0,
2378  INT_MAX / 1000,
2380  exit(1);
2381  standby_message_timeout *= 1000;
2382  break;
2383  case 'S':
2384 
2385  /*
2386  * When specifying replication slot name, use a permanent
2387  * slot.
2388  */
2390  temp_replication_slot = false;
2391  break;
2392  case 't':
2394  break;
2395  case 'T':
2397  break;
2398  case 'U':
2399  dbuser = pg_strdup(optarg);
2400  break;
2401  case 'v':
2402  verbose++;
2403  break;
2404  case 'w':
2405  dbgetpassword = -1;
2406  break;
2407  case 'W':
2408  dbgetpassword = 1;
2409  break;
2410  case 'X':
2411  if (strcmp(optarg, "n") == 0 ||
2412  strcmp(optarg, "none") == 0)
2413  {
2414  includewal = NO_WAL;
2415  }
2416  else if (strcmp(optarg, "f") == 0 ||
2417  strcmp(optarg, "fetch") == 0)
2418  {
2420  }
2421  else if (strcmp(optarg, "s") == 0 ||
2422  strcmp(optarg, "stream") == 0)
2423  {
2425  }
2426  else
2427  pg_fatal("invalid wal-method option \"%s\", must be \"fetch\", \"stream\", or \"none\"",
2428  optarg);
2429  break;
2430  case 'z':
2431  compression_algorithm = "gzip";
2432  compression_detail = NULL;
2433  compressloc = COMPRESS_LOCATION_UNSPECIFIED;
2434  break;
2435  case 'Z':
2437  &compression_detail, &compressloc);
2438  break;
2439  case 1:
2441  break;
2442  case 2:
2443  no_slot = true;
2444  break;
2445  case 3:
2446  verify_checksums = false;
2447  break;
2448  case 4:
2449  estimatesize = false;
2450  break;
2451  case 5:
2452  manifest = false;
2453  break;
2454  case 6:
2455  manifest_force_encode = true;
2456  break;
2457  case 7:
2459  break;
2460  case 8:
2462  exit(1);
2463  break;
2464  default:
2465  /* getopt_long already emitted a complaint */
2466  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2467  exit(1);
2468  }
2469  }
2470 
2471  /*
2472  * Any non-option arguments?
2473  */
2474  if (optind < argc)
2475  {
2476  pg_log_error("too many command-line arguments (first is \"%s\")",
2477  argv[optind]);
2478  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2479  exit(1);
2480  }
2481 
2482  /*
2483  * Setting the backup target to 'client' is equivalent to leaving out the
2484  * option. This logic allows us to assume elsewhere that the backup is
2485  * being stored locally if and only if backup_target == NULL.
2486  */
2487  if (backup_target != NULL && strcmp(backup_target, "client") == 0)
2488  {
2490  backup_target = NULL;
2491  }
2492 
2493  /*
2494  * Can't use --format with --target. Without --target, default format is
2495  * tar.
2496  */
2497  if (backup_target != NULL && format != '\0')
2498  {
2499  pg_log_error("cannot specify both format and backup target");
2500  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2501  exit(1);
2502  }
2503  if (format == '\0')
2504  format = 'p';
2505 
2506  /*
2507  * Either directory or backup target should be specified, but not both
2508  */
2509  if (basedir == NULL && backup_target == NULL)
2510  {
2511  pg_log_error("must specify output directory or backup target");
2512  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2513  exit(1);
2514  }
2515  if (basedir != NULL && backup_target != NULL)
2516  {
2517  pg_log_error("cannot specify both output directory and backup target");
2518  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2519  exit(1);
2520  }
2521 
2522  /*
2523  * If the user has not specified where to perform backup compression,
2524  * default to the client, unless the user specified --target, in which
2525  * case the server is the only choice.
2526  */
2527  if (compressloc == COMPRESS_LOCATION_UNSPECIFIED)
2528  {
2529  if (backup_target == NULL)
2530  compressloc = COMPRESS_LOCATION_CLIENT;
2531  else
2532  compressloc = COMPRESS_LOCATION_SERVER;
2533  }
2534 
2535  /*
2536  * If any compression that we're doing is happening on the client side, we
2537  * must try to parse the compression algorithm and detail, but if it's all
2538  * on the server side, then we're just going to pass through whatever was
2539  * requested and let the server decide what to do.
2540  */
2541  if (compressloc == COMPRESS_LOCATION_CLIENT)
2542  {
2544  char *error_detail;
2545 
2547  pg_fatal("unrecognized compression algorithm: \"%s\"",
2549 
2550  parse_compress_specification(alg, compression_detail, &client_compress);
2551  error_detail = validate_compress_specification(&client_compress);
2552  if (error_detail != NULL)
2553  pg_fatal("invalid compression specification: %s",
2554  error_detail);
2555  }
2556  else
2557  {
2558  Assert(compressloc == COMPRESS_LOCATION_SERVER);
2559  client_compress.algorithm = PG_COMPRESSION_NONE;
2560  client_compress.options = 0;
2561  }
2562 
2563  /*
2564  * Can't perform client-side compression if the backup is not being sent
2565  * to the client.
2566  */
2567  if (backup_target != NULL && compressloc == COMPRESS_LOCATION_CLIENT)
2568  {
2569  pg_log_error("client-side compression is not possible when a backup target is specified");
2570  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2571  exit(1);
2572  }
2573 
2574  /*
2575  * Client-side compression doesn't make sense unless tar format is in use.
2576  */
2577  if (format == 'p' && compressloc == COMPRESS_LOCATION_CLIENT &&
2578  client_compress.algorithm != PG_COMPRESSION_NONE)
2579  {
2580  pg_log_error("only tar mode backups can be compressed");
2581  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2582  exit(1);
2583  }
2584 
2585  /*
2586  * Sanity checks for WAL method.
2587  */
2588  if (backup_target != NULL && includewal == STREAM_WAL)
2589  {
2590  pg_log_error("WAL cannot be streamed when a backup target is specified");
2591  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2592  exit(1);
2593  }
2594  if (format == 't' && includewal == STREAM_WAL && strcmp(basedir, "-") == 0)
2595  {
2596  pg_log_error("cannot stream write-ahead logs in tar mode to stdout");
2597  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2598  exit(1);
2599  }
2600 
2602  {
2603  pg_log_error("replication slots can only be used with WAL streaming");
2604  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2605  exit(1);
2606  }
2607 
2608  /*
2609  * Sanity checks for replication slot options.
2610  */
2611  if (no_slot)
2612  {
2613  if (replication_slot)
2614  {
2615  pg_log_error("--no-slot cannot be used with slot name");
2616  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2617  exit(1);
2618  }
2619  temp_replication_slot = false;
2620  }
2621 
2622  if (create_slot)
2623  {
2624  if (!replication_slot)
2625  {
2626  pg_log_error("%s needs a slot to be specified using --slot",
2627  "--create-slot");
2628  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2629  exit(1);
2630  }
2631 
2632  if (no_slot)
2633  {
2634  pg_log_error("%s and %s are incompatible options",
2635  "--create-slot", "--no-slot");
2636  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2637  exit(1);
2638  }
2639  }
2640 
2641  /*
2642  * Sanity checks on WAL directory.
2643  */
2644  if (xlog_dir)
2645  {
2646  if (backup_target != NULL)
2647  {
2648  pg_log_error("WAL directory location cannot be specified along with a backup target");
2649  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2650  exit(1);
2651  }
2652  if (format != 'p')
2653  {
2654  pg_log_error("WAL directory location can only be specified in plain mode");
2655  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2656  exit(1);
2657  }
2658 
2659  /* clean up xlog directory name, check it's absolute */
2661  if (!is_absolute_path(xlog_dir))
2662  {
2663  pg_log_error("WAL directory location must be an absolute path");
2664  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2665  exit(1);
2666  }
2667  }
2668 
2669  /*
2670  * Sanity checks for progress reporting options.
2671  */
2672  if (showprogress && !estimatesize)
2673  {
2674  pg_log_error("%s and %s are incompatible options",
2675  "--progress", "--no-estimate-size");
2676  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2677  exit(1);
2678  }
2679 
2680  /*
2681  * Sanity checks for backup manifest options.
2682  */
2683  if (!manifest && manifest_checksums != NULL)
2684  {
2685  pg_log_error("%s and %s are incompatible options",
2686  "--no-manifest", "--manifest-checksums");
2687  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2688  exit(1);
2689  }
2690 
2692  {
2693  pg_log_error("%s and %s are incompatible options",
2694  "--no-manifest", "--manifest-force-encode");
2695  pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2696  exit(1);
2697  }
2698 
2699  /* connection in replication mode to server */
2700  conn = GetConnection();
2701  if (!conn)
2702  {
2703  /* Error message already written in GetConnection() */
2704  exit(1);
2705  }
2706  atexit(disconnect_atexit);
2707 
2708 #ifndef WIN32
2709 
2710  /*
2711  * Trap SIGCHLD to be able to handle the WAL stream process exiting. There
2712  * is no SIGCHLD on Windows, there we rely on the background thread
2713  * setting the signal variable on unexpected but graceful exit. If the WAL
2714  * stream thread crashes on Windows it will bring down the entire process
2715  * as it's a thread, so there is nothing to catch should that happen. A
2716  * crash on UNIX will be caught by the signal handler.
2717  */
2719 #endif
2720 
2721  /*
2722  * Set umask so that directories/files are created with the same
2723  * permissions as directories/files in the source data directory.
2724  *
2725  * pg_mode_mask is set to owner-only by default and then updated in
2726  * GetConnection() where we get the mode from the server-side with
2727  * RetrieveDataDirCreatePerm() and then call SetDataDirectoryCreatePerm().
2728  */
2729  umask(pg_mode_mask);
2730 
2731  /* Backup manifests are supported in 13 and newer versions */
2733  manifest = false;
2734 
2735  /*
2736  * If an output directory was specified, verify that it exists, or create
2737  * it. Note that for a tar backup, an output directory of "-" means we are
2738  * writing to stdout, so do nothing in that case.
2739  */
2740  if (basedir != NULL && (format == 'p' || strcmp(basedir, "-") != 0))
2742 
2743  /* determine remote server's xlog segment size */
2744  if (!RetrieveWalSegSize(conn))
2745  exit(1);
2746 
2747  /* Create pg_wal symlink, if required */
2748  if (xlog_dir)
2749  {
2750  char *linkloc;
2751 
2753 
2754  /*
2755  * Form name of the place where the symlink must go. pg_xlog has been
2756  * renamed to pg_wal in post-10 clusters.
2757  */
2758  linkloc = psprintf("%s/%s", basedir,
2760  "pg_xlog" : "pg_wal");
2761 
2762  if (symlink(xlog_dir, linkloc) != 0)
2763  pg_fatal("could not create symbolic link \"%s\": %m", linkloc);
2764  free(linkloc);
2765  }
2766 
2767  BaseBackup(compression_algorithm, compression_detail, compressloc,
2768  &client_compress);
2769 
2770  success = true;
2771  return 0;
2772 }
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1613
#define MAX_RATE_UPPER
Definition: basebackup.h:21
bbstreamer * bbstreamer_gzip_writer_new(char *pathname, FILE *file, pg_compress_specification *compress)
bbstreamer * bbstreamer_zstd_compressor_new(bbstreamer *next, pg_compress_specification *compress)
static void bbstreamer_content(bbstreamer *streamer, bbstreamer_member *member, const char *data, int len, bbstreamer_archive_context context)
Definition: bbstreamer.h:126
static void bbstreamer_finalize(bbstreamer *streamer)
Definition: bbstreamer.h:136
bbstreamer * bbstreamer_tar_terminator_new(bbstreamer *next)
bbstreamer * bbstreamer_lz4_compressor_new(bbstreamer *next, pg_compress_specification *compress)
bbstreamer * bbstreamer_tar_parser_new(bbstreamer *next)
bbstreamer * bbstreamer_lz4_decompressor_new(bbstreamer *next)
@ BBSTREAMER_UNKNOWN
Definition: bbstreamer.h:55
static void bbstreamer_free(bbstreamer *streamer)
Definition: bbstreamer.h:144
bbstreamer * bbstreamer_recovery_injector_new(bbstreamer *next, bool is_recovery_guc_supported, PQExpBuffer recoveryconfcontents)
bbstreamer * bbstreamer_tar_archiver_new(bbstreamer *next)
bbstreamer * bbstreamer_zstd_decompressor_new(bbstreamer *next)
bbstreamer * bbstreamer_plain_writer_new(char *pathname, FILE *file)
bbstreamer * bbstreamer_extractor_new(const char *basepath, const char *(*link_map)(const char *), void(*report_output_file)(const char *))
bbstreamer * bbstreamer_gzip_decompressor_new(bbstreamer *next)
void bbstreamer_inject_file(bbstreamer *streamer, char *pathname, char *data, int len)
#define unconstify(underlying_type, expr)
Definition: c.h:1255
unsigned int uint32
Definition: c.h:495
signed int int32
Definition: c.h:483
#define ngettext(s, p, n)
Definition: c.h:1194
#define SIGNAL_ARGS
Definition: c.h:1355
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1227
#define UINT64_FORMAT
Definition: c.h:538
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:436
bool parse_compress_algorithm(char *name, pg_compress_algorithm *algorithm)
Definition: compression.c:49
void parse_compress_specification(pg_compress_algorithm algorithm, char *specification, pg_compress_specification *result)
Definition: compression.c:107
char * validate_compress_specification(pg_compress_specification *spec)
Definition: compression.c:344
pg_compress_algorithm
Definition: compression.h:22
@ PG_COMPRESSION_GZIP
Definition: compression.h:24
@ PG_COMPRESSION_LZ4
Definition: compression.h:25
@ PG_COMPRESSION_NONE
Definition: compression.h:23
@ PG_COMPRESSION_ZSTD
Definition: compression.h:26
void parse_compress_options(const char *option, char **algorithm, char **detail)
PGconn * GetConnection(UserMapping *user, bool will_prep_stmt, PgFdwConnState **state)
Definition: connection.c:177
#define _(x)
Definition: elog.c:91
int durable_rename(const char *oldfile, const char *newfile, int elevel)
Definition: fd.c:759
const char * PQparameterStatus(const PGconn *conn, const char *paramName)
Definition: fe-connect.c:7213
int PQserverVersion(const PGconn *conn)
Definition: fe-connect.c:7238
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:7248
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4602
int PQbackendPID(const PGconn *conn)
Definition: fe-connect.c:7282
void PQfreemem(void *ptr)
Definition: fe-exec.c:3973
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:3352
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3422
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3817
int PQgetisnull(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3842
int PQsendQuery(PGconn *conn, const char *query)
Definition: fe-exec.c:1422
char * PQresultErrorField(const PGresult *res, int fieldcode)
Definition: fe-exec.c:3407
int PQnfields(const PGresult *res)
Definition: fe-exec.c:3430
PGresult * PQgetResult(PGconn *conn)
Definition: fe-exec.c:2035
int PQgetCopyData(PGconn *conn, char **buffer, int async)
Definition: fe-exec.c:2775
void * pg_malloc0(size_t size)
Definition: fe_memutils.c:53
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
void pg_free(void *ptr)
Definition: fe_memutils.c:105
int pg_mode_mask
Definition: file_perm.c:25
int pg_dir_create_mode
Definition: file_perm.c:18
DataDirSyncMethod
Definition: file_utils.h:28
@ DATA_DIR_SYNC_METHOD_FSYNC
Definition: file_utils.h:29
int getopt_long(int argc, char *const argv[], const char *optstring, const struct option *longopts, int *longindex)
Definition: getopt_long.c:60
#define no_argument
Definition: getopt_long.h:24
#define required_argument
Definition: getopt_long.h:25
#define free(a)
Definition: header.h:65
#define colon
Definition: indent_codes.h:43
#define write(a, b, c)
Definition: win32.h:14
#define read(a, b, c)
Definition: win32.h:13
int i
Definition: isn.c:73
@ PGRES_COMMAND_OK
Definition: libpq-fe.h:97
@ PGRES_COPY_OUT
Definition: libpq-fe.h:103
@ PGRES_TUPLES_OK
Definition: libpq-fe.h:100
Assert(fmt[strlen(fmt) - 1] !='\n')
exit(1)
void pg_logging_init(const char *argv0)
Definition: logging.c:83
#define pg_log_error(...)
Definition: logging.h:106
#define pg_log_error_hint(...)
Definition: logging.h:112
#define pg_log_info(...)
Definition: logging.h:124
#define pg_log_error_detail(...)
Definition: logging.h:109
const char * progname
Definition: main.c:45
char * pnstrdup(const char *in, Size len)
Definition: mcxt.c:1655
bool option_parse_int(const char *optarg, const char *optname, int min_range, int max_range, int *result)
Definition: option_utils.c:50
bool parse_sync_method(const char *optarg, DataDirSyncMethod *sync_method)
Definition: option_utils.c:90
void * arg
#define pg_fatal(...)
static void ReceiveArchiveStreamChunk(size_t r, char *copybuf, void *callback_data)
static int verbose
static bool checksum_failure
void(* WriteDataCallback)(size_t nbytes, char *buf, void *callback_data)
Definition: pg_basebackup.c:79
static bool noclean
static bool estimatesize
static bool found_existing_pgdata
static bool manifest
static bool found_existing_xlogdir
#define MINIMUM_VERSION_FOR_TEMP_SLOTS
Definition: pg_basebackup.c:91
static int32 maxrate
static void ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation, bool tablespacenum, pg_compress_specification *compress)
static char * backup_target
static char format
static char * xlog_dir
static void ReceiveCopyData(PGconn *conn, WriteDataCallback callback, void *callback_data)
static void StartLogStreamer(char *startpos, uint32 timeline, char *sysidentifier, pg_compress_algorithm wal_compress_algorithm, int wal_compress_level)
static void ReceiveBackupManifestChunk(size_t r, char *copybuf, void *callback_data)
int main(int argc, char **argv)
static char * GetCopyDataString(size_t r, char *copybuf, size_t *cursor)
static int32 parse_max_rate(char *src)
IncludeWal
@ STREAM_WAL
@ FETCH_WAL
@ NO_WAL
static volatile sig_atomic_t bgchild_exited
static int bgpipe[2]
static bool create_slot
static void ReceiveTarCopyChunk(size_t r, char *copybuf, void *callback_data)
static int LogStreamerMain(logstreamer_param *param)
static void ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
static void backup_parse_compress_options(char *option, char **algorithm, char **detail, CompressionLocation *locationres)
static PQExpBuffer recoveryconfcontents
static int tablespacecount
static void progress_update_filename(const char *filename)
static pid_t bgchild
CompressionLocation
@ COMPRESS_LOCATION_UNSPECIFIED
@ COMPRESS_LOCATION_CLIENT
@ COMPRESS_LOCATION_SERVER
static bool reached_end_position(XLogRecPtr segendpos, uint32 timeline, bool segment_finished)
static int has_xlogendptr
static void verify_dir_is_empty_or_create(char *dirname, bool *created, bool *found)
static char * progress_filename
static uint64 totalsize_kb
struct WriteTarState WriteTarState
static pg_time_t last_progress_report
static bool verify_checksums
static char * replication_slot
static void GetCopyDataEnd(size_t r, char *copybuf, size_t cursor)
static bool success
static void ReceiveBackupManifest(PGconn *conn)
static uint64 totaldone
static void progress_report(int tablespacenum, bool force, bool finished)
static void BaseBackup(char *compression_algorithm, char *compression_detail, CompressionLocation compressloc, pg_compress_specification *client_compress)
static bool manifest_force_encode
static char * manifest_checksums
#define MINIMUM_VERSION_FOR_TERMINATED_TARFILE
static TablespaceList tablespace_dirs
static bool found_tablespace_dirs
static bool in_log_streamer
static bool made_new_xlogdir
struct TablespaceList TablespaceList
static IncludeWal includewal
static void ReportCopyDataParseError(size_t r, char *copybuf)
struct ArchiveStreamState ArchiveStreamState
static bool do_sync
static bool writerecoveryconf
static bbstreamer * CreateBackupStreamer(char *archive_name, char *spclocation, bbstreamer **manifest_inject_streamer_p, bool is_recovery_guc_supported, bool expect_unterminated_tarfile, pg_compress_specification *compress)
static void cleanup_directories_atexit(void)
static bool temp_replication_slot
#define MINIMUM_VERSION_FOR_MANIFESTS
Definition: pg_basebackup.c:96
static bool no_slot
static bool made_tablespace_dirs
static char GetCopyDataByte(size_t r, char *copybuf, size_t *cursor)
#define VERBOSE_FILENAME_LENGTH
static uint64 GetCopyDataUInt64(size_t r, char *copybuf, size_t *cursor)
static bool fastcheckpoint
struct WriteManifestState WriteManifestState
static bool made_new_pgdata
static void kill_bgchild_atexit(void)
static DataDirSyncMethod sync_method
struct TablespaceListCell TablespaceListCell
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:41
static char * label
static void ReceiveBackupManifestInMemoryChunk(size_t r, char *copybuf, void *callback_data)
static bool showprogress
static void usage(void)
static void tablespace_list_append(const char *arg)
static const char * get_tablespace_mapping(const char *dir)
static char * basedir
static void disconnect_atexit(void)
static void ReceiveBackupManifestInMemory(PGconn *conn, PQExpBuffer buf)
static XLogRecPtr xlogendptr
#define MINIMUM_VERSION_FOR_PG_WAL
Definition: pg_basebackup.c:86
static int standby_message_timeout
static void sigchld_handler(SIGNAL_ARGS)
#define pg_ntoh64(x)
Definition: pg_bswap.h:126
#define MAXPGPATH
static char * filename
Definition: pg_dumpall.c:121
PGDLLIMPORT int optind
Definition: getopt.c:50
PGDLLIMPORT char * optarg
Definition: getopt.c:52
static pg_compress_algorithm compression_algorithm
Definition: pg_receivewal.c:55
static XLogRecPtr endpos
Definition: pg_receivewal.c:56
static XLogRecPtr startpos
static char * buf
Definition: pg_test_fsync.c:73
int64 pg_time_t
Definition: pgtime.h:23
int pg_mkdir_p(char *path, int omode)
Definition: pgmkdirp.c:57
#define is_absolute_path(filename)
Definition: port.h:103
int pg_strcasecmp(const char *s1, const char *s2)
Definition: pgstrcasecmp.c:36
void canonicalize_path(char *path)
Definition: path.c:264
int pg_check_dir(const char *dir)
Definition: pgcheckdir.c:33
const char * get_progname(const char *argv0)
Definition: path.c:574
pqsigfunc pqsignal(int signo, pqsigfunc func)
#define snprintf
Definition: port.h:238
#define fprintf
Definition: port.h:242
#define PGINVALID_SOCKET
Definition: port.h:31
#define is_windows_absolute_path(filename)
Definition: port.h:89
#define printf(...)
Definition: port.h:244
size_t strlcat(char *dst, const char *src, size_t siz)
Definition: strlcat.c:33
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define is_nonwindows_absolute_path(filename)
Definition: port.h:82
#define PG_DIAG_SQLSTATE
Definition: postgres_ext.h:56
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:72
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:90
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:265
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:114
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:129
#define PQExpBufferDataBroken(buf)
Definition: pqexpbuffer.h:67
char * c
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
bool ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
Definition: receivelog.c:453
bool CheckServerVersionForStreaming(PGconn *conn)
Definition: receivelog.c:375
PQExpBuffer GenerateRecoveryConfig(PGconn *pgconn, char *replication_slot)
Definition: recovery_gen.c:23
#define MINIMUM_VERSION_FOR_RECOVERY_GUC
Definition: recovery_gen.h:21
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:50
void AppendIntegerCommandOption(PQExpBuffer buf, bool use_new_option_syntax, char *option_name, int32 option_value)
Definition: streamutil.c:784
int dbgetpassword
Definition: streamutil.c:52
bool RetrieveWalSegSize(PGconn *conn)
Definition: streamutil.c:275
int WalSegSz
Definition: streamutil.c:34
char * dbhost
Definition: streamutil.c:48
char * dbport
Definition: streamutil.c:50
void AppendPlainCommandOption(PQExpBuffer buf, bool use_new_option_syntax, char *option_name)
Definition: streamutil.c:740
void AppendStringCommandOption(PQExpBuffer buf, bool use_new_option_syntax, char *option_name, char *option_value)
Definition: streamutil.c:761
char * connection_string
Definition: streamutil.c:47
PGconn * conn
Definition: streamutil.c:54
bool RunIdentifySystem(PGconn *conn, char **sysid, TimeLineID *starttli, XLogRecPtr *startpos, char **db_name)
Definition: streamutil.c:408
char * dbuser
Definition: streamutil.c:49
char manifest_filename[MAXPGPATH]
Definition: pg_basebackup.c:63
pg_compress_specification * compress
Definition: pg_basebackup.c:59
bbstreamer * manifest_inject_streamer
Definition: pg_basebackup.c:61
bbstreamer * streamer
Definition: pg_basebackup.c:60
PQExpBuffer manifest_buffer
Definition: pg_basebackup.c:62
char * sysidentifier
Definition: receivelog.h:33
TimeLineID timeline
Definition: receivelog.h:32
stream_stop_callback stream_stop
Definition: receivelog.h:41
char * replication_slot
Definition: receivelog.h:48
XLogRecPtr startpos
Definition: receivelog.h:31
bool do_sync
Definition: receivelog.h:38
pgsocket stop_socket
Definition: receivelog.h:43
int standby_message_timeout
Definition: receivelog.h:35
WalWriteMethod * walmethod
Definition: receivelog.h:46
bool mark_done
Definition: receivelog.h:37
char * partial_suffix
Definition: receivelog.h:47
bool synchronous
Definition: receivelog.h:36
struct TablespaceListCell * next
Definition: pg_basebackup.c:45
char old_dir[MAXPGPATH]
Definition: pg_basebackup.c:46
char new_dir[MAXPGPATH]
Definition: pg_basebackup.c:47
TablespaceListCell * tail
Definition: pg_basebackup.c:53
TablespaceListCell * head
Definition: pg_basebackup.c:52
void(* free)(WalWriteMethod *wwmethod)
Definition: walmethods.h:92
bool(* finish)(WalWriteMethod *wwmethod)
Definition: walmethods.h:86
const WalWriteMethodOps * ops
Definition: walmethods.h:105
char filename[MAXPGPATH]
Definition: pg_basebackup.c:75
bbstreamer * streamer
Definition: pg_basebackup.c:70
Definition: type.h:137
XLogRecPtr startptr
pg_compress_algorithm wal_compress_algorithm
char xlog[MAXPGPATH]
pg_compress_algorithm algorithm
Definition: compression.h:34
Definition: regguts.h:323
static StringInfo copybuf
Definition: tablesync.c:130
static void callback(struct sockaddr *addr, struct sockaddr *mask, void *unused)
Definition: test_ifaddrs.c:46
char * wait_result_to_str(int exitstatus)
Definition: wait_error.c:33
WalWriteMethod * CreateWalDirectoryMethod(const char *basedir, pg_compress_algorithm compression_algorithm, int compression_level, bool sync)
Definition: walmethods.c:640
WalWriteMethod * CreateWalTarMethod(const char *tarbase, pg_compress_algorithm compression_algorithm, int compression_level, bool sync)
Definition: walmethods.c:1355
static void CreateReplicationSlot(CreateReplicationSlotCmd *cmd)
Definition: walsender.c:1041
#define SIGCHLD
Definition: win32_port.h:178
void _dosmaperr(unsigned long)
Definition: win32error.c:177
#define kill(pid, sig)
Definition: win32_port.h:485
#define symlink(oldpath, newpath)
Definition: win32_port.h:235
#define select(n, r, w, e, timeout)
Definition: win32_port.h:495
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)
uint64 XLogRecPtr
Definition: xlogdefs.h:21
uint32 TimeLineID
Definition: xlogdefs.h:59
static const char * directory
Definition: zic.c:634