1 /*-------------------------------------------------------------------------
5 * The WAL sender process (walsender) is new as of Postgres 9.0. It takes
6 * charge of XLOG streaming sender in the primary server. At first, it is
7 * started by the postmaster when the walreceiver in the standby server
8 * connects to the primary server and requests XLOG streaming replication,
9 * i.e., unlike any auxiliary process, it is not an always-running process.
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 an 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.
27 * Note that there can be more than one walsender process concurrently.
29 * Portions Copyright (c) 2010-2010, PostgreSQL Global Development Group
33 * $PostgreSQL: pgsql/src/backend/replication/walsender.c,v 1.22 2010/05/26 22:34:49 heikki Exp $
35 *-------------------------------------------------------------------------
41 #include "access/xlog_internal.h"
42 #include "catalog/pg_type.h"
43 #include "libpq/libpq.h"
44 #include "libpq/pqformat.h"
45 #include "libpq/pqsignal.h"
46 #include "miscadmin.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 */
70 #define NAPTIME_PER_CYCLE 100000L /* max sleep time between cycles (100ms) */
73 * These variables are used similarly to openLogFile/Id/Seg/Off,
74 * but for walsender to read the XLOG.
76 static int sendFile = -1;
77 static uint32 sendId = 0;
78 static uint32 sendSeg = 0;
79 static uint32 sendOff = 0;
82 * How far have we sent WAL already? This is also advertised in
85 static XLogRecPtr sentPtr = {0, 0};
87 /* Flags set by signal handlers for later service in main loop */
88 static volatile sig_atomic_t got_SIGHUP = false;
89 static volatile sig_atomic_t shutdown_requested = false;
90 static volatile sig_atomic_t ready_to_stop = false;
93 static void WalSndSigHupHandler(SIGNAL_ARGS);
94 static void WalSndShutdownHandler(SIGNAL_ARGS);
95 static void WalSndQuickDieHandler(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(StringInfo outMsg, bool *caughtup);
104 static void CheckClosedConnection(void);
107 * How much WAL to send in one message? Must be >= XLOG_BLCKSZ.
109 * We don't have a good idea of what a good value would be; there's some
110 * overhead per message in both walsender and walreceiver, but on the other
111 * hand sending large batches makes walsender less responsive to signals
112 * because signals are checked only between messages. 128kB (with
113 * default 8k blocks) seems like a reasonable guess for now.
115 #define MAX_SEND_SIZE (XLOG_BLCKSZ * 16)
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 /* Unblock signals (they were blocked when the postmaster forked us) */
148 PG_SETMASK(&UnBlockSig);
150 /* Tell the standby that walsender is ready for receiving commands */
151 ReadyForQuery(DestRemote);
153 /* Handle handshake messages before streaming */
156 /* Main loop of walsender */
161 WalSndHandshake(void)
163 StringInfoData input_message;
164 bool replication_started = false;
166 initStringInfo(&input_message);
168 while (!replication_started)
172 /* Wait for a command to arrive */
173 firstchar = pq_getbyte();
176 * Check for any other interesting events that happened while we
182 ProcessConfigFile(PGC_SIGHUP);
185 if (firstchar != EOF)
188 * Read the message contents. This is expected to be done without
189 * blocking because we've been able to get message type code.
191 if (pq_getmessage(&input_message, 0))
192 firstchar = EOF; /* suitable message already logged */
195 /* Handle the very limited subset of commands expected in this phase */
198 case 'Q': /* Query message */
200 const char *query_string;
203 query_string = pq_getmsgstring(&input_message);
204 pq_getmsgend(&input_message);
206 if (strcmp(query_string, "IDENTIFY_SYSTEM") == 0)
213 * Reply with a result set with one row, two columns.
214 * First col is system ID, and second if timeline ID
217 snprintf(sysid, sizeof(sysid), UINT64_FORMAT,
218 GetSystemIdentifier());
219 snprintf(tli, sizeof(tli), "%u", ThisTimeLineID);
221 /* Send a RowDescription message */
222 pq_beginmessage(&buf, 'T');
223 pq_sendint(&buf, 2, 2); /* 2 fields */
226 pq_sendstring(&buf, "systemid"); /* col name */
227 pq_sendint(&buf, 0, 4); /* table oid */
228 pq_sendint(&buf, 0, 2); /* attnum */
229 pq_sendint(&buf, TEXTOID, 4); /* type oid */
230 pq_sendint(&buf, -1, 2); /* typlen */
231 pq_sendint(&buf, 0, 4); /* typmod */
232 pq_sendint(&buf, 0, 2); /* format code */
235 pq_sendstring(&buf, "timeline"); /* col name */
236 pq_sendint(&buf, 0, 4); /* table oid */
237 pq_sendint(&buf, 0, 2); /* attnum */
238 pq_sendint(&buf, INT4OID, 4); /* type oid */
239 pq_sendint(&buf, 4, 2); /* typlen */
240 pq_sendint(&buf, 0, 4); /* typmod */
241 pq_sendint(&buf, 0, 2); /* format code */
244 /* Send a DataRow message */
245 pq_beginmessage(&buf, 'D');
246 pq_sendint(&buf, 2, 2); /* # of columns */
247 pq_sendint(&buf, strlen(sysid), 4); /* col1 len */
248 pq_sendbytes(&buf, (char *) &sysid, strlen(sysid));
249 pq_sendint(&buf, strlen(tli), 4); /* col2 len */
250 pq_sendbytes(&buf, (char *) tli, strlen(tli));
253 /* Send CommandComplete and ReadyForQuery messages */
254 EndCommand("SELECT", DestRemote);
255 ReadyForQuery(DestRemote);
257 else if (sscanf(query_string, "START_REPLICATION %X/%X",
258 &recptr.xlogid, &recptr.xrecoff) == 2)
263 * Check that we're logging enough information in the
264 * WAL for log-shipping.
266 * NOTE: This only checks the current value of
267 * wal_level. Even if the current setting is not
268 * 'minimal', there can be old WAL in the pg_xlog
269 * directory that was created with 'minimal'.
270 * So this is not bulletproof, the purpose is
271 * just to give a user-friendly error message that
272 * hints how to configure the system correctly.
274 if (wal_level == WAL_LEVEL_MINIMAL)
276 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
277 errmsg("standby connections not allowed because wal_level=\"minimal\"")));
279 /* Send a CopyOutResponse message, and start streaming */
280 pq_beginmessage(&buf, 'H');
281 pq_sendbyte(&buf, 0);
282 pq_sendint(&buf, 0, 2);
287 * Initialize position to the received one, then the
288 * xlog records begin to be shipped from that position
292 /* break out of the loop */
293 replication_started = true;
298 (errcode(ERRCODE_PROTOCOL_VIOLATION),
299 errmsg("invalid standby query string: %s", query_string)));
305 /* standby is closing the connection */
309 /* standby disconnected unexpectedly */
311 (errcode(ERRCODE_PROTOCOL_VIOLATION),
312 errmsg("unexpected EOF on standby connection")));
317 (errcode(ERRCODE_PROTOCOL_VIOLATION),
318 errmsg("invalid standby handshake message type %d", firstchar)));
324 * Check if the remote end has closed the connection.
327 CheckClosedConnection(void)
329 unsigned char firstchar;
332 r = pq_getbyte_if_available(&firstchar);
335 /* unexpected error or EOF */
337 (errcode(ERRCODE_PROTOCOL_VIOLATION),
338 errmsg("unexpected EOF on standby connection")));
343 /* no data available without blocking */
347 /* Handle the very limited subset of commands expected in this phase */
351 * 'X' means that the standby is closing down the socket.
358 (errcode(ERRCODE_PROTOCOL_VIOLATION),
359 errmsg("invalid standby closing message type %d",
364 /* Main loop of walsender process */
368 StringInfoData output_message;
369 bool caughtup = false;
371 initStringInfo(&output_message);
376 long remain; /* remaining time (us) */
379 * Emergency bailout if postmaster has died. This is to avoid the
380 * necessity for manual cleanup of all postmaster children.
382 if (!PostmasterIsAlive(true))
384 /* Process any requests or signals received recently */
388 ProcessConfigFile(PGC_SIGHUP);
392 * When SIGUSR2 arrives, we send all outstanding logs up to the
393 * shutdown checkpoint record (i.e., the latest record) and exit.
397 XLogSend(&output_message, &caughtup);
398 shutdown_requested = true;
401 /* Normal exit from the walsender is here */
402 if (shutdown_requested)
404 /* Inform the standby that XLOG streaming was done */
405 pq_puttextmessage('C', "COPY 0");
412 * If we had sent all accumulated WAL in last round, nap for the
413 * configured time before retrying.
415 * On some platforms, signals won't interrupt the sleep. To ensure we
416 * respond reasonably promptly when someone signals us, break down the
417 * sleep into NAPTIME_PER_CYCLE increments, and check for
418 * interrupts after each nap.
422 remain = WalSndDelay * 1000L;
425 /* Check for interrupts */
426 if (got_SIGHUP || shutdown_requested || ready_to_stop)
429 /* Sleep and check that the connection is still alive */
430 pg_usleep(remain > NAPTIME_PER_CYCLE ? NAPTIME_PER_CYCLE : remain);
431 CheckClosedConnection();
433 remain -= NAPTIME_PER_CYCLE;
436 /* Attempt to send the log once every loop */
437 if (!XLogSend(&output_message, &caughtup))
441 /* can't get here because the above loop never exits */
447 * Reset whereToSendOutput to prevent ereport from attempting to send any
448 * more messages to the standby.
450 if (whereToSendOutput == DestRemote)
451 whereToSendOutput = DestNone;
454 return 1; /* keep the compiler quiet */
457 /* Initialize a per-walsender data structure for this walsender process */
461 /* use volatile pointer to prevent code rearrangement */
465 * WalSndCtl should be set up already (we inherit this by fork() or
466 * EXEC_BACKEND mechanism from the postmaster).
468 Assert(WalSndCtl != NULL);
469 Assert(MyWalSnd == NULL);
472 * Find a free walsender slot and reserve it. If this fails, we must be
473 * out of WalSnd structures.
475 for (i = 0; i < max_wal_senders; i++)
477 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
479 SpinLockAcquire(&walsnd->mutex);
481 if (walsnd->pid != 0)
483 SpinLockRelease(&walsnd->mutex);
489 MyWalSnd = (WalSnd *) walsnd;
490 walsnd->pid = MyProcPid;
491 MemSet(&MyWalSnd->sentPtr, 0, sizeof(XLogRecPtr));
492 SpinLockRelease(&walsnd->mutex);
496 if (MyWalSnd == NULL)
498 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
499 errmsg("number of requested standby connections "
500 "exceeds max_wal_senders (currently %d)",
503 /* Arrange to clean up at walsender exit */
504 on_shmem_exit(WalSndKill, 0);
507 /* Destroy the per-walsender data structure for this walsender process */
509 WalSndKill(int code, Datum arg)
511 Assert(MyWalSnd != NULL);
514 * Mark WalSnd struct no longer in use. Assume that no lock is required
519 /* WalSnd struct isn't mine anymore */
524 * Read 'nbytes' bytes from WAL into 'buf', starting at location 'recptr'
527 XLogRead(char *buf, XLogRecPtr recptr, Size nbytes)
529 XLogRecPtr startRecPtr = recptr;
530 char path[MAXPGPATH];
531 uint32 lastRemovedLog;
532 uint32 lastRemovedSeg;
542 startoff = recptr.xrecoff % XLogSegSize;
544 if (sendFile < 0 || !XLByteInSeg(recptr, sendId, sendSeg))
546 /* Switch to another logfile segment */
550 XLByteToSeg(recptr, sendId, sendSeg);
551 XLogFilePath(path, ThisTimeLineID, sendId, sendSeg);
553 sendFile = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
557 * If the file is not found, assume it's because the
558 * standby asked for a too old WAL segment that has already
559 * been removed or recycled.
563 char filename[MAXFNAMELEN];
564 XLogFileName(filename, ThisTimeLineID, sendId, sendSeg);
566 (errcode_for_file_access(),
567 errmsg("requested WAL segment %s has already been removed",
572 (errcode_for_file_access(),
573 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
574 path, sendId, sendSeg)));
579 /* Need to seek in the file? */
580 if (sendOff != startoff)
582 if (lseek(sendFile, (off_t) startoff, SEEK_SET) < 0)
584 (errcode_for_file_access(),
585 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
586 sendId, sendSeg, startoff)));
590 /* How many bytes are within this segment? */
591 if (nbytes > (XLogSegSize - startoff))
592 segbytes = XLogSegSize - startoff;
596 readbytes = read(sendFile, buf, segbytes);
599 (errcode_for_file_access(),
600 errmsg("could not read from log file %u, segment %u, offset %u, "
602 sendId, sendSeg, sendOff, (unsigned long) segbytes)));
604 /* Update state for read */
605 XLByteAdvance(recptr, readbytes);
607 sendOff += readbytes;
613 * After reading into the buffer, check that what we read was valid.
614 * We do this after reading, because even though the segment was present
615 * when we opened it, it might get recycled or removed while we read it.
616 * The read() succeeds in that case, but the data we tried to read might
617 * already have been overwritten with new WAL records.
619 XLogGetLastRemoved(&lastRemovedLog, &lastRemovedSeg);
620 XLByteToSeg(startRecPtr, log, seg);
621 if (log < lastRemovedLog ||
622 (log == lastRemovedLog && seg <= lastRemovedSeg))
624 char filename[MAXFNAMELEN];
625 XLogFileName(filename, ThisTimeLineID, log, seg);
627 (errcode_for_file_access(),
628 errmsg("requested WAL segment %s has already been removed",
634 * Read up to MAX_SEND_SIZE bytes of WAL that's been written (and flushed),
635 * but not yet sent to the client, and send it. If there is no unsent WAL,
636 * *caughtup is set to true and nothing is sent, otherwise *caughtup is set
639 * Returns true if OK, false if trouble.
642 XLogSend(StringInfo outMsg, bool *caughtup)
644 XLogRecPtr SendRqstPtr;
648 char activitymsg[50];
650 /* use volatile pointer to prevent code rearrangement */
651 volatile WalSnd *walsnd = MyWalSnd;
653 /* Attempt to send all records flushed to the disk already */
654 SendRqstPtr = GetWriteRecPtr();
656 /* Quick exit if nothing to do */
657 if (!XLByteLT(sentPtr, SendRqstPtr))
663 * Otherwise let the caller know that we're not fully caught up. Unless
664 * there's a huge backlog, we'll be caught up to the current WriteRecPtr
665 * after we've sent everything below, but more WAL could accumulate while
666 * we're busy sending.
671 * Figure out how much to send in one message. If there's less than
672 * MAX_SEND_SIZE bytes to send, send everything. Otherwise send
673 * MAX_SEND_SIZE bytes, but round to page boundary.
675 * The rounding is not only for performance reasons. Walreceiver
676 * relies on the fact that we never split a WAL record across two
677 * messages. Since a long WAL record is split at page boundary into
678 * continuation records, page boundary is always a safe cut-off point.
679 * We also assume that SendRqstPtr never points in the middle of a WAL
683 if (startptr.xrecoff >= XLogFileSize)
686 * crossing a logid boundary, skip the non-existent last log
687 * segment in previous logical log file.
689 startptr.xlogid += 1;
690 startptr.xrecoff = 0;
694 XLByteAdvance(endptr, MAX_SEND_SIZE);
695 /* round down to page boundary. */
696 endptr.xrecoff -= (endptr.xrecoff % XLOG_BLCKSZ);
697 /* if we went beyond SendRqstPtr, back off */
698 if (XLByteLT(SendRqstPtr, endptr))
699 endptr = SendRqstPtr;
702 * OK to read and send the slice.
704 * We don't need to convert the xlogid/xrecoff from host byte order to
705 * network byte order because the both server can be expected to have
706 * the same byte order. If they have different byte order, we don't
709 pq_sendbyte(outMsg, 'w');
710 pq_sendbytes(outMsg, (char *) &startptr, sizeof(startptr));
712 if (endptr.xlogid != startptr.xlogid)
714 Assert(endptr.xlogid == startptr.xlogid + 1);
715 nbytes = endptr.xrecoff + XLogFileSize - startptr.xrecoff;
718 nbytes = endptr.xrecoff - startptr.xrecoff;
723 * Read the log directly into the output buffer to prevent extra
726 enlargeStringInfo(outMsg, nbytes);
728 XLogRead(&outMsg->data[outMsg->len], startptr, nbytes);
729 outMsg->len += nbytes;
730 outMsg->data[outMsg->len] = '\0';
732 pq_putmessage('d', outMsg->data, outMsg->len);
733 resetStringInfo(outMsg);
735 /* Update shared memory status */
736 SpinLockAcquire(&walsnd->mutex);
737 walsnd->sentPtr = sentPtr;
738 SpinLockRelease(&walsnd->mutex);
740 /* Flush pending output */
744 /* Report progress of XLOG streaming in PS display */
745 snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%X",
746 sentPtr.xlogid, sentPtr.xrecoff);
747 set_ps_display(activitymsg, false);
752 /* SIGHUP: set flag to re-read config file at next convenient time */
754 WalSndSigHupHandler(SIGNAL_ARGS)
759 /* SIGTERM: set flag to shut down */
761 WalSndShutdownHandler(SIGNAL_ARGS)
763 shutdown_requested = true;
767 * WalSndQuickDieHandler() occurs when signalled SIGQUIT by the postmaster.
769 * Some backend has bought the farm,
770 * so we need to stop what we're doing and exit.
773 WalSndQuickDieHandler(SIGNAL_ARGS)
775 PG_SETMASK(&BlockSig);
778 * We DO NOT want to run proc_exit() callbacks -- we're here because
779 * shared memory may be corrupted, so we don't want to try to clean up our
780 * transaction. Just nail the windows shut and get out of town. Now that
781 * there's an atexit callback to prevent third-party code from breaking
782 * things by calling exit() directly, we have to reset the callbacks
783 * explicitly to make this work as intended.
788 * Note we do exit(2) not exit(0). This is to force the postmaster into a
789 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
790 * backend. This is necessary precisely because we don't clean up our
791 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
792 * should ensure the postmaster sees this as a crash, too, but no harm in
793 * being doubly sure.)
798 /* SIGUSR2: set flag to do a last cycle and shut down afterwards */
800 WalSndLastCycleHandler(SIGNAL_ARGS)
802 ready_to_stop = true;
805 /* Set up signal handlers */
809 /* Set up signal handlers */
810 pqsignal(SIGHUP, WalSndSigHupHandler); /* set flag to read config
812 pqsignal(SIGINT, SIG_IGN); /* not used */
813 pqsignal(SIGTERM, WalSndShutdownHandler); /* request shutdown */
814 pqsignal(SIGQUIT, WalSndQuickDieHandler); /* hard crash time */
815 pqsignal(SIGALRM, SIG_IGN);
816 pqsignal(SIGPIPE, SIG_IGN);
817 pqsignal(SIGUSR1, SIG_IGN); /* not used */
818 pqsignal(SIGUSR2, WalSndLastCycleHandler); /* request a last cycle and
821 /* Reset some signals that are accepted by postmaster but not here */
822 pqsignal(SIGCHLD, SIG_DFL);
823 pqsignal(SIGTTIN, SIG_DFL);
824 pqsignal(SIGTTOU, SIG_DFL);
825 pqsignal(SIGCONT, SIG_DFL);
826 pqsignal(SIGWINCH, SIG_DFL);
829 /* Report shared-memory space needed by WalSndShmemInit */
831 WalSndShmemSize(void)
835 size = offsetof(WalSndCtlData, walsnds);
836 size = add_size(size, mul_size(max_wal_senders, sizeof(WalSnd)));
841 /* Allocate and initialize walsender-related shared memory */
843 WalSndShmemInit(void)
848 WalSndCtl = (WalSndCtlData *)
849 ShmemInitStruct("Wal Sender Ctl", WalSndShmemSize(), &found);
853 /* First time through, so initialize */
854 MemSet(WalSndCtl, 0, WalSndShmemSize());
856 for (i = 0; i < max_wal_senders; i++)
858 WalSnd *walsnd = &WalSndCtl->walsnds[i];
860 SpinLockInit(&walsnd->mutex);
866 * This isn't currently used for anything. Monitoring tools might be
867 * interested in the future, and we'll need something like this in the
868 * future for synchronous replication.
872 * Returns the oldest Send position among walsenders. Or InvalidXLogRecPtr
876 GetOldestWALSendPointer(void)
878 XLogRecPtr oldest = {0, 0};
882 for (i = 0; i < max_wal_senders; i++)
884 /* use volatile pointer to prevent code rearrangement */
885 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
888 if (walsnd->pid == 0)
891 SpinLockAcquire(&walsnd->mutex);
892 recptr = walsnd->sentPtr;
893 SpinLockRelease(&walsnd->mutex);
895 if (recptr.xlogid == 0 && recptr.xrecoff == 0)
898 if (!found || XLByteLT(recptr, oldest))