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 WalSndDelay = 1000; /* max sleep time between some actions */
79 int replication_timeout = 60 * 1000; /* maximum time to send one
83 * These variables are used similarly to openLogFile/Id/Seg/Off,
84 * but for walsender to read the XLOG.
86 static int sendFile = -1;
87 static uint32 sendId = 0;
88 static uint32 sendSeg = 0;
89 static uint32 sendOff = 0;
92 * How far have we sent WAL already? This is also advertised in
93 * MyWalSnd->sentPtr. (Actually, this is the next WAL location to send.)
95 static XLogRecPtr sentPtr = {0, 0};
98 * Buffer for processing reply messages.
100 static StringInfoData reply_message;
103 * Timestamp of the last receipt of the reply from the standby.
105 static TimestampTz last_reply_timestamp;
107 /* Flags set by signal handlers for later service in main loop */
108 static volatile sig_atomic_t got_SIGHUP = false;
109 volatile sig_atomic_t walsender_shutdown_requested = false;
110 volatile sig_atomic_t walsender_ready_to_stop = false;
112 /* Signal handlers */
113 static void WalSndSigHupHandler(SIGNAL_ARGS);
114 static void WalSndShutdownHandler(SIGNAL_ARGS);
115 static void WalSndQuickDieHandler(SIGNAL_ARGS);
116 static void WalSndXLogSendHandler(SIGNAL_ARGS);
117 static void WalSndLastCycleHandler(SIGNAL_ARGS);
119 /* Prototypes for private functions */
120 static bool HandleReplicationCommand(const char *cmd_string);
121 static int WalSndLoop(void);
122 static void InitWalSnd(void);
123 static void WalSndHandshake(void);
124 static void WalSndKill(int code, Datum arg);
125 static void XLogSend(char *msgbuf, bool *caughtup);
126 static void IdentifySystem(void);
127 static void StartReplication(StartReplicationCmd *cmd);
128 static void ProcessStandbyMessage(void);
129 static void ProcessStandbyReplyMessage(void);
130 static void ProcessStandbyHSFeedbackMessage(void);
131 static void ProcessRepliesIfAny(void);
134 /* Main entry point for walsender process */
138 MemoryContext walsnd_context;
140 am_cascading_walsender = RecoveryInProgress();
142 /* Create a per-walsender data structure in shared memory */
146 * Create a memory context that we will do all our work in. We do this so
147 * that we can reset the context during error recovery and thereby avoid
148 * possible memory leaks. Formerly this code just ran in
149 * TopMemoryContext, but resetting that would be a really bad idea.
151 * XXX: we don't actually attempt error recovery in walsender, we just
152 * close the connection and exit.
154 walsnd_context = AllocSetContextCreate(TopMemoryContext,
156 ALLOCSET_DEFAULT_MINSIZE,
157 ALLOCSET_DEFAULT_INITSIZE,
158 ALLOCSET_DEFAULT_MAXSIZE);
159 MemoryContextSwitchTo(walsnd_context);
161 /* Set up resource owner */
162 CurrentResourceOwner = ResourceOwnerCreate(NULL, "walsender top-level resource owner");
164 /* Unblock signals (they were blocked when the postmaster forked us) */
165 PG_SETMASK(&UnBlockSig);
168 * Use the recovery target timeline ID during recovery
170 if (am_cascading_walsender)
171 ThisTimeLineID = GetRecoveryTargetTLI();
173 /* Tell the standby that walsender is ready for receiving commands */
174 ReadyForQuery(DestRemote);
176 /* Handle handshake messages before streaming */
179 /* Initialize shared memory status */
181 /* use volatile pointer to prevent code rearrangement */
182 volatile WalSnd *walsnd = MyWalSnd;
184 SpinLockAcquire(&walsnd->mutex);
185 walsnd->sentPtr = sentPtr;
186 SpinLockRelease(&walsnd->mutex);
191 /* Main loop of walsender */
196 * Execute commands from walreceiver, until we enter streaming mode.
199 WalSndHandshake(void)
201 StringInfoData input_message;
202 bool replication_started = false;
204 initStringInfo(&input_message);
206 while (!replication_started)
210 WalSndSetState(WALSNDSTATE_STARTUP);
211 set_ps_display("idle", false);
213 /* Wait for a command to arrive */
214 firstchar = pq_getbyte();
217 * Emergency bailout if postmaster has died. This is to avoid the
218 * necessity for manual cleanup of all postmaster children.
220 if (!PostmasterIsAlive())
224 * Check for any other interesting events that happened while we
230 ProcessConfigFile(PGC_SIGHUP);
233 if (firstchar != EOF)
236 * Read the message contents. This is expected to be done without
237 * blocking because we've been able to get message type code.
239 if (pq_getmessage(&input_message, 0))
240 firstchar = EOF; /* suitable message already logged */
243 /* Handle the very limited subset of commands expected in this phase */
246 case 'Q': /* Query message */
248 const char *query_string;
250 query_string = pq_getmsgstring(&input_message);
251 pq_getmsgend(&input_message);
253 if (HandleReplicationCommand(query_string))
254 replication_started = true;
259 /* standby is closing the connection */
263 /* standby disconnected unexpectedly */
265 (errcode(ERRCODE_PROTOCOL_VIOLATION),
266 errmsg("unexpected EOF on standby connection")));
271 (errcode(ERRCODE_PROTOCOL_VIOLATION),
272 errmsg("invalid standby handshake message type %d", firstchar)));
286 char xpos[MAXFNAMELEN];
290 * Reply with a result set with one row, three columns. First col is
291 * system ID, second is timeline ID, and third is current xlog location.
294 snprintf(sysid, sizeof(sysid), UINT64_FORMAT,
295 GetSystemIdentifier());
296 snprintf(tli, sizeof(tli), "%u", ThisTimeLineID);
298 logptr = am_cascading_walsender ? GetStandbyFlushRecPtr() : GetInsertRecPtr();
300 snprintf(xpos, sizeof(xpos), "%X/%X",
301 logptr.xlogid, logptr.xrecoff);
303 /* Send a RowDescription message */
304 pq_beginmessage(&buf, 'T');
305 pq_sendint(&buf, 3, 2); /* 3 fields */
308 pq_sendstring(&buf, "systemid"); /* col name */
309 pq_sendint(&buf, 0, 4); /* table oid */
310 pq_sendint(&buf, 0, 2); /* attnum */
311 pq_sendint(&buf, TEXTOID, 4); /* type oid */
312 pq_sendint(&buf, -1, 2); /* typlen */
313 pq_sendint(&buf, 0, 4); /* typmod */
314 pq_sendint(&buf, 0, 2); /* format code */
317 pq_sendstring(&buf, "timeline"); /* col name */
318 pq_sendint(&buf, 0, 4); /* table oid */
319 pq_sendint(&buf, 0, 2); /* attnum */
320 pq_sendint(&buf, INT4OID, 4); /* type oid */
321 pq_sendint(&buf, 4, 2); /* typlen */
322 pq_sendint(&buf, 0, 4); /* typmod */
323 pq_sendint(&buf, 0, 2); /* format code */
326 pq_sendstring(&buf, "xlogpos");
327 pq_sendint(&buf, 0, 4);
328 pq_sendint(&buf, 0, 2);
329 pq_sendint(&buf, TEXTOID, 4);
330 pq_sendint(&buf, -1, 2);
331 pq_sendint(&buf, 0, 4);
332 pq_sendint(&buf, 0, 2);
335 /* Send a DataRow message */
336 pq_beginmessage(&buf, 'D');
337 pq_sendint(&buf, 3, 2); /* # of columns */
338 pq_sendint(&buf, strlen(sysid), 4); /* col1 len */
339 pq_sendbytes(&buf, (char *) &sysid, strlen(sysid));
340 pq_sendint(&buf, strlen(tli), 4); /* col2 len */
341 pq_sendbytes(&buf, (char *) tli, strlen(tli));
342 pq_sendint(&buf, strlen(xpos), 4); /* col3 len */
343 pq_sendbytes(&buf, (char *) xpos, strlen(xpos));
347 /* Send CommandComplete and ReadyForQuery messages */
348 EndCommand("SELECT", DestRemote);
349 ReadyForQuery(DestRemote);
350 /* ReadyForQuery did pq_flush for us */
357 StartReplication(StartReplicationCmd *cmd)
362 * Let postmaster know that we're streaming. Once we've declared us as a
363 * WAL sender process, postmaster will let us outlive the bgwriter and
364 * kill us last in the shutdown sequence, so we get a chance to stream all
365 * remaining WAL at shutdown, including the shutdown checkpoint. Note that
366 * there's no going back, and we mustn't write any WAL records after this.
368 MarkPostmasterChildWalSender();
369 SendPostmasterSignal(PMSIGNAL_ADVANCE_STATE_MACHINE);
372 * We assume here that we're logging enough information in the WAL for
373 * log-shipping, since this is checked in PostmasterMain().
375 * NOTE: wal_level can only change at shutdown, so in most cases it is
376 * difficult for there to be WAL data that we can still see that was written
377 * at wal_level='minimal'.
381 * When we first start replication the standby will be behind the primary.
382 * For some applications, for example, synchronous replication, it is
383 * important to have a clear state for this initial catchup mode, so we
384 * can trigger actions when we change streaming state later. We may stay
385 * in this state for a long time, which is exactly why we want to be able
386 * to monitor whether or not we are still here.
388 WalSndSetState(WALSNDSTATE_CATCHUP);
390 /* Send a CopyBothResponse message, and start streaming */
391 pq_beginmessage(&buf, 'W');
392 pq_sendbyte(&buf, 0);
393 pq_sendint(&buf, 0, 2);
398 * Initialize position to the received one, then the xlog records begin to
399 * be shipped from that position
401 sentPtr = cmd->startpoint;
405 * Execute an incoming replication command.
408 HandleReplicationCommand(const char *cmd_string)
410 bool replication_started = false;
413 MemoryContext cmd_context;
414 MemoryContext old_context;
416 elog(DEBUG1, "received replication command: %s", cmd_string);
418 cmd_context = AllocSetContextCreate(CurrentMemoryContext,
419 "Replication command context",
420 ALLOCSET_DEFAULT_MINSIZE,
421 ALLOCSET_DEFAULT_INITSIZE,
422 ALLOCSET_DEFAULT_MAXSIZE);
423 old_context = MemoryContextSwitchTo(cmd_context);
425 replication_scanner_init(cmd_string);
426 parse_rc = replication_yyparse();
429 (errcode(ERRCODE_SYNTAX_ERROR),
430 (errmsg_internal("replication command parser returned %d",
433 cmd_node = replication_parse_result;
435 switch (cmd_node->type)
437 case T_IdentifySystemCmd:
441 case T_StartReplicationCmd:
442 StartReplication((StartReplicationCmd *) cmd_node);
444 /* break out of the loop */
445 replication_started = true;
448 case T_BaseBackupCmd:
449 SendBaseBackup((BaseBackupCmd *) cmd_node);
451 /* Send CommandComplete and ReadyForQuery messages */
452 EndCommand("SELECT", DestRemote);
453 ReadyForQuery(DestRemote);
454 /* ReadyForQuery did pq_flush for us */
459 (errcode(ERRCODE_PROTOCOL_VIOLATION),
460 errmsg("invalid standby query string: %s", cmd_string)));
464 MemoryContextSwitchTo(old_context);
465 MemoryContextDelete(cmd_context);
467 return replication_started;
471 * Check if the remote end has closed the connection.
474 ProcessRepliesIfAny(void)
476 unsigned char firstchar;
478 int received = false;
482 r = pq_getbyte_if_available(&firstchar);
485 /* unexpected error or EOF */
487 (errcode(ERRCODE_PROTOCOL_VIOLATION),
488 errmsg("unexpected EOF on standby connection")));
493 /* no data available without blocking */
497 /* Handle the very limited subset of commands expected in this phase */
501 * 'd' means a standby reply wrapped in a CopyData packet.
504 ProcessStandbyMessage();
509 * 'X' means that the standby is closing down the socket.
516 (errcode(ERRCODE_PROTOCOL_VIOLATION),
517 errmsg("invalid standby message type \"%c\"",
523 * Save the last reply timestamp if we've received at least one reply.
526 last_reply_timestamp = GetCurrentTimestamp();
530 * Process a status update message received from standby.
533 ProcessStandbyMessage(void)
537 resetStringInfo(&reply_message);
540 * Read the message contents.
542 if (pq_getmessage(&reply_message, 0))
545 (errcode(ERRCODE_PROTOCOL_VIOLATION),
546 errmsg("unexpected EOF on standby connection")));
551 * Check message type from the first byte.
553 msgtype = pq_getmsgbyte(&reply_message);
558 ProcessStandbyReplyMessage();
562 ProcessStandbyHSFeedbackMessage();
567 (errcode(ERRCODE_PROTOCOL_VIOLATION),
568 errmsg("unexpected message type \"%c\"", msgtype)));
574 * Regular reply from standby advising of WAL positions on standby server.
577 ProcessStandbyReplyMessage(void)
579 StandbyReplyMessage reply;
581 pq_copymsgbytes(&reply_message, (char *) &reply, sizeof(StandbyReplyMessage));
583 elog(DEBUG2, "write %X/%X flush %X/%X apply %X/%X",
584 reply.write.xlogid, reply.write.xrecoff,
585 reply.flush.xlogid, reply.flush.xrecoff,
586 reply.apply.xlogid, reply.apply.xrecoff);
589 * Update shared state for this WalSender process based on reply data from
593 /* use volatile pointer to prevent code rearrangement */
594 volatile WalSnd *walsnd = MyWalSnd;
596 SpinLockAcquire(&walsnd->mutex);
597 walsnd->write = reply.write;
598 walsnd->flush = reply.flush;
599 walsnd->apply = reply.apply;
600 SpinLockRelease(&walsnd->mutex);
603 if (!am_cascading_walsender)
604 SyncRepReleaseWaiters();
608 * Hot Standby feedback
611 ProcessStandbyHSFeedbackMessage(void)
613 StandbyHSFeedbackMessage reply;
614 TransactionId newxmin = InvalidTransactionId;
616 pq_copymsgbytes(&reply_message, (char *) &reply, sizeof(StandbyHSFeedbackMessage));
618 elog(DEBUG2, "hot standby feedback xmin %u epoch %u",
623 * Update the WalSender's proc xmin to allow it to be visible to
624 * snapshots. This will hold back the removal of dead rows and thereby
625 * prevent the generation of cleanup conflicts on the standby server.
627 if (TransactionIdIsValid(reply.xmin))
629 TransactionId nextXid;
631 bool epochOK = false;
633 GetNextXidAndEpoch(&nextXid, &nextEpoch);
636 * Epoch of oldestXmin should be same as standby or if the counter has
637 * wrapped, then one less than reply.
639 if (reply.xmin <= nextXid)
641 if (reply.epoch == nextEpoch)
646 if (nextEpoch > 0 && reply.epoch == nextEpoch - 1)
651 * Feedback from standby must not go backwards, nor should it go
652 * forwards further than our most recent xid.
654 if (epochOK && TransactionIdPrecedesOrEquals(reply.xmin, nextXid))
656 if (!TransactionIdIsValid(MyProc->xmin))
658 TransactionId oldestXmin = GetOldestXmin(true, true);
660 if (TransactionIdPrecedes(oldestXmin, reply.xmin))
661 newxmin = reply.xmin;
663 newxmin = oldestXmin;
667 if (TransactionIdPrecedes(MyProc->xmin, reply.xmin))
668 newxmin = reply.xmin;
670 newxmin = MyProc->xmin; /* stay the same */
676 * Grab the ProcArrayLock to set xmin, or invalidate for bad reply
678 if (MyProc->xmin != newxmin)
680 LWLockAcquire(ProcArrayLock, LW_SHARED);
681 MyProc->xmin = newxmin;
682 LWLockRelease(ProcArrayLock);
686 /* Main loop of walsender process */
690 char *output_message;
691 bool caughtup = false;
694 * Allocate buffer that will be used for each output message. We do this
695 * just once to reduce palloc overhead. The buffer must be made large
696 * enough for maximum-sized messages.
698 output_message = palloc(1 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE);
701 * Allocate buffer that will be used for processing reply messages. As
702 * above, do this just once to reduce palloc overhead.
704 initStringInfo(&reply_message);
706 /* Initialize the last reply timestamp */
707 last_reply_timestamp = GetCurrentTimestamp();
709 /* Loop forever, unless we get an error */
713 * Emergency bailout if postmaster has died. This is to avoid the
714 * necessity for manual cleanup of all postmaster children.
716 if (!PostmasterIsAlive())
719 /* Process any requests or signals received recently */
723 ProcessConfigFile(PGC_SIGHUP);
727 /* Normal exit from the walsender is here */
728 if (walsender_shutdown_requested)
730 /* Inform the standby that XLOG streaming was done */
731 pq_puttextmessage('C', "COPY 0");
738 * If we don't have any pending data in the output buffer, try to send
741 if (!pq_is_send_pending())
743 XLogSend(output_message, &caughtup);
746 * Even if we wrote all the WAL that was available when we started
747 * sending, more might have arrived while we were sending this
748 * batch. We had the latch set while sending, so we have not
749 * received any signals from that time. Let's arm the latch again,
750 * and after that check that we're still up-to-date.
752 if (caughtup && !pq_is_send_pending())
754 ResetLatch(&MyWalSnd->latch);
756 XLogSend(output_message, &caughtup);
760 /* Flush pending output to the client */
761 if (pq_flush_if_writable() != 0)
765 * When SIGUSR2 arrives, we send any outstanding logs up to the
766 * shutdown checkpoint record (i.e., the latest record) and exit.
767 * This may be a normal termination at shutdown, or a promotion,
768 * the walsender is not sure which.
770 if (walsender_ready_to_stop && !pq_is_send_pending())
772 XLogSend(output_message, &caughtup);
773 ProcessRepliesIfAny();
774 if (caughtup && !pq_is_send_pending())
775 walsender_shutdown_requested = true;
778 if ((caughtup || pq_is_send_pending()) &&
780 !walsender_shutdown_requested)
782 TimestampTz finish_time = 0;
786 /* Reschedule replication timeout */
787 if (replication_timeout > 0)
792 finish_time = TimestampTzPlusMilliseconds(last_reply_timestamp,
793 replication_timeout);
794 TimestampDifference(GetCurrentTimestamp(),
795 finish_time, &secs, &usecs);
796 sleeptime = secs * 1000 + usecs / 1000;
797 if (WalSndDelay < sleeptime)
798 sleeptime = WalSndDelay;
803 * XXX: Without timeout, we don't really need the periodic
804 * wakeups anymore, WaitLatchOrSocket should reliably wake up
805 * as soon as something interesting happens.
807 sleeptime = WalSndDelay;
811 wakeEvents = WL_LATCH_SET | WL_SOCKET_READABLE | WL_TIMEOUT;
812 if (pq_is_send_pending())
813 wakeEvents |= WL_SOCKET_WRITEABLE;
814 WaitLatchOrSocket(&MyWalSnd->latch, wakeEvents,
815 MyProcPort->sock, sleeptime);
817 /* Check for replication timeout */
818 if (replication_timeout > 0 &&
819 GetCurrentTimestamp() >= finish_time)
822 * Since typically expiration of replication timeout means
823 * communication problem, we don't send the error message to
827 (errmsg("terminating walsender process due to replication timeout")));
833 * If we're in catchup state, see if its time to move to streaming.
834 * This is an important state change for users, since before this
835 * point data loss might occur if the primary dies and we need to
836 * failover to the standby. The state change is also important for
837 * synchronous replication, since commits that started to wait at that
838 * point might wait for some time.
840 if (MyWalSnd->state == WALSNDSTATE_CATCHUP && caughtup)
843 (errmsg("standby \"%s\" has now caught up with primary",
845 WalSndSetState(WALSNDSTATE_STREAMING);
848 ProcessRepliesIfAny();
852 * Get here on send failure. Clean up and exit.
854 * Reset whereToSendOutput to prevent ereport from attempting to send any
855 * more messages to the standby.
857 if (whereToSendOutput == DestRemote)
858 whereToSendOutput = DestNone;
861 return 1; /* keep the compiler quiet */
864 /* Initialize a per-walsender data structure for this walsender process */
871 * WalSndCtl should be set up already (we inherit this by fork() or
872 * EXEC_BACKEND mechanism from the postmaster).
874 Assert(WalSndCtl != NULL);
875 Assert(MyWalSnd == NULL);
878 * Find a free walsender slot and reserve it. If this fails, we must be
879 * out of WalSnd structures.
881 for (i = 0; i < max_wal_senders; i++)
883 /* use volatile pointer to prevent code rearrangement */
884 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
886 SpinLockAcquire(&walsnd->mutex);
888 if (walsnd->pid != 0)
890 SpinLockRelease(&walsnd->mutex);
896 * Found a free slot. Reserve it for us.
898 walsnd->pid = MyProcPid;
899 MemSet(&walsnd->sentPtr, 0, sizeof(XLogRecPtr));
900 walsnd->state = WALSNDSTATE_STARTUP;
901 SpinLockRelease(&walsnd->mutex);
902 /* don't need the lock anymore */
903 OwnLatch((Latch *) &walsnd->latch);
904 MyWalSnd = (WalSnd *) walsnd;
909 if (MyWalSnd == NULL)
911 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
912 errmsg("number of requested standby connections "
913 "exceeds max_wal_senders (currently %d)",
916 /* Arrange to clean up at walsender exit */
917 on_shmem_exit(WalSndKill, 0);
920 /* Destroy the per-walsender data structure for this walsender process */
922 WalSndKill(int code, Datum arg)
924 Assert(MyWalSnd != NULL);
927 * Mark WalSnd struct no longer in use. Assume that no lock is required
931 DisownLatch(&MyWalSnd->latch);
933 /* WalSnd struct isn't mine anymore */
938 * Read 'count' bytes from WAL into 'buf', starting at location 'startptr'
940 * XXX probably this should be improved to suck data directly from the
941 * WAL buffers when possible.
943 * Will open, and keep open, one WAL segment stored in the global file
944 * descriptor sendFile. This means if XLogRead is used once, there will
945 * always be one descriptor left open until the process ends, but never
949 XLogRead(char *buf, XLogRecPtr startptr, Size count)
954 uint32 lastRemovedLog;
955 uint32 lastRemovedSeg;
970 startoff = recptr.xrecoff % XLogSegSize;
972 if (sendFile < 0 || !XLByteInSeg(recptr, sendId, sendSeg))
974 char path[MAXPGPATH];
976 /* Switch to another logfile segment */
980 XLByteToSeg(recptr, sendId, sendSeg);
981 XLogFilePath(path, ThisTimeLineID, sendId, sendSeg);
983 sendFile = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
987 * If the file is not found, assume it's because the standby
988 * asked for a too old WAL segment that has already been
989 * removed or recycled.
993 char filename[MAXFNAMELEN];
995 XLogFileName(filename, ThisTimeLineID, sendId, sendSeg);
997 (errcode_for_file_access(),
998 errmsg("requested WAL segment %s has already been removed",
1003 (errcode_for_file_access(),
1004 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
1005 path, sendId, sendSeg)));
1010 /* Need to seek in the file? */
1011 if (sendOff != startoff)
1013 if (lseek(sendFile, (off_t) startoff, SEEK_SET) < 0)
1015 (errcode_for_file_access(),
1016 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
1017 sendId, sendSeg, startoff)));
1021 /* How many bytes are within this segment? */
1022 if (nbytes > (XLogSegSize - startoff))
1023 segbytes = XLogSegSize - startoff;
1027 readbytes = read(sendFile, p, segbytes);
1030 (errcode_for_file_access(),
1031 errmsg("could not read from log file %u, segment %u, offset %u, "
1033 sendId, sendSeg, sendOff, (unsigned long) segbytes)));
1035 /* Update state for read */
1036 XLByteAdvance(recptr, readbytes);
1038 sendOff += readbytes;
1039 nbytes -= readbytes;
1044 * After reading into the buffer, check that what we read was valid. We do
1045 * this after reading, because even though the segment was present when we
1046 * opened it, it might get recycled or removed while we read it. The
1047 * read() succeeds in that case, but the data we tried to read might
1048 * already have been overwritten with new WAL records.
1050 XLogGetLastRemoved(&lastRemovedLog, &lastRemovedSeg);
1051 XLByteToSeg(startptr, log, seg);
1052 if (log < lastRemovedLog ||
1053 (log == lastRemovedLog && seg <= lastRemovedSeg))
1055 char filename[MAXFNAMELEN];
1057 XLogFileName(filename, ThisTimeLineID, log, seg);
1059 (errcode_for_file_access(),
1060 errmsg("requested WAL segment %s has already been removed",
1065 * During recovery, the currently-open WAL file might be replaced with
1066 * the file of the same name retrieved from archive. So we always need
1067 * to check what we read was valid after reading into the buffer. If it's
1068 * invalid, we try to open and read the file again.
1070 if (am_cascading_walsender)
1072 /* use volatile pointer to prevent code rearrangement */
1073 volatile WalSnd *walsnd = MyWalSnd;
1076 SpinLockAcquire(&walsnd->mutex);
1077 reload = walsnd->needreload;
1078 walsnd->needreload = false;
1079 SpinLockRelease(&walsnd->mutex);
1081 if (reload && sendFile >= 0)
1092 * Read up to MAX_SEND_SIZE bytes of WAL that's been flushed to disk,
1093 * but not yet sent to the client, and buffer it in the libpq output
1096 * msgbuf is a work area in which the output message is constructed. It's
1097 * passed in just so we can avoid re-palloc'ing the buffer on each cycle.
1098 * It must be of size 1 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE.
1100 * If there is no unsent WAL remaining, *caughtup is set to true, otherwise
1101 * *caughtup is set to false.
1105 XLogSend(char *msgbuf, bool *caughtup)
1107 XLogRecPtr SendRqstPtr;
1108 XLogRecPtr startptr;
1111 WalDataMessageHeader msghdr;
1114 * Attempt to send all data that's already been written out and fsync'd to
1115 * disk. We cannot go further than what's been written out given the
1116 * current implementation of XLogRead(). And in any case it's unsafe to
1117 * send WAL that is not securely down to disk on the master: if the master
1118 * subsequently crashes and restarts, slaves must not have applied any WAL
1119 * that gets lost on the master.
1121 SendRqstPtr = am_cascading_walsender ? GetStandbyFlushRecPtr() : GetFlushRecPtr();
1123 /* Quick exit if nothing to do */
1124 if (XLByteLE(SendRqstPtr, sentPtr))
1131 * Figure out how much to send in one message. If there's no more than
1132 * MAX_SEND_SIZE bytes to send, send everything. Otherwise send
1133 * MAX_SEND_SIZE bytes, but round back to logfile or page boundary.
1135 * The rounding is not only for performance reasons. Walreceiver relies on
1136 * the fact that we never split a WAL record across two messages. Since a
1137 * long WAL record is split at page boundary into continuation records,
1138 * page boundary is always a safe cut-off point. We also assume that
1139 * SendRqstPtr never points to the middle of a WAL record.
1142 if (startptr.xrecoff >= XLogFileSize)
1145 * crossing a logid boundary, skip the non-existent last log segment
1146 * in previous logical log file.
1148 startptr.xlogid += 1;
1149 startptr.xrecoff = 0;
1153 XLByteAdvance(endptr, MAX_SEND_SIZE);
1154 if (endptr.xlogid != startptr.xlogid)
1156 /* Don't cross a logfile boundary within one message */
1157 Assert(endptr.xlogid == startptr.xlogid + 1);
1158 endptr.xlogid = startptr.xlogid;
1159 endptr.xrecoff = XLogFileSize;
1162 /* if we went beyond SendRqstPtr, back off */
1163 if (XLByteLE(SendRqstPtr, endptr))
1165 endptr = SendRqstPtr;
1170 /* round down to page boundary. */
1171 endptr.xrecoff -= (endptr.xrecoff % XLOG_BLCKSZ);
1175 nbytes = endptr.xrecoff - startptr.xrecoff;
1176 Assert(nbytes <= MAX_SEND_SIZE);
1179 * OK to read and send the slice.
1184 * Read the log directly into the output buffer to avoid extra memcpy
1187 XLogRead(msgbuf + 1 + sizeof(WalDataMessageHeader), startptr, nbytes);
1190 * We fill the message header last so that the send timestamp is taken as
1193 msghdr.dataStart = startptr;
1194 msghdr.walEnd = SendRqstPtr;
1195 msghdr.sendTime = GetCurrentTimestamp();
1197 memcpy(msgbuf + 1, &msghdr, sizeof(WalDataMessageHeader));
1199 pq_putmessage_noblock('d', msgbuf, 1 + sizeof(WalDataMessageHeader) + nbytes);
1203 /* Update shared memory status */
1205 /* use volatile pointer to prevent code rearrangement */
1206 volatile WalSnd *walsnd = MyWalSnd;
1208 SpinLockAcquire(&walsnd->mutex);
1209 walsnd->sentPtr = sentPtr;
1210 SpinLockRelease(&walsnd->mutex);
1213 /* Report progress of XLOG streaming in PS display */
1214 if (update_process_title)
1216 char activitymsg[50];
1218 snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%X",
1219 sentPtr.xlogid, sentPtr.xrecoff);
1220 set_ps_display(activitymsg, false);
1227 * Request walsenders to reload the currently-open WAL file
1230 WalSndRqstFileReload(void)
1234 for (i = 0; i < max_wal_senders; i++)
1236 /* use volatile pointer to prevent code rearrangement */
1237 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1239 if (walsnd->pid == 0)
1242 SpinLockAcquire(&walsnd->mutex);
1243 walsnd->needreload = true;
1244 SpinLockRelease(&walsnd->mutex);
1248 /* SIGHUP: set flag to re-read config file at next convenient time */
1250 WalSndSigHupHandler(SIGNAL_ARGS)
1254 SetLatch(&MyWalSnd->latch);
1257 /* SIGTERM: set flag to shut down */
1259 WalSndShutdownHandler(SIGNAL_ARGS)
1261 walsender_shutdown_requested = true;
1263 SetLatch(&MyWalSnd->latch);
1267 * WalSndQuickDieHandler() occurs when signalled SIGQUIT by the postmaster.
1269 * Some backend has bought the farm,
1270 * so we need to stop what we're doing and exit.
1273 WalSndQuickDieHandler(SIGNAL_ARGS)
1275 PG_SETMASK(&BlockSig);
1278 * We DO NOT want to run proc_exit() callbacks -- we're here because
1279 * shared memory may be corrupted, so we don't want to try to clean up our
1280 * transaction. Just nail the windows shut and get out of town. Now that
1281 * there's an atexit callback to prevent third-party code from breaking
1282 * things by calling exit() directly, we have to reset the callbacks
1283 * explicitly to make this work as intended.
1288 * Note we do exit(2) not exit(0). This is to force the postmaster into a
1289 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
1290 * backend. This is necessary precisely because we don't clean up our
1291 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
1292 * should ensure the postmaster sees this as a crash, too, but no harm in
1293 * being doubly sure.)
1298 /* SIGUSR1: set flag to send WAL records */
1300 WalSndXLogSendHandler(SIGNAL_ARGS)
1302 latch_sigusr1_handler();
1305 /* SIGUSR2: set flag to do a last cycle and shut down afterwards */
1307 WalSndLastCycleHandler(SIGNAL_ARGS)
1309 walsender_ready_to_stop = true;
1311 SetLatch(&MyWalSnd->latch);
1314 /* Set up signal handlers */
1318 /* Set up signal handlers */
1319 pqsignal(SIGHUP, WalSndSigHupHandler); /* set flag to read config
1321 pqsignal(SIGINT, SIG_IGN); /* not used */
1322 pqsignal(SIGTERM, WalSndShutdownHandler); /* request shutdown */
1323 pqsignal(SIGQUIT, WalSndQuickDieHandler); /* hard crash time */
1324 pqsignal(SIGALRM, SIG_IGN);
1325 pqsignal(SIGPIPE, SIG_IGN);
1326 pqsignal(SIGUSR1, WalSndXLogSendHandler); /* request WAL sending */
1327 pqsignal(SIGUSR2, WalSndLastCycleHandler); /* request a last cycle and
1330 /* Reset some signals that are accepted by postmaster but not here */
1331 pqsignal(SIGCHLD, SIG_DFL);
1332 pqsignal(SIGTTIN, SIG_DFL);
1333 pqsignal(SIGTTOU, SIG_DFL);
1334 pqsignal(SIGCONT, SIG_DFL);
1335 pqsignal(SIGWINCH, SIG_DFL);
1338 /* Report shared-memory space needed by WalSndShmemInit */
1340 WalSndShmemSize(void)
1344 size = offsetof(WalSndCtlData, walsnds);
1345 size = add_size(size, mul_size(max_wal_senders, sizeof(WalSnd)));
1350 /* Allocate and initialize walsender-related shared memory */
1352 WalSndShmemInit(void)
1357 WalSndCtl = (WalSndCtlData *)
1358 ShmemInitStruct("Wal Sender Ctl", WalSndShmemSize(), &found);
1362 /* First time through, so initialize */
1363 MemSet(WalSndCtl, 0, WalSndShmemSize());
1365 SHMQueueInit(&(WalSndCtl->SyncRepQueue));
1367 for (i = 0; i < max_wal_senders; i++)
1369 WalSnd *walsnd = &WalSndCtl->walsnds[i];
1371 SpinLockInit(&walsnd->mutex);
1372 InitSharedLatch(&walsnd->latch);
1377 /* Wake up all walsenders */
1383 for (i = 0; i < max_wal_senders; i++)
1384 SetLatch(&WalSndCtl->walsnds[i].latch);
1387 /* Set state for current walsender (only called in walsender) */
1389 WalSndSetState(WalSndState state)
1391 /* use volatile pointer to prevent code rearrangement */
1392 volatile WalSnd *walsnd = MyWalSnd;
1394 Assert(am_walsender);
1396 if (walsnd->state == state)
1399 SpinLockAcquire(&walsnd->mutex);
1400 walsnd->state = state;
1401 SpinLockRelease(&walsnd->mutex);
1405 * Return a string constant representing the state. This is used
1406 * in system views, and should *not* be translated.
1409 WalSndGetStateString(WalSndState state)
1413 case WALSNDSTATE_STARTUP:
1415 case WALSNDSTATE_BACKUP:
1417 case WALSNDSTATE_CATCHUP:
1419 case WALSNDSTATE_STREAMING:
1427 * Returns activity of walsenders, including pids and xlog locations sent to
1431 pg_stat_get_wal_senders(PG_FUNCTION_ARGS)
1433 #define PG_STAT_GET_WAL_SENDERS_COLS 8
1434 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1436 Tuplestorestate *tupstore;
1437 MemoryContext per_query_ctx;
1438 MemoryContext oldcontext;
1441 int sync_standby = -1;
1444 /* check to see if caller supports us returning a tuplestore */
1445 if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
1447 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1448 errmsg("set-valued function called in context that cannot accept a set")));
1449 if (!(rsinfo->allowedModes & SFRM_Materialize))
1451 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1452 errmsg("materialize mode required, but it is not " \
1453 "allowed in this context")));
1455 /* Build a tuple descriptor for our result type */
1456 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1457 elog(ERROR, "return type must be a row type");
1459 per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1460 oldcontext = MemoryContextSwitchTo(per_query_ctx);
1462 tupstore = tuplestore_begin_heap(true, false, work_mem);
1463 rsinfo->returnMode = SFRM_Materialize;
1464 rsinfo->setResult = tupstore;
1465 rsinfo->setDesc = tupdesc;
1467 MemoryContextSwitchTo(oldcontext);
1470 * Get the priorities of sync standbys all in one go, to minimise lock
1471 * acquisitions and to allow us to evaluate who is the current sync
1472 * standby. This code must match the code in SyncRepReleaseWaiters().
1474 sync_priority = palloc(sizeof(int) * max_wal_senders);
1475 LWLockAcquire(SyncRepLock, LW_SHARED);
1476 for (i = 0; i < max_wal_senders; i++)
1478 /* use volatile pointer to prevent code rearrangement */
1479 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1481 if (walsnd->pid != 0)
1483 sync_priority[i] = walsnd->sync_standby_priority;
1485 if (walsnd->state == WALSNDSTATE_STREAMING &&
1486 walsnd->sync_standby_priority > 0 &&
1488 priority > walsnd->sync_standby_priority))
1490 priority = walsnd->sync_standby_priority;
1495 LWLockRelease(SyncRepLock);
1497 for (i = 0; i < max_wal_senders; i++)
1499 /* use volatile pointer to prevent code rearrangement */
1500 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1501 char location[MAXFNAMELEN];
1507 Datum values[PG_STAT_GET_WAL_SENDERS_COLS];
1508 bool nulls[PG_STAT_GET_WAL_SENDERS_COLS];
1510 if (walsnd->pid == 0)
1513 SpinLockAcquire(&walsnd->mutex);
1514 sentPtr = walsnd->sentPtr;
1515 state = walsnd->state;
1516 write = walsnd->write;
1517 flush = walsnd->flush;
1518 apply = walsnd->apply;
1519 SpinLockRelease(&walsnd->mutex);
1521 memset(nulls, 0, sizeof(nulls));
1522 values[0] = Int32GetDatum(walsnd->pid);
1527 * Only superusers can see details. Other users only get the pid
1528 * value to know it's a walsender, but no details.
1530 MemSet(&nulls[1], true, PG_STAT_GET_WAL_SENDERS_COLS - 1);
1534 values[1] = CStringGetTextDatum(WalSndGetStateString(state));
1536 snprintf(location, sizeof(location), "%X/%X",
1537 sentPtr.xlogid, sentPtr.xrecoff);
1538 values[2] = CStringGetTextDatum(location);
1540 if (write.xlogid == 0 && write.xrecoff == 0)
1542 snprintf(location, sizeof(location), "%X/%X",
1543 write.xlogid, write.xrecoff);
1544 values[3] = CStringGetTextDatum(location);
1546 if (flush.xlogid == 0 && flush.xrecoff == 0)
1548 snprintf(location, sizeof(location), "%X/%X",
1549 flush.xlogid, flush.xrecoff);
1550 values[4] = CStringGetTextDatum(location);
1552 if (apply.xlogid == 0 && apply.xrecoff == 0)
1554 snprintf(location, sizeof(location), "%X/%X",
1555 apply.xlogid, apply.xrecoff);
1556 values[5] = CStringGetTextDatum(location);
1558 values[6] = Int32GetDatum(sync_priority[i]);
1561 * More easily understood version of standby state. This is purely
1562 * informational, not different from priority.
1564 if (sync_priority[i] == 0)
1565 values[7] = CStringGetTextDatum("async");
1566 else if (i == sync_standby)
1567 values[7] = CStringGetTextDatum("sync");
1569 values[7] = CStringGetTextDatum("potential");
1572 tuplestore_putvalues(tupstore, tupdesc, values, nulls);
1574 pfree(sync_priority);
1576 /* clean up and return the tuplestore */
1577 tuplestore_donestoring(tupstore);
1583 * This isn't currently used for anything. Monitoring tools might be
1584 * interested in the future, and we'll need something like this in the
1585 * future for synchronous replication.
1589 * Returns the oldest Send position among walsenders. Or InvalidXLogRecPtr
1593 GetOldestWALSendPointer(void)
1595 XLogRecPtr oldest = {0, 0};
1599 for (i = 0; i < max_wal_senders; i++)
1601 /* use volatile pointer to prevent code rearrangement */
1602 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1605 if (walsnd->pid == 0)
1608 SpinLockAcquire(&walsnd->mutex);
1609 recptr = walsnd->sentPtr;
1610 SpinLockRelease(&walsnd->mutex);
1612 if (recptr.xlogid == 0 && recptr.xrecoff == 0)
1615 if (!found || XLByteLT(recptr, oldest))