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();
364 SendPostmasterSignal(PMSIGNAL_ADVANCE_STATE_MACHINE);
367 * Check that we're logging enough information in the WAL for
370 * NOTE: This only checks the current value of wal_level. Even if the
371 * current setting is not 'minimal', there can be old WAL in the pg_xlog
372 * directory that was created with 'minimal'. So this is not bulletproof,
373 * the purpose is just to give a user-friendly error message that hints
374 * how to configure the system correctly.
376 if (wal_level == WAL_LEVEL_MINIMAL)
378 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
379 errmsg("standby connections not allowed because wal_level=minimal")));
382 * When we first start replication the standby will be behind the primary.
383 * For some applications, for example, synchronous replication, it is
384 * important to have a clear state for this initial catchup mode, so we
385 * can trigger actions when we change streaming state later. We may stay
386 * in this state for a long time, which is exactly why we want to be
387 * able to monitor whether or not we are still here.
389 WalSndSetState(WALSNDSTATE_CATCHUP);
391 /* Send a CopyBothResponse message, and start streaming */
392 pq_beginmessage(&buf, 'W');
393 pq_sendbyte(&buf, 0);
394 pq_sendint(&buf, 0, 2);
399 * Initialize position to the received one, then the xlog records begin to
400 * be shipped from that position
402 sentPtr = cmd->startpoint;
406 * Execute an incoming replication command.
409 HandleReplicationCommand(const char *cmd_string)
411 bool replication_started = false;
414 MemoryContext cmd_context;
415 MemoryContext old_context;
417 elog(DEBUG1, "received replication command: %s", cmd_string);
419 cmd_context = AllocSetContextCreate(CurrentMemoryContext,
420 "Replication command context",
421 ALLOCSET_DEFAULT_MINSIZE,
422 ALLOCSET_DEFAULT_INITSIZE,
423 ALLOCSET_DEFAULT_MAXSIZE);
424 old_context = MemoryContextSwitchTo(cmd_context);
426 replication_scanner_init(cmd_string);
427 parse_rc = replication_yyparse();
430 (errcode(ERRCODE_SYNTAX_ERROR),
431 (errmsg_internal("replication command parser returned %d",
434 cmd_node = replication_parse_result;
436 switch (cmd_node->type)
438 case T_IdentifySystemCmd:
442 case T_StartReplicationCmd:
443 StartReplication((StartReplicationCmd *) cmd_node);
445 /* break out of the loop */
446 replication_started = true;
449 case T_BaseBackupCmd:
450 SendBaseBackup((BaseBackupCmd *) cmd_node);
452 /* Send CommandComplete and ReadyForQuery messages */
453 EndCommand("SELECT", DestRemote);
454 ReadyForQuery(DestRemote);
455 /* ReadyForQuery did pq_flush for us */
460 (errcode(ERRCODE_PROTOCOL_VIOLATION),
461 errmsg("invalid standby query string: %s", cmd_string)));
465 MemoryContextSwitchTo(old_context);
466 MemoryContextDelete(cmd_context);
468 return replication_started;
472 * Check if the remote end has closed the connection.
475 ProcessRepliesIfAny(void)
477 unsigned char firstchar;
479 int received = false;
483 r = pq_getbyte_if_available(&firstchar);
486 /* unexpected error or EOF */
488 (errcode(ERRCODE_PROTOCOL_VIOLATION),
489 errmsg("unexpected EOF on standby connection")));
494 /* no data available without blocking */
498 /* Handle the very limited subset of commands expected in this phase */
502 * 'd' means a standby reply wrapped in a CopyData packet.
505 ProcessStandbyMessage();
510 * 'X' means that the standby is closing down the socket.
517 (errcode(ERRCODE_PROTOCOL_VIOLATION),
518 errmsg("invalid standby message type %d",
523 * Save the last reply timestamp if we've received at least
527 last_reply_timestamp = GetCurrentTimestamp();
531 * Process a status update message received from standby.
534 ProcessStandbyMessage(void)
538 resetStringInfo(&reply_message);
541 * Read the message contents.
543 if (pq_getmessage(&reply_message, 0))
546 (errcode(ERRCODE_PROTOCOL_VIOLATION),
547 errmsg("unexpected EOF on standby connection")));
552 * Check message type from the first byte.
554 msgtype = pq_getmsgbyte(&reply_message);
559 ProcessStandbyReplyMessage();
563 ProcessStandbyHSFeedbackMessage();
568 (errcode(ERRCODE_PROTOCOL_VIOLATION),
569 errmsg("unexpected message type %c", msgtype)));
575 * Regular reply from standby advising of WAL positions on standby server.
578 ProcessStandbyReplyMessage(void)
580 StandbyReplyMessage reply;
582 pq_copymsgbytes(&reply_message, (char *) &reply, sizeof(StandbyReplyMessage));
584 elog(DEBUG2, "write %X/%X flush %X/%X apply %X/%X",
585 reply.write.xlogid, reply.write.xrecoff,
586 reply.flush.xlogid, reply.flush.xrecoff,
587 reply.apply.xlogid, reply.apply.xrecoff);
590 * Update shared state for this WalSender process
591 * based on reply data from standby.
594 /* use volatile pointer to prevent code rearrangement */
595 volatile WalSnd *walsnd = MyWalSnd;
597 SpinLockAcquire(&walsnd->mutex);
598 walsnd->write = reply.write;
599 walsnd->flush = reply.flush;
600 walsnd->apply = reply.apply;
601 SpinLockRelease(&walsnd->mutex);
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
624 * to snapshots. This will hold back the removal of dead rows
625 * and thereby prevent the generation of cleanup conflicts
626 * on the standby server.
628 if (TransactionIdIsValid(reply.xmin))
630 TransactionId nextXid;
632 bool epochOK = false;
634 GetNextXidAndEpoch(&nextXid, &nextEpoch);
637 * Epoch of oldestXmin should be same as standby or
638 * if the counter has wrapped, then one less than reply.
640 if (reply.xmin <= nextXid)
642 if (reply.epoch == nextEpoch)
647 if (nextEpoch > 0 && reply.epoch == nextEpoch - 1)
652 * Feedback from standby must not go backwards, nor should it go
653 * forwards further than our most recent xid.
655 if (epochOK && TransactionIdPrecedesOrEquals(reply.xmin, nextXid))
657 if (!TransactionIdIsValid(MyProc->xmin))
659 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(true))
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
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
750 * again, 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.
768 if (walsender_ready_to_stop && !pq_is_send_pending())
770 XLogSend(output_message, &caughtup);
771 ProcessRepliesIfAny();
772 if (caughtup && !pq_is_send_pending())
773 walsender_shutdown_requested = true;
776 if ((caughtup || pq_is_send_pending()) &&
778 !walsender_shutdown_requested)
780 TimestampTz finish_time = 0;
783 /* Reschedule replication timeout */
784 if (replication_timeout > 0)
789 finish_time = TimestampTzPlusMilliseconds(last_reply_timestamp,
790 replication_timeout);
791 TimestampDifference(GetCurrentTimestamp(),
792 finish_time, &secs, &usecs);
793 sleeptime = secs * 1000 + usecs / 1000;
794 if (WalSndDelay < sleeptime)
795 sleeptime = WalSndDelay;
800 * XXX: Without timeout, we don't really need the periodic
801 * wakeups anymore, WaitLatchOrSocket should reliably wake up
802 * as soon as something interesting happens.
804 sleeptime = WalSndDelay;
808 WaitLatchOrSocket(&MyWalSnd->latch, MyProcPort->sock,
809 true, pq_is_send_pending(),
812 /* Check for replication timeout */
813 if (replication_timeout > 0 &&
814 GetCurrentTimestamp() >= finish_time)
817 * Since typically expiration of replication timeout means
818 * communication problem, we don't send the error message
822 (errmsg("terminating walsender process due to replication timeout")));
828 * If we're in catchup state, see if its time to move to streaming.
829 * This is an important state change for users, since before this
830 * point data loss might occur if the primary dies and we need to
831 * failover to the standby. The state change is also important for
832 * synchronous replication, since commits that started to wait at
833 * that point might wait for some time.
835 if (MyWalSnd->state == WALSNDSTATE_CATCHUP && caughtup)
838 (errmsg("standby \"%s\" has now caught up with primary",
840 WalSndSetState(WALSNDSTATE_STREAMING);
843 ProcessRepliesIfAny();
847 * Get here on send failure. Clean up and exit.
849 * Reset whereToSendOutput to prevent ereport from attempting to send any
850 * more messages to the standby.
852 if (whereToSendOutput == DestRemote)
853 whereToSendOutput = DestNone;
856 return 1; /* keep the compiler quiet */
859 /* Initialize a per-walsender data structure for this walsender process */
866 * WalSndCtl should be set up already (we inherit this by fork() or
867 * EXEC_BACKEND mechanism from the postmaster).
869 Assert(WalSndCtl != NULL);
870 Assert(MyWalSnd == NULL);
873 * Find a free walsender slot and reserve it. If this fails, we must be
874 * out of WalSnd structures.
876 for (i = 0; i < max_wal_senders; i++)
878 /* use volatile pointer to prevent code rearrangement */
879 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
881 SpinLockAcquire(&walsnd->mutex);
883 if (walsnd->pid != 0)
885 SpinLockRelease(&walsnd->mutex);
891 * Found a free slot. Reserve it for us.
893 walsnd->pid = MyProcPid;
894 MemSet(&walsnd->sentPtr, 0, sizeof(XLogRecPtr));
895 walsnd->state = WALSNDSTATE_STARTUP;
896 SpinLockRelease(&walsnd->mutex);
897 /* don't need the lock anymore */
898 OwnLatch((Latch *) &walsnd->latch);
899 MyWalSnd = (WalSnd *) walsnd;
904 if (MyWalSnd == NULL)
906 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
907 errmsg("number of requested standby connections "
908 "exceeds max_wal_senders (currently %d)",
911 /* Arrange to clean up at walsender exit */
912 on_shmem_exit(WalSndKill, 0);
915 /* Destroy the per-walsender data structure for this walsender process */
917 WalSndKill(int code, Datum arg)
919 Assert(MyWalSnd != NULL);
922 * Mark WalSnd struct no longer in use. Assume that no lock is required
926 DisownLatch(&MyWalSnd->latch);
928 /* WalSnd struct isn't mine anymore */
933 * Read 'nbytes' bytes from WAL into 'buf', starting at location 'recptr'
935 * XXX probably this should be improved to suck data directly from the
936 * WAL buffers when possible.
938 * Will open, and keep open, one WAL segment stored in the global file
939 * descriptor sendFile. This means if XLogRead is used once, there will
940 * always be one descriptor left open until the process ends, but never
944 XLogRead(char *buf, XLogRecPtr recptr, Size nbytes)
946 XLogRecPtr startRecPtr = recptr;
947 char path[MAXPGPATH];
948 uint32 lastRemovedLog;
949 uint32 lastRemovedSeg;
959 startoff = recptr.xrecoff % XLogSegSize;
961 if (sendFile < 0 || !XLByteInSeg(recptr, sendId, sendSeg))
963 /* Switch to another logfile segment */
967 XLByteToSeg(recptr, sendId, sendSeg);
968 XLogFilePath(path, ThisTimeLineID, sendId, sendSeg);
970 sendFile = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
974 * If the file is not found, assume it's because the standby
975 * asked for a too old WAL segment that has already been
976 * removed or recycled.
980 char filename[MAXFNAMELEN];
982 XLogFileName(filename, ThisTimeLineID, sendId, sendSeg);
984 (errcode_for_file_access(),
985 errmsg("requested WAL segment %s has already been removed",
990 (errcode_for_file_access(),
991 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
992 path, sendId, sendSeg)));
997 /* Need to seek in the file? */
998 if (sendOff != startoff)
1000 if (lseek(sendFile, (off_t) startoff, SEEK_SET) < 0)
1002 (errcode_for_file_access(),
1003 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
1004 sendId, sendSeg, startoff)));
1008 /* How many bytes are within this segment? */
1009 if (nbytes > (XLogSegSize - startoff))
1010 segbytes = XLogSegSize - startoff;
1014 readbytes = read(sendFile, buf, segbytes);
1017 (errcode_for_file_access(),
1018 errmsg("could not read from log file %u, segment %u, offset %u, "
1020 sendId, sendSeg, sendOff, (unsigned long) segbytes)));
1022 /* Update state for read */
1023 XLByteAdvance(recptr, readbytes);
1025 sendOff += readbytes;
1026 nbytes -= readbytes;
1031 * After reading into the buffer, check that what we read was valid. We do
1032 * this after reading, because even though the segment was present when we
1033 * opened it, it might get recycled or removed while we read it. The
1034 * read() succeeds in that case, but the data we tried to read might
1035 * already have been overwritten with new WAL records.
1037 XLogGetLastRemoved(&lastRemovedLog, &lastRemovedSeg);
1038 XLByteToSeg(startRecPtr, log, seg);
1039 if (log < lastRemovedLog ||
1040 (log == lastRemovedLog && seg <= lastRemovedSeg))
1042 char filename[MAXFNAMELEN];
1044 XLogFileName(filename, ThisTimeLineID, log, seg);
1046 (errcode_for_file_access(),
1047 errmsg("requested WAL segment %s has already been removed",
1053 * Read up to MAX_SEND_SIZE bytes of WAL that's been flushed to disk,
1054 * but not yet sent to the client, and buffer it in the libpq output
1057 * msgbuf is a work area in which the output message is constructed. It's
1058 * passed in just so we can avoid re-palloc'ing the buffer on each cycle.
1059 * It must be of size 1 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE.
1061 * If there is no unsent WAL remaining, *caughtup is set to true, otherwise
1062 * *caughtup is set to false.
1066 XLogSend(char *msgbuf, bool *caughtup)
1068 XLogRecPtr SendRqstPtr;
1069 XLogRecPtr startptr;
1072 WalDataMessageHeader msghdr;
1075 * Attempt to send all data that's already been written out and fsync'd to
1076 * disk. We cannot go further than what's been written out given the
1077 * current implementation of XLogRead(). And in any case it's unsafe to
1078 * send WAL that is not securely down to disk on the master: if the master
1079 * subsequently crashes and restarts, slaves must not have applied any WAL
1080 * that gets lost on the master.
1082 SendRqstPtr = GetFlushRecPtr();
1084 /* Quick exit if nothing to do */
1085 if (XLByteLE(SendRqstPtr, sentPtr))
1092 * Figure out how much to send in one message. If there's no more than
1093 * MAX_SEND_SIZE bytes to send, send everything. Otherwise send
1094 * MAX_SEND_SIZE bytes, but round back to logfile or page boundary.
1096 * The rounding is not only for performance reasons. Walreceiver relies on
1097 * the fact that we never split a WAL record across two messages. Since a
1098 * long WAL record is split at page boundary into continuation records,
1099 * page boundary is always a safe cut-off point. We also assume that
1100 * SendRqstPtr never points to the middle of a WAL record.
1103 if (startptr.xrecoff >= XLogFileSize)
1106 * crossing a logid boundary, skip the non-existent last log segment
1107 * in previous logical log file.
1109 startptr.xlogid += 1;
1110 startptr.xrecoff = 0;
1114 XLByteAdvance(endptr, MAX_SEND_SIZE);
1115 if (endptr.xlogid != startptr.xlogid)
1117 /* Don't cross a logfile boundary within one message */
1118 Assert(endptr.xlogid == startptr.xlogid + 1);
1119 endptr.xlogid = startptr.xlogid;
1120 endptr.xrecoff = XLogFileSize;
1123 /* if we went beyond SendRqstPtr, back off */
1124 if (XLByteLE(SendRqstPtr, endptr))
1126 endptr = SendRqstPtr;
1131 /* round down to page boundary. */
1132 endptr.xrecoff -= (endptr.xrecoff % XLOG_BLCKSZ);
1136 nbytes = endptr.xrecoff - startptr.xrecoff;
1137 Assert(nbytes <= MAX_SEND_SIZE);
1140 * OK to read and send the slice.
1145 * Read the log directly into the output buffer to avoid extra memcpy
1148 XLogRead(msgbuf + 1 + sizeof(WalDataMessageHeader), startptr, nbytes);
1151 * We fill the message header last so that the send timestamp is taken as
1154 msghdr.dataStart = startptr;
1155 msghdr.walEnd = SendRqstPtr;
1156 msghdr.sendTime = GetCurrentTimestamp();
1158 memcpy(msgbuf + 1, &msghdr, sizeof(WalDataMessageHeader));
1160 pq_putmessage_noblock('d', msgbuf, 1 + sizeof(WalDataMessageHeader) + nbytes);
1164 /* Update shared memory status */
1166 /* use volatile pointer to prevent code rearrangement */
1167 volatile WalSnd *walsnd = MyWalSnd;
1169 SpinLockAcquire(&walsnd->mutex);
1170 walsnd->sentPtr = sentPtr;
1171 SpinLockRelease(&walsnd->mutex);
1174 /* Report progress of XLOG streaming in PS display */
1175 if (update_process_title)
1177 char activitymsg[50];
1179 snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%X",
1180 sentPtr.xlogid, sentPtr.xrecoff);
1181 set_ps_display(activitymsg, false);
1187 /* SIGHUP: set flag to re-read config file at next convenient time */
1189 WalSndSigHupHandler(SIGNAL_ARGS)
1193 SetLatch(&MyWalSnd->latch);
1196 /* SIGTERM: set flag to shut down */
1198 WalSndShutdownHandler(SIGNAL_ARGS)
1200 walsender_shutdown_requested = true;
1202 SetLatch(&MyWalSnd->latch);
1206 * WalSndQuickDieHandler() occurs when signalled SIGQUIT by the postmaster.
1208 * Some backend has bought the farm,
1209 * so we need to stop what we're doing and exit.
1212 WalSndQuickDieHandler(SIGNAL_ARGS)
1214 PG_SETMASK(&BlockSig);
1217 * We DO NOT want to run proc_exit() callbacks -- we're here because
1218 * shared memory may be corrupted, so we don't want to try to clean up our
1219 * transaction. Just nail the windows shut and get out of town. Now that
1220 * there's an atexit callback to prevent third-party code from breaking
1221 * things by calling exit() directly, we have to reset the callbacks
1222 * explicitly to make this work as intended.
1227 * Note we do exit(2) not exit(0). This is to force the postmaster into a
1228 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
1229 * backend. This is necessary precisely because we don't clean up our
1230 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
1231 * should ensure the postmaster sees this as a crash, too, but no harm in
1232 * being doubly sure.)
1237 /* SIGUSR1: set flag to send WAL records */
1239 WalSndXLogSendHandler(SIGNAL_ARGS)
1241 latch_sigusr1_handler();
1244 /* SIGUSR2: set flag to do a last cycle and shut down afterwards */
1246 WalSndLastCycleHandler(SIGNAL_ARGS)
1248 walsender_ready_to_stop = true;
1250 SetLatch(&MyWalSnd->latch);
1253 /* Set up signal handlers */
1257 /* Set up signal handlers */
1258 pqsignal(SIGHUP, WalSndSigHupHandler); /* set flag to read config
1260 pqsignal(SIGINT, SIG_IGN); /* not used */
1261 pqsignal(SIGTERM, WalSndShutdownHandler); /* request shutdown */
1262 pqsignal(SIGQUIT, WalSndQuickDieHandler); /* hard crash time */
1263 pqsignal(SIGALRM, SIG_IGN);
1264 pqsignal(SIGPIPE, SIG_IGN);
1265 pqsignal(SIGUSR1, WalSndXLogSendHandler); /* request WAL sending */
1266 pqsignal(SIGUSR2, WalSndLastCycleHandler); /* request a last cycle and
1269 /* Reset some signals that are accepted by postmaster but not here */
1270 pqsignal(SIGCHLD, SIG_DFL);
1271 pqsignal(SIGTTIN, SIG_DFL);
1272 pqsignal(SIGTTOU, SIG_DFL);
1273 pqsignal(SIGCONT, SIG_DFL);
1274 pqsignal(SIGWINCH, SIG_DFL);
1277 /* Report shared-memory space needed by WalSndShmemInit */
1279 WalSndShmemSize(void)
1283 size = offsetof(WalSndCtlData, walsnds);
1284 size = add_size(size, mul_size(max_wal_senders, sizeof(WalSnd)));
1289 /* Allocate and initialize walsender-related shared memory */
1291 WalSndShmemInit(void)
1296 WalSndCtl = (WalSndCtlData *)
1297 ShmemInitStruct("Wal Sender Ctl", WalSndShmemSize(), &found);
1301 /* First time through, so initialize */
1302 MemSet(WalSndCtl, 0, WalSndShmemSize());
1304 SHMQueueInit(&(WalSndCtl->SyncRepQueue));
1306 for (i = 0; i < max_wal_senders; i++)
1308 WalSnd *walsnd = &WalSndCtl->walsnds[i];
1310 SpinLockInit(&walsnd->mutex);
1311 InitSharedLatch(&walsnd->latch);
1316 /* Wake up all walsenders */
1322 for (i = 0; i < max_wal_senders; i++)
1323 SetLatch(&WalSndCtl->walsnds[i].latch);
1326 /* Set state for current walsender (only called in walsender) */
1328 WalSndSetState(WalSndState state)
1330 /* use volatile pointer to prevent code rearrangement */
1331 volatile WalSnd *walsnd = MyWalSnd;
1333 Assert(am_walsender);
1335 if (walsnd->state == state)
1338 SpinLockAcquire(&walsnd->mutex);
1339 walsnd->state = state;
1340 SpinLockRelease(&walsnd->mutex);
1344 * Return a string constant representing the state. This is used
1345 * in system views, and should *not* be translated.
1348 WalSndGetStateString(WalSndState state)
1352 case WALSNDSTATE_STARTUP:
1354 case WALSNDSTATE_BACKUP:
1356 case WALSNDSTATE_CATCHUP:
1358 case WALSNDSTATE_STREAMING:
1366 * Returns activity of walsenders, including pids and xlog locations sent to
1370 pg_stat_get_wal_senders(PG_FUNCTION_ARGS)
1372 #define PG_STAT_GET_WAL_SENDERS_COLS 8
1373 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1375 Tuplestorestate *tupstore;
1376 MemoryContext per_query_ctx;
1377 MemoryContext oldcontext;
1380 int sync_standby = -1;
1383 /* check to see if caller supports us returning a tuplestore */
1384 if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
1386 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1387 errmsg("set-valued function called in context that cannot accept a set")));
1388 if (!(rsinfo->allowedModes & SFRM_Materialize))
1390 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1391 errmsg("materialize mode required, but it is not " \
1392 "allowed in this context")));
1394 /* Build a tuple descriptor for our result type */
1395 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1396 elog(ERROR, "return type must be a row type");
1398 per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1399 oldcontext = MemoryContextSwitchTo(per_query_ctx);
1401 tupstore = tuplestore_begin_heap(true, false, work_mem);
1402 rsinfo->returnMode = SFRM_Materialize;
1403 rsinfo->setResult = tupstore;
1404 rsinfo->setDesc = tupdesc;
1406 MemoryContextSwitchTo(oldcontext);
1409 * Get the priorities of sync standbys all in one go, to minimise
1410 * lock acquisitions and to allow us to evaluate who is the current
1411 * sync standby. This code must match the code in SyncRepReleaseWaiters().
1413 sync_priority = palloc(sizeof(int) * max_wal_senders);
1414 LWLockAcquire(SyncRepLock, LW_SHARED);
1415 for (i = 0; i < max_wal_senders; i++)
1417 /* use volatile pointer to prevent code rearrangement */
1418 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1420 if (walsnd->pid != 0)
1422 sync_priority[i] = walsnd->sync_standby_priority;
1424 if (walsnd->state == WALSNDSTATE_STREAMING &&
1425 walsnd->sync_standby_priority > 0 &&
1427 priority > walsnd->sync_standby_priority))
1429 priority = walsnd->sync_standby_priority;
1434 LWLockRelease(SyncRepLock);
1436 for (i = 0; i < max_wal_senders; i++)
1438 /* use volatile pointer to prevent code rearrangement */
1439 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1440 char location[MAXFNAMELEN];
1446 Datum values[PG_STAT_GET_WAL_SENDERS_COLS];
1447 bool nulls[PG_STAT_GET_WAL_SENDERS_COLS];
1449 if (walsnd->pid == 0)
1452 SpinLockAcquire(&walsnd->mutex);
1453 sentPtr = walsnd->sentPtr;
1454 state = walsnd->state;
1455 write = walsnd->write;
1456 flush = walsnd->flush;
1457 apply = walsnd->apply;
1458 SpinLockRelease(&walsnd->mutex);
1460 memset(nulls, 0, sizeof(nulls));
1461 values[0] = Int32GetDatum(walsnd->pid);
1466 * Only superusers can see details. Other users only get
1467 * the pid value to know it's a walsender, but no details.
1469 MemSet(&nulls[1], true, PG_STAT_GET_WAL_SENDERS_COLS - 1);
1473 values[1] = CStringGetTextDatum(WalSndGetStateString(state));
1475 snprintf(location, sizeof(location), "%X/%X",
1476 sentPtr.xlogid, sentPtr.xrecoff);
1477 values[2] = CStringGetTextDatum(location);
1479 if (write.xlogid == 0 && write.xrecoff == 0)
1481 snprintf(location, sizeof(location), "%X/%X",
1482 write.xlogid, write.xrecoff);
1483 values[3] = CStringGetTextDatum(location);
1485 if (flush.xlogid == 0 && flush.xrecoff == 0)
1487 snprintf(location, sizeof(location), "%X/%X",
1488 flush.xlogid, flush.xrecoff);
1489 values[4] = CStringGetTextDatum(location);
1491 if (apply.xlogid == 0 && apply.xrecoff == 0)
1493 snprintf(location, sizeof(location), "%X/%X",
1494 apply.xlogid, apply.xrecoff);
1495 values[5] = CStringGetTextDatum(location);
1497 values[6] = Int32GetDatum(sync_priority[i]);
1500 * More easily understood version of standby state.
1501 * This is purely informational, not different from priority.
1503 if (sync_priority[i] == 0)
1504 values[7] = CStringGetTextDatum("ASYNC");
1505 else if (i == sync_standby)
1506 values[7] = CStringGetTextDatum("SYNC");
1508 values[7] = CStringGetTextDatum("POTENTIAL");
1511 tuplestore_putvalues(tupstore, tupdesc, values, nulls);
1513 pfree(sync_priority);
1515 /* clean up and return the tuplestore */
1516 tuplestore_donestoring(tupstore);
1522 * This isn't currently used for anything. Monitoring tools might be
1523 * interested in the future, and we'll need something like this in the
1524 * future for synchronous replication.
1528 * Returns the oldest Send position among walsenders. Or InvalidXLogRecPtr
1532 GetOldestWALSendPointer(void)
1534 XLogRecPtr oldest = {0, 0};
1538 for (i = 0; i < max_wal_senders; i++)
1540 /* use volatile pointer to prevent code rearrangement */
1541 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1544 if (walsnd->pid == 0)
1547 SpinLockAcquire(&walsnd->mutex);
1548 recptr = walsnd->sentPtr;
1549 SpinLockRelease(&walsnd->mutex);
1551 if (recptr.xlogid == 0 && recptr.xrecoff == 0)
1554 if (!found || XLByteLT(recptr, oldest))