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 */
77 int replication_timeout = 60 * 1000; /* maximum time to send one WAL data message */
80 * These variables are used similarly to openLogFile/Id/Seg/Off,
81 * but for walsender to read the XLOG.
83 static int sendFile = -1;
84 static uint32 sendId = 0;
85 static uint32 sendSeg = 0;
86 static uint32 sendOff = 0;
89 * How far have we sent WAL already? This is also advertised in
90 * MyWalSnd->sentPtr. (Actually, this is the next WAL location to send.)
92 static XLogRecPtr sentPtr = {0, 0};
95 * Buffer for processing reply messages.
97 static StringInfoData reply_message;
100 * Timestamp of the last receipt of the reply from the standby.
102 static TimestampTz last_reply_timestamp;
104 /* Flags set by signal handlers for later service in main loop */
105 static volatile sig_atomic_t got_SIGHUP = false;
106 volatile sig_atomic_t walsender_shutdown_requested = false;
107 volatile sig_atomic_t walsender_ready_to_stop = false;
109 /* Signal handlers */
110 static void WalSndSigHupHandler(SIGNAL_ARGS);
111 static void WalSndShutdownHandler(SIGNAL_ARGS);
112 static void WalSndQuickDieHandler(SIGNAL_ARGS);
113 static void WalSndXLogSendHandler(SIGNAL_ARGS);
114 static void WalSndLastCycleHandler(SIGNAL_ARGS);
116 /* Prototypes for private functions */
117 static bool HandleReplicationCommand(const char *cmd_string);
118 static int WalSndLoop(void);
119 static void InitWalSnd(void);
120 static void WalSndHandshake(void);
121 static void WalSndKill(int code, Datum arg);
122 static void XLogSend(char *msgbuf, bool *caughtup);
123 static void IdentifySystem(void);
124 static void StartReplication(StartReplicationCmd * cmd);
125 static void ProcessStandbyMessage(void);
126 static void ProcessStandbyReplyMessage(void);
127 static void ProcessStandbyHSFeedbackMessage(void);
128 static void ProcessRepliesIfAny(void);
131 /* Main entry point for walsender process */
135 MemoryContext walsnd_context;
137 if (RecoveryInProgress())
139 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
140 errmsg("recovery is still in progress, can't accept WAL streaming connections")));
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);
167 /* Tell the standby that walsender is ready for receiving commands */
168 ReadyForQuery(DestRemote);
170 /* Handle handshake messages before streaming */
173 /* Initialize shared memory status */
175 /* use volatile pointer to prevent code rearrangement */
176 volatile WalSnd *walsnd = MyWalSnd;
178 SpinLockAcquire(&walsnd->mutex);
179 walsnd->sentPtr = sentPtr;
180 SpinLockRelease(&walsnd->mutex);
185 /* Main loop of walsender */
190 * Execute commands from walreceiver, until we enter streaming mode.
193 WalSndHandshake(void)
195 StringInfoData input_message;
196 bool replication_started = false;
198 initStringInfo(&input_message);
200 while (!replication_started)
204 WalSndSetState(WALSNDSTATE_STARTUP);
205 set_ps_display("idle", false);
207 /* Wait for a command to arrive */
208 firstchar = pq_getbyte();
211 * Emergency bailout if postmaster has died. This is to avoid the
212 * necessity for manual cleanup of all postmaster children.
214 if (!PostmasterIsAlive(true))
218 * Check for any other interesting events that happened while we
224 ProcessConfigFile(PGC_SIGHUP);
227 if (firstchar != EOF)
230 * Read the message contents. This is expected to be done without
231 * blocking because we've been able to get message type code.
233 if (pq_getmessage(&input_message, 0))
234 firstchar = EOF; /* suitable message already logged */
237 /* Handle the very limited subset of commands expected in this phase */
240 case 'Q': /* Query message */
242 const char *query_string;
244 query_string = pq_getmsgstring(&input_message);
245 pq_getmsgend(&input_message);
247 if (HandleReplicationCommand(query_string))
248 replication_started = true;
253 /* standby is closing the connection */
257 /* standby disconnected unexpectedly */
259 (errcode(ERRCODE_PROTOCOL_VIOLATION),
260 errmsg("unexpected EOF on standby connection")));
265 (errcode(ERRCODE_PROTOCOL_VIOLATION),
266 errmsg("invalid standby handshake message type %d", firstchar)));
280 char xpos[MAXFNAMELEN];
284 * Reply with a result set with one row, three columns. First col is system
285 * ID, second is timeline ID, and third is current xlog location.
288 snprintf(sysid, sizeof(sysid), UINT64_FORMAT,
289 GetSystemIdentifier());
290 snprintf(tli, sizeof(tli), "%u", ThisTimeLineID);
292 logptr = GetInsertRecPtr();
294 snprintf(xpos, sizeof(xpos), "%X/%X",
295 logptr.xlogid, logptr.xrecoff);
297 /* Send a RowDescription message */
298 pq_beginmessage(&buf, 'T');
299 pq_sendint(&buf, 3, 2); /* 3 fields */
302 pq_sendstring(&buf, "systemid"); /* col name */
303 pq_sendint(&buf, 0, 4); /* table oid */
304 pq_sendint(&buf, 0, 2); /* attnum */
305 pq_sendint(&buf, TEXTOID, 4); /* type oid */
306 pq_sendint(&buf, -1, 2); /* typlen */
307 pq_sendint(&buf, 0, 4); /* typmod */
308 pq_sendint(&buf, 0, 2); /* format code */
311 pq_sendstring(&buf, "timeline"); /* col name */
312 pq_sendint(&buf, 0, 4); /* table oid */
313 pq_sendint(&buf, 0, 2); /* attnum */
314 pq_sendint(&buf, INT4OID, 4); /* type oid */
315 pq_sendint(&buf, 4, 2); /* typlen */
316 pq_sendint(&buf, 0, 4); /* typmod */
317 pq_sendint(&buf, 0, 2); /* format code */
320 pq_sendstring(&buf, "xlogpos");
321 pq_sendint(&buf, 0, 4);
322 pq_sendint(&buf, 0, 2);
323 pq_sendint(&buf, TEXTOID, 4);
324 pq_sendint(&buf, -1, 2);
325 pq_sendint(&buf, 0, 4);
326 pq_sendint(&buf, 0, 2);
329 /* Send a DataRow message */
330 pq_beginmessage(&buf, 'D');
331 pq_sendint(&buf, 3, 2); /* # of columns */
332 pq_sendint(&buf, strlen(sysid), 4); /* col1 len */
333 pq_sendbytes(&buf, (char *) &sysid, strlen(sysid));
334 pq_sendint(&buf, strlen(tli), 4); /* col2 len */
335 pq_sendbytes(&buf, (char *) tli, strlen(tli));
336 pq_sendint(&buf, strlen(xpos), 4); /* col3 len */
337 pq_sendbytes(&buf, (char *) xpos, strlen(xpos));
341 /* Send CommandComplete and ReadyForQuery messages */
342 EndCommand("SELECT", DestRemote);
343 ReadyForQuery(DestRemote);
344 /* ReadyForQuery did pq_flush for us */
351 StartReplication(StartReplicationCmd * cmd)
356 * Let postmaster know that we're streaming. Once we've declared us as
357 * a WAL sender process, postmaster will let us outlive the bgwriter and
358 * kill us last in the shutdown sequence, so we get a chance to stream
359 * all remaining WAL at shutdown, including the shutdown checkpoint.
360 * Note that there's no going back, and we mustn't write any WAL records
363 MarkPostmasterChildWalSender();
366 * Check that we're logging enough information in the WAL for
369 * NOTE: This only checks the current value of wal_level. Even if the
370 * current setting is not 'minimal', there can be old WAL in the pg_xlog
371 * directory that was created with 'minimal'. So this is not bulletproof,
372 * the purpose is just to give a user-friendly error message that hints
373 * how to configure the system correctly.
375 if (wal_level == WAL_LEVEL_MINIMAL)
377 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
378 errmsg("standby connections not allowed because 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
386 * able 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 %d",
522 * Save the last reply timestamp if we've received at least
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
590 * based on reply data from standby.
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 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
623 * to snapshots. This will hold back the removal of dead rows
624 * and thereby prevent the generation of cleanup conflicts
625 * 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
637 * if the counter has 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);
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 */
712 * Emergency bailout if postmaster has died. This is to avoid the
713 * necessity for manual cleanup of all postmaster children.
715 if (!PostmasterIsAlive(true))
718 /* Process any requests or signals received recently */
722 ProcessConfigFile(PGC_SIGHUP);
726 /* Normal exit from the walsender is here */
727 if (walsender_shutdown_requested)
729 /* Inform the standby that XLOG streaming was done */
730 pq_puttextmessage('C', "COPY 0");
737 * If we don't have any pending data in the output buffer, try to
740 if (!pq_is_send_pending())
742 XLogSend(output_message, &caughtup);
745 * Even if we wrote all the WAL that was available when we started
746 * sending, more might have arrived while we were sending this
747 * batch. We had the latch set while sending, so we have not
748 * received any signals from that time. Let's arm the latch
749 * again, and after that check that we're still up-to-date.
751 if (caughtup && !pq_is_send_pending())
753 ResetLatch(&MyWalSnd->latch);
755 XLogSend(output_message, &caughtup);
759 /* Flush pending output to the client */
760 if (pq_flush_if_writable() != 0)
764 * When SIGUSR2 arrives, we send any outstanding logs up to the
765 * shutdown checkpoint record (i.e., the latest record) and exit.
767 if (walsender_ready_to_stop && !pq_is_send_pending())
769 XLogSend(output_message, &caughtup);
770 ProcessRepliesIfAny();
771 if (caughtup && !pq_is_send_pending())
772 walsender_shutdown_requested = true;
775 if ((caughtup || pq_is_send_pending()) &&
777 !walsender_shutdown_requested)
779 TimestampTz finish_time;
782 /* Reschedule replication timeout */
783 if (replication_timeout > 0)
788 finish_time = TimestampTzPlusMilliseconds(last_reply_timestamp,
789 replication_timeout);
790 TimestampDifference(GetCurrentTimestamp(),
791 finish_time, &secs, &usecs);
792 sleeptime = secs * 1000 + usecs / 1000;
793 if (WalSndDelay < sleeptime)
794 sleeptime = WalSndDelay;
799 * XXX: Without timeout, we don't really need the periodic
800 * wakeups anymore, WaitLatchOrSocket should reliably wake up
801 * as soon as something interesting happens.
803 sleeptime = WalSndDelay;
807 WaitLatchOrSocket(&MyWalSnd->latch, MyProcPort->sock,
808 true, pq_is_send_pending(),
811 /* Check for replication timeout */
812 if (replication_timeout > 0 &&
813 GetCurrentTimestamp() >= finish_time)
816 * Since typically expiration of replication timeout means
817 * communication problem, we don't send the error message
821 (errmsg("terminating walsender process due to replication timeout")));
827 * If we're in catchup state, see if its time to move to streaming.
828 * This is an important state change for users, since before this
829 * point data loss might occur if the primary dies and we need to
830 * failover to the standby. The state change is also important for
831 * synchronous replication, since commits that started to wait at
832 * that point might wait for some time.
834 if (MyWalSnd->state == WALSNDSTATE_CATCHUP && caughtup)
837 (errmsg("standby \"%s\" has now caught up with primary",
839 WalSndSetState(WALSNDSTATE_STREAMING);
842 ProcessRepliesIfAny();
846 * Get here on send failure. Clean up and exit.
848 * Reset whereToSendOutput to prevent ereport from attempting to send any
849 * more messages to the standby.
851 if (whereToSendOutput == DestRemote)
852 whereToSendOutput = DestNone;
855 return 1; /* keep the compiler quiet */
858 /* Initialize a per-walsender data structure for this walsender process */
865 * WalSndCtl should be set up already (we inherit this by fork() or
866 * EXEC_BACKEND mechanism from the postmaster).
868 Assert(WalSndCtl != NULL);
869 Assert(MyWalSnd == NULL);
872 * Find a free walsender slot and reserve it. If this fails, we must be
873 * out of WalSnd structures.
875 for (i = 0; i < max_wal_senders; i++)
877 /* use volatile pointer to prevent code rearrangement */
878 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
880 SpinLockAcquire(&walsnd->mutex);
882 if (walsnd->pid != 0)
884 SpinLockRelease(&walsnd->mutex);
890 * Found a free slot. Reserve it for us.
892 walsnd->pid = MyProcPid;
893 MemSet(&walsnd->sentPtr, 0, sizeof(XLogRecPtr));
894 walsnd->state = WALSNDSTATE_STARTUP;
895 SpinLockRelease(&walsnd->mutex);
896 /* don't need the lock anymore */
897 OwnLatch((Latch *) &walsnd->latch);
898 MyWalSnd = (WalSnd *) walsnd;
903 if (MyWalSnd == NULL)
905 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
906 errmsg("number of requested standby connections "
907 "exceeds max_wal_senders (currently %d)",
910 /* Arrange to clean up at walsender exit */
911 on_shmem_exit(WalSndKill, 0);
914 /* Destroy the per-walsender data structure for this walsender process */
916 WalSndKill(int code, Datum arg)
918 Assert(MyWalSnd != NULL);
921 * Mark WalSnd struct no longer in use. Assume that no lock is required
925 DisownLatch(&MyWalSnd->latch);
927 /* WalSnd struct isn't mine anymore */
932 * Read 'nbytes' bytes from WAL into 'buf', starting at location 'recptr'
934 * XXX probably this should be improved to suck data directly from the
935 * WAL buffers when possible.
937 * Will open, and keep open, one WAL segment stored in the global file
938 * descriptor sendFile. This means if XLogRead is used once, there will
939 * always be one descriptor left open until the process ends, but never
943 XLogRead(char *buf, XLogRecPtr recptr, Size nbytes)
945 XLogRecPtr startRecPtr = recptr;
946 char path[MAXPGPATH];
947 uint32 lastRemovedLog;
948 uint32 lastRemovedSeg;
958 startoff = recptr.xrecoff % XLogSegSize;
960 if (sendFile < 0 || !XLByteInSeg(recptr, sendId, sendSeg))
962 /* Switch to another logfile segment */
966 XLByteToSeg(recptr, sendId, sendSeg);
967 XLogFilePath(path, ThisTimeLineID, sendId, sendSeg);
969 sendFile = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
973 * If the file is not found, assume it's because the standby
974 * asked for a too old WAL segment that has already been
975 * removed or recycled.
979 char filename[MAXFNAMELEN];
981 XLogFileName(filename, ThisTimeLineID, sendId, sendSeg);
983 (errcode_for_file_access(),
984 errmsg("requested WAL segment %s has already been removed",
989 (errcode_for_file_access(),
990 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
991 path, sendId, sendSeg)));
996 /* Need to seek in the file? */
997 if (sendOff != startoff)
999 if (lseek(sendFile, (off_t) startoff, SEEK_SET) < 0)
1001 (errcode_for_file_access(),
1002 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
1003 sendId, sendSeg, startoff)));
1007 /* How many bytes are within this segment? */
1008 if (nbytes > (XLogSegSize - startoff))
1009 segbytes = XLogSegSize - startoff;
1013 readbytes = read(sendFile, buf, segbytes);
1016 (errcode_for_file_access(),
1017 errmsg("could not read from log file %u, segment %u, offset %u, "
1019 sendId, sendSeg, sendOff, (unsigned long) segbytes)));
1021 /* Update state for read */
1022 XLByteAdvance(recptr, readbytes);
1024 sendOff += readbytes;
1025 nbytes -= readbytes;
1030 * After reading into the buffer, check that what we read was valid. We do
1031 * this after reading, because even though the segment was present when we
1032 * opened it, it might get recycled or removed while we read it. The
1033 * read() succeeds in that case, but the data we tried to read might
1034 * already have been overwritten with new WAL records.
1036 XLogGetLastRemoved(&lastRemovedLog, &lastRemovedSeg);
1037 XLByteToSeg(startRecPtr, log, seg);
1038 if (log < lastRemovedLog ||
1039 (log == lastRemovedLog && seg <= lastRemovedSeg))
1041 char filename[MAXFNAMELEN];
1043 XLogFileName(filename, ThisTimeLineID, log, seg);
1045 (errcode_for_file_access(),
1046 errmsg("requested WAL segment %s has already been removed",
1052 * Read up to MAX_SEND_SIZE bytes of WAL that's been flushed to disk,
1053 * but not yet sent to the client, and buffer it in the libpq output
1056 * msgbuf is a work area in which the output message is constructed. It's
1057 * passed in just so we can avoid re-palloc'ing the buffer on each cycle.
1058 * It must be of size 1 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE.
1060 * If there is no unsent WAL remaining, *caughtup is set to true, otherwise
1061 * *caughtup is set to false.
1065 XLogSend(char *msgbuf, bool *caughtup)
1067 XLogRecPtr SendRqstPtr;
1068 XLogRecPtr startptr;
1071 WalDataMessageHeader msghdr;
1074 * Attempt to send all data that's already been written out and fsync'd to
1075 * disk. We cannot go further than what's been written out given the
1076 * current implementation of XLogRead(). And in any case it's unsafe to
1077 * send WAL that is not securely down to disk on the master: if the master
1078 * subsequently crashes and restarts, slaves must not have applied any WAL
1079 * that gets lost on the master.
1081 SendRqstPtr = GetFlushRecPtr();
1083 /* Quick exit if nothing to do */
1084 if (XLByteLE(SendRqstPtr, sentPtr))
1091 * Figure out how much to send in one message. If there's no more than
1092 * MAX_SEND_SIZE bytes to send, send everything. Otherwise send
1093 * MAX_SEND_SIZE bytes, but round back to logfile or page boundary.
1095 * The rounding is not only for performance reasons. Walreceiver relies on
1096 * the fact that we never split a WAL record across two messages. Since a
1097 * long WAL record is split at page boundary into continuation records,
1098 * page boundary is always a safe cut-off point. We also assume that
1099 * SendRqstPtr never points to the middle of a WAL record.
1102 if (startptr.xrecoff >= XLogFileSize)
1105 * crossing a logid boundary, skip the non-existent last log segment
1106 * in previous logical log file.
1108 startptr.xlogid += 1;
1109 startptr.xrecoff = 0;
1113 XLByteAdvance(endptr, MAX_SEND_SIZE);
1114 if (endptr.xlogid != startptr.xlogid)
1116 /* Don't cross a logfile boundary within one message */
1117 Assert(endptr.xlogid == startptr.xlogid + 1);
1118 endptr.xlogid = startptr.xlogid;
1119 endptr.xrecoff = XLogFileSize;
1122 /* if we went beyond SendRqstPtr, back off */
1123 if (XLByteLE(SendRqstPtr, endptr))
1125 endptr = SendRqstPtr;
1130 /* round down to page boundary. */
1131 endptr.xrecoff -= (endptr.xrecoff % XLOG_BLCKSZ);
1135 nbytes = endptr.xrecoff - startptr.xrecoff;
1136 Assert(nbytes <= MAX_SEND_SIZE);
1139 * OK to read and send the slice.
1144 * Read the log directly into the output buffer to avoid extra memcpy
1147 XLogRead(msgbuf + 1 + sizeof(WalDataMessageHeader), startptr, nbytes);
1150 * We fill the message header last so that the send timestamp is taken as
1153 msghdr.dataStart = startptr;
1154 msghdr.walEnd = SendRqstPtr;
1155 msghdr.sendTime = GetCurrentTimestamp();
1157 memcpy(msgbuf + 1, &msghdr, sizeof(WalDataMessageHeader));
1159 pq_putmessage_noblock('d', msgbuf, 1 + sizeof(WalDataMessageHeader) + nbytes);
1163 /* Update shared memory status */
1165 /* use volatile pointer to prevent code rearrangement */
1166 volatile WalSnd *walsnd = MyWalSnd;
1168 SpinLockAcquire(&walsnd->mutex);
1169 walsnd->sentPtr = sentPtr;
1170 SpinLockRelease(&walsnd->mutex);
1173 /* Report progress of XLOG streaming in PS display */
1174 if (update_process_title)
1176 char activitymsg[50];
1178 snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%X",
1179 sentPtr.xlogid, sentPtr.xrecoff);
1180 set_ps_display(activitymsg, false);
1186 /* SIGHUP: set flag to re-read config file at next convenient time */
1188 WalSndSigHupHandler(SIGNAL_ARGS)
1192 SetLatch(&MyWalSnd->latch);
1195 /* SIGTERM: set flag to shut down */
1197 WalSndShutdownHandler(SIGNAL_ARGS)
1199 walsender_shutdown_requested = true;
1201 SetLatch(&MyWalSnd->latch);
1205 * WalSndQuickDieHandler() occurs when signalled SIGQUIT by the postmaster.
1207 * Some backend has bought the farm,
1208 * so we need to stop what we're doing and exit.
1211 WalSndQuickDieHandler(SIGNAL_ARGS)
1213 PG_SETMASK(&BlockSig);
1216 * We DO NOT want to run proc_exit() callbacks -- we're here because
1217 * shared memory may be corrupted, so we don't want to try to clean up our
1218 * transaction. Just nail the windows shut and get out of town. Now that
1219 * there's an atexit callback to prevent third-party code from breaking
1220 * things by calling exit() directly, we have to reset the callbacks
1221 * explicitly to make this work as intended.
1226 * Note we do exit(2) not exit(0). This is to force the postmaster into a
1227 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
1228 * backend. This is necessary precisely because we don't clean up our
1229 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
1230 * should ensure the postmaster sees this as a crash, too, but no harm in
1231 * being doubly sure.)
1236 /* SIGUSR1: set flag to send WAL records */
1238 WalSndXLogSendHandler(SIGNAL_ARGS)
1240 latch_sigusr1_handler();
1243 /* SIGUSR2: set flag to do a last cycle and shut down afterwards */
1245 WalSndLastCycleHandler(SIGNAL_ARGS)
1247 walsender_ready_to_stop = true;
1249 SetLatch(&MyWalSnd->latch);
1252 /* Set up signal handlers */
1256 /* Set up signal handlers */
1257 pqsignal(SIGHUP, WalSndSigHupHandler); /* set flag to read config
1259 pqsignal(SIGINT, SIG_IGN); /* not used */
1260 pqsignal(SIGTERM, WalSndShutdownHandler); /* request shutdown */
1261 pqsignal(SIGQUIT, WalSndQuickDieHandler); /* hard crash time */
1262 pqsignal(SIGALRM, SIG_IGN);
1263 pqsignal(SIGPIPE, SIG_IGN);
1264 pqsignal(SIGUSR1, WalSndXLogSendHandler); /* request WAL sending */
1265 pqsignal(SIGUSR2, WalSndLastCycleHandler); /* request a last cycle and
1268 /* Reset some signals that are accepted by postmaster but not here */
1269 pqsignal(SIGCHLD, SIG_DFL);
1270 pqsignal(SIGTTIN, SIG_DFL);
1271 pqsignal(SIGTTOU, SIG_DFL);
1272 pqsignal(SIGCONT, SIG_DFL);
1273 pqsignal(SIGWINCH, SIG_DFL);
1276 /* Report shared-memory space needed by WalSndShmemInit */
1278 WalSndShmemSize(void)
1282 size = offsetof(WalSndCtlData, walsnds);
1283 size = add_size(size, mul_size(max_wal_senders, sizeof(WalSnd)));
1288 /* Allocate and initialize walsender-related shared memory */
1290 WalSndShmemInit(void)
1295 WalSndCtl = (WalSndCtlData *)
1296 ShmemInitStruct("Wal Sender Ctl", WalSndShmemSize(), &found);
1300 /* First time through, so initialize */
1301 MemSet(WalSndCtl, 0, WalSndShmemSize());
1303 SHMQueueInit(&(WalSndCtl->SyncRepQueue));
1305 for (i = 0; i < max_wal_senders; i++)
1307 WalSnd *walsnd = &WalSndCtl->walsnds[i];
1309 SpinLockInit(&walsnd->mutex);
1310 InitSharedLatch(&walsnd->latch);
1315 /* Wake up all walsenders */
1321 for (i = 0; i < max_wal_senders; i++)
1322 SetLatch(&WalSndCtl->walsnds[i].latch);
1325 /* Set state for current walsender (only called in walsender) */
1327 WalSndSetState(WalSndState state)
1329 /* use volatile pointer to prevent code rearrangement */
1330 volatile WalSnd *walsnd = MyWalSnd;
1332 Assert(am_walsender);
1334 if (walsnd->state == state)
1337 SpinLockAcquire(&walsnd->mutex);
1338 walsnd->state = state;
1339 SpinLockRelease(&walsnd->mutex);
1343 * Return a string constant representing the state. This is used
1344 * in system views, and should *not* be translated.
1347 WalSndGetStateString(WalSndState state)
1351 case WALSNDSTATE_STARTUP:
1353 case WALSNDSTATE_BACKUP:
1355 case WALSNDSTATE_CATCHUP:
1357 case WALSNDSTATE_STREAMING:
1365 * Returns activity of walsenders, including pids and xlog locations sent to
1369 pg_stat_get_wal_senders(PG_FUNCTION_ARGS)
1371 #define PG_STAT_GET_WAL_SENDERS_COLS 8
1372 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1374 Tuplestorestate *tupstore;
1375 MemoryContext per_query_ctx;
1376 MemoryContext oldcontext;
1379 int sync_standby = -1;
1382 /* check to see if caller supports us returning a tuplestore */
1383 if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
1385 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1386 errmsg("set-valued function called in context that cannot accept a set")));
1387 if (!(rsinfo->allowedModes & SFRM_Materialize))
1389 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1390 errmsg("materialize mode required, but it is not " \
1391 "allowed in this context")));
1393 /* Build a tuple descriptor for our result type */
1394 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1395 elog(ERROR, "return type must be a row type");
1397 per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1398 oldcontext = MemoryContextSwitchTo(per_query_ctx);
1400 tupstore = tuplestore_begin_heap(true, false, work_mem);
1401 rsinfo->returnMode = SFRM_Materialize;
1402 rsinfo->setResult = tupstore;
1403 rsinfo->setDesc = tupdesc;
1405 MemoryContextSwitchTo(oldcontext);
1408 * Get the priorities of sync standbys all in one go, to minimise
1409 * lock acquisitions and to allow us to evaluate who is the current
1410 * sync standby. This code must match the code in SyncRepReleaseWaiters().
1412 sync_priority = palloc(sizeof(int) * max_wal_senders);
1413 LWLockAcquire(SyncRepLock, LW_SHARED);
1414 for (i = 0; i < max_wal_senders; i++)
1416 /* use volatile pointer to prevent code rearrangement */
1417 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1419 if (walsnd->pid != 0)
1421 sync_priority[i] = walsnd->sync_standby_priority;
1423 if (walsnd->state == WALSNDSTATE_STREAMING &&
1424 walsnd->sync_standby_priority > 0 &&
1426 priority > walsnd->sync_standby_priority))
1428 priority = walsnd->sync_standby_priority;
1433 LWLockRelease(SyncRepLock);
1435 for (i = 0; i < max_wal_senders; i++)
1437 /* use volatile pointer to prevent code rearrangement */
1438 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1439 char location[MAXFNAMELEN];
1445 Datum values[PG_STAT_GET_WAL_SENDERS_COLS];
1446 bool nulls[PG_STAT_GET_WAL_SENDERS_COLS];
1448 if (walsnd->pid == 0)
1451 SpinLockAcquire(&walsnd->mutex);
1452 sentPtr = walsnd->sentPtr;
1453 state = walsnd->state;
1454 write = walsnd->write;
1455 flush = walsnd->flush;
1456 apply = walsnd->apply;
1457 SpinLockRelease(&walsnd->mutex);
1459 memset(nulls, 0, sizeof(nulls));
1460 values[0] = Int32GetDatum(walsnd->pid);
1465 * Only superusers can see details. Other users only get
1466 * the pid value to know it's a walsender, but no details.
1468 MemSet(&nulls[1], true, PG_STAT_GET_WAL_SENDERS_COLS - 1);
1472 values[1] = CStringGetTextDatum(WalSndGetStateString(state));
1474 snprintf(location, sizeof(location), "%X/%X",
1475 sentPtr.xlogid, sentPtr.xrecoff);
1476 values[2] = CStringGetTextDatum(location);
1478 if (write.xlogid == 0 && write.xrecoff == 0)
1480 snprintf(location, sizeof(location), "%X/%X",
1481 write.xlogid, write.xrecoff);
1482 values[3] = CStringGetTextDatum(location);
1484 if (flush.xlogid == 0 && flush.xrecoff == 0)
1486 snprintf(location, sizeof(location), "%X/%X",
1487 flush.xlogid, flush.xrecoff);
1488 values[4] = CStringGetTextDatum(location);
1490 if (apply.xlogid == 0 && apply.xrecoff == 0)
1492 snprintf(location, sizeof(location), "%X/%X",
1493 apply.xlogid, apply.xrecoff);
1494 values[5] = CStringGetTextDatum(location);
1496 values[6] = Int32GetDatum(sync_priority[i]);
1499 * More easily understood version of standby state.
1500 * This is purely informational, not different from priority.
1502 if (sync_priority[i] == 0)
1503 values[7] = CStringGetTextDatum("ASYNC");
1504 else if (i == sync_standby)
1505 values[7] = CStringGetTextDatum("SYNC");
1507 values[7] = CStringGetTextDatum("POTENTIAL");
1510 tuplestore_putvalues(tupstore, tupdesc, values, nulls);
1512 pfree(sync_priority);
1514 /* clean up and return the tuplestore */
1515 tuplestore_donestoring(tupstore);
1521 * This isn't currently used for anything. Monitoring tools might be
1522 * interested in the future, and we'll need something like this in the
1523 * future for synchronous replication.
1527 * Returns the oldest Send position among walsenders. Or InvalidXLogRecPtr
1531 GetOldestWALSendPointer(void)
1533 XLogRecPtr oldest = {0, 0};
1537 for (i = 0; i < max_wal_senders; i++)
1539 /* use volatile pointer to prevent code rearrangement */
1540 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1543 if (walsnd->pid == 0)
1546 SpinLockAcquire(&walsnd->mutex);
1547 recptr = walsnd->sentPtr;
1548 SpinLockRelease(&walsnd->mutex);
1550 if (recptr.xlogid == 0 && recptr.xrecoff == 0)
1553 if (!found || XLByteLT(recptr, oldest))