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};
86 * How far have we completed replication already? This is also
87 * advertised in MyWalSnd->ackdPtr. This is not used in asynchronous
90 static XLogRecPtr ackdPtr = {0, 0};
92 /* Flags set by signal handlers for later service in main loop */
93 static volatile sig_atomic_t got_SIGHUP = false;
94 static volatile sig_atomic_t shutdown_requested = false;
95 static volatile sig_atomic_t 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 int WalSndLoop(void);
106 static void InitWalSnd(void);
107 static void WalSndHandshake(void);
108 static void WalSndKill(int code, Datum arg);
109 static void XLogRead(char *buf, XLogRecPtr recptr, Size nbytes);
110 static bool XLogSend(char *msgbuf, bool *caughtup);
111 static void ProcessStreamMsgs(StringInfo inMsg);
114 /* Main entry point for walsender process */
118 MemoryContext walsnd_context;
120 if (RecoveryInProgress())
122 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
123 errmsg("recovery is still in progress, can't accept WAL streaming connections")));
125 /* Create a per-walsender data structure in shared memory */
129 * Create a memory context that we will do all our work in. We do this so
130 * that we can reset the context during error recovery and thereby avoid
131 * possible memory leaks. Formerly this code just ran in
132 * TopMemoryContext, but resetting that would be a really bad idea.
134 * XXX: we don't actually attempt error recovery in walsender, we just
135 * close the connection and exit.
137 walsnd_context = AllocSetContextCreate(TopMemoryContext,
139 ALLOCSET_DEFAULT_MINSIZE,
140 ALLOCSET_DEFAULT_INITSIZE,
141 ALLOCSET_DEFAULT_MAXSIZE);
142 MemoryContextSwitchTo(walsnd_context);
144 /* Unblock signals (they were blocked when the postmaster forked us) */
145 PG_SETMASK(&UnBlockSig);
147 /* Tell the standby that walsender is ready for receiving commands */
148 ReadyForQuery(DestRemote);
150 /* Handle handshake messages before streaming */
153 /* Initialize shared memory status */
155 /* use volatile pointer to prevent code rearrangement */
156 volatile WalSnd *walsnd = MyWalSnd;
158 SpinLockAcquire(&walsnd->mutex);
159 walsnd->sentPtr = sentPtr;
160 SpinLockRelease(&walsnd->mutex);
163 /* Main loop of walsender */
168 * Execute commands from walreceiver, until we enter streaming mode.
171 WalSndHandshake(void)
173 StringInfoData input_message;
174 bool replication_started = false;
176 initStringInfo(&input_message);
178 while (!replication_started)
182 /* Wait for a command to arrive */
183 firstchar = pq_getbyte();
186 * Emergency bailout if postmaster has died. This is to avoid the
187 * necessity for manual cleanup of all postmaster children.
189 if (!PostmasterIsAlive(true))
193 * Check for any other interesting events that happened while we
199 ProcessConfigFile(PGC_SIGHUP);
202 if (firstchar != EOF)
205 * Read the message contents. This is expected to be done without
206 * blocking because we've been able to get message type code.
208 if (pq_getmessage(&input_message, 0))
209 firstchar = EOF; /* suitable message already logged */
212 /* Handle the very limited subset of commands expected in this phase */
215 case 'Q': /* Query message */
217 const char *query_string;
220 query_string = pq_getmsgstring(&input_message);
221 pq_getmsgend(&input_message);
223 if (strcmp(query_string, "IDENTIFY_SYSTEM") == 0)
230 * Reply with a result set with one row, two columns.
231 * First col is system ID, and second is timeline ID
234 snprintf(sysid, sizeof(sysid), UINT64_FORMAT,
235 GetSystemIdentifier());
236 snprintf(tli, sizeof(tli), "%u", ThisTimeLineID);
238 /* Send a RowDescription message */
239 pq_beginmessage(&buf, 'T');
240 pq_sendint(&buf, 2, 2); /* 2 fields */
243 pq_sendstring(&buf, "systemid"); /* col name */
244 pq_sendint(&buf, 0, 4); /* table oid */
245 pq_sendint(&buf, 0, 2); /* attnum */
246 pq_sendint(&buf, TEXTOID, 4); /* type oid */
247 pq_sendint(&buf, -1, 2); /* typlen */
248 pq_sendint(&buf, 0, 4); /* typmod */
249 pq_sendint(&buf, 0, 2); /* format code */
252 pq_sendstring(&buf, "timeline"); /* col name */
253 pq_sendint(&buf, 0, 4); /* table oid */
254 pq_sendint(&buf, 0, 2); /* attnum */
255 pq_sendint(&buf, INT4OID, 4); /* type oid */
256 pq_sendint(&buf, 4, 2); /* typlen */
257 pq_sendint(&buf, 0, 4); /* typmod */
258 pq_sendint(&buf, 0, 2); /* format code */
261 /* Send a DataRow message */
262 pq_beginmessage(&buf, 'D');
263 pq_sendint(&buf, 2, 2); /* # of columns */
264 pq_sendint(&buf, strlen(sysid), 4); /* col1 len */
265 pq_sendbytes(&buf, (char *) &sysid, strlen(sysid));
266 pq_sendint(&buf, strlen(tli), 4); /* col2 len */
267 pq_sendbytes(&buf, (char *) tli, strlen(tli));
270 /* Send CommandComplete and ReadyForQuery messages */
271 EndCommand("SELECT", DestRemote);
272 ReadyForQuery(DestRemote);
273 /* ReadyForQuery did pq_flush for us */
275 else if (sscanf(query_string, "START_REPLICATION %X/%X",
276 &recptr.xlogid, &recptr.xrecoff) == 2)
281 * Check that we're logging enough information in the
282 * WAL for log-shipping.
284 * NOTE: This only checks the current value of
285 * wal_level. Even if the current setting is not
286 * 'minimal', there can be old WAL in the pg_xlog
287 * directory that was created with 'minimal'. So this
288 * is not bulletproof, the purpose is just to give a
289 * user-friendly error message that hints how to
290 * configure the system correctly.
292 if (wal_level == WAL_LEVEL_MINIMAL)
294 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
295 errmsg("standby connections not allowed because wal_level=minimal")));
297 /* Send a CopyXLogResponse message, and start streaming */
298 pq_beginmessage(&buf, 'W');
303 * Initialize positions to the received one, then the
304 * xlog records begin to be shipped from that position
306 sentPtr = ackdPtr = recptr;
308 /* break out of the loop */
309 replication_started = true;
314 (errcode(ERRCODE_PROTOCOL_VIOLATION),
315 errmsg("invalid standby query string: %s", query_string)));
321 /* standby is closing the connection */
325 /* standby disconnected unexpectedly */
327 (errcode(ERRCODE_PROTOCOL_VIOLATION),
328 errmsg("unexpected EOF on standby connection")));
333 (errcode(ERRCODE_PROTOCOL_VIOLATION),
334 errmsg("invalid standby handshake message type %d", firstchar)));
340 * Process messages received from the standby.
345 ProcessStreamMsgs(StringInfo inMsg)
349 /* Loop to process successive complete messages available */
352 unsigned char firstchar;
355 r = pq_getbyte_if_available(&firstchar);
358 /* unexpected error or EOF */
360 (errcode(ERRCODE_PROTOCOL_VIOLATION),
361 errmsg("unexpected EOF on standby connection")));
366 /* no data available without blocking */
370 /* Handle the very limited subset of commands expected in this phase */
373 case 'd': /* CopyData message */
375 unsigned char rpltype;
378 * Read the message contents. This is expected to be done without
379 * blocking because we've been able to get message type code.
381 if (pq_getmessage(inMsg, 0))
382 proc_exit(0); /* suitable message already logged */
384 /* Read the replication message type from CopyData message */
385 rpltype = pq_getmsgbyte(inMsg);
390 WalAckMessageData *msgdata;
392 msgdata = (WalAckMessageData *) pq_getmsgbytes(inMsg, sizeof(WalAckMessageData));
395 * Update local status.
397 * The ackd ptr received from standby should not
400 if (XLByteLE(ackdPtr, msgdata->ackEnd))
401 ackdPtr = msgdata->ackEnd;
404 (errmsg("replication completion location went back from "
406 ackdPtr.xlogid, ackdPtr.xrecoff,
407 msgdata->ackEnd.xlogid, msgdata->ackEnd.xrecoff)));
409 acked = true; /* also need to update shared position */
414 (errcode(ERRCODE_PROTOCOL_VIOLATION),
415 errmsg("invalid replication message type %d",
422 * 'X' means that the standby is closing down the socket.
429 (errcode(ERRCODE_PROTOCOL_VIOLATION),
430 errmsg("invalid standby closing message type %d",
437 /* use volatile pointer to prevent code rearrangement */
438 volatile WalSnd *walsnd = MyWalSnd;
440 SpinLockAcquire(&walsnd->mutex);
441 walsnd->ackdPtr = ackdPtr;
442 SpinLockRelease(&walsnd->mutex);
446 /* Main loop of walsender process */
450 StringInfoData input_message;
451 char *output_message;
452 bool caughtup = false;
454 initStringInfo(&input_message);
457 * Allocate buffer that will be used for each output message. We do this
458 * just once to reduce palloc overhead. The buffer must be made large
459 * enough for maximum-sized messages.
461 output_message = palloc(1 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE);
463 /* Loop forever, unless we get an error */
467 * Emergency bailout if postmaster has died. This is to avoid the
468 * necessity for manual cleanup of all postmaster children.
470 if (!PostmasterIsAlive(true))
473 /* Process any requests or signals received recently */
477 ProcessConfigFile(PGC_SIGHUP);
481 * When SIGUSR2 arrives, we send all outstanding logs up to the
482 * shutdown checkpoint record (i.e., the latest record) and exit.
486 if (!XLogSend(output_message, &caughtup))
489 shutdown_requested = true;
492 /* Normal exit from the walsender is here */
493 if (shutdown_requested)
495 /* Inform the standby that XLOG streaming was done */
496 pq_puttextmessage('C', "COPY 0");
503 * If we had sent all accumulated WAL in last round, nap for the
504 * configured time before retrying.
509 * Even if we wrote all the WAL that was available when we started
510 * sending, more might have arrived while we were sending this
511 * batch. We had the latch set while sending, so we have not
512 * received any signals from that time. Let's arm the latch
513 * again, and after that check that we're still up-to-date.
515 ResetLatch(&MyWalSnd->latch);
517 if (!XLogSend(output_message, &caughtup))
519 if (caughtup && !got_SIGHUP && !ready_to_stop && !shutdown_requested)
522 * XXX: We don't really need the periodic wakeups anymore,
523 * WaitLatchOrSocket should reliably wake up as soon as
524 * something interesting happens.
528 WaitLatchOrSocket(&MyWalSnd->latch, MyProcPort->sock,
529 WalSndDelay * 1000L);
532 /* Process messages received from the standby */
533 ProcessStreamMsgs(&input_message);
537 /* Attempt to send the log once every loop */
538 if (!XLogSend(output_message, &caughtup))
544 * Get here on send failure. Clean up and exit.
546 * Reset whereToSendOutput to prevent ereport from attempting to send any
547 * more messages to the standby.
549 if (whereToSendOutput == DestRemote)
550 whereToSendOutput = DestNone;
553 return 1; /* keep the compiler quiet */
556 /* Initialize a per-walsender data structure for this walsender process */
563 * WalSndCtl should be set up already (we inherit this by fork() or
564 * EXEC_BACKEND mechanism from the postmaster).
566 Assert(WalSndCtl != NULL);
567 Assert(MyWalSnd == NULL);
570 * Find a free walsender slot and reserve it. If this fails, we must be
571 * out of WalSnd structures.
573 for (i = 0; i < max_wal_senders; i++)
575 /* use volatile pointer to prevent code rearrangement */
576 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
578 SpinLockAcquire(&walsnd->mutex);
580 if (walsnd->pid != 0)
582 SpinLockRelease(&walsnd->mutex);
588 * Found a free slot. Reserve it for us.
590 walsnd->pid = MyProcPid;
591 MemSet(&walsnd->sentPtr, 0, sizeof(XLogRecPtr));
592 MemSet(&walsnd->ackdPtr, 0, sizeof(XLogRecPtr));
593 SpinLockRelease(&walsnd->mutex);
594 /* don't need the lock anymore */
595 OwnLatch((Latch *) &walsnd->latch);
596 MyWalSnd = (WalSnd *) walsnd;
601 if (MyWalSnd == NULL)
603 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
604 errmsg("number of requested standby connections "
605 "exceeds max_wal_senders (currently %d)",
608 /* Arrange to clean up at walsender exit */
609 on_shmem_exit(WalSndKill, 0);
612 /* Destroy the per-walsender data structure for this walsender process */
614 WalSndKill(int code, Datum arg)
616 Assert(MyWalSnd != NULL);
619 * Mark WalSnd struct no longer in use. Assume that no lock is required
623 DisownLatch(&MyWalSnd->latch);
625 /* WalSnd struct isn't mine anymore */
630 * Read 'nbytes' bytes from WAL into 'buf', starting at location 'recptr'
632 * XXX probably this should be improved to suck data directly from the
633 * WAL buffers when possible.
636 XLogRead(char *buf, XLogRecPtr recptr, Size nbytes)
638 XLogRecPtr startRecPtr = recptr;
639 char path[MAXPGPATH];
640 uint32 lastRemovedLog;
641 uint32 lastRemovedSeg;
651 startoff = recptr.xrecoff % XLogSegSize;
653 if (sendFile < 0 || !XLByteInSeg(recptr, sendId, sendSeg))
655 /* Switch to another logfile segment */
659 XLByteToSeg(recptr, sendId, sendSeg);
660 XLogFilePath(path, ThisTimeLineID, sendId, sendSeg);
662 sendFile = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
666 * If the file is not found, assume it's because the standby
667 * asked for a too old WAL segment that has already been
668 * removed or recycled.
672 char filename[MAXFNAMELEN];
674 XLogFileName(filename, ThisTimeLineID, sendId, sendSeg);
676 (errcode_for_file_access(),
677 errmsg("requested WAL segment %s has already been removed",
682 (errcode_for_file_access(),
683 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
684 path, sendId, sendSeg)));
689 /* Need to seek in the file? */
690 if (sendOff != startoff)
692 if (lseek(sendFile, (off_t) startoff, SEEK_SET) < 0)
694 (errcode_for_file_access(),
695 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
696 sendId, sendSeg, startoff)));
700 /* How many bytes are within this segment? */
701 if (nbytes > (XLogSegSize - startoff))
702 segbytes = XLogSegSize - startoff;
706 readbytes = read(sendFile, buf, segbytes);
709 (errcode_for_file_access(),
710 errmsg("could not read from log file %u, segment %u, offset %u, "
712 sendId, sendSeg, sendOff, (unsigned long) segbytes)));
714 /* Update state for read */
715 XLByteAdvance(recptr, readbytes);
717 sendOff += readbytes;
723 * After reading into the buffer, check that what we read was valid. We do
724 * this after reading, because even though the segment was present when we
725 * opened it, it might get recycled or removed while we read it. The
726 * read() succeeds in that case, but the data we tried to read might
727 * already have been overwritten with new WAL records.
729 XLogGetLastRemoved(&lastRemovedLog, &lastRemovedSeg);
730 XLByteToSeg(startRecPtr, log, seg);
731 if (log < lastRemovedLog ||
732 (log == lastRemovedLog && seg <= lastRemovedSeg))
734 char filename[MAXFNAMELEN];
736 XLogFileName(filename, ThisTimeLineID, log, seg);
738 (errcode_for_file_access(),
739 errmsg("requested WAL segment %s has already been removed",
745 * Read up to MAX_SEND_SIZE bytes of WAL that's been flushed to disk,
746 * but not yet sent to the client, and send it.
748 * msgbuf is a work area in which the output message is constructed. It's
749 * passed in just so we can avoid re-palloc'ing the buffer on each cycle.
750 * It must be of size 1 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE.
752 * If there is no unsent WAL remaining, *caughtup is set to true, otherwise
753 * *caughtup is set to false.
755 * Returns true if OK, false if trouble.
758 XLogSend(char *msgbuf, bool *caughtup)
760 XLogRecPtr SendRqstPtr;
764 WalDataMessageHeader msghdr;
767 * Attempt to send all data that's already been written out and fsync'd to
768 * disk. We cannot go further than what's been written out given the
769 * current implementation of XLogRead(). And in any case it's unsafe to
770 * send WAL that is not securely down to disk on the master: if the master
771 * subsequently crashes and restarts, slaves must not have applied any WAL
772 * that gets lost on the master.
774 SendRqstPtr = GetFlushRecPtr();
776 /* Quick exit if nothing to do */
777 if (XLByteLE(SendRqstPtr, sentPtr))
784 * Figure out how much to send in one message. If there's no more than
785 * MAX_SEND_SIZE bytes to send, send everything. Otherwise send
786 * MAX_SEND_SIZE bytes, but round back to logfile or page boundary.
788 * The rounding is not only for performance reasons. Walreceiver relies on
789 * the fact that we never split a WAL record across two messages. Since a
790 * long WAL record is split at page boundary into continuation records,
791 * page boundary is always a safe cut-off point. We also assume that
792 * SendRqstPtr never points to the middle of a WAL record.
795 if (startptr.xrecoff >= XLogFileSize)
798 * crossing a logid boundary, skip the non-existent last log segment
799 * in previous logical log file.
801 startptr.xlogid += 1;
802 startptr.xrecoff = 0;
806 XLByteAdvance(endptr, MAX_SEND_SIZE);
807 if (endptr.xlogid != startptr.xlogid)
809 /* Don't cross a logfile boundary within one message */
810 Assert(endptr.xlogid == startptr.xlogid + 1);
811 endptr.xlogid = startptr.xlogid;
812 endptr.xrecoff = XLogFileSize;
815 /* if we went beyond SendRqstPtr, back off */
816 if (XLByteLE(SendRqstPtr, endptr))
818 endptr = SendRqstPtr;
823 /* round down to page boundary. */
824 endptr.xrecoff -= (endptr.xrecoff % XLOG_BLCKSZ);
828 nbytes = endptr.xrecoff - startptr.xrecoff;
829 Assert(nbytes <= MAX_SEND_SIZE);
832 * OK to read and send the slice.
837 * Read the log directly into the output buffer to avoid extra memcpy
840 XLogRead(msgbuf + 1 + sizeof(WalDataMessageHeader), startptr, nbytes);
843 * We fill the message header last so that the send timestamp is taken as
846 msghdr.dataStart = startptr;
847 msghdr.walEnd = SendRqstPtr;
848 msghdr.sendTime = GetCurrentTimestamp();
850 memcpy(msgbuf + 1, &msghdr, sizeof(WalDataMessageHeader));
852 pq_putmessage('d', msgbuf, 1 + sizeof(WalDataMessageHeader) + nbytes);
854 /* Flush pending output to the client */
860 /* Update shared memory status */
862 /* use volatile pointer to prevent code rearrangement */
863 volatile WalSnd *walsnd = MyWalSnd;
865 SpinLockAcquire(&walsnd->mutex);
866 walsnd->sentPtr = sentPtr;
867 SpinLockRelease(&walsnd->mutex);
870 /* Report progress of XLOG streaming in PS display */
871 if (update_process_title)
873 char activitymsg[50];
875 snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%X",
876 sentPtr.xlogid, sentPtr.xrecoff);
877 set_ps_display(activitymsg, false);
883 /* SIGHUP: set flag to re-read config file at next convenient time */
885 WalSndSigHupHandler(SIGNAL_ARGS)
889 SetLatch(&MyWalSnd->latch);
892 /* SIGTERM: set flag to shut down */
894 WalSndShutdownHandler(SIGNAL_ARGS)
896 shutdown_requested = true;
898 SetLatch(&MyWalSnd->latch);
902 * WalSndQuickDieHandler() occurs when signalled SIGQUIT by the postmaster.
904 * Some backend has bought the farm,
905 * so we need to stop what we're doing and exit.
908 WalSndQuickDieHandler(SIGNAL_ARGS)
910 PG_SETMASK(&BlockSig);
913 * We DO NOT want to run proc_exit() callbacks -- we're here because
914 * shared memory may be corrupted, so we don't want to try to clean up our
915 * transaction. Just nail the windows shut and get out of town. Now that
916 * there's an atexit callback to prevent third-party code from breaking
917 * things by calling exit() directly, we have to reset the callbacks
918 * explicitly to make this work as intended.
923 * Note we do exit(2) not exit(0). This is to force the postmaster into a
924 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
925 * backend. This is necessary precisely because we don't clean up our
926 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
927 * should ensure the postmaster sees this as a crash, too, but no harm in
928 * being doubly sure.)
933 /* SIGUSR1: set flag to send WAL records */
935 WalSndXLogSendHandler(SIGNAL_ARGS)
937 latch_sigusr1_handler();
940 /* SIGUSR2: set flag to do a last cycle and shut down afterwards */
942 WalSndLastCycleHandler(SIGNAL_ARGS)
944 ready_to_stop = true;
946 SetLatch(&MyWalSnd->latch);
949 /* Set up signal handlers */
953 /* Set up signal handlers */
954 pqsignal(SIGHUP, WalSndSigHupHandler); /* set flag to read config
956 pqsignal(SIGINT, SIG_IGN); /* not used */
957 pqsignal(SIGTERM, WalSndShutdownHandler); /* request shutdown */
958 pqsignal(SIGQUIT, WalSndQuickDieHandler); /* hard crash time */
959 pqsignal(SIGALRM, SIG_IGN);
960 pqsignal(SIGPIPE, SIG_IGN);
961 pqsignal(SIGUSR1, WalSndXLogSendHandler); /* request WAL sending */
962 pqsignal(SIGUSR2, WalSndLastCycleHandler); /* request a last cycle and
965 /* Reset some signals that are accepted by postmaster but not here */
966 pqsignal(SIGCHLD, SIG_DFL);
967 pqsignal(SIGTTIN, SIG_DFL);
968 pqsignal(SIGTTOU, SIG_DFL);
969 pqsignal(SIGCONT, SIG_DFL);
970 pqsignal(SIGWINCH, SIG_DFL);
973 /* Report shared-memory space needed by WalSndShmemInit */
975 WalSndShmemSize(void)
979 size = offsetof(WalSndCtlData, walsnds);
980 size = add_size(size, mul_size(max_wal_senders, sizeof(WalSnd)));
985 /* Allocate and initialize walsender-related shared memory */
987 WalSndShmemInit(void)
992 WalSndCtl = (WalSndCtlData *)
993 ShmemInitStruct("Wal Sender Ctl", WalSndShmemSize(), &found);
997 /* First time through, so initialize */
998 MemSet(WalSndCtl, 0, WalSndShmemSize());
1000 for (i = 0; i < max_wal_senders; i++)
1002 WalSnd *walsnd = &WalSndCtl->walsnds[i];
1004 SpinLockInit(&walsnd->mutex);
1005 InitSharedLatch(&walsnd->latch);
1010 /* Wake up all walsenders */
1016 for (i = 0; i < max_wal_senders; i++)
1017 SetLatch(&WalSndCtl->walsnds[i].latch);
1021 * This isn't currently used for anything. Monitoring tools might be
1022 * interested in the future, and we'll need something like this in the
1023 * future for synchronous replication.
1027 * Returns the oldest Send position among walsenders. Or InvalidXLogRecPtr
1031 GetOldestWALSendPointer(void)
1033 XLogRecPtr oldest = {0, 0};
1037 for (i = 0; i < max_wal_senders; i++)
1039 /* use volatile pointer to prevent code rearrangement */
1040 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1043 if (walsnd->pid == 0)
1046 SpinLockAcquire(&walsnd->mutex);
1047 recptr = walsnd->sentPtr;
1048 SpinLockRelease(&walsnd->mutex);
1050 if (recptr.xlogid == 0 && recptr.xrecoff == 0)
1053 if (!found || XLByteLT(recptr, oldest))