1 /*-------------------------------------------------------------------------
3 * pg_basebackup.c - receive a base backup using streaming replication protocol
5 * Author: Magnus Hagander <magnus@hagander.net>
7 * Portions Copyright (c) 1996-2014, PostgreSQL Global Development Group
10 * src/bin/pg_basebackup/pg_basebackup.c
11 *-------------------------------------------------------------------------
14 #include "postgres_fe.h"
19 #include <sys/types.h>
28 #include "getopt_long.h"
30 #include "pqexpbuffer.h"
33 #include "receivelog.h"
34 #include "replication/basebackup.h"
35 #include "streamutil.h"
38 #define atooid(x) ((Oid) strtoul((x), NULL, 10))
40 typedef struct TablespaceListCell
42 struct TablespaceListCell *next;
43 char old_dir[MAXPGPATH];
44 char new_dir[MAXPGPATH];
47 typedef struct TablespaceList
49 TablespaceListCell *head;
50 TablespaceListCell *tail;
54 static char *basedir = NULL;
55 static TablespaceList tablespace_dirs = {NULL, NULL};
56 static char *xlog_dir = "";
57 static char format = 'p'; /* p(lain)/t(ar) */
58 static char *label = "pg_basebackup base backup";
59 static bool showprogress = false;
60 static int verbose = 0;
61 static int compresslevel = 0;
62 static bool includewal = false;
63 static bool streamwal = false;
64 static bool fastcheckpoint = false;
65 static bool writerecoveryconf = false;
66 static int standby_message_timeout = 10 * 1000; /* 10 sec = default */
67 static pg_time_t last_progress_report = 0;
68 static int32 maxrate = 0; /* no limit by default */
71 /* Progress counters */
72 static uint64 totalsize;
73 static uint64 totaldone;
74 static int tablespacecount;
76 /* Pipe to communicate with background wal receiver process */
78 static int bgpipe[2] = {-1, -1};
81 /* Handle to child process */
82 static pid_t bgchild = -1;
84 /* End position for xlog streaming, empty string if unknown yet */
85 static XLogRecPtr xlogendptr;
88 static int has_xlogendptr = 0;
90 static volatile LONG has_xlogendptr = 0;
93 /* Contents of recovery.conf to be generated */
94 static PQExpBuffer recoveryconfcontents = NULL;
96 /* Function headers */
97 static void usage(void);
98 static void disconnect_and_exit(int code);
99 static void verify_dir_is_empty_or_create(char *dirname);
100 static void progress_report(int tablespacenum, const char *filename, bool force);
102 static void ReceiveTarFile(PGconn *conn, PGresult *res, int rownum);
103 static void ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res, int rownum);
104 static void GenerateRecoveryConf(PGconn *conn);
105 static void WriteRecoveryConf(void);
106 static void BaseBackup(void);
108 static bool reached_end_position(XLogRecPtr segendpos, uint32 timeline,
109 bool segment_finished);
111 static const char *get_tablespace_mapping(const char *dir);
112 static void tablespace_list_append(const char *arg);
116 disconnect_and_exit(int code)
124 * On windows, our background thread dies along with the process. But on
125 * Unix, if we have started a subprocess, we want to kill it off so it
126 * doesn't remain running trying to stream data.
129 kill(bgchild, SIGTERM);
137 * Split argument into old_dir and new_dir and append to tablespace mapping
141 tablespace_list_append(const char *arg)
143 TablespaceListCell *cell = (TablespaceListCell *) pg_malloc0(sizeof(TablespaceListCell));
148 dst_ptr = dst = cell->old_dir;
149 for (arg_ptr = arg; *arg_ptr; arg_ptr++)
151 if (dst_ptr - dst >= MAXPGPATH)
153 fprintf(stderr, _("%s: directory name too long\n"), progname);
157 if (*arg_ptr == '\\' && *(arg_ptr + 1) == '=')
158 ; /* skip backslash escaping = */
159 else if (*arg_ptr == '=' && (arg_ptr == arg || *(arg_ptr - 1) != '\\'))
163 fprintf(stderr, _("%s: multiple \"=\" signs in tablespace mapping\n"), progname);
167 dst = dst_ptr = cell->new_dir;
170 *dst_ptr++ = *arg_ptr;
173 if (!*cell->old_dir || !*cell->new_dir)
176 _("%s: invalid tablespace mapping format \"%s\", must be \"OLDDIR=NEWDIR\"\n"),
182 * This check isn't absolutely necessary. But all tablespaces are created
183 * with absolute directories, so specifying a non-absolute path here would
184 * just never match, possibly confusing users. It's also good to be
185 * consistent with the new_dir check.
187 if (!is_absolute_path(cell->old_dir))
189 fprintf(stderr, _("%s: old directory is not an absolute path in tablespace mapping: %s\n"),
190 progname, cell->old_dir);
194 if (!is_absolute_path(cell->new_dir))
196 fprintf(stderr, _("%s: new directory is not an absolute path in tablespace mapping: %s\n"),
197 progname, cell->new_dir);
201 if (tablespace_dirs.tail)
202 tablespace_dirs.tail->next = cell;
204 tablespace_dirs.head = cell;
205 tablespace_dirs.tail = cell;
211 get_gz_error(gzFile gzf)
216 errmsg = gzerror(gzf, &errnum);
217 if (errnum == Z_ERRNO)
218 return strerror(errno);
227 printf(_("%s takes a base backup of a running PostgreSQL server.\n\n"),
229 printf(_("Usage:\n"));
230 printf(_(" %s [OPTION]...\n"), progname);
231 printf(_("\nOptions controlling the output:\n"));
232 printf(_(" -D, --pgdata=DIRECTORY receive base backup into directory\n"));
233 printf(_(" -F, --format=p|t output format (plain (default), tar)\n"));
234 printf(_(" -r, --max-rate=RATE maximum transfer rate to transfer data directory\n"
235 " (in kB/s, or use suffix \"k\" or \"M\")\n"));
236 printf(_(" -R, --write-recovery-conf\n"
237 " write recovery.conf after backup\n"));
238 printf(_(" -T, --tablespace-mapping=OLDDIR=NEWDIR\n"
239 " relocate tablespace in OLDDIR to NEWDIR\n"));
240 printf(_(" -x, --xlog include required WAL files in backup (fetch mode)\n"));
241 printf(_(" -X, --xlog-method=fetch|stream\n"
242 " include required WAL files with specified method\n"));
243 printf(_(" --xlogdir=XLOGDIR location for the transaction log directory\n"));
244 printf(_(" -z, --gzip compress tar output\n"));
245 printf(_(" -Z, --compress=0-9 compress tar output with given compression level\n"));
246 printf(_("\nGeneral options:\n"));
247 printf(_(" -c, --checkpoint=fast|spread\n"
248 " set fast or spread checkpointing\n"));
249 printf(_(" -l, --label=LABEL set backup label\n"));
250 printf(_(" -P, --progress show progress information\n"));
251 printf(_(" -v, --verbose output verbose messages\n"));
252 printf(_(" -V, --version output version information, then exit\n"));
253 printf(_(" -?, --help show this help, then exit\n"));
254 printf(_("\nConnection options:\n"));
255 printf(_(" -d, --dbname=CONNSTR connection string\n"));
256 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
257 printf(_(" -p, --port=PORT database server port number\n"));
258 printf(_(" -s, --status-interval=INTERVAL\n"
259 " time between status packets sent to server (in seconds)\n"));
260 printf(_(" -U, --username=NAME connect as specified database user\n"));
261 printf(_(" -w, --no-password never prompt for password\n"));
262 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
263 printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
268 * Called in the background process every time data is received.
269 * On Unix, we check to see if there is any data on our pipe
270 * (which would mean we have a stop position), and if it is, check if
271 * it is time to stop.
272 * On Windows, we are in a single process, so we can just check if it's
276 reached_end_position(XLogRecPtr segendpos, uint32 timeline,
277 bool segment_finished)
287 * Don't have the end pointer yet - check our pipe to see if it has
291 FD_SET(bgpipe[0], &fds);
293 MemSet(&tv, 0, sizeof(tv));
295 r = select(bgpipe[0] + 1, &fds, NULL, NULL, &tv);
302 MemSet(xlogend, 0, sizeof(xlogend));
303 r = read(bgpipe[0], xlogend, sizeof(xlogend) - 1);
306 fprintf(stderr, _("%s: could not read from ready pipe: %s\n"),
307 progname, strerror(errno));
311 if (sscanf(xlogend, "%X/%X", &hi, &lo) != 2)
314 _("%s: could not parse transaction log location \"%s\"\n"),
318 xlogendptr = ((uint64) hi) << 32 | lo;
322 * Fall through to check if we've reached the point further
329 * No data received on the pipe means we don't know the end
330 * position yet - so just say it's not time to stop yet.
337 * On win32, has_xlogendptr is set by the main thread, so if it's not
338 * set here, we just go back and wait until it shows up.
345 * At this point we have an end pointer, so compare it to the current
346 * position to figure out if it's time to stop.
348 if (segendpos >= xlogendptr)
352 * Have end pointer, but haven't reached it yet - so tell the caller to
362 char xlogdir[MAXPGPATH];
368 LogStreamerMain(logstreamer_param *param)
370 if (!ReceiveXlogStream(param->bgconn, param->startptr, param->timeline,
371 param->sysidentifier, param->xlogdir,
372 reached_end_position, standby_message_timeout,
376 * Any errors will already have been reported in the function process,
377 * but we need to tell the parent that we didn't shutdown in a nice
382 PQfinish(param->bgconn);
387 * Initiate background process for receiving xlog during the backup.
388 * The background stream will use its own database connection so we can
389 * stream the logfile in parallel with the backups.
392 StartLogStreamer(char *startpos, uint32 timeline, char *sysidentifier)
394 logstreamer_param *param;
398 param = pg_malloc0(sizeof(logstreamer_param));
399 param->timeline = timeline;
400 param->sysidentifier = sysidentifier;
402 /* Convert the starting position */
403 if (sscanf(startpos, "%X/%X", &hi, &lo) != 2)
406 _("%s: could not parse transaction log location \"%s\"\n"),
408 disconnect_and_exit(1);
410 param->startptr = ((uint64) hi) << 32 | lo;
411 /* Round off to even segment position */
412 param->startptr -= param->startptr % XLOG_SEG_SIZE;
415 /* Create our background pipe */
416 if (pipe(bgpipe) < 0)
419 _("%s: could not create pipe for background process: %s\n"),
420 progname, strerror(errno));
421 disconnect_and_exit(1);
425 /* Get a second connection */
426 param->bgconn = GetConnection();
428 /* Error message already written in GetConnection() */
432 * Always in plain format, so we can write to basedir/pg_xlog. But the
433 * directory entry in the tar file may arrive later, so make sure it's
434 * created before we start.
436 snprintf(param->xlogdir, sizeof(param->xlogdir), "%s/pg_xlog", basedir);
437 verify_dir_is_empty_or_create(param->xlogdir);
440 * Start a child process and tell it to start streaming. On Unix, this is
441 * a fork(). On Windows, we create a thread.
447 /* in child process */
448 exit(LogStreamerMain(param));
450 else if (bgchild < 0)
452 fprintf(stderr, _("%s: could not create background process: %s\n"),
453 progname, strerror(errno));
454 disconnect_and_exit(1);
458 * Else we are in the parent process and all is well.
461 bgchild = _beginthreadex(NULL, 0, (void *) LogStreamerMain, param, 0, NULL);
464 fprintf(stderr, _("%s: could not create background thread: %s\n"),
465 progname, strerror(errno));
466 disconnect_and_exit(1);
472 * Verify that the given directory exists and is empty. If it does not
473 * exist, it is created. If it exists but is not empty, an error will
474 * be give and the process ended.
477 verify_dir_is_empty_or_create(char *dirname)
479 switch (pg_check_dir(dirname))
484 * Does not exist, so create
486 if (pg_mkdir_p(dirname, S_IRWXU) == -1)
489 _("%s: could not create directory \"%s\": %s\n"),
490 progname, dirname, strerror(errno));
491 disconnect_and_exit(1);
508 _("%s: directory \"%s\" exists but is not empty\n"),
510 disconnect_and_exit(1);
516 fprintf(stderr, _("%s: could not access directory \"%s\": %s\n"),
517 progname, dirname, strerror(errno));
518 disconnect_and_exit(1);
524 * Print a progress report based on the global variables. If verbose output
525 * is enabled, also print the current file name.
527 * Progress report is written at maximum once per second, unless the
528 * force parameter is set to true.
531 progress_report(int tablespacenum, const char *filename, bool force)
534 char totaldone_str[32];
535 char totalsize_str[32];
542 if (now == last_progress_report && !force)
543 return; /* Max once per second */
545 last_progress_report = now;
546 percent = totalsize ? (int) ((totaldone / 1024) * 100 / totalsize) : 0;
549 * Avoid overflowing past 100% or the full size. This may make the total
550 * size number change as we approach the end of the backup (the estimate
551 * will always be wrong if WAL is included), but that's better than having
552 * the done column be bigger than the total.
556 if (totaldone / 1024 > totalsize)
557 totalsize = totaldone / 1024;
560 * Separate step to keep platform-dependent format code out of
561 * translatable strings. And we only test for INT64_FORMAT availability
562 * in snprintf, not fprintf.
564 snprintf(totaldone_str, sizeof(totaldone_str), INT64_FORMAT,
566 snprintf(totalsize_str, sizeof(totalsize_str), INT64_FORMAT, totalsize);
568 #define VERBOSE_FILENAME_LENGTH 35
574 * No filename given, so clear the status line (used for last
578 ngettext("%*s/%s kB (100%%), %d/%d tablespace %*s",
579 "%*s/%s kB (100%%), %d/%d tablespaces %*s",
581 (int) strlen(totalsize_str),
582 totaldone_str, totalsize_str,
583 tablespacenum, tablespacecount,
584 VERBOSE_FILENAME_LENGTH + 5, "");
587 bool truncate = (strlen(filename) > VERBOSE_FILENAME_LENGTH);
590 ngettext("%*s/%s kB (%d%%), %d/%d tablespace (%s%-*.*s)",
591 "%*s/%s kB (%d%%), %d/%d tablespaces (%s%-*.*s)",
593 (int) strlen(totalsize_str),
594 totaldone_str, totalsize_str, percent,
595 tablespacenum, tablespacecount,
596 /* Prefix with "..." if we do leading truncation */
597 truncate ? "..." : "",
598 truncate ? VERBOSE_FILENAME_LENGTH - 3 : VERBOSE_FILENAME_LENGTH,
599 truncate ? VERBOSE_FILENAME_LENGTH - 3 : VERBOSE_FILENAME_LENGTH,
600 /* Truncate filename at beginning if it's too long */
601 truncate ? filename + strlen(filename) - VERBOSE_FILENAME_LENGTH + 3 : filename);
606 ngettext("%*s/%s kB (%d%%), %d/%d tablespace",
607 "%*s/%s kB (%d%%), %d/%d tablespaces",
609 (int) strlen(totalsize_str),
610 totaldone_str, totalsize_str, percent,
611 tablespacenum, tablespacecount);
613 fprintf(stderr, "\r");
617 parse_max_rate(char *src)
624 result = strtod(src, &after_num);
625 if (src == after_num)
628 _("%s: transfer rate \"%s\" is not a valid value\n"),
635 _("%s: invalid transfer rate \"%s\": %s\n"),
636 progname, src, strerror(errno));
643 * Reject obviously wrong values here.
645 fprintf(stderr, _("%s: transfer rate must be greater than zero\n"),
651 * Evaluate suffix, after skipping over possible whitespace. Lack of
652 * suffix means kilobytes.
654 while (*after_num != '\0' && isspace((unsigned char) *after_num))
657 if (*after_num != '\0')
660 if (*after_num == 'k')
662 /* kilobyte is the expected unit. */
665 else if (*after_num == 'M')
672 /* The rest can only consist of white space. */
673 while (*after_num != '\0' && isspace((unsigned char) *after_num))
676 if (*after_num != '\0')
679 _("%s: invalid --max-rate unit: \"%s\"\n"),
685 if ((uint64) result != (uint64) ((uint32) result))
688 _("%s: transfer rate \"%s\" exceeds integer range\n"),
694 * The range is checked on the server side too, but avoid the server
695 * connection if a nonsensical value was passed.
697 if (result < MAX_RATE_LOWER || result > MAX_RATE_UPPER)
700 _("%s: transfer rate \"%s\" is out of range\n"),
705 return (int32) result;
709 * Write a piece of tar data
716 FILE *tarfile, char *buf, int r, char *current_file)
719 if (ztarfile != NULL)
721 if (gzwrite(ztarfile, buf, r) != r)
724 _("%s: could not write to compressed file \"%s\": %s\n"),
725 progname, current_file, get_gz_error(ztarfile));
726 disconnect_and_exit(1);
732 if (fwrite(buf, r, 1, tarfile) != 1)
734 fprintf(stderr, _("%s: could not write to file \"%s\": %s\n"),
735 progname, current_file, strerror(errno));
736 disconnect_and_exit(1);
742 #define WRITE_TAR_DATA(buf, sz) writeTarData(ztarfile, tarfile, buf, sz, filename)
744 #define WRITE_TAR_DATA(buf, sz) writeTarData(tarfile, buf, sz, filename)
748 * Receive a tar format file from the connection to the server, and write
749 * the data from this file directly into a tar file. If compression is
750 * enabled, the data will be compressed while written to the file.
752 * The file will be named base.tar[.gz] if it's for the main data directory
753 * or <tablespaceoid>.tar[.gz] if it's for another tablespace.
755 * No attempt to inspect or validate the contents of the file is done.
758 ReceiveTarFile(PGconn *conn, PGresult *res, int rownum)
760 char filename[MAXPGPATH];
761 char *copybuf = NULL;
762 FILE *tarfile = NULL;
764 bool basetablespace = PQgetisnull(res, rownum, 0);
765 bool in_tarhdr = true;
766 bool skip_file = false;
771 gzFile ztarfile = NULL;
779 if (strcmp(basedir, "-") == 0)
782 if (compresslevel != 0)
784 ztarfile = gzdopen(dup(fileno(stdout)), "wb");
785 if (gzsetparams(ztarfile, compresslevel,
786 Z_DEFAULT_STRATEGY) != Z_OK)
789 _("%s: could not set compression level %d: %s\n"),
790 progname, compresslevel, get_gz_error(ztarfile));
791 disconnect_and_exit(1);
797 strcpy(filename, "-");
802 if (compresslevel != 0)
804 snprintf(filename, sizeof(filename), "%s/base.tar.gz", basedir);
805 ztarfile = gzopen(filename, "wb");
806 if (gzsetparams(ztarfile, compresslevel,
807 Z_DEFAULT_STRATEGY) != Z_OK)
810 _("%s: could not set compression level %d: %s\n"),
811 progname, compresslevel, get_gz_error(ztarfile));
812 disconnect_and_exit(1);
818 snprintf(filename, sizeof(filename), "%s/base.tar", basedir);
819 tarfile = fopen(filename, "wb");
826 * Specific tablespace
829 if (compresslevel != 0)
831 snprintf(filename, sizeof(filename), "%s/%s.tar.gz", basedir,
832 PQgetvalue(res, rownum, 0));
833 ztarfile = gzopen(filename, "wb");
834 if (gzsetparams(ztarfile, compresslevel,
835 Z_DEFAULT_STRATEGY) != Z_OK)
838 _("%s: could not set compression level %d: %s\n"),
839 progname, compresslevel, get_gz_error(ztarfile));
840 disconnect_and_exit(1);
846 snprintf(filename, sizeof(filename), "%s/%s.tar", basedir,
847 PQgetvalue(res, rownum, 0));
848 tarfile = fopen(filename, "wb");
853 if (compresslevel != 0)
857 /* Compression is in use */
859 _("%s: could not create compressed file \"%s\": %s\n"),
860 progname, filename, get_gz_error(ztarfile));
861 disconnect_and_exit(1);
867 /* Either no zlib support, or zlib support but compresslevel = 0 */
870 fprintf(stderr, _("%s: could not create file \"%s\": %s\n"),
871 progname, filename, strerror(errno));
872 disconnect_and_exit(1);
877 * Get the COPY data stream
879 res = PQgetResult(conn);
880 if (PQresultStatus(res) != PGRES_COPY_OUT)
882 fprintf(stderr, _("%s: could not get COPY data stream: %s"),
883 progname, PQerrorMessage(conn));
884 disconnect_and_exit(1);
897 r = PQgetCopyData(conn, ©buf, 0);
901 * End of chunk. If requested, and this is the base tablespace,
902 * write recovery.conf into the tarfile. When done, close the file
905 * Also, write two completely empty blocks at the end of the tar
906 * file, as required by some tar programs.
910 MemSet(zerobuf, 0, sizeof(zerobuf));
912 if (basetablespace && writerecoveryconf)
917 tarCreateHeader(header, "recovery.conf", NULL,
918 recoveryconfcontents->len,
922 padding = ((recoveryconfcontents->len + 511) & ~511) - recoveryconfcontents->len;
924 WRITE_TAR_DATA(header, sizeof(header));
925 WRITE_TAR_DATA(recoveryconfcontents->data, recoveryconfcontents->len);
927 WRITE_TAR_DATA(zerobuf, padding);
930 /* 2 * 512 bytes empty data at end of file */
931 WRITE_TAR_DATA(zerobuf, sizeof(zerobuf));
934 if (ztarfile != NULL)
936 if (gzclose(ztarfile) != 0)
939 _("%s: could not close compressed file \"%s\": %s\n"),
940 progname, filename, get_gz_error(ztarfile));
941 disconnect_and_exit(1);
947 if (strcmp(basedir, "-") != 0)
949 if (fclose(tarfile) != 0)
952 _("%s: could not close file \"%s\": %s\n"),
953 progname, filename, strerror(errno));
954 disconnect_and_exit(1);
963 fprintf(stderr, _("%s: could not read COPY data: %s"),
964 progname, PQerrorMessage(conn));
965 disconnect_and_exit(1);
968 if (!writerecoveryconf || !basetablespace)
971 * When not writing recovery.conf, or when not working on the base
972 * tablespace, we never have to look for an existing recovery.conf
973 * file in the stream.
975 WRITE_TAR_DATA(copybuf, r);
980 * Look for a recovery.conf in the existing tar stream. If it's
981 * there, we must skip it so we can later overwrite it with our
982 * own version of the file.
984 * To do this, we have to process the individual files inside the
985 * TAR stream. The stream consists of a header and zero or more
986 * chunks, all 512 bytes long. The stream from the server is
987 * broken up into smaller pieces, so we have to track the size of
988 * the files to find the next header structure.
998 * We're currently reading a header structure inside the
999 * TAR stream, i.e. the file metadata.
1004 * Copy the header structure into tarhdr in case the
1005 * header is not aligned to 512 bytes or it's not
1006 * returned in whole by the last PQgetCopyData call.
1011 hdrleft = 512 - tarhdrsz;
1012 bytes2copy = (rr > hdrleft ? hdrleft : rr);
1014 memcpy(&tarhdr[tarhdrsz], copybuf + pos, bytes2copy);
1018 tarhdrsz += bytes2copy;
1023 * We have the complete header structure in tarhdr,
1024 * look at the file metadata: - the subsequent file
1025 * contents have to be skipped if the filename is
1026 * recovery.conf - find out the size of the file
1027 * padded to the next multiple of 512
1031 skip_file = (strcmp(&tarhdr[0], "recovery.conf") == 0);
1033 sscanf(&tarhdr[124], "%11o", (unsigned int *) &filesz);
1035 padding = ((filesz + 511) & ~511) - filesz;
1038 /* Next part is the file, not the header */
1042 * If we're not skipping the file, write the tar
1043 * header unmodified.
1046 WRITE_TAR_DATA(tarhdr, 512);
1052 * We're processing a file's contents.
1057 * We still have data to read (and possibly write).
1061 bytes2write = (filesz > rr ? rr : filesz);
1064 WRITE_TAR_DATA(copybuf + pos, bytes2write);
1068 filesz -= bytes2write;
1073 * No more data in the current file, the next piece of
1074 * data (if any) will be a new file header structure.
1085 progress_report(rownum, filename, false);
1087 progress_report(rownum, filename, true);
1089 if (copybuf != NULL)
1095 * Retrieve tablespace path, either relocated or original depending on whether
1096 * -T was passed or not.
1099 get_tablespace_mapping(const char *dir)
1101 TablespaceListCell *cell;
1103 for (cell = tablespace_dirs.head; cell; cell = cell->next)
1104 if (strcmp(dir, cell->old_dir) == 0)
1105 return cell->new_dir;
1112 * Receive a tar format stream from the connection to the server, and unpack
1113 * the contents of it into a directory. Only files, directories and
1114 * symlinks are supported, no other kinds of special files.
1116 * If the data is for the main data directory, it will be restored in the
1117 * specified directory. If it's for another tablespace, it will be restored
1118 * in the original or mapped directory.
1121 ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res, int rownum)
1123 char current_path[MAXPGPATH];
1124 char filename[MAXPGPATH];
1125 const char *mapped_tblspc_path;
1126 int current_len_left;
1127 int current_padding = 0;
1128 bool basetablespace;
1129 char *copybuf = NULL;
1132 basetablespace = PQgetisnull(res, rownum, 0);
1134 strlcpy(current_path, basedir, sizeof(current_path));
1136 strlcpy(current_path,
1137 get_tablespace_mapping(PQgetvalue(res, rownum, 1)),
1138 sizeof(current_path));
1143 res = PQgetResult(conn);
1144 if (PQresultStatus(res) != PGRES_COPY_OUT)
1146 fprintf(stderr, _("%s: could not get COPY data stream: %s"),
1147 progname, PQerrorMessage(conn));
1148 disconnect_and_exit(1);
1155 if (copybuf != NULL)
1161 r = PQgetCopyData(conn, ©buf, 0);
1175 fprintf(stderr, _("%s: could not read COPY data: %s"),
1176 progname, PQerrorMessage(conn));
1177 disconnect_and_exit(1);
1185 * No current file, so this must be the header for a new file
1189 fprintf(stderr, _("%s: invalid tar block header size: %d\n"),
1191 disconnect_and_exit(1);
1195 if (sscanf(copybuf + 124, "%11o", ¤t_len_left) != 1)
1197 fprintf(stderr, _("%s: could not parse file size\n"),
1199 disconnect_and_exit(1);
1202 /* Set permissions on the file */
1203 if (sscanf(©buf[100], "%07o ", &filemode) != 1)
1205 fprintf(stderr, _("%s: could not parse file mode\n"),
1207 disconnect_and_exit(1);
1211 * All files are padded up to 512 bytes
1214 ((current_len_left + 511) & ~511) - current_len_left;
1217 * First part of header is zero terminated filename
1219 snprintf(filename, sizeof(filename), "%s/%s", current_path,
1221 if (filename[strlen(filename) - 1] == '/')
1224 * Ends in a slash means directory or symlink to directory
1226 if (copybuf[156] == '5')
1231 filename[strlen(filename) - 1] = '\0'; /* Remove trailing slash */
1232 if (mkdir(filename, S_IRWXU) != 0)
1235 * When streaming WAL, pg_xlog will have been created
1236 * by the wal receiver process. Also, when transaction
1237 * log directory location was specified, pg_xlog has
1238 * already been created as a symbolic link before
1239 * starting the actual backup. So just ignore failure
1242 if ((!streamwal && (strcmp(xlog_dir, "") == 0))
1243 || strcmp(filename + strlen(filename) - 8, "/pg_xlog") != 0)
1246 _("%s: could not create directory \"%s\": %s\n"),
1247 progname, filename, strerror(errno));
1248 disconnect_and_exit(1);
1252 if (chmod(filename, (mode_t) filemode))
1254 _("%s: could not set permissions on directory \"%s\": %s\n"),
1255 progname, filename, strerror(errno));
1258 else if (copybuf[156] == '2')
1263 * It's most likely a link in pg_tblspc directory, to the
1264 * location of a tablespace. Apply any tablespace mapping
1265 * given on the command line (--tablespace-mapping).
1266 * (We blindly apply the mapping without checking that
1267 * the link really is inside pg_tblspc. We don't expect
1268 * there to be other symlinks in a data directory, but
1269 * if there are, you can call it an undocumented feature
1270 * that you can map them too.)
1272 filename[strlen(filename) - 1] = '\0'; /* Remove trailing slash */
1274 mapped_tblspc_path = get_tablespace_mapping(©buf[157]);
1275 if (symlink(mapped_tblspc_path, filename) != 0)
1278 _("%s: could not create symbolic link from \"%s\" to \"%s\": %s\n"),
1279 progname, filename, mapped_tblspc_path,
1281 disconnect_and_exit(1);
1287 _("%s: unrecognized link indicator \"%c\"\n"),
1288 progname, copybuf[156]);
1289 disconnect_and_exit(1);
1291 continue; /* directory or link handled */
1297 file = fopen(filename, "wb");
1300 fprintf(stderr, _("%s: could not create file \"%s\": %s\n"),
1301 progname, filename, strerror(errno));
1302 disconnect_and_exit(1);
1306 if (chmod(filename, (mode_t) filemode))
1307 fprintf(stderr, _("%s: could not set permissions on file \"%s\": %s\n"),
1308 progname, filename, strerror(errno));
1311 if (current_len_left == 0)
1314 * Done with this file, next one will be a new tar header
1324 * Continuing blocks in existing file
1326 if (current_len_left == 0 && r == current_padding)
1329 * Received the padding block for this file, ignore it and
1330 * close the file, then move on to the next tar header.
1338 if (fwrite(copybuf, r, 1, file) != 1)
1340 fprintf(stderr, _("%s: could not write to file \"%s\": %s\n"),
1341 progname, filename, strerror(errno));
1342 disconnect_and_exit(1);
1345 progress_report(rownum, filename, false);
1347 current_len_left -= r;
1348 if (current_len_left == 0 && current_padding == 0)
1351 * Received the last block, and there is no padding to be
1352 * expected. Close the file and move on to the next tar
1359 } /* continuing data in existing file */
1360 } /* loop over all data blocks */
1361 progress_report(rownum, filename, true);
1366 _("%s: COPY stream ended before last file was finished\n"),
1368 disconnect_and_exit(1);
1371 if (copybuf != NULL)
1374 if (basetablespace && writerecoveryconf)
1375 WriteRecoveryConf();
1379 * Escape a parameter value so that it can be used as part of a libpq
1380 * connection string, e.g. in:
1382 * application_name=<value>
1384 * The returned string is malloc'd. Return NULL on out-of-memory.
1387 escapeConnectionParameter(const char *src)
1389 bool need_quotes = false;
1390 bool need_escaping = false;
1396 * First check if quoting is needed. Any quote (') or backslash (\)
1397 * characters need to be escaped. Parameters are separated by whitespace,
1398 * so any string containing whitespace characters need to be quoted. An
1399 * empty string is represented by ''.
1401 if (strchr(src, '\'') != NULL || strchr(src, '\\') != NULL)
1402 need_escaping = true;
1404 for (p = src; *p; p++)
1406 if (isspace((unsigned char) *p))
1414 return pg_strdup("''");
1416 if (!need_quotes && !need_escaping)
1417 return pg_strdup(src); /* no quoting or escaping needed */
1420 * Allocate a buffer large enough for the worst case that all the source
1421 * characters need to be escaped, plus quotes.
1423 dstbuf = pg_malloc(strlen(src) * 2 + 2 + 1);
1430 if (*src == '\'' || *src == '\\')
1442 * Escape a string so that it can be used as a value in a key-value pair
1443 * a configuration file.
1446 escape_quotes(const char *src)
1448 char *result = escape_single_quotes_ascii(src);
1452 fprintf(stderr, _("%s: out of memory\n"), progname);
1459 * Create a recovery.conf file in memory using a PQExpBuffer
1462 GenerateRecoveryConf(PGconn *conn)
1464 PQconninfoOption *connOptions;
1465 PQconninfoOption *option;
1466 PQExpBufferData conninfo_buf;
1469 recoveryconfcontents = createPQExpBuffer();
1470 if (!recoveryconfcontents)
1472 fprintf(stderr, _("%s: out of memory\n"), progname);
1473 disconnect_and_exit(1);
1476 connOptions = PQconninfo(conn);
1477 if (connOptions == NULL)
1479 fprintf(stderr, _("%s: out of memory\n"), progname);
1480 disconnect_and_exit(1);
1483 appendPQExpBufferStr(recoveryconfcontents, "standby_mode = 'on'\n");
1485 initPQExpBuffer(&conninfo_buf);
1486 for (option = connOptions; option && option->keyword; option++)
1489 * Do not emit this setting if: - the setting is "replication",
1490 * "dbname" or "fallback_application_name", since these would be
1491 * overridden by the libpqwalreceiver module anyway. - not set or
1494 if (strcmp(option->keyword, "replication") == 0 ||
1495 strcmp(option->keyword, "dbname") == 0 ||
1496 strcmp(option->keyword, "fallback_application_name") == 0 ||
1497 (option->val == NULL) ||
1498 (option->val != NULL && option->val[0] == '\0'))
1501 /* Separate key-value pairs with spaces */
1502 if (conninfo_buf.len != 0)
1503 appendPQExpBufferStr(&conninfo_buf, " ");
1506 * Write "keyword=value" pieces, the value string is escaped and/or
1507 * quoted if necessary.
1509 escaped = escapeConnectionParameter(option->val);
1510 appendPQExpBuffer(&conninfo_buf, "%s=%s", option->keyword, escaped);
1515 * Escape the connection string, so that it can be put in the config file.
1516 * Note that this is different from the escaping of individual connection
1519 escaped = escape_quotes(conninfo_buf.data);
1520 appendPQExpBuffer(recoveryconfcontents, "primary_conninfo = '%s'\n", escaped);
1523 if (PQExpBufferBroken(recoveryconfcontents) ||
1524 PQExpBufferDataBroken(conninfo_buf))
1526 fprintf(stderr, _("%s: out of memory\n"), progname);
1527 disconnect_and_exit(1);
1530 termPQExpBuffer(&conninfo_buf);
1532 PQconninfoFree(connOptions);
1537 * Write a recovery.conf file into the directory specified in basedir,
1538 * with the contents already collected in memory.
1541 WriteRecoveryConf(void)
1543 char filename[MAXPGPATH];
1546 sprintf(filename, "%s/recovery.conf", basedir);
1548 cf = fopen(filename, "w");
1551 fprintf(stderr, _("%s: could not create file \"%s\": %s\n"), progname, filename, strerror(errno));
1552 disconnect_and_exit(1);
1555 if (fwrite(recoveryconfcontents->data, recoveryconfcontents->len, 1, cf) != 1)
1558 _("%s: could not write to file \"%s\": %s\n"),
1559 progname, filename, strerror(errno));
1560 disconnect_and_exit(1);
1571 char *sysidentifier;
1572 TimeLineID latesttli;
1573 TimeLineID starttli;
1575 char escaped_label[MAXPGPATH];
1576 char *maxrate_clause = NULL;
1585 * Connect in replication mode to the server
1587 conn = GetConnection();
1589 /* Error message already written in GetConnection() */
1593 * Check server version. BASE_BACKUP command was introduced in 9.1, so we
1594 * can't work with servers older than 9.1.
1596 minServerMajor = 901;
1597 maxServerMajor = PG_VERSION_NUM / 100;
1598 serverMajor = PQserverVersion(conn) / 100;
1599 if (serverMajor < minServerMajor || serverMajor > maxServerMajor)
1601 const char *serverver = PQparameterStatus(conn, "server_version");
1603 fprintf(stderr, _("%s: incompatible server version %s\n"),
1604 progname, serverver ? serverver : "'unknown'");
1605 disconnect_and_exit(1);
1609 * If WAL streaming was requested, also check that the server is new
1612 if (streamwal && !CheckServerVersionForStreaming(conn))
1614 /* Error message already written in CheckServerVersionForStreaming() */
1615 disconnect_and_exit(1);
1619 * Build contents of recovery.conf if requested
1621 if (writerecoveryconf)
1622 GenerateRecoveryConf(conn);
1625 * Run IDENTIFY_SYSTEM so we can get the timeline
1627 if (!RunIdentifySystem(conn, &sysidentifier, &latesttli, NULL, NULL))
1628 disconnect_and_exit(1);
1631 * Start the actual backup
1633 PQescapeStringConn(conn, escaped_label, label, sizeof(escaped_label), &i);
1636 maxrate_clause = psprintf("MAX_RATE %u", maxrate);
1639 psprintf("BASE_BACKUP LABEL '%s' %s %s %s %s %s",
1641 showprogress ? "PROGRESS" : "",
1642 includewal && !streamwal ? "WAL" : "",
1643 fastcheckpoint ? "FAST" : "",
1644 includewal ? "NOWAIT" : "",
1645 maxrate_clause ? maxrate_clause : "");
1647 if (PQsendQuery(conn, basebkp) == 0)
1649 fprintf(stderr, _("%s: could not send replication command \"%s\": %s"),
1650 progname, "BASE_BACKUP", PQerrorMessage(conn));
1651 disconnect_and_exit(1);
1655 * Get the starting xlog position
1657 res = PQgetResult(conn);
1658 if (PQresultStatus(res) != PGRES_TUPLES_OK)
1660 fprintf(stderr, _("%s: could not initiate base backup: %s"),
1661 progname, PQerrorMessage(conn));
1662 disconnect_and_exit(1);
1664 if (PQntuples(res) != 1)
1667 _("%s: server returned unexpected response to BASE_BACKUP command; got %d rows and %d fields, expected %d rows and %d fields\n"),
1668 progname, PQntuples(res), PQnfields(res), 1, 2);
1669 disconnect_and_exit(1);
1672 strlcpy(xlogstart, PQgetvalue(res, 0, 0), sizeof(xlogstart));
1675 * 9.3 and later sends the TLI of the starting point. With older servers,
1676 * assume it's the same as the latest timeline reported by
1679 if (PQnfields(res) >= 2)
1680 starttli = atoi(PQgetvalue(res, 0, 1));
1682 starttli = latesttli;
1684 MemSet(xlogend, 0, sizeof(xlogend));
1686 if (verbose && includewal)
1687 fprintf(stderr, _("transaction log start point: %s on timeline %u\n"),
1688 xlogstart, starttli);
1693 res = PQgetResult(conn);
1694 if (PQresultStatus(res) != PGRES_TUPLES_OK)
1696 fprintf(stderr, _("%s: could not get backup header: %s"),
1697 progname, PQerrorMessage(conn));
1698 disconnect_and_exit(1);
1700 if (PQntuples(res) < 1)
1702 fprintf(stderr, _("%s: no data returned from server\n"), progname);
1703 disconnect_and_exit(1);
1707 * Sum up the total size, for progress reporting
1709 totalsize = totaldone = 0;
1710 tablespacecount = PQntuples(res);
1711 for (i = 0; i < PQntuples(res); i++)
1713 totalsize += atol(PQgetvalue(res, i, 2));
1716 * Verify tablespace directories are empty. Don't bother with the
1717 * first once since it can be relocated, and it will be checked before
1718 * we do anything anyway.
1720 if (format == 'p' && !PQgetisnull(res, i, 1))
1722 char *path = (char *) get_tablespace_mapping(PQgetvalue(res, i, 1));
1724 verify_dir_is_empty_or_create(path);
1729 * When writing to stdout, require a single tablespace
1731 if (format == 't' && strcmp(basedir, "-") == 0 && PQntuples(res) > 1)
1734 _("%s: can only write single tablespace to stdout, database has %d\n"),
1735 progname, PQntuples(res));
1736 disconnect_and_exit(1);
1740 * If we're streaming WAL, start the streaming session before we start
1741 * receiving the actual data chunks.
1746 fprintf(stderr, _("%s: starting background WAL receiver\n"),
1748 StartLogStreamer(xlogstart, starttli, sysidentifier);
1752 * Start receiving chunks
1754 for (i = 0; i < PQntuples(res); i++)
1757 ReceiveTarFile(conn, res, i);
1759 ReceiveAndUnpackTarFile(conn, res, i);
1760 } /* Loop over all tablespaces */
1764 progress_report(PQntuples(res), NULL, true);
1765 fprintf(stderr, "\n"); /* Need to move to next line */
1771 * Get the stop position
1773 res = PQgetResult(conn);
1774 if (PQresultStatus(res) != PGRES_TUPLES_OK)
1777 _("%s: could not get transaction log end position from server: %s"),
1778 progname, PQerrorMessage(conn));
1779 disconnect_and_exit(1);
1781 if (PQntuples(res) != 1)
1784 _("%s: no transaction log end position returned from server\n"),
1786 disconnect_and_exit(1);
1788 strlcpy(xlogend, PQgetvalue(res, 0, 0), sizeof(xlogend));
1789 if (verbose && includewal)
1790 fprintf(stderr, "transaction log end point: %s\n", xlogend);
1793 res = PQgetResult(conn);
1794 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1796 fprintf(stderr, _("%s: final receive failed: %s"),
1797 progname, PQerrorMessage(conn));
1798 disconnect_and_exit(1);
1814 _("%s: waiting for background process to finish streaming ...\n"), progname);
1817 if (write(bgpipe[1], xlogend, strlen(xlogend)) != strlen(xlogend))
1820 _("%s: could not send command to background pipe: %s\n"),
1821 progname, strerror(errno));
1822 disconnect_and_exit(1);
1825 /* Just wait for the background process to exit */
1826 r = waitpid(bgchild, &status, 0);
1829 fprintf(stderr, _("%s: could not wait for child process: %s\n"),
1830 progname, strerror(errno));
1831 disconnect_and_exit(1);
1835 fprintf(stderr, _("%s: child %d died, expected %d\n"),
1836 progname, r, (int) bgchild);
1837 disconnect_and_exit(1);
1839 if (!WIFEXITED(status))
1841 fprintf(stderr, _("%s: child process did not exit normally\n"),
1843 disconnect_and_exit(1);
1845 if (WEXITSTATUS(status) != 0)
1847 fprintf(stderr, _("%s: child process exited with error %d\n"),
1848 progname, WEXITSTATUS(status));
1849 disconnect_and_exit(1);
1851 /* Exited normally, we're happy! */
1855 * On Windows, since we are in the same process, we can just store the
1856 * value directly in the variable, and then set the flag that says
1859 if (sscanf(xlogend, "%X/%X", &hi, &lo) != 2)
1862 _("%s: could not parse transaction log location \"%s\"\n"),
1864 disconnect_and_exit(1);
1866 xlogendptr = ((uint64) hi) << 32 | lo;
1867 InterlockedIncrement(&has_xlogendptr);
1869 /* First wait for the thread to exit */
1870 if (WaitForSingleObjectEx((HANDLE) bgchild, INFINITE, FALSE) !=
1873 _dosmaperr(GetLastError());
1874 fprintf(stderr, _("%s: could not wait for child thread: %s\n"),
1875 progname, strerror(errno));
1876 disconnect_and_exit(1);
1878 if (GetExitCodeThread((HANDLE) bgchild, &status) == 0)
1880 _dosmaperr(GetLastError());
1881 fprintf(stderr, _("%s: could not get child thread exit status: %s\n"),
1882 progname, strerror(errno));
1883 disconnect_and_exit(1);
1887 fprintf(stderr, _("%s: child thread exited with error %u\n"),
1888 progname, (unsigned int) status);
1889 disconnect_and_exit(1);
1891 /* Exited normally, we're happy */
1895 /* Free the recovery.conf contents */
1896 destroyPQExpBuffer(recoveryconfcontents);
1899 * End of copy data. Final result is already checked inside the loop.
1905 fprintf(stderr, "%s: base backup completed\n", progname);
1910 main(int argc, char **argv)
1912 static struct option long_options[] = {
1913 {"help", no_argument, NULL, '?'},
1914 {"version", no_argument, NULL, 'V'},
1915 {"pgdata", required_argument, NULL, 'D'},
1916 {"format", required_argument, NULL, 'F'},
1917 {"checkpoint", required_argument, NULL, 'c'},
1918 {"max-rate", required_argument, NULL, 'r'},
1919 {"write-recovery-conf", no_argument, NULL, 'R'},
1920 {"tablespace-mapping", required_argument, NULL, 'T'},
1921 {"xlog", no_argument, NULL, 'x'},
1922 {"xlog-method", required_argument, NULL, 'X'},
1923 {"gzip", no_argument, NULL, 'z'},
1924 {"compress", required_argument, NULL, 'Z'},
1925 {"label", required_argument, NULL, 'l'},
1926 {"dbname", required_argument, NULL, 'd'},
1927 {"host", required_argument, NULL, 'h'},
1928 {"port", required_argument, NULL, 'p'},
1929 {"username", required_argument, NULL, 'U'},
1930 {"no-password", no_argument, NULL, 'w'},
1931 {"password", no_argument, NULL, 'W'},
1932 {"status-interval", required_argument, NULL, 's'},
1933 {"verbose", no_argument, NULL, 'v'},
1934 {"progress", no_argument, NULL, 'P'},
1935 {"xlogdir", required_argument, NULL, 1},
1942 progname = get_progname(argv[0]);
1943 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_basebackup"));
1947 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
1952 else if (strcmp(argv[1], "-V") == 0
1953 || strcmp(argv[1], "--version") == 0)
1955 puts("pg_basebackup (PostgreSQL) " PG_VERSION);
1960 while ((c = getopt_long(argc, argv, "D:F:r:RT:xX:l:zZ:d:c:h:p:U:s:wWvP",
1961 long_options, &option_index)) != -1)
1966 basedir = pg_strdup(optarg);
1969 if (strcmp(optarg, "p") == 0 || strcmp(optarg, "plain") == 0)
1971 else if (strcmp(optarg, "t") == 0 || strcmp(optarg, "tar") == 0)
1976 _("%s: invalid output format \"%s\", must be \"plain\" or \"tar\"\n"),
1982 maxrate = parse_max_rate(optarg);
1985 writerecoveryconf = true;
1988 tablespace_list_append(optarg);
1994 _("%s: cannot specify both --xlog and --xlog-method\n"),
2006 _("%s: cannot specify both --xlog and --xlog-method\n"),
2012 if (strcmp(optarg, "f") == 0 ||
2013 strcmp(optarg, "fetch") == 0)
2015 else if (strcmp(optarg, "s") == 0 ||
2016 strcmp(optarg, "stream") == 0)
2021 _("%s: invalid xlog-method option \"%s\", must be \"fetch\" or \"stream\"\n"),
2027 xlog_dir = pg_strdup(optarg);
2030 label = pg_strdup(optarg);
2034 compresslevel = Z_DEFAULT_COMPRESSION;
2036 compresslevel = 1; /* will be rejected below */
2040 compresslevel = atoi(optarg);
2041 if (compresslevel <= 0 || compresslevel > 9)
2043 fprintf(stderr, _("%s: invalid compression level \"%s\"\n"),
2049 if (pg_strcasecmp(optarg, "fast") == 0)
2050 fastcheckpoint = true;
2051 else if (pg_strcasecmp(optarg, "spread") == 0)
2052 fastcheckpoint = false;
2055 fprintf(stderr, _("%s: invalid checkpoint argument \"%s\", must be \"fast\" or \"spread\"\n"),
2061 connection_string = pg_strdup(optarg);
2064 dbhost = pg_strdup(optarg);
2067 dbport = pg_strdup(optarg);
2070 dbuser = pg_strdup(optarg);
2079 standby_message_timeout = atoi(optarg) * 1000;
2080 if (standby_message_timeout < 0)
2082 fprintf(stderr, _("%s: invalid status interval \"%s\"\n"),
2091 showprogress = true;
2096 * getopt_long already emitted a complaint
2098 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2105 * Any non-option arguments?
2110 _("%s: too many command-line arguments (first is \"%s\")\n"),
2111 progname, argv[optind]);
2112 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2118 * Required arguments
2120 if (basedir == NULL)
2122 fprintf(stderr, _("%s: no target directory specified\n"), progname);
2123 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2129 * Mutually exclusive arguments
2131 if (format == 'p' && compresslevel != 0)
2134 _("%s: only tar mode backups can be compressed\n"),
2136 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2141 if (format != 'p' && streamwal)
2144 _("%s: WAL streaming can only be used in plain mode\n"),
2146 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2151 if (strcmp(xlog_dir, "") != 0)
2156 _("%s: transaction log directory location can only be specified in plain mode\n"),
2158 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2163 /* clean up xlog directory name, check it's absolute */
2164 canonicalize_path(xlog_dir);
2165 if (!is_absolute_path(xlog_dir))
2167 fprintf(stderr, _("%s: transaction log directory location must be "
2168 "an absolute path\n"), progname);
2169 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
2176 if (compresslevel != 0)
2179 _("%s: this build does not support compression\n"),
2186 * Verify that the target directory exists, or create it. For plaintext
2187 * backups, always require the directory. For tar backups, require it
2188 * unless we are writing to stdout.
2190 if (format == 'p' || strcmp(basedir, "-") != 0)
2191 verify_dir_is_empty_or_create(basedir);
2193 /* Create transaction log symlink, if required */
2194 if (strcmp(xlog_dir, "") != 0)
2198 verify_dir_is_empty_or_create(xlog_dir);
2200 /* form name of the place where the symlink must go */
2201 linkloc = psprintf("%s/pg_xlog", basedir);
2204 if (symlink(xlog_dir, linkloc) != 0)
2206 fprintf(stderr, _("%s: could not create symbolic link \"%s\": %s\n"),
2207 progname, linkloc, strerror(errno));
2211 fprintf(stderr, _("%s: symlinks are not supported on this platform\n"));