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