OSDN Git Service

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