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