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-2013, PostgreSQL Global Development Group
10 * src/bin/pg_basebackup/pg_basebackup.c
11 *-------------------------------------------------------------------------
14 #include "postgres_fe.h"
16 #include "pqexpbuffer.h"
22 #include <sys/types.h>
30 #include "getopt_long.h"
32 #include "receivelog.h"
33 #include "streamutil.h"
38 char format = 'p'; /* p(lain)/t(ar) */
39 char *label = "pg_basebackup base backup";
40 bool showprogress = false;
42 int compresslevel = 0;
43 bool includewal = false;
44 bool streamwal = false;
45 bool fastcheckpoint = false;
46 bool writerecoveryconf = false;
47 int standby_message_timeout = 10 * 1000; /* 10 sec = default */
49 /* Progress counters */
50 static uint64 totalsize;
51 static uint64 totaldone;
52 static int tablespacecount;
54 /* Pipe to communicate with background wal receiver process */
56 static int bgpipe[2] = {-1, -1};
59 /* Handle to child process */
60 static pid_t bgchild = -1;
62 /* End position for xlog streaming, empty string if unknown yet */
63 static XLogRecPtr xlogendptr;
66 static int has_xlogendptr = 0;
68 static volatile LONG has_xlogendptr = 0;
71 /* Contents of recovery.conf to be generated */
72 static PQExpBuffer recoveryconfcontents = NULL;
74 /* Function headers */
75 static void usage(void);
76 static void verify_dir_is_empty_or_create(char *dirname);
77 static void progress_report(int tablespacenum, const char *filename);
79 static void ReceiveTarFile(PGconn *conn, PGresult *res, int rownum);
80 static void ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res, int rownum);
81 static void GenerateRecoveryConf(PGconn *conn);
82 static void WriteRecoveryConf(void);
83 static void BaseBackup(void);
85 static bool reached_end_position(XLogRecPtr segendpos, uint32 timeline,
86 bool segment_finished);
90 get_gz_error(gzFile gzf)
95 errmsg = gzerror(gzf, &errnum);
96 if (errnum == Z_ERRNO)
97 return strerror(errno);
106 printf(_("%s takes a base backup of a running PostgreSQL server.\n\n"),
108 printf(_("Usage:\n"));
109 printf(_(" %s [OPTION]...\n"), progname);
110 printf(_("\nOptions controlling the output:\n"));
111 printf(_(" -D, --pgdata=DIRECTORY receive base backup into directory\n"));
112 printf(_(" -F, --format=p|t output format (plain (default), tar)\n"));
113 printf(_(" -R, --write-recovery-conf\n"
114 " write recovery.conf after backup\n"));
115 printf(_(" -x, --xlog include required WAL files in backup (fetch mode)\n"));
116 printf(_(" -X, --xlog-method=fetch|stream\n"
117 " include required WAL files with specified method\n"));
118 printf(_(" -z, --gzip compress tar output\n"));
119 printf(_(" -Z, --compress=0-9 compress tar output with given compression level\n"));
120 printf(_("\nGeneral options:\n"));
121 printf(_(" -c, --checkpoint=fast|spread\n"
122 " set fast or spread checkpointing\n"));
123 printf(_(" -l, --label=LABEL set backup label\n"));
124 printf(_(" -P, --progress show progress information\n"));
125 printf(_(" -v, --verbose output verbose messages\n"));
126 printf(_(" -V, --version output version information, then exit\n"));
127 printf(_(" -?, --help show this help, then exit\n"));
128 printf(_("\nConnection options:\n"));
129 printf(_(" -d, --dbname=CONNSTR connection string\n"));
130 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
131 printf(_(" -p, --port=PORT database server port number\n"));
132 printf(_(" -s, --status-interval=INTERVAL\n"
133 " time between status packets sent to server (in seconds)\n"));
134 printf(_(" -U, --username=NAME connect as specified database user\n"));
135 printf(_(" -w, --no-password never prompt for password\n"));
136 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
137 printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
142 * Called in the background process every time data is received.
143 * On Unix, we check to see if there is any data on our pipe
144 * (which would mean we have a stop position), and if it is, check if
145 * it is time to stop.
146 * On Windows, we are in a single process, so we can just check if it's
150 reached_end_position(XLogRecPtr segendpos, uint32 timeline,
151 bool segment_finished)
161 * Don't have the end pointer yet - check our pipe to see if it has
165 FD_SET(bgpipe[0], &fds);
167 MemSet(&tv, 0, sizeof(tv));
169 r = select(bgpipe[0] + 1, &fds, NULL, NULL, &tv);
176 MemSet(xlogend, 0, sizeof(xlogend));
177 r = read(bgpipe[0], xlogend, sizeof(xlogend)-1);
180 fprintf(stderr, _("%s: could not read from ready pipe: %s\n"),
181 progname, strerror(errno));
185 if (sscanf(xlogend, "%X/%X", &hi, &lo) != 2)
188 _("%s: could not parse transaction log location \"%s\"\n"),
192 xlogendptr = ((uint64) hi) << 32 | lo;
196 * Fall through to check if we've reached the point further
203 * No data received on the pipe means we don't know the end
204 * position yet - so just say it's not time to stop yet.
211 * On win32, has_xlogendptr is set by the main thread, so if it's not
212 * set here, we just go back and wait until it shows up.
219 * At this point we have an end pointer, so compare it to the current
220 * position to figure out if it's time to stop.
222 if (segendpos >= xlogendptr)
226 * Have end pointer, but haven't reached it yet - so tell the caller to
236 char xlogdir[MAXPGPATH];
242 LogStreamerMain(logstreamer_param *param)
244 if (!ReceiveXlogStream(param->bgconn, param->startptr, param->timeline,
245 param->sysidentifier, param->xlogdir,
246 reached_end_position, standby_message_timeout,
250 * Any errors will already have been reported in the function process,
251 * but we need to tell the parent that we didn't shutdown in a nice
256 PQfinish(param->bgconn);
261 * Initiate background process for receiving xlog during the backup.
262 * The background stream will use its own database connection so we can
263 * stream the logfile in parallel with the backups.
266 StartLogStreamer(char *startpos, uint32 timeline, char *sysidentifier)
268 logstreamer_param *param;
272 param = pg_malloc0(sizeof(logstreamer_param));
273 param->timeline = timeline;
274 param->sysidentifier = sysidentifier;
276 /* Convert the starting position */
277 if (sscanf(startpos, "%X/%X", &hi, &lo) != 2)
280 _("%s: could not parse transaction log location \"%s\"\n"),
282 disconnect_and_exit(1);
284 param->startptr = ((uint64) hi) << 32 | lo;
285 /* Round off to even segment position */
286 param->startptr -= param->startptr % XLOG_SEG_SIZE;
289 /* Create our background pipe */
290 if (pipe(bgpipe) < 0)
293 _("%s: could not create pipe for background process: %s\n"),
294 progname, strerror(errno));
295 disconnect_and_exit(1);
299 /* Get a second connection */
300 param->bgconn = GetConnection();
302 /* Error message already written in GetConnection() */
306 * Always in plain format, so we can write to basedir/pg_xlog. But the
307 * directory entry in the tar file may arrive later, so make sure it's
308 * created before we start.
310 snprintf(param->xlogdir, sizeof(param->xlogdir), "%s/pg_xlog", basedir);
311 verify_dir_is_empty_or_create(param->xlogdir);
314 * Start a child process and tell it to start streaming. On Unix, this is
315 * a fork(). On Windows, we create a thread.
321 /* in child process */
322 exit(LogStreamerMain(param));
324 else if (bgchild < 0)
326 fprintf(stderr, _("%s: could not create background process: %s\n"),
327 progname, strerror(errno));
328 disconnect_and_exit(1);
332 * Else we are in the parent process and all is well.
335 bgchild = _beginthreadex(NULL, 0, (void *) LogStreamerMain, param, 0, NULL);
338 fprintf(stderr, _("%s: could not create background thread: %s\n"),
339 progname, strerror(errno));
340 disconnect_and_exit(1);
346 * Verify that the given directory exists and is empty. If it does not
347 * exist, it is created. If it exists but is not empty, an error will
348 * be give and the process ended.
351 verify_dir_is_empty_or_create(char *dirname)
353 switch (pg_check_dir(dirname))
358 * Does not exist, so create
360 if (pg_mkdir_p(dirname, S_IRWXU) == -1)
363 _("%s: could not create directory \"%s\": %s\n"),
364 progname, dirname, strerror(errno));
365 disconnect_and_exit(1);
382 _("%s: directory \"%s\" exists but is not empty\n"),
384 disconnect_and_exit(1);
390 fprintf(stderr, _("%s: could not access directory \"%s\": %s\n"),
391 progname, dirname, strerror(errno));
392 disconnect_and_exit(1);
398 * Print a progress report based on the global variables. If verbose output
399 * is enabled, also print the current file name.
402 progress_report(int tablespacenum, const char *filename)
404 int percent = (int) ((totaldone / 1024) * 100 / totalsize);
405 char totaldone_str[32];
406 char totalsize_str[32];
409 * Avoid overflowing past 100% or the full size. This may make the total
410 * size number change as we approach the end of the backup (the estimate
411 * will always be wrong if WAL is included), but that's better than having
412 * the done column be bigger than the total.
416 if (totaldone / 1024 > totalsize)
417 totalsize = totaldone / 1024;
420 * Separate step to keep platform-dependent format code out of
421 * translatable strings. And we only test for INT64_FORMAT availability
422 * in snprintf, not fprintf.
424 snprintf(totaldone_str, sizeof(totaldone_str), INT64_FORMAT,
426 snprintf(totalsize_str, sizeof(totalsize_str), INT64_FORMAT, totalsize);
428 #define VERBOSE_FILENAME_LENGTH 35
434 * No filename given, so clear the status line (used for last
438 ngettext("%*s/%s kB (100%%), %d/%d tablespace %*s",
439 "%*s/%s kB (100%%), %d/%d tablespaces %*s",
441 (int) strlen(totalsize_str),
442 totaldone_str, totalsize_str,
443 tablespacenum, tablespacecount,
444 VERBOSE_FILENAME_LENGTH + 5, "");
447 bool truncate = (strlen(filename) > VERBOSE_FILENAME_LENGTH);
450 ngettext("%*s/%s kB (%d%%), %d/%d tablespace (%s%-*.*s)",
451 "%*s/%s kB (%d%%), %d/%d tablespaces (%s%-*.*s)",
453 (int) strlen(totalsize_str),
454 totaldone_str, totalsize_str, percent,
455 tablespacenum, tablespacecount,
456 /* Prefix with "..." if we do leading truncation */
457 truncate ? "..." : "",
458 truncate ? VERBOSE_FILENAME_LENGTH - 3 : VERBOSE_FILENAME_LENGTH,
459 truncate ? VERBOSE_FILENAME_LENGTH - 3 : VERBOSE_FILENAME_LENGTH,
460 /* Truncate filename at beginning if it's too long */
461 truncate ? filename + strlen(filename) - VERBOSE_FILENAME_LENGTH + 3 : filename);
466 ngettext("%*s/%s kB (%d%%), %d/%d tablespace",
467 "%*s/%s kB (%d%%), %d/%d tablespaces",
469 (int) strlen(totalsize_str),
470 totaldone_str, totalsize_str, percent,
471 tablespacenum, tablespacecount);
473 fprintf(stderr, "\r");
478 * Write a piece of tar data
485 FILE *tarfile, char *buf, int r, char *current_file)
488 if (ztarfile != NULL)
490 if (gzwrite(ztarfile, buf, r) != r)
493 _("%s: could not write to compressed file \"%s\": %s\n"),
494 progname, current_file, get_gz_error(ztarfile));
495 disconnect_and_exit(1);
501 if (fwrite(buf, r, 1, tarfile) != 1)
503 fprintf(stderr, _("%s: could not write to file \"%s\": %s\n"),
504 progname, current_file, strerror(errno));
505 disconnect_and_exit(1);
511 #define WRITE_TAR_DATA(buf, sz) writeTarData(ztarfile, tarfile, buf, sz, filename)
513 #define WRITE_TAR_DATA(buf, sz) writeTarData(tarfile, buf, sz, filename)
517 * Receive a tar format file from the connection to the server, and write
518 * the data from this file directly into a tar file. If compression is
519 * enabled, the data will be compressed while written to the file.
521 * The file will be named base.tar[.gz] if it's for the main data directory
522 * or <tablespaceoid>.tar[.gz] if it's for another tablespace.
524 * No attempt to inspect or validate the contents of the file is done.
527 ReceiveTarFile(PGconn *conn, PGresult *res, int rownum)
529 char filename[MAXPGPATH];
530 char *copybuf = NULL;
531 FILE *tarfile = NULL;
533 bool basetablespace = PQgetisnull(res, rownum, 0);
534 bool in_tarhdr = true;
535 bool skip_file = false;
540 gzFile ztarfile = NULL;
548 if (strcmp(basedir, "-") == 0)
551 if (compresslevel != 0)
553 ztarfile = gzdopen(dup(fileno(stdout)), "wb");
554 if (gzsetparams(ztarfile, compresslevel,
555 Z_DEFAULT_STRATEGY) != Z_OK)
558 _("%s: could not set compression level %d: %s\n"),
559 progname, compresslevel, get_gz_error(ztarfile));
560 disconnect_and_exit(1);
570 if (compresslevel != 0)
572 snprintf(filename, sizeof(filename), "%s/base.tar.gz", basedir);
573 ztarfile = gzopen(filename, "wb");
574 if (gzsetparams(ztarfile, compresslevel,
575 Z_DEFAULT_STRATEGY) != Z_OK)
578 _("%s: could not set compression level %d: %s\n"),
579 progname, compresslevel, get_gz_error(ztarfile));
580 disconnect_and_exit(1);
586 snprintf(filename, sizeof(filename), "%s/base.tar", basedir);
587 tarfile = fopen(filename, "wb");
594 * Specific tablespace
597 if (compresslevel != 0)
599 snprintf(filename, sizeof(filename), "%s/%s.tar.gz", basedir,
600 PQgetvalue(res, rownum, 0));
601 ztarfile = gzopen(filename, "wb");
602 if (gzsetparams(ztarfile, compresslevel,
603 Z_DEFAULT_STRATEGY) != Z_OK)
606 _("%s: could not set compression level %d: %s\n"),
607 progname, compresslevel, get_gz_error(ztarfile));
608 disconnect_and_exit(1);
614 snprintf(filename, sizeof(filename), "%s/%s.tar", basedir,
615 PQgetvalue(res, rownum, 0));
616 tarfile = fopen(filename, "wb");
621 if (compresslevel != 0)
625 /* Compression is in use */
627 _("%s: could not create compressed file \"%s\": %s\n"),
628 progname, filename, get_gz_error(ztarfile));
629 disconnect_and_exit(1);
635 /* Either no zlib support, or zlib support but compresslevel = 0 */
638 fprintf(stderr, _("%s: could not create file \"%s\": %s\n"),
639 progname, filename, strerror(errno));
640 disconnect_and_exit(1);
645 * Get the COPY data stream
647 res = PQgetResult(conn);
648 if (PQresultStatus(res) != PGRES_COPY_OUT)
650 fprintf(stderr, _("%s: could not get COPY data stream: %s"),
651 progname, PQerrorMessage(conn));
652 disconnect_and_exit(1);
665 r = PQgetCopyData(conn, ©buf, 0);
669 * End of chunk. If requested, and this is the base tablespace,
670 * write recovery.conf into the tarfile. When done, close the file
673 * Also, write two completely empty blocks at the end of the tar
674 * file, as required by some tar programs.
678 MemSet(zerobuf, 0, sizeof(zerobuf));
680 if (basetablespace && writerecoveryconf)
685 tarCreateHeader(header, "recovery.conf", NULL,
686 recoveryconfcontents->len,
690 padding = ((recoveryconfcontents->len + 511) & ~511) - recoveryconfcontents->len;
692 WRITE_TAR_DATA(header, sizeof(header));
693 WRITE_TAR_DATA(recoveryconfcontents->data, recoveryconfcontents->len);
695 WRITE_TAR_DATA(zerobuf, padding);
698 /* 2 * 512 bytes empty data at end of file */
699 WRITE_TAR_DATA(zerobuf, sizeof(zerobuf));
702 if (ztarfile != NULL)
704 if (gzclose(ztarfile) != 0)
707 _("%s: could not close compressed file \"%s\": %s\n"),
708 progname, filename, get_gz_error(ztarfile));
709 disconnect_and_exit(1);
715 if (strcmp(basedir, "-") != 0)
717 if (fclose(tarfile) != 0)
720 _("%s: could not close file \"%s\": %s\n"),
721 progname, filename, strerror(errno));
722 disconnect_and_exit(1);
731 fprintf(stderr, _("%s: could not read COPY data: %s"),
732 progname, PQerrorMessage(conn));
733 disconnect_and_exit(1);
736 if (!writerecoveryconf || !basetablespace)
739 * When not writing recovery.conf, or when not working on the base
740 * tablespace, we never have to look for an existing recovery.conf
741 * file in the stream.
743 WRITE_TAR_DATA(copybuf, r);
748 * Look for a recovery.conf in the existing tar stream. If it's
749 * there, we must skip it so we can later overwrite it with our
750 * own version of the file.
752 * To do this, we have to process the individual files inside the
753 * TAR stream. The stream consists of a header and zero or more
754 * chunks, all 512 bytes long. The stream from the server is
755 * broken up into smaller pieces, so we have to track the size of
756 * the files to find the next header structure.
766 * We're currently reading a header structure inside the
767 * TAR stream, i.e. the file metadata.
772 * Copy the header structure into tarhdr in case the
773 * header is not aligned to 512 bytes or it's not
774 * returned in whole by the last PQgetCopyData call.
779 hdrleft = 512 - tarhdrsz;
780 bytes2copy = (rr > hdrleft ? hdrleft : rr);
782 memcpy(&tarhdr[tarhdrsz], copybuf + pos, bytes2copy);
786 tarhdrsz += bytes2copy;
791 * We have the complete header structure in tarhdr,
792 * look at the file metadata: - the subsequent file
793 * contents have to be skipped if the filename is
794 * recovery.conf - find out the size of the file
795 * padded to the next multiple of 512
799 skip_file = (strcmp(&tarhdr[0], "recovery.conf") == 0);
801 sscanf(&tarhdr[124], "%11o", (unsigned int *) &filesz);
803 padding = ((filesz + 511) & ~511) - filesz;
806 /* Next part is the file, not the header */
810 * If we're not skipping the file, write the tar
814 WRITE_TAR_DATA(tarhdr, 512);
820 * We're processing a file's contents.
825 * We still have data to read (and possibly write).
829 bytes2write = (filesz > rr ? rr : filesz);
832 WRITE_TAR_DATA(copybuf + pos, bytes2write);
836 filesz -= bytes2write;
841 * No more data in the current file, the next piece of
842 * data (if any) will be a new file header structure.
854 progress_report(rownum, filename);
862 * Receive a tar format stream from the connection to the server, and unpack
863 * the contents of it into a directory. Only files, directories and
864 * symlinks are supported, no other kinds of special files.
866 * If the data is for the main data directory, it will be restored in the
867 * specified directory. If it's for another tablespace, it will be restored
868 * in the original directory, since relocation of tablespaces is not
872 ReceiveAndUnpackTarFile(PGconn *conn, PGresult *res, int rownum)
874 char current_path[MAXPGPATH];
875 char filename[MAXPGPATH];
876 int current_len_left;
877 int current_padding = 0;
878 bool basetablespace = PQgetisnull(res, rownum, 0);
879 char *copybuf = NULL;
883 strcpy(current_path, basedir);
885 strcpy(current_path, PQgetvalue(res, rownum, 1));
890 res = PQgetResult(conn);
891 if (PQresultStatus(res) != PGRES_COPY_OUT)
893 fprintf(stderr, _("%s: could not get COPY data stream: %s"),
894 progname, PQerrorMessage(conn));
895 disconnect_and_exit(1);
908 r = PQgetCopyData(conn, ©buf, 0);
922 fprintf(stderr, _("%s: could not read COPY data: %s"),
923 progname, PQerrorMessage(conn));
924 disconnect_and_exit(1);
932 * No current file, so this must be the header for a new file
936 fprintf(stderr, _("%s: invalid tar block header size: %d\n"),
938 disconnect_and_exit(1);
942 if (sscanf(copybuf + 124, "%11o", ¤t_len_left) != 1)
944 fprintf(stderr, _("%s: could not parse file size\n"),
946 disconnect_and_exit(1);
949 /* Set permissions on the file */
950 if (sscanf(©buf[100], "%07o ", &filemode) != 1)
952 fprintf(stderr, _("%s: could not parse file mode\n"),
954 disconnect_and_exit(1);
958 * All files are padded up to 512 bytes
961 ((current_len_left + 511) & ~511) - current_len_left;
964 * First part of header is zero terminated filename
966 snprintf(filename, sizeof(filename), "%s/%s", current_path,
968 if (filename[strlen(filename) - 1] == '/')
971 * Ends in a slash means directory or symlink to directory
973 if (copybuf[156] == '5')
978 filename[strlen(filename) - 1] = '\0'; /* Remove trailing slash */
979 if (mkdir(filename, S_IRWXU) != 0)
982 * When streaming WAL, pg_xlog will have been created
983 * by the wal receiver process, so just ignore failure
986 if (!streamwal || strcmp(filename + strlen(filename) - 8, "/pg_xlog") != 0)
989 _("%s: could not create directory \"%s\": %s\n"),
990 progname, filename, strerror(errno));
991 disconnect_and_exit(1);
995 if (chmod(filename, (mode_t) filemode))
997 _("%s: could not set permissions on directory \"%s\": %s\n"),
998 progname, filename, strerror(errno));
1001 else if (copybuf[156] == '2')
1006 filename[strlen(filename) - 1] = '\0'; /* Remove trailing slash */
1007 if (symlink(©buf[157], filename) != 0)
1010 _("%s: could not create symbolic link from \"%s\" to \"%s\": %s\n"),
1011 progname, filename, ©buf[157], strerror(errno));
1012 disconnect_and_exit(1);
1018 _("%s: unrecognized link indicator \"%c\"\n"),
1019 progname, copybuf[156]);
1020 disconnect_and_exit(1);
1022 continue; /* directory or link handled */
1028 file = fopen(filename, "wb");
1031 fprintf(stderr, _("%s: could not create file \"%s\": %s\n"),
1032 progname, filename, strerror(errno));
1033 disconnect_and_exit(1);
1037 if (chmod(filename, (mode_t) filemode))
1038 fprintf(stderr, _("%s: could not set permissions on file \"%s\": %s\n"),
1039 progname, filename, strerror(errno));
1042 if (current_len_left == 0)
1045 * Done with this file, next one will be a new tar header
1055 * Continuing blocks in existing file
1057 if (current_len_left == 0 && r == current_padding)
1060 * Received the padding block for this file, ignore it and
1061 * close the file, then move on to the next tar header.
1069 if (fwrite(copybuf, r, 1, file) != 1)
1071 fprintf(stderr, _("%s: could not write to file \"%s\": %s\n"),
1072 progname, filename, strerror(errno));
1073 disconnect_and_exit(1);
1077 progress_report(rownum, filename);
1079 current_len_left -= r;
1080 if (current_len_left == 0 && current_padding == 0)
1083 * Received the last block, and there is no padding to be
1084 * expected. Close the file and move on to the next tar
1091 } /* continuing data in existing file */
1092 } /* loop over all data blocks */
1097 _("%s: COPY stream ended before last file was finished\n"),
1099 disconnect_and_exit(1);
1102 if (copybuf != NULL)
1105 if (basetablespace && writerecoveryconf)
1106 WriteRecoveryConf();
1110 * Escape a parameter value so that it can be used as part of a libpq
1111 * connection string, e.g. in:
1113 * application_name=<value>
1115 * The returned string is malloc'd. Return NULL on out-of-memory.
1118 escapeConnectionParameter(const char *src)
1120 bool need_quotes = false;
1121 bool need_escaping = false;
1127 * First check if quoting is needed. Any quote (') or backslash (\)
1128 * characters need to be escaped. Parameters are separated by whitespace,
1129 * so any string containing whitespace characters need to be quoted. An
1130 * empty string is represented by ''.
1132 if (strchr(src, '\'') != NULL || strchr(src, '\\') != NULL)
1133 need_escaping = true;
1135 for (p = src; *p; p++)
1137 if (isspace((unsigned char) *p))
1145 return pg_strdup("''");
1147 if (!need_quotes && !need_escaping)
1148 return pg_strdup(src); /* no quoting or escaping needed */
1151 * Allocate a buffer large enough for the worst case that all the source
1152 * characters need to be escaped, plus quotes.
1154 dstbuf = pg_malloc(strlen(src) * 2 + 2 + 1);
1161 if (*src == '\'' || *src == '\\')
1173 * Escape a string so that it can be used as a value in a key-value pair
1174 * a configuration file.
1177 escape_quotes(const char *src)
1179 char *result = escape_single_quotes_ascii(src);
1183 fprintf(stderr, _("%s: out of memory\n"), progname);
1190 * Create a recovery.conf file in memory using a PQExpBuffer
1193 GenerateRecoveryConf(PGconn *conn)
1195 PQconninfoOption *connOptions;
1196 PQconninfoOption *option;
1197 PQExpBufferData conninfo_buf;
1200 recoveryconfcontents = createPQExpBuffer();
1201 if (!recoveryconfcontents)
1203 fprintf(stderr, _("%s: out of memory\n"), progname);
1204 disconnect_and_exit(1);
1207 connOptions = PQconninfo(conn);
1208 if (connOptions == NULL)
1210 fprintf(stderr, _("%s: out of memory\n"), progname);
1211 disconnect_and_exit(1);
1214 appendPQExpBufferStr(recoveryconfcontents, "standby_mode = 'on'\n");
1216 initPQExpBuffer(&conninfo_buf);
1217 for (option = connOptions; option && option->keyword; option++)
1220 * Do not emit this setting if: - the setting is "replication",
1221 * "dbname" or "fallback_application_name", since these would be
1222 * overridden by the libpqwalreceiver module anyway. - not set or
1225 if (strcmp(option->keyword, "replication") == 0 ||
1226 strcmp(option->keyword, "dbname") == 0 ||
1227 strcmp(option->keyword, "fallback_application_name") == 0 ||
1228 (option->val == NULL) ||
1229 (option->val != NULL && option->val[0] == '\0'))
1232 /* Separate key-value pairs with spaces */
1233 if (conninfo_buf.len != 0)
1234 appendPQExpBufferStr(&conninfo_buf, " ");
1237 * Write "keyword=value" pieces, the value string is escaped and/or
1238 * quoted if necessary.
1240 escaped = escapeConnectionParameter(option->val);
1241 appendPQExpBuffer(&conninfo_buf, "%s=%s", option->keyword, escaped);
1246 * Escape the connection string, so that it can be put in the config file.
1247 * Note that this is different from the escaping of individual connection
1250 escaped = escape_quotes(conninfo_buf.data);
1251 appendPQExpBuffer(recoveryconfcontents, "primary_conninfo = '%s'\n", escaped);
1254 if (PQExpBufferBroken(recoveryconfcontents) ||
1255 PQExpBufferDataBroken(conninfo_buf))
1257 fprintf(stderr, _("%s: out of memory\n"), progname);
1258 disconnect_and_exit(1);
1261 termPQExpBuffer(&conninfo_buf);
1263 PQconninfoFree(connOptions);
1268 * Write a recovery.conf file into the directory specified in basedir,
1269 * with the contents already collected in memory.
1272 WriteRecoveryConf(void)
1274 char filename[MAXPGPATH];
1277 sprintf(filename, "%s/recovery.conf", basedir);
1279 cf = fopen(filename, "w");
1282 fprintf(stderr, _("%s: could not create file \"%s\": %s\n"), progname, filename, strerror(errno));
1283 disconnect_and_exit(1);
1286 if (fwrite(recoveryconfcontents->data, recoveryconfcontents->len, 1, cf) != 1)
1289 _("%s: could not write to file \"%s\": %s\n"),
1290 progname, filename, strerror(errno));
1291 disconnect_and_exit(1);
1302 char *sysidentifier;
1305 char current_path[MAXPGPATH];
1306 char escaped_label[MAXPGPATH];
1315 * Connect in replication mode to the server
1317 conn = GetConnection();
1319 /* Error message already written in GetConnection() */
1323 * Check server version. BASE_BACKUP command was introduced in 9.1, so we
1324 * can't work with servers older than 9.1.
1326 minServerMajor = 901;
1327 maxServerMajor = PG_VERSION_NUM / 100;
1328 serverMajor = PQserverVersion(conn) / 100;
1329 if (serverMajor < minServerMajor || serverMajor > maxServerMajor)
1331 const char *serverver = PQparameterStatus(conn, "server_version");
1333 fprintf(stderr, _("%s: incompatible server version %s\n"),
1334 progname, serverver ? serverver : "'unknown'");
1335 disconnect_and_exit(1);
1339 * If WAL streaming was requested, also check that the server is new
1342 if (streamwal && !CheckServerVersionForStreaming(conn))
1344 /* Error message already written in CheckServerVersionForStreaming() */
1345 disconnect_and_exit(1);
1349 * Build contents of recovery.conf if requested
1351 if (writerecoveryconf)
1352 GenerateRecoveryConf(conn);
1355 * Run IDENTIFY_SYSTEM so we can get the timeline
1357 res = PQexec(conn, "IDENTIFY_SYSTEM");
1358 if (PQresultStatus(res) != PGRES_TUPLES_OK)
1360 fprintf(stderr, _("%s: could not send replication command \"%s\": %s"),
1361 progname, "IDENTIFY_SYSTEM", PQerrorMessage(conn));
1362 disconnect_and_exit(1);
1364 if (PQntuples(res) != 1 || PQnfields(res) != 3)
1367 _("%s: could not identify system: got %d rows and %d fields, expected %d rows and %d fields\n"),
1368 progname, PQntuples(res), PQnfields(res), 1, 3);
1369 disconnect_and_exit(1);
1371 sysidentifier = pg_strdup(PQgetvalue(res, 0, 0));
1372 latesttli = atoi(PQgetvalue(res, 0, 1));
1376 * Start the actual backup
1378 PQescapeStringConn(conn, escaped_label, label, sizeof(escaped_label), &i);
1379 snprintf(current_path, sizeof(current_path),
1380 "BASE_BACKUP LABEL '%s' %s %s %s %s",
1382 showprogress ? "PROGRESS" : "",
1383 includewal && !streamwal ? "WAL" : "",
1384 fastcheckpoint ? "FAST" : "",
1385 includewal ? "NOWAIT" : "");
1387 if (PQsendQuery(conn, current_path) == 0)
1389 fprintf(stderr, _("%s: could not send replication command \"%s\": %s"),
1390 progname, "BASE_BACKUP", PQerrorMessage(conn));
1391 disconnect_and_exit(1);
1395 * Get the starting xlog position
1397 res = PQgetResult(conn);
1398 if (PQresultStatus(res) != PGRES_TUPLES_OK)
1400 fprintf(stderr, _("%s: could not initiate base backup: %s"),
1401 progname, PQerrorMessage(conn));
1402 disconnect_and_exit(1);
1404 if (PQntuples(res) != 1)
1407 _("%s: server returned unexpected response to BASE_BACKUP command; got %d rows and %d fields, expected %d rows and %d fields\n"),
1408 progname, PQntuples(res), PQnfields(res), 1, 2);
1409 disconnect_and_exit(1);
1412 strcpy(xlogstart, PQgetvalue(res, 0, 0));
1415 * 9.3 and later sends the TLI of the starting point. With older servers,
1416 * assume it's the same as the latest timeline reported by
1419 if (PQnfields(res) >= 2)
1420 starttli = atoi(PQgetvalue(res, 0, 1));
1422 starttli = latesttli;
1424 MemSet(xlogend, 0, sizeof(xlogend));
1426 if (verbose && includewal)
1427 fprintf(stderr, _("transaction log start point: %s on timeline %u\n"),
1428 xlogstart, starttli);
1433 res = PQgetResult(conn);
1434 if (PQresultStatus(res) != PGRES_TUPLES_OK)
1436 fprintf(stderr, _("%s: could not get backup header: %s"),
1437 progname, PQerrorMessage(conn));
1438 disconnect_and_exit(1);
1440 if (PQntuples(res) < 1)
1442 fprintf(stderr, _("%s: no data returned from server\n"), progname);
1443 disconnect_and_exit(1);
1447 * Sum up the total size, for progress reporting
1449 totalsize = totaldone = 0;
1450 tablespacecount = PQntuples(res);
1451 for (i = 0; i < PQntuples(res); i++)
1454 totalsize += atol(PQgetvalue(res, i, 2));
1457 * Verify tablespace directories are empty. Don't bother with the
1458 * first once since it can be relocated, and it will be checked before
1459 * we do anything anyway.
1461 if (format == 'p' && !PQgetisnull(res, i, 1))
1462 verify_dir_is_empty_or_create(PQgetvalue(res, i, 1));
1466 * When writing to stdout, require a single tablespace
1468 if (format == 't' && strcmp(basedir, "-") == 0 && PQntuples(res) > 1)
1471 _("%s: can only write single tablespace to stdout, database has %d\n"),
1472 progname, PQntuples(res));
1473 disconnect_and_exit(1);
1477 * If we're streaming WAL, start the streaming session before we start
1478 * receiving the actual data chunks.
1483 fprintf(stderr, _("%s: starting background WAL receiver\n"),
1485 StartLogStreamer(xlogstart, starttli, sysidentifier);
1489 * Start receiving chunks
1491 for (i = 0; i < PQntuples(res); i++)
1494 ReceiveTarFile(conn, res, i);
1496 ReceiveAndUnpackTarFile(conn, res, i);
1497 } /* Loop over all tablespaces */
1501 progress_report(PQntuples(res), NULL);
1502 fprintf(stderr, "\n"); /* Need to move to next line */
1507 * Get the stop position
1509 res = PQgetResult(conn);
1510 if (PQresultStatus(res) != PGRES_TUPLES_OK)
1513 _("%s: could not get transaction log end position from server: %s"),
1514 progname, PQerrorMessage(conn));
1515 disconnect_and_exit(1);
1517 if (PQntuples(res) != 1)
1520 _("%s: no transaction log end position returned from server\n"),
1522 disconnect_and_exit(1);
1524 strcpy(xlogend, PQgetvalue(res, 0, 0));
1525 if (verbose && includewal)
1526 fprintf(stderr, "transaction log end point: %s\n", xlogend);
1529 res = PQgetResult(conn);
1530 if (PQresultStatus(res) != PGRES_COMMAND_OK)
1532 fprintf(stderr, _("%s: final receive failed: %s"),
1533 progname, PQerrorMessage(conn));
1534 disconnect_and_exit(1);
1550 _("%s: waiting for background process to finish streaming ...\n"), progname);
1553 if (write(bgpipe[1], xlogend, strlen(xlogend)) != strlen(xlogend))
1556 _("%s: could not send command to background pipe: %s\n"),
1557 progname, strerror(errno));
1558 disconnect_and_exit(1);
1561 /* Just wait for the background process to exit */
1562 r = waitpid(bgchild, &status, 0);
1565 fprintf(stderr, _("%s: could not wait for child process: %s\n"),
1566 progname, strerror(errno));
1567 disconnect_and_exit(1);
1571 fprintf(stderr, _("%s: child %d died, expected %d\n"),
1572 progname, r, (int) bgchild);
1573 disconnect_and_exit(1);
1575 if (!WIFEXITED(status))
1577 fprintf(stderr, _("%s: child process did not exit normally\n"),
1579 disconnect_and_exit(1);
1581 if (WEXITSTATUS(status) != 0)
1583 fprintf(stderr, _("%s: child process exited with error %d\n"),
1584 progname, WEXITSTATUS(status));
1585 disconnect_and_exit(1);
1587 /* Exited normally, we're happy! */
1591 * On Windows, since we are in the same process, we can just store the
1592 * value directly in the variable, and then set the flag that says
1595 if (sscanf(xlogend, "%X/%X", &hi, &lo) != 2)
1598 _("%s: could not parse transaction log location \"%s\"\n"),
1600 disconnect_and_exit(1);
1602 xlogendptr = ((uint64) hi) << 32 | lo;
1603 InterlockedIncrement(&has_xlogendptr);
1605 /* First wait for the thread to exit */
1606 if (WaitForSingleObjectEx((HANDLE) bgchild, INFINITE, FALSE) !=
1609 _dosmaperr(GetLastError());
1610 fprintf(stderr, _("%s: could not wait for child thread: %s\n"),
1611 progname, strerror(errno));
1612 disconnect_and_exit(1);
1614 if (GetExitCodeThread((HANDLE) bgchild, &status) == 0)
1616 _dosmaperr(GetLastError());
1617 fprintf(stderr, _("%s: could not get child thread exit status: %s\n"),
1618 progname, strerror(errno));
1619 disconnect_and_exit(1);
1623 fprintf(stderr, _("%s: child thread exited with error %u\n"),
1624 progname, (unsigned int) status);
1625 disconnect_and_exit(1);
1627 /* Exited normally, we're happy */
1631 /* Free the recovery.conf contents */
1632 destroyPQExpBuffer(recoveryconfcontents);
1635 * End of copy data. Final result is already checked inside the loop.
1641 fprintf(stderr, "%s: base backup completed\n", progname);
1646 main(int argc, char **argv)
1648 static struct option long_options[] = {
1649 {"help", no_argument, NULL, '?'},
1650 {"version", no_argument, NULL, 'V'},
1651 {"pgdata", required_argument, NULL, 'D'},
1652 {"format", required_argument, NULL, 'F'},
1653 {"checkpoint", required_argument, NULL, 'c'},
1654 {"write-recovery-conf", no_argument, NULL, 'R'},
1655 {"xlog", no_argument, NULL, 'x'},
1656 {"xlog-method", required_argument, NULL, 'X'},
1657 {"gzip", no_argument, NULL, 'z'},
1658 {"compress", required_argument, NULL, 'Z'},
1659 {"label", required_argument, NULL, 'l'},
1660 {"dbname", required_argument, NULL, 'd'},
1661 {"host", required_argument, NULL, 'h'},
1662 {"port", required_argument, NULL, 'p'},
1663 {"username", required_argument, NULL, 'U'},
1664 {"no-password", no_argument, NULL, 'w'},
1665 {"password", no_argument, NULL, 'W'},
1666 {"status-interval", required_argument, NULL, 's'},
1667 {"verbose", no_argument, NULL, 'v'},
1668 {"progress", no_argument, NULL, 'P'},
1675 progname = get_progname(argv[0]);
1676 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_basebackup"));
1680 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
1685 else if (strcmp(argv[1], "-V") == 0
1686 || strcmp(argv[1], "--version") == 0)
1688 puts("pg_basebackup (PostgreSQL) " PG_VERSION);
1693 while ((c = getopt_long(argc, argv, "D:F:RxX:l:zZ:d:c:h:p:U:s:wWvP",
1694 long_options, &option_index)) != -1)
1699 basedir = pg_strdup(optarg);
1702 if (strcmp(optarg, "p") == 0 || strcmp(optarg, "plain") == 0)
1704 else if (strcmp(optarg, "t") == 0 || strcmp(optarg, "tar") == 0)
1709 _("%s: invalid output format \"%s\", must be \"plain\" or \"tar\"\n"),
1715 writerecoveryconf = true;
1721 _("%s: cannot specify both --xlog and --xlog-method\n"),
1733 _("%s: cannot specify both --xlog and --xlog-method\n"),
1739 if (strcmp(optarg, "f") == 0 ||
1740 strcmp(optarg, "fetch") == 0)
1742 else if (strcmp(optarg, "s") == 0 ||
1743 strcmp(optarg, "stream") == 0)
1748 _("%s: invalid xlog-method option \"%s\", must be \"fetch\" or \"stream\"\n"),
1754 label = pg_strdup(optarg);
1758 compresslevel = Z_DEFAULT_COMPRESSION;
1760 compresslevel = 1; /* will be rejected below */
1764 compresslevel = atoi(optarg);
1765 if (compresslevel <= 0 || compresslevel > 9)
1767 fprintf(stderr, _("%s: invalid compression level \"%s\"\n"),
1773 if (pg_strcasecmp(optarg, "fast") == 0)
1774 fastcheckpoint = true;
1775 else if (pg_strcasecmp(optarg, "spread") == 0)
1776 fastcheckpoint = false;
1779 fprintf(stderr, _("%s: invalid checkpoint argument \"%s\", must be \"fast\" or \"spread\"\n"),
1785 connection_string = pg_strdup(optarg);
1788 dbhost = pg_strdup(optarg);
1791 dbport = pg_strdup(optarg);
1794 dbuser = pg_strdup(optarg);
1803 standby_message_timeout = atoi(optarg) * 1000;
1804 if (standby_message_timeout < 0)
1806 fprintf(stderr, _("%s: invalid status interval \"%s\"\n"),
1815 showprogress = true;
1820 * getopt_long already emitted a complaint
1822 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
1829 * Any non-option arguments?
1834 _("%s: too many command-line arguments (first is \"%s\")\n"),
1835 progname, argv[optind]);
1836 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
1842 * Required arguments
1844 if (basedir == NULL)
1846 fprintf(stderr, _("%s: no target directory specified\n"), progname);
1847 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
1853 * Mutually exclusive arguments
1855 if (format == 'p' && compresslevel != 0)
1858 _("%s: only tar mode backups can be compressed\n"),
1860 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
1865 if (format != 'p' && streamwal)
1868 _("%s: WAL streaming can only be used in plain mode\n"),
1870 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
1876 if (compresslevel != 0)
1879 _("%s: this build does not support compression\n"),
1886 * Verify that the target directory exists, or create it. For plaintext
1887 * backups, always require the directory. For tar backups, require it
1888 * unless we are writing to stdout.
1890 if (format == 'p' || strcmp(basedir, "-") != 0)
1891 verify_dir_is_empty_or_create(basedir);