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 *-------------------------------------------------------------------------
40 #include "access/transam.h"
41 #include "access/xlog_internal.h"
42 #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 "nodes/replnodes.h"
49 #include "replication/basebackup.h"
50 #include "replication/walprotocol.h"
51 #include "replication/walreceiver.h"
52 #include "replication/walsender.h"
53 #include "storage/fd.h"
54 #include "storage/ipc.h"
55 #include "storage/pmsignal.h"
56 #include "storage/proc.h"
57 #include "storage/procarray.h"
58 #include "tcop/tcopprot.h"
59 #include "utils/builtins.h"
60 #include "utils/guc.h"
61 #include "utils/memutils.h"
62 #include "utils/ps_status.h"
63 #include "utils/resowner.h"
66 /* Array of WalSnds in shared memory */
67 WalSndCtlData *WalSndCtl = NULL;
69 /* My slot in the shared memory array */
70 WalSnd *MyWalSnd = NULL;
73 bool am_walsender = false; /* Am I a walsender process ? */
74 bool am_cascading_walsender = false; /* Am I cascading WAL to another standby ? */
76 /* User-settable parameters for walsender */
77 int max_wal_senders = 0; /* the maximum number of concurrent walsenders */
78 int replication_timeout = 60 * 1000; /* maximum time to send one
82 * These variables are used similarly to openLogFile/Id/Seg/Off,
83 * but for walsender to read the XLOG.
85 static int sendFile = -1;
86 static uint32 sendId = 0;
87 static uint32 sendSeg = 0;
88 static uint32 sendOff = 0;
91 * How far have we sent WAL already? This is also advertised in
92 * MyWalSnd->sentPtr. (Actually, this is the next WAL location to send.)
94 static XLogRecPtr sentPtr = {0, 0};
97 * Buffer for processing reply messages.
99 static StringInfoData reply_message;
102 * Timestamp of the last receipt of the reply from the standby.
104 static TimestampTz last_reply_timestamp;
106 /* Flags set by signal handlers for later service in main loop */
107 static volatile sig_atomic_t got_SIGHUP = false;
108 volatile sig_atomic_t walsender_shutdown_requested = false;
109 volatile sig_atomic_t walsender_ready_to_stop = false;
111 /* Signal handlers */
112 static void WalSndSigHupHandler(SIGNAL_ARGS);
113 static void WalSndShutdownHandler(SIGNAL_ARGS);
114 static void WalSndQuickDieHandler(SIGNAL_ARGS);
115 static void WalSndXLogSendHandler(SIGNAL_ARGS);
116 static void WalSndLastCycleHandler(SIGNAL_ARGS);
118 /* Prototypes for private functions */
119 static bool HandleReplicationCommand(const char *cmd_string);
120 static int WalSndLoop(void);
121 static void InitWalSnd(void);
122 static void WalSndHandshake(void);
123 static void WalSndKill(int code, Datum arg);
124 static void XLogSend(char *msgbuf, bool *caughtup);
125 static void IdentifySystem(void);
126 static void StartReplication(StartReplicationCmd *cmd);
127 static void ProcessStandbyMessage(void);
128 static void ProcessStandbyReplyMessage(void);
129 static void ProcessStandbyHSFeedbackMessage(void);
130 static void ProcessRepliesIfAny(void);
133 /* Main entry point for walsender process */
137 MemoryContext walsnd_context;
139 am_cascading_walsender = RecoveryInProgress();
141 /* Create a per-walsender data structure in shared memory */
145 * Create a memory context that we will do all our work in. We do this so
146 * that we can reset the context during error recovery and thereby avoid
147 * possible memory leaks. Formerly this code just ran in
148 * TopMemoryContext, but resetting that would be a really bad idea.
150 * XXX: we don't actually attempt error recovery in walsender, we just
151 * close the connection and exit.
153 walsnd_context = AllocSetContextCreate(TopMemoryContext,
155 ALLOCSET_DEFAULT_MINSIZE,
156 ALLOCSET_DEFAULT_INITSIZE,
157 ALLOCSET_DEFAULT_MAXSIZE);
158 MemoryContextSwitchTo(walsnd_context);
160 /* Set up resource owner */
161 CurrentResourceOwner = ResourceOwnerCreate(NULL, "walsender top-level resource owner");
163 /* Unblock signals (they were blocked when the postmaster forked us) */
164 PG_SETMASK(&UnBlockSig);
167 * Use the recovery target timeline ID during recovery
169 if (am_cascading_walsender)
170 ThisTimeLineID = GetRecoveryTargetTLI();
172 /* Tell the standby that walsender is ready for receiving commands */
173 ReadyForQuery(DestRemote);
175 /* Handle handshake messages before streaming */
178 /* Initialize shared memory status */
180 /* use volatile pointer to prevent code rearrangement */
181 volatile WalSnd *walsnd = MyWalSnd;
183 SpinLockAcquire(&walsnd->mutex);
184 walsnd->sentPtr = sentPtr;
185 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 WalSndSetState(WALSNDSTATE_STARTUP);
210 set_ps_display("idle", false);
212 /* Wait for a command to arrive */
213 firstchar = pq_getbyte();
216 * Emergency bailout if postmaster has died. This is to avoid the
217 * necessity for manual cleanup of all postmaster children.
219 if (!PostmasterIsAlive())
223 * Check for any other interesting events that happened while we
229 ProcessConfigFile(PGC_SIGHUP);
232 if (firstchar != EOF)
235 * Read the message contents. This is expected to be done without
236 * blocking because we've been able to get message type code.
238 if (pq_getmessage(&input_message, 0))
239 firstchar = EOF; /* suitable message already logged */
242 /* Handle the very limited subset of commands expected in this phase */
245 case 'Q': /* Query message */
247 const char *query_string;
249 query_string = pq_getmsgstring(&input_message);
250 pq_getmsgend(&input_message);
252 if (HandleReplicationCommand(query_string))
253 replication_started = true;
258 /* standby is closing the connection */
262 /* standby disconnected unexpectedly */
264 (errcode(ERRCODE_PROTOCOL_VIOLATION),
265 errmsg("unexpected EOF on standby connection")));
270 (errcode(ERRCODE_PROTOCOL_VIOLATION),
271 errmsg("invalid standby handshake message type %d", firstchar)));
285 char xpos[MAXFNAMELEN];
289 * Reply with a result set with one row, three columns. First col is
290 * system ID, second is timeline ID, and third is current xlog location.
293 snprintf(sysid, sizeof(sysid), UINT64_FORMAT,
294 GetSystemIdentifier());
295 snprintf(tli, sizeof(tli), "%u", ThisTimeLineID);
297 logptr = am_cascading_walsender ? GetStandbyFlushRecPtr() : GetInsertRecPtr();
299 snprintf(xpos, sizeof(xpos), "%X/%X",
300 logptr.xlogid, logptr.xrecoff);
302 /* Send a RowDescription message */
303 pq_beginmessage(&buf, 'T');
304 pq_sendint(&buf, 3, 2); /* 3 fields */
307 pq_sendstring(&buf, "systemid"); /* col name */
308 pq_sendint(&buf, 0, 4); /* table oid */
309 pq_sendint(&buf, 0, 2); /* attnum */
310 pq_sendint(&buf, TEXTOID, 4); /* type oid */
311 pq_sendint(&buf, -1, 2); /* typlen */
312 pq_sendint(&buf, 0, 4); /* typmod */
313 pq_sendint(&buf, 0, 2); /* format code */
316 pq_sendstring(&buf, "timeline"); /* col name */
317 pq_sendint(&buf, 0, 4); /* table oid */
318 pq_sendint(&buf, 0, 2); /* attnum */
319 pq_sendint(&buf, INT4OID, 4); /* type oid */
320 pq_sendint(&buf, 4, 2); /* typlen */
321 pq_sendint(&buf, 0, 4); /* typmod */
322 pq_sendint(&buf, 0, 2); /* format code */
325 pq_sendstring(&buf, "xlogpos");
326 pq_sendint(&buf, 0, 4);
327 pq_sendint(&buf, 0, 2);
328 pq_sendint(&buf, TEXTOID, 4);
329 pq_sendint(&buf, -1, 2);
330 pq_sendint(&buf, 0, 4);
331 pq_sendint(&buf, 0, 2);
334 /* Send a DataRow message */
335 pq_beginmessage(&buf, 'D');
336 pq_sendint(&buf, 3, 2); /* # of columns */
337 pq_sendint(&buf, strlen(sysid), 4); /* col1 len */
338 pq_sendbytes(&buf, (char *) &sysid, strlen(sysid));
339 pq_sendint(&buf, strlen(tli), 4); /* col2 len */
340 pq_sendbytes(&buf, (char *) tli, strlen(tli));
341 pq_sendint(&buf, strlen(xpos), 4); /* col3 len */
342 pq_sendbytes(&buf, (char *) xpos, strlen(xpos));
346 /* Send CommandComplete and ReadyForQuery messages */
347 EndCommand("SELECT", DestRemote);
348 ReadyForQuery(DestRemote);
349 /* ReadyForQuery did pq_flush for us */
356 StartReplication(StartReplicationCmd *cmd)
361 * Let postmaster know that we're streaming. Once we've declared us as a
362 * WAL sender process, postmaster will let us outlive the bgwriter and
363 * kill us last in the shutdown sequence, so we get a chance to stream all
364 * remaining WAL at shutdown, including the shutdown checkpoint. Note that
365 * there's no going back, and we mustn't write any WAL records after this.
367 MarkPostmasterChildWalSender();
368 SendPostmasterSignal(PMSIGNAL_ADVANCE_STATE_MACHINE);
371 * We assume here that we're logging enough information in the WAL for
372 * log-shipping, since this is checked in PostmasterMain().
374 * NOTE: wal_level can only change at shutdown, so in most cases it is
375 * difficult for there to be WAL data that we can still see that was written
376 * at wal_level='minimal'.
380 * When we first start replication the standby will be behind the primary.
381 * For some applications, for example, synchronous replication, it is
382 * important to have a clear state for this initial catchup mode, so we
383 * can trigger actions when we change streaming state later. We may stay
384 * in this state for a long time, which is exactly why we want to be able
385 * to monitor whether or not we are still here.
387 WalSndSetState(WALSNDSTATE_CATCHUP);
389 /* Send a CopyBothResponse message, and start streaming */
390 pq_beginmessage(&buf, 'W');
391 pq_sendbyte(&buf, 0);
392 pq_sendint(&buf, 0, 2);
397 * Initialize position to the received one, then the xlog records begin to
398 * be shipped from that position
400 sentPtr = cmd->startpoint;
404 * Execute an incoming replication command.
407 HandleReplicationCommand(const char *cmd_string)
409 bool replication_started = false;
412 MemoryContext cmd_context;
413 MemoryContext old_context;
415 elog(DEBUG1, "received replication command: %s", cmd_string);
417 cmd_context = AllocSetContextCreate(CurrentMemoryContext,
418 "Replication command context",
419 ALLOCSET_DEFAULT_MINSIZE,
420 ALLOCSET_DEFAULT_INITSIZE,
421 ALLOCSET_DEFAULT_MAXSIZE);
422 old_context = MemoryContextSwitchTo(cmd_context);
424 replication_scanner_init(cmd_string);
425 parse_rc = replication_yyparse();
428 (errcode(ERRCODE_SYNTAX_ERROR),
429 (errmsg_internal("replication command parser returned %d",
432 cmd_node = replication_parse_result;
434 switch (cmd_node->type)
436 case T_IdentifySystemCmd:
440 case T_StartReplicationCmd:
441 StartReplication((StartReplicationCmd *) cmd_node);
443 /* break out of the loop */
444 replication_started = true;
447 case T_BaseBackupCmd:
448 SendBaseBackup((BaseBackupCmd *) cmd_node);
450 /* Send CommandComplete and ReadyForQuery messages */
451 EndCommand("SELECT", DestRemote);
452 ReadyForQuery(DestRemote);
453 /* ReadyForQuery did pq_flush for us */
458 (errcode(ERRCODE_PROTOCOL_VIOLATION),
459 errmsg("invalid standby query string: %s", cmd_string)));
463 MemoryContextSwitchTo(old_context);
464 MemoryContextDelete(cmd_context);
466 return replication_started;
470 * Check if the remote end has closed the connection.
473 ProcessRepliesIfAny(void)
475 unsigned char firstchar;
477 bool received = false;
481 r = pq_getbyte_if_available(&firstchar);
484 /* unexpected error or EOF */
486 (errcode(ERRCODE_PROTOCOL_VIOLATION),
487 errmsg("unexpected EOF on standby connection")));
492 /* no data available without blocking */
496 /* Handle the very limited subset of commands expected in this phase */
500 * 'd' means a standby reply wrapped in a CopyData packet.
503 ProcessStandbyMessage();
508 * 'X' means that the standby is closing down the socket.
515 (errcode(ERRCODE_PROTOCOL_VIOLATION),
516 errmsg("invalid standby message type \"%c\"",
522 * Save the last reply timestamp if we've received at least one reply.
525 last_reply_timestamp = GetCurrentTimestamp();
529 * Process a status update message received from standby.
532 ProcessStandbyMessage(void)
536 resetStringInfo(&reply_message);
539 * Read the message contents.
541 if (pq_getmessage(&reply_message, 0))
544 (errcode(ERRCODE_PROTOCOL_VIOLATION),
545 errmsg("unexpected EOF on standby connection")));
550 * Check message type from the first byte.
552 msgtype = pq_getmsgbyte(&reply_message);
557 ProcessStandbyReplyMessage();
561 ProcessStandbyHSFeedbackMessage();
566 (errcode(ERRCODE_PROTOCOL_VIOLATION),
567 errmsg("unexpected message type \"%c\"", msgtype)));
573 * Regular reply from standby advising of WAL positions on standby server.
576 ProcessStandbyReplyMessage(void)
578 StandbyReplyMessage reply;
580 pq_copymsgbytes(&reply_message, (char *) &reply, sizeof(StandbyReplyMessage));
582 elog(DEBUG2, "write %X/%X flush %X/%X apply %X/%X",
583 reply.write.xlogid, reply.write.xrecoff,
584 reply.flush.xlogid, reply.flush.xrecoff,
585 reply.apply.xlogid, reply.apply.xrecoff);
588 * Update shared state for this WalSender process based on reply data from
592 /* use volatile pointer to prevent code rearrangement */
593 volatile WalSnd *walsnd = MyWalSnd;
595 SpinLockAcquire(&walsnd->mutex);
596 walsnd->write = reply.write;
597 walsnd->flush = reply.flush;
598 walsnd->apply = reply.apply;
599 SpinLockRelease(&walsnd->mutex);
602 if (!am_cascading_walsender)
603 SyncRepReleaseWaiters();
607 * Hot Standby feedback
610 ProcessStandbyHSFeedbackMessage(void)
612 StandbyHSFeedbackMessage reply;
613 TransactionId newxmin = InvalidTransactionId;
615 pq_copymsgbytes(&reply_message, (char *) &reply, sizeof(StandbyHSFeedbackMessage));
617 elog(DEBUG2, "hot standby feedback xmin %u epoch %u",
622 * Update the WalSender's proc xmin to allow it to be visible to
623 * snapshots. This will hold back the removal of dead rows and thereby
624 * prevent the generation of cleanup conflicts on the standby server.
626 if (TransactionIdIsValid(reply.xmin))
628 TransactionId nextXid;
630 bool epochOK = false;
632 GetNextXidAndEpoch(&nextXid, &nextEpoch);
635 * Epoch of oldestXmin should be same as standby or if the counter has
636 * wrapped, then one less than reply.
638 if (reply.xmin <= nextXid)
640 if (reply.epoch == nextEpoch)
645 if (nextEpoch > 0 && reply.epoch == nextEpoch - 1)
650 * Feedback from standby must not go backwards, nor should it go
651 * forwards further than our most recent xid.
653 if (epochOK && TransactionIdPrecedesOrEquals(reply.xmin, nextXid))
655 if (!TransactionIdIsValid(MyProc->xmin))
657 TransactionId oldestXmin = GetOldestXmin(true, true);
659 if (TransactionIdPrecedes(oldestXmin, reply.xmin))
660 newxmin = reply.xmin;
662 newxmin = oldestXmin;
666 if (TransactionIdPrecedes(MyProc->xmin, reply.xmin))
667 newxmin = reply.xmin;
669 newxmin = MyProc->xmin; /* stay the same */
675 * Grab the ProcArrayLock to set xmin, or invalidate for bad reply
677 if (MyProc->xmin != newxmin)
679 LWLockAcquire(ProcArrayLock, LW_SHARED);
680 MyProc->xmin = newxmin;
681 LWLockRelease(ProcArrayLock);
685 /* Main loop of walsender process */
689 char *output_message;
690 bool caughtup = false;
693 * Allocate buffer that will be used for each output message. We do this
694 * just once to reduce palloc overhead. The buffer must be made large
695 * enough for maximum-sized messages.
697 output_message = palloc(1 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE);
700 * Allocate buffer that will be used for processing reply messages. As
701 * above, do this just once to reduce palloc overhead.
703 initStringInfo(&reply_message);
705 /* Initialize the last reply timestamp */
706 last_reply_timestamp = GetCurrentTimestamp();
708 /* Loop forever, unless we get an error */
711 /* Clear any already-pending wakeups */
712 ResetLatch(&MyWalSnd->latch);
715 * Emergency bailout if postmaster has died. This is to avoid the
716 * necessity for manual cleanup of all postmaster children.
718 if (!PostmasterIsAlive())
721 /* Process any requests or signals received recently */
725 ProcessConfigFile(PGC_SIGHUP);
729 /* Normal exit from the walsender is here */
730 if (walsender_shutdown_requested)
732 /* Inform the standby that XLOG streaming is done */
733 pq_puttextmessage('C', "COPY 0");
739 /* Check for input from the client */
740 ProcessRepliesIfAny();
743 * If we don't have any pending data in the output buffer, try to send
744 * some more. If there is some, we don't bother to call XLogSend
745 * again until we've flushed it ... but we'd better assume we are not
748 if (!pq_is_send_pending())
749 XLogSend(output_message, &caughtup);
753 /* Try to flush pending output to the client */
754 if (pq_flush_if_writable() != 0)
757 /* If nothing remains to be sent right now ... */
758 if (caughtup && !pq_is_send_pending())
761 * If we're in catchup state, move to streaming. This is an
762 * important state change for users to know about, since before
763 * this point data loss might occur if the primary dies and we
764 * need to failover to the standby. The state change is also
765 * important for synchronous replication, since commits that
766 * started to wait at that point might wait for some time.
768 if (MyWalSnd->state == WALSNDSTATE_CATCHUP)
771 (errmsg("standby \"%s\" has now caught up with primary",
773 WalSndSetState(WALSNDSTATE_STREAMING);
777 * When SIGUSR2 arrives, we send any outstanding logs up to the
778 * shutdown checkpoint record (i.e., the latest record) and exit.
779 * This may be a normal termination at shutdown, or a promotion,
780 * the walsender is not sure which.
782 if (walsender_ready_to_stop)
784 /* ... let's just be real sure we're caught up ... */
785 XLogSend(output_message, &caughtup);
786 if (caughtup && !pq_is_send_pending())
788 walsender_shutdown_requested = true;
789 continue; /* don't want to wait more */
795 * We don't block if not caught up, unless there is unsent data
796 * pending in which case we'd better block until the socket is
797 * write-ready. This test is only needed for the case where XLogSend
798 * loaded a subset of the available data but then pq_flush_if_writable
799 * flushed it all --- we should immediately try to send more.
801 if (caughtup || pq_is_send_pending())
803 TimestampTz finish_time = 0;
807 wakeEvents = WL_LATCH_SET | WL_POSTMASTER_DEATH |
809 if (pq_is_send_pending())
810 wakeEvents |= WL_SOCKET_WRITEABLE;
812 /* Determine time until replication timeout */
813 if (replication_timeout > 0)
818 finish_time = TimestampTzPlusMilliseconds(last_reply_timestamp,
819 replication_timeout);
820 TimestampDifference(GetCurrentTimestamp(),
821 finish_time, &secs, &usecs);
822 sleeptime = secs * 1000 + usecs / 1000;
823 /* Avoid Assert in WaitLatchOrSocket if timeout is past */
826 wakeEvents |= WL_TIMEOUT;
829 /* Sleep until something happens or replication timeout */
830 WaitLatchOrSocket(&MyWalSnd->latch, wakeEvents,
831 MyProcPort->sock, sleeptime);
834 * Check for replication timeout. Note we ignore the corner case
835 * possibility that the client replied just as we reached the
836 * timeout ... he's supposed to reply *before* that.
838 if (replication_timeout > 0 &&
839 GetCurrentTimestamp() >= finish_time)
842 * Since typically expiration of replication timeout means
843 * communication problem, we don't send the error message to
847 (errmsg("terminating walsender process due to replication timeout")));
854 * Get here on send failure. Clean up and exit.
856 * Reset whereToSendOutput to prevent ereport from attempting to send any
857 * more messages to the standby.
859 if (whereToSendOutput == DestRemote)
860 whereToSendOutput = DestNone;
863 return 1; /* keep the compiler quiet */
866 /* Initialize a per-walsender data structure for this walsender process */
873 * WalSndCtl should be set up already (we inherit this by fork() or
874 * EXEC_BACKEND mechanism from the postmaster).
876 Assert(WalSndCtl != NULL);
877 Assert(MyWalSnd == NULL);
880 * Find a free walsender slot and reserve it. If this fails, we must be
881 * out of WalSnd structures.
883 for (i = 0; i < max_wal_senders; i++)
885 /* use volatile pointer to prevent code rearrangement */
886 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
888 SpinLockAcquire(&walsnd->mutex);
890 if (walsnd->pid != 0)
892 SpinLockRelease(&walsnd->mutex);
898 * Found a free slot. Reserve it for us.
900 walsnd->pid = MyProcPid;
901 MemSet(&walsnd->sentPtr, 0, sizeof(XLogRecPtr));
902 walsnd->state = WALSNDSTATE_STARTUP;
903 SpinLockRelease(&walsnd->mutex);
904 /* don't need the lock anymore */
905 OwnLatch((Latch *) &walsnd->latch);
906 MyWalSnd = (WalSnd *) walsnd;
911 if (MyWalSnd == NULL)
913 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
914 errmsg("number of requested standby connections "
915 "exceeds max_wal_senders (currently %d)",
918 /* Arrange to clean up at walsender exit */
919 on_shmem_exit(WalSndKill, 0);
922 /* Destroy the per-walsender data structure for this walsender process */
924 WalSndKill(int code, Datum arg)
926 Assert(MyWalSnd != NULL);
929 * Mark WalSnd struct no longer in use. Assume that no lock is required
933 DisownLatch(&MyWalSnd->latch);
935 /* WalSnd struct isn't mine anymore */
940 * Read 'count' bytes from WAL into 'buf', starting at location 'startptr'
942 * XXX probably this should be improved to suck data directly from the
943 * WAL buffers when possible.
945 * Will open, and keep open, one WAL segment stored in the global file
946 * descriptor sendFile. This means if XLogRead is used once, there will
947 * always be one descriptor left open until the process ends, but never
951 XLogRead(char *buf, XLogRecPtr startptr, Size count)
956 uint32 lastRemovedLog;
957 uint32 lastRemovedSeg;
972 startoff = recptr.xrecoff % XLogSegSize;
974 if (sendFile < 0 || !XLByteInSeg(recptr, sendId, sendSeg))
976 char path[MAXPGPATH];
978 /* Switch to another logfile segment */
982 XLByteToSeg(recptr, sendId, sendSeg);
983 XLogFilePath(path, ThisTimeLineID, sendId, sendSeg);
985 sendFile = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
989 * If the file is not found, assume it's because the standby
990 * asked for a too old WAL segment that has already been
991 * removed or recycled.
995 char filename[MAXFNAMELEN];
997 XLogFileName(filename, ThisTimeLineID, sendId, sendSeg);
999 (errcode_for_file_access(),
1000 errmsg("requested WAL segment %s has already been removed",
1005 (errcode_for_file_access(),
1006 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
1007 path, sendId, sendSeg)));
1012 /* Need to seek in the file? */
1013 if (sendOff != startoff)
1015 if (lseek(sendFile, (off_t) startoff, SEEK_SET) < 0)
1017 (errcode_for_file_access(),
1018 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
1019 sendId, sendSeg, startoff)));
1023 /* How many bytes are within this segment? */
1024 if (nbytes > (XLogSegSize - startoff))
1025 segbytes = XLogSegSize - startoff;
1029 readbytes = read(sendFile, p, segbytes);
1032 (errcode_for_file_access(),
1033 errmsg("could not read from log file %u, segment %u, offset %u, "
1035 sendId, sendSeg, sendOff, (unsigned long) segbytes)));
1037 /* Update state for read */
1038 XLByteAdvance(recptr, readbytes);
1040 sendOff += readbytes;
1041 nbytes -= readbytes;
1046 * After reading into the buffer, check that what we read was valid. We do
1047 * this after reading, because even though the segment was present when we
1048 * opened it, it might get recycled or removed while we read it. The
1049 * read() succeeds in that case, but the data we tried to read might
1050 * already have been overwritten with new WAL records.
1052 XLogGetLastRemoved(&lastRemovedLog, &lastRemovedSeg);
1053 XLByteToSeg(startptr, log, seg);
1054 if (log < lastRemovedLog ||
1055 (log == lastRemovedLog && seg <= lastRemovedSeg))
1057 char filename[MAXFNAMELEN];
1059 XLogFileName(filename, ThisTimeLineID, log, seg);
1061 (errcode_for_file_access(),
1062 errmsg("requested WAL segment %s has already been removed",
1067 * During recovery, the currently-open WAL file might be replaced with
1068 * the file of the same name retrieved from archive. So we always need
1069 * to check what we read was valid after reading into the buffer. If it's
1070 * invalid, we try to open and read the file again.
1072 if (am_cascading_walsender)
1074 /* use volatile pointer to prevent code rearrangement */
1075 volatile WalSnd *walsnd = MyWalSnd;
1078 SpinLockAcquire(&walsnd->mutex);
1079 reload = walsnd->needreload;
1080 walsnd->needreload = false;
1081 SpinLockRelease(&walsnd->mutex);
1083 if (reload && sendFile >= 0)
1094 * Read up to MAX_SEND_SIZE bytes of WAL that's been flushed to disk,
1095 * but not yet sent to the client, and buffer it in the libpq output
1098 * msgbuf is a work area in which the output message is constructed. It's
1099 * passed in just so we can avoid re-palloc'ing the buffer on each cycle.
1100 * It must be of size 1 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE.
1102 * If there is no unsent WAL remaining, *caughtup is set to true, otherwise
1103 * *caughtup is set to false.
1107 XLogSend(char *msgbuf, bool *caughtup)
1109 XLogRecPtr SendRqstPtr;
1110 XLogRecPtr startptr;
1113 WalDataMessageHeader msghdr;
1116 * Attempt to send all data that's already been written out and fsync'd to
1117 * disk. We cannot go further than what's been written out given the
1118 * current implementation of XLogRead(). And in any case it's unsafe to
1119 * send WAL that is not securely down to disk on the master: if the master
1120 * subsequently crashes and restarts, slaves must not have applied any WAL
1121 * that gets lost on the master.
1123 SendRqstPtr = am_cascading_walsender ? GetStandbyFlushRecPtr() : GetFlushRecPtr();
1125 /* Quick exit if nothing to do */
1126 if (XLByteLE(SendRqstPtr, sentPtr))
1133 * Figure out how much to send in one message. If there's no more than
1134 * MAX_SEND_SIZE bytes to send, send everything. Otherwise send
1135 * MAX_SEND_SIZE bytes, but round back to logfile or page boundary.
1137 * The rounding is not only for performance reasons. Walreceiver relies on
1138 * the fact that we never split a WAL record across two messages. Since a
1139 * long WAL record is split at page boundary into continuation records,
1140 * page boundary is always a safe cut-off point. We also assume that
1141 * SendRqstPtr never points to the middle of a WAL record.
1144 if (startptr.xrecoff >= XLogFileSize)
1147 * crossing a logid boundary, skip the non-existent last log segment
1148 * in previous logical log file.
1150 startptr.xlogid += 1;
1151 startptr.xrecoff = 0;
1155 XLByteAdvance(endptr, MAX_SEND_SIZE);
1156 if (endptr.xlogid != startptr.xlogid)
1158 /* Don't cross a logfile boundary within one message */
1159 Assert(endptr.xlogid == startptr.xlogid + 1);
1160 endptr.xlogid = startptr.xlogid;
1161 endptr.xrecoff = XLogFileSize;
1164 /* if we went beyond SendRqstPtr, back off */
1165 if (XLByteLE(SendRqstPtr, endptr))
1167 endptr = SendRqstPtr;
1172 /* round down to page boundary. */
1173 endptr.xrecoff -= (endptr.xrecoff % XLOG_BLCKSZ);
1177 nbytes = endptr.xrecoff - startptr.xrecoff;
1178 Assert(nbytes <= MAX_SEND_SIZE);
1181 * OK to read and send the slice.
1186 * Read the log directly into the output buffer to avoid extra memcpy
1189 XLogRead(msgbuf + 1 + sizeof(WalDataMessageHeader), startptr, nbytes);
1192 * We fill the message header last so that the send timestamp is taken as
1195 msghdr.dataStart = startptr;
1196 msghdr.walEnd = SendRqstPtr;
1197 msghdr.sendTime = GetCurrentTimestamp();
1199 memcpy(msgbuf + 1, &msghdr, sizeof(WalDataMessageHeader));
1201 pq_putmessage_noblock('d', msgbuf, 1 + sizeof(WalDataMessageHeader) + nbytes);
1205 /* Update shared memory status */
1207 /* use volatile pointer to prevent code rearrangement */
1208 volatile WalSnd *walsnd = MyWalSnd;
1210 SpinLockAcquire(&walsnd->mutex);
1211 walsnd->sentPtr = sentPtr;
1212 SpinLockRelease(&walsnd->mutex);
1215 /* Report progress of XLOG streaming in PS display */
1216 if (update_process_title)
1218 char activitymsg[50];
1220 snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%X",
1221 sentPtr.xlogid, sentPtr.xrecoff);
1222 set_ps_display(activitymsg, false);
1229 * Request walsenders to reload the currently-open WAL file
1232 WalSndRqstFileReload(void)
1236 for (i = 0; i < max_wal_senders; i++)
1238 /* use volatile pointer to prevent code rearrangement */
1239 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1241 if (walsnd->pid == 0)
1244 SpinLockAcquire(&walsnd->mutex);
1245 walsnd->needreload = true;
1246 SpinLockRelease(&walsnd->mutex);
1250 /* SIGHUP: set flag to re-read config file at next convenient time */
1252 WalSndSigHupHandler(SIGNAL_ARGS)
1254 int save_errno = errno;
1258 SetLatch(&MyWalSnd->latch);
1263 /* SIGTERM: set flag to shut down */
1265 WalSndShutdownHandler(SIGNAL_ARGS)
1267 int save_errno = errno;
1269 walsender_shutdown_requested = true;
1271 SetLatch(&MyWalSnd->latch);
1277 * WalSndQuickDieHandler() occurs when signalled SIGQUIT by the postmaster.
1279 * Some backend has bought the farm,
1280 * so we need to stop what we're doing and exit.
1283 WalSndQuickDieHandler(SIGNAL_ARGS)
1285 PG_SETMASK(&BlockSig);
1288 * We DO NOT want to run proc_exit() callbacks -- we're here because
1289 * shared memory may be corrupted, so we don't want to try to clean up our
1290 * transaction. Just nail the windows shut and get out of town. Now that
1291 * there's an atexit callback to prevent third-party code from breaking
1292 * things by calling exit() directly, we have to reset the callbacks
1293 * explicitly to make this work as intended.
1298 * Note we do exit(2) not exit(0). This is to force the postmaster into a
1299 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
1300 * backend. This is necessary precisely because we don't clean up our
1301 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
1302 * should ensure the postmaster sees this as a crash, too, but no harm in
1303 * being doubly sure.)
1308 /* SIGUSR1: set flag to send WAL records */
1310 WalSndXLogSendHandler(SIGNAL_ARGS)
1312 int save_errno = errno;
1314 latch_sigusr1_handler();
1319 /* SIGUSR2: set flag to do a last cycle and shut down afterwards */
1321 WalSndLastCycleHandler(SIGNAL_ARGS)
1323 int save_errno = errno;
1325 walsender_ready_to_stop = true;
1327 SetLatch(&MyWalSnd->latch);
1332 /* Set up signal handlers */
1336 /* Set up signal handlers */
1337 pqsignal(SIGHUP, WalSndSigHupHandler); /* set flag to read config
1339 pqsignal(SIGINT, SIG_IGN); /* not used */
1340 pqsignal(SIGTERM, WalSndShutdownHandler); /* request shutdown */
1341 pqsignal(SIGQUIT, WalSndQuickDieHandler); /* hard crash time */
1342 pqsignal(SIGALRM, SIG_IGN);
1343 pqsignal(SIGPIPE, SIG_IGN);
1344 pqsignal(SIGUSR1, WalSndXLogSendHandler); /* request WAL sending */
1345 pqsignal(SIGUSR2, WalSndLastCycleHandler); /* request a last cycle and
1348 /* Reset some signals that are accepted by postmaster but not here */
1349 pqsignal(SIGCHLD, SIG_DFL);
1350 pqsignal(SIGTTIN, SIG_DFL);
1351 pqsignal(SIGTTOU, SIG_DFL);
1352 pqsignal(SIGCONT, SIG_DFL);
1353 pqsignal(SIGWINCH, SIG_DFL);
1356 /* Report shared-memory space needed by WalSndShmemInit */
1358 WalSndShmemSize(void)
1362 size = offsetof(WalSndCtlData, walsnds);
1363 size = add_size(size, mul_size(max_wal_senders, sizeof(WalSnd)));
1368 /* Allocate and initialize walsender-related shared memory */
1370 WalSndShmemInit(void)
1375 WalSndCtl = (WalSndCtlData *)
1376 ShmemInitStruct("Wal Sender Ctl", WalSndShmemSize(), &found);
1380 /* First time through, so initialize */
1381 MemSet(WalSndCtl, 0, WalSndShmemSize());
1383 SHMQueueInit(&(WalSndCtl->SyncRepQueue));
1385 for (i = 0; i < max_wal_senders; i++)
1387 WalSnd *walsnd = &WalSndCtl->walsnds[i];
1389 SpinLockInit(&walsnd->mutex);
1390 InitSharedLatch(&walsnd->latch);
1395 /* Wake up all walsenders */
1401 for (i = 0; i < max_wal_senders; i++)
1402 SetLatch(&WalSndCtl->walsnds[i].latch);
1405 /* Set state for current walsender (only called in walsender) */
1407 WalSndSetState(WalSndState state)
1409 /* use volatile pointer to prevent code rearrangement */
1410 volatile WalSnd *walsnd = MyWalSnd;
1412 Assert(am_walsender);
1414 if (walsnd->state == state)
1417 SpinLockAcquire(&walsnd->mutex);
1418 walsnd->state = state;
1419 SpinLockRelease(&walsnd->mutex);
1423 * Return a string constant representing the state. This is used
1424 * in system views, and should *not* be translated.
1427 WalSndGetStateString(WalSndState state)
1431 case WALSNDSTATE_STARTUP:
1433 case WALSNDSTATE_BACKUP:
1435 case WALSNDSTATE_CATCHUP:
1437 case WALSNDSTATE_STREAMING:
1445 * Returns activity of walsenders, including pids and xlog locations sent to
1449 pg_stat_get_wal_senders(PG_FUNCTION_ARGS)
1451 #define PG_STAT_GET_WAL_SENDERS_COLS 8
1452 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1454 Tuplestorestate *tupstore;
1455 MemoryContext per_query_ctx;
1456 MemoryContext oldcontext;
1459 int sync_standby = -1;
1462 /* check to see if caller supports us returning a tuplestore */
1463 if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
1465 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1466 errmsg("set-valued function called in context that cannot accept a set")));
1467 if (!(rsinfo->allowedModes & SFRM_Materialize))
1469 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1470 errmsg("materialize mode required, but it is not " \
1471 "allowed in this context")));
1473 /* Build a tuple descriptor for our result type */
1474 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1475 elog(ERROR, "return type must be a row type");
1477 per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1478 oldcontext = MemoryContextSwitchTo(per_query_ctx);
1480 tupstore = tuplestore_begin_heap(true, false, work_mem);
1481 rsinfo->returnMode = SFRM_Materialize;
1482 rsinfo->setResult = tupstore;
1483 rsinfo->setDesc = tupdesc;
1485 MemoryContextSwitchTo(oldcontext);
1488 * Get the priorities of sync standbys all in one go, to minimise lock
1489 * acquisitions and to allow us to evaluate who is the current sync
1490 * standby. This code must match the code in SyncRepReleaseWaiters().
1492 sync_priority = palloc(sizeof(int) * max_wal_senders);
1493 LWLockAcquire(SyncRepLock, LW_SHARED);
1494 for (i = 0; i < max_wal_senders; i++)
1496 /* use volatile pointer to prevent code rearrangement */
1497 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1499 if (walsnd->pid != 0)
1501 sync_priority[i] = walsnd->sync_standby_priority;
1503 if (walsnd->state == WALSNDSTATE_STREAMING &&
1504 walsnd->sync_standby_priority > 0 &&
1506 priority > walsnd->sync_standby_priority))
1508 priority = walsnd->sync_standby_priority;
1513 LWLockRelease(SyncRepLock);
1515 for (i = 0; i < max_wal_senders; i++)
1517 /* use volatile pointer to prevent code rearrangement */
1518 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1519 char location[MAXFNAMELEN];
1525 Datum values[PG_STAT_GET_WAL_SENDERS_COLS];
1526 bool nulls[PG_STAT_GET_WAL_SENDERS_COLS];
1528 if (walsnd->pid == 0)
1531 SpinLockAcquire(&walsnd->mutex);
1532 sentPtr = walsnd->sentPtr;
1533 state = walsnd->state;
1534 write = walsnd->write;
1535 flush = walsnd->flush;
1536 apply = walsnd->apply;
1537 SpinLockRelease(&walsnd->mutex);
1539 memset(nulls, 0, sizeof(nulls));
1540 values[0] = Int32GetDatum(walsnd->pid);
1545 * Only superusers can see details. Other users only get the pid
1546 * value to know it's a walsender, but no details.
1548 MemSet(&nulls[1], true, PG_STAT_GET_WAL_SENDERS_COLS - 1);
1552 values[1] = CStringGetTextDatum(WalSndGetStateString(state));
1554 snprintf(location, sizeof(location), "%X/%X",
1555 sentPtr.xlogid, sentPtr.xrecoff);
1556 values[2] = CStringGetTextDatum(location);
1558 if (write.xlogid == 0 && write.xrecoff == 0)
1560 snprintf(location, sizeof(location), "%X/%X",
1561 write.xlogid, write.xrecoff);
1562 values[3] = CStringGetTextDatum(location);
1564 if (flush.xlogid == 0 && flush.xrecoff == 0)
1566 snprintf(location, sizeof(location), "%X/%X",
1567 flush.xlogid, flush.xrecoff);
1568 values[4] = CStringGetTextDatum(location);
1570 if (apply.xlogid == 0 && apply.xrecoff == 0)
1572 snprintf(location, sizeof(location), "%X/%X",
1573 apply.xlogid, apply.xrecoff);
1574 values[5] = CStringGetTextDatum(location);
1576 values[6] = Int32GetDatum(sync_priority[i]);
1579 * More easily understood version of standby state. This is purely
1580 * informational, not different from priority.
1582 if (sync_priority[i] == 0)
1583 values[7] = CStringGetTextDatum("async");
1584 else if (i == sync_standby)
1585 values[7] = CStringGetTextDatum("sync");
1587 values[7] = CStringGetTextDatum("potential");
1590 tuplestore_putvalues(tupstore, tupdesc, values, nulls);
1592 pfree(sync_priority);
1594 /* clean up and return the tuplestore */
1595 tuplestore_donestoring(tupstore);
1601 * This isn't currently used for anything. Monitoring tools might be
1602 * interested in the future, and we'll need something like this in the
1603 * future for synchronous replication.
1607 * Returns the oldest Send position among walsenders. Or InvalidXLogRecPtr
1611 GetOldestWALSendPointer(void)
1613 XLogRecPtr oldest = {0, 0};
1617 for (i = 0; i < max_wal_senders; i++)
1619 /* use volatile pointer to prevent code rearrangement */
1620 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1623 if (walsnd->pid == 0)
1626 SpinLockAcquire(&walsnd->mutex);
1627 recptr = walsnd->sentPtr;
1628 SpinLockRelease(&walsnd->mutex);
1630 if (recptr.xlogid == 0 && recptr.xrecoff == 0)
1633 if (!found || XLByteLT(recptr, oldest))