1 /*-------------------------------------------------------------------------
3 * pg_receivewal.c - receive streaming WAL data and write it
6 * Author: Magnus Hagander <magnus@hagander.net>
8 * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
11 * src/bin/pg_basebackup/pg_receivewal.c
12 *-------------------------------------------------------------------------
15 #include "postgres_fe.h"
23 #include "access/xlog_internal.h"
24 #include "getopt_long.h"
26 #include "receivelog.h"
27 #include "streamutil.h"
30 /* Time to sleep between reconnection attempts */
31 #define RECONNECT_SLEEP_TIME 5
34 static char *basedir = NULL;
35 static int verbose = 0;
36 static int compresslevel = 0;
37 static int noloop = 0;
38 static int standby_message_timeout = 10 * 1000; /* 10 sec = default */
39 static volatile bool time_to_stop = false;
40 static bool do_create_slot = false;
41 static bool slot_exists_ok = false;
42 static bool do_drop_slot = false;
43 static bool synchronous = false;
44 static char *replication_slot = NULL;
45 static XLogRecPtr endpos = InvalidXLogRecPtr;
48 static void usage(void);
49 static DIR *get_destination_dir(char *dest_folder);
50 static void close_destination_dir(DIR *dest_dir, char *dest_folder);
51 static XLogRecPtr FindStreamingStart(uint32 *tli);
52 static void StreamLog(void);
53 static bool stop_streaming(XLogRecPtr segendpos, uint32 timeline,
54 bool segment_finished);
56 #define disconnect_and_exit(code) \
58 if (conn != NULL) PQfinish(conn); \
62 /* Routines to evaluate segment file format */
63 #define IsCompressXLogFileName(fname) \
64 (strlen(fname) == XLOG_FNAME_LEN + strlen(".gz") && \
65 strspn(fname, "0123456789ABCDEF") == XLOG_FNAME_LEN && \
66 strcmp((fname) + XLOG_FNAME_LEN, ".gz") == 0)
67 #define IsPartialCompressXLogFileName(fname) \
68 (strlen(fname) == XLOG_FNAME_LEN + strlen(".gz.partial") && \
69 strspn(fname, "0123456789ABCDEF") == XLOG_FNAME_LEN && \
70 strcmp((fname) + XLOG_FNAME_LEN, ".gz.partial") == 0)
75 printf(_("%s receives PostgreSQL streaming write-ahead logs.\n\n"),
77 printf(_("Usage:\n"));
78 printf(_(" %s [OPTION]...\n"), progname);
79 printf(_("\nOptions:\n"));
80 printf(_(" -D, --directory=DIR receive write-ahead log files into this directory\n"));
81 printf(_(" -E, --endpos=LSN exit after receiving the specified LSN\n"));
82 printf(_(" --if-not-exists do not error if slot already exists when creating a slot\n"));
83 printf(_(" -n, --no-loop do not loop on connection lost\n"));
84 printf(_(" -s, --status-interval=SECS\n"
85 " time between status packets sent to server (default: %d)\n"), (standby_message_timeout / 1000));
86 printf(_(" -S, --slot=SLOTNAME replication slot to use\n"));
87 printf(_(" --synchronous flush write-ahead log immediately after writing\n"));
88 printf(_(" -v, --verbose output verbose messages\n"));
89 printf(_(" -V, --version output version information, then exit\n"));
90 printf(_(" -Z, --compress=0-9 compress logs with given compression level\n"));
91 printf(_(" -?, --help show this help, then exit\n"));
92 printf(_("\nConnection options:\n"));
93 printf(_(" -d, --dbname=CONNSTR connection string\n"));
94 printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
95 printf(_(" -p, --port=PORT database server port number\n"));
96 printf(_(" -U, --username=NAME connect as specified database user\n"));
97 printf(_(" -w, --no-password never prompt for password\n"));
98 printf(_(" -W, --password force password prompt (should happen automatically)\n"));
99 printf(_("\nOptional actions:\n"));
100 printf(_(" --create-slot create a new replication slot (for the slot's name see --slot)\n"));
101 printf(_(" --drop-slot drop the replication slot (for the slot's name see --slot)\n"));
102 printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
106 stop_streaming(XLogRecPtr xlogpos, uint32 timeline, bool segment_finished)
108 static uint32 prevtimeline = 0;
109 static XLogRecPtr prevpos = InvalidXLogRecPtr;
111 /* we assume that we get called once at the end of each segment */
112 if (verbose && segment_finished)
113 fprintf(stderr, _("%s: finished segment at %X/%X (timeline %u)\n"),
114 progname, (uint32) (xlogpos >> 32), (uint32) xlogpos,
117 if (!XLogRecPtrIsInvalid(endpos) && endpos < xlogpos)
120 fprintf(stderr, _("%s: stopped streaming at %X/%X (timeline %u)\n"),
121 progname, (uint32) (xlogpos >> 32), (uint32) xlogpos,
128 * Note that we report the previous, not current, position here. After a
129 * timeline switch, xlogpos points to the beginning of the segment because
130 * that's where we always begin streaming. Reporting the end of previous
131 * timeline isn't totally accurate, because the next timeline can begin
132 * slightly before the end of the WAL that we received on the previous
133 * timeline, but it's close enough for reporting purposes.
135 if (verbose && prevtimeline != 0 && prevtimeline != timeline)
136 fprintf(stderr, _("%s: switched to timeline %u at %X/%X\n"),
138 (uint32) (prevpos >> 32), (uint32) prevpos);
140 prevtimeline = timeline;
146 fprintf(stderr, _("%s: received interrupt signal, exiting\n"),
155 * Get destination directory.
158 get_destination_dir(char *dest_folder)
162 Assert(dest_folder != NULL);
163 dir = opendir(dest_folder);
166 fprintf(stderr, _("%s: could not open directory \"%s\": %s\n"),
167 progname, basedir, strerror(errno));
168 disconnect_and_exit(1);
176 * Close existing directory.
179 close_destination_dir(DIR *dest_dir, char *dest_folder)
181 Assert(dest_dir != NULL && dest_folder != NULL);
182 if (closedir(dest_dir))
184 fprintf(stderr, _("%s: could not close directory \"%s\": %s\n"),
185 progname, dest_folder, strerror(errno));
186 disconnect_and_exit(1);
192 * Determine starting location for streaming, based on any existing xlog
193 * segments in the directory. We start at the end of the last one that is
194 * complete (size matches wal segment size), on the timeline with highest ID.
196 * If there are no WAL files in the directory, returns InvalidXLogRecPtr.
199 FindStreamingStart(uint32 *tli)
202 struct dirent *dirent;
203 XLogSegNo high_segno = 0;
205 bool high_ispartial = false;
207 dir = get_destination_dir(basedir);
209 while (errno = 0, (dirent = readdir(dir)) != NULL)
217 * Check if the filename looks like an xlog file, or a .partial file.
219 if (IsXLogFileName(dirent->d_name))
224 else if (IsPartialXLogFileName(dirent->d_name))
229 else if (IsCompressXLogFileName(dirent->d_name))
234 else if (IsPartialCompressXLogFileName(dirent->d_name))
243 * Looks like an xlog file. Parse its position.
245 XLogFromFileName(dirent->d_name, &tli, &segno, WalSegSz);
248 * Check that the segment has the right size, if it's supposed to be
249 * completed. For non-compressed segments just check the on-disk size
250 * and see if it matches a completed segment. For compressed segments,
251 * look at the last 4 bytes of the compressed file, which is where the
252 * uncompressed size is located for gz files with a size lower than
253 * 4GB, and then compare it to the size of a completed segment. The 4
254 * last bytes correspond to the ISIZE member according to
255 * http://www.zlib.org/rfc-gzip.html.
257 if (!ispartial && !iscompress)
260 char fullpath[MAXPGPATH * 2];
262 snprintf(fullpath, sizeof(fullpath), "%s/%s", basedir, dirent->d_name);
263 if (stat(fullpath, &statbuf) != 0)
265 fprintf(stderr, _("%s: could not stat file \"%s\": %s\n"),
266 progname, fullpath, strerror(errno));
267 disconnect_and_exit(1);
270 if (statbuf.st_size != WalSegSz)
273 _("%s: segment file \"%s\" has incorrect size %d, skipping\n"),
274 progname, dirent->d_name, (int) statbuf.st_size);
278 else if (!ispartial && iscompress)
283 char fullpath[MAXPGPATH * 2];
285 snprintf(fullpath, sizeof(fullpath), "%s/%s", basedir, dirent->d_name);
287 fd = open(fullpath, O_RDONLY | PG_BINARY);
290 fprintf(stderr, _("%s: could not open compressed file \"%s\": %s\n"),
291 progname, fullpath, strerror(errno));
292 disconnect_and_exit(1);
294 if (lseek(fd, (off_t) (-4), SEEK_END) < 0)
296 fprintf(stderr, _("%s: could not seek in compressed file \"%s\": %s\n"),
297 progname, fullpath, strerror(errno));
298 disconnect_and_exit(1);
300 if (read(fd, (char *) buf, sizeof(buf)) != sizeof(buf))
302 fprintf(stderr, _("%s: could not read compressed file \"%s\": %s\n"),
303 progname, fullpath, strerror(errno));
304 disconnect_and_exit(1);
308 bytes_out = (buf[3] << 24) | (buf[2] << 16) |
309 (buf[1] << 8) | buf[0];
311 if (bytes_out != WalSegSz)
314 _("%s: compressed segment file \"%s\" has incorrect uncompressed size %d, skipping\n"),
315 progname, dirent->d_name, bytes_out);
320 /* Looks like a valid segment. Remember that we saw it. */
321 if ((segno > high_segno) ||
322 (segno == high_segno && tli > high_tli) ||
323 (segno == high_segno && tli == high_tli && high_ispartial && !ispartial))
327 high_ispartial = ispartial;
333 fprintf(stderr, _("%s: could not read directory \"%s\": %s\n"),
334 progname, basedir, strerror(errno));
335 disconnect_and_exit(1);
338 close_destination_dir(dir, basedir);
345 * Move the starting pointer to the start of the next segment, if the
346 * highest one we saw was completed. Otherwise start streaming from
347 * the beginning of the .partial segment.
352 XLogSegNoOffsetToRecPtr(high_segno, 0, high_ptr, WalSegSz);
358 return InvalidXLogRecPtr;
362 * Start the log streaming
367 XLogRecPtr serverpos;
368 TimeLineID servertli;
371 MemSet(&stream, 0, sizeof(stream));
374 * Connect in replication mode to the server
377 conn = GetConnection();
379 /* Error message already written in GetConnection() */
382 if (!CheckServerVersionForStreaming(conn))
385 * Error message already written in CheckServerVersionForStreaming().
386 * There's no hope of recovering from a version mismatch, so don't
389 disconnect_and_exit(1);
393 * Identify server, obtaining start LSN position and current timeline ID
394 * at the same time, necessary if not valid data can be found in the
395 * existing output directory.
397 if (!RunIdentifySystem(conn, NULL, &servertli, &serverpos, NULL))
398 disconnect_and_exit(1);
401 * Figure out where to start streaming.
403 stream.startpos = FindStreamingStart(&stream.timeline);
404 if (stream.startpos == InvalidXLogRecPtr)
406 stream.startpos = serverpos;
407 stream.timeline = servertli;
411 * Always start streaming at the beginning of a segment
413 stream.startpos -= XLogSegmentOffset(stream.startpos, WalSegSz);
416 * Start the replication
420 _("%s: starting log streaming at %X/%X (timeline %u)\n"),
421 progname, (uint32) (stream.startpos >> 32), (uint32) stream.startpos,
424 stream.stream_stop = stop_streaming;
425 stream.stop_socket = PGINVALID_SOCKET;
426 stream.standby_message_timeout = standby_message_timeout;
427 stream.synchronous = synchronous;
428 stream.do_sync = true;
429 stream.mark_done = false;
430 stream.walmethod = CreateWalDirectoryMethod(basedir, compresslevel,
432 stream.partial_suffix = ".partial";
433 stream.replication_slot = replication_slot;
435 ReceiveXlogStream(conn, &stream);
437 if (!stream.walmethod->finish())
440 _("%s: could not finish writing WAL files: %s\n"),
441 progname, strerror(errno));
447 FreeWalDirectoryMethod();
448 pg_free(stream.walmethod);
454 * When sigint is called, just tell the system to exit at the next possible
460 sigint_handler(int signum)
467 main(int argc, char **argv)
469 static struct option long_options[] = {
470 {"help", no_argument, NULL, '?'},
471 {"version", no_argument, NULL, 'V'},
472 {"directory", required_argument, NULL, 'D'},
473 {"dbname", required_argument, NULL, 'd'},
474 {"endpos", required_argument, NULL, 'E'},
475 {"host", required_argument, NULL, 'h'},
476 {"port", required_argument, NULL, 'p'},
477 {"username", required_argument, NULL, 'U'},
478 {"no-loop", no_argument, NULL, 'n'},
479 {"no-password", no_argument, NULL, 'w'},
480 {"password", no_argument, NULL, 'W'},
481 {"status-interval", required_argument, NULL, 's'},
482 {"slot", required_argument, NULL, 'S'},
483 {"verbose", no_argument, NULL, 'v'},
484 {"compress", required_argument, NULL, 'Z'},
486 {"create-slot", no_argument, NULL, 1},
487 {"drop-slot", no_argument, NULL, 2},
488 {"if-not-exists", no_argument, NULL, 3},
489 {"synchronous", no_argument, NULL, 4},
498 progname = get_progname(argv[0]);
499 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_basebackup"));
503 if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
508 else if (strcmp(argv[1], "-V") == 0 ||
509 strcmp(argv[1], "--version") == 0)
511 puts("pg_receivewal (PostgreSQL) " PG_VERSION);
516 while ((c = getopt_long(argc, argv, "D:d:E:h:p:U:s:S:nwWvZ:",
517 long_options, &option_index)) != -1)
522 basedir = pg_strdup(optarg);
525 connection_string = pg_strdup(optarg);
528 dbhost = pg_strdup(optarg);
531 if (atoi(optarg) <= 0)
533 fprintf(stderr, _("%s: invalid port number \"%s\"\n"),
537 dbport = pg_strdup(optarg);
540 dbuser = pg_strdup(optarg);
549 standby_message_timeout = atoi(optarg) * 1000;
550 if (standby_message_timeout < 0)
552 fprintf(stderr, _("%s: invalid status interval \"%s\"\n"),
558 replication_slot = pg_strdup(optarg);
561 if (sscanf(optarg, "%X/%X", &hi, &lo) != 2)
564 _("%s: could not parse end position \"%s\"\n"),
568 endpos = ((uint64) hi) << 32 | lo;
577 compresslevel = atoi(optarg);
578 if (compresslevel < 0 || compresslevel > 9)
580 fprintf(stderr, _("%s: invalid compression level \"%s\"\n"),
587 do_create_slot = true;
593 slot_exists_ok = true;
601 * getopt_long already emitted a complaint
603 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
610 * Any non-option arguments?
615 _("%s: too many command-line arguments (first is \"%s\")\n"),
616 progname, argv[optind]);
617 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
622 if (do_drop_slot && do_create_slot)
624 fprintf(stderr, _("%s: cannot use --create-slot together with --drop-slot\n"), progname);
625 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
630 if (replication_slot == NULL && (do_drop_slot || do_create_slot))
632 /* translator: second %s is an option name */
633 fprintf(stderr, _("%s: %s needs a slot to be specified using --slot\n"), progname,
634 do_drop_slot ? "--drop-slot" : "--create-slot");
635 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
643 if (basedir == NULL && !do_drop_slot && !do_create_slot)
645 fprintf(stderr, _("%s: no target directory specified\n"), progname);
646 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
652 if (compresslevel != 0)
655 _("%s: this build does not support compression\n"),
662 * Check existence of destination folder.
664 if (!do_drop_slot && !do_create_slot)
666 DIR *dir = get_destination_dir(basedir);
668 close_destination_dir(dir, basedir);
672 pqsignal(SIGINT, sigint_handler);
676 * Obtain a connection before doing anything.
678 conn = GetConnection();
680 /* error message already written in GetConnection() */
684 * Run IDENTIFY_SYSTEM to make sure we've successfully have established a
685 * replication connection and haven't connected using a database specific
688 if (!RunIdentifySystem(conn, NULL, NULL, NULL, &db_name))
689 disconnect_and_exit(1);
691 /* determine remote server's xlog segment size */
692 if (!RetrieveWalSegSize(conn))
693 disconnect_and_exit(1);
696 * Check that there is a database associated with connection, none should
697 * be defined in this context.
702 _("%s: replication connection using slot \"%s\" is unexpectedly database specific\n"),
703 progname, replication_slot);
704 disconnect_and_exit(1);
708 * Drop a replication slot.
714 _("%s: dropping replication slot \"%s\"\n"),
715 progname, replication_slot);
717 if (!DropReplicationSlot(conn, replication_slot))
718 disconnect_and_exit(1);
719 disconnect_and_exit(0);
722 /* Create a replication slot */
727 _("%s: creating replication slot \"%s\"\n"),
728 progname, replication_slot);
730 if (!CreateReplicationSlot(conn, replication_slot, NULL, false, true, false,
732 disconnect_and_exit(1);
733 disconnect_and_exit(0);
737 * Don't close the connection here so that subsequent StreamLog() can
747 * We've been Ctrl-C'ed or end of streaming position has been
748 * willingly reached, so exit without an error code.
754 fprintf(stderr, _("%s: disconnected\n"), progname);
760 /* translator: check source for value for %d */
761 _("%s: disconnected; waiting %d seconds to try again\n"),
762 progname, RECONNECT_SLEEP_TIME);
763 pg_usleep(RECONNECT_SLEEP_TIME * 1000000);