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