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 */
76 * Buffer for WAL sending
78 * WalSndOutBuffer is a work area in which the output message is constructed.
79 * It's used in just so we can avoid re-palloc'ing the buffer on each cycle.
80 * It must be of size 6 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE.
82 static char *WalSndOutBuffer;
83 static int WalSndOutHead; /* head of pending output */
84 static int WalSndOutTail; /* tail of pending output */
87 * These variables are used similarly to openLogFile/Id/Seg/Off,
88 * but for walsender to read the XLOG.
90 static int sendFile = -1;
91 static uint32 sendId = 0;
92 static uint32 sendSeg = 0;
93 static uint32 sendOff = 0;
96 * How far have we sent WAL already? This is also advertised in
97 * MyWalSnd->sentPtr. (Actually, this is the next WAL location to send.)
99 static XLogRecPtr sentPtr = {0, 0};
102 * How far have we completed replication already? This is also
103 * advertised in MyWalSnd->ackdPtr. This is not used in asynchronous
106 static XLogRecPtr ackdPtr = {0, 0};
108 /* Replication mode requested by connected standby */
109 static int rplMode = REPLICATION_MODE_ASYNC;
111 /* Flags set by signal handlers for later service in main loop */
112 static volatile sig_atomic_t got_SIGHUP = false;
113 static volatile sig_atomic_t shutdown_requested = false;
114 static volatile sig_atomic_t ready_to_stop = false;
116 /* Flag set by signal handler of backends for replication */
117 static volatile sig_atomic_t replication_done = false;
119 /* Signal handlers */
120 static void WalSndSigHupHandler(SIGNAL_ARGS);
121 static void WalSndShutdownHandler(SIGNAL_ARGS);
122 static void WalSndQuickDieHandler(SIGNAL_ARGS);
123 static void WalSndXLogSendHandler(SIGNAL_ARGS);
124 static void WalSndLastCycleHandler(SIGNAL_ARGS);
126 /* Prototypes for private functions */
127 static int WalSndLoop(void);
128 static void InitWalSnd(void);
129 static void WalSndHandshake(void);
130 static void WalSndKill(int code, Datum arg);
131 static void XLogRead(char *buf, XLogRecPtr recptr, Size nbytes);
132 static bool XLogSend(bool *caughtup, bool *pending);
133 static void ProcessStreamMsgs(StringInfo inMsg);
135 static void RegisterWalSndWaiter(BackendId backendId, XLogRecPtr record,
137 static void WakeupWalSndWaiters(XLogRecPtr record);
138 static XLogRecPtr GetOldestAckdPtr(void);
141 /* Main entry point for walsender process */
145 MemoryContext walsnd_context;
147 if (RecoveryInProgress())
149 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
150 errmsg("recovery is still in progress, can't accept WAL streaming connections")));
152 /* Create a per-walsender data structure in shared memory */
156 * Create a memory context that we will do all our work in. We do this so
157 * that we can reset the context during error recovery and thereby avoid
158 * possible memory leaks. Formerly this code just ran in
159 * TopMemoryContext, but resetting that would be a really bad idea.
161 * XXX: we don't actually attempt error recovery in walsender, we just
162 * close the connection and exit.
164 walsnd_context = AllocSetContextCreate(TopMemoryContext,
166 ALLOCSET_DEFAULT_MINSIZE,
167 ALLOCSET_DEFAULT_INITSIZE,
168 ALLOCSET_DEFAULT_MAXSIZE);
169 MemoryContextSwitchTo(walsnd_context);
171 /* Unblock signals (they were blocked when the postmaster forked us) */
172 PG_SETMASK(&UnBlockSig);
174 /* Tell the standby that walsender is ready for receiving commands */
175 ReadyForQuery(DestRemote);
177 /* Handle handshake messages before streaming */
180 /* Initialize shared memory status */
182 /* use volatile pointer to prevent code rearrangement */
183 volatile WalSnd *walsnd = MyWalSnd;
185 SpinLockAcquire(&walsnd->mutex);
186 walsnd->sentPtr = sentPtr;
187 SpinLockRelease(&walsnd->mutex);
190 /* Main loop of walsender */
195 * Execute commands from walreceiver, until we enter streaming mode.
198 WalSndHandshake(void)
200 StringInfoData input_message;
201 bool replication_started = false;
203 initStringInfo(&input_message);
205 while (!replication_started)
209 /* Wait for a command to arrive */
210 firstchar = pq_getbyte();
213 * Emergency bailout if postmaster has died. This is to avoid the
214 * necessity for manual cleanup of all postmaster children.
216 if (!PostmasterIsAlive(true))
220 * Check for any other interesting events that happened while we
226 ProcessConfigFile(PGC_SIGHUP);
229 if (firstchar != EOF)
232 * Read the message contents. This is expected to be done without
233 * blocking because we've been able to get message type code.
235 if (pq_getmessage(&input_message, 0))
236 firstchar = EOF; /* suitable message already logged */
239 /* Handle the very limited subset of commands expected in this phase */
244 case 'Q': /* Query message */
246 const char *query_string;
249 query_string = pq_getmsgstring(&input_message);
250 pq_getmsgend(&input_message);
252 if (strcmp(query_string, "IDENTIFY_SYSTEM") == 0)
259 * Reply with a result set with one row, two columns.
260 * First col is system ID, and second is timeline ID
263 snprintf(sysid, sizeof(sysid), UINT64_FORMAT,
264 GetSystemIdentifier());
265 snprintf(tli, sizeof(tli), "%u", ThisTimeLineID);
267 /* Send a RowDescription message */
268 pq_beginmessage(&buf, 'T');
269 pq_sendint(&buf, 2, 2); /* 2 fields */
272 pq_sendstring(&buf, "systemid"); /* col name */
273 pq_sendint(&buf, 0, 4); /* table oid */
274 pq_sendint(&buf, 0, 2); /* attnum */
275 pq_sendint(&buf, TEXTOID, 4); /* type oid */
276 pq_sendint(&buf, -1, 2); /* typlen */
277 pq_sendint(&buf, 0, 4); /* typmod */
278 pq_sendint(&buf, 0, 2); /* format code */
281 pq_sendstring(&buf, "timeline"); /* col name */
282 pq_sendint(&buf, 0, 4); /* table oid */
283 pq_sendint(&buf, 0, 2); /* attnum */
284 pq_sendint(&buf, INT4OID, 4); /* type oid */
285 pq_sendint(&buf, 4, 2); /* typlen */
286 pq_sendint(&buf, 0, 4); /* typmod */
287 pq_sendint(&buf, 0, 2); /* format code */
290 /* Send a DataRow message */
291 pq_beginmessage(&buf, 'D');
292 pq_sendint(&buf, 2, 2); /* # of columns */
293 pq_sendint(&buf, strlen(sysid), 4); /* col1 len */
294 pq_sendbytes(&buf, (char *) &sysid, strlen(sysid));
295 pq_sendint(&buf, strlen(tli), 4); /* col2 len */
296 pq_sendbytes(&buf, (char *) tli, strlen(tli));
299 /* Send CommandComplete and ReadyForQuery messages */
300 EndCommand("SELECT", DestRemote);
301 ReadyForQuery(DestRemote);
302 /* ReadyForQuery did pq_flush for us */
304 else if (sscanf(query_string, "START_REPLICATION %X/%X MODE %5s",
305 &recptr.xlogid, &recptr.xrecoff, rplModeStr) == 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(rplModeStr, entry->name) == 0)
334 rplMode = entry->val;
338 if (entry == NULL || entry->name == NULL)
340 (errcode(ERRCODE_PROTOCOL_VIOLATION),
341 errmsg("invalid replication mode: %s", rplModeStr)));
343 MyWalSnd->rplMode = rplMode;
345 /* Send a CopyXLogResponse message, and start streaming */
346 pq_beginmessage(&buf, 'W');
351 * Initialize positions to the received one, then the
352 * xlog records begin to be shipped from that position
354 sentPtr = ackdPtr = recptr;
356 /* break out of the loop */
357 replication_started = true;
362 (errcode(ERRCODE_PROTOCOL_VIOLATION),
363 errmsg("invalid standby query string: %s", query_string)));
369 /* standby is closing the connection */
373 /* standby disconnected unexpectedly */
375 (errcode(ERRCODE_PROTOCOL_VIOLATION),
376 errmsg("unexpected EOF on standby connection")));
381 (errcode(ERRCODE_PROTOCOL_VIOLATION),
382 errmsg("invalid standby handshake message type %d", firstchar)));
388 * Process messages received from the standby.
393 ProcessStreamMsgs(StringInfo inMsg)
397 /* Loop to process successive complete messages available */
400 unsigned char firstchar;
403 r = pq_getbyte_if_available(&firstchar);
406 /* unexpected error or EOF */
408 (errcode(ERRCODE_PROTOCOL_VIOLATION),
409 errmsg("unexpected EOF on standby connection")));
414 /* no data available without blocking */
418 /* Handle the very limited subset of commands expected in this phase */
421 case 'd': /* CopyData message */
423 unsigned char rpltype;
426 * Read the message contents. This is expected to be done without
427 * blocking because we've been able to get message type code.
429 if (pq_getmessage(inMsg, 0))
430 proc_exit(0); /* suitable message already logged */
432 /* Read the replication message type from CopyData message */
433 rpltype = pq_getmsgbyte(inMsg);
438 WalAckMessageData *msgdata;
440 msgdata = (WalAckMessageData *) pq_getmsgbytes(inMsg, sizeof(WalAckMessageData));
443 * Update local status.
445 * The ackd ptr received from standby should not
448 if (XLByteLE(ackdPtr, msgdata->ackEnd))
449 ackdPtr = msgdata->ackEnd;
452 (errmsg("replication completion location went back from "
454 ackdPtr.xlogid, ackdPtr.xrecoff,
455 msgdata->ackEnd.xlogid, msgdata->ackEnd.xrecoff)));
457 acked = true; /* also need to update shared position */
462 (errcode(ERRCODE_PROTOCOL_VIOLATION),
463 errmsg("invalid replication message type %d",
470 * 'X' means that the standby is closing down the socket.
477 (errcode(ERRCODE_PROTOCOL_VIOLATION),
478 errmsg("invalid standby closing message type %d",
485 /* use volatile pointer to prevent code rearrangement */
486 volatile WalSnd *walsnd = MyWalSnd;
488 SpinLockAcquire(&walsnd->mutex);
489 walsnd->ackdPtr = ackdPtr;
490 SpinLockRelease(&walsnd->mutex);
493 /* Wake up the backends that this walsender had been blocking */
494 WakeupWalSndWaiters(ackdPtr);
497 /* Main loop of walsender process */
501 StringInfoData input_message;
502 bool caughtup = false;
503 bool pending = false;
505 initStringInfo(&input_message);
508 * Allocate buffer that will be used for each output message. We do this
509 * just once to reduce palloc overhead. The buffer must be made large
510 * enough for maximum-sized messages.
512 WalSndOutBuffer = palloc(6 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE);
513 WalSndOutHead = WalSndOutTail = 0;
515 /* Loop forever, unless we get an error */
519 * Emergency bailout if postmaster has died. This is to avoid the
520 * necessity for manual cleanup of all postmaster children.
522 if (!PostmasterIsAlive(true))
525 /* Process any requests or signals received recently */
529 ProcessConfigFile(PGC_SIGHUP);
533 * When SIGUSR2 arrives, we send all outstanding logs up to the
534 * shutdown checkpoint record (i.e., the latest record) and exit.
538 if (!XLogSend(&caughtup, &pending))
540 if (caughtup && !pending)
541 shutdown_requested = true;
544 /* Normal exit from the walsender is here */
545 if (shutdown_requested)
547 /* Inform the standby that XLOG streaming was done */
548 pq_puttextmessage('C', "COPY 0");
555 * If we had sent all accumulated WAL in last round or could not
556 * flush pending WAL in output buffer because the socket was not
557 * writable, nap for the configured time before retrying.
559 if (caughtup || pending)
562 * Even if we wrote all the WAL that was available when we started
563 * sending, more might have arrived while we were sending this
564 * batch. We had the latch set while sending, so we have not
565 * received any signals from that time. Let's arm the latch
566 * again, and after that check that we're still up-to-date.
568 ResetLatch(&MyWalSnd->latch);
570 if (!XLogSend(&caughtup, &pending))
572 if ((caughtup || pending) && !got_SIGHUP && !ready_to_stop &&
580 * XXX: We don't really need the periodic wakeups anymore,
581 * WaitLatchOrSocket should reliably wake up as soon as
582 * something interesting happens.
586 * Check for replication timeout if it's enabled and we need to
587 * wait for the socket to be writable to flush pending WAL in
590 check_timeout = replication_timeout > 0 && pending;
592 sleeptime = replication_timeout;
594 sleeptime = WalSndDelay;
597 res = WaitLatchOrSocket(&MyWalSnd->latch, MyProcPort->sock,
598 true, (WalSndOutTail > 0),
601 if (res == 0 && check_timeout)
604 * Since typically expiration of replication timeout means
605 * communication problem, we don't send the error message
609 (errmsg("terminating walsender process due to replication timeout")));
614 /* Process messages received from the standby */
615 ProcessStreamMsgs(&input_message);
619 /* Attempt to send the log once every loop */
620 if (!XLogSend(&caughtup, &pending))
626 * Get here on send failure. Clean up and exit.
628 * Reset whereToSendOutput to prevent ereport from attempting to send any
629 * more messages to the standby.
631 if (whereToSendOutput == DestRemote)
632 whereToSendOutput = DestNone;
635 return 1; /* keep the compiler quiet */
638 /* Initialize a per-walsender data structure for this walsender process */
645 * WalSndCtl should be set up already (we inherit this by fork() or
646 * EXEC_BACKEND mechanism from the postmaster).
648 Assert(WalSndCtl != NULL);
649 Assert(MyWalSnd == NULL);
652 * Find a free walsender slot and reserve it. If this fails, we must be
653 * out of WalSnd structures.
655 for (i = 0; i < max_wal_senders; i++)
657 /* use volatile pointer to prevent code rearrangement */
658 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
660 SpinLockAcquire(&walsnd->mutex);
662 if (walsnd->pid != 0)
664 SpinLockRelease(&walsnd->mutex);
670 * Found a free slot. Reserve it for us.
672 walsnd->pid = MyProcPid;
673 MemSet(&walsnd->sentPtr, 0, sizeof(XLogRecPtr));
674 MemSet(&walsnd->ackdPtr, 0, sizeof(XLogRecPtr));
675 SpinLockRelease(&walsnd->mutex);
676 /* don't need the lock anymore */
677 OwnLatch((Latch *) &walsnd->latch);
678 MyWalSnd = (WalSnd *) walsnd;
683 if (MyWalSnd == NULL)
685 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
686 errmsg("number of requested standby connections "
687 "exceeds max_wal_senders (currently %d)",
690 /* Arrange to clean up at walsender exit */
691 on_shmem_exit(WalSndKill, 0);
694 /* Destroy the per-walsender data structure for this walsender process */
696 WalSndKill(int code, Datum arg)
698 Assert(MyWalSnd != NULL);
700 /* Wake up the backends that this walsender had been blocking */
701 MyWalSnd->rplMode = REPLICATION_MODE_ASYNC;
702 WakeupWalSndWaiters(GetOldestAckdPtr());
705 * Mark WalSnd struct no longer in use. Assume that no lock is required
709 DisownLatch(&MyWalSnd->latch);
711 /* WalSnd struct isn't mine anymore */
716 * Read 'nbytes' bytes from WAL into 'buf', starting at location 'recptr'
718 * XXX probably this should be improved to suck data directly from the
719 * WAL buffers when possible.
722 XLogRead(char *buf, XLogRecPtr recptr, Size nbytes)
724 XLogRecPtr startRecPtr = recptr;
725 char path[MAXPGPATH];
726 uint32 lastRemovedLog;
727 uint32 lastRemovedSeg;
737 startoff = recptr.xrecoff % XLogSegSize;
739 if (sendFile < 0 || !XLByteInSeg(recptr, sendId, sendSeg))
741 /* Switch to another logfile segment */
745 XLByteToSeg(recptr, sendId, sendSeg);
746 XLogFilePath(path, ThisTimeLineID, sendId, sendSeg);
748 sendFile = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
752 * If the file is not found, assume it's because the standby
753 * asked for a too old WAL segment that has already been
754 * removed or recycled.
758 char filename[MAXFNAMELEN];
760 XLogFileName(filename, ThisTimeLineID, sendId, sendSeg);
762 (errcode_for_file_access(),
763 errmsg("requested WAL segment %s has already been removed",
768 (errcode_for_file_access(),
769 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
770 path, sendId, sendSeg)));
775 /* Need to seek in the file? */
776 if (sendOff != startoff)
778 if (lseek(sendFile, (off_t) startoff, SEEK_SET) < 0)
780 (errcode_for_file_access(),
781 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
782 sendId, sendSeg, startoff)));
786 /* How many bytes are within this segment? */
787 if (nbytes > (XLogSegSize - startoff))
788 segbytes = XLogSegSize - startoff;
792 readbytes = read(sendFile, buf, segbytes);
795 (errcode_for_file_access(),
796 errmsg("could not read from log file %u, segment %u, offset %u, "
798 sendId, sendSeg, sendOff, (unsigned long) segbytes)));
800 /* Update state for read */
801 XLByteAdvance(recptr, readbytes);
803 sendOff += readbytes;
809 * After reading into the buffer, check that what we read was valid. We do
810 * this after reading, because even though the segment was present when we
811 * opened it, it might get recycled or removed while we read it. The
812 * read() succeeds in that case, but the data we tried to read might
813 * already have been overwritten with new WAL records.
815 XLogGetLastRemoved(&lastRemovedLog, &lastRemovedSeg);
816 XLByteToSeg(startRecPtr, log, seg);
817 if (log < lastRemovedLog ||
818 (log == lastRemovedLog && seg <= lastRemovedSeg))
820 char filename[MAXFNAMELEN];
822 XLogFileName(filename, ThisTimeLineID, log, seg);
824 (errcode_for_file_access(),
825 errmsg("requested WAL segment %s has already been removed",
831 * Read up to MAX_SEND_SIZE bytes of WAL that's been flushed to disk,
832 * but not yet sent to the client, and send it.
834 * If there is no unsent WAL remaining, *caughtup is set to true, otherwise
835 * *caughtup is set to false.
837 * If there is pending WAL in output buffer, *pending is set to true,
838 * otherwise *pending is set to false.
840 * Returns true if OK, false if trouble.
843 XLogSend(bool *caughtup, bool *pending)
845 XLogRecPtr SendRqstPtr;
847 static XLogRecPtr endptr;
851 WalDataMessageHeader msghdr;
853 /* Attempt to flush pending WAL in output buffer */
856 if (WalSndOutHead != WalSndOutTail)
858 res = pq_putbytes_if_writable(WalSndOutBuffer + WalSndOutHead,
859 WalSndOutTail - WalSndOutHead);
862 WalSndOutHead += res;
863 if (WalSndOutHead != WalSndOutTail)
867 res = pq_flush_if_writable();
877 * Attempt to send all data that's already been written out and fsync'd to
878 * disk. We cannot go further than what's been written out given the
879 * current implementation of XLogRead(). And in any case it's unsafe to
880 * send WAL that is not securely down to disk on the master: if the master
881 * subsequently crashes and restarts, slaves must not have applied any WAL
882 * that gets lost on the master.
884 SendRqstPtr = GetFlushRecPtr();
886 /* Quick exit if nothing to do */
887 if (XLByteLE(SendRqstPtr, sentPtr))
894 * Figure out how much to send in one message. If there's no more than
895 * MAX_SEND_SIZE bytes to send, send everything. Otherwise send
896 * MAX_SEND_SIZE bytes, but round back to logfile or page boundary.
898 * The rounding is not only for performance reasons. Walreceiver relies on
899 * the fact that we never split a WAL record across two messages. Since a
900 * long WAL record is split at page boundary into continuation records,
901 * page boundary is always a safe cut-off point. We also assume that
902 * SendRqstPtr never points to the middle of a WAL record.
905 if (startptr.xrecoff >= XLogFileSize)
908 * crossing a logid boundary, skip the non-existent last log segment
909 * in previous logical log file.
911 startptr.xlogid += 1;
912 startptr.xrecoff = 0;
916 XLByteAdvance(endptr, MAX_SEND_SIZE);
917 if (endptr.xlogid != startptr.xlogid)
919 /* Don't cross a logfile boundary within one message */
920 Assert(endptr.xlogid == startptr.xlogid + 1);
921 endptr.xlogid = startptr.xlogid;
922 endptr.xrecoff = XLogFileSize;
925 /* if we went beyond SendRqstPtr, back off */
926 if (XLByteLE(SendRqstPtr, endptr))
928 endptr = SendRqstPtr;
933 /* round down to page boundary. */
934 endptr.xrecoff -= (endptr.xrecoff % XLOG_BLCKSZ);
938 nbytes = endptr.xrecoff - startptr.xrecoff;
939 Assert(nbytes <= MAX_SEND_SIZE);
942 * OK to read and send the slice.
944 WalSndOutBuffer[0] = 'd';
945 WalSndOutBuffer[5] = 'w';
947 WalSndOutTail = 6 + sizeof(WalDataMessageHeader) + nbytes;
949 n32 = htonl((uint32) WalSndOutTail - 1);
950 memcpy(WalSndOutBuffer + 1, &n32, 4);
953 * Read the log directly into the output buffer to avoid extra memcpy
956 XLogRead(WalSndOutBuffer + 6 + sizeof(WalDataMessageHeader), startptr, nbytes);
959 * We fill the message header last so that the send timestamp is taken as
962 msghdr.dataStart = startptr;
963 msghdr.walEnd = SendRqstPtr;
964 msghdr.sendTime = GetCurrentTimestamp();
966 memcpy(WalSndOutBuffer + 6, &msghdr, sizeof(WalDataMessageHeader));
968 res = pq_putbytes_if_writable(WalSndOutBuffer, WalSndOutTail);
973 if (WalSndOutHead != WalSndOutTail)
980 /* Flush pending output to the client */
981 res = pq_flush_if_writable();
992 WalSndOutHead = WalSndOutTail = 0;
997 /* Update shared memory status */
999 /* use volatile pointer to prevent code rearrangement */
1000 volatile WalSnd *walsnd = MyWalSnd;
1002 SpinLockAcquire(&walsnd->mutex);
1003 walsnd->sentPtr = sentPtr;
1004 SpinLockRelease(&walsnd->mutex);
1007 /* Report progress of XLOG streaming in PS display */
1008 if (update_process_title)
1010 char activitymsg[50];
1012 snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%X",
1013 sentPtr.xlogid, sentPtr.xrecoff);
1014 set_ps_display(activitymsg, false);
1020 /* SIGHUP: set flag to re-read config file at next convenient time */
1022 WalSndSigHupHandler(SIGNAL_ARGS)
1026 SetLatch(&MyWalSnd->latch);
1029 /* SIGTERM: set flag to shut down */
1031 WalSndShutdownHandler(SIGNAL_ARGS)
1033 shutdown_requested = true;
1035 SetLatch(&MyWalSnd->latch);
1039 * WalSndQuickDieHandler() occurs when signalled SIGQUIT by the postmaster.
1041 * Some backend has bought the farm,
1042 * so we need to stop what we're doing and exit.
1045 WalSndQuickDieHandler(SIGNAL_ARGS)
1047 PG_SETMASK(&BlockSig);
1050 * We DO NOT want to run proc_exit() callbacks -- we're here because
1051 * shared memory may be corrupted, so we don't want to try to clean up our
1052 * transaction. Just nail the windows shut and get out of town. Now that
1053 * there's an atexit callback to prevent third-party code from breaking
1054 * things by calling exit() directly, we have to reset the callbacks
1055 * explicitly to make this work as intended.
1060 * Note we do exit(2) not exit(0). This is to force the postmaster into a
1061 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
1062 * backend. This is necessary precisely because we don't clean up our
1063 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
1064 * should ensure the postmaster sees this as a crash, too, but no harm in
1065 * being doubly sure.)
1070 /* SIGUSR1: set flag to send WAL records */
1072 WalSndXLogSendHandler(SIGNAL_ARGS)
1074 latch_sigusr1_handler();
1077 /* SIGUSR2: set flag to do a last cycle and shut down afterwards */
1079 WalSndLastCycleHandler(SIGNAL_ARGS)
1081 ready_to_stop = true;
1083 SetLatch(&MyWalSnd->latch);
1086 /* Set up signal handlers */
1090 /* Set up signal handlers */
1091 pqsignal(SIGHUP, WalSndSigHupHandler); /* set flag to read config
1093 pqsignal(SIGINT, SIG_IGN); /* not used */
1094 pqsignal(SIGTERM, WalSndShutdownHandler); /* request shutdown */
1095 pqsignal(SIGQUIT, WalSndQuickDieHandler); /* hard crash time */
1096 pqsignal(SIGALRM, SIG_IGN);
1097 pqsignal(SIGPIPE, SIG_IGN);
1098 pqsignal(SIGUSR1, WalSndXLogSendHandler); /* request WAL sending */
1099 pqsignal(SIGUSR2, WalSndLastCycleHandler); /* request a last cycle and
1102 /* Reset some signals that are accepted by postmaster but not here */
1103 pqsignal(SIGCHLD, SIG_DFL);
1104 pqsignal(SIGTTIN, SIG_DFL);
1105 pqsignal(SIGTTOU, SIG_DFL);
1106 pqsignal(SIGCONT, SIG_DFL);
1107 pqsignal(SIGWINCH, SIG_DFL);
1110 /* Report shared-memory space needed by WalSndShmemInit */
1112 WalSndShmemSize(void)
1116 size = offsetof(WalSndCtlData, walsnds);
1117 size = add_size(size, mul_size(max_wal_senders, sizeof(WalSnd)));
1120 * If replication is enabled, we have a data structure called
1121 * WalSndWaiters, created in shared memory.
1123 if (max_wal_senders > 0)
1124 size = add_size(size, mul_size(MaxBackends, sizeof(WalSndWaiter)));
1129 /* Allocate and initialize walsender-related shared memory */
1131 WalSndShmemInit(void)
1135 Size size = add_size(offsetof(WalSndCtlData, walsnds),
1136 mul_size(max_wal_senders, sizeof(WalSnd)));
1138 WalSndCtl = (WalSndCtlData *)
1139 ShmemInitStruct("Wal Sender Ctl", size, &found);
1143 /* First time through, so initialize */
1144 MemSet(WalSndCtl, 0, size);
1146 for (i = 0; i < max_wal_senders; i++)
1148 WalSnd *walsnd = &WalSndCtl->walsnds[i];
1150 SpinLockInit(&walsnd->mutex);
1151 InitSharedLatch(&walsnd->latch);
1155 /* Create or attach to the WalSndWaiters array too, if needed */
1156 if (max_wal_senders > 0)
1158 WalSndWaiters = (WalSndWaiter *)
1159 ShmemInitStruct("WalSndWaiters",
1160 mul_size(MaxBackends, sizeof(WalSndWaiter)),
1162 WalSndCtl->maxWaiters = MaxBackends;
1166 /* Wake up all walsenders */
1172 for (i = 0; i < max_wal_senders; i++)
1173 SetLatch(&WalSndCtl->walsnds[i].latch);
1177 * Ensure that replication has been completed up to the given position.
1180 WaitXLogSend(XLogRecPtr record)
1183 bool mustwait = false;
1185 Assert(max_wal_senders > 0);
1187 for (i = 0; i < max_wal_senders; i++)
1189 /* use volatile pointer to prevent code rearrangement */
1190 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1193 /* Don't need to wait for asynchronous walsender */
1194 if (walsnd->pid == 0 ||
1195 walsnd->rplMode <= REPLICATION_MODE_ASYNC)
1198 SpinLockAcquire(&walsnd->mutex);
1199 recptr = walsnd->ackdPtr;
1200 SpinLockRelease(&walsnd->mutex);
1202 if (recptr.xlogid == 0 && recptr.xrecoff == 0)
1205 /* Quick exit if already known replicated */
1206 if (XLByteLE(record, recptr))
1213 * Don't need to wait for replication if there is no synchronous
1220 * Register myself into the wait list and sleep until replication
1221 * has been completed up to the given position and the walsender
1224 * If replication has been completed up to the latest position
1225 * before the registration, walsender might be unable to send the
1226 * signal immediately. We must wake up the walsender after the
1229 ResetLatch(&MyProc->latch);
1230 RegisterWalSndWaiter(MyBackendId, record, &MyProc->latch);
1235 WaitLatch(&MyProc->latch, 1000000L);
1237 /* If done already, we finish waiting */
1238 if (replication_done)
1240 replication_done = false;
1247 * Register the given backend into the wait list.
1250 RegisterWalSndWaiter(BackendId backendId, XLogRecPtr record, Latch *latch)
1252 /* use volatile pointer to prevent code rearrangement */
1253 volatile WalSndCtlData *walsndctl = WalSndCtl;
1257 LWLockAcquire(WalSndWaiterLock, LW_EXCLUSIVE);
1259 /* Out of slots. This should not happen. */
1260 if (walsndctl->numWaiters + 1 > walsndctl->maxWaiters)
1261 elog(PANIC, "out of replication waiters slots");
1264 * The given position is expected to be relatively new in the
1265 * wait list. Since the entries in the list are sorted in an
1266 * increasing order of XLogRecPtr, we can shorten the time it
1267 * takes to find an insert slot by scanning the list backwards.
1269 for (i = walsndctl->numWaiters; i > 0; i--)
1271 if (XLByteLE(WalSndWaiters[i - 1].record, record))
1276 /* Shuffle the list if needed */
1278 memmove(&WalSndWaiters[i + 1], &WalSndWaiters[i],
1279 count * sizeof(WalSndWaiter));
1281 WalSndWaiters[i].backendId = backendId;
1282 WalSndWaiters[i].record = record;
1283 WalSndWaiters[i].latch = latch;
1284 walsndctl->numWaiters++;
1286 LWLockRelease(WalSndWaiterLock);
1290 * Wake up the backends waiting until replication has been completed
1291 * up to the position older than or equal to the given one.
1293 * Wake up all waiters if InvalidXLogRecPtr is given.
1296 WakeupWalSndWaiters(XLogRecPtr record)
1298 /* use volatile pointer to prevent code rearrangement */
1299 volatile WalSndCtlData *walsndctl = WalSndCtl;
1302 bool all_wakeup = (record.xlogid == 0 && record.xrecoff == 0);
1304 LWLockAcquire(WalSndWaiterLock, LW_EXCLUSIVE);
1306 for (i = 0; i < walsndctl->numWaiters; i++)
1308 /* use volatile pointer to prevent code rearrangement */
1309 volatile WalSndWaiter *waiter = &WalSndWaiters[i];
1311 if (all_wakeup || XLByteLE(waiter->record, record))
1313 SetProcLatch(waiter->latch, PROCSIG_REPLICATION_INTERRUPT,
1320 * If the backend waiting for the Ack position newer than
1321 * the given one is found, we don't need to search the wait
1322 * list any more. This is because the waiters in the list
1323 * are guaranteed to be sorted in an increasing order of
1330 /* If there are still some waiters, left-justify them in the list */
1331 walsndctl->numWaiters -= count;
1332 if (walsndctl->numWaiters > 0 && count > 0)
1333 memmove(&WalSndWaiters[0], &WalSndWaiters[i],
1334 walsndctl->numWaiters * sizeof(WalSndWaiter));
1336 LWLockRelease(WalSndWaiterLock);
1340 * Returns the oldest Ack position in synchronous walsenders. Or
1341 * InvalidXLogRecPtr if none.
1344 GetOldestAckdPtr(void)
1346 XLogRecPtr oldest = {0, 0};
1350 for (i = 0; i < max_wal_senders; i++)
1352 /* use volatile pointer to prevent code rearrangement */
1353 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1357 * Ignore the Ack position that asynchronous walsender has
1358 * since it has never received any Ack.
1360 if (walsnd->pid == 0 ||
1361 walsnd->rplMode <= REPLICATION_MODE_ASYNC)
1364 SpinLockAcquire(&walsnd->mutex);
1365 recptr = walsnd->ackdPtr;
1366 SpinLockRelease(&walsnd->mutex);
1369 * Ignore the Ack position that the walsender which has not
1370 * received any Ack yet has.
1372 if (recptr.xlogid == 0 && recptr.xrecoff == 0)
1375 if (!found || XLByteLT(recptr, oldest))
1383 * This is called when PROCSIG_REPLICATION_INTERRUPT is received.
1386 HandleReplicationInterrupt(void)
1388 replication_done = true;