1 /*-------------------------------------------------------------------------
5 * The WAL sender process (walsender) is new as of Postgres 9.0. It takes
6 * care of sending XLOG from the primary server to a single recipient.
7 * (Note that there can be more than one walsender process concurrently.)
8 * It is started by the postmaster when the walreceiver of a standby server
9 * connects to the primary server and requests XLOG streaming replication.
10 * It attempts to keep reading XLOG records from the disk and sending them
11 * to the standby server, as long as the connection is alive (i.e., like
12 * any backend, there is a one-to-one relationship between a connection
13 * and a walsender process).
15 * Normal termination is by SIGTERM, which instructs the walsender to
16 * close the connection and exit(0) at next convenient moment. Emergency
17 * termination is by SIGQUIT; like any backend, the walsender will simply
18 * abort and exit on SIGQUIT. A close of the connection and a FATAL error
19 * are treated as not a crash but approximately normal termination;
20 * the walsender will exit quickly without sending any more XLOG records.
22 * If the server is shut down, postmaster sends us SIGUSR2 after all
23 * regular backends have exited and the shutdown checkpoint has been written.
24 * This instruct walsender to send any outstanding WAL, including the
25 * shutdown checkpoint record, and then exit.
28 * Portions Copyright (c) 2010-2010, PostgreSQL Global Development Group
31 * $PostgreSQL: pgsql/src/backend/replication/walsender.c,v 1.32 2010/09/15 06:51:19 heikki Exp $
33 *-------------------------------------------------------------------------
40 #include "access/xlog_internal.h"
41 #include "catalog/pg_type.h"
42 #include "libpq/libpq.h"
43 #include "libpq/pqformat.h"
44 #include "libpq/pqsignal.h"
45 #include "miscadmin.h"
46 #include "replication/walprotocol.h"
47 #include "replication/walsender.h"
48 #include "storage/fd.h"
49 #include "storage/ipc.h"
50 #include "storage/pmsignal.h"
51 #include "storage/proc.h"
52 #include "tcop/tcopprot.h"
53 #include "utils/guc.h"
54 #include "utils/memutils.h"
55 #include "utils/ps_status.h"
58 /* Array of WalSnds in shared memory */
59 WalSndCtlData *WalSndCtl = NULL;
61 /* My slot in the shared memory array */
62 static WalSnd *MyWalSnd = NULL;
64 /* Array of WalSndWaiter in shared memory */
65 static WalSndWaiter *WalSndWaiters;
68 bool am_walsender = false; /* Am I a walsender process ? */
70 /* User-settable parameters for walsender */
71 int max_wal_senders = 0; /* the maximum number of concurrent walsenders */
72 int WalSndDelay = 200; /* max sleep time between some actions */
73 int replication_timeout = 0; /* maximum time to wait for the Ack from the standby */
74 char *standby_fencing_command = NULL; /* command to shoot the standby in the head */
77 * Buffer for WAL sending
79 * WalSndOutBuffer is a work area in which the output message is constructed.
80 * It's used in just so we can avoid re-palloc'ing the buffer on each cycle.
81 * It must be of size 6 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE.
83 static char *WalSndOutBuffer;
84 static int WalSndOutHead; /* head of pending output */
85 static int WalSndOutTail; /* tail of pending output */
88 * These variables are used similarly to openLogFile/Id/Seg/Off,
89 * but for walsender to read the XLOG.
91 static int sendFile = -1;
92 static uint32 sendId = 0;
93 static uint32 sendSeg = 0;
94 static uint32 sendOff = 0;
97 * How far have we sent WAL already? This is also advertised in
98 * MyWalSnd->sentPtr. (Actually, this is the next WAL location to send.)
100 static XLogRecPtr sentPtr = {0, 0};
103 * How far have we completed replication already? This is also
104 * advertised in MyWalSnd->ackdPtr. This is not used in asynchronous
107 static XLogRecPtr ackdPtr = {0, 0};
109 /* Flags set by signal handlers for later service in main loop */
110 static volatile sig_atomic_t got_SIGHUP = false;
111 static volatile sig_atomic_t shutdown_requested = false;
112 static volatile sig_atomic_t ready_to_stop = false;
114 /* Flag set by signal handler of backends for replication */
115 static volatile sig_atomic_t replication_done = false;
117 /* Signal handlers */
118 static void WalSndSigHupHandler(SIGNAL_ARGS);
119 static void WalSndShutdownHandler(SIGNAL_ARGS);
120 static void WalSndQuickDieHandler(SIGNAL_ARGS);
121 static void WalSndXLogSendHandler(SIGNAL_ARGS);
122 static void WalSndLastCycleHandler(SIGNAL_ARGS);
124 /* Prototypes for private functions */
125 static int WalSndLoop(void);
126 static void InitWalSnd(void);
127 static void WalSndHandshake(void);
128 static void WalSndKill(int code, Datum arg);
129 static void XLogRead(char *buf, XLogRecPtr recptr, Size nbytes);
130 static bool XLogSend(bool *caughtup, bool *pending);
131 static void ProcessStreamMsgs(StringInfo inMsg);
132 static void ExecuteStandbyFencingCommand(void);
134 static void RegisterWalSndWaiter(BackendId backendId, XLogRecPtr record,
136 static void WakeupWalSndWaiters(XLogRecPtr record);
137 static XLogRecPtr GetOldestAckdPtr(void);
140 /* Main entry point for walsender process */
144 MemoryContext walsnd_context;
146 if (RecoveryInProgress())
148 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
149 errmsg("recovery is still in progress, can't accept WAL streaming connections")));
151 /* Create a per-walsender data structure in shared memory */
155 * Create a memory context that we will do all our work in. We do this so
156 * that we can reset the context during error recovery and thereby avoid
157 * possible memory leaks. Formerly this code just ran in
158 * TopMemoryContext, but resetting that would be a really bad idea.
160 * XXX: we don't actually attempt error recovery in walsender, we just
161 * close the connection and exit.
163 walsnd_context = AllocSetContextCreate(TopMemoryContext,
165 ALLOCSET_DEFAULT_MINSIZE,
166 ALLOCSET_DEFAULT_INITSIZE,
167 ALLOCSET_DEFAULT_MAXSIZE);
168 MemoryContextSwitchTo(walsnd_context);
170 /* Unblock signals (they were blocked when the postmaster forked us) */
171 PG_SETMASK(&UnBlockSig);
173 /* Tell the standby that walsender is ready for receiving commands */
174 ReadyForQuery(DestRemote);
176 /* Handle handshake messages before streaming */
179 /* Initialize shared memory status */
181 /* use volatile pointer to prevent code rearrangement */
182 volatile WalSnd *walsnd = MyWalSnd;
184 SpinLockAcquire(&walsnd->mutex);
185 walsnd->sentPtr = sentPtr;
186 SpinLockRelease(&walsnd->mutex);
189 /* Main loop of walsender */
194 * Execute commands from walreceiver, until we enter streaming mode.
197 WalSndHandshake(void)
199 StringInfoData input_message;
200 bool replication_started = false;
202 initStringInfo(&input_message);
204 while (!replication_started)
208 /* Wait for a command to arrive */
209 firstchar = pq_getbyte();
212 * Emergency bailout if postmaster has died. This is to avoid the
213 * necessity for manual cleanup of all postmaster children.
215 if (!PostmasterIsAlive(true))
219 * Check for any other interesting events that happened while we
225 ProcessConfigFile(PGC_SIGHUP);
228 if (firstchar != EOF)
231 * Read the message contents. This is expected to be done without
232 * blocking because we've been able to get message type code.
234 if (pq_getmessage(&input_message, 0))
235 firstchar = EOF; /* suitable message already logged */
238 /* Handle the very limited subset of commands expected in this phase */
243 case 'Q': /* Query message */
245 const char *query_string;
248 query_string = pq_getmsgstring(&input_message);
249 pq_getmsgend(&input_message);
251 if (strcmp(query_string, "IDENTIFY_SYSTEM") == 0)
258 * Reply with a result set with one row, two columns.
259 * First col is system ID, and second is timeline ID
262 snprintf(sysid, sizeof(sysid), UINT64_FORMAT,
263 GetSystemIdentifier());
264 snprintf(tli, sizeof(tli), "%u", ThisTimeLineID);
266 /* Send a RowDescription message */
267 pq_beginmessage(&buf, 'T');
268 pq_sendint(&buf, 2, 2); /* 2 fields */
271 pq_sendstring(&buf, "systemid"); /* col name */
272 pq_sendint(&buf, 0, 4); /* table oid */
273 pq_sendint(&buf, 0, 2); /* attnum */
274 pq_sendint(&buf, TEXTOID, 4); /* type oid */
275 pq_sendint(&buf, -1, 2); /* typlen */
276 pq_sendint(&buf, 0, 4); /* typmod */
277 pq_sendint(&buf, 0, 2); /* format code */
280 pq_sendstring(&buf, "timeline"); /* col name */
281 pq_sendint(&buf, 0, 4); /* table oid */
282 pq_sendint(&buf, 0, 2); /* attnum */
283 pq_sendint(&buf, INT4OID, 4); /* type oid */
284 pq_sendint(&buf, 4, 2); /* typlen */
285 pq_sendint(&buf, 0, 4); /* typmod */
286 pq_sendint(&buf, 0, 2); /* format code */
289 /* Send a DataRow message */
290 pq_beginmessage(&buf, 'D');
291 pq_sendint(&buf, 2, 2); /* # of columns */
292 pq_sendint(&buf, strlen(sysid), 4); /* col1 len */
293 pq_sendbytes(&buf, (char *) &sysid, strlen(sysid));
294 pq_sendint(&buf, strlen(tli), 4); /* col2 len */
295 pq_sendbytes(&buf, (char *) tli, strlen(tli));
298 /* Send CommandComplete and ReadyForQuery messages */
299 EndCommand("SELECT", DestRemote);
300 ReadyForQuery(DestRemote);
301 /* ReadyForQuery did pq_flush for us */
303 else if (sscanf(query_string, "START_REPLICATION %X/%X MODE %5s",
304 &recptr.xlogid, &recptr.xrecoff, modestr) == 3)
310 * Check that we're logging enough information in the
311 * WAL for log-shipping.
313 * NOTE: This only checks the current value of
314 * wal_level. Even if the current setting is not
315 * 'minimal', there can be old WAL in the pg_xlog
316 * directory that was created with 'minimal'. So this
317 * is not bulletproof, the purpose is just to give a
318 * user-friendly error message that hints how to
319 * configure the system correctly.
321 if (wal_level == WAL_LEVEL_MINIMAL)
323 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
324 errmsg("standby connections not allowed because wal_level=minimal")));
326 /* Verify that the specified replication mode is valid */
328 const struct config_enum_entry *entry;
330 for (entry = replication_mode_options; entry && entry->name; entry++)
332 if (strcmp(modestr, entry->name) == 0)
338 if (entry == NULL || entry->name == NULL)
340 (errcode(ERRCODE_PROTOCOL_VIOLATION),
341 errmsg("invalid replication mode: %s", modestr)));
344 /* Change the state according to replication mode specified by standby */
346 /* use volatile pointer to prevent code rearrangement */
347 volatile WalSnd *walsnd = MyWalSnd;
349 SpinLockAcquire(&walsnd->mutex);
350 walsnd->walSndState = (mode == REPLICATION_MODE_ASYNC) ?
351 WALSND_ASYNC : WALSND_CATCHUP;
352 SpinLockRelease(&walsnd->mutex);
355 /* Send a CopyXLogResponse message, and start streaming */
356 pq_beginmessage(&buf, 'W');
361 * Initialize positions to the received one, then the
362 * xlog records begin to be shipped from that position
364 sentPtr = ackdPtr = recptr;
366 /* break out of the loop */
367 replication_started = true;
372 (errcode(ERRCODE_PROTOCOL_VIOLATION),
373 errmsg("invalid standby query string: %s", query_string)));
379 /* standby is closing the connection */
383 /* standby disconnected unexpectedly */
385 (errcode(ERRCODE_PROTOCOL_VIOLATION),
386 errmsg("unexpected EOF on standby connection")));
391 (errcode(ERRCODE_PROTOCOL_VIOLATION),
392 errmsg("invalid standby handshake message type %d", firstchar)));
398 * Process messages received from the standby.
403 ProcessStreamMsgs(StringInfo inMsg)
407 /* Loop to process successive complete messages available */
410 unsigned char firstchar;
413 r = pq_getbyte_if_available(&firstchar);
416 /* unexpected error or EOF */
418 (errcode(ERRCODE_PROTOCOL_VIOLATION),
419 errmsg("unexpected EOF on standby connection")));
424 /* no data available without blocking */
428 /* Handle the very limited subset of commands expected in this phase */
431 case 'd': /* CopyData message */
433 unsigned char rpltype;
436 * Read the message contents. This is expected to be done without
437 * blocking because we've been able to get message type code.
439 if (pq_getmessage(inMsg, 0))
440 proc_exit(0); /* suitable message already logged */
442 /* Read the replication message type from CopyData message */
443 rpltype = pq_getmsgbyte(inMsg);
448 WalAckMessageData *msgdata;
450 msgdata = (WalAckMessageData *) pq_getmsgbytes(inMsg, sizeof(WalAckMessageData));
453 * Update local status.
455 * The ackd ptr received from standby should not
458 if (XLByteLE(ackdPtr, msgdata->ackEnd))
459 ackdPtr = msgdata->ackEnd;
462 (errmsg("replication completion location went back from "
464 ackdPtr.xlogid, ackdPtr.xrecoff,
465 msgdata->ackEnd.xlogid, msgdata->ackEnd.xrecoff)));
467 acked = true; /* also need to update shared position */
472 (errcode(ERRCODE_PROTOCOL_VIOLATION),
473 errmsg("invalid replication message type %d",
480 * 'X' means that the standby is closing down the socket.
487 (errcode(ERRCODE_PROTOCOL_VIOLATION),
488 errmsg("invalid standby message type %d",
495 /* use volatile pointer to prevent code rearrangement */
496 volatile WalSnd *walsnd = MyWalSnd;
498 SpinLockAcquire(&walsnd->mutex);
499 walsnd->ackdPtr = ackdPtr;
500 SpinLockRelease(&walsnd->mutex);
503 /* Wake up the backends that this walsender had been blocking */
504 WakeupWalSndWaiters(ackdPtr);
507 /* Main loop of walsender process */
511 StringInfoData input_message;
512 bool caughtup = false;
513 bool pending = false;
514 XLogRecPtr switchptr = {0, 0};
516 initStringInfo(&input_message);
519 * Allocate buffer that will be used for each output message. We do this
520 * just once to reduce palloc overhead. The buffer must be made large
521 * enough for maximum-sized messages.
523 WalSndOutBuffer = palloc(6 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE);
524 WalSndOutHead = WalSndOutTail = 0;
526 /* Loop forever, unless we get an error */
530 * Emergency bailout if postmaster has died. This is to avoid the
531 * necessity for manual cleanup of all postmaster children.
533 if (!PostmasterIsAlive(true))
536 /* Process any requests or signals received recently */
540 ProcessConfigFile(PGC_SIGHUP);
544 * When SIGUSR2 arrives, we send all outstanding logs up to the
545 * shutdown checkpoint record (i.e., the latest record) and exit.
549 if (!XLogSend(&caughtup, &pending))
551 if (caughtup && !pending)
552 shutdown_requested = true;
555 /* Normal exit from the walsender is here */
556 if (shutdown_requested)
558 /* Inform the standby that XLOG streaming was done */
559 pq_puttextmessage('C', "COPY 0");
566 * If we had sent all accumulated WAL in last round or could not
567 * flush pending WAL in output buffer because the socket was not
568 * writable, nap for the configured time before retrying.
570 if (caughtup || pending)
573 * Even if we wrote all the WAL that was available when we started
574 * sending, more might have arrived while we were sending this
575 * batch. We had the latch set while sending, so we have not
576 * received any signals from that time. Let's arm the latch
577 * again, and after that check that we're still up-to-date.
579 ResetLatch(&MyWalSnd->latch);
581 if (!XLogSend(&caughtup, &pending))
585 * If the standby has almost caught up with the primary, we change
586 * the state to WALSND_PRESYNC and start making transactions wait
587 * until their WAL has been replicated.
589 * No lock is required to get WalSnd->walSndState here since it can
590 * be updated only by walsender.
592 if (MyWalSnd->walSndState == WALSND_CATCHUP && caughtup)
594 /* use volatile pointer to prevent code rearrangement */
595 volatile WalSnd *walsnd = MyWalSnd;
597 SpinLockAcquire(&walsnd->mutex);
598 walsnd->walSndState = WALSND_PRESYNC;
599 SpinLockRelease(&walsnd->mutex);
602 * switchptr indicates how far we must complete replication
603 * before advertising that the standby has already been in
604 * sync with the primary.
606 switchptr = GetFlushRecPtr();
609 if ((caughtup || pending) && !got_SIGHUP && !ready_to_stop &&
617 * XXX: We don't really need the periodic wakeups anymore,
618 * WaitLatchOrSocket should reliably wake up as soon as
619 * something interesting happens.
623 * Check for replication timeout if it's enabled and we need
624 * to wait until the socket has become writable to flush
625 * pending WAL in output buffer or until the Ack message
626 * from the standby has become available.
628 if (replication_timeout > 0 &&
630 (MyWalSnd->walSndState >= WALSND_CATCHUP &&
631 XLByteLT(ackdPtr, sentPtr))))
633 sleeptime = replication_timeout;
634 check_timeout = true;
638 sleeptime = WalSndDelay;
639 check_timeout = false;
643 res = WaitLatchOrSocket(&MyWalSnd->latch, MyProcPort->sock,
644 true, (WalSndOutTail > 0),
647 if (res == 0 && check_timeout)
650 * Since typically expiration of replication timeout means
651 * communication problem, we don't send the error message
655 (errmsg("terminating walsender process due to replication timeout")));
660 /* Process messages received from the standby */
661 ProcessStreamMsgs(&input_message);
664 * If the standby has caught up with the primary, we change
665 * the state to WALSND_SYNC and inform the standby that it's
666 * in sync with the primary. This state ensures that all the
667 * transactions completed from a client's point of view have
668 * been replicated to the standby.
670 if (MyWalSnd->walSndState == WALSND_PRESYNC &&
671 XLByteLE(switchptr, ackdPtr) && !pending)
673 /* use volatile pointer to prevent code rearrangement */
674 volatile WalSnd *walsnd = MyWalSnd;
676 SpinLockAcquire(&walsnd->mutex);
677 walsnd->walSndState = WALSND_SYNC;
678 SpinLockRelease(&walsnd->mutex);
681 * We can send a XLogCatchupComplete message without blocking
682 * since it's guaranteed that there is no pending data in the
685 pq_putmessage('d', "c", 1);
692 /* Attempt to send the log once every loop */
693 if (!XLogSend(&caughtup, &pending))
699 * Get here on send failure. Clean up and exit.
701 * Reset whereToSendOutput to prevent ereport from attempting to send any
702 * more messages to the standby.
704 if (whereToSendOutput == DestRemote)
705 whereToSendOutput = DestNone;
708 return 1; /* keep the compiler quiet */
711 /* Initialize a per-walsender data structure for this walsender process */
718 * WalSndCtl should be set up already (we inherit this by fork() or
719 * EXEC_BACKEND mechanism from the postmaster).
721 Assert(WalSndCtl != NULL);
722 Assert(MyWalSnd == NULL);
725 * Find a free walsender slot and reserve it. If this fails, we must be
726 * out of WalSnd structures.
728 for (i = 0; i < max_wal_senders; i++)
730 /* use volatile pointer to prevent code rearrangement */
731 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
733 SpinLockAcquire(&walsnd->mutex);
735 if (walsnd->pid != 0)
737 SpinLockRelease(&walsnd->mutex);
743 * Found a free slot. Reserve it for us.
745 walsnd->pid = MyProcPid;
746 MemSet(&walsnd->sentPtr, 0, sizeof(XLogRecPtr));
747 MemSet(&walsnd->ackdPtr, 0, sizeof(XLogRecPtr));
748 walsnd->walSndState = WALSND_INIT;
749 SpinLockRelease(&walsnd->mutex);
750 /* don't need the lock anymore */
751 OwnLatch((Latch *) &walsnd->latch);
752 MyWalSnd = (WalSnd *) walsnd;
757 if (MyWalSnd == NULL)
759 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
760 errmsg("number of requested standby connections "
761 "exceeds max_wal_senders (currently %d)",
764 /* Arrange to clean up at walsender exit */
765 on_shmem_exit(WalSndKill, 0);
768 /* Destroy the per-walsender data structure for this walsender process */
770 WalSndKill(int code, Datum arg)
772 /* use volatile pointer to prevent code rearrangement */
773 volatile WalSnd *walsnd = MyWalSnd;
775 Assert(MyWalSnd != NULL);
778 * If replication was terminated for a reason other than the master
779 * server shutdown or emergency bailout (i.e., unexpected death of
780 * postmaster), we can expect this server can work standalone,
781 * so we call standby_fencing_command to shoot the standby server
782 * in the head if it's specified.
784 if (!ready_to_stop && PostmasterIsAlive(true))
785 ExecuteStandbyFencingCommand();
787 /* Wake up the backends that this walsender had been blocking */
788 SpinLockAcquire(&walsnd->mutex);
789 walsnd->walSndState = WALSND_INIT;
790 SpinLockRelease(&walsnd->mutex);
791 WakeupWalSndWaiters(GetOldestAckdPtr());
794 * Mark WalSnd struct no longer in use. Assume that no lock is required
798 DisownLatch(&MyWalSnd->latch);
800 /* WalSnd struct isn't mine anymore */
805 * Read 'nbytes' bytes from WAL into 'buf', starting at location 'recptr'
807 * XXX probably this should be improved to suck data directly from the
808 * WAL buffers when possible.
811 XLogRead(char *buf, XLogRecPtr recptr, Size nbytes)
813 XLogRecPtr startRecPtr = recptr;
814 char path[MAXPGPATH];
815 uint32 lastRemovedLog;
816 uint32 lastRemovedSeg;
826 startoff = recptr.xrecoff % XLogSegSize;
828 if (sendFile < 0 || !XLByteInSeg(recptr, sendId, sendSeg))
830 /* Switch to another logfile segment */
834 XLByteToSeg(recptr, sendId, sendSeg);
835 XLogFilePath(path, ThisTimeLineID, sendId, sendSeg);
837 sendFile = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
841 * If the file is not found, assume it's because the standby
842 * asked for a too old WAL segment that has already been
843 * removed or recycled.
847 char filename[MAXFNAMELEN];
849 XLogFileName(filename, ThisTimeLineID, sendId, sendSeg);
851 (errcode_for_file_access(),
852 errmsg("requested WAL segment %s has already been removed",
857 (errcode_for_file_access(),
858 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
859 path, sendId, sendSeg)));
864 /* Need to seek in the file? */
865 if (sendOff != startoff)
867 if (lseek(sendFile, (off_t) startoff, SEEK_SET) < 0)
869 (errcode_for_file_access(),
870 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
871 sendId, sendSeg, startoff)));
875 /* How many bytes are within this segment? */
876 if (nbytes > (XLogSegSize - startoff))
877 segbytes = XLogSegSize - startoff;
881 readbytes = read(sendFile, buf, segbytes);
884 (errcode_for_file_access(),
885 errmsg("could not read from log file %u, segment %u, offset %u, "
887 sendId, sendSeg, sendOff, (unsigned long) segbytes)));
889 /* Update state for read */
890 XLByteAdvance(recptr, readbytes);
892 sendOff += readbytes;
898 * After reading into the buffer, check that what we read was valid. We do
899 * this after reading, because even though the segment was present when we
900 * opened it, it might get recycled or removed while we read it. The
901 * read() succeeds in that case, but the data we tried to read might
902 * already have been overwritten with new WAL records.
904 XLogGetLastRemoved(&lastRemovedLog, &lastRemovedSeg);
905 XLByteToSeg(startRecPtr, log, seg);
906 if (log < lastRemovedLog ||
907 (log == lastRemovedLog && seg <= lastRemovedSeg))
909 char filename[MAXFNAMELEN];
911 XLogFileName(filename, ThisTimeLineID, log, seg);
913 (errcode_for_file_access(),
914 errmsg("requested WAL segment %s has already been removed",
920 * Read up to MAX_SEND_SIZE bytes of WAL that's been flushed to disk,
921 * but not yet sent to the client, and send it.
923 * If there is no unsent WAL remaining, *caughtup is set to true, otherwise
924 * *caughtup is set to false.
926 * If there is pending WAL in output buffer, *pending is set to true,
927 * otherwise *pending is set to false.
929 * Returns true if OK, false if trouble.
932 XLogSend(bool *caughtup, bool *pending)
934 XLogRecPtr SendRqstPtr;
936 static XLogRecPtr endptr;
940 WalDataMessageHeader msghdr;
942 /* Attempt to flush pending WAL in output buffer */
945 if (WalSndOutHead != WalSndOutTail)
947 res = pq_putbytes_if_writable(WalSndOutBuffer + WalSndOutHead,
948 WalSndOutTail - WalSndOutHead);
951 WalSndOutHead += res;
952 if (WalSndOutHead != WalSndOutTail)
956 res = pq_flush_if_writable();
966 * Attempt to send all data that's already been written out and fsync'd to
967 * disk. We cannot go further than what's been written out given the
968 * current implementation of XLogRead(). And in any case it's unsafe to
969 * send WAL that is not securely down to disk on the master: if the master
970 * subsequently crashes and restarts, slaves must not have applied any WAL
971 * that gets lost on the master.
973 SendRqstPtr = GetFlushRecPtr();
975 /* Quick exit if nothing to do */
976 if (XLByteLE(SendRqstPtr, sentPtr))
983 * Figure out how much to send in one message. If there's no more than
984 * MAX_SEND_SIZE bytes to send, send everything. Otherwise send
985 * MAX_SEND_SIZE bytes, but round back to logfile or page boundary.
987 * The rounding is not only for performance reasons. Walreceiver relies on
988 * the fact that we never split a WAL record across two messages. Since a
989 * long WAL record is split at page boundary into continuation records,
990 * page boundary is always a safe cut-off point. We also assume that
991 * SendRqstPtr never points to the middle of a WAL record.
994 if (startptr.xrecoff >= XLogFileSize)
997 * crossing a logid boundary, skip the non-existent last log segment
998 * in previous logical log file.
1000 startptr.xlogid += 1;
1001 startptr.xrecoff = 0;
1005 XLByteAdvance(endptr, MAX_SEND_SIZE);
1006 if (endptr.xlogid != startptr.xlogid)
1008 /* Don't cross a logfile boundary within one message */
1009 Assert(endptr.xlogid == startptr.xlogid + 1);
1010 endptr.xlogid = startptr.xlogid;
1011 endptr.xrecoff = XLogFileSize;
1014 /* if we went beyond SendRqstPtr, back off */
1015 if (XLByteLE(SendRqstPtr, endptr))
1017 endptr = SendRqstPtr;
1022 /* round down to page boundary. */
1023 endptr.xrecoff -= (endptr.xrecoff % XLOG_BLCKSZ);
1027 nbytes = endptr.xrecoff - startptr.xrecoff;
1028 Assert(nbytes <= MAX_SEND_SIZE);
1031 * OK to read and send the slice.
1033 WalSndOutBuffer[0] = 'd';
1034 WalSndOutBuffer[5] = 'w';
1036 WalSndOutTail = 6 + sizeof(WalDataMessageHeader) + nbytes;
1038 n32 = htonl((uint32) WalSndOutTail - 1);
1039 memcpy(WalSndOutBuffer + 1, &n32, 4);
1042 * Read the log directly into the output buffer to avoid extra memcpy
1045 XLogRead(WalSndOutBuffer + 6 + sizeof(WalDataMessageHeader), startptr, nbytes);
1048 * We fill the message header last so that the send timestamp is taken as
1051 msghdr.dataStart = startptr;
1052 msghdr.walEnd = SendRqstPtr;
1053 msghdr.sendTime = GetCurrentTimestamp();
1055 memcpy(WalSndOutBuffer + 6, &msghdr, sizeof(WalDataMessageHeader));
1057 res = pq_putbytes_if_writable(WalSndOutBuffer, WalSndOutTail);
1061 WalSndOutHead = res;
1062 if (WalSndOutHead != WalSndOutTail)
1069 /* Flush pending output to the client */
1070 res = pq_flush_if_writable();
1081 WalSndOutHead = WalSndOutTail = 0;
1086 /* Update shared memory status */
1088 /* use volatile pointer to prevent code rearrangement */
1089 volatile WalSnd *walsnd = MyWalSnd;
1091 SpinLockAcquire(&walsnd->mutex);
1092 walsnd->sentPtr = sentPtr;
1093 SpinLockRelease(&walsnd->mutex);
1096 /* Report progress of XLOG streaming in PS display */
1097 if (update_process_title)
1099 char activitymsg[50];
1101 snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%X",
1102 sentPtr.xlogid, sentPtr.xrecoff);
1103 set_ps_display(activitymsg, false);
1110 * Attempt to execute standby_fencing_command at the end of replication.
1113 ExecuteStandbyFencingCommand(void)
1115 char standbyFencingCmd[MAXPGPATH];
1121 /* Do nothing if no command supplied */
1122 if (standby_fencing_command[0] == '\0')
1126 * construct the command to be executed
1128 dp = standbyFencingCmd;
1129 endp = standbyFencingCmd + MAXPGPATH - 1;
1132 for (sp = standby_fencing_command; *sp; sp++)
1140 /* %a: application_name */
1141 const char *appname = application_name;
1143 if (appname == NULL || *appname == '\0')
1144 appname = _("[unknown]");
1147 strlcpy(dp, appname, endp - dp);
1152 /* convert %% to a single % */
1158 /* otherwise treat the % as not special */
1173 (errmsg_internal("executing standby fencing command \"%s\"",
1174 standbyFencingCmd)));
1177 * execute the constructed command
1179 rc = system(standbyFencingCmd);
1183 * No matter what code is returned, walsender can't stop exiting.
1184 * We don't need to care about the return code of the command here.
1187 (errmsg("standby fencing command failed with return code %d",
1189 errdetail("The failed standby fencing command was: %s",
1190 standbyFencingCmd)));
1194 /* SIGHUP: set flag to re-read config file at next convenient time */
1196 WalSndSigHupHandler(SIGNAL_ARGS)
1200 SetLatch(&MyWalSnd->latch);
1203 /* SIGTERM: set flag to shut down */
1205 WalSndShutdownHandler(SIGNAL_ARGS)
1207 shutdown_requested = true;
1209 SetLatch(&MyWalSnd->latch);
1213 * WalSndQuickDieHandler() occurs when signalled SIGQUIT by the postmaster.
1215 * Some backend has bought the farm,
1216 * so we need to stop what we're doing and exit.
1219 WalSndQuickDieHandler(SIGNAL_ARGS)
1221 PG_SETMASK(&BlockSig);
1224 * We DO NOT want to run proc_exit() callbacks -- we're here because
1225 * shared memory may be corrupted, so we don't want to try to clean up our
1226 * transaction. Just nail the windows shut and get out of town. Now that
1227 * there's an atexit callback to prevent third-party code from breaking
1228 * things by calling exit() directly, we have to reset the callbacks
1229 * explicitly to make this work as intended.
1234 * Note we do exit(2) not exit(0). This is to force the postmaster into a
1235 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
1236 * backend. This is necessary precisely because we don't clean up our
1237 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
1238 * should ensure the postmaster sees this as a crash, too, but no harm in
1239 * being doubly sure.)
1244 /* SIGUSR1: set flag to send WAL records */
1246 WalSndXLogSendHandler(SIGNAL_ARGS)
1248 latch_sigusr1_handler();
1251 /* SIGUSR2: set flag to do a last cycle and shut down afterwards */
1253 WalSndLastCycleHandler(SIGNAL_ARGS)
1255 ready_to_stop = true;
1257 SetLatch(&MyWalSnd->latch);
1260 /* Set up signal handlers */
1264 /* Set up signal handlers */
1265 pqsignal(SIGHUP, WalSndSigHupHandler); /* set flag to read config
1267 pqsignal(SIGINT, SIG_IGN); /* not used */
1268 pqsignal(SIGTERM, WalSndShutdownHandler); /* request shutdown */
1269 pqsignal(SIGQUIT, WalSndQuickDieHandler); /* hard crash time */
1270 pqsignal(SIGALRM, SIG_IGN);
1271 pqsignal(SIGPIPE, SIG_IGN);
1272 pqsignal(SIGUSR1, WalSndXLogSendHandler); /* request WAL sending */
1273 pqsignal(SIGUSR2, WalSndLastCycleHandler); /* request a last cycle and
1276 /* Reset some signals that are accepted by postmaster but not here */
1277 pqsignal(SIGCHLD, SIG_DFL);
1278 pqsignal(SIGTTIN, SIG_DFL);
1279 pqsignal(SIGTTOU, SIG_DFL);
1280 pqsignal(SIGCONT, SIG_DFL);
1281 pqsignal(SIGWINCH, SIG_DFL);
1284 /* Report shared-memory space needed by WalSndShmemInit */
1286 WalSndShmemSize(void)
1290 size = offsetof(WalSndCtlData, walsnds);
1291 size = add_size(size, mul_size(max_wal_senders, sizeof(WalSnd)));
1294 * If replication is enabled, we have a data structure called
1295 * WalSndWaiters, created in shared memory.
1297 if (max_wal_senders > 0)
1298 size = add_size(size, mul_size(MaxBackends, sizeof(WalSndWaiter)));
1303 /* Allocate and initialize walsender-related shared memory */
1305 WalSndShmemInit(void)
1309 Size size = add_size(offsetof(WalSndCtlData, walsnds),
1310 mul_size(max_wal_senders, sizeof(WalSnd)));
1312 WalSndCtl = (WalSndCtlData *)
1313 ShmemInitStruct("Wal Sender Ctl", size, &found);
1317 /* First time through, so initialize */
1318 MemSet(WalSndCtl, 0, size);
1320 for (i = 0; i < max_wal_senders; i++)
1322 WalSnd *walsnd = &WalSndCtl->walsnds[i];
1324 SpinLockInit(&walsnd->mutex);
1325 InitSharedLatch(&walsnd->latch);
1329 /* Create or attach to the WalSndWaiters array too, if needed */
1330 if (max_wal_senders > 0)
1332 WalSndWaiters = (WalSndWaiter *)
1333 ShmemInitStruct("WalSndWaiters",
1334 mul_size(MaxBackends, sizeof(WalSndWaiter)),
1336 WalSndCtl->maxWaiters = MaxBackends;
1340 /* Wake up all walsenders */
1346 for (i = 0; i < max_wal_senders; i++)
1347 SetLatch(&WalSndCtl->walsnds[i].latch);
1351 * Ensure that replication has been completed up to the given position.
1354 WaitXLogSend(XLogRecPtr record)
1357 bool mustwait = false;
1359 Assert(max_wal_senders > 0);
1361 for (i = 0; i < max_wal_senders; i++)
1363 /* use volatile pointer to prevent code rearrangement */
1364 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1368 if (walsnd->pid == 0)
1371 SpinLockAcquire(&walsnd->mutex);
1372 state = walsnd->walSndState;
1373 recptr = walsnd->ackdPtr;
1374 SpinLockRelease(&walsnd->mutex);
1376 if (state <= WALSND_ASYNC ||
1377 (recptr.xlogid == 0 && recptr.xrecoff == 0))
1380 /* Quick exit if already known replicated */
1381 if (XLByteLE(record, recptr))
1385 * If walsender is bulk-sending WAL for standby to catch up,
1386 * we don't need to wait for Ack from standby.
1388 if (state <= WALSND_CATCHUP)
1395 * Don't need to wait for replication if there is no synchronous
1402 * Register myself into the wait list and sleep until replication
1403 * has been completed up to the given position and the walsender
1406 * If replication has been completed up to the latest position
1407 * before the registration, walsender might be unable to send the
1408 * signal immediately. We must wake up the walsender after the
1411 ResetLatch(&MyProc->latch);
1412 RegisterWalSndWaiter(MyBackendId, record, &MyProc->latch);
1417 WaitLatch(&MyProc->latch, 1000000L);
1419 /* If done already, we finish waiting */
1420 if (replication_done)
1422 replication_done = false;
1429 * Register the given backend into the wait list.
1432 RegisterWalSndWaiter(BackendId backendId, XLogRecPtr record, Latch *latch)
1434 /* use volatile pointer to prevent code rearrangement */
1435 volatile WalSndCtlData *walsndctl = WalSndCtl;
1439 LWLockAcquire(WalSndWaiterLock, LW_EXCLUSIVE);
1441 /* Out of slots. This should not happen. */
1442 if (walsndctl->numWaiters + 1 > walsndctl->maxWaiters)
1443 elog(PANIC, "out of replication waiters slots");
1446 * The given position is expected to be relatively new in the
1447 * wait list. Since the entries in the list are sorted in an
1448 * increasing order of XLogRecPtr, we can shorten the time it
1449 * takes to find an insert slot by scanning the list backwards.
1451 for (i = walsndctl->numWaiters; i > 0; i--)
1453 if (XLByteLE(WalSndWaiters[i - 1].record, record))
1458 /* Shuffle the list if needed */
1460 memmove(&WalSndWaiters[i + 1], &WalSndWaiters[i],
1461 count * sizeof(WalSndWaiter));
1463 WalSndWaiters[i].backendId = backendId;
1464 WalSndWaiters[i].record = record;
1465 WalSndWaiters[i].latch = latch;
1466 walsndctl->numWaiters++;
1468 LWLockRelease(WalSndWaiterLock);
1472 * Wake up the backends waiting until replication has been completed
1473 * up to the position older than or equal to the given one.
1475 * Wake up all waiters if InvalidXLogRecPtr is given.
1478 WakeupWalSndWaiters(XLogRecPtr record)
1480 /* use volatile pointer to prevent code rearrangement */
1481 volatile WalSndCtlData *walsndctl = WalSndCtl;
1484 bool all_wakeup = (record.xlogid == 0 && record.xrecoff == 0);
1486 LWLockAcquire(WalSndWaiterLock, LW_EXCLUSIVE);
1488 for (i = 0; i < walsndctl->numWaiters; i++)
1490 /* use volatile pointer to prevent code rearrangement */
1491 volatile WalSndWaiter *waiter = &WalSndWaiters[i];
1493 if (all_wakeup || XLByteLE(waiter->record, record))
1495 SetProcLatch(waiter->latch, PROCSIG_REPLICATION_INTERRUPT,
1502 * If the backend waiting for the Ack position newer than
1503 * the given one is found, we don't need to search the wait
1504 * list any more. This is because the waiters in the list
1505 * are guaranteed to be sorted in an increasing order of
1512 /* If there are still some waiters, left-justify them in the list */
1513 walsndctl->numWaiters -= count;
1514 if (walsndctl->numWaiters > 0 && count > 0)
1515 memmove(&WalSndWaiters[0], &WalSndWaiters[i],
1516 walsndctl->numWaiters * sizeof(WalSndWaiter));
1518 LWLockRelease(WalSndWaiterLock);
1522 * Returns the oldest Ack position in synchronous walsenders. Or
1523 * InvalidXLogRecPtr if none.
1526 GetOldestAckdPtr(void)
1528 XLogRecPtr oldest = {0, 0};
1532 for (i = 0; i < max_wal_senders; i++)
1534 /* use volatile pointer to prevent code rearrangement */
1535 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1539 if (walsnd->pid == 0)
1542 SpinLockAcquire(&walsnd->mutex);
1543 state = walsnd->walSndState;
1544 recptr = walsnd->ackdPtr;
1545 SpinLockRelease(&walsnd->mutex);
1547 if (state <= WALSND_ASYNC ||
1548 (recptr.xlogid == 0 && recptr.xrecoff == 0))
1551 if (!found || XLByteLT(recptr, oldest))
1559 * This is called when PROCSIG_REPLICATION_INTERRUPT is received.
1562 HandleReplicationInterrupt(void)
1564 replication_done = true;