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 "tcop/tcopprot.h"
57 #include "utils/builtins.h"
58 #include "utils/guc.h"
59 #include "utils/memutils.h"
60 #include "utils/ps_status.h"
61 #include "utils/resowner.h"
64 /* Array of WalSnds in shared memory */
65 WalSndCtlData *WalSndCtl = NULL;
67 /* My slot in the shared memory array */
68 static WalSnd *MyWalSnd = NULL;
71 bool am_walsender = false; /* Am I a walsender process ? */
73 /* User-settable parameters for walsender */
74 int max_wal_senders = 0; /* the maximum number of concurrent walsenders */
75 int WalSndDelay = 200; /* max sleep time between some actions */
78 * These variables are used similarly to openLogFile/Id/Seg/Off,
79 * but for walsender to read the XLOG.
81 static int sendFile = -1;
82 static uint32 sendId = 0;
83 static uint32 sendSeg = 0;
84 static uint32 sendOff = 0;
87 * How far have we sent WAL already? This is also advertised in
88 * MyWalSnd->sentPtr. (Actually, this is the next WAL location to send.)
90 static XLogRecPtr sentPtr = {0, 0};
92 /* Flags set by signal handlers for later service in main loop */
93 static volatile sig_atomic_t got_SIGHUP = false;
94 volatile sig_atomic_t walsender_shutdown_requested = false;
95 volatile sig_atomic_t walsender_ready_to_stop = false;
98 static void WalSndSigHupHandler(SIGNAL_ARGS);
99 static void WalSndShutdownHandler(SIGNAL_ARGS);
100 static void WalSndQuickDieHandler(SIGNAL_ARGS);
101 static void WalSndXLogSendHandler(SIGNAL_ARGS);
102 static void WalSndLastCycleHandler(SIGNAL_ARGS);
104 /* Prototypes for private functions */
105 static bool HandleReplicationCommand(const char *cmd_string);
106 static int WalSndLoop(void);
107 static void InitWalSnd(void);
108 static void WalSndHandshake(void);
109 static void WalSndKill(int code, Datum arg);
110 static bool XLogSend(char *msgbuf, bool *caughtup);
111 static void IdentifySystem(void);
112 static void StartReplication(StartReplicationCmd * cmd);
113 static void ProcessStandbyReplyMessage(void);
114 static void ProcessRepliesIfAny(void);
117 /* Main entry point for walsender process */
121 MemoryContext walsnd_context;
123 if (RecoveryInProgress())
125 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
126 errmsg("recovery is still in progress, can't accept WAL streaming connections")));
128 /* Create a per-walsender data structure in shared memory */
132 * Create a memory context that we will do all our work in. We do this so
133 * that we can reset the context during error recovery and thereby avoid
134 * possible memory leaks. Formerly this code just ran in
135 * TopMemoryContext, but resetting that would be a really bad idea.
137 * XXX: we don't actually attempt error recovery in walsender, we just
138 * close the connection and exit.
140 walsnd_context = AllocSetContextCreate(TopMemoryContext,
142 ALLOCSET_DEFAULT_MINSIZE,
143 ALLOCSET_DEFAULT_INITSIZE,
144 ALLOCSET_DEFAULT_MAXSIZE);
145 MemoryContextSwitchTo(walsnd_context);
147 /* Set up resource owner */
148 CurrentResourceOwner = ResourceOwnerCreate(NULL, "walsender top-level resource owner");
150 /* Unblock signals (they were blocked when the postmaster forked us) */
151 PG_SETMASK(&UnBlockSig);
153 /* Tell the standby that walsender is ready for receiving commands */
154 ReadyForQuery(DestRemote);
156 /* Handle handshake messages before streaming */
159 /* Initialize shared memory status */
161 /* use volatile pointer to prevent code rearrangement */
162 volatile WalSnd *walsnd = MyWalSnd;
164 SpinLockAcquire(&walsnd->mutex);
165 walsnd->sentPtr = sentPtr;
166 SpinLockRelease(&walsnd->mutex);
169 /* Main loop of walsender */
174 * Execute commands from walreceiver, until we enter streaming mode.
177 WalSndHandshake(void)
179 StringInfoData input_message;
180 bool replication_started = false;
182 initStringInfo(&input_message);
184 while (!replication_started)
188 WalSndSetState(WALSNDSTATE_STARTUP);
189 set_ps_display("idle", false);
191 /* Wait for a command to arrive */
192 firstchar = pq_getbyte();
195 * Emergency bailout if postmaster has died. This is to avoid the
196 * necessity for manual cleanup of all postmaster children.
198 if (!PostmasterIsAlive(true))
202 * Check for any other interesting events that happened while we
208 ProcessConfigFile(PGC_SIGHUP);
211 if (firstchar != EOF)
214 * Read the message contents. This is expected to be done without
215 * blocking because we've been able to get message type code.
217 if (pq_getmessage(&input_message, 0))
218 firstchar = EOF; /* suitable message already logged */
221 /* Handle the very limited subset of commands expected in this phase */
224 case 'Q': /* Query message */
226 const char *query_string;
228 query_string = pq_getmsgstring(&input_message);
229 pq_getmsgend(&input_message);
231 if (HandleReplicationCommand(query_string))
232 replication_started = true;
237 /* standby is closing the connection */
241 /* standby disconnected unexpectedly */
243 (errcode(ERRCODE_PROTOCOL_VIOLATION),
244 errmsg("unexpected EOF on standby connection")));
249 (errcode(ERRCODE_PROTOCOL_VIOLATION),
250 errmsg("invalid standby handshake message type %d", firstchar)));
264 char xpos[MAXFNAMELEN];
268 * Reply with a result set with one row, three columns. First col is system
269 * ID, second is timeline ID, and third is current xlog location.
272 snprintf(sysid, sizeof(sysid), UINT64_FORMAT,
273 GetSystemIdentifier());
274 snprintf(tli, sizeof(tli), "%u", ThisTimeLineID);
276 logptr = GetInsertRecPtr();
278 snprintf(xpos, sizeof(xpos), "%X/%X",
279 logptr.xlogid, logptr.xrecoff);
281 /* Send a RowDescription message */
282 pq_beginmessage(&buf, 'T');
283 pq_sendint(&buf, 3, 2); /* 3 fields */
286 pq_sendstring(&buf, "systemid"); /* col name */
287 pq_sendint(&buf, 0, 4); /* table oid */
288 pq_sendint(&buf, 0, 2); /* attnum */
289 pq_sendint(&buf, TEXTOID, 4); /* type oid */
290 pq_sendint(&buf, -1, 2); /* typlen */
291 pq_sendint(&buf, 0, 4); /* typmod */
292 pq_sendint(&buf, 0, 2); /* format code */
295 pq_sendstring(&buf, "timeline"); /* col name */
296 pq_sendint(&buf, 0, 4); /* table oid */
297 pq_sendint(&buf, 0, 2); /* attnum */
298 pq_sendint(&buf, INT4OID, 4); /* type oid */
299 pq_sendint(&buf, 4, 2); /* typlen */
300 pq_sendint(&buf, 0, 4); /* typmod */
301 pq_sendint(&buf, 0, 2); /* format code */
304 pq_sendstring(&buf, "xlogpos");
305 pq_sendint(&buf, 0, 4);
306 pq_sendint(&buf, 0, 2);
307 pq_sendint(&buf, TEXTOID, 4);
308 pq_sendint(&buf, -1, 2);
309 pq_sendint(&buf, 0, 4);
310 pq_sendint(&buf, 0, 2);
313 /* Send a DataRow message */
314 pq_beginmessage(&buf, 'D');
315 pq_sendint(&buf, 3, 2); /* # of columns */
316 pq_sendint(&buf, strlen(sysid), 4); /* col1 len */
317 pq_sendbytes(&buf, (char *) &sysid, strlen(sysid));
318 pq_sendint(&buf, strlen(tli), 4); /* col2 len */
319 pq_sendbytes(&buf, (char *) tli, strlen(tli));
320 pq_sendint(&buf, strlen(xpos), 4); /* col3 len */
321 pq_sendbytes(&buf, (char *) xpos, strlen(xpos));
325 /* Send CommandComplete and ReadyForQuery messages */
326 EndCommand("SELECT", DestRemote);
327 ReadyForQuery(DestRemote);
328 /* ReadyForQuery did pq_flush for us */
335 StartReplication(StartReplicationCmd * cmd)
340 * Let postmaster know that we're streaming. Once we've declared us as
341 * a WAL sender process, postmaster will let us outlive the bgwriter and
342 * kill us last in the shutdown sequence, so we get a chance to stream
343 * all remaining WAL at shutdown, including the shutdown checkpoint.
344 * Note that there's no going back, and we mustn't write any WAL records
347 MarkPostmasterChildWalSender();
350 * Check that we're logging enough information in the WAL for
353 * NOTE: This only checks the current value of wal_level. Even if the
354 * current setting is not 'minimal', there can be old WAL in the pg_xlog
355 * directory that was created with 'minimal'. So this is not bulletproof,
356 * the purpose is just to give a user-friendly error message that hints
357 * how to configure the system correctly.
359 if (wal_level == WAL_LEVEL_MINIMAL)
361 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
362 errmsg("standby connections not allowed because wal_level=minimal")));
364 /* Send a CopyBothResponse message, and start streaming */
365 pq_beginmessage(&buf, 'W');
366 pq_sendbyte(&buf, 0);
367 pq_sendint(&buf, 0, 2);
372 * Initialize position to the received one, then the xlog records begin to
373 * be shipped from that position
375 sentPtr = cmd->startpoint;
379 * Execute an incoming replication command.
382 HandleReplicationCommand(const char *cmd_string)
384 bool replication_started = false;
387 MemoryContext cmd_context;
388 MemoryContext old_context;
390 elog(DEBUG1, "received replication command: %s", cmd_string);
392 cmd_context = AllocSetContextCreate(CurrentMemoryContext,
393 "Replication command context",
394 ALLOCSET_DEFAULT_MINSIZE,
395 ALLOCSET_DEFAULT_INITSIZE,
396 ALLOCSET_DEFAULT_MAXSIZE);
397 old_context = MemoryContextSwitchTo(cmd_context);
399 replication_scanner_init(cmd_string);
400 parse_rc = replication_yyparse();
403 (errcode(ERRCODE_SYNTAX_ERROR),
404 (errmsg_internal("replication command parser returned %d",
407 cmd_node = replication_parse_result;
409 switch (cmd_node->type)
411 case T_IdentifySystemCmd:
415 case T_StartReplicationCmd:
416 StartReplication((StartReplicationCmd *) cmd_node);
418 /* break out of the loop */
419 replication_started = true;
422 case T_BaseBackupCmd:
423 SendBaseBackup((BaseBackupCmd *) cmd_node);
425 /* Send CommandComplete and ReadyForQuery messages */
426 EndCommand("SELECT", DestRemote);
427 ReadyForQuery(DestRemote);
428 /* ReadyForQuery did pq_flush for us */
433 (errcode(ERRCODE_PROTOCOL_VIOLATION),
434 errmsg("invalid standby query string: %s", cmd_string)));
438 MemoryContextSwitchTo(old_context);
439 MemoryContextDelete(cmd_context);
441 return replication_started;
445 * Check if the remote end has closed the connection.
448 ProcessRepliesIfAny(void)
450 unsigned char firstchar;
453 r = pq_getbyte_if_available(&firstchar);
456 /* unexpected error or EOF */
458 (errcode(ERRCODE_PROTOCOL_VIOLATION),
459 errmsg("unexpected EOF on standby connection")));
464 /* no data available without blocking */
468 /* Handle the very limited subset of commands expected in this phase */
472 * 'd' means a standby reply wrapped in a COPY BOTH packet.
475 ProcessStandbyReplyMessage();
479 * 'X' means that the standby is closing down the socket.
486 (errcode(ERRCODE_PROTOCOL_VIOLATION),
487 errmsg("invalid standby closing message type %d",
493 * Process a status update message received from standby.
496 ProcessStandbyReplyMessage(void)
498 static StringInfoData input_message;
499 StandbyReplyMessage reply;
502 initStringInfo(&input_message);
505 * Read the message contents.
507 if (pq_getmessage(&input_message, 0))
510 (errcode(ERRCODE_PROTOCOL_VIOLATION),
511 errmsg("unexpected EOF on standby connection")));
516 * Check message type from the first byte. At the moment, there is only
519 msgtype = pq_getmsgbyte(&input_message);
522 (errcode(ERRCODE_PROTOCOL_VIOLATION),
523 errmsg("unexpected message type %c", msgtype)));
525 pq_copymsgbytes(&input_message, (char *) &reply, sizeof(StandbyReplyMessage));
527 elog(DEBUG2, "write %X/%X flush %X/%X apply %X/%X ",
528 reply.write.xlogid, reply.write.xrecoff,
529 reply.flush.xlogid, reply.flush.xrecoff,
530 reply.apply.xlogid, reply.apply.xrecoff);
533 * Update shared state for this WalSender process
534 * based on reply data from standby.
537 /* use volatile pointer to prevent code rearrangement */
538 volatile WalSnd *walsnd = MyWalSnd;
540 SpinLockAcquire(&walsnd->mutex);
541 walsnd->write = reply.write;
542 walsnd->flush = reply.flush;
543 walsnd->apply = reply.apply;
544 SpinLockRelease(&walsnd->mutex);
548 /* Main loop of walsender process */
552 char *output_message;
553 bool caughtup = false;
556 * Allocate buffer that will be used for each output message. We do this
557 * just once to reduce palloc overhead. The buffer must be made large
558 * enough for maximum-sized messages.
560 output_message = palloc(1 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE);
562 /* Loop forever, unless we get an error */
566 * Emergency bailout if postmaster has died. This is to avoid the
567 * necessity for manual cleanup of all postmaster children.
569 if (!PostmasterIsAlive(true))
572 /* Process any requests or signals received recently */
576 ProcessConfigFile(PGC_SIGHUP);
580 * When SIGUSR2 arrives, we send all outstanding logs up to the
581 * shutdown checkpoint record (i.e., the latest record) and exit.
583 if (walsender_ready_to_stop)
585 if (!XLogSend(output_message, &caughtup))
587 ProcessRepliesIfAny();
589 walsender_shutdown_requested = true;
592 /* Normal exit from the walsender is here */
593 if (walsender_shutdown_requested)
595 /* Inform the standby that XLOG streaming was done */
596 pq_puttextmessage('C', "COPY 0");
603 * If we had sent all accumulated WAL in last round, nap for the
604 * configured time before retrying.
609 * Even if we wrote all the WAL that was available when we started
610 * sending, more might have arrived while we were sending this
611 * batch. We had the latch set while sending, so we have not
612 * received any signals from that time. Let's arm the latch
613 * again, and after that check that we're still up-to-date.
615 ResetLatch(&MyWalSnd->latch);
617 if (!XLogSend(output_message, &caughtup))
619 if (caughtup && !got_SIGHUP && !walsender_ready_to_stop && !walsender_shutdown_requested)
622 * XXX: We don't really need the periodic wakeups anymore,
623 * WaitLatchOrSocket should reliably wake up as soon as
624 * something interesting happens.
628 WaitLatchOrSocket(&MyWalSnd->latch, MyProcPort->sock,
629 WalSndDelay * 1000L);
634 /* Attempt to send the log once every loop */
635 if (!XLogSend(output_message, &caughtup))
639 /* Update our state to indicate if we're behind or not */
640 WalSndSetState(caughtup ? WALSNDSTATE_STREAMING : WALSNDSTATE_CATCHUP);
641 ProcessRepliesIfAny();
645 * Get here on send failure. Clean up and exit.
647 * Reset whereToSendOutput to prevent ereport from attempting to send any
648 * more messages to the standby.
650 if (whereToSendOutput == DestRemote)
651 whereToSendOutput = DestNone;
654 return 1; /* keep the compiler quiet */
657 /* Initialize a per-walsender data structure for this walsender process */
664 * WalSndCtl should be set up already (we inherit this by fork() or
665 * EXEC_BACKEND mechanism from the postmaster).
667 Assert(WalSndCtl != NULL);
668 Assert(MyWalSnd == NULL);
671 * Find a free walsender slot and reserve it. If this fails, we must be
672 * out of WalSnd structures.
674 for (i = 0; i < max_wal_senders; i++)
676 /* use volatile pointer to prevent code rearrangement */
677 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
679 SpinLockAcquire(&walsnd->mutex);
681 if (walsnd->pid != 0)
683 SpinLockRelease(&walsnd->mutex);
689 * Found a free slot. Reserve it for us.
691 walsnd->pid = MyProcPid;
692 MemSet(&walsnd->sentPtr, 0, sizeof(XLogRecPtr));
693 walsnd->state = WALSNDSTATE_STARTUP;
694 SpinLockRelease(&walsnd->mutex);
695 /* don't need the lock anymore */
696 OwnLatch((Latch *) &walsnd->latch);
697 MyWalSnd = (WalSnd *) walsnd;
702 if (MyWalSnd == NULL)
704 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
705 errmsg("number of requested standby connections "
706 "exceeds max_wal_senders (currently %d)",
709 /* Arrange to clean up at walsender exit */
710 on_shmem_exit(WalSndKill, 0);
713 /* Destroy the per-walsender data structure for this walsender process */
715 WalSndKill(int code, Datum arg)
717 Assert(MyWalSnd != NULL);
720 * Mark WalSnd struct no longer in use. Assume that no lock is required
724 DisownLatch(&MyWalSnd->latch);
726 /* WalSnd struct isn't mine anymore */
731 * Read 'nbytes' bytes from WAL into 'buf', starting at location 'recptr'
733 * XXX probably this should be improved to suck data directly from the
734 * WAL buffers when possible.
736 * Will open, and keep open, one WAL segment stored in the global file
737 * descriptor sendFile. This means if XLogRead is used once, there will
738 * always be one descriptor left open until the process ends, but never
742 XLogRead(char *buf, XLogRecPtr recptr, Size nbytes)
744 XLogRecPtr startRecPtr = recptr;
745 char path[MAXPGPATH];
746 uint32 lastRemovedLog;
747 uint32 lastRemovedSeg;
757 startoff = recptr.xrecoff % XLogSegSize;
759 if (sendFile < 0 || !XLByteInSeg(recptr, sendId, sendSeg))
761 /* Switch to another logfile segment */
765 XLByteToSeg(recptr, sendId, sendSeg);
766 XLogFilePath(path, ThisTimeLineID, sendId, sendSeg);
768 sendFile = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
772 * If the file is not found, assume it's because the standby
773 * asked for a too old WAL segment that has already been
774 * removed or recycled.
778 char filename[MAXFNAMELEN];
780 XLogFileName(filename, ThisTimeLineID, sendId, sendSeg);
782 (errcode_for_file_access(),
783 errmsg("requested WAL segment %s has already been removed",
788 (errcode_for_file_access(),
789 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
790 path, sendId, sendSeg)));
795 /* Need to seek in the file? */
796 if (sendOff != startoff)
798 if (lseek(sendFile, (off_t) startoff, SEEK_SET) < 0)
800 (errcode_for_file_access(),
801 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
802 sendId, sendSeg, startoff)));
806 /* How many bytes are within this segment? */
807 if (nbytes > (XLogSegSize - startoff))
808 segbytes = XLogSegSize - startoff;
812 readbytes = read(sendFile, buf, segbytes);
815 (errcode_for_file_access(),
816 errmsg("could not read from log file %u, segment %u, offset %u, "
818 sendId, sendSeg, sendOff, (unsigned long) segbytes)));
820 /* Update state for read */
821 XLByteAdvance(recptr, readbytes);
823 sendOff += readbytes;
829 * After reading into the buffer, check that what we read was valid. We do
830 * this after reading, because even though the segment was present when we
831 * opened it, it might get recycled or removed while we read it. The
832 * read() succeeds in that case, but the data we tried to read might
833 * already have been overwritten with new WAL records.
835 XLogGetLastRemoved(&lastRemovedLog, &lastRemovedSeg);
836 XLByteToSeg(startRecPtr, log, seg);
837 if (log < lastRemovedLog ||
838 (log == lastRemovedLog && seg <= lastRemovedSeg))
840 char filename[MAXFNAMELEN];
842 XLogFileName(filename, ThisTimeLineID, log, seg);
844 (errcode_for_file_access(),
845 errmsg("requested WAL segment %s has already been removed",
851 * Read up to MAX_SEND_SIZE bytes of WAL that's been flushed to disk,
852 * but not yet sent to the client, and send it.
854 * msgbuf is a work area in which the output message is constructed. It's
855 * passed in just so we can avoid re-palloc'ing the buffer on each cycle.
856 * It must be of size 1 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE.
858 * If there is no unsent WAL remaining, *caughtup is set to true, otherwise
859 * *caughtup is set to false.
861 * Returns true if OK, false if trouble.
864 XLogSend(char *msgbuf, bool *caughtup)
866 XLogRecPtr SendRqstPtr;
870 WalDataMessageHeader msghdr;
873 * Attempt to send all data that's already been written out and fsync'd to
874 * disk. We cannot go further than what's been written out given the
875 * current implementation of XLogRead(). And in any case it's unsafe to
876 * send WAL that is not securely down to disk on the master: if the master
877 * subsequently crashes and restarts, slaves must not have applied any WAL
878 * that gets lost on the master.
880 SendRqstPtr = GetFlushRecPtr();
882 /* Quick exit if nothing to do */
883 if (XLByteLE(SendRqstPtr, sentPtr))
890 * Figure out how much to send in one message. If there's no more than
891 * MAX_SEND_SIZE bytes to send, send everything. Otherwise send
892 * MAX_SEND_SIZE bytes, but round back to logfile or page boundary.
894 * The rounding is not only for performance reasons. Walreceiver relies on
895 * the fact that we never split a WAL record across two messages. Since a
896 * long WAL record is split at page boundary into continuation records,
897 * page boundary is always a safe cut-off point. We also assume that
898 * SendRqstPtr never points to the middle of a WAL record.
901 if (startptr.xrecoff >= XLogFileSize)
904 * crossing a logid boundary, skip the non-existent last log segment
905 * in previous logical log file.
907 startptr.xlogid += 1;
908 startptr.xrecoff = 0;
912 XLByteAdvance(endptr, MAX_SEND_SIZE);
913 if (endptr.xlogid != startptr.xlogid)
915 /* Don't cross a logfile boundary within one message */
916 Assert(endptr.xlogid == startptr.xlogid + 1);
917 endptr.xlogid = startptr.xlogid;
918 endptr.xrecoff = XLogFileSize;
921 /* if we went beyond SendRqstPtr, back off */
922 if (XLByteLE(SendRqstPtr, endptr))
924 endptr = SendRqstPtr;
929 /* round down to page boundary. */
930 endptr.xrecoff -= (endptr.xrecoff % XLOG_BLCKSZ);
934 nbytes = endptr.xrecoff - startptr.xrecoff;
935 Assert(nbytes <= MAX_SEND_SIZE);
938 * OK to read and send the slice.
943 * Read the log directly into the output buffer to avoid extra memcpy
946 XLogRead(msgbuf + 1 + sizeof(WalDataMessageHeader), startptr, nbytes);
949 * We fill the message header last so that the send timestamp is taken as
952 msghdr.dataStart = startptr;
953 msghdr.walEnd = SendRqstPtr;
954 msghdr.sendTime = GetCurrentTimestamp();
956 memcpy(msgbuf + 1, &msghdr, sizeof(WalDataMessageHeader));
958 pq_putmessage('d', msgbuf, 1 + sizeof(WalDataMessageHeader) + nbytes);
960 /* Flush pending output to the client */
966 /* Update shared memory status */
968 /* use volatile pointer to prevent code rearrangement */
969 volatile WalSnd *walsnd = MyWalSnd;
971 SpinLockAcquire(&walsnd->mutex);
972 walsnd->sentPtr = sentPtr;
973 SpinLockRelease(&walsnd->mutex);
976 /* Report progress of XLOG streaming in PS display */
977 if (update_process_title)
979 char activitymsg[50];
981 snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%X",
982 sentPtr.xlogid, sentPtr.xrecoff);
983 set_ps_display(activitymsg, false);
989 /* SIGHUP: set flag to re-read config file at next convenient time */
991 WalSndSigHupHandler(SIGNAL_ARGS)
995 SetLatch(&MyWalSnd->latch);
998 /* SIGTERM: set flag to shut down */
1000 WalSndShutdownHandler(SIGNAL_ARGS)
1002 walsender_shutdown_requested = true;
1004 SetLatch(&MyWalSnd->latch);
1008 * WalSndQuickDieHandler() occurs when signalled SIGQUIT by the postmaster.
1010 * Some backend has bought the farm,
1011 * so we need to stop what we're doing and exit.
1014 WalSndQuickDieHandler(SIGNAL_ARGS)
1016 PG_SETMASK(&BlockSig);
1019 * We DO NOT want to run proc_exit() callbacks -- we're here because
1020 * shared memory may be corrupted, so we don't want to try to clean up our
1021 * transaction. Just nail the windows shut and get out of town. Now that
1022 * there's an atexit callback to prevent third-party code from breaking
1023 * things by calling exit() directly, we have to reset the callbacks
1024 * explicitly to make this work as intended.
1029 * Note we do exit(2) not exit(0). This is to force the postmaster into a
1030 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
1031 * backend. This is necessary precisely because we don't clean up our
1032 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
1033 * should ensure the postmaster sees this as a crash, too, but no harm in
1034 * being doubly sure.)
1039 /* SIGUSR1: set flag to send WAL records */
1041 WalSndXLogSendHandler(SIGNAL_ARGS)
1043 latch_sigusr1_handler();
1046 /* SIGUSR2: set flag to do a last cycle and shut down afterwards */
1048 WalSndLastCycleHandler(SIGNAL_ARGS)
1050 walsender_ready_to_stop = true;
1052 SetLatch(&MyWalSnd->latch);
1055 /* Set up signal handlers */
1059 /* Set up signal handlers */
1060 pqsignal(SIGHUP, WalSndSigHupHandler); /* set flag to read config
1062 pqsignal(SIGINT, SIG_IGN); /* not used */
1063 pqsignal(SIGTERM, WalSndShutdownHandler); /* request shutdown */
1064 pqsignal(SIGQUIT, WalSndQuickDieHandler); /* hard crash time */
1065 pqsignal(SIGALRM, SIG_IGN);
1066 pqsignal(SIGPIPE, SIG_IGN);
1067 pqsignal(SIGUSR1, WalSndXLogSendHandler); /* request WAL sending */
1068 pqsignal(SIGUSR2, WalSndLastCycleHandler); /* request a last cycle and
1071 /* Reset some signals that are accepted by postmaster but not here */
1072 pqsignal(SIGCHLD, SIG_DFL);
1073 pqsignal(SIGTTIN, SIG_DFL);
1074 pqsignal(SIGTTOU, SIG_DFL);
1075 pqsignal(SIGCONT, SIG_DFL);
1076 pqsignal(SIGWINCH, SIG_DFL);
1079 /* Report shared-memory space needed by WalSndShmemInit */
1081 WalSndShmemSize(void)
1085 size = offsetof(WalSndCtlData, walsnds);
1086 size = add_size(size, mul_size(max_wal_senders, sizeof(WalSnd)));
1091 /* Allocate and initialize walsender-related shared memory */
1093 WalSndShmemInit(void)
1098 WalSndCtl = (WalSndCtlData *)
1099 ShmemInitStruct("Wal Sender Ctl", WalSndShmemSize(), &found);
1103 /* First time through, so initialize */
1104 MemSet(WalSndCtl, 0, WalSndShmemSize());
1106 for (i = 0; i < max_wal_senders; i++)
1108 WalSnd *walsnd = &WalSndCtl->walsnds[i];
1110 SpinLockInit(&walsnd->mutex);
1111 InitSharedLatch(&walsnd->latch);
1116 /* Wake up all walsenders */
1122 for (i = 0; i < max_wal_senders; i++)
1123 SetLatch(&WalSndCtl->walsnds[i].latch);
1126 /* Set state for current walsender (only called in walsender) */
1128 WalSndSetState(WalSndState state)
1130 /* use volatile pointer to prevent code rearrangement */
1131 volatile WalSnd *walsnd = MyWalSnd;
1133 Assert(am_walsender);
1135 if (walsnd->state == state)
1138 SpinLockAcquire(&walsnd->mutex);
1139 walsnd->state = state;
1140 SpinLockRelease(&walsnd->mutex);
1144 * Return a string constant representing the state. This is used
1145 * in system views, and should *not* be translated.
1148 WalSndGetStateString(WalSndState state)
1152 case WALSNDSTATE_STARTUP:
1154 case WALSNDSTATE_BACKUP:
1156 case WALSNDSTATE_CATCHUP:
1158 case WALSNDSTATE_STREAMING:
1166 * Returns activity of walsenders, including pids and xlog locations sent to
1170 pg_stat_get_wal_senders(PG_FUNCTION_ARGS)
1172 #define PG_STAT_GET_WAL_SENDERS_COLS 6
1173 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1175 Tuplestorestate *tupstore;
1176 MemoryContext per_query_ctx;
1177 MemoryContext oldcontext;
1180 /* check to see if caller supports us returning a tuplestore */
1181 if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
1183 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1184 errmsg("set-valued function called in context that cannot accept a set")));
1185 if (!(rsinfo->allowedModes & SFRM_Materialize))
1187 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1188 errmsg("materialize mode required, but it is not " \
1189 "allowed in this context")));
1191 /* Build a tuple descriptor for our result type */
1192 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1193 elog(ERROR, "return type must be a row type");
1195 per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1196 oldcontext = MemoryContextSwitchTo(per_query_ctx);
1198 tupstore = tuplestore_begin_heap(true, false, work_mem);
1199 rsinfo->returnMode = SFRM_Materialize;
1200 rsinfo->setResult = tupstore;
1201 rsinfo->setDesc = tupdesc;
1203 MemoryContextSwitchTo(oldcontext);
1205 for (i = 0; i < max_wal_senders; i++)
1207 /* use volatile pointer to prevent code rearrangement */
1208 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1209 char location[MAXFNAMELEN];
1215 Datum values[PG_STAT_GET_WAL_SENDERS_COLS];
1216 bool nulls[PG_STAT_GET_WAL_SENDERS_COLS];
1218 if (walsnd->pid == 0)
1221 SpinLockAcquire(&walsnd->mutex);
1222 sentPtr = walsnd->sentPtr;
1223 state = walsnd->state;
1224 write = walsnd->write;
1225 flush = walsnd->flush;
1226 apply = walsnd->apply;
1227 SpinLockRelease(&walsnd->mutex);
1229 memset(nulls, 0, sizeof(nulls));
1230 values[0] = Int32GetDatum(walsnd->pid);
1235 * Only superusers can see details. Other users only get
1236 * the pid value to know it's a walsender, but no details.
1246 values[1] = CStringGetTextDatum(WalSndGetStateString(state));
1248 snprintf(location, sizeof(location), "%X/%X",
1249 sentPtr.xlogid, sentPtr.xrecoff);
1250 values[2] = CStringGetTextDatum(location);
1252 if (write.xlogid == 0 && write.xrecoff == 0)
1254 snprintf(location, sizeof(location), "%X/%X",
1255 write.xlogid, write.xrecoff);
1256 values[3] = CStringGetTextDatum(location);
1258 if (flush.xlogid == 0 && flush.xrecoff == 0)
1260 snprintf(location, sizeof(location), "%X/%X",
1261 flush.xlogid, flush.xrecoff);
1262 values[4] = CStringGetTextDatum(location);
1264 if (apply.xlogid == 0 && apply.xrecoff == 0)
1266 snprintf(location, sizeof(location), "%X/%X",
1267 apply.xlogid, apply.xrecoff);
1268 values[5] = CStringGetTextDatum(location);
1271 tuplestore_putvalues(tupstore, tupdesc, values, nulls);
1274 /* clean up and return the tuplestore */
1275 tuplestore_donestoring(tupstore);
1281 * This isn't currently used for anything. Monitoring tools might be
1282 * interested in the future, and we'll need something like this in the
1283 * future for synchronous replication.
1287 * Returns the oldest Send position among walsenders. Or InvalidXLogRecPtr
1291 GetOldestWALSendPointer(void)
1293 XLogRecPtr oldest = {0, 0};
1297 for (i = 0; i < max_wal_senders; i++)
1299 /* use volatile pointer to prevent code rearrangement */
1300 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1303 if (walsnd->pid == 0)
1306 SpinLockAcquire(&walsnd->mutex);
1307 recptr = walsnd->sentPtr;
1308 SpinLockRelease(&walsnd->mutex);
1310 if (recptr.xlogid == 0 && recptr.xrecoff == 0)
1313 if (!found || XLByteLT(recptr, oldest))