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.11 2010/03/24 20:11:12 sriggs 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/lock.h"
51 #include "storage/pmsignal.h"
52 #include "tcop/tcopprot.h"
53 #include "utils/guc.h"
54 #include "utils/memutils.h"
55 #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 MaxWalSenders = 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;
119 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
120 errmsg("must be superuser to start walsender")));
122 if (RecoveryInProgress())
124 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
125 errmsg("recovery is still in progress, can't accept WAL streaming connections")));
127 /* Create a per-walsender data structure in shared memory */
131 * Create a memory context that we will do all our work in. We do this so
132 * that we can reset the context during error recovery and thereby avoid
133 * possible memory leaks. Formerly this code just ran in
134 * TopMemoryContext, but resetting that would be a really bad idea.
136 * XXX: we don't actually attempt error recovery in walsender, we just
137 * close the connection and exit.
139 walsnd_context = AllocSetContextCreate(TopMemoryContext,
141 ALLOCSET_DEFAULT_MINSIZE,
142 ALLOCSET_DEFAULT_INITSIZE,
143 ALLOCSET_DEFAULT_MAXSIZE);
144 MemoryContextSwitchTo(walsnd_context);
146 /* Unblock signals (they were blocked when the postmaster forked us) */
147 PG_SETMASK(&UnBlockSig);
149 /* Tell the standby that walsender is ready for receiving commands */
150 ReadyForQuery(DestRemote);
152 /* Handle handshake messages before streaming */
155 /* Main loop of walsender */
160 WalSndHandshake(void)
162 StringInfoData input_message;
163 bool replication_started = false;
165 initStringInfo(&input_message);
167 while (!replication_started)
171 /* Wait for a command to arrive */
172 firstchar = pq_getbyte();
175 * Check for any other interesting events that happened while we
181 ProcessConfigFile(PGC_SIGHUP);
184 if (firstchar != EOF)
187 * Read the message contents. This is expected to be done without
188 * blocking because we've been able to get message type code.
190 if (pq_getmessage(&input_message, 0))
191 firstchar = EOF; /* suitable message already logged */
194 /* Handle the very limited subset of commands expected in this phase */
197 case 'Q': /* Query message */
199 const char *query_string;
202 query_string = pq_getmsgstring(&input_message);
203 pq_getmsgend(&input_message);
205 if (strcmp(query_string, "IDENTIFY_SYSTEM") == 0)
212 * Reply with a result set with one row, two columns.
213 * First col is system ID, and second if timeline ID
216 snprintf(sysid, sizeof(sysid), UINT64_FORMAT,
217 GetSystemIdentifier());
218 snprintf(tli, sizeof(tli), "%u", ThisTimeLineID);
220 /* Send a RowDescription message */
221 pq_beginmessage(&buf, 'T');
222 pq_sendint(&buf, 2, 2); /* 2 fields */
225 pq_sendstring(&buf, "systemid"); /* col name */
226 pq_sendint(&buf, 0, 4); /* table oid */
227 pq_sendint(&buf, 0, 2); /* attnum */
228 pq_sendint(&buf, TEXTOID, 4); /* type oid */
229 pq_sendint(&buf, -1, 2); /* typlen */
230 pq_sendint(&buf, 0, 4); /* typmod */
231 pq_sendint(&buf, 0, 2); /* format code */
234 pq_sendstring(&buf, "timeline"); /* col name */
235 pq_sendint(&buf, 0, 4); /* table oid */
236 pq_sendint(&buf, 0, 2); /* attnum */
237 pq_sendint(&buf, INT4OID, 4); /* type oid */
238 pq_sendint(&buf, 4, 2); /* typlen */
239 pq_sendint(&buf, 0, 4); /* typmod */
240 pq_sendint(&buf, 0, 2); /* format code */
243 /* Send a DataRow message */
244 pq_beginmessage(&buf, 'D');
245 pq_sendint(&buf, 2, 2); /* # of columns */
246 pq_sendint(&buf, strlen(sysid), 4); /* col1 len */
247 pq_sendbytes(&buf, (char *) &sysid, strlen(sysid));
248 pq_sendint(&buf, strlen(tli), 4); /* col2 len */
249 pq_sendbytes(&buf, (char *) tli, strlen(tli));
252 /* Send CommandComplete and ReadyForQuery messages */
253 EndCommand("SELECT", DestRemote);
254 ReadyForQuery(DestRemote);
256 else if (sscanf(query_string, "START_REPLICATION %X/%X",
257 &recptr.xlogid, &recptr.xrecoff) == 2)
261 /* Send a CopyOutResponse message, and start streaming */
262 pq_beginmessage(&buf, 'H');
263 pq_sendbyte(&buf, 0);
264 pq_sendint(&buf, 0, 2);
268 * Initialize position to the received one, then the
269 * xlog records begin to be shipped from that position
273 /* break out of the loop */
274 replication_started = true;
279 (errcode(ERRCODE_PROTOCOL_VIOLATION),
280 errmsg("invalid standby query string: %s", query_string)));
286 /* standby is closing the connection */
290 /* standby disconnected unexpectedly */
292 (errcode(ERRCODE_PROTOCOL_VIOLATION),
293 errmsg("unexpected EOF on standby connection")));
298 (errcode(ERRCODE_PROTOCOL_VIOLATION),
299 errmsg("invalid standby handshake message type %d", firstchar)));
305 * Check if the remote end has closed the connection.
308 CheckClosedConnection(void)
310 unsigned char firstchar;
313 r = pq_getbyte_if_available(&firstchar);
316 /* unexpected error or EOF */
318 (errcode(ERRCODE_PROTOCOL_VIOLATION),
319 errmsg("unexpected EOF on standby connection")));
324 /* no data available without blocking */
328 /* Handle the very limited subset of commands expected in this phase */
332 * 'X' means that the standby is closing down the socket.
339 (errcode(ERRCODE_PROTOCOL_VIOLATION),
340 errmsg("invalid standby closing message type %d",
345 /* Main loop of walsender process */
349 StringInfoData output_message;
351 initStringInfo(&output_message);
356 int remain; /* remaining time (ms) */
359 * Emergency bailout if postmaster has died. This is to avoid the
360 * necessity for manual cleanup of all postmaster children.
362 if (!PostmasterIsAlive(true))
364 /* Process any requests or signals received recently */
368 ProcessConfigFile(PGC_SIGHUP);
372 * When SIGUSR2 arrives, we send all outstanding logs up to the
373 * shutdown checkpoint record (i.e., the latest record) and exit.
377 XLogSend(&output_message);
378 shutdown_requested = true;
381 /* Normal exit from the walsender is here */
382 if (shutdown_requested)
384 /* Inform the standby that XLOG streaming was done */
385 pq_puttextmessage('C', "COPY 0");
392 * Nap for the configured time or until a message arrives.
394 * On some platforms, signals won't interrupt the sleep. To ensure we
395 * respond reasonably promptly when someone signals us, break down the
396 * sleep into NAPTIME_PER_CYCLE (ms) increments, and check for
397 * interrupts after each nap.
399 remain = WalSndDelay * 1000L;
402 if (got_SIGHUP || shutdown_requested || ready_to_stop)
406 * Check to see whether a message from the standby or an interrupt
407 * from other processes has arrived.
409 pg_usleep(remain > NAPTIME_PER_CYCLE ? NAPTIME_PER_CYCLE : remain);
410 CheckClosedConnection();
412 remain -= NAPTIME_PER_CYCLE;
415 /* Attempt to send the log once every loop */
416 if (!XLogSend(&output_message))
420 /* can't get here because the above loop never exits */
426 * Reset whereToSendOutput to prevent ereport from attempting to send any
427 * more messages to the standby.
429 if (whereToSendOutput == DestRemote)
430 whereToSendOutput = DestNone;
433 return 1; /* keep the compiler quiet */
436 /* Initialize a per-walsender data structure for this walsender process */
440 /* use volatile pointer to prevent code rearrangement */
444 * WalSndCtl should be set up already (we inherit this by fork() or
445 * EXEC_BACKEND mechanism from the postmaster).
447 Assert(WalSndCtl != NULL);
448 Assert(MyWalSnd == NULL);
451 * Find a free walsender slot and reserve it. If this fails, we must be
452 * out of WalSnd structures.
454 for (i = 0; i < MaxWalSenders; i++)
456 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
458 SpinLockAcquire(&walsnd->mutex);
460 if (walsnd->pid != 0)
462 SpinLockRelease(&walsnd->mutex);
468 MyWalSnd = (WalSnd *) walsnd;
469 walsnd->pid = MyProcPid;
470 MemSet(&MyWalSnd->sentPtr, 0, sizeof(XLogRecPtr));
471 SpinLockRelease(&walsnd->mutex);
475 if (MyWalSnd == NULL)
477 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
478 errmsg("sorry, too many standbys already")));
480 /* Arrange to clean up at walsender exit */
481 on_shmem_exit(WalSndKill, 0);
484 /* Destroy the per-walsender data structure for this walsender process */
486 WalSndKill(int code, Datum arg)
488 Assert(MyWalSnd != NULL);
491 * Mark WalSnd struct no longer in use. Assume that no lock is required
496 /* WalSnd struct isn't mine anymore */
501 * Read 'nbytes' bytes from WAL into 'buf', starting at location 'recptr'
504 XLogRead(char *buf, XLogRecPtr recptr, Size nbytes)
506 char path[MAXPGPATH];
514 startoff = recptr.xrecoff % XLogSegSize;
516 if (sendFile < 0 || !XLByteInSeg(recptr, sendId, sendSeg))
518 /* Switch to another logfile segment */
522 XLByteToSeg(recptr, sendId, sendSeg);
523 XLogFilePath(path, ThisTimeLineID, sendId, sendSeg);
525 sendFile = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
527 ereport(FATAL, /* XXX: Why FATAL? */
528 (errcode_for_file_access(),
529 errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
530 path, sendId, sendSeg)));
534 /* Need to seek in the file? */
535 if (sendOff != startoff)
537 if (lseek(sendFile, (off_t) startoff, SEEK_SET) < 0)
539 (errcode_for_file_access(),
540 errmsg("could not seek in log file %u, segment %u to offset %u: %m",
541 sendId, sendSeg, startoff)));
545 /* How many bytes are within this segment? */
546 if (nbytes > (XLogSegSize - startoff))
547 segbytes = XLogSegSize - startoff;
551 readbytes = read(sendFile, buf, segbytes);
554 (errcode_for_file_access(),
555 errmsg("could not read from log file %u, segment %u, offset %u, "
557 sendId, sendSeg, sendOff, (unsigned long) segbytes)));
559 /* Update state for read */
560 XLByteAdvance(recptr, readbytes);
562 sendOff += readbytes;
569 * Read all WAL that's been written (and flushed) since last cycle, and send
572 * Returns true if OK, false if trouble.
575 XLogSend(StringInfo outMsg)
577 XLogRecPtr SendRqstPtr;
578 char activitymsg[50];
580 /* use volatile pointer to prevent code rearrangement */
581 volatile WalSnd *walsnd = MyWalSnd;
583 /* Attempt to send all records flushed to the disk already */
584 SendRqstPtr = GetWriteRecPtr();
586 /* Quick exit if nothing to do */
587 if (!XLByteLT(sentPtr, SendRqstPtr))
591 * We gather multiple records together by issuing just one XLogRead() of a
592 * suitable size, and send them as one CopyData message. Repeat until
593 * we've sent everything we can.
595 while (XLByteLT(sentPtr, SendRqstPtr))
602 * Figure out how much to send in one message. If there's less than
603 * MAX_SEND_SIZE bytes to send, send everything. Otherwise send
604 * MAX_SEND_SIZE bytes, but round to page boundary.
606 * The rounding is not only for performance reasons. Walreceiver
607 * relies on the fact that we never split a WAL record across two
608 * messages. Since a long WAL record is split at page boundary into
609 * continuation records, page boundary is always a safe cut-off point.
610 * We also assume that SendRqstPtr never points in the middle of a WAL
614 if (startptr.xrecoff >= XLogFileSize)
617 * crossing a logid boundary, skip the non-existent last log
618 * segment in previous logical log file.
620 startptr.xlogid += 1;
621 startptr.xrecoff = 0;
625 XLByteAdvance(endptr, MAX_SEND_SIZE);
626 /* round down to page boundary. */
627 endptr.xrecoff -= (endptr.xrecoff % XLOG_BLCKSZ);
628 /* if we went beyond SendRqstPtr, back off */
629 if (XLByteLT(SendRqstPtr, endptr))
630 endptr = SendRqstPtr;
633 * OK to read and send the slice.
635 * We don't need to convert the xlogid/xrecoff from host byte order to
636 * network byte order because the both server can be expected to have
637 * the same byte order. If they have different byte order, we don't
640 pq_sendbyte(outMsg, 'w');
641 pq_sendbytes(outMsg, (char *) &startptr, sizeof(startptr));
643 if (endptr.xlogid != startptr.xlogid)
645 Assert(endptr.xlogid == startptr.xlogid + 1);
646 nbytes = endptr.xrecoff + XLogFileSize - startptr.xrecoff;
649 nbytes = endptr.xrecoff - startptr.xrecoff;
654 * Read the log directly into the output buffer to prevent extra
657 enlargeStringInfo(outMsg, nbytes);
659 XLogRead(&outMsg->data[outMsg->len], startptr, nbytes);
660 outMsg->len += nbytes;
661 outMsg->data[outMsg->len] = '\0';
663 pq_putmessage('d', outMsg->data, outMsg->len);
664 resetStringInfo(outMsg);
667 /* Update shared memory status */
668 SpinLockAcquire(&walsnd->mutex);
669 walsnd->sentPtr = sentPtr;
670 SpinLockRelease(&walsnd->mutex);
672 /* Flush pending output */
676 /* Report progress of XLOG streaming in PS display */
677 snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%X",
678 sentPtr.xlogid, sentPtr.xrecoff);
679 set_ps_display(activitymsg, false);
684 /* SIGHUP: set flag to re-read config file at next convenient time */
686 WalSndSigHupHandler(SIGNAL_ARGS)
691 /* SIGTERM: set flag to shut down */
693 WalSndShutdownHandler(SIGNAL_ARGS)
695 shutdown_requested = true;
699 * WalSndQuickDieHandler() occurs when signalled SIGQUIT by the postmaster.
701 * Some backend has bought the farm,
702 * so we need to stop what we're doing and exit.
705 WalSndQuickDieHandler(SIGNAL_ARGS)
707 PG_SETMASK(&BlockSig);
710 * We DO NOT want to run proc_exit() callbacks -- we're here because
711 * shared memory may be corrupted, so we don't want to try to clean up our
712 * transaction. Just nail the windows shut and get out of town. Now that
713 * there's an atexit callback to prevent third-party code from breaking
714 * things by calling exit() directly, we have to reset the callbacks
715 * explicitly to make this work as intended.
720 * Note we do exit(2) not exit(0). This is to force the postmaster into a
721 * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
722 * backend. This is necessary precisely because we don't clean up our
723 * shared memory state. (The "dead man switch" mechanism in pmsignal.c
724 * should ensure the postmaster sees this as a crash, too, but no harm in
725 * being doubly sure.)
730 /* SIGUSR2: set flag to do a last cycle and shut down afterwards */
732 WalSndLastCycleHandler(SIGNAL_ARGS)
734 ready_to_stop = true;
737 /* Set up signal handlers */
741 /* Set up signal handlers */
742 pqsignal(SIGHUP, WalSndSigHupHandler); /* set flag to read config
744 pqsignal(SIGINT, SIG_IGN); /* not used */
745 pqsignal(SIGTERM, WalSndShutdownHandler); /* request shutdown */
746 pqsignal(SIGQUIT, WalSndQuickDieHandler); /* hard crash time */
747 pqsignal(SIGALRM, SIG_IGN);
748 pqsignal(SIGPIPE, SIG_IGN);
749 pqsignal(SIGUSR1, SIG_IGN); /* not used */
750 pqsignal(SIGUSR2, WalSndLastCycleHandler); /* request a last cycle and
753 /* Reset some signals that are accepted by postmaster but not here */
754 pqsignal(SIGCHLD, SIG_DFL);
755 pqsignal(SIGTTIN, SIG_DFL);
756 pqsignal(SIGTTOU, SIG_DFL);
757 pqsignal(SIGCONT, SIG_DFL);
758 pqsignal(SIGWINCH, SIG_DFL);
761 /* Report shared-memory space needed by WalSndShmemInit */
763 WalSndShmemSize(void)
767 size = offsetof(WalSndCtlData, walsnds);
768 size = add_size(size, mul_size(MaxWalSenders, sizeof(WalSnd)));
773 /* Allocate and initialize walsender-related shared memory */
775 WalSndShmemInit(void)
780 WalSndCtl = (WalSndCtlData *)
781 ShmemInitStruct("Wal Sender Ctl", WalSndShmemSize(), &found);
783 if (WalSndCtl == NULL)
785 (errcode(ERRCODE_OUT_OF_MEMORY),
786 errmsg("not enough shared memory for walsender")));
788 return; /* already initialized */
790 /* Initialize the data structures */
791 MemSet(WalSndCtl, 0, WalSndShmemSize());
793 for (i = 0; i < MaxWalSenders; i++)
795 WalSnd *walsnd = &WalSndCtl->walsnds[i];
797 SpinLockInit(&walsnd->mutex);
802 * Returns the oldest Send position among walsenders. Or InvalidXLogRecPtr
806 GetOldestWALSendPointer(void)
808 XLogRecPtr oldest = {0, 0};
812 for (i = 0; i < MaxWalSenders; i++)
814 /* use volatile pointer to prevent code rearrangement */
815 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
818 if (walsnd->pid == 0)
821 SpinLockAcquire(&walsnd->mutex);
822 recptr = walsnd->sentPtr;
823 SpinLockRelease(&walsnd->mutex);
825 if (recptr.xlogid == 0 && recptr.xrecoff == 0)
828 if (!found || XLByteLT(recptr, oldest))