]> granicus.if.org Git - postgresql/blob - src/backend/replication/walsender.c
pgindent run for 9.0, second run
[postgresql] / src / backend / replication / walsender.c
1 /*-------------------------------------------------------------------------
2  *
3  * walsender.c
4  *
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).
14  *
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.
21  *
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.
26  *
27  *
28  * Portions Copyright (c) 2010-2010, PostgreSQL Global Development Group
29  *
30  * IDENTIFICATION
31  *        $PostgreSQL: pgsql/src/backend/replication/walsender.c,v 1.28 2010/07/06 19:18:57 momjian Exp $
32  *
33  *-------------------------------------------------------------------------
34  */
35 #include "postgres.h"
36
37 #include <unistd.h>
38
39 #include "access/xlog_internal.h"
40 #include "catalog/pg_type.h"
41 #include "libpq/libpq.h"
42 #include "libpq/pqformat.h"
43 #include "libpq/pqsignal.h"
44 #include "miscadmin.h"
45 #include "replication/walprotocol.h"
46 #include "replication/walsender.h"
47 #include "storage/fd.h"
48 #include "storage/ipc.h"
49 #include "storage/pmsignal.h"
50 #include "tcop/tcopprot.h"
51 #include "utils/guc.h"
52 #include "utils/memutils.h"
53 #include "utils/ps_status.h"
54
55
56 /* Array of WalSnds in shared memory */
57 WalSndCtlData *WalSndCtl = NULL;
58
59 /* My slot in the shared memory array */
60 static WalSnd *MyWalSnd = NULL;
61
62 /* Global state */
63 bool            am_walsender = false;           /* Am I a walsender process ? */
64
65 /* User-settable parameters for walsender */
66 int                     max_wal_senders = 0;    /* the maximum number of concurrent walsenders */
67 int                     WalSndDelay = 200;      /* max sleep time between some actions */
68
69 #define NAPTIME_PER_CYCLE 100000L               /* max sleep time between cycles
70                                                                                  * (100ms) */
71
72 /*
73  * These variables are used similarly to openLogFile/Id/Seg/Off,
74  * but for walsender to read the XLOG.
75  */
76 static int      sendFile = -1;
77 static uint32 sendId = 0;
78 static uint32 sendSeg = 0;
79 static uint32 sendOff = 0;
80
81 /*
82  * How far have we sent WAL already? This is also advertised in
83  * MyWalSnd->sentPtr.  (Actually, this is the next WAL location to send.)
84  */
85 static XLogRecPtr sentPtr = {0, 0};
86
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;
91
92 /* Signal handlers */
93 static void WalSndSigHupHandler(SIGNAL_ARGS);
94 static void WalSndShutdownHandler(SIGNAL_ARGS);
95 static void WalSndQuickDieHandler(SIGNAL_ARGS);
96
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);
105
106
107 /* Main entry point for walsender process */
108 int
109 WalSenderMain(void)
110 {
111         MemoryContext walsnd_context;
112
113         if (RecoveryInProgress())
114                 ereport(FATAL,
115                                 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
116                                  errmsg("recovery is still in progress, can't accept WAL streaming connections")));
117
118         /* Create a per-walsender data structure in shared memory */
119         InitWalSnd();
120
121         /*
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.
126          *
127          * XXX: we don't actually attempt error recovery in walsender, we just
128          * close the connection and exit.
129          */
130         walsnd_context = AllocSetContextCreate(TopMemoryContext,
131                                                                                    "Wal Sender",
132                                                                                    ALLOCSET_DEFAULT_MINSIZE,
133                                                                                    ALLOCSET_DEFAULT_INITSIZE,
134                                                                                    ALLOCSET_DEFAULT_MAXSIZE);
135         MemoryContextSwitchTo(walsnd_context);
136
137         /* Unblock signals (they were blocked when the postmaster forked us) */
138         PG_SETMASK(&UnBlockSig);
139
140         /* Tell the standby that walsender is ready for receiving commands */
141         ReadyForQuery(DestRemote);
142
143         /* Handle handshake messages before streaming */
144         WalSndHandshake();
145
146         /* Main loop of walsender */
147         return WalSndLoop();
148 }
149
150 /*
151  * Execute commands from walreceiver, until we enter streaming mode.
152  */
153 static void
154 WalSndHandshake(void)
155 {
156         StringInfoData input_message;
157         bool            replication_started = false;
158
159         initStringInfo(&input_message);
160
161         while (!replication_started)
162         {
163                 int                     firstchar;
164
165                 /* Wait for a command to arrive */
166                 firstchar = pq_getbyte();
167
168                 /*
169                  * Emergency bailout if postmaster has died.  This is to avoid the
170                  * necessity for manual cleanup of all postmaster children.
171                  */
172                 if (!PostmasterIsAlive(true))
173                         exit(1);
174
175                 /*
176                  * Check for any other interesting events that happened while we
177                  * slept.
178                  */
179                 if (got_SIGHUP)
180                 {
181                         got_SIGHUP = false;
182                         ProcessConfigFile(PGC_SIGHUP);
183                 }
184
185                 if (firstchar != EOF)
186                 {
187                         /*
188                          * Read the message contents. This is expected to be done without
189                          * blocking because we've been able to get message type code.
190                          */
191                         if (pq_getmessage(&input_message, 0))
192                                 firstchar = EOF;        /* suitable message already logged */
193                 }
194
195                 /* Handle the very limited subset of commands expected in this phase */
196                 switch (firstchar)
197                 {
198                         case 'Q':                       /* Query message */
199                                 {
200                                         const char *query_string;
201                                         XLogRecPtr      recptr;
202
203                                         query_string = pq_getmsgstring(&input_message);
204                                         pq_getmsgend(&input_message);
205
206                                         if (strcmp(query_string, "IDENTIFY_SYSTEM") == 0)
207                                         {
208                                                 StringInfoData buf;
209                                                 char            sysid[32];
210                                                 char            tli[11];
211
212                                                 /*
213                                                  * Reply with a result set with one row, two columns.
214                                                  * First col is system ID, and second is timeline ID
215                                                  */
216
217                                                 snprintf(sysid, sizeof(sysid), UINT64_FORMAT,
218                                                                  GetSystemIdentifier());
219                                                 snprintf(tli, sizeof(tli), "%u", ThisTimeLineID);
220
221                                                 /* Send a RowDescription message */
222                                                 pq_beginmessage(&buf, 'T');
223                                                 pq_sendint(&buf, 2, 2); /* 2 fields */
224
225                                                 /* first field */
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 */
233
234                                                 /* second field */
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 */
242                                                 pq_endmessage(&buf);
243
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));
251                                                 pq_endmessage(&buf);
252
253                                                 /* Send CommandComplete and ReadyForQuery messages */
254                                                 EndCommand("SELECT", DestRemote);
255                                                 ReadyForQuery(DestRemote);
256                                                 /* ReadyForQuery did pq_flush for us */
257                                         }
258                                         else if (sscanf(query_string, "START_REPLICATION %X/%X",
259                                                                         &recptr.xlogid, &recptr.xrecoff) == 2)
260                                         {
261                                                 StringInfoData buf;
262
263                                                 /*
264                                                  * Check that we're logging enough information in the
265                                                  * WAL for log-shipping.
266                                                  *
267                                                  * NOTE: This only checks the current value of
268                                                  * wal_level. Even if the current setting is not
269                                                  * 'minimal', there can be old WAL in the pg_xlog
270                                                  * directory that was created with 'minimal'. So this
271                                                  * is not bulletproof, the purpose is just to give a
272                                                  * user-friendly error message that hints how to
273                                                  * configure the system correctly.
274                                                  */
275                                                 if (wal_level == WAL_LEVEL_MINIMAL)
276                                                         ereport(FATAL,
277                                                                         (errcode(ERRCODE_CANNOT_CONNECT_NOW),
278                                                                          errmsg("standby connections not allowed because wal_level=minimal")));
279
280                                                 /* Send a CopyOutResponse message, and start streaming */
281                                                 pq_beginmessage(&buf, 'H');
282                                                 pq_sendbyte(&buf, 0);
283                                                 pq_sendint(&buf, 0, 2);
284                                                 pq_endmessage(&buf);
285                                                 pq_flush();
286
287                                                 /*
288                                                  * Initialize position to the received one, then the
289                                                  * xlog records begin to be shipped from that position
290                                                  */
291                                                 sentPtr = recptr;
292
293                                                 /* break out of the loop */
294                                                 replication_started = true;
295                                         }
296                                         else
297                                         {
298                                                 ereport(FATAL,
299                                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
300                                                                  errmsg("invalid standby query string: %s", query_string)));
301                                         }
302                                         break;
303                                 }
304
305                         case 'X':
306                                 /* standby is closing the connection */
307                                 proc_exit(0);
308
309                         case EOF:
310                                 /* standby disconnected unexpectedly */
311                                 ereport(COMMERROR,
312                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
313                                                  errmsg("unexpected EOF on standby connection")));
314                                 proc_exit(0);
315
316                         default:
317                                 ereport(FATAL,
318                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
319                                                  errmsg("invalid standby handshake message type %d", firstchar)));
320                 }
321         }
322 }
323
324 /*
325  * Check if the remote end has closed the connection.
326  */
327 static void
328 CheckClosedConnection(void)
329 {
330         unsigned char firstchar;
331         int                     r;
332
333         r = pq_getbyte_if_available(&firstchar);
334         if (r < 0)
335         {
336                 /* unexpected error or EOF */
337                 ereport(COMMERROR,
338                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
339                                  errmsg("unexpected EOF on standby connection")));
340                 proc_exit(0);
341         }
342         if (r == 0)
343         {
344                 /* no data available without blocking */
345                 return;
346         }
347
348         /* Handle the very limited subset of commands expected in this phase */
349         switch (firstchar)
350         {
351                         /*
352                          * 'X' means that the standby is closing down the socket.
353                          */
354                 case 'X':
355                         proc_exit(0);
356
357                 default:
358                         ereport(FATAL,
359                                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
360                                          errmsg("invalid standby closing message type %d",
361                                                         firstchar)));
362         }
363 }
364
365 /* Main loop of walsender process */
366 static int
367 WalSndLoop(void)
368 {
369         char       *output_message;
370         bool            caughtup = false;
371
372         /*
373          * Allocate buffer that will be used for each output message.  We do this
374          * just once to reduce palloc overhead.  The buffer must be made large
375          * enough for maximum-sized messages.
376          */
377         output_message = palloc(1 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE);
378
379         /* Loop forever, unless we get an error */
380         for (;;)
381         {
382                 long            remain;         /* remaining time (us) */
383
384                 /*
385                  * Emergency bailout if postmaster has died.  This is to avoid the
386                  * necessity for manual cleanup of all postmaster children.
387                  */
388                 if (!PostmasterIsAlive(true))
389                         exit(1);
390
391                 /* Process any requests or signals received recently */
392                 if (got_SIGHUP)
393                 {
394                         got_SIGHUP = false;
395                         ProcessConfigFile(PGC_SIGHUP);
396                 }
397
398                 /*
399                  * When SIGUSR2 arrives, we send all outstanding logs up to the
400                  * shutdown checkpoint record (i.e., the latest record) and exit.
401                  */
402                 if (ready_to_stop)
403                 {
404                         if (!XLogSend(output_message, &caughtup))
405                                 break;
406                         if (caughtup)
407                                 shutdown_requested = true;
408                 }
409
410                 /* Normal exit from the walsender is here */
411                 if (shutdown_requested)
412                 {
413                         /* Inform the standby that XLOG streaming was done */
414                         pq_puttextmessage('C', "COPY 0");
415                         pq_flush();
416
417                         proc_exit(0);
418                 }
419
420                 /*
421                  * If we had sent all accumulated WAL in last round, nap for the
422                  * configured time before retrying.
423                  *
424                  * On some platforms, signals won't interrupt the sleep.  To ensure we
425                  * respond reasonably promptly when someone signals us, break down the
426                  * sleep into NAPTIME_PER_CYCLE increments, and check for interrupts
427                  * after each nap.
428                  */
429                 if (caughtup)
430                 {
431                         remain = WalSndDelay * 1000L;
432                         while (remain > 0)
433                         {
434                                 /* Check for interrupts */
435                                 if (got_SIGHUP || shutdown_requested || ready_to_stop)
436                                         break;
437
438                                 /* Sleep and check that the connection is still alive */
439                                 pg_usleep(remain > NAPTIME_PER_CYCLE ? NAPTIME_PER_CYCLE : remain);
440                                 CheckClosedConnection();
441
442                                 remain -= NAPTIME_PER_CYCLE;
443                         }
444                 }
445
446                 /* Attempt to send the log once every loop */
447                 if (!XLogSend(output_message, &caughtup))
448                         break;
449         }
450
451         /*
452          * Get here on send failure.  Clean up and exit.
453          *
454          * Reset whereToSendOutput to prevent ereport from attempting to send any
455          * more messages to the standby.
456          */
457         if (whereToSendOutput == DestRemote)
458                 whereToSendOutput = DestNone;
459
460         proc_exit(0);
461         return 1;                                       /* keep the compiler quiet */
462 }
463
464 /* Initialize a per-walsender data structure for this walsender process */
465 static void
466 InitWalSnd(void)
467 {
468         int                     i;
469
470         /*
471          * WalSndCtl should be set up already (we inherit this by fork() or
472          * EXEC_BACKEND mechanism from the postmaster).
473          */
474         Assert(WalSndCtl != NULL);
475         Assert(MyWalSnd == NULL);
476
477         /*
478          * Find a free walsender slot and reserve it. If this fails, we must be
479          * out of WalSnd structures.
480          */
481         for (i = 0; i < max_wal_senders; i++)
482         {
483                 /* use volatile pointer to prevent code rearrangement */
484                 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
485
486                 SpinLockAcquire(&walsnd->mutex);
487
488                 if (walsnd->pid != 0)
489                 {
490                         SpinLockRelease(&walsnd->mutex);
491                         continue;
492                 }
493                 else
494                 {
495                         /* found */
496                         MyWalSnd = (WalSnd *) walsnd;
497                         walsnd->pid = MyProcPid;
498                         MemSet(&MyWalSnd->sentPtr, 0, sizeof(XLogRecPtr));
499                         SpinLockRelease(&walsnd->mutex);
500                         break;
501                 }
502         }
503         if (MyWalSnd == NULL)
504                 ereport(FATAL,
505                                 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
506                                  errmsg("number of requested standby connections "
507                                                 "exceeds max_wal_senders (currently %d)",
508                                                 max_wal_senders)));
509
510         /* Arrange to clean up at walsender exit */
511         on_shmem_exit(WalSndKill, 0);
512 }
513
514 /* Destroy the per-walsender data structure for this walsender process */
515 static void
516 WalSndKill(int code, Datum arg)
517 {
518         Assert(MyWalSnd != NULL);
519
520         /*
521          * Mark WalSnd struct no longer in use. Assume that no lock is required
522          * for this.
523          */
524         MyWalSnd->pid = 0;
525
526         /* WalSnd struct isn't mine anymore */
527         MyWalSnd = NULL;
528 }
529
530 /*
531  * Read 'nbytes' bytes from WAL into 'buf', starting at location 'recptr'
532  *
533  * XXX probably this should be improved to suck data directly from the
534  * WAL buffers when possible.
535  */
536 static void
537 XLogRead(char *buf, XLogRecPtr recptr, Size nbytes)
538 {
539         XLogRecPtr      startRecPtr = recptr;
540         char            path[MAXPGPATH];
541         uint32          lastRemovedLog;
542         uint32          lastRemovedSeg;
543         uint32          log;
544         uint32          seg;
545
546         while (nbytes > 0)
547         {
548                 uint32          startoff;
549                 int                     segbytes;
550                 int                     readbytes;
551
552                 startoff = recptr.xrecoff % XLogSegSize;
553
554                 if (sendFile < 0 || !XLByteInSeg(recptr, sendId, sendSeg))
555                 {
556                         /* Switch to another logfile segment */
557                         if (sendFile >= 0)
558                                 close(sendFile);
559
560                         XLByteToSeg(recptr, sendId, sendSeg);
561                         XLogFilePath(path, ThisTimeLineID, sendId, sendSeg);
562
563                         sendFile = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
564                         if (sendFile < 0)
565                         {
566                                 /*
567                                  * If the file is not found, assume it's because the standby
568                                  * asked for a too old WAL segment that has already been
569                                  * removed or recycled.
570                                  */
571                                 if (errno == ENOENT)
572                                 {
573                                         char            filename[MAXFNAMELEN];
574
575                                         XLogFileName(filename, ThisTimeLineID, sendId, sendSeg);
576                                         ereport(ERROR,
577                                                         (errcode_for_file_access(),
578                                                          errmsg("requested WAL segment %s has already been removed",
579                                                                         filename)));
580                                 }
581                                 else
582                                         ereport(ERROR,
583                                                         (errcode_for_file_access(),
584                                                          errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
585                                                                         path, sendId, sendSeg)));
586                         }
587                         sendOff = 0;
588                 }
589
590                 /* Need to seek in the file? */
591                 if (sendOff != startoff)
592                 {
593                         if (lseek(sendFile, (off_t) startoff, SEEK_SET) < 0)
594                                 ereport(ERROR,
595                                                 (errcode_for_file_access(),
596                                                  errmsg("could not seek in log file %u, segment %u to offset %u: %m",
597                                                                 sendId, sendSeg, startoff)));
598                         sendOff = startoff;
599                 }
600
601                 /* How many bytes are within this segment? */
602                 if (nbytes > (XLogSegSize - startoff))
603                         segbytes = XLogSegSize - startoff;
604                 else
605                         segbytes = nbytes;
606
607                 readbytes = read(sendFile, buf, segbytes);
608                 if (readbytes <= 0)
609                         ereport(ERROR,
610                                         (errcode_for_file_access(),
611                         errmsg("could not read from log file %u, segment %u, offset %u, "
612                                    "length %lu: %m",
613                                    sendId, sendSeg, sendOff, (unsigned long) segbytes)));
614
615                 /* Update state for read */
616                 XLByteAdvance(recptr, readbytes);
617
618                 sendOff += readbytes;
619                 nbytes -= readbytes;
620                 buf += readbytes;
621         }
622
623         /*
624          * After reading into the buffer, check that what we read was valid. We do
625          * this after reading, because even though the segment was present when we
626          * opened it, it might get recycled or removed while we read it. The
627          * read() succeeds in that case, but the data we tried to read might
628          * already have been overwritten with new WAL records.
629          */
630         XLogGetLastRemoved(&lastRemovedLog, &lastRemovedSeg);
631         XLByteToSeg(startRecPtr, log, seg);
632         if (log < lastRemovedLog ||
633                 (log == lastRemovedLog && seg <= lastRemovedSeg))
634         {
635                 char            filename[MAXFNAMELEN];
636
637                 XLogFileName(filename, ThisTimeLineID, log, seg);
638                 ereport(ERROR,
639                                 (errcode_for_file_access(),
640                                  errmsg("requested WAL segment %s has already been removed",
641                                                 filename)));
642         }
643 }
644
645 /*
646  * Read up to MAX_SEND_SIZE bytes of WAL that's been flushed to disk,
647  * but not yet sent to the client, and send it.
648  *
649  * msgbuf is a work area in which the output message is constructed.  It's
650  * passed in just so we can avoid re-palloc'ing the buffer on each cycle.
651  * It must be of size 1 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE.
652  *
653  * If there is no unsent WAL remaining, *caughtup is set to true, otherwise
654  * *caughtup is set to false.
655  *
656  * Returns true if OK, false if trouble.
657  */
658 static bool
659 XLogSend(char *msgbuf, bool *caughtup)
660 {
661         XLogRecPtr      SendRqstPtr;
662         XLogRecPtr      startptr;
663         XLogRecPtr      endptr;
664         Size            nbytes;
665         WalDataMessageHeader msghdr;
666
667         /*
668          * Attempt to send all data that's already been written out and fsync'd to
669          * disk.  We cannot go further than what's been written out given the
670          * current implementation of XLogRead().  And in any case it's unsafe to
671          * send WAL that is not securely down to disk on the master: if the master
672          * subsequently crashes and restarts, slaves must not have applied any WAL
673          * that gets lost on the master.
674          */
675         SendRqstPtr = GetFlushRecPtr();
676
677         /* Quick exit if nothing to do */
678         if (XLByteLE(SendRqstPtr, sentPtr))
679         {
680                 *caughtup = true;
681                 return true;
682         }
683
684         /*
685          * Figure out how much to send in one message. If there's no more than
686          * MAX_SEND_SIZE bytes to send, send everything. Otherwise send
687          * MAX_SEND_SIZE bytes, but round back to logfile or page boundary.
688          *
689          * The rounding is not only for performance reasons. Walreceiver relies on
690          * the fact that we never split a WAL record across two messages. Since a
691          * long WAL record is split at page boundary into continuation records,
692          * page boundary is always a safe cut-off point. We also assume that
693          * SendRqstPtr never points to the middle of a WAL record.
694          */
695         startptr = sentPtr;
696         if (startptr.xrecoff >= XLogFileSize)
697         {
698                 /*
699                  * crossing a logid boundary, skip the non-existent last log segment
700                  * in previous logical log file.
701                  */
702                 startptr.xlogid += 1;
703                 startptr.xrecoff = 0;
704         }
705
706         endptr = startptr;
707         XLByteAdvance(endptr, MAX_SEND_SIZE);
708         if (endptr.xlogid != startptr.xlogid)
709         {
710                 /* Don't cross a logfile boundary within one message */
711                 Assert(endptr.xlogid == startptr.xlogid + 1);
712                 endptr.xlogid = startptr.xlogid;
713                 endptr.xrecoff = XLogFileSize;
714         }
715
716         /* if we went beyond SendRqstPtr, back off */
717         if (XLByteLE(SendRqstPtr, endptr))
718         {
719                 endptr = SendRqstPtr;
720                 *caughtup = true;
721         }
722         else
723         {
724                 /* round down to page boundary. */
725                 endptr.xrecoff -= (endptr.xrecoff % XLOG_BLCKSZ);
726                 *caughtup = false;
727         }
728
729         nbytes = endptr.xrecoff - startptr.xrecoff;
730         Assert(nbytes <= MAX_SEND_SIZE);
731
732         /*
733          * OK to read and send the slice.
734          */
735         msgbuf[0] = 'w';
736
737         /*
738          * Read the log directly into the output buffer to avoid extra memcpy
739          * calls.
740          */
741         XLogRead(msgbuf + 1 + sizeof(WalDataMessageHeader), startptr, nbytes);
742
743         /*
744          * We fill the message header last so that the send timestamp is taken as
745          * late as possible.
746          */
747         msghdr.dataStart = startptr;
748         msghdr.walEnd = SendRqstPtr;
749         msghdr.sendTime = GetCurrentTimestamp();
750
751         memcpy(msgbuf + 1, &msghdr, sizeof(WalDataMessageHeader));
752
753         pq_putmessage('d', msgbuf, 1 + sizeof(WalDataMessageHeader) + nbytes);
754
755         /* Flush pending output to the client */
756         if (pq_flush())
757                 return false;
758
759         sentPtr = endptr;
760
761         /* Update shared memory status */
762         {
763                 /* use volatile pointer to prevent code rearrangement */
764                 volatile WalSnd *walsnd = MyWalSnd;
765
766                 SpinLockAcquire(&walsnd->mutex);
767                 walsnd->sentPtr = sentPtr;
768                 SpinLockRelease(&walsnd->mutex);
769         }
770
771         /* Report progress of XLOG streaming in PS display */
772         if (update_process_title)
773         {
774                 char            activitymsg[50];
775
776                 snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%X",
777                                  sentPtr.xlogid, sentPtr.xrecoff);
778                 set_ps_display(activitymsg, false);
779         }
780
781         return true;
782 }
783
784 /* SIGHUP: set flag to re-read config file at next convenient time */
785 static void
786 WalSndSigHupHandler(SIGNAL_ARGS)
787 {
788         got_SIGHUP = true;
789 }
790
791 /* SIGTERM: set flag to shut down */
792 static void
793 WalSndShutdownHandler(SIGNAL_ARGS)
794 {
795         shutdown_requested = true;
796 }
797
798 /*
799  * WalSndQuickDieHandler() occurs when signalled SIGQUIT by the postmaster.
800  *
801  * Some backend has bought the farm,
802  * so we need to stop what we're doing and exit.
803  */
804 static void
805 WalSndQuickDieHandler(SIGNAL_ARGS)
806 {
807         PG_SETMASK(&BlockSig);
808
809         /*
810          * We DO NOT want to run proc_exit() callbacks -- we're here because
811          * shared memory may be corrupted, so we don't want to try to clean up our
812          * transaction.  Just nail the windows shut and get out of town.  Now that
813          * there's an atexit callback to prevent third-party code from breaking
814          * things by calling exit() directly, we have to reset the callbacks
815          * explicitly to make this work as intended.
816          */
817         on_exit_reset();
818
819         /*
820          * Note we do exit(2) not exit(0).      This is to force the postmaster into a
821          * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
822          * backend.  This is necessary precisely because we don't clean up our
823          * shared memory state.  (The "dead man switch" mechanism in pmsignal.c
824          * should ensure the postmaster sees this as a crash, too, but no harm in
825          * being doubly sure.)
826          */
827         exit(2);
828 }
829
830 /* SIGUSR2: set flag to do a last cycle and shut down afterwards */
831 static void
832 WalSndLastCycleHandler(SIGNAL_ARGS)
833 {
834         ready_to_stop = true;
835 }
836
837 /* Set up signal handlers */
838 void
839 WalSndSignals(void)
840 {
841         /* Set up signal handlers */
842         pqsignal(SIGHUP, WalSndSigHupHandler);          /* set flag to read config
843                                                                                                  * file */
844         pqsignal(SIGINT, SIG_IGN);      /* not used */
845         pqsignal(SIGTERM, WalSndShutdownHandler);       /* request shutdown */
846         pqsignal(SIGQUIT, WalSndQuickDieHandler);       /* hard crash time */
847         pqsignal(SIGALRM, SIG_IGN);
848         pqsignal(SIGPIPE, SIG_IGN);
849         pqsignal(SIGUSR1, SIG_IGN); /* not used */
850         pqsignal(SIGUSR2, WalSndLastCycleHandler);      /* request a last cycle and
851                                                                                                  * shutdown */
852
853         /* Reset some signals that are accepted by postmaster but not here */
854         pqsignal(SIGCHLD, SIG_DFL);
855         pqsignal(SIGTTIN, SIG_DFL);
856         pqsignal(SIGTTOU, SIG_DFL);
857         pqsignal(SIGCONT, SIG_DFL);
858         pqsignal(SIGWINCH, SIG_DFL);
859 }
860
861 /* Report shared-memory space needed by WalSndShmemInit */
862 Size
863 WalSndShmemSize(void)
864 {
865         Size            size = 0;
866
867         size = offsetof(WalSndCtlData, walsnds);
868         size = add_size(size, mul_size(max_wal_senders, sizeof(WalSnd)));
869
870         return size;
871 }
872
873 /* Allocate and initialize walsender-related shared memory */
874 void
875 WalSndShmemInit(void)
876 {
877         bool            found;
878         int                     i;
879
880         WalSndCtl = (WalSndCtlData *)
881                 ShmemInitStruct("Wal Sender Ctl", WalSndShmemSize(), &found);
882
883         if (!found)
884         {
885                 /* First time through, so initialize */
886                 MemSet(WalSndCtl, 0, WalSndShmemSize());
887
888                 for (i = 0; i < max_wal_senders; i++)
889                 {
890                         WalSnd     *walsnd = &WalSndCtl->walsnds[i];
891
892                         SpinLockInit(&walsnd->mutex);
893                 }
894         }
895 }
896
897 /*
898  * This isn't currently used for anything. Monitoring tools might be
899  * interested in the future, and we'll need something like this in the
900  * future for synchronous replication.
901  */
902 #ifdef NOT_USED
903 /*
904  * Returns the oldest Send position among walsenders. Or InvalidXLogRecPtr
905  * if none.
906  */
907 XLogRecPtr
908 GetOldestWALSendPointer(void)
909 {
910         XLogRecPtr      oldest = {0, 0};
911         int                     i;
912         bool            found = false;
913
914         for (i = 0; i < max_wal_senders; i++)
915         {
916                 /* use volatile pointer to prevent code rearrangement */
917                 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
918                 XLogRecPtr      recptr;
919
920                 if (walsnd->pid == 0)
921                         continue;
922
923                 SpinLockAcquire(&walsnd->mutex);
924                 recptr = walsnd->sentPtr;
925                 SpinLockRelease(&walsnd->mutex);
926
927                 if (recptr.xlogid == 0 && recptr.xrecoff == 0)
928                         continue;
929
930                 if (!found || XLByteLT(recptr, oldest))
931                         oldest = recptr;
932                 found = true;
933         }
934         return oldest;
935 }
936
937 #endif