OSDN Git Service

Introduce replication timeout for asynchronous and synchronous replication.
[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 "storage/proc.h"
52 #include "tcop/tcopprot.h"
53 #include "utils/guc.h"
54 #include "utils/memutils.h"
55 #include "utils/ps_status.h"
56
57
58 /* Array of WalSnds in shared memory */
59 WalSndCtlData *WalSndCtl = NULL;
60
61 /* My slot in the shared memory array */
62 static WalSnd *MyWalSnd = NULL;
63
64 /* Array of WalSndWaiter in shared memory */
65 static WalSndWaiter  *WalSndWaiters;
66
67 /* Global state */
68 bool            am_walsender = false;           /* Am I a walsender process ? */
69
70 /* User-settable parameters for walsender */
71 int                     max_wal_senders = 0;    /* the maximum number of concurrent walsenders */
72 int                     WalSndDelay = 200;      /* max sleep time between some actions */
73 int                     replication_timeout = 0;        /* maximum time to wait for the Ack from the standby */
74
75 /*
76  * Buffer for WAL sending
77  *
78  * WalSndOutBuffer is a work area in which the output message is constructed.
79  * It's used in just so we can avoid re-palloc'ing the buffer on each cycle.
80  * It must be of size 6 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE.
81  */
82 static char        *WalSndOutBuffer;
83 static int              WalSndOutHead;          /* head of pending output */
84 static int              WalSndOutTail;          /* tail of pending output */
85
86 /*
87  * These variables are used similarly to openLogFile/Id/Seg/Off,
88  * but for walsender to read the XLOG.
89  */
90 static int      sendFile = -1;
91 static uint32 sendId = 0;
92 static uint32 sendSeg = 0;
93 static uint32 sendOff = 0;
94
95 /*
96  * How far have we sent WAL already? This is also advertised in
97  * MyWalSnd->sentPtr.  (Actually, this is the next WAL location to send.)
98  */
99 static XLogRecPtr sentPtr = {0, 0};
100
101 /*
102  * How far have we completed replication already? This is also
103  * advertised in MyWalSnd->ackdPtr. This is not used in asynchronous
104  * replication case.
105  */
106 static XLogRecPtr ackdPtr = {0, 0};
107
108 /* Replication mode requested by connected standby */
109 static int      rplMode = REPLICATION_MODE_ASYNC;
110
111 /* Flags set by signal handlers for later service in main loop */
112 static volatile sig_atomic_t got_SIGHUP = false;
113 static volatile sig_atomic_t shutdown_requested = false;
114 static volatile sig_atomic_t ready_to_stop = false;
115
116 /* Flag set by signal handler of backends for replication */
117 static volatile sig_atomic_t replication_done = false;
118
119 /* Signal handlers */
120 static void WalSndSigHupHandler(SIGNAL_ARGS);
121 static void WalSndShutdownHandler(SIGNAL_ARGS);
122 static void WalSndQuickDieHandler(SIGNAL_ARGS);
123 static void WalSndXLogSendHandler(SIGNAL_ARGS);
124 static void WalSndLastCycleHandler(SIGNAL_ARGS);
125
126 /* Prototypes for private functions */
127 static int      WalSndLoop(void);
128 static void InitWalSnd(void);
129 static void WalSndHandshake(void);
130 static void WalSndKill(int code, Datum arg);
131 static void XLogRead(char *buf, XLogRecPtr recptr, Size nbytes);
132 static bool XLogSend(bool *caughtup, bool *pending);
133 static void ProcessStreamMsgs(StringInfo inMsg);
134
135 static void RegisterWalSndWaiter(BackendId backendId, XLogRecPtr record,
136                                                                  Latch *latch);
137 static void WakeupWalSndWaiters(XLogRecPtr record);
138 static XLogRecPtr GetOldestAckdPtr(void);
139
140
141 /* Main entry point for walsender process */
142 int
143 WalSenderMain(void)
144 {
145         MemoryContext walsnd_context;
146
147         if (RecoveryInProgress())
148                 ereport(FATAL,
149                                 (errcode(ERRCODE_CANNOT_CONNECT_NOW),
150                                  errmsg("recovery is still in progress, can't accept WAL streaming connections")));
151
152         /* Create a per-walsender data structure in shared memory */
153         InitWalSnd();
154
155         /*
156          * Create a memory context that we will do all our work in.  We do this so
157          * that we can reset the context during error recovery and thereby avoid
158          * possible memory leaks.  Formerly this code just ran in
159          * TopMemoryContext, but resetting that would be a really bad idea.
160          *
161          * XXX: we don't actually attempt error recovery in walsender, we just
162          * close the connection and exit.
163          */
164         walsnd_context = AllocSetContextCreate(TopMemoryContext,
165                                                                                    "Wal Sender",
166                                                                                    ALLOCSET_DEFAULT_MINSIZE,
167                                                                                    ALLOCSET_DEFAULT_INITSIZE,
168                                                                                    ALLOCSET_DEFAULT_MAXSIZE);
169         MemoryContextSwitchTo(walsnd_context);
170
171         /* Unblock signals (they were blocked when the postmaster forked us) */
172         PG_SETMASK(&UnBlockSig);
173
174         /* Tell the standby that walsender is ready for receiving commands */
175         ReadyForQuery(DestRemote);
176
177         /* Handle handshake messages before streaming */
178         WalSndHandshake();
179
180         /* Initialize shared memory status */
181         {
182                 /* use volatile pointer to prevent code rearrangement */
183                 volatile WalSnd *walsnd = MyWalSnd;
184
185                 SpinLockAcquire(&walsnd->mutex);
186                 walsnd->sentPtr = sentPtr;
187                 SpinLockRelease(&walsnd->mutex);
188         }
189
190         /* Main loop of walsender */
191         return WalSndLoop();
192 }
193
194 /*
195  * Execute commands from walreceiver, until we enter streaming mode.
196  */
197 static void
198 WalSndHandshake(void)
199 {
200         StringInfoData input_message;
201         bool            replication_started = false;
202
203         initStringInfo(&input_message);
204
205         while (!replication_started)
206         {
207                 int                     firstchar;
208
209                 /* Wait for a command to arrive */
210                 firstchar = pq_getbyte();
211
212                 /*
213                  * Emergency bailout if postmaster has died.  This is to avoid the
214                  * necessity for manual cleanup of all postmaster children.
215                  */
216                 if (!PostmasterIsAlive(true))
217                         exit(1);
218
219                 /*
220                  * Check for any other interesting events that happened while we
221                  * slept.
222                  */
223                 if (got_SIGHUP)
224                 {
225                         got_SIGHUP = false;
226                         ProcessConfigFile(PGC_SIGHUP);
227                 }
228
229                 if (firstchar != EOF)
230                 {
231                         /*
232                          * Read the message contents. This is expected to be done without
233                          * blocking because we've been able to get message type code.
234                          */
235                         if (pq_getmessage(&input_message, 0))
236                                 firstchar = EOF;        /* suitable message already logged */
237                 }
238
239                 /* Handle the very limited subset of commands expected in this phase */
240                 switch (firstchar)
241                 {
242                         char            rplModeStr[6];
243
244                         case 'Q':                       /* Query message */
245                                 {
246                                         const char *query_string;
247                                         XLogRecPtr      recptr;
248
249                                         query_string = pq_getmsgstring(&input_message);
250                                         pq_getmsgend(&input_message);
251
252                                         if (strcmp(query_string, "IDENTIFY_SYSTEM") == 0)
253                                         {
254                                                 StringInfoData buf;
255                                                 char            sysid[32];
256                                                 char            tli[11];
257
258                                                 /*
259                                                  * Reply with a result set with one row, two columns.
260                                                  * First col is system ID, and second is timeline ID
261                                                  */
262
263                                                 snprintf(sysid, sizeof(sysid), UINT64_FORMAT,
264                                                                  GetSystemIdentifier());
265                                                 snprintf(tli, sizeof(tli), "%u", ThisTimeLineID);
266
267                                                 /* Send a RowDescription message */
268                                                 pq_beginmessage(&buf, 'T');
269                                                 pq_sendint(&buf, 2, 2); /* 2 fields */
270
271                                                 /* first field */
272                                                 pq_sendstring(&buf, "systemid");                /* col name */
273                                                 pq_sendint(&buf, 0, 4); /* table oid */
274                                                 pq_sendint(&buf, 0, 2); /* attnum */
275                                                 pq_sendint(&buf, TEXTOID, 4);   /* type oid */
276                                                 pq_sendint(&buf, -1, 2);                /* typlen */
277                                                 pq_sendint(&buf, 0, 4); /* typmod */
278                                                 pq_sendint(&buf, 0, 2); /* format code */
279
280                                                 /* second field */
281                                                 pq_sendstring(&buf, "timeline");                /* col name */
282                                                 pq_sendint(&buf, 0, 4); /* table oid */
283                                                 pq_sendint(&buf, 0, 2); /* attnum */
284                                                 pq_sendint(&buf, INT4OID, 4);   /* type oid */
285                                                 pq_sendint(&buf, 4, 2); /* typlen */
286                                                 pq_sendint(&buf, 0, 4); /* typmod */
287                                                 pq_sendint(&buf, 0, 2); /* format code */
288                                                 pq_endmessage(&buf);
289
290                                                 /* Send a DataRow message */
291                                                 pq_beginmessage(&buf, 'D');
292                                                 pq_sendint(&buf, 2, 2); /* # of columns */
293                                                 pq_sendint(&buf, strlen(sysid), 4);             /* col1 len */
294                                                 pq_sendbytes(&buf, (char *) &sysid, strlen(sysid));
295                                                 pq_sendint(&buf, strlen(tli), 4);               /* col2 len */
296                                                 pq_sendbytes(&buf, (char *) tli, strlen(tli));
297                                                 pq_endmessage(&buf);
298
299                                                 /* Send CommandComplete and ReadyForQuery messages */
300                                                 EndCommand("SELECT", DestRemote);
301                                                 ReadyForQuery(DestRemote);
302                                                 /* ReadyForQuery did pq_flush for us */
303                                         }
304                                         else if (sscanf(query_string, "START_REPLICATION %X/%X MODE %5s",
305                                                                         &recptr.xlogid, &recptr.xrecoff, rplModeStr) == 3)
306                                         {
307                                                 StringInfoData buf;
308
309                                                 /*
310                                                  * Check that we're logging enough information in the
311                                                  * WAL for log-shipping.
312                                                  *
313                                                  * NOTE: This only checks the current value of
314                                                  * wal_level. Even if the current setting is not
315                                                  * 'minimal', there can be old WAL in the pg_xlog
316                                                  * directory that was created with 'minimal'. So this
317                                                  * is not bulletproof, the purpose is just to give a
318                                                  * user-friendly error message that hints how to
319                                                  * configure the system correctly.
320                                                  */
321                                                 if (wal_level == WAL_LEVEL_MINIMAL)
322                                                         ereport(FATAL,
323                                                                         (errcode(ERRCODE_CANNOT_CONNECT_NOW),
324                                                                          errmsg("standby connections not allowed because wal_level=minimal")));
325
326                                                 /* Verify that the specified replication mode is valid */
327                                                 {
328                                                         const struct config_enum_entry *entry;
329
330                                                         for (entry = replication_mode_options; entry && entry->name; entry++)
331                                                         {
332                                                                 if (strcmp(rplModeStr, entry->name) == 0)
333                                                                 {
334                                                                         rplMode = entry->val;
335                                                                         break;
336                                                                 }
337                                                         }
338                                                         if (entry == NULL || entry->name == NULL)
339                                                                 ereport(FATAL,
340                                                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
341                                                                                  errmsg("invalid replication mode: %s", rplModeStr)));
342                                                 }
343                                                 MyWalSnd->rplMode = rplMode;
344
345                                                 /* Send a CopyXLogResponse message, and start streaming */
346                                                 pq_beginmessage(&buf, 'W');
347                                                 pq_endmessage(&buf);
348                                                 pq_flush();
349
350                                                 /*
351                                                  * Initialize positions to the received one, then the
352                                                  * xlog records begin to be shipped from that position
353                                                  */
354                                                 sentPtr = ackdPtr = recptr;
355
356                                                 /* break out of the loop */
357                                                 replication_started = true;
358                                         }
359                                         else
360                                         {
361                                                 ereport(FATAL,
362                                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
363                                                                  errmsg("invalid standby query string: %s", query_string)));
364                                         }
365                                         break;
366                                 }
367
368                         case 'X':
369                                 /* standby is closing the connection */
370                                 proc_exit(0);
371
372                         case EOF:
373                                 /* standby disconnected unexpectedly */
374                                 ereport(COMMERROR,
375                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
376                                                  errmsg("unexpected EOF on standby connection")));
377                                 proc_exit(0);
378
379                         default:
380                                 ereport(FATAL,
381                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
382                                                  errmsg("invalid standby handshake message type %d", firstchar)));
383                 }
384         }
385 }
386
387 /*
388  * Process messages received from the standby.
389  *
390  * ereports on error.
391  */
392 static void
393 ProcessStreamMsgs(StringInfo inMsg)
394 {
395         bool    acked = false;
396
397         /* Loop to process successive complete messages available */
398         for (;;)
399         {
400                 unsigned char firstchar;
401                 int                     r;
402
403                 r = pq_getbyte_if_available(&firstchar);
404                 if (r < 0)
405                 {
406                         /* unexpected error or EOF */
407                         ereport(COMMERROR,
408                                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
409                                          errmsg("unexpected EOF on standby connection")));
410                         proc_exit(0);
411                 }
412                 if (r == 0)
413                 {
414                         /* no data available without blocking */
415                         break;
416                 }
417
418                 /* Handle the very limited subset of commands expected in this phase */
419                 switch (firstchar)
420                 {
421                         case 'd':       /* CopyData message */
422                         {
423                                 unsigned char   rpltype;
424
425                                 /*
426                                  * Read the message contents. This is expected to be done without
427                                  * blocking because we've been able to get message type code.
428                                  */
429                                 if (pq_getmessage(inMsg, 0))
430                                         proc_exit(0);           /* suitable message already logged */
431
432                                 /* Read the replication message type from CopyData message */
433                                 rpltype = pq_getmsgbyte(inMsg);
434                                 switch (rpltype)
435                                 {
436                                         case 'l':
437                                         {
438                                                 WalAckMessageData  *msgdata;
439
440                                                 msgdata = (WalAckMessageData *) pq_getmsgbytes(inMsg, sizeof(WalAckMessageData));
441
442                                                 /*
443                                                  * Update local status.
444                                                  *
445                                                  * The ackd ptr received from standby should not
446                                                  * go backwards.
447                                                  */
448                                                 if (XLByteLE(ackdPtr, msgdata->ackEnd))
449                                                         ackdPtr = msgdata->ackEnd;
450                                                 else
451                                                         ereport(FATAL,
452                                                                         (errmsg("replication completion location went back from "
453                                                                                         "%X/%X to %X/%X",
454                                                                                         ackdPtr.xlogid, ackdPtr.xrecoff,
455                                                                                         msgdata->ackEnd.xlogid, msgdata->ackEnd.xrecoff)));
456
457                                                 acked = true;   /* also need to update shared position */
458                                                 break;
459                                         }
460                                         default:
461                                                 ereport(FATAL,
462                                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
463                                                                  errmsg("invalid replication message type %d",
464                                                                                 rpltype)));
465                                 }
466                                 break;
467                         }
468
469                         /*
470                          * 'X' means that the standby is closing down the socket.
471                          */
472                         case 'X':
473                                 proc_exit(0);
474
475                         default:
476                                 ereport(FATAL,
477                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
478                                                  errmsg("invalid standby closing message type %d",
479                                                                 firstchar)));
480                 }
481         }
482
483         if (acked)
484         {
485                 /* use volatile pointer to prevent code rearrangement */
486                 volatile WalSnd *walsnd = MyWalSnd;
487
488                 SpinLockAcquire(&walsnd->mutex);
489                 walsnd->ackdPtr = ackdPtr;
490                 SpinLockRelease(&walsnd->mutex);
491         }
492
493         /* Wake up the backends that this walsender had been blocking */
494         WakeupWalSndWaiters(ackdPtr);
495 }
496
497 /* Main loop of walsender process */
498 static int
499 WalSndLoop(void)
500 {
501         StringInfoData  input_message;
502         bool            caughtup = false;
503         bool            pending = false;
504
505         initStringInfo(&input_message);
506
507         /*
508          * Allocate buffer that will be used for each output message.  We do this
509          * just once to reduce palloc overhead.  The buffer must be made large
510          * enough for maximum-sized messages.
511          */
512         WalSndOutBuffer = palloc(6 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE);
513         WalSndOutHead = WalSndOutTail = 0;
514
515         /* Loop forever, unless we get an error */
516         for (;;)
517         {
518                 /*
519                  * Emergency bailout if postmaster has died.  This is to avoid the
520                  * necessity for manual cleanup of all postmaster children.
521                  */
522                 if (!PostmasterIsAlive(true))
523                         exit(1);
524
525                 /* Process any requests or signals received recently */
526                 if (got_SIGHUP)
527                 {
528                         got_SIGHUP = false;
529                         ProcessConfigFile(PGC_SIGHUP);
530                 }
531
532                 /*
533                  * When SIGUSR2 arrives, we send all outstanding logs up to the
534                  * shutdown checkpoint record (i.e., the latest record) and exit.
535                  */
536                 if (ready_to_stop)
537                 {
538                         if (!XLogSend(&caughtup, &pending))
539                                 break;
540                         if (caughtup && !pending)
541                                 shutdown_requested = true;
542                 }
543
544                 /* Normal exit from the walsender is here */
545                 if (shutdown_requested)
546                 {
547                         /* Inform the standby that XLOG streaming was done */
548                         pq_puttextmessage('C', "COPY 0");
549                         pq_flush();
550
551                         proc_exit(0);
552                 }
553
554                 /*
555                  * If we had sent all accumulated WAL in last round or could not
556                  * flush pending WAL in output buffer because the socket was not
557                  * writable, nap for the configured time before retrying.
558                  */
559                 if (caughtup || pending)
560                 {
561                         /*
562                          * Even if we wrote all the WAL that was available when we started
563                          * sending, more might have arrived while we were sending this
564                          * batch. We had the latch set while sending, so we have not
565                          * received any signals from that time. Let's arm the latch
566                          * again, and after that check that we're still up-to-date.
567                          */
568                         ResetLatch(&MyWalSnd->latch);
569
570                         if (!XLogSend(&caughtup, &pending))
571                                 break;
572                         if ((caughtup || pending) && !got_SIGHUP && !ready_to_stop &&
573                                 !shutdown_requested)
574                         {
575                                 bool            check_timeout;
576                                 long            sleeptime;
577                                 int                     res;
578
579                                 /*
580                                  * XXX: We don't really need the periodic wakeups anymore,
581                                  * WaitLatchOrSocket should reliably wake up as soon as
582                                  * something interesting happens.
583                                  */
584
585                                 /*
586                                  * Check for replication timeout if it's enabled and we need to
587                                  * wait for the socket to be writable to flush pending WAL in
588                                  * output buffer.
589                                  */
590                                 check_timeout = replication_timeout > 0 && pending;
591                                 if (check_timeout)
592                                         sleeptime = replication_timeout;
593                                 else
594                                         sleeptime = WalSndDelay;
595
596                                 /* Sleep */
597                                 res = WaitLatchOrSocket(&MyWalSnd->latch, MyProcPort->sock,
598                                                                                 true, (WalSndOutTail > 0),
599                                                                                 sleeptime * 1000L);
600
601                                 if (res == 0 && check_timeout)
602                                 {
603                                         /*
604                                          * Since typically expiration of replication timeout means
605                                          * communication problem, we don't send the error message
606                                          * to the standby.
607                                          */
608                                         ereport(COMMERROR,
609                                                         (errmsg("terminating walsender process due to replication timeout")));
610                                         break;
611                                 }
612                         }
613
614                         /* Process messages received from the standby */
615                         ProcessStreamMsgs(&input_message);
616                 }
617                 else
618                 {
619                         /* Attempt to send the log once every loop */
620                         if (!XLogSend(&caughtup, &pending))
621                                 break;
622                 }
623         }
624
625         /*
626          * Get here on send failure.  Clean up and exit.
627          *
628          * Reset whereToSendOutput to prevent ereport from attempting to send any
629          * more messages to the standby.
630          */
631         if (whereToSendOutput == DestRemote)
632                 whereToSendOutput = DestNone;
633
634         proc_exit(0);
635         return 1;                                       /* keep the compiler quiet */
636 }
637
638 /* Initialize a per-walsender data structure for this walsender process */
639 static void
640 InitWalSnd(void)
641 {
642         int                     i;
643
644         /*
645          * WalSndCtl should be set up already (we inherit this by fork() or
646          * EXEC_BACKEND mechanism from the postmaster).
647          */
648         Assert(WalSndCtl != NULL);
649         Assert(MyWalSnd == NULL);
650
651         /*
652          * Find a free walsender slot and reserve it. If this fails, we must be
653          * out of WalSnd structures.
654          */
655         for (i = 0; i < max_wal_senders; i++)
656         {
657                 /* use volatile pointer to prevent code rearrangement */
658                 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
659
660                 SpinLockAcquire(&walsnd->mutex);
661
662                 if (walsnd->pid != 0)
663                 {
664                         SpinLockRelease(&walsnd->mutex);
665                         continue;
666                 }
667                 else
668                 {
669                         /*
670                          * Found a free slot. Reserve it for us.
671                          */
672                         walsnd->pid = MyProcPid;
673                         MemSet(&walsnd->sentPtr, 0, sizeof(XLogRecPtr));
674                         MemSet(&walsnd->ackdPtr, 0, sizeof(XLogRecPtr));
675                         SpinLockRelease(&walsnd->mutex);
676                         /* don't need the lock anymore */
677                         OwnLatch((Latch *) &walsnd->latch);
678                         MyWalSnd = (WalSnd *) walsnd;
679
680                         break;
681                 }
682         }
683         if (MyWalSnd == NULL)
684                 ereport(FATAL,
685                                 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
686                                  errmsg("number of requested standby connections "
687                                                 "exceeds max_wal_senders (currently %d)",
688                                                 max_wal_senders)));
689
690         /* Arrange to clean up at walsender exit */
691         on_shmem_exit(WalSndKill, 0);
692 }
693
694 /* Destroy the per-walsender data structure for this walsender process */
695 static void
696 WalSndKill(int code, Datum arg)
697 {
698         Assert(MyWalSnd != NULL);
699
700         /* Wake up the backends that this walsender had been blocking */
701         MyWalSnd->rplMode = REPLICATION_MODE_ASYNC;
702         WakeupWalSndWaiters(GetOldestAckdPtr());
703
704         /*
705          * Mark WalSnd struct no longer in use. Assume that no lock is required
706          * for this.
707          */
708         MyWalSnd->pid = 0;
709         DisownLatch(&MyWalSnd->latch);
710
711         /* WalSnd struct isn't mine anymore */
712         MyWalSnd = NULL;
713 }
714
715 /*
716  * Read 'nbytes' bytes from WAL into 'buf', starting at location 'recptr'
717  *
718  * XXX probably this should be improved to suck data directly from the
719  * WAL buffers when possible.
720  */
721 static void
722 XLogRead(char *buf, XLogRecPtr recptr, Size nbytes)
723 {
724         XLogRecPtr      startRecPtr = recptr;
725         char            path[MAXPGPATH];
726         uint32          lastRemovedLog;
727         uint32          lastRemovedSeg;
728         uint32          log;
729         uint32          seg;
730
731         while (nbytes > 0)
732         {
733                 uint32          startoff;
734                 int                     segbytes;
735                 int                     readbytes;
736
737                 startoff = recptr.xrecoff % XLogSegSize;
738
739                 if (sendFile < 0 || !XLByteInSeg(recptr, sendId, sendSeg))
740                 {
741                         /* Switch to another logfile segment */
742                         if (sendFile >= 0)
743                                 close(sendFile);
744
745                         XLByteToSeg(recptr, sendId, sendSeg);
746                         XLogFilePath(path, ThisTimeLineID, sendId, sendSeg);
747
748                         sendFile = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
749                         if (sendFile < 0)
750                         {
751                                 /*
752                                  * If the file is not found, assume it's because the standby
753                                  * asked for a too old WAL segment that has already been
754                                  * removed or recycled.
755                                  */
756                                 if (errno == ENOENT)
757                                 {
758                                         char            filename[MAXFNAMELEN];
759
760                                         XLogFileName(filename, ThisTimeLineID, sendId, sendSeg);
761                                         ereport(ERROR,
762                                                         (errcode_for_file_access(),
763                                                          errmsg("requested WAL segment %s has already been removed",
764                                                                         filename)));
765                                 }
766                                 else
767                                         ereport(ERROR,
768                                                         (errcode_for_file_access(),
769                                                          errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
770                                                                         path, sendId, sendSeg)));
771                         }
772                         sendOff = 0;
773                 }
774
775                 /* Need to seek in the file? */
776                 if (sendOff != startoff)
777                 {
778                         if (lseek(sendFile, (off_t) startoff, SEEK_SET) < 0)
779                                 ereport(ERROR,
780                                                 (errcode_for_file_access(),
781                                                  errmsg("could not seek in log file %u, segment %u to offset %u: %m",
782                                                                 sendId, sendSeg, startoff)));
783                         sendOff = startoff;
784                 }
785
786                 /* How many bytes are within this segment? */
787                 if (nbytes > (XLogSegSize - startoff))
788                         segbytes = XLogSegSize - startoff;
789                 else
790                         segbytes = nbytes;
791
792                 readbytes = read(sendFile, buf, segbytes);
793                 if (readbytes <= 0)
794                         ereport(ERROR,
795                                         (errcode_for_file_access(),
796                         errmsg("could not read from log file %u, segment %u, offset %u, "
797                                    "length %lu: %m",
798                                    sendId, sendSeg, sendOff, (unsigned long) segbytes)));
799
800                 /* Update state for read */
801                 XLByteAdvance(recptr, readbytes);
802
803                 sendOff += readbytes;
804                 nbytes -= readbytes;
805                 buf += readbytes;
806         }
807
808         /*
809          * After reading into the buffer, check that what we read was valid. We do
810          * this after reading, because even though the segment was present when we
811          * opened it, it might get recycled or removed while we read it. The
812          * read() succeeds in that case, but the data we tried to read might
813          * already have been overwritten with new WAL records.
814          */
815         XLogGetLastRemoved(&lastRemovedLog, &lastRemovedSeg);
816         XLByteToSeg(startRecPtr, log, seg);
817         if (log < lastRemovedLog ||
818                 (log == lastRemovedLog && seg <= lastRemovedSeg))
819         {
820                 char            filename[MAXFNAMELEN];
821
822                 XLogFileName(filename, ThisTimeLineID, log, seg);
823                 ereport(ERROR,
824                                 (errcode_for_file_access(),
825                                  errmsg("requested WAL segment %s has already been removed",
826                                                 filename)));
827         }
828 }
829
830 /*
831  * Read up to MAX_SEND_SIZE bytes of WAL that's been flushed to disk,
832  * but not yet sent to the client, and send it.
833  *
834  * If there is no unsent WAL remaining, *caughtup is set to true, otherwise
835  * *caughtup is set to false.
836  *
837  * If there is pending WAL in output buffer, *pending is set to true,
838  * otherwise *pending is set to false.
839  *
840  * Returns true if OK, false if trouble.
841  */
842 static bool
843 XLogSend(bool *caughtup, bool *pending)
844 {
845         XLogRecPtr      SendRqstPtr;
846         XLogRecPtr      startptr;
847         static XLogRecPtr       endptr;
848         Size            nbytes;
849         uint32          n32;
850         int                     res;
851         WalDataMessageHeader msghdr;
852
853         /* Attempt to flush pending WAL in output buffer */
854         if (*pending)
855         {
856                 if (WalSndOutHead != WalSndOutTail)
857                 {
858                         res = pq_putbytes_if_writable(WalSndOutBuffer + WalSndOutHead,
859                                                                                   WalSndOutTail - WalSndOutHead);
860                         if (res == EOF)
861                                 return false;
862                         WalSndOutHead += res;
863                         if (WalSndOutHead != WalSndOutTail)
864                                 return true;
865                 }
866
867                 res = pq_flush_if_writable();
868                 if (res == EOF)
869                         return false;
870                 if (res == 0)
871                         return true;
872
873                 goto updt;
874         }
875
876         /*
877          * Attempt to send all data that's already been written out and fsync'd to
878          * disk.  We cannot go further than what's been written out given the
879          * current implementation of XLogRead().  And in any case it's unsafe to
880          * send WAL that is not securely down to disk on the master: if the master
881          * subsequently crashes and restarts, slaves must not have applied any WAL
882          * that gets lost on the master.
883          */
884         SendRqstPtr = GetFlushRecPtr();
885
886         /* Quick exit if nothing to do */
887         if (XLByteLE(SendRqstPtr, sentPtr))
888         {
889                 *caughtup = true;
890                 return true;
891         }
892
893         /*
894          * Figure out how much to send in one message. If there's no more than
895          * MAX_SEND_SIZE bytes to send, send everything. Otherwise send
896          * MAX_SEND_SIZE bytes, but round back to logfile or page boundary.
897          *
898          * The rounding is not only for performance reasons. Walreceiver relies on
899          * the fact that we never split a WAL record across two messages. Since a
900          * long WAL record is split at page boundary into continuation records,
901          * page boundary is always a safe cut-off point. We also assume that
902          * SendRqstPtr never points to the middle of a WAL record.
903          */
904         startptr = sentPtr;
905         if (startptr.xrecoff >= XLogFileSize)
906         {
907                 /*
908                  * crossing a logid boundary, skip the non-existent last log segment
909                  * in previous logical log file.
910                  */
911                 startptr.xlogid += 1;
912                 startptr.xrecoff = 0;
913         }
914
915         endptr = startptr;
916         XLByteAdvance(endptr, MAX_SEND_SIZE);
917         if (endptr.xlogid != startptr.xlogid)
918         {
919                 /* Don't cross a logfile boundary within one message */
920                 Assert(endptr.xlogid == startptr.xlogid + 1);
921                 endptr.xlogid = startptr.xlogid;
922                 endptr.xrecoff = XLogFileSize;
923         }
924
925         /* if we went beyond SendRqstPtr, back off */
926         if (XLByteLE(SendRqstPtr, endptr))
927         {
928                 endptr = SendRqstPtr;
929                 *caughtup = true;
930         }
931         else
932         {
933                 /* round down to page boundary. */
934                 endptr.xrecoff -= (endptr.xrecoff % XLOG_BLCKSZ);
935                 *caughtup = false;
936         }
937
938         nbytes = endptr.xrecoff - startptr.xrecoff;
939         Assert(nbytes <= MAX_SEND_SIZE);
940
941         /*
942          * OK to read and send the slice.
943          */
944         WalSndOutBuffer[0] = 'd';
945         WalSndOutBuffer[5] = 'w';
946         WalSndOutHead = 0;
947         WalSndOutTail = 6 + sizeof(WalDataMessageHeader) + nbytes;
948
949         n32 = htonl((uint32) WalSndOutTail - 1);
950         memcpy(WalSndOutBuffer + 1, &n32, 4);
951
952         /*
953          * Read the log directly into the output buffer to avoid extra memcpy
954          * calls.
955          */
956         XLogRead(WalSndOutBuffer + 6 + sizeof(WalDataMessageHeader), startptr, nbytes);
957
958         /*
959          * We fill the message header last so that the send timestamp is taken as
960          * late as possible.
961          */
962         msghdr.dataStart = startptr;
963         msghdr.walEnd = SendRqstPtr;
964         msghdr.sendTime = GetCurrentTimestamp();
965
966         memcpy(WalSndOutBuffer + 6, &msghdr, sizeof(WalDataMessageHeader));
967
968         res = pq_putbytes_if_writable(WalSndOutBuffer, WalSndOutTail);
969         if (res == EOF)
970                 return false;
971
972         WalSndOutHead = res;
973         if (WalSndOutHead != WalSndOutTail)
974         {
975                 *caughtup = false;
976                 *pending = true;
977                 return true;
978         }
979
980         /* Flush pending output to the client */
981         res = pq_flush_if_writable();
982         if (res == EOF)
983                 return false;
984         if (res == 0)
985         {
986                 *caughtup = false;
987                 *pending = true;
988                 return true;
989         }
990
991 updt:
992         WalSndOutHead = WalSndOutTail = 0;
993         *pending = false;
994
995         sentPtr = endptr;
996
997         /* Update shared memory status */
998         {
999                 /* use volatile pointer to prevent code rearrangement */
1000                 volatile WalSnd *walsnd = MyWalSnd;
1001
1002                 SpinLockAcquire(&walsnd->mutex);
1003                 walsnd->sentPtr = sentPtr;
1004                 SpinLockRelease(&walsnd->mutex);
1005         }
1006
1007         /* Report progress of XLOG streaming in PS display */
1008         if (update_process_title)
1009         {
1010                 char            activitymsg[50];
1011
1012                 snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%X",
1013                                  sentPtr.xlogid, sentPtr.xrecoff);
1014                 set_ps_display(activitymsg, false);
1015         }
1016
1017         return true;
1018 }
1019
1020 /* SIGHUP: set flag to re-read config file at next convenient time */
1021 static void
1022 WalSndSigHupHandler(SIGNAL_ARGS)
1023 {
1024         got_SIGHUP = true;
1025         if (MyWalSnd)
1026                 SetLatch(&MyWalSnd->latch);
1027 }
1028
1029 /* SIGTERM: set flag to shut down */
1030 static void
1031 WalSndShutdownHandler(SIGNAL_ARGS)
1032 {
1033         shutdown_requested = true;
1034         if (MyWalSnd)
1035                 SetLatch(&MyWalSnd->latch);
1036 }
1037
1038 /*
1039  * WalSndQuickDieHandler() occurs when signalled SIGQUIT by the postmaster.
1040  *
1041  * Some backend has bought the farm,
1042  * so we need to stop what we're doing and exit.
1043  */
1044 static void
1045 WalSndQuickDieHandler(SIGNAL_ARGS)
1046 {
1047         PG_SETMASK(&BlockSig);
1048
1049         /*
1050          * We DO NOT want to run proc_exit() callbacks -- we're here because
1051          * shared memory may be corrupted, so we don't want to try to clean up our
1052          * transaction.  Just nail the windows shut and get out of town.  Now that
1053          * there's an atexit callback to prevent third-party code from breaking
1054          * things by calling exit() directly, we have to reset the callbacks
1055          * explicitly to make this work as intended.
1056          */
1057         on_exit_reset();
1058
1059         /*
1060          * Note we do exit(2) not exit(0).      This is to force the postmaster into a
1061          * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
1062          * backend.  This is necessary precisely because we don't clean up our
1063          * shared memory state.  (The "dead man switch" mechanism in pmsignal.c
1064          * should ensure the postmaster sees this as a crash, too, but no harm in
1065          * being doubly sure.)
1066          */
1067         exit(2);
1068 }
1069
1070 /* SIGUSR1: set flag to send WAL records */
1071 static void
1072 WalSndXLogSendHandler(SIGNAL_ARGS)
1073 {
1074         latch_sigusr1_handler();
1075 }
1076
1077 /* SIGUSR2: set flag to do a last cycle and shut down afterwards */
1078 static void
1079 WalSndLastCycleHandler(SIGNAL_ARGS)
1080 {
1081         ready_to_stop = true;
1082         if (MyWalSnd)
1083                 SetLatch(&MyWalSnd->latch);
1084 }
1085
1086 /* Set up signal handlers */
1087 void
1088 WalSndSignals(void)
1089 {
1090         /* Set up signal handlers */
1091         pqsignal(SIGHUP, WalSndSigHupHandler);          /* set flag to read config
1092                                                                                                  * file */
1093         pqsignal(SIGINT, SIG_IGN);      /* not used */
1094         pqsignal(SIGTERM, WalSndShutdownHandler);       /* request shutdown */
1095         pqsignal(SIGQUIT, WalSndQuickDieHandler);       /* hard crash time */
1096         pqsignal(SIGALRM, SIG_IGN);
1097         pqsignal(SIGPIPE, SIG_IGN);
1098         pqsignal(SIGUSR1, WalSndXLogSendHandler);       /* request WAL sending */
1099         pqsignal(SIGUSR2, WalSndLastCycleHandler);      /* request a last cycle and
1100                                                                                                  * shutdown */
1101
1102         /* Reset some signals that are accepted by postmaster but not here */
1103         pqsignal(SIGCHLD, SIG_DFL);
1104         pqsignal(SIGTTIN, SIG_DFL);
1105         pqsignal(SIGTTOU, SIG_DFL);
1106         pqsignal(SIGCONT, SIG_DFL);
1107         pqsignal(SIGWINCH, SIG_DFL);
1108 }
1109
1110 /* Report shared-memory space needed by WalSndShmemInit */
1111 Size
1112 WalSndShmemSize(void)
1113 {
1114         Size            size = 0;
1115
1116         size = offsetof(WalSndCtlData, walsnds);
1117         size = add_size(size, mul_size(max_wal_senders, sizeof(WalSnd)));
1118
1119         /*
1120          * If replication is enabled, we have a data structure called
1121          * WalSndWaiters, created in shared memory.
1122          */
1123         if (max_wal_senders > 0)
1124                 size = add_size(size, mul_size(MaxBackends, sizeof(WalSndWaiter)));
1125
1126         return size;
1127 }
1128
1129 /* Allocate and initialize walsender-related shared memory */
1130 void
1131 WalSndShmemInit(void)
1132 {
1133         bool            found;
1134         int                     i;
1135         Size            size = add_size(offsetof(WalSndCtlData, walsnds),
1136                                                                 mul_size(max_wal_senders, sizeof(WalSnd)));
1137
1138         WalSndCtl = (WalSndCtlData *)
1139                 ShmemInitStruct("Wal Sender Ctl", size, &found);
1140
1141         if (!found)
1142         {
1143                 /* First time through, so initialize */
1144                 MemSet(WalSndCtl, 0, size);
1145
1146                 for (i = 0; i < max_wal_senders; i++)
1147                 {
1148                         WalSnd     *walsnd = &WalSndCtl->walsnds[i];
1149
1150                         SpinLockInit(&walsnd->mutex);
1151                         InitSharedLatch(&walsnd->latch);
1152                 }
1153         }
1154
1155         /* Create or attach to the WalSndWaiters array too, if needed */
1156         if (max_wal_senders > 0)
1157         {
1158                 WalSndWaiters = (WalSndWaiter *)
1159                         ShmemInitStruct("WalSndWaiters",
1160                                                         mul_size(MaxBackends, sizeof(WalSndWaiter)),
1161                                                         &found);
1162                 WalSndCtl->maxWaiters = MaxBackends;
1163         }
1164 }
1165
1166 /* Wake up all walsenders */
1167 void
1168 WalSndWakeup(void)
1169 {
1170         int             i;
1171
1172         for (i = 0; i < max_wal_senders; i++)
1173                 SetLatch(&WalSndCtl->walsnds[i].latch);
1174 }
1175
1176 /*
1177  * Ensure that replication has been completed up to the given position.
1178  */
1179 void
1180 WaitXLogSend(XLogRecPtr record)
1181 {
1182         int             i;
1183         bool    mustwait = false;
1184
1185         Assert(max_wal_senders > 0);
1186
1187         for (i = 0; i < max_wal_senders; i++)
1188         {
1189                 /* use volatile pointer to prevent code rearrangement */
1190                 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1191                 XLogRecPtr              recptr;
1192
1193                 /* Don't need to wait for asynchronous walsender */
1194                 if (walsnd->pid == 0 ||
1195                         walsnd->rplMode <= REPLICATION_MODE_ASYNC)
1196                         continue;
1197
1198                 SpinLockAcquire(&walsnd->mutex);
1199                 recptr = walsnd->ackdPtr;
1200                 SpinLockRelease(&walsnd->mutex);
1201
1202                 if (recptr.xlogid == 0 && recptr.xrecoff == 0)
1203                         continue;
1204
1205                 /* Quick exit if already known replicated */
1206                 if (XLByteLE(record, recptr))
1207                         return;
1208
1209                 mustwait = true;
1210         }
1211
1212         /*
1213          * Don't need to wait for replication if there is no synchronous
1214          * standby
1215          */
1216         if (!mustwait)
1217                 return;
1218
1219         /*
1220          * Register myself into the wait list and sleep until replication
1221          * has been completed up to the given position and the walsender
1222          * signals me.
1223          *
1224          * If replication has been completed up to the latest position
1225          * before the registration, walsender might be unable to send the
1226          * signal immediately. We must wake up the walsender after the
1227          * registration.
1228          */
1229         ResetLatch(&MyProc->latch);
1230         RegisterWalSndWaiter(MyBackendId, record, &MyProc->latch);
1231         WalSndWakeup();
1232
1233         for (;;)
1234         {
1235                 WaitLatch(&MyProc->latch, 1000000L);
1236
1237                 /* If done already, we finish waiting */
1238                 if (replication_done)
1239                 {
1240                         replication_done = false;
1241                         return;
1242                 }
1243         }
1244 }
1245
1246 /*
1247  * Register the given backend into the wait list.
1248  */
1249 static void
1250 RegisterWalSndWaiter(BackendId backendId, XLogRecPtr record, Latch *latch)
1251 {
1252         /* use volatile pointer to prevent code rearrangement */
1253         volatile WalSndCtlData  *walsndctl = WalSndCtl;
1254         int             i;
1255         int             count = 0;
1256
1257         LWLockAcquire(WalSndWaiterLock, LW_EXCLUSIVE);
1258
1259         /* Out of slots. This should not happen. */
1260         if (walsndctl->numWaiters + 1 > walsndctl->maxWaiters)
1261                 elog(PANIC, "out of replication waiters slots");
1262
1263         /*
1264          * The given position is expected to be relatively new in the
1265          * wait list. Since the entries in the list are sorted in an
1266          * increasing order of XLogRecPtr, we can shorten the time it
1267          * takes to find an insert slot by scanning the list backwards.
1268          */
1269         for (i = walsndctl->numWaiters; i > 0; i--)
1270         {
1271                 if (XLByteLE(WalSndWaiters[i - 1].record, record))
1272                         break;
1273                 count++;
1274         }
1275
1276         /* Shuffle the list if needed */
1277         if (count > 0)
1278                 memmove(&WalSndWaiters[i + 1], &WalSndWaiters[i],
1279                                 count * sizeof(WalSndWaiter));
1280
1281         WalSndWaiters[i].backendId = backendId;
1282         WalSndWaiters[i].record = record;
1283         WalSndWaiters[i].latch = latch;
1284         walsndctl->numWaiters++;
1285
1286         LWLockRelease(WalSndWaiterLock);
1287 }
1288
1289 /*
1290  * Wake up the backends waiting until replication has been completed
1291  * up to the position older than or equal to the given one.
1292  *
1293  * Wake up all waiters if InvalidXLogRecPtr is given.
1294    */
1295 static void
1296 WakeupWalSndWaiters(XLogRecPtr record)
1297 {
1298         /* use volatile pointer to prevent code rearrangement */
1299         volatile WalSndCtlData  *walsndctl = WalSndCtl;
1300         int             i;
1301         int             count = 0;
1302         bool    all_wakeup = (record.xlogid == 0 && record.xrecoff == 0);
1303
1304         LWLockAcquire(WalSndWaiterLock, LW_EXCLUSIVE);
1305
1306         for (i = 0; i < walsndctl->numWaiters; i++)
1307         {
1308                 /* use volatile pointer to prevent code rearrangement */
1309                 volatile WalSndWaiter  *waiter = &WalSndWaiters[i];
1310
1311                 if (all_wakeup || XLByteLE(waiter->record, record))
1312                 {
1313                         SetProcLatch(waiter->latch, PROCSIG_REPLICATION_INTERRUPT,
1314                                                  waiter->backendId);
1315                         count++;
1316                 }
1317                 else
1318                 {
1319                         /*
1320                          * If the backend waiting for the Ack position newer than
1321                          * the given one is found, we don't need to search the wait
1322                          * list any more. This is because the waiters in the list
1323                          * are guaranteed to be sorted in an increasing order of
1324                          * XLogRecPtr.
1325                          */
1326                         break;
1327                 }
1328         }
1329
1330         /* If there are still some waiters, left-justify them in the list */
1331         walsndctl->numWaiters -= count;
1332         if (walsndctl->numWaiters > 0 && count > 0)
1333                 memmove(&WalSndWaiters[0], &WalSndWaiters[i],
1334                                 walsndctl->numWaiters * sizeof(WalSndWaiter));
1335
1336         LWLockRelease(WalSndWaiterLock);
1337 }
1338
1339 /*
1340  * Returns the oldest Ack position in synchronous walsenders. Or
1341  * InvalidXLogRecPtr if none.
1342  */
1343 static XLogRecPtr
1344 GetOldestAckdPtr(void)
1345 {
1346         XLogRecPtr      oldest = {0, 0};
1347         int             i;
1348         bool    found = false;
1349
1350         for (i = 0; i < max_wal_senders; i++)
1351         {
1352                 /* use volatile pointer to prevent code rearrangement */
1353                 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1354                 XLogRecPtr              recptr;
1355
1356                 /*
1357                  * Ignore the Ack position that asynchronous walsender has
1358                  * since it has never received any Ack.
1359                  */
1360                 if (walsnd->pid == 0 ||
1361                         walsnd->rplMode <= REPLICATION_MODE_ASYNC)
1362                         continue;
1363
1364                 SpinLockAcquire(&walsnd->mutex);
1365                 recptr = walsnd->ackdPtr;
1366                 SpinLockRelease(&walsnd->mutex);
1367
1368                 /*
1369                  * Ignore the Ack position that the walsender which has not
1370                  * received any Ack yet has.
1371                  */
1372                 if (recptr.xlogid == 0 && recptr.xrecoff == 0)
1373                         continue;
1374
1375                 if (!found || XLByteLT(recptr, oldest))
1376                         oldest = recptr;
1377                 found = true;
1378         }
1379         return oldest;
1380 }
1381
1382 /*
1383  * This is called when PROCSIG_REPLICATION_INTERRUPT is received.
1384  */
1385 void
1386 HandleReplicationInterrupt(void)
1387 {
1388         replication_done = true;
1389 }