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.20 2010/05/09 18:11:55 tgl 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);
104 static void CheckClosedConnection(void);
107 * How much WAL to send in one message? Must be >= XLOG_BLCKSZ.
109 #define MAX_SEND_SIZE (XLOG_SEG_SIZE / 2)
111 /* Main entry point for walsender process */
115 MemoryContext walsnd_context;
117 if (RecoveryInProgress())
119 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
120 errmsg("recovery is still in progress, can't accept WAL streaming connections")));
122 /* Create a per-walsender data structure in shared memory */
126 * Create a memory context that we will do all our work in. We do this so
127 * that we can reset the context during error recovery and thereby avoid
128 * possible memory leaks. Formerly this code just ran in
129 * TopMemoryContext, but resetting that would be a really bad idea.
131 * XXX: we don't actually attempt error recovery in walsender, we just
132 * close the connection and exit.
134 walsnd_context = AllocSetContextCreate(TopMemoryContext,
136 ALLOCSET_DEFAULT_MINSIZE,
137 ALLOCSET_DEFAULT_INITSIZE,
138 ALLOCSET_DEFAULT_MAXSIZE);
139 MemoryContextSwitchTo(walsnd_context);
141 /* Unblock signals (they were blocked when the postmaster forked us) */
142 PG_SETMASK(&UnBlockSig);
144 /* Tell the standby that walsender is ready for receiving commands */
145 ReadyForQuery(DestRemote);
147 /* Handle handshake messages before streaming */
150 /* Main loop of walsender */
155 WalSndHandshake(void)
157 StringInfoData input_message;
158 bool replication_started = false;
160 initStringInfo(&input_message);
162 while (!replication_started)
166 /* Wait for a command to arrive */
167 firstchar = pq_getbyte();
170 * Check for any other interesting events that happened while we
176 ProcessConfigFile(PGC_SIGHUP);
179 if (firstchar != EOF)
182 * Read the message contents. This is expected to be done without
183 * blocking because we've been able to get message type code.
185 if (pq_getmessage(&input_message, 0))
186 firstchar = EOF; /* suitable message already logged */
189 /* Handle the very limited subset of commands expected in this phase */
192 case 'Q': /* Query message */
194 const char *query_string;
197 query_string = pq_getmsgstring(&input_message);
198 pq_getmsgend(&input_message);
200 if (strcmp(query_string, "IDENTIFY_SYSTEM") == 0)
207 * Reply with a result set with one row, two columns.
208 * First col is system ID, and second if timeline ID
211 snprintf(sysid, sizeof(sysid), UINT64_FORMAT,
212 GetSystemIdentifier());
213 snprintf(tli, sizeof(tli), "%u", ThisTimeLineID);
215 /* Send a RowDescription message */
216 pq_beginmessage(&buf, 'T');
217 pq_sendint(&buf, 2, 2); /* 2 fields */
220 pq_sendstring(&buf, "systemid"); /* col name */
221 pq_sendint(&buf, 0, 4); /* table oid */
222 pq_sendint(&buf, 0, 2); /* attnum */
223 pq_sendint(&buf, TEXTOID, 4); /* type oid */
224 pq_sendint(&buf, -1, 2); /* typlen */
225 pq_sendint(&buf, 0, 4); /* typmod */
226 pq_sendint(&buf, 0, 2); /* format code */
229 pq_sendstring(&buf, "timeline"); /* col name */
230 pq_sendint(&buf, 0, 4); /* table oid */
231 pq_sendint(&buf, 0, 2); /* attnum */
232 pq_sendint(&buf, INT4OID, 4); /* type oid */
233 pq_sendint(&buf, 4, 2); /* typlen */
234 pq_sendint(&buf, 0, 4); /* typmod */
235 pq_sendint(&buf, 0, 2); /* format code */
238 /* Send a DataRow message */
239 pq_beginmessage(&buf, 'D');
240 pq_sendint(&buf, 2, 2); /* # of columns */
241 pq_sendint(&buf, strlen(sysid), 4); /* col1 len */
242 pq_sendbytes(&buf, (char *) &sysid, strlen(sysid));
243 pq_sendint(&buf, strlen(tli), 4); /* col2 len */
244 pq_sendbytes(&buf, (char *) tli, strlen(tli));
247 /* Send CommandComplete and ReadyForQuery messages */
248 EndCommand("SELECT", DestRemote);
249 ReadyForQuery(DestRemote);
251 else if (sscanf(query_string, "START_REPLICATION %X/%X",
252 &recptr.xlogid, &recptr.xrecoff) == 2)
257 * Check that we're logging enough information in the
258 * WAL for log-shipping.
260 * NOTE: This only checks the current value of
261 * wal_level. Even if the current setting is not
262 * 'minimal', there can be old WAL in the pg_xlog
263 * directory that was created with 'minimal'.
264 * So this is not bulletproof, the purpose is
265 * just to give a user-friendly error message that
266 * hints how to configure the system correctly.
268 if (wal_level == WAL_LEVEL_MINIMAL)
270 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
271 errmsg("standby connections not allowed because wal_level=\"minimal\"")));
273 /* Send a CopyOutResponse message, and start streaming */
274 pq_beginmessage(&buf, 'H');
275 pq_sendbyte(&buf, 0);
276 pq_sendint(&buf, 0, 2);
281 * Initialize position to the received one, then the
282 * xlog records begin to be shipped from that position
286 /* break out of the loop */
287 replication_started = true;
292 (errcode(ERRCODE_PROTOCOL_VIOLATION),
293 errmsg("invalid standby query string: %s", query_string)));
299 /* standby is closing the connection */
303 /* standby disconnected unexpectedly */
305 (errcode(ERRCODE_PROTOCOL_VIOLATION),
306 errmsg("unexpected EOF on standby connection")));
311 (errcode(ERRCODE_PROTOCOL_VIOLATION),
312 errmsg("invalid standby handshake message type %d", firstchar)));
318 * Check if the remote end has closed the connection.
321 CheckClosedConnection(void)
323 unsigned char firstchar;
326 r = pq_getbyte_if_available(&firstchar);
329 /* unexpected error or EOF */
331 (errcode(ERRCODE_PROTOCOL_VIOLATION),
332 errmsg("unexpected EOF on standby connection")));
337 /* no data available without blocking */
341 /* Handle the very limited subset of commands expected in this phase */
345 * 'X' means that the standby is closing down the socket.
352 (errcode(ERRCODE_PROTOCOL_VIOLATION),
353 errmsg("invalid standby closing message type %d",
358 /* Main loop of walsender process */
362 StringInfoData output_message;
364 initStringInfo(&output_message);
369 long remain; /* remaining time (us) */
372 * Emergency bailout if postmaster has died. This is to avoid the
373 * necessity for manual cleanup of all postmaster children.
375 if (!PostmasterIsAlive(true))
377 /* Process any requests or signals received recently */
381 ProcessConfigFile(PGC_SIGHUP);
385 * When SIGUSR2 arrives, we send all outstanding logs up to the
386 * shutdown checkpoint record (i.e., the latest record) and exit.
390 XLogSend(&output_message);
391 shutdown_requested = true;
394 /* Normal exit from the walsender is here */
395 if (shutdown_requested)
397 /* Inform the standby that XLOG streaming was done */
398 pq_puttextmessage('C', "COPY 0");
405 * Nap for the configured time or until a message arrives.
407 * On some platforms, signals won't interrupt the sleep. To ensure we
408 * respond reasonably promptly when someone signals us, break down the
409 * sleep into NAPTIME_PER_CYCLE increments, and check for
410 * interrupts after each nap.
412 remain = WalSndDelay * 1000L;
415 if (got_SIGHUP || shutdown_requested || ready_to_stop)
419 * Check to see whether a message from the standby or an interrupt
420 * from other processes has arrived.
422 pg_usleep(remain > NAPTIME_PER_CYCLE ? NAPTIME_PER_CYCLE : remain);
423 CheckClosedConnection();
425 remain -= NAPTIME_PER_CYCLE;
428 /* Attempt to send the log once every loop */
429 if (!XLogSend(&output_message))
433 /* can't get here because the above loop never exits */
439 * Reset whereToSendOutput to prevent ereport from attempting to send any
440 * more messages to the standby.
442 if (whereToSendOutput == DestRemote)
443 whereToSendOutput = DestNone;
446 return 1; /* keep the compiler quiet */
449 /* Initialize a per-walsender data structure for this walsender process */
453 /* use volatile pointer to prevent code rearrangement */
457 * WalSndCtl should be set up already (we inherit this by fork() or
458 * EXEC_BACKEND mechanism from the postmaster).
460 Assert(WalSndCtl != NULL);
461 Assert(MyWalSnd == NULL);
464 * Find a free walsender slot and reserve it. If this fails, we must be
465 * out of WalSnd structures.
467 for (i = 0; i < max_wal_senders; i++)
469 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
471 SpinLockAcquire(&walsnd->mutex);
473 if (walsnd->pid != 0)
475 SpinLockRelease(&walsnd->mutex);
481 MyWalSnd = (WalSnd *) walsnd;
482 walsnd->pid = MyProcPid;
483 MemSet(&MyWalSnd->sentPtr, 0, sizeof(XLogRecPtr));
484 SpinLockRelease(&walsnd->mutex);
488 if (MyWalSnd == NULL)
490 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
491 errmsg("number of requested standby connections "
492 "exceeds max_wal_senders (currently %d)",
495 /* Arrange to clean up at walsender exit */
496 on_shmem_exit(WalSndKill, 0);
499 /* Destroy the per-walsender data structure for this walsender process */
501 WalSndKill(int code, Datum arg)
503 Assert(MyWalSnd != NULL);
506 * Mark WalSnd struct no longer in use. Assume that no lock is required
511 /* WalSnd struct isn't mine anymore */
516 * Read 'nbytes' bytes from WAL into 'buf', starting at location 'recptr'
519 XLogRead(char *buf, XLogRecPtr recptr, Size nbytes)
521 XLogRecPtr startRecPtr = recptr;
522 char path[MAXPGPATH];
523 uint32 lastRemovedLog;
524 uint32 lastRemovedSeg;
534 startoff = recptr.xrecoff % XLogSegSize;
536 if (sendFile < 0 || !XLByteInSeg(recptr, sendId, sendSeg))
538 /* Switch to another logfile segment */
542 XLByteToSeg(recptr, sendId, sendSeg);
543 XLogFilePath(path, ThisTimeLineID, sendId, sendSeg);
545 sendFile = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
549 * If the file is not found, assume it's because the
550 * standby asked for a too old WAL segment that has already
551 * been removed or recycled.
555 char filename[MAXFNAMELEN];
556 XLogFileName(filename, ThisTimeLineID, sendId, sendSeg);
558 (errcode_for_file_access(),
559 errmsg("requested WAL segment %s has already been removed",
564 (errcode_for_file_access(),
565 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
566 path, sendId, sendSeg)));
571 /* Need to seek in the file? */
572 if (sendOff != startoff)
574 if (lseek(sendFile, (off_t) startoff, SEEK_SET) < 0)
576 (errcode_for_file_access(),
577 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
578 sendId, sendSeg, startoff)));
582 /* How many bytes are within this segment? */
583 if (nbytes > (XLogSegSize - startoff))
584 segbytes = XLogSegSize - startoff;
588 readbytes = read(sendFile, buf, segbytes);
591 (errcode_for_file_access(),
592 errmsg("could not read from log file %u, segment %u, offset %u, "
594 sendId, sendSeg, sendOff, (unsigned long) segbytes)));
596 /* Update state for read */
597 XLByteAdvance(recptr, readbytes);
599 sendOff += readbytes;
605 * After reading into the buffer, check that what we read was valid.
606 * We do this after reading, because even though the segment was present
607 * when we opened it, it might get recycled or removed while we read it.
608 * The read() succeeds in that case, but the data we tried to read might
609 * already have been overwritten with new WAL records.
611 XLogGetLastRemoved(&lastRemovedLog, &lastRemovedSeg);
612 XLByteToSeg(startRecPtr, log, seg);
613 if (log < lastRemovedLog ||
614 (log == lastRemovedLog && seg <= lastRemovedSeg))
616 char filename[MAXFNAMELEN];
617 XLogFileName(filename, ThisTimeLineID, log, seg);
619 (errcode_for_file_access(),
620 errmsg("requested WAL segment %s has already been removed",
626 * Read all WAL that's been written (and flushed) since last cycle, and send
629 * Returns true if OK, false if trouble.
632 XLogSend(StringInfo outMsg)
634 XLogRecPtr SendRqstPtr;
635 char activitymsg[50];
637 /* use volatile pointer to prevent code rearrangement */
638 volatile WalSnd *walsnd = MyWalSnd;
640 /* Attempt to send all records flushed to the disk already */
641 SendRqstPtr = GetWriteRecPtr();
643 /* Quick exit if nothing to do */
644 if (!XLByteLT(sentPtr, SendRqstPtr))
648 * We gather multiple records together by issuing just one XLogRead() of a
649 * suitable size, and send them as one CopyData message. Repeat until
650 * we've sent everything we can.
652 while (XLByteLT(sentPtr, SendRqstPtr))
659 * Figure out how much to send in one message. If there's less than
660 * MAX_SEND_SIZE bytes to send, send everything. Otherwise send
661 * MAX_SEND_SIZE bytes, but round to page boundary.
663 * The rounding is not only for performance reasons. Walreceiver
664 * relies on the fact that we never split a WAL record across two
665 * messages. Since a long WAL record is split at page boundary into
666 * continuation records, page boundary is always a safe cut-off point.
667 * We also assume that SendRqstPtr never points in the middle of a WAL
671 if (startptr.xrecoff >= XLogFileSize)
674 * crossing a logid boundary, skip the non-existent last log
675 * segment in previous logical log file.
677 startptr.xlogid += 1;
678 startptr.xrecoff = 0;
682 XLByteAdvance(endptr, MAX_SEND_SIZE);
683 /* round down to page boundary. */
684 endptr.xrecoff -= (endptr.xrecoff % XLOG_BLCKSZ);
685 /* if we went beyond SendRqstPtr, back off */
686 if (XLByteLT(SendRqstPtr, endptr))
687 endptr = SendRqstPtr;
690 * OK to read and send the slice.
692 * We don't need to convert the xlogid/xrecoff from host byte order to
693 * network byte order because the both server can be expected to have
694 * the same byte order. If they have different byte order, we don't
697 pq_sendbyte(outMsg, 'w');
698 pq_sendbytes(outMsg, (char *) &startptr, sizeof(startptr));
700 if (endptr.xlogid != startptr.xlogid)
702 Assert(endptr.xlogid == startptr.xlogid + 1);
703 nbytes = endptr.xrecoff + XLogFileSize - startptr.xrecoff;
706 nbytes = endptr.xrecoff - startptr.xrecoff;
711 * Read the log directly into the output buffer to prevent extra
714 enlargeStringInfo(outMsg, nbytes);
716 XLogRead(&outMsg->data[outMsg->len], startptr, nbytes);
717 outMsg->len += nbytes;
718 outMsg->data[outMsg->len] = '\0';
720 pq_putmessage('d', outMsg->data, outMsg->len);
721 resetStringInfo(outMsg);
724 /* Update shared memory status */
725 SpinLockAcquire(&walsnd->mutex);
726 walsnd->sentPtr = sentPtr;
727 SpinLockRelease(&walsnd->mutex);
729 /* Flush pending output */
733 /* Report progress of XLOG streaming in PS display */
734 snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%X",
735 sentPtr.xlogid, sentPtr.xrecoff);
736 set_ps_display(activitymsg, false);
741 /* SIGHUP: set flag to re-read config file at next convenient time */
743 WalSndSigHupHandler(SIGNAL_ARGS)
748 /* SIGTERM: set flag to shut down */
750 WalSndShutdownHandler(SIGNAL_ARGS)
752 shutdown_requested = true;
756 * WalSndQuickDieHandler() occurs when signalled SIGQUIT by the postmaster.
758 * Some backend has bought the farm,
759 * so we need to stop what we're doing and exit.
762 WalSndQuickDieHandler(SIGNAL_ARGS)
764 PG_SETMASK(&BlockSig);
767 * We DO NOT want to run proc_exit() callbacks -- we're here because
768 * shared memory may be corrupted, so we don't want to try to clean up our
769 * transaction. Just nail the windows shut and get out of town. Now that
770 * there's an atexit callback to prevent third-party code from breaking
771 * things by calling exit() directly, we have to reset the callbacks
772 * explicitly to make this work as intended.
777 * Note we do exit(2) not exit(0). This is to force the postmaster into a
778 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
779 * backend. This is necessary precisely because we don't clean up our
780 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
781 * should ensure the postmaster sees this as a crash, too, but no harm in
782 * being doubly sure.)
787 /* SIGUSR2: set flag to do a last cycle and shut down afterwards */
789 WalSndLastCycleHandler(SIGNAL_ARGS)
791 ready_to_stop = true;
794 /* Set up signal handlers */
798 /* Set up signal handlers */
799 pqsignal(SIGHUP, WalSndSigHupHandler); /* set flag to read config
801 pqsignal(SIGINT, SIG_IGN); /* not used */
802 pqsignal(SIGTERM, WalSndShutdownHandler); /* request shutdown */
803 pqsignal(SIGQUIT, WalSndQuickDieHandler); /* hard crash time */
804 pqsignal(SIGALRM, SIG_IGN);
805 pqsignal(SIGPIPE, SIG_IGN);
806 pqsignal(SIGUSR1, SIG_IGN); /* not used */
807 pqsignal(SIGUSR2, WalSndLastCycleHandler); /* request a last cycle and
810 /* Reset some signals that are accepted by postmaster but not here */
811 pqsignal(SIGCHLD, SIG_DFL);
812 pqsignal(SIGTTIN, SIG_DFL);
813 pqsignal(SIGTTOU, SIG_DFL);
814 pqsignal(SIGCONT, SIG_DFL);
815 pqsignal(SIGWINCH, SIG_DFL);
818 /* Report shared-memory space needed by WalSndShmemInit */
820 WalSndShmemSize(void)
824 size = offsetof(WalSndCtlData, walsnds);
825 size = add_size(size, mul_size(max_wal_senders, sizeof(WalSnd)));
830 /* Allocate and initialize walsender-related shared memory */
832 WalSndShmemInit(void)
837 WalSndCtl = (WalSndCtlData *)
838 ShmemInitStruct("Wal Sender Ctl", WalSndShmemSize(), &found);
842 /* First time through, so initialize */
843 MemSet(WalSndCtl, 0, WalSndShmemSize());
845 for (i = 0; i < max_wal_senders; i++)
847 WalSnd *walsnd = &WalSndCtl->walsnds[i];
849 SpinLockInit(&walsnd->mutex);
855 * This isn't currently used for anything. Monitoring tools might be
856 * interested in the future, and we'll need something like this in the
857 * future for synchronous replication.
861 * Returns the oldest Send position among walsenders. Or InvalidXLogRecPtr
865 GetOldestWALSendPointer(void)
867 XLogRecPtr oldest = {0, 0};
871 for (i = 0; i < max_wal_senders; i++)
873 /* use volatile pointer to prevent code rearrangement */
874 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
877 if (walsnd->pid == 0)
880 SpinLockAcquire(&walsnd->mutex);
881 recptr = walsnd->sentPtr;
882 SpinLockRelease(&walsnd->mutex);
884 if (recptr.xlogid == 0 && recptr.xrecoff == 0)
887 if (!found || XLByteLT(recptr, oldest))