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-2010, PostgreSQL Global Development Group
31 * $PostgreSQL: pgsql/src/backend/replication/walsender.c,v 1.32 2010/09/15 06:51:19 heikki Exp $
33 *-------------------------------------------------------------------------
40 #include "access/xlog_internal.h"
41 #include "catalog/pg_type.h"
42 #include "libpq/libpq.h"
43 #include "libpq/pqformat.h"
44 #include "libpq/pqsignal.h"
45 #include "miscadmin.h"
46 #include "replication/walprotocol.h"
47 #include "replication/walsender.h"
48 #include "storage/fd.h"
49 #include "storage/ipc.h"
50 #include "storage/pmsignal.h"
51 #include "tcop/tcopprot.h"
52 #include "utils/guc.h"
53 #include "utils/memutils.h"
54 #include "utils/ps_status.h"
57 /* Array of WalSnds in shared memory */
58 WalSndCtlData *WalSndCtl = NULL;
60 /* My slot in the shared memory array */
61 static WalSnd *MyWalSnd = NULL;
64 bool am_walsender = false; /* Am I a walsender process ? */
66 /* User-settable parameters for walsender */
67 int max_wal_senders = 0; /* the maximum number of concurrent walsenders */
68 int WalSndDelay = 200; /* max sleep time between some actions */
71 * These variables are used similarly to openLogFile/Id/Seg/Off,
72 * but for walsender to read the XLOG.
74 static int sendFile = -1;
75 static uint32 sendId = 0;
76 static uint32 sendSeg = 0;
77 static uint32 sendOff = 0;
80 * How far have we sent WAL already? This is also advertised in
81 * MyWalSnd->sentPtr. (Actually, this is the next WAL location to send.)
83 static XLogRecPtr sentPtr = {0, 0};
85 /* Flags set by signal handlers for later service in main loop */
86 static volatile sig_atomic_t got_SIGHUP = false;
87 static volatile sig_atomic_t shutdown_requested = false;
88 static volatile sig_atomic_t ready_to_stop = false;
91 static void WalSndSigHupHandler(SIGNAL_ARGS);
92 static void WalSndShutdownHandler(SIGNAL_ARGS);
93 static void WalSndQuickDieHandler(SIGNAL_ARGS);
94 static void WalSndXLogSendHandler(SIGNAL_ARGS);
95 static void WalSndLastCycleHandler(SIGNAL_ARGS);
97 /* Prototypes for private functions */
98 static int WalSndLoop(void);
99 static void InitWalSnd(void);
100 static void WalSndHandshake(void);
101 static void WalSndKill(int code, Datum arg);
102 static void XLogRead(char *buf, XLogRecPtr recptr, Size nbytes);
103 static bool XLogSend(char *msgbuf, bool *caughtup);
104 static void CheckClosedConnection(void);
107 /* Main entry point for walsender process */
111 MemoryContext walsnd_context;
113 if (RecoveryInProgress())
115 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
116 errmsg("recovery is still in progress, can't accept WAL streaming connections")));
118 /* Create a per-walsender data structure in shared memory */
122 * Create a memory context that we will do all our work in. We do this so
123 * that we can reset the context during error recovery and thereby avoid
124 * possible memory leaks. Formerly this code just ran in
125 * TopMemoryContext, but resetting that would be a really bad idea.
127 * XXX: we don't actually attempt error recovery in walsender, we just
128 * close the connection and exit.
130 walsnd_context = AllocSetContextCreate(TopMemoryContext,
132 ALLOCSET_DEFAULT_MINSIZE,
133 ALLOCSET_DEFAULT_INITSIZE,
134 ALLOCSET_DEFAULT_MAXSIZE);
135 MemoryContextSwitchTo(walsnd_context);
137 /* Unblock signals (they were blocked when the postmaster forked us) */
138 PG_SETMASK(&UnBlockSig);
140 /* Tell the standby that walsender is ready for receiving commands */
141 ReadyForQuery(DestRemote);
143 /* Handle handshake messages before streaming */
146 /* Initialize shared memory status */
148 /* use volatile pointer to prevent code rearrangement */
149 volatile WalSnd *walsnd = MyWalSnd;
151 SpinLockAcquire(&walsnd->mutex);
152 walsnd->sentPtr = sentPtr;
153 SpinLockRelease(&walsnd->mutex);
156 /* Main loop of walsender */
161 * Execute commands from walreceiver, until we enter streaming mode.
164 WalSndHandshake(void)
166 StringInfoData input_message;
167 bool replication_started = false;
169 initStringInfo(&input_message);
171 while (!replication_started)
175 /* Wait for a command to arrive */
176 firstchar = pq_getbyte();
179 * Emergency bailout if postmaster has died. This is to avoid the
180 * necessity for manual cleanup of all postmaster children.
182 if (!PostmasterIsAlive(true))
186 * Check for any other interesting events that happened while we
192 ProcessConfigFile(PGC_SIGHUP);
195 if (firstchar != EOF)
198 * Read the message contents. This is expected to be done without
199 * blocking because we've been able to get message type code.
201 if (pq_getmessage(&input_message, 0))
202 firstchar = EOF; /* suitable message already logged */
205 /* Handle the very limited subset of commands expected in this phase */
208 case 'Q': /* Query message */
210 const char *query_string;
213 query_string = pq_getmsgstring(&input_message);
214 pq_getmsgend(&input_message);
216 if (strcmp(query_string, "IDENTIFY_SYSTEM") == 0)
223 * Reply with a result set with one row, two columns.
224 * First col is system ID, and second is timeline ID
227 snprintf(sysid, sizeof(sysid), UINT64_FORMAT,
228 GetSystemIdentifier());
229 snprintf(tli, sizeof(tli), "%u", ThisTimeLineID);
231 /* Send a RowDescription message */
232 pq_beginmessage(&buf, 'T');
233 pq_sendint(&buf, 2, 2); /* 2 fields */
236 pq_sendstring(&buf, "systemid"); /* col name */
237 pq_sendint(&buf, 0, 4); /* table oid */
238 pq_sendint(&buf, 0, 2); /* attnum */
239 pq_sendint(&buf, TEXTOID, 4); /* type oid */
240 pq_sendint(&buf, -1, 2); /* typlen */
241 pq_sendint(&buf, 0, 4); /* typmod */
242 pq_sendint(&buf, 0, 2); /* format code */
245 pq_sendstring(&buf, "timeline"); /* col name */
246 pq_sendint(&buf, 0, 4); /* table oid */
247 pq_sendint(&buf, 0, 2); /* attnum */
248 pq_sendint(&buf, INT4OID, 4); /* type oid */
249 pq_sendint(&buf, 4, 2); /* typlen */
250 pq_sendint(&buf, 0, 4); /* typmod */
251 pq_sendint(&buf, 0, 2); /* format code */
254 /* Send a DataRow message */
255 pq_beginmessage(&buf, 'D');
256 pq_sendint(&buf, 2, 2); /* # of columns */
257 pq_sendint(&buf, strlen(sysid), 4); /* col1 len */
258 pq_sendbytes(&buf, (char *) &sysid, strlen(sysid));
259 pq_sendint(&buf, strlen(tli), 4); /* col2 len */
260 pq_sendbytes(&buf, (char *) tli, strlen(tli));
263 /* Send CommandComplete and ReadyForQuery messages */
264 EndCommand("SELECT", DestRemote);
265 ReadyForQuery(DestRemote);
266 /* ReadyForQuery did pq_flush for us */
268 else if (sscanf(query_string, "START_REPLICATION %X/%X",
269 &recptr.xlogid, &recptr.xrecoff) == 2)
274 * Check that we're logging enough information in the
275 * WAL for log-shipping.
277 * NOTE: This only checks the current value of
278 * wal_level. Even if the current setting is not
279 * 'minimal', there can be old WAL in the pg_xlog
280 * directory that was created with 'minimal'. So this
281 * is not bulletproof, the purpose is just to give a
282 * user-friendly error message that hints how to
283 * configure the system correctly.
285 if (wal_level == WAL_LEVEL_MINIMAL)
287 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
288 errmsg("standby connections not allowed because wal_level=minimal")));
290 /* Send a CopyBothResponse message, and start streaming */
291 pq_beginmessage(&buf, 'W');
292 pq_sendbyte(&buf, 0);
293 pq_sendint(&buf, 0, 2);
298 * Initialize position to the received one, then the
299 * xlog records begin to be shipped from that position
303 /* break out of the loop */
304 replication_started = true;
309 (errcode(ERRCODE_PROTOCOL_VIOLATION),
310 errmsg("invalid standby query string: %s", query_string)));
316 /* standby is closing the connection */
320 /* standby disconnected unexpectedly */
322 (errcode(ERRCODE_PROTOCOL_VIOLATION),
323 errmsg("unexpected EOF on standby connection")));
328 (errcode(ERRCODE_PROTOCOL_VIOLATION),
329 errmsg("invalid standby handshake message type %d", firstchar)));
335 * Check if the remote end has closed the connection.
338 CheckClosedConnection(void)
340 unsigned char firstchar;
343 r = pq_getbyte_if_available(&firstchar);
346 /* unexpected error or EOF */
348 (errcode(ERRCODE_PROTOCOL_VIOLATION),
349 errmsg("unexpected EOF on standby connection")));
354 /* no data available without blocking */
358 /* Handle the very limited subset of commands expected in this phase */
362 * 'X' means that the standby is closing down the socket.
369 (errcode(ERRCODE_PROTOCOL_VIOLATION),
370 errmsg("invalid standby closing message type %d",
375 /* Main loop of walsender process */
379 char *output_message;
380 bool caughtup = false;
383 * Allocate buffer that will be used for each output message. We do this
384 * just once to reduce palloc overhead. The buffer must be made large
385 * enough for maximum-sized messages.
387 output_message = palloc(1 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE);
389 /* Loop forever, unless we get an error */
393 * Emergency bailout if postmaster has died. This is to avoid the
394 * necessity for manual cleanup of all postmaster children.
396 if (!PostmasterIsAlive(true))
399 /* Process any requests or signals received recently */
403 ProcessConfigFile(PGC_SIGHUP);
407 * When SIGUSR2 arrives, we send all outstanding logs up to the
408 * shutdown checkpoint record (i.e., the latest record) and exit.
412 if (!XLogSend(output_message, &caughtup))
415 shutdown_requested = true;
418 /* Normal exit from the walsender is here */
419 if (shutdown_requested)
421 /* Inform the standby that XLOG streaming was done */
422 pq_puttextmessage('C', "COPY 0");
429 * If we had sent all accumulated WAL in last round, nap for the
430 * configured time before retrying.
435 * Even if we wrote all the WAL that was available when we started
436 * sending, more might have arrived while we were sending this
437 * batch. We had the latch set while sending, so we have not
438 * received any signals from that time. Let's arm the latch
439 * again, and after that check that we're still up-to-date.
441 ResetLatch(&MyWalSnd->latch);
443 if (!XLogSend(output_message, &caughtup))
445 if (caughtup && !got_SIGHUP && !ready_to_stop && !shutdown_requested)
448 * XXX: We don't really need the periodic wakeups anymore,
449 * WaitLatchOrSocket should reliably wake up as soon as
450 * something interesting happens.
454 WaitLatchOrSocket(&MyWalSnd->latch, MyProcPort->sock,
455 WalSndDelay * 1000L);
458 /* Check if the connection was closed */
459 CheckClosedConnection();
463 /* Attempt to send the log once every loop */
464 if (!XLogSend(output_message, &caughtup))
470 * Get here on send failure. Clean up and exit.
472 * Reset whereToSendOutput to prevent ereport from attempting to send any
473 * more messages to the standby.
475 if (whereToSendOutput == DestRemote)
476 whereToSendOutput = DestNone;
479 return 1; /* keep the compiler quiet */
482 /* Initialize a per-walsender data structure for this walsender process */
489 * WalSndCtl should be set up already (we inherit this by fork() or
490 * EXEC_BACKEND mechanism from the postmaster).
492 Assert(WalSndCtl != NULL);
493 Assert(MyWalSnd == NULL);
496 * Find a free walsender slot and reserve it. If this fails, we must be
497 * out of WalSnd structures.
499 for (i = 0; i < max_wal_senders; i++)
501 /* use volatile pointer to prevent code rearrangement */
502 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
504 SpinLockAcquire(&walsnd->mutex);
506 if (walsnd->pid != 0)
508 SpinLockRelease(&walsnd->mutex);
514 * Found a free slot. Reserve it for us.
516 walsnd->pid = MyProcPid;
517 MemSet(&walsnd->sentPtr, 0, sizeof(XLogRecPtr));
518 SpinLockRelease(&walsnd->mutex);
519 /* don't need the lock anymore */
520 OwnLatch((Latch *) &walsnd->latch);
521 MyWalSnd = (WalSnd *) walsnd;
526 if (MyWalSnd == NULL)
528 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
529 errmsg("number of requested standby connections "
530 "exceeds max_wal_senders (currently %d)",
533 /* Arrange to clean up at walsender exit */
534 on_shmem_exit(WalSndKill, 0);
537 /* Destroy the per-walsender data structure for this walsender process */
539 WalSndKill(int code, Datum arg)
541 Assert(MyWalSnd != NULL);
544 * Mark WalSnd struct no longer in use. Assume that no lock is required
548 DisownLatch(&MyWalSnd->latch);
550 /* WalSnd struct isn't mine anymore */
555 * Read 'nbytes' bytes from WAL into 'buf', starting at location 'recptr'
557 * XXX probably this should be improved to suck data directly from the
558 * WAL buffers when possible.
561 XLogRead(char *buf, XLogRecPtr recptr, Size nbytes)
563 XLogRecPtr startRecPtr = recptr;
564 char path[MAXPGPATH];
565 uint32 lastRemovedLog;
566 uint32 lastRemovedSeg;
576 startoff = recptr.xrecoff % XLogSegSize;
578 if (sendFile < 0 || !XLByteInSeg(recptr, sendId, sendSeg))
580 /* Switch to another logfile segment */
584 XLByteToSeg(recptr, sendId, sendSeg);
585 XLogFilePath(path, ThisTimeLineID, sendId, sendSeg);
587 sendFile = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
591 * If the file is not found, assume it's because the standby
592 * asked for a too old WAL segment that has already been
593 * removed or recycled.
597 char filename[MAXFNAMELEN];
599 XLogFileName(filename, ThisTimeLineID, sendId, sendSeg);
601 (errcode_for_file_access(),
602 errmsg("requested WAL segment %s has already been removed",
607 (errcode_for_file_access(),
608 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
609 path, sendId, sendSeg)));
614 /* Need to seek in the file? */
615 if (sendOff != startoff)
617 if (lseek(sendFile, (off_t) startoff, SEEK_SET) < 0)
619 (errcode_for_file_access(),
620 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
621 sendId, sendSeg, startoff)));
625 /* How many bytes are within this segment? */
626 if (nbytes > (XLogSegSize - startoff))
627 segbytes = XLogSegSize - startoff;
631 readbytes = read(sendFile, buf, segbytes);
634 (errcode_for_file_access(),
635 errmsg("could not read from log file %u, segment %u, offset %u, "
637 sendId, sendSeg, sendOff, (unsigned long) segbytes)));
639 /* Update state for read */
640 XLByteAdvance(recptr, readbytes);
642 sendOff += readbytes;
648 * After reading into the buffer, check that what we read was valid. We do
649 * this after reading, because even though the segment was present when we
650 * opened it, it might get recycled or removed while we read it. The
651 * read() succeeds in that case, but the data we tried to read might
652 * already have been overwritten with new WAL records.
654 XLogGetLastRemoved(&lastRemovedLog, &lastRemovedSeg);
655 XLByteToSeg(startRecPtr, log, seg);
656 if (log < lastRemovedLog ||
657 (log == lastRemovedLog && seg <= lastRemovedSeg))
659 char filename[MAXFNAMELEN];
661 XLogFileName(filename, ThisTimeLineID, log, seg);
663 (errcode_for_file_access(),
664 errmsg("requested WAL segment %s has already been removed",
670 * Read up to MAX_SEND_SIZE bytes of WAL that's been flushed to disk,
671 * but not yet sent to the client, and send it.
673 * msgbuf is a work area in which the output message is constructed. It's
674 * passed in just so we can avoid re-palloc'ing the buffer on each cycle.
675 * It must be of size 1 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE.
677 * If there is no unsent WAL remaining, *caughtup is set to true, otherwise
678 * *caughtup is set to false.
680 * Returns true if OK, false if trouble.
683 XLogSend(char *msgbuf, bool *caughtup)
685 XLogRecPtr SendRqstPtr;
689 WalDataMessageHeader msghdr;
692 * Attempt to send all data that's already been written out and fsync'd to
693 * disk. We cannot go further than what's been written out given the
694 * current implementation of XLogRead(). And in any case it's unsafe to
695 * send WAL that is not securely down to disk on the master: if the master
696 * subsequently crashes and restarts, slaves must not have applied any WAL
697 * that gets lost on the master.
699 SendRqstPtr = GetFlushRecPtr();
701 /* Quick exit if nothing to do */
702 if (XLByteLE(SendRqstPtr, sentPtr))
709 * Figure out how much to send in one message. If there's no more than
710 * MAX_SEND_SIZE bytes to send, send everything. Otherwise send
711 * MAX_SEND_SIZE bytes, but round back to logfile or page boundary.
713 * The rounding is not only for performance reasons. Walreceiver relies on
714 * the fact that we never split a WAL record across two messages. Since a
715 * long WAL record is split at page boundary into continuation records,
716 * page boundary is always a safe cut-off point. We also assume that
717 * SendRqstPtr never points to the middle of a WAL record.
720 if (startptr.xrecoff >= XLogFileSize)
723 * crossing a logid boundary, skip the non-existent last log segment
724 * in previous logical log file.
726 startptr.xlogid += 1;
727 startptr.xrecoff = 0;
731 XLByteAdvance(endptr, MAX_SEND_SIZE);
732 if (endptr.xlogid != startptr.xlogid)
734 /* Don't cross a logfile boundary within one message */
735 Assert(endptr.xlogid == startptr.xlogid + 1);
736 endptr.xlogid = startptr.xlogid;
737 endptr.xrecoff = XLogFileSize;
740 /* if we went beyond SendRqstPtr, back off */
741 if (XLByteLE(SendRqstPtr, endptr))
743 endptr = SendRqstPtr;
748 /* round down to page boundary. */
749 endptr.xrecoff -= (endptr.xrecoff % XLOG_BLCKSZ);
753 nbytes = endptr.xrecoff - startptr.xrecoff;
754 Assert(nbytes <= MAX_SEND_SIZE);
757 * OK to read and send the slice.
762 * Read the log directly into the output buffer to avoid extra memcpy
765 XLogRead(msgbuf + 1 + sizeof(WalDataMessageHeader), startptr, nbytes);
768 * We fill the message header last so that the send timestamp is taken as
771 msghdr.dataStart = startptr;
772 msghdr.walEnd = SendRqstPtr;
773 msghdr.sendTime = GetCurrentTimestamp();
775 memcpy(msgbuf + 1, &msghdr, sizeof(WalDataMessageHeader));
777 pq_putmessage('d', msgbuf, 1 + sizeof(WalDataMessageHeader) + nbytes);
779 /* Flush pending output to the client */
785 /* Update shared memory status */
787 /* use volatile pointer to prevent code rearrangement */
788 volatile WalSnd *walsnd = MyWalSnd;
790 SpinLockAcquire(&walsnd->mutex);
791 walsnd->sentPtr = sentPtr;
792 SpinLockRelease(&walsnd->mutex);
795 /* Report progress of XLOG streaming in PS display */
796 if (update_process_title)
798 char activitymsg[50];
800 snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%X",
801 sentPtr.xlogid, sentPtr.xrecoff);
802 set_ps_display(activitymsg, false);
808 /* SIGHUP: set flag to re-read config file at next convenient time */
810 WalSndSigHupHandler(SIGNAL_ARGS)
814 SetLatch(&MyWalSnd->latch);
817 /* SIGTERM: set flag to shut down */
819 WalSndShutdownHandler(SIGNAL_ARGS)
821 shutdown_requested = true;
823 SetLatch(&MyWalSnd->latch);
827 * WalSndQuickDieHandler() occurs when signalled SIGQUIT by the postmaster.
829 * Some backend has bought the farm,
830 * so we need to stop what we're doing and exit.
833 WalSndQuickDieHandler(SIGNAL_ARGS)
835 PG_SETMASK(&BlockSig);
838 * We DO NOT want to run proc_exit() callbacks -- we're here because
839 * shared memory may be corrupted, so we don't want to try to clean up our
840 * transaction. Just nail the windows shut and get out of town. Now that
841 * there's an atexit callback to prevent third-party code from breaking
842 * things by calling exit() directly, we have to reset the callbacks
843 * explicitly to make this work as intended.
848 * Note we do exit(2) not exit(0). This is to force the postmaster into a
849 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
850 * backend. This is necessary precisely because we don't clean up our
851 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
852 * should ensure the postmaster sees this as a crash, too, but no harm in
853 * being doubly sure.)
858 /* SIGUSR1: set flag to send WAL records */
860 WalSndXLogSendHandler(SIGNAL_ARGS)
862 latch_sigusr1_handler();
865 /* SIGUSR2: set flag to do a last cycle and shut down afterwards */
867 WalSndLastCycleHandler(SIGNAL_ARGS)
869 ready_to_stop = true;
871 SetLatch(&MyWalSnd->latch);
874 /* Set up signal handlers */
878 /* Set up signal handlers */
879 pqsignal(SIGHUP, WalSndSigHupHandler); /* set flag to read config
881 pqsignal(SIGINT, SIG_IGN); /* not used */
882 pqsignal(SIGTERM, WalSndShutdownHandler); /* request shutdown */
883 pqsignal(SIGQUIT, WalSndQuickDieHandler); /* hard crash time */
884 pqsignal(SIGALRM, SIG_IGN);
885 pqsignal(SIGPIPE, SIG_IGN);
886 pqsignal(SIGUSR1, WalSndXLogSendHandler); /* request WAL sending */
887 pqsignal(SIGUSR2, WalSndLastCycleHandler); /* request a last cycle and
890 /* Reset some signals that are accepted by postmaster but not here */
891 pqsignal(SIGCHLD, SIG_DFL);
892 pqsignal(SIGTTIN, SIG_DFL);
893 pqsignal(SIGTTOU, SIG_DFL);
894 pqsignal(SIGCONT, SIG_DFL);
895 pqsignal(SIGWINCH, SIG_DFL);
898 /* Report shared-memory space needed by WalSndShmemInit */
900 WalSndShmemSize(void)
904 size = offsetof(WalSndCtlData, walsnds);
905 size = add_size(size, mul_size(max_wal_senders, sizeof(WalSnd)));
910 /* Allocate and initialize walsender-related shared memory */
912 WalSndShmemInit(void)
917 WalSndCtl = (WalSndCtlData *)
918 ShmemInitStruct("Wal Sender Ctl", WalSndShmemSize(), &found);
922 /* First time through, so initialize */
923 MemSet(WalSndCtl, 0, WalSndShmemSize());
925 for (i = 0; i < max_wal_senders; i++)
927 WalSnd *walsnd = &WalSndCtl->walsnds[i];
929 SpinLockInit(&walsnd->mutex);
930 InitSharedLatch(&walsnd->latch);
935 /* Wake up all walsenders */
941 for (i = 0; i < max_wal_senders; i++)
942 SetLatch(&WalSndCtl->walsnds[i].latch);
946 * This isn't currently used for anything. Monitoring tools might be
947 * interested in the future, and we'll need something like this in the
948 * future for synchronous replication.
952 * Returns the oldest Send position among walsenders. Or InvalidXLogRecPtr
956 GetOldestWALSendPointer(void)
958 XLogRecPtr oldest = {0, 0};
962 for (i = 0; i < max_wal_senders; i++)
964 /* use volatile pointer to prevent code rearrangement */
965 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
968 if (walsnd->pid == 0)
971 SpinLockAcquire(&walsnd->mutex);
972 recptr = walsnd->sentPtr;
973 SpinLockRelease(&walsnd->mutex);
975 if (recptr.xlogid == 0 && recptr.xrecoff == 0)
978 if (!found || XLByteLT(recptr, oldest))