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-2011, PostgreSQL Global Development Group
31 * src/backend/replication/walsender.c
33 *-------------------------------------------------------------------------
41 #include "access/xlog_internal.h"
42 #include "access/transam.h"
43 #include "catalog/pg_type.h"
44 #include "libpq/libpq.h"
45 #include "libpq/pqformat.h"
46 #include "libpq/pqsignal.h"
47 #include "miscadmin.h"
48 #include "replication/basebackup.h"
49 #include "replication/replnodes.h"
50 #include "replication/walprotocol.h"
51 #include "replication/walsender.h"
52 #include "storage/fd.h"
53 #include "storage/ipc.h"
54 #include "storage/pmsignal.h"
55 #include "storage/proc.h"
56 #include "storage/procarray.h"
57 #include "tcop/tcopprot.h"
58 #include "utils/builtins.h"
59 #include "utils/guc.h"
60 #include "utils/memutils.h"
61 #include "utils/ps_status.h"
62 #include "utils/resowner.h"
65 /* Array of WalSnds in shared memory */
66 WalSndCtlData *WalSndCtl = NULL;
68 /* My slot in the shared memory array */
69 WalSnd *MyWalSnd = NULL;
72 bool am_walsender = false; /* Am I a walsender process ? */
74 /* User-settable parameters for walsender */
75 int max_wal_senders = 0; /* the maximum number of concurrent walsenders */
76 int WalSndDelay = 1000; /* max sleep time between some actions */
79 * These variables are used similarly to openLogFile/Id/Seg/Off,
80 * but for walsender to read the XLOG.
82 static int sendFile = -1;
83 static uint32 sendId = 0;
84 static uint32 sendSeg = 0;
85 static uint32 sendOff = 0;
88 * How far have we sent WAL already? This is also advertised in
89 * MyWalSnd->sentPtr. (Actually, this is the next WAL location to send.)
91 static XLogRecPtr sentPtr = {0, 0};
94 * Buffer for processing reply messages.
96 static StringInfoData reply_message;
98 /* Flags set by signal handlers for later service in main loop */
99 static volatile sig_atomic_t got_SIGHUP = false;
100 volatile sig_atomic_t walsender_shutdown_requested = false;
101 volatile sig_atomic_t walsender_ready_to_stop = false;
103 /* Signal handlers */
104 static void WalSndSigHupHandler(SIGNAL_ARGS);
105 static void WalSndShutdownHandler(SIGNAL_ARGS);
106 static void WalSndQuickDieHandler(SIGNAL_ARGS);
107 static void WalSndXLogSendHandler(SIGNAL_ARGS);
108 static void WalSndLastCycleHandler(SIGNAL_ARGS);
110 /* Prototypes for private functions */
111 static bool HandleReplicationCommand(const char *cmd_string);
112 static int WalSndLoop(void);
113 static void InitWalSnd(void);
114 static void WalSndHandshake(void);
115 static void WalSndKill(int code, Datum arg);
116 static bool XLogSend(char *msgbuf, bool *caughtup);
117 static void IdentifySystem(void);
118 static void StartReplication(StartReplicationCmd * cmd);
119 static void ProcessStandbyMessage(void);
120 static void ProcessStandbyReplyMessage(void);
121 static void ProcessStandbyHSFeedbackMessage(void);
122 static void ProcessRepliesIfAny(void);
125 /* Main entry point for walsender process */
129 MemoryContext walsnd_context;
131 if (RecoveryInProgress())
133 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
134 errmsg("recovery is still in progress, can't accept WAL streaming connections")));
136 /* Create a per-walsender data structure in shared memory */
140 * Create a memory context that we will do all our work in. We do this so
141 * that we can reset the context during error recovery and thereby avoid
142 * possible memory leaks. Formerly this code just ran in
143 * TopMemoryContext, but resetting that would be a really bad idea.
145 * XXX: we don't actually attempt error recovery in walsender, we just
146 * close the connection and exit.
148 walsnd_context = AllocSetContextCreate(TopMemoryContext,
150 ALLOCSET_DEFAULT_MINSIZE,
151 ALLOCSET_DEFAULT_INITSIZE,
152 ALLOCSET_DEFAULT_MAXSIZE);
153 MemoryContextSwitchTo(walsnd_context);
155 /* Set up resource owner */
156 CurrentResourceOwner = ResourceOwnerCreate(NULL, "walsender top-level resource owner");
158 /* Unblock signals (they were blocked when the postmaster forked us) */
159 PG_SETMASK(&UnBlockSig);
161 /* Tell the standby that walsender is ready for receiving commands */
162 ReadyForQuery(DestRemote);
164 /* Handle handshake messages before streaming */
167 /* Initialize shared memory status */
169 /* use volatile pointer to prevent code rearrangement */
170 volatile WalSnd *walsnd = MyWalSnd;
172 SpinLockAcquire(&walsnd->mutex);
173 walsnd->sentPtr = sentPtr;
174 SpinLockRelease(&walsnd->mutex);
179 /* Main loop of walsender */
184 * Execute commands from walreceiver, until we enter streaming mode.
187 WalSndHandshake(void)
189 StringInfoData input_message;
190 bool replication_started = false;
192 initStringInfo(&input_message);
194 while (!replication_started)
198 WalSndSetState(WALSNDSTATE_STARTUP);
199 set_ps_display("idle", false);
201 /* Wait for a command to arrive */
202 firstchar = pq_getbyte();
205 * Emergency bailout if postmaster has died. This is to avoid the
206 * necessity for manual cleanup of all postmaster children.
208 if (!PostmasterIsAlive(true))
212 * Check for any other interesting events that happened while we
218 ProcessConfigFile(PGC_SIGHUP);
221 if (firstchar != EOF)
224 * Read the message contents. This is expected to be done without
225 * blocking because we've been able to get message type code.
227 if (pq_getmessage(&input_message, 0))
228 firstchar = EOF; /* suitable message already logged */
231 /* Handle the very limited subset of commands expected in this phase */
234 case 'Q': /* Query message */
236 const char *query_string;
238 query_string = pq_getmsgstring(&input_message);
239 pq_getmsgend(&input_message);
241 if (HandleReplicationCommand(query_string))
242 replication_started = true;
247 /* standby is closing the connection */
251 /* standby disconnected unexpectedly */
253 (errcode(ERRCODE_PROTOCOL_VIOLATION),
254 errmsg("unexpected EOF on standby connection")));
259 (errcode(ERRCODE_PROTOCOL_VIOLATION),
260 errmsg("invalid standby handshake message type %d", firstchar)));
274 char xpos[MAXFNAMELEN];
278 * Reply with a result set with one row, three columns. First col is system
279 * ID, second is timeline ID, and third is current xlog location.
282 snprintf(sysid, sizeof(sysid), UINT64_FORMAT,
283 GetSystemIdentifier());
284 snprintf(tli, sizeof(tli), "%u", ThisTimeLineID);
286 logptr = GetInsertRecPtr();
288 snprintf(xpos, sizeof(xpos), "%X/%X",
289 logptr.xlogid, logptr.xrecoff);
291 /* Send a RowDescription message */
292 pq_beginmessage(&buf, 'T');
293 pq_sendint(&buf, 3, 2); /* 3 fields */
296 pq_sendstring(&buf, "systemid"); /* col name */
297 pq_sendint(&buf, 0, 4); /* table oid */
298 pq_sendint(&buf, 0, 2); /* attnum */
299 pq_sendint(&buf, TEXTOID, 4); /* type oid */
300 pq_sendint(&buf, -1, 2); /* typlen */
301 pq_sendint(&buf, 0, 4); /* typmod */
302 pq_sendint(&buf, 0, 2); /* format code */
305 pq_sendstring(&buf, "timeline"); /* col name */
306 pq_sendint(&buf, 0, 4); /* table oid */
307 pq_sendint(&buf, 0, 2); /* attnum */
308 pq_sendint(&buf, INT4OID, 4); /* type oid */
309 pq_sendint(&buf, 4, 2); /* typlen */
310 pq_sendint(&buf, 0, 4); /* typmod */
311 pq_sendint(&buf, 0, 2); /* format code */
314 pq_sendstring(&buf, "xlogpos");
315 pq_sendint(&buf, 0, 4);
316 pq_sendint(&buf, 0, 2);
317 pq_sendint(&buf, TEXTOID, 4);
318 pq_sendint(&buf, -1, 2);
319 pq_sendint(&buf, 0, 4);
320 pq_sendint(&buf, 0, 2);
323 /* Send a DataRow message */
324 pq_beginmessage(&buf, 'D');
325 pq_sendint(&buf, 3, 2); /* # of columns */
326 pq_sendint(&buf, strlen(sysid), 4); /* col1 len */
327 pq_sendbytes(&buf, (char *) &sysid, strlen(sysid));
328 pq_sendint(&buf, strlen(tli), 4); /* col2 len */
329 pq_sendbytes(&buf, (char *) tli, strlen(tli));
330 pq_sendint(&buf, strlen(xpos), 4); /* col3 len */
331 pq_sendbytes(&buf, (char *) xpos, strlen(xpos));
335 /* Send CommandComplete and ReadyForQuery messages */
336 EndCommand("SELECT", DestRemote);
337 ReadyForQuery(DestRemote);
338 /* ReadyForQuery did pq_flush for us */
345 StartReplication(StartReplicationCmd * cmd)
350 * Let postmaster know that we're streaming. Once we've declared us as
351 * a WAL sender process, postmaster will let us outlive the bgwriter and
352 * kill us last in the shutdown sequence, so we get a chance to stream
353 * all remaining WAL at shutdown, including the shutdown checkpoint.
354 * Note that there's no going back, and we mustn't write any WAL records
357 MarkPostmasterChildWalSender();
360 * Check that we're logging enough information in the WAL for
363 * NOTE: This only checks the current value of wal_level. Even if the
364 * current setting is not 'minimal', there can be old WAL in the pg_xlog
365 * directory that was created with 'minimal'. So this is not bulletproof,
366 * the purpose is just to give a user-friendly error message that hints
367 * how to configure the system correctly.
369 if (wal_level == WAL_LEVEL_MINIMAL)
371 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
372 errmsg("standby connections not allowed because wal_level=minimal")));
375 * When we first start replication the standby will be behind the primary.
376 * For some applications, for example, synchronous replication, it is
377 * important to have a clear state for this initial catchup mode, so we
378 * can trigger actions when we change streaming state later. We may stay
379 * in this state for a long time, which is exactly why we want to be
380 * able to monitor whether or not we are still here.
382 WalSndSetState(WALSNDSTATE_CATCHUP);
384 /* Send a CopyBothResponse message, and start streaming */
385 pq_beginmessage(&buf, 'W');
386 pq_sendbyte(&buf, 0);
387 pq_sendint(&buf, 0, 2);
392 * Initialize position to the received one, then the xlog records begin to
393 * be shipped from that position
395 sentPtr = cmd->startpoint;
399 * Execute an incoming replication command.
402 HandleReplicationCommand(const char *cmd_string)
404 bool replication_started = false;
407 MemoryContext cmd_context;
408 MemoryContext old_context;
410 elog(DEBUG1, "received replication command: %s", cmd_string);
412 cmd_context = AllocSetContextCreate(CurrentMemoryContext,
413 "Replication command context",
414 ALLOCSET_DEFAULT_MINSIZE,
415 ALLOCSET_DEFAULT_INITSIZE,
416 ALLOCSET_DEFAULT_MAXSIZE);
417 old_context = MemoryContextSwitchTo(cmd_context);
419 replication_scanner_init(cmd_string);
420 parse_rc = replication_yyparse();
423 (errcode(ERRCODE_SYNTAX_ERROR),
424 (errmsg_internal("replication command parser returned %d",
427 cmd_node = replication_parse_result;
429 switch (cmd_node->type)
431 case T_IdentifySystemCmd:
435 case T_StartReplicationCmd:
436 StartReplication((StartReplicationCmd *) cmd_node);
438 /* break out of the loop */
439 replication_started = true;
442 case T_BaseBackupCmd:
443 SendBaseBackup((BaseBackupCmd *) cmd_node);
445 /* Send CommandComplete and ReadyForQuery messages */
446 EndCommand("SELECT", DestRemote);
447 ReadyForQuery(DestRemote);
448 /* ReadyForQuery did pq_flush for us */
453 (errcode(ERRCODE_PROTOCOL_VIOLATION),
454 errmsg("invalid standby query string: %s", cmd_string)));
458 MemoryContextSwitchTo(old_context);
459 MemoryContextDelete(cmd_context);
461 return replication_started;
465 * Check if the remote end has closed the connection.
468 ProcessRepliesIfAny(void)
470 unsigned char firstchar;
475 r = pq_getbyte_if_available(&firstchar);
478 /* unexpected error or EOF */
480 (errcode(ERRCODE_PROTOCOL_VIOLATION),
481 errmsg("unexpected EOF on standby connection")));
486 /* no data available without blocking */
490 /* Handle the very limited subset of commands expected in this phase */
494 * 'd' means a standby reply wrapped in a CopyData packet.
497 ProcessStandbyMessage();
501 * 'X' means that the standby is closing down the socket.
508 (errcode(ERRCODE_PROTOCOL_VIOLATION),
509 errmsg("invalid standby closing message type %d",
516 * Process a status update message received from standby.
519 ProcessStandbyMessage(void)
523 resetStringInfo(&reply_message);
526 * Read the message contents.
528 if (pq_getmessage(&reply_message, 0))
531 (errcode(ERRCODE_PROTOCOL_VIOLATION),
532 errmsg("unexpected EOF on standby connection")));
537 * Check message type from the first byte. At the moment, there is only
540 msgtype = pq_getmsgbyte(&reply_message);
545 ProcessStandbyReplyMessage();
549 ProcessStandbyHSFeedbackMessage();
554 (errcode(ERRCODE_PROTOCOL_VIOLATION),
555 errmsg("unexpected message type %c", msgtype)));
561 * Regular reply from standby advising of WAL positions on standby server.
564 ProcessStandbyReplyMessage(void)
566 StandbyReplyMessage reply;
568 pq_copymsgbytes(&reply_message, (char *) &reply, sizeof(StandbyReplyMessage));
570 elog(DEBUG2, "write %X/%X flush %X/%X apply %X/%X",
571 reply.write.xlogid, reply.write.xrecoff,
572 reply.flush.xlogid, reply.flush.xrecoff,
573 reply.apply.xlogid, reply.apply.xrecoff);
576 * Update shared state for this WalSender process
577 * based on reply data from standby.
580 /* use volatile pointer to prevent code rearrangement */
581 volatile WalSnd *walsnd = MyWalSnd;
583 SpinLockAcquire(&walsnd->mutex);
584 walsnd->write = reply.write;
585 walsnd->flush = reply.flush;
586 walsnd->apply = reply.apply;
587 SpinLockRelease(&walsnd->mutex);
590 SyncRepReleaseWaiters();
594 * Hot Standby feedback
597 ProcessStandbyHSFeedbackMessage(void)
599 StandbyHSFeedbackMessage reply;
600 TransactionId newxmin = InvalidTransactionId;
602 pq_copymsgbytes(&reply_message, (char *) &reply, sizeof(StandbyHSFeedbackMessage));
604 elog(DEBUG2, "hot standby feedback xmin %u epoch %u",
609 * Update the WalSender's proc xmin to allow it to be visible
610 * to snapshots. This will hold back the removal of dead rows
611 * and thereby prevent the generation of cleanup conflicts
612 * on the standby server.
614 if (TransactionIdIsValid(reply.xmin))
616 TransactionId nextXid;
618 bool epochOK = false;
620 GetNextXidAndEpoch(&nextXid, &nextEpoch);
623 * Epoch of oldestXmin should be same as standby or
624 * if the counter has wrapped, then one less than reply.
626 if (reply.xmin <= nextXid)
628 if (reply.epoch == nextEpoch)
633 if (nextEpoch > 0 && reply.epoch == nextEpoch - 1)
638 * Feedback from standby must not go backwards, nor should it go
639 * forwards further than our most recent xid.
641 if (epochOK && TransactionIdPrecedesOrEquals(reply.xmin, nextXid))
643 if (!TransactionIdIsValid(MyProc->xmin))
645 TransactionId oldestXmin = GetOldestXmin(true, true);
646 if (TransactionIdPrecedes(oldestXmin, reply.xmin))
647 newxmin = reply.xmin;
649 newxmin = oldestXmin;
653 if (TransactionIdPrecedes(MyProc->xmin, reply.xmin))
654 newxmin = reply.xmin;
656 newxmin = MyProc->xmin; /* stay the same */
662 * Grab the ProcArrayLock to set xmin, or invalidate for bad reply
664 if (MyProc->xmin != newxmin)
666 LWLockAcquire(ProcArrayLock, LW_SHARED);
667 MyProc->xmin = newxmin;
668 LWLockRelease(ProcArrayLock);
672 /* Main loop of walsender process */
676 char *output_message;
677 bool caughtup = false;
680 * Allocate buffer that will be used for each output message. We do this
681 * just once to reduce palloc overhead. The buffer must be made large
682 * enough for maximum-sized messages.
684 output_message = palloc(1 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE);
687 * Allocate buffer that will be used for processing reply messages. As
688 * above, do this just once to reduce palloc overhead.
690 initStringInfo(&reply_message);
692 /* Loop forever, unless we get an error */
696 * Emergency bailout if postmaster has died. This is to avoid the
697 * necessity for manual cleanup of all postmaster children.
699 if (!PostmasterIsAlive(true))
702 /* Process any requests or signals received recently */
706 ProcessConfigFile(PGC_SIGHUP);
711 * When SIGUSR2 arrives, we send all outstanding logs up to the
712 * shutdown checkpoint record (i.e., the latest record) and exit.
714 if (walsender_ready_to_stop)
716 if (!XLogSend(output_message, &caughtup))
718 ProcessRepliesIfAny();
720 walsender_shutdown_requested = true;
723 /* Normal exit from the walsender is here */
724 if (walsender_shutdown_requested)
726 /* Inform the standby that XLOG streaming was done */
727 pq_puttextmessage('C', "COPY 0");
734 * If we had sent all accumulated WAL in last round, nap for the
735 * configured time before retrying.
740 * Even if we wrote all the WAL that was available when we started
741 * sending, more might have arrived while we were sending this
742 * batch. We had the latch set while sending, so we have not
743 * received any signals from that time. Let's arm the latch
744 * again, and after that check that we're still up-to-date.
746 ResetLatch(&MyWalSnd->latch);
748 if (!XLogSend(output_message, &caughtup))
750 if (caughtup && !got_SIGHUP && !walsender_ready_to_stop && !walsender_shutdown_requested)
753 * XXX: We don't really need the periodic wakeups anymore,
754 * WaitLatchOrSocket should reliably wake up as soon as
755 * something interesting happens.
759 WaitLatchOrSocket(&MyWalSnd->latch, MyProcPort->sock,
760 WalSndDelay * 1000L);
765 /* Attempt to send the log once every loop */
766 if (!XLogSend(output_message, &caughtup))
771 * If we're in catchup state, see if its time to move to streaming.
772 * This is an important state change for users, since before this
773 * point data loss might occur if the primary dies and we need to
774 * failover to the standby. The state change is also important for
775 * synchronous replication, since commits that started to wait at
776 * that point might wait for some time.
778 if (MyWalSnd->state == WALSNDSTATE_CATCHUP && caughtup)
781 (errmsg("standby \"%s\" has now caught up with primary",
783 WalSndSetState(WALSNDSTATE_STREAMING);
786 ProcessRepliesIfAny();
790 * Get here on send failure. Clean up and exit.
792 * Reset whereToSendOutput to prevent ereport from attempting to send any
793 * more messages to the standby.
795 if (whereToSendOutput == DestRemote)
796 whereToSendOutput = DestNone;
799 return 1; /* keep the compiler quiet */
802 /* Initialize a per-walsender data structure for this walsender process */
809 * WalSndCtl should be set up already (we inherit this by fork() or
810 * EXEC_BACKEND mechanism from the postmaster).
812 Assert(WalSndCtl != NULL);
813 Assert(MyWalSnd == NULL);
816 * Find a free walsender slot and reserve it. If this fails, we must be
817 * out of WalSnd structures.
819 for (i = 0; i < max_wal_senders; i++)
821 /* use volatile pointer to prevent code rearrangement */
822 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
824 SpinLockAcquire(&walsnd->mutex);
826 if (walsnd->pid != 0)
828 SpinLockRelease(&walsnd->mutex);
834 * Found a free slot. Reserve it for us.
836 walsnd->pid = MyProcPid;
837 MemSet(&walsnd->sentPtr, 0, sizeof(XLogRecPtr));
838 walsnd->state = WALSNDSTATE_STARTUP;
839 SpinLockRelease(&walsnd->mutex);
840 /* don't need the lock anymore */
841 OwnLatch((Latch *) &walsnd->latch);
842 MyWalSnd = (WalSnd *) walsnd;
847 if (MyWalSnd == NULL)
849 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
850 errmsg("number of requested standby connections "
851 "exceeds max_wal_senders (currently %d)",
854 /* Arrange to clean up at walsender exit */
855 on_shmem_exit(WalSndKill, 0);
858 /* Destroy the per-walsender data structure for this walsender process */
860 WalSndKill(int code, Datum arg)
862 Assert(MyWalSnd != NULL);
865 * Mark WalSnd struct no longer in use. Assume that no lock is required
869 DisownLatch(&MyWalSnd->latch);
871 /* WalSnd struct isn't mine anymore */
876 * Read 'nbytes' bytes from WAL into 'buf', starting at location 'recptr'
878 * XXX probably this should be improved to suck data directly from the
879 * WAL buffers when possible.
881 * Will open, and keep open, one WAL segment stored in the global file
882 * descriptor sendFile. This means if XLogRead is used once, there will
883 * always be one descriptor left open until the process ends, but never
887 XLogRead(char *buf, XLogRecPtr recptr, Size nbytes)
889 XLogRecPtr startRecPtr = recptr;
890 char path[MAXPGPATH];
891 uint32 lastRemovedLog;
892 uint32 lastRemovedSeg;
902 startoff = recptr.xrecoff % XLogSegSize;
904 if (sendFile < 0 || !XLByteInSeg(recptr, sendId, sendSeg))
906 /* Switch to another logfile segment */
910 XLByteToSeg(recptr, sendId, sendSeg);
911 XLogFilePath(path, ThisTimeLineID, sendId, sendSeg);
913 sendFile = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
917 * If the file is not found, assume it's because the standby
918 * asked for a too old WAL segment that has already been
919 * removed or recycled.
923 char filename[MAXFNAMELEN];
925 XLogFileName(filename, ThisTimeLineID, sendId, sendSeg);
927 (errcode_for_file_access(),
928 errmsg("requested WAL segment %s has already been removed",
933 (errcode_for_file_access(),
934 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
935 path, sendId, sendSeg)));
940 /* Need to seek in the file? */
941 if (sendOff != startoff)
943 if (lseek(sendFile, (off_t) startoff, SEEK_SET) < 0)
945 (errcode_for_file_access(),
946 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
947 sendId, sendSeg, startoff)));
951 /* How many bytes are within this segment? */
952 if (nbytes > (XLogSegSize - startoff))
953 segbytes = XLogSegSize - startoff;
957 readbytes = read(sendFile, buf, segbytes);
960 (errcode_for_file_access(),
961 errmsg("could not read from log file %u, segment %u, offset %u, "
963 sendId, sendSeg, sendOff, (unsigned long) segbytes)));
965 /* Update state for read */
966 XLByteAdvance(recptr, readbytes);
968 sendOff += readbytes;
974 * After reading into the buffer, check that what we read was valid. We do
975 * this after reading, because even though the segment was present when we
976 * opened it, it might get recycled or removed while we read it. The
977 * read() succeeds in that case, but the data we tried to read might
978 * already have been overwritten with new WAL records.
980 XLogGetLastRemoved(&lastRemovedLog, &lastRemovedSeg);
981 XLByteToSeg(startRecPtr, log, seg);
982 if (log < lastRemovedLog ||
983 (log == lastRemovedLog && seg <= lastRemovedSeg))
985 char filename[MAXFNAMELEN];
987 XLogFileName(filename, ThisTimeLineID, log, seg);
989 (errcode_for_file_access(),
990 errmsg("requested WAL segment %s has already been removed",
996 * Read up to MAX_SEND_SIZE bytes of WAL that's been flushed to disk,
997 * but not yet sent to the client, and send it.
999 * msgbuf is a work area in which the output message is constructed. It's
1000 * passed in just so we can avoid re-palloc'ing the buffer on each cycle.
1001 * It must be of size 1 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE.
1003 * If there is no unsent WAL remaining, *caughtup is set to true, otherwise
1004 * *caughtup is set to false.
1006 * Returns true if OK, false if trouble.
1009 XLogSend(char *msgbuf, bool *caughtup)
1011 XLogRecPtr SendRqstPtr;
1012 XLogRecPtr startptr;
1015 WalDataMessageHeader msghdr;
1018 * Attempt to send all data that's already been written out and fsync'd to
1019 * disk. We cannot go further than what's been written out given the
1020 * current implementation of XLogRead(). And in any case it's unsafe to
1021 * send WAL that is not securely down to disk on the master: if the master
1022 * subsequently crashes and restarts, slaves must not have applied any WAL
1023 * that gets lost on the master.
1025 SendRqstPtr = GetFlushRecPtr();
1027 /* Quick exit if nothing to do */
1028 if (XLByteLE(SendRqstPtr, sentPtr))
1035 * Figure out how much to send in one message. If there's no more than
1036 * MAX_SEND_SIZE bytes to send, send everything. Otherwise send
1037 * MAX_SEND_SIZE bytes, but round back to logfile or page boundary.
1039 * The rounding is not only for performance reasons. Walreceiver relies on
1040 * the fact that we never split a WAL record across two messages. Since a
1041 * long WAL record is split at page boundary into continuation records,
1042 * page boundary is always a safe cut-off point. We also assume that
1043 * SendRqstPtr never points to the middle of a WAL record.
1046 if (startptr.xrecoff >= XLogFileSize)
1049 * crossing a logid boundary, skip the non-existent last log segment
1050 * in previous logical log file.
1052 startptr.xlogid += 1;
1053 startptr.xrecoff = 0;
1057 XLByteAdvance(endptr, MAX_SEND_SIZE);
1058 if (endptr.xlogid != startptr.xlogid)
1060 /* Don't cross a logfile boundary within one message */
1061 Assert(endptr.xlogid == startptr.xlogid + 1);
1062 endptr.xlogid = startptr.xlogid;
1063 endptr.xrecoff = XLogFileSize;
1066 /* if we went beyond SendRqstPtr, back off */
1067 if (XLByteLE(SendRqstPtr, endptr))
1069 endptr = SendRqstPtr;
1074 /* round down to page boundary. */
1075 endptr.xrecoff -= (endptr.xrecoff % XLOG_BLCKSZ);
1079 nbytes = endptr.xrecoff - startptr.xrecoff;
1080 Assert(nbytes <= MAX_SEND_SIZE);
1083 * OK to read and send the slice.
1088 * Read the log directly into the output buffer to avoid extra memcpy
1091 XLogRead(msgbuf + 1 + sizeof(WalDataMessageHeader), startptr, nbytes);
1094 * We fill the message header last so that the send timestamp is taken as
1097 msghdr.dataStart = startptr;
1098 msghdr.walEnd = SendRqstPtr;
1099 msghdr.sendTime = GetCurrentTimestamp();
1101 memcpy(msgbuf + 1, &msghdr, sizeof(WalDataMessageHeader));
1103 pq_putmessage('d', msgbuf, 1 + sizeof(WalDataMessageHeader) + nbytes);
1105 /* Flush pending output to the client */
1111 /* Update shared memory status */
1113 /* use volatile pointer to prevent code rearrangement */
1114 volatile WalSnd *walsnd = MyWalSnd;
1116 SpinLockAcquire(&walsnd->mutex);
1117 walsnd->sentPtr = sentPtr;
1118 SpinLockRelease(&walsnd->mutex);
1121 /* Report progress of XLOG streaming in PS display */
1122 if (update_process_title)
1124 char activitymsg[50];
1126 snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%X",
1127 sentPtr.xlogid, sentPtr.xrecoff);
1128 set_ps_display(activitymsg, false);
1134 /* SIGHUP: set flag to re-read config file at next convenient time */
1136 WalSndSigHupHandler(SIGNAL_ARGS)
1140 SetLatch(&MyWalSnd->latch);
1143 /* SIGTERM: set flag to shut down */
1145 WalSndShutdownHandler(SIGNAL_ARGS)
1147 walsender_shutdown_requested = true;
1149 SetLatch(&MyWalSnd->latch);
1153 * WalSndQuickDieHandler() occurs when signalled SIGQUIT by the postmaster.
1155 * Some backend has bought the farm,
1156 * so we need to stop what we're doing and exit.
1159 WalSndQuickDieHandler(SIGNAL_ARGS)
1161 PG_SETMASK(&BlockSig);
1164 * We DO NOT want to run proc_exit() callbacks -- we're here because
1165 * shared memory may be corrupted, so we don't want to try to clean up our
1166 * transaction. Just nail the windows shut and get out of town. Now that
1167 * there's an atexit callback to prevent third-party code from breaking
1168 * things by calling exit() directly, we have to reset the callbacks
1169 * explicitly to make this work as intended.
1174 * Note we do exit(2) not exit(0). This is to force the postmaster into a
1175 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
1176 * backend. This is necessary precisely because we don't clean up our
1177 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
1178 * should ensure the postmaster sees this as a crash, too, but no harm in
1179 * being doubly sure.)
1184 /* SIGUSR1: set flag to send WAL records */
1186 WalSndXLogSendHandler(SIGNAL_ARGS)
1188 latch_sigusr1_handler();
1191 /* SIGUSR2: set flag to do a last cycle and shut down afterwards */
1193 WalSndLastCycleHandler(SIGNAL_ARGS)
1195 walsender_ready_to_stop = true;
1197 SetLatch(&MyWalSnd->latch);
1200 /* Set up signal handlers */
1204 /* Set up signal handlers */
1205 pqsignal(SIGHUP, WalSndSigHupHandler); /* set flag to read config
1207 pqsignal(SIGINT, SIG_IGN); /* not used */
1208 pqsignal(SIGTERM, WalSndShutdownHandler); /* request shutdown */
1209 pqsignal(SIGQUIT, WalSndQuickDieHandler); /* hard crash time */
1210 pqsignal(SIGALRM, SIG_IGN);
1211 pqsignal(SIGPIPE, SIG_IGN);
1212 pqsignal(SIGUSR1, WalSndXLogSendHandler); /* request WAL sending */
1213 pqsignal(SIGUSR2, WalSndLastCycleHandler); /* request a last cycle and
1216 /* Reset some signals that are accepted by postmaster but not here */
1217 pqsignal(SIGCHLD, SIG_DFL);
1218 pqsignal(SIGTTIN, SIG_DFL);
1219 pqsignal(SIGTTOU, SIG_DFL);
1220 pqsignal(SIGCONT, SIG_DFL);
1221 pqsignal(SIGWINCH, SIG_DFL);
1224 /* Report shared-memory space needed by WalSndShmemInit */
1226 WalSndShmemSize(void)
1230 size = offsetof(WalSndCtlData, walsnds);
1231 size = add_size(size, mul_size(max_wal_senders, sizeof(WalSnd)));
1236 /* Allocate and initialize walsender-related shared memory */
1238 WalSndShmemInit(void)
1243 WalSndCtl = (WalSndCtlData *)
1244 ShmemInitStruct("Wal Sender Ctl", WalSndShmemSize(), &found);
1248 /* First time through, so initialize */
1249 MemSet(WalSndCtl, 0, WalSndShmemSize());
1251 SHMQueueInit(&(WalSndCtl->SyncRepQueue));
1253 for (i = 0; i < max_wal_senders; i++)
1255 WalSnd *walsnd = &WalSndCtl->walsnds[i];
1257 SpinLockInit(&walsnd->mutex);
1258 InitSharedLatch(&walsnd->latch);
1263 /* Wake up all walsenders */
1269 for (i = 0; i < max_wal_senders; i++)
1270 SetLatch(&WalSndCtl->walsnds[i].latch);
1273 /* Set state for current walsender (only called in walsender) */
1275 WalSndSetState(WalSndState state)
1277 /* use volatile pointer to prevent code rearrangement */
1278 volatile WalSnd *walsnd = MyWalSnd;
1280 Assert(am_walsender);
1282 if (walsnd->state == state)
1285 SpinLockAcquire(&walsnd->mutex);
1286 walsnd->state = state;
1287 SpinLockRelease(&walsnd->mutex);
1291 * Return a string constant representing the state. This is used
1292 * in system views, and should *not* be translated.
1295 WalSndGetStateString(WalSndState state)
1299 case WALSNDSTATE_STARTUP:
1301 case WALSNDSTATE_BACKUP:
1303 case WALSNDSTATE_CATCHUP:
1305 case WALSNDSTATE_STREAMING:
1313 * Returns activity of walsenders, including pids and xlog locations sent to
1317 pg_stat_get_wal_senders(PG_FUNCTION_ARGS)
1319 #define PG_STAT_GET_WAL_SENDERS_COLS 8
1320 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1322 Tuplestorestate *tupstore;
1323 MemoryContext per_query_ctx;
1324 MemoryContext oldcontext;
1327 int sync_standby = -1;
1330 /* check to see if caller supports us returning a tuplestore */
1331 if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
1333 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1334 errmsg("set-valued function called in context that cannot accept a set")));
1335 if (!(rsinfo->allowedModes & SFRM_Materialize))
1337 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1338 errmsg("materialize mode required, but it is not " \
1339 "allowed in this context")));
1341 /* Build a tuple descriptor for our result type */
1342 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1343 elog(ERROR, "return type must be a row type");
1345 per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1346 oldcontext = MemoryContextSwitchTo(per_query_ctx);
1348 tupstore = tuplestore_begin_heap(true, false, work_mem);
1349 rsinfo->returnMode = SFRM_Materialize;
1350 rsinfo->setResult = tupstore;
1351 rsinfo->setDesc = tupdesc;
1353 MemoryContextSwitchTo(oldcontext);
1356 * Get the priorities of sync standbys all in one go, to minimise
1357 * lock acquisitions and to allow us to evaluate who is the current
1358 * sync standby. This code must match the code in SyncRepReleaseWaiters().
1360 sync_priority = palloc(sizeof(int) * max_wal_senders);
1361 LWLockAcquire(SyncRepLock, LW_SHARED);
1362 for (i = 0; i < max_wal_senders; i++)
1364 /* use volatile pointer to prevent code rearrangement */
1365 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1367 if (walsnd->pid != 0)
1369 sync_priority[i] = walsnd->sync_standby_priority;
1371 if (walsnd->state == WALSNDSTATE_STREAMING &&
1372 walsnd->sync_standby_priority > 0 &&
1374 priority > walsnd->sync_standby_priority))
1376 priority = walsnd->sync_standby_priority;
1381 LWLockRelease(SyncRepLock);
1383 for (i = 0; i < max_wal_senders; i++)
1385 /* use volatile pointer to prevent code rearrangement */
1386 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1387 char location[MAXFNAMELEN];
1393 Datum values[PG_STAT_GET_WAL_SENDERS_COLS];
1394 bool nulls[PG_STAT_GET_WAL_SENDERS_COLS];
1396 if (walsnd->pid == 0)
1399 SpinLockAcquire(&walsnd->mutex);
1400 sentPtr = walsnd->sentPtr;
1401 state = walsnd->state;
1402 write = walsnd->write;
1403 flush = walsnd->flush;
1404 apply = walsnd->apply;
1405 SpinLockRelease(&walsnd->mutex);
1407 memset(nulls, 0, sizeof(nulls));
1408 values[0] = Int32GetDatum(walsnd->pid);
1413 * Only superusers can see details. Other users only get
1414 * the pid value to know it's a walsender, but no details.
1416 MemSet(&nulls[1], true, PG_STAT_GET_WAL_SENDERS_COLS - 1);
1420 values[1] = CStringGetTextDatum(WalSndGetStateString(state));
1422 snprintf(location, sizeof(location), "%X/%X",
1423 sentPtr.xlogid, sentPtr.xrecoff);
1424 values[2] = CStringGetTextDatum(location);
1426 if (write.xlogid == 0 && write.xrecoff == 0)
1428 snprintf(location, sizeof(location), "%X/%X",
1429 write.xlogid, write.xrecoff);
1430 values[3] = CStringGetTextDatum(location);
1432 if (flush.xlogid == 0 && flush.xrecoff == 0)
1434 snprintf(location, sizeof(location), "%X/%X",
1435 flush.xlogid, flush.xrecoff);
1436 values[4] = CStringGetTextDatum(location);
1438 if (apply.xlogid == 0 && apply.xrecoff == 0)
1440 snprintf(location, sizeof(location), "%X/%X",
1441 apply.xlogid, apply.xrecoff);
1442 values[5] = CStringGetTextDatum(location);
1444 values[6] = Int32GetDatum(sync_priority[i]);
1447 * More easily understood version of standby state.
1448 * This is purely informational, not different from priority.
1450 if (sync_priority[i] == 0)
1451 values[7] = CStringGetTextDatum("ASYNC");
1452 else if (i == sync_standby)
1453 values[7] = CStringGetTextDatum("SYNC");
1455 values[7] = CStringGetTextDatum("POTENTIAL");
1458 tuplestore_putvalues(tupstore, tupdesc, values, nulls);
1460 pfree(sync_priority);
1462 /* clean up and return the tuplestore */
1463 tuplestore_donestoring(tupstore);
1469 * This isn't currently used for anything. Monitoring tools might be
1470 * interested in the future, and we'll need something like this in the
1471 * future for synchronous replication.
1475 * Returns the oldest Send position among walsenders. Or InvalidXLogRecPtr
1479 GetOldestWALSendPointer(void)
1481 XLogRecPtr oldest = {0, 0};
1485 for (i = 0; i < max_wal_senders; i++)
1487 /* use volatile pointer to prevent code rearrangement */
1488 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1491 if (walsnd->pid == 0)
1494 SpinLockAcquire(&walsnd->mutex);
1495 recptr = walsnd->sentPtr;
1496 SpinLockRelease(&walsnd->mutex);
1498 if (recptr.xlogid == 0 && recptr.xrecoff == 0)
1501 if (!found || XLByteLT(recptr, oldest))