OSDN Git Service

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