1 /*-------------------------------------------------------------------------
3 * receivelog.c - receive transaction log files using the streaming
4 * replication protocol.
6 * Author: Magnus Hagander <magnus@hagander.net>
8 * Portions Copyright (c) 1996-2016, PostgreSQL Global Development Group
11 * src/bin/pg_basebackup/receivelog.c
12 *-------------------------------------------------------------------------
15 #include "postgres_fe.h"
19 #ifdef HAVE_SYS_SELECT_H
20 #include <sys/select.h>
24 #include "receivelog.h"
25 #include "streamutil.h"
28 #include "access/xlog_internal.h"
31 /* fd and filename for currently open WAL file */
32 static int walfile = -1;
33 static char current_walfile_name[MAXPGPATH] = "";
34 static bool reportFlushPosition = false;
35 static XLogRecPtr lastFlushPosition = InvalidXLogRecPtr;
37 static bool still_sending = true; /* feedback still needs to be sent? */
39 static PGresult *HandleCopyStream(PGconn *conn, StreamCtl *stream,
41 static int CopyStreamPoll(PGconn *conn, long timeout_ms);
42 static int CopyStreamReceive(PGconn *conn, long timeout, char **buffer);
43 static bool ProcessKeepaliveMsg(PGconn *conn, char *copybuf, int len,
44 XLogRecPtr blockpos, int64 *last_status);
45 static bool ProcessXLogDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
46 XLogRecPtr *blockpos);
47 static PGresult *HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
48 XLogRecPtr blockpos, XLogRecPtr *stoppos);
49 static bool CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos,
51 static long CalculateCopyStreamSleeptime(int64 now, int standby_message_timeout,
54 static bool ReadEndOfStreamingResult(PGresult *res, XLogRecPtr *startpos,
58 mark_file_as_archived(const char *basedir, const char *fname)
61 static char tmppath[MAXPGPATH];
63 snprintf(tmppath, sizeof(tmppath), "%s/archive_status/%s.done",
66 fd = open(tmppath, O_WRONLY | O_CREAT | PG_BINARY, S_IRUSR | S_IWUSR);
69 fprintf(stderr, _("%s: could not create archive status file \"%s\": %s\n"),
70 progname, tmppath, strerror(errno));
76 fprintf(stderr, _("%s: could not fsync file \"%s\": %s\n"),
77 progname, tmppath, strerror(errno));
90 * Open a new WAL file in the specified directory.
92 * The file will be padded to 16Mb with zeroes. The base filename (without
93 * partial_suffix) is stored in current_walfile_name.
96 open_walfile(StreamCtl *stream, XLogRecPtr startpoint)
105 XLByteToSeg(startpoint, segno);
106 XLogFileName(current_walfile_name, stream->timeline, segno);
108 snprintf(fn, sizeof(fn), "%s/%s%s", stream->basedir, current_walfile_name,
109 stream->partial_suffix ? stream->partial_suffix : "");
110 f = open(fn, O_WRONLY | O_CREAT | PG_BINARY, S_IRUSR | S_IWUSR);
114 _("%s: could not open transaction log file \"%s\": %s\n"),
115 progname, fn, strerror(errno));
120 * Verify that the file is either empty (just created), or a complete
121 * XLogSegSize segment. Anything in between indicates a corrupt file.
123 if (fstat(f, &statbuf) != 0)
126 _("%s: could not stat transaction log file \"%s\": %s\n"),
127 progname, fn, strerror(errno));
131 if (statbuf.st_size == XLogSegSize)
133 /* File is open and ready to use */
137 if (statbuf.st_size != 0)
140 _("%s: transaction log file \"%s\" has %d bytes, should be 0 or %d\n"),
141 progname, fn, (int) statbuf.st_size, XLogSegSize);
146 /* New, empty, file. So pad it to 16Mb with zeroes */
147 zerobuf = pg_malloc0(XLOG_BLCKSZ);
148 for (bytes = 0; bytes < XLogSegSize; bytes += XLOG_BLCKSZ)
150 if (write(f, zerobuf, XLOG_BLCKSZ) != XLOG_BLCKSZ)
153 _("%s: could not pad transaction log file \"%s\": %s\n"),
154 progname, fn, strerror(errno));
163 if (lseek(f, SEEK_SET, 0) != 0)
166 _("%s: could not seek to beginning of transaction log file \"%s\": %s\n"),
167 progname, fn, strerror(errno));
176 * Close the current WAL file (if open), and rename it to the correct
177 * filename if it's complete. On failure, prints an error message to stderr
178 * and returns false, otherwise returns true.
181 close_walfile(StreamCtl *stream, XLogRecPtr pos)
188 currpos = lseek(walfile, 0, SEEK_CUR);
192 _("%s: could not determine seek position in file \"%s\": %s\n"),
193 progname, current_walfile_name, strerror(errno));
197 if (fsync(walfile) != 0)
199 fprintf(stderr, _("%s: could not fsync file \"%s\": %s\n"),
200 progname, current_walfile_name, strerror(errno));
204 if (close(walfile) != 0)
206 fprintf(stderr, _("%s: could not close file \"%s\": %s\n"),
207 progname, current_walfile_name, strerror(errno));
214 * If we finished writing a .partial file, rename it into place.
216 if (currpos == XLOG_SEG_SIZE && stream->partial_suffix)
218 char oldfn[MAXPGPATH];
219 char newfn[MAXPGPATH];
221 snprintf(oldfn, sizeof(oldfn), "%s/%s%s", stream->basedir, current_walfile_name, stream->partial_suffix);
222 snprintf(newfn, sizeof(newfn), "%s/%s", stream->basedir, current_walfile_name);
223 if (rename(oldfn, newfn) != 0)
225 fprintf(stderr, _("%s: could not rename file \"%s\": %s\n"),
226 progname, current_walfile_name, strerror(errno));
230 else if (stream->partial_suffix)
232 _("%s: not renaming \"%s%s\", segment is not complete\n"),
233 progname, current_walfile_name, stream->partial_suffix);
236 * Mark file as archived if requested by the caller - pg_basebackup needs
237 * to do so as files can otherwise get archived again after promotion of a
238 * new node. This is in line with walreceiver.c always doing a
239 * XLogArchiveForceDone() after a complete segment.
241 if (currpos == XLOG_SEG_SIZE && stream->mark_done)
243 /* writes error message if failed */
244 if (!mark_file_as_archived(stream->basedir, current_walfile_name))
248 lastFlushPosition = pos;
254 * Check if a timeline history file exists.
257 existsTimeLineHistoryFile(StreamCtl *stream)
259 char path[MAXPGPATH];
260 char histfname[MAXFNAMELEN];
264 * Timeline 1 never has a history file. We treat that as if it existed,
265 * since we never need to stream it.
267 if (stream->timeline == 1)
270 TLHistoryFileName(histfname, stream->timeline);
272 snprintf(path, sizeof(path), "%s/%s", stream->basedir, histfname);
274 fd = open(path, O_RDONLY | PG_BINARY, 0);
278 fprintf(stderr, _("%s: could not open timeline history file \"%s\": %s\n"),
279 progname, path, strerror(errno));
290 writeTimeLineHistoryFile(StreamCtl *stream, char *filename, char *content)
292 int size = strlen(content);
293 char path[MAXPGPATH];
294 char tmppath[MAXPGPATH];
295 char histfname[MAXFNAMELEN];
299 * Check that the server's idea of how timeline history files should be
300 * named matches ours.
302 TLHistoryFileName(histfname, stream->timeline);
303 if (strcmp(histfname, filename) != 0)
305 fprintf(stderr, _("%s: server reported unexpected history file name for timeline %u: %s\n"),
306 progname, stream->timeline, filename);
310 snprintf(path, sizeof(path), "%s/%s", stream->basedir, histfname);
313 * Write into a temp file name.
315 snprintf(tmppath, MAXPGPATH, "%s.tmp", path);
319 fd = open(tmppath, O_WRONLY | O_CREAT | PG_BINARY, S_IRUSR | S_IWUSR);
322 fprintf(stderr, _("%s: could not create timeline history file \"%s\": %s\n"),
323 progname, tmppath, strerror(errno));
328 if ((int) write(fd, content, size) != size)
330 int save_errno = errno;
333 * If we fail to make the file, delete it to release disk space
339 fprintf(stderr, _("%s: could not write timeline history file \"%s\": %s\n"),
340 progname, tmppath, strerror(errno));
347 fprintf(stderr, _("%s: could not fsync file \"%s\": %s\n"),
348 progname, tmppath, strerror(errno));
354 fprintf(stderr, _("%s: could not close file \"%s\": %s\n"),
355 progname, tmppath, strerror(errno));
360 * Now move the completed history file into place with its final name.
362 if (rename(tmppath, path) < 0)
364 fprintf(stderr, _("%s: could not rename file \"%s\" to \"%s\": %s\n"),
365 progname, tmppath, path, strerror(errno));
369 /* Maintain archive_status, check close_walfile() for details. */
370 if (stream->mark_done)
372 /* writes error message if failed */
373 if (!mark_file_as_archived(stream->basedir, histfname))
381 * Send a Standby Status Update message to server.
384 sendFeedback(PGconn *conn, XLogRecPtr blockpos, int64 now, bool replyRequested)
386 char replybuf[1 + 8 + 8 + 8 + 8 + 1];
391 fe_sendint64(blockpos, &replybuf[len]); /* write */
393 if (reportFlushPosition)
394 fe_sendint64(lastFlushPosition, &replybuf[len]); /* flush */
396 fe_sendint64(InvalidXLogRecPtr, &replybuf[len]); /* flush */
398 fe_sendint64(InvalidXLogRecPtr, &replybuf[len]); /* apply */
400 fe_sendint64(now, &replybuf[len]); /* sendTime */
402 replybuf[len] = replyRequested ? 1 : 0; /* replyRequested */
405 if (PQputCopyData(conn, replybuf, len) <= 0 || PQflush(conn))
407 fprintf(stderr, _("%s: could not send feedback packet: %s"),
408 progname, PQerrorMessage(conn));
416 * Check that the server version we're connected to is supported by
417 * ReceiveXlogStream().
419 * If it's not, an error message is printed to stderr, and false is returned.
422 CheckServerVersionForStreaming(PGconn *conn)
429 * The message format used in streaming replication changed in 9.3, so we
430 * cannot stream from older servers. And we don't support servers newer
431 * than the client; it might work, but we don't know, so err on the safe
434 minServerMajor = 903;
435 maxServerMajor = PG_VERSION_NUM / 100;
436 serverMajor = PQserverVersion(conn) / 100;
437 if (serverMajor < minServerMajor)
439 const char *serverver = PQparameterStatus(conn, "server_version");
441 fprintf(stderr, _("%s: incompatible server version %s; client does not support streaming from server versions older than %s\n"),
443 serverver ? serverver : "'unknown'",
447 else if (serverMajor > maxServerMajor)
449 const char *serverver = PQparameterStatus(conn, "server_version");
451 fprintf(stderr, _("%s: incompatible server version %s; client does not support streaming from server versions newer than %s\n"),
453 serverver ? serverver : "'unknown'",
461 * Receive a log stream starting at the specified position.
463 * Individual parameters are passed through the StreamCtl structure.
465 * If sysidentifier is specified, validate that both the system
466 * identifier and the timeline matches the specified ones
467 * (by sending an extra IDENTIFY_SYSTEM command)
469 * All received segments will be written to the directory
470 * specified by basedir. This will also fetch any missing timeline history
473 * The stream_stop callback will be called every time data
474 * is received, and whenever a segment is completed. If it returns
475 * true, the streaming will stop and the function
476 * return. As long as it returns false, streaming will continue
479 * standby_message_timeout controls how often we send a message
480 * back to the master letting it know our progress, in milliseconds.
481 * This message will only contain the write location, and never
484 * If 'partial_suffix' is not NULL, files are initially created with the
485 * given suffix, and the suffix is removed once the file is finished. That
486 * allows you to tell the difference between partial and completed files,
487 * so that you can continue later where you left.
489 * If 'synchronous' is true, the received WAL is flushed as soon as written,
490 * otherwise only when the WAL file is closed.
492 * Note: The log position *must* be at a log segment start!
495 ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
503 * The caller should've checked the server version already, but doesn't do
504 * any harm to check it here too.
506 if (!CheckServerVersionForStreaming(conn))
510 * Decide whether we want to report the flush position. If we report
511 * the flush position, the primary will know what WAL we'll
512 * possibly re-request, and it can then remove older WAL safely.
513 * We must always do that when we are using slots.
515 * Reporting the flush position makes one eligible as a synchronous
516 * replica. People shouldn't include generic names in
517 * synchronous_standby_names, but we've protected them against it so
518 * far, so let's continue to do so unless specifically requested.
520 if (replication_slot != NULL)
522 reportFlushPosition = true;
523 sprintf(slotcmd, "SLOT \"%s\" ", replication_slot);
527 if (stream->synchronous)
528 reportFlushPosition = true;
530 reportFlushPosition = false;
534 if (stream->sysidentifier != NULL)
536 /* Validate system identifier hasn't changed */
537 res = PQexec(conn, "IDENTIFY_SYSTEM");
538 if (PQresultStatus(res) != PGRES_TUPLES_OK)
541 _("%s: could not send replication command \"%s\": %s"),
542 progname, "IDENTIFY_SYSTEM", PQerrorMessage(conn));
546 if (PQntuples(res) != 1 || PQnfields(res) < 3)
549 _("%s: could not identify system: got %d rows and %d fields, expected %d rows and %d or more fields\n"),
550 progname, PQntuples(res), PQnfields(res), 1, 3);
554 if (strcmp(stream->sysidentifier, PQgetvalue(res, 0, 0)) != 0)
557 _("%s: system identifier does not match between base backup and streaming connection\n"),
562 if (stream->timeline > atoi(PQgetvalue(res, 0, 1)))
565 _("%s: starting timeline %u is not present in the server\n"),
566 progname, stream->timeline);
574 * initialize flush position to starting point, it's the caller's
575 * responsibility that that's sane.
577 lastFlushPosition = stream->startpos;
582 * Fetch the timeline history file for this timeline, if we don't have
585 if (!existsTimeLineHistoryFile(stream))
587 snprintf(query, sizeof(query), "TIMELINE_HISTORY %u", stream->timeline);
588 res = PQexec(conn, query);
589 if (PQresultStatus(res) != PGRES_TUPLES_OK)
591 /* FIXME: we might send it ok, but get an error */
592 fprintf(stderr, _("%s: could not send replication command \"%s\": %s"),
593 progname, "TIMELINE_HISTORY", PQresultErrorMessage(res));
599 * The response to TIMELINE_HISTORY is a single row result set
600 * with two fields: filename and content
602 if (PQnfields(res) != 2 || PQntuples(res) != 1)
605 _("%s: unexpected response to TIMELINE_HISTORY command: got %d rows and %d fields, expected %d rows and %d fields\n"),
606 progname, PQntuples(res), PQnfields(res), 1, 2);
609 /* Write the history file to disk */
610 writeTimeLineHistoryFile(stream,
611 PQgetvalue(res, 0, 0),
612 PQgetvalue(res, 0, 1));
618 * Before we start streaming from the requested location, check if the
619 * callback tells us to stop here.
621 if (stream->stream_stop(stream->startpos, stream->timeline, false))
624 /* Initiate the replication stream at specified location */
625 snprintf(query, sizeof(query), "START_REPLICATION %s%X/%X TIMELINE %u",
627 (uint32) (stream->startpos >> 32), (uint32) stream->startpos,
629 res = PQexec(conn, query);
630 if (PQresultStatus(res) != PGRES_COPY_BOTH)
632 fprintf(stderr, _("%s: could not send replication command \"%s\": %s"),
633 progname, "START_REPLICATION", PQresultErrorMessage(res));
640 res = HandleCopyStream(conn, stream, &stoppos);
645 * Streaming finished.
647 * There are two possible reasons for that: a controlled shutdown, or
648 * we reached the end of the current timeline. In case of
649 * end-of-timeline, the server sends a result set after Copy has
650 * finished, containing information about the next timeline. Read
651 * that, and restart streaming from the next timeline. In case of
652 * controlled shutdown, stop here.
654 if (PQresultStatus(res) == PGRES_TUPLES_OK)
657 * End-of-timeline. Read the next timeline's ID and starting
658 * position. Usually, the starting position will match the end of
659 * the previous timeline, but there are corner cases like if the
660 * server had sent us half of a WAL record, when it was promoted.
661 * The new timeline will begin at the end of the last complete
662 * record in that case, overlapping the partial WAL record on the
668 parsed = ReadEndOfStreamingResult(res, &stream->startpos, &newtimeline);
673 /* Sanity check the values the server gave us */
674 if (newtimeline <= stream->timeline)
677 _("%s: server reported unexpected next timeline %u, following timeline %u\n"),
678 progname, newtimeline, stream->timeline);
681 if (stream->startpos > stoppos)
684 _("%s: server stopped streaming timeline %u at %X/%X, but reported next timeline %u to begin at %X/%X\n"),
686 stream->timeline, (uint32) (stoppos >> 32), (uint32) stoppos,
687 newtimeline, (uint32) (stream->startpos >> 32), (uint32) stream->startpos);
691 /* Read the final result, which should be CommandComplete. */
692 res = PQgetResult(conn);
693 if (PQresultStatus(res) != PGRES_COMMAND_OK)
696 _("%s: unexpected termination of replication stream: %s"),
697 progname, PQresultErrorMessage(res));
704 * Loop back to start streaming from the new timeline. Always
705 * start streaming at the beginning of a segment.
707 stream->timeline = newtimeline;
708 stream->startpos = stream->startpos - (stream->startpos % XLOG_SEG_SIZE);
711 else if (PQresultStatus(res) == PGRES_COMMAND_OK)
716 * End of replication (ie. controlled shut down of the server).
718 * Check if the callback thinks it's OK to stop here. If not,
721 if (stream->stream_stop(stoppos, stream->timeline, false))
725 fprintf(stderr, _("%s: replication stream was terminated before stop point\n"),
732 /* Server returned an error. */
734 _("%s: unexpected termination of replication stream: %s"),
735 progname, PQresultErrorMessage(res));
742 if (walfile != -1 && close(walfile) != 0)
743 fprintf(stderr, _("%s: could not close file \"%s\": %s\n"),
744 progname, current_walfile_name, strerror(errno));
750 * Helper function to parse the result set returned by server after streaming
751 * has finished. On failure, prints an error to stderr and returns false.
754 ReadEndOfStreamingResult(PGresult *res, XLogRecPtr *startpos, uint32 *timeline)
756 uint32 startpos_xlogid,
760 * The result set consists of one row and two columns, e.g:
762 * next_tli | next_tli_startpos
763 * ----------+-------------------
766 * next_tli is the timeline ID of the next timeline after the one that
767 * just finished streaming. next_tli_startpos is the XLOG position where
768 * the server switched to it.
771 if (PQnfields(res) < 2 || PQntuples(res) != 1)
774 _("%s: unexpected result set after end-of-timeline: got %d rows and %d fields, expected %d rows and %d fields\n"),
775 progname, PQntuples(res), PQnfields(res), 1, 2);
779 *timeline = atoi(PQgetvalue(res, 0, 0));
780 if (sscanf(PQgetvalue(res, 0, 1), "%X/%X", &startpos_xlogid,
781 &startpos_xrecoff) != 2)
784 _("%s: could not parse next timeline's starting point \"%s\"\n"),
785 progname, PQgetvalue(res, 0, 1));
788 *startpos = ((uint64) startpos_xlogid << 32) | startpos_xrecoff;
794 * The main loop of ReceiveXlogStream. Handles the COPY stream after
795 * initiating streaming with the START_STREAMING command.
797 * If the COPY ends (not necessarily successfully) due a message from the
798 * server, returns a PGresult and sets *stoppos to the last byte written.
799 * On any other sort of error, returns NULL.
802 HandleCopyStream(PGconn *conn, StreamCtl *stream,
805 char *copybuf = NULL;
806 int64 last_status = -1;
807 XLogRecPtr blockpos = stream->startpos;
809 still_sending = true;
818 * Check if we should continue streaming, or abort at this point.
820 if (!CheckCopyStreamStop(conn, stream, blockpos, stoppos))
823 now = feGetCurrentTimestamp();
826 * If synchronous option is true, issue sync command as soon as there
827 * are WAL data which has not been flushed yet.
829 if (stream->synchronous && lastFlushPosition < blockpos && walfile != -1)
831 if (fsync(walfile) != 0)
833 fprintf(stderr, _("%s: could not fsync file \"%s\": %s\n"),
834 progname, current_walfile_name, strerror(errno));
837 lastFlushPosition = blockpos;
840 * Send feedback so that the server sees the latest WAL locations
843 if (!sendFeedback(conn, blockpos, now, false))
849 * Potentially send a status message to the master
851 if (still_sending && stream->standby_message_timeout > 0 &&
852 feTimestampDifferenceExceeds(last_status, now,
853 stream->standby_message_timeout))
855 /* Time to send feedback! */
856 if (!sendFeedback(conn, blockpos, now, false))
862 * Calculate how long send/receive loops should sleep
864 sleeptime = CalculateCopyStreamSleeptime(now, stream->standby_message_timeout,
867 r = CopyStreamReceive(conn, sleeptime, ©buf);
874 PGresult *res = HandleEndOfCopyStream(conn, stream, copybuf, blockpos, stoppos);
882 /* Check the message type. */
883 if (copybuf[0] == 'k')
885 if (!ProcessKeepaliveMsg(conn, copybuf, r, blockpos,
889 else if (copybuf[0] == 'w')
891 if (!ProcessXLogDataMsg(conn, stream, copybuf, r, &blockpos))
895 * Check if we should continue streaming, or abort at this
898 if (!CheckCopyStreamStop(conn, stream, blockpos, stoppos))
903 fprintf(stderr, _("%s: unrecognized streaming header: \"%c\"\n"),
904 progname, copybuf[0]);
909 * Process the received data, and any subsequent data we can read
912 r = CopyStreamReceive(conn, 0, ©buf);
923 * Wait until we can read CopyData message, or timeout.
925 * Returns 1 if data has become available for reading, 0 if timed out
926 * or interrupted by signal, and -1 on an error.
929 CopyStreamPoll(PGconn *conn, long timeout_ms)
933 struct timeval timeout;
934 struct timeval *timeoutptr;
936 if (PQsocket(conn) < 0)
938 fprintf(stderr, _("%s: invalid socket: %s"), progname,
939 PQerrorMessage(conn));
943 FD_ZERO(&input_mask);
944 FD_SET(PQsocket(conn), &input_mask);
950 timeout.tv_sec = timeout_ms / 1000L;
951 timeout.tv_usec = (timeout_ms % 1000L) * 1000L;
952 timeoutptr = &timeout;
955 ret = select(PQsocket(conn) + 1, &input_mask, NULL, NULL, timeoutptr);
956 if (ret == 0 || (ret < 0 && errno == EINTR))
957 return 0; /* Got a timeout or signal */
960 fprintf(stderr, _("%s: select() failed: %s\n"),
961 progname, strerror(errno));
969 * Receive CopyData message available from XLOG stream, blocking for
970 * maximum of 'timeout' ms.
972 * If data was received, returns the length of the data. *buffer is set to
973 * point to a buffer holding the received message. The buffer is only valid
974 * until the next CopyStreamReceive call.
976 * 0 if no data was available within timeout, or wait was interrupted
977 * by signal. -1 on error. -2 if the server ended the COPY.
980 CopyStreamReceive(PGconn *conn, long timeout, char **buffer)
982 char *copybuf = NULL;
989 /* Try to receive a CopyData message */
990 rawlen = PQgetCopyData(conn, ©buf, 1);
994 * No data available. Wait for some to appear, but not longer than the
995 * specified timeout, so that we can ping the server.
1001 ret = CopyStreamPoll(conn, timeout);
1006 /* Else there is actually data on the socket */
1007 if (PQconsumeInput(conn) == 0)
1010 _("%s: could not receive data from WAL stream: %s"),
1011 progname, PQerrorMessage(conn));
1015 /* Now that we've consumed some input, try again */
1016 rawlen = PQgetCopyData(conn, ©buf, 1);
1020 if (rawlen == -1) /* end-of-streaming or error */
1024 fprintf(stderr, _("%s: could not read COPY data: %s"),
1025 progname, PQerrorMessage(conn));
1029 /* Return received messages to caller */
1035 * Process the keepalive message.
1038 ProcessKeepaliveMsg(PGconn *conn, char *copybuf, int len,
1039 XLogRecPtr blockpos, int64 *last_status)
1042 bool replyRequested;
1046 * Parse the keepalive message, enclosed in the CopyData message. We just
1047 * check if the server requested a reply, and ignore the rest.
1049 pos = 1; /* skip msgtype 'k' */
1050 pos += 8; /* skip walEnd */
1051 pos += 8; /* skip sendTime */
1055 fprintf(stderr, _("%s: streaming header too small: %d\n"),
1059 replyRequested = copybuf[pos];
1061 /* If the server requested an immediate reply, send one. */
1062 if (replyRequested && still_sending)
1064 if (reportFlushPosition && lastFlushPosition < blockpos &&
1068 * If a valid flush location needs to be reported, flush the
1069 * current WAL file so that the latest flush location is sent back
1070 * to the server. This is necessary to see whether the last WAL
1071 * data has been successfully replicated or not, at the normal
1072 * shutdown of the server.
1074 if (fsync(walfile) != 0)
1076 fprintf(stderr, _("%s: could not fsync file \"%s\": %s\n"),
1077 progname, current_walfile_name, strerror(errno));
1080 lastFlushPosition = blockpos;
1083 now = feGetCurrentTimestamp();
1084 if (!sendFeedback(conn, blockpos, now, false))
1093 * Process XLogData message.
1096 ProcessXLogDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
1097 XLogRecPtr *blockpos)
1105 * Once we've decided we don't want to receive any more, just ignore any
1106 * subsequent XLogData messages.
1108 if (!(still_sending))
1112 * Read the header of the XLogData message, enclosed in the CopyData
1113 * message. We only need the WAL location field (dataStart), the rest of
1114 * the header is ignored.
1116 hdr_len = 1; /* msgtype 'w' */
1117 hdr_len += 8; /* dataStart */
1118 hdr_len += 8; /* walEnd */
1119 hdr_len += 8; /* sendTime */
1122 fprintf(stderr, _("%s: streaming header too small: %d\n"),
1126 *blockpos = fe_recvint64(©buf[1]);
1128 /* Extract WAL location for this block */
1129 xlogoff = *blockpos % XLOG_SEG_SIZE;
1132 * Verify that the initial location in the stream matches where we think
1137 /* No file open yet */
1141 _("%s: received transaction log record for offset %u with no file open\n"),
1148 /* More data in existing segment */
1149 /* XXX: store seek value don't reseek all the time */
1150 if (lseek(walfile, 0, SEEK_CUR) != xlogoff)
1153 _("%s: got WAL data offset %08x, expected %08x\n"),
1154 progname, xlogoff, (int) lseek(walfile, 0, SEEK_CUR));
1159 bytes_left = len - hdr_len;
1167 * If crossing a WAL boundary, only write up until we reach
1170 if (xlogoff + bytes_left > XLOG_SEG_SIZE)
1171 bytes_to_write = XLOG_SEG_SIZE - xlogoff;
1173 bytes_to_write = bytes_left;
1177 if (!open_walfile(stream, *blockpos))
1179 /* Error logged by open_walfile */
1185 copybuf + hdr_len + bytes_written,
1186 bytes_to_write) != bytes_to_write)
1189 _("%s: could not write %u bytes to WAL file \"%s\": %s\n"),
1190 progname, bytes_to_write, current_walfile_name,
1195 /* Write was successful, advance our position */
1196 bytes_written += bytes_to_write;
1197 bytes_left -= bytes_to_write;
1198 *blockpos += bytes_to_write;
1199 xlogoff += bytes_to_write;
1201 /* Did we reach the end of a WAL segment? */
1202 if (*blockpos % XLOG_SEG_SIZE == 0)
1204 if (!close_walfile(stream, *blockpos))
1205 /* Error message written in close_walfile() */
1210 if (still_sending && stream->stream_stop(*blockpos, stream->timeline, true))
1212 if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
1214 fprintf(stderr, _("%s: could not send copy-end packet: %s"),
1215 progname, PQerrorMessage(conn));
1218 still_sending = false;
1219 return true; /* ignore the rest of this XLogData packet */
1223 /* No more data left to write, receive next copy packet */
1229 * Handle end of the copy stream.
1232 HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
1233 XLogRecPtr blockpos, XLogRecPtr *stoppos)
1235 PGresult *res = PQgetResult(conn);
1238 * The server closed its end of the copy stream. If we haven't closed
1239 * ours already, we need to do so now, unless the server threw an error,
1240 * in which case we don't.
1244 if (!close_walfile(stream, blockpos))
1246 /* Error message written in close_walfile() */
1250 if (PQresultStatus(res) == PGRES_COPY_IN)
1252 if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
1255 _("%s: could not send copy-end packet: %s"),
1256 progname, PQerrorMessage(conn));
1260 res = PQgetResult(conn);
1262 still_sending = false;
1264 if (copybuf != NULL)
1266 *stoppos = blockpos;
1271 * Check if we should continue streaming, or abort at this point.
1274 CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos,
1275 XLogRecPtr *stoppos)
1277 if (still_sending && stream->stream_stop(blockpos, stream->timeline, false))
1279 if (!close_walfile(stream, blockpos))
1281 /* Potential error message is written by close_walfile */
1284 if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
1286 fprintf(stderr, _("%s: could not send copy-end packet: %s"),
1287 progname, PQerrorMessage(conn));
1290 still_sending = false;
1297 * Calculate how long send/receive loops should sleep
1300 CalculateCopyStreamSleeptime(int64 now, int standby_message_timeout,
1303 int64 status_targettime = 0;
1306 if (standby_message_timeout && still_sending)
1307 status_targettime = last_status +
1308 (standby_message_timeout - 1) * ((int64) 1000);
1310 if (status_targettime > 0)
1315 feTimestampDifference(now,
1319 /* Always sleep at least 1 sec */
1326 sleeptime = secs * 1000 + usecs / 1000;