]> granicus.if.org Git - postgresql/blob - src/backend/replication/walsender.c
Move "hot" members of PGPROC into a separate PGXACT array.
[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 "access/transam.h"
41 #include "access/xlog_internal.h"
42 #include "catalog/pg_type.h"
43 #include "funcapi.h"
44 #include "libpq/libpq.h"
45 #include "libpq/pqformat.h"
46 #include "libpq/pqsignal.h"
47 #include "miscadmin.h"
48 #include "nodes/replnodes.h"
49 #include "replication/basebackup.h"
50 #include "replication/syncrep.h"
51 #include "replication/walprotocol.h"
52 #include "replication/walreceiver.h"
53 #include "replication/walsender.h"
54 #include "replication/walsender_private.h"
55 #include "storage/fd.h"
56 #include "storage/ipc.h"
57 #include "storage/pmsignal.h"
58 #include "storage/proc.h"
59 #include "storage/procarray.h"
60 #include "tcop/tcopprot.h"
61 #include "utils/builtins.h"
62 #include "utils/guc.h"
63 #include "utils/memutils.h"
64 #include "utils/ps_status.h"
65 #include "utils/resowner.h"
66 #include "utils/timestamp.h"
67
68
69 /* Array of WalSnds in shared memory */
70 WalSndCtlData *WalSndCtl = NULL;
71
72 /* My slot in the shared memory array */
73 WalSnd     *MyWalSnd = NULL;
74
75 /* Global state */
76 bool            am_walsender = false;           /* Am I a walsender process ? */
77 bool            am_cascading_walsender = false; /* Am I cascading WAL to another standby ? */
78
79 /* User-settable parameters for walsender */
80 int                     max_wal_senders = 0;    /* the maximum number of concurrent walsenders */
81 int                     replication_timeout = 60 * 1000;        /* maximum time to send one
82                                                                                                  * WAL data message */
83
84 /*
85  * These variables are used similarly to openLogFile/Id/Seg/Off,
86  * but for walsender to read the XLOG.
87  */
88 static int      sendFile = -1;
89 static uint32 sendId = 0;
90 static uint32 sendSeg = 0;
91 static uint32 sendOff = 0;
92
93 /*
94  * How far have we sent WAL already? This is also advertised in
95  * MyWalSnd->sentPtr.  (Actually, this is the next WAL location to send.)
96  */
97 static XLogRecPtr sentPtr = {0, 0};
98
99 /*
100  * Buffer for processing reply messages.
101  */
102 static StringInfoData reply_message;
103
104 /*
105  * Timestamp of the last receipt of the reply from the standby.
106  */
107 static TimestampTz last_reply_timestamp;
108
109 /* Flags set by signal handlers for later service in main loop */
110 static volatile sig_atomic_t got_SIGHUP = false;
111 volatile sig_atomic_t walsender_shutdown_requested = false;
112 volatile sig_atomic_t walsender_ready_to_stop = false;
113
114 /* Signal handlers */
115 static void WalSndSigHupHandler(SIGNAL_ARGS);
116 static void WalSndShutdownHandler(SIGNAL_ARGS);
117 static void WalSndQuickDieHandler(SIGNAL_ARGS);
118 static void WalSndXLogSendHandler(SIGNAL_ARGS);
119 static void WalSndLastCycleHandler(SIGNAL_ARGS);
120
121 /* Prototypes for private functions */
122 static bool HandleReplicationCommand(const char *cmd_string);
123 static int      WalSndLoop(void);
124 static void InitWalSnd(void);
125 static void WalSndHandshake(void);
126 static void WalSndKill(int code, Datum arg);
127 static void XLogSend(char *msgbuf, bool *caughtup);
128 static void IdentifySystem(void);
129 static void StartReplication(StartReplicationCmd *cmd);
130 static void ProcessStandbyMessage(void);
131 static void ProcessStandbyReplyMessage(void);
132 static void ProcessStandbyHSFeedbackMessage(void);
133 static void ProcessRepliesIfAny(void);
134
135
136 /* Main entry point for walsender process */
137 int
138 WalSenderMain(void)
139 {
140         MemoryContext walsnd_context;
141
142         am_cascading_walsender = RecoveryInProgress();
143
144         /* Create a per-walsender data structure in shared memory */
145         InitWalSnd();
146
147         /*
148          * Create a memory context that we will do all our work in.  We do this so
149          * that we can reset the context during error recovery and thereby avoid
150          * possible memory leaks.  Formerly this code just ran in
151          * TopMemoryContext, but resetting that would be a really bad idea.
152          *
153          * XXX: we don't actually attempt error recovery in walsender, we just
154          * close the connection and exit.
155          */
156         walsnd_context = AllocSetContextCreate(TopMemoryContext,
157                                                                                    "Wal Sender",
158                                                                                    ALLOCSET_DEFAULT_MINSIZE,
159                                                                                    ALLOCSET_DEFAULT_INITSIZE,
160                                                                                    ALLOCSET_DEFAULT_MAXSIZE);
161         MemoryContextSwitchTo(walsnd_context);
162
163         /* Set up resource owner */
164         CurrentResourceOwner = ResourceOwnerCreate(NULL, "walsender top-level resource owner");
165
166         /* Unblock signals (they were blocked when the postmaster forked us) */
167         PG_SETMASK(&UnBlockSig);
168
169         /*
170          * Use the recovery target timeline ID during recovery
171          */
172         if (am_cascading_walsender)
173                 ThisTimeLineID = GetRecoveryTargetTLI();
174
175         /* Tell the standby that walsender is ready for receiving commands */
176         ReadyForQuery(DestRemote);
177
178         /* Handle handshake messages before streaming */
179         WalSndHandshake();
180
181         /* Initialize shared memory status */
182         {
183                 /* use volatile pointer to prevent code rearrangement */
184                 volatile WalSnd *walsnd = MyWalSnd;
185
186                 SpinLockAcquire(&walsnd->mutex);
187                 walsnd->sentPtr = sentPtr;
188                 SpinLockRelease(&walsnd->mutex);
189         }
190
191         SyncRepInitConfig();
192
193         /* Main loop of walsender */
194         return WalSndLoop();
195 }
196
197 /*
198  * Execute commands from walreceiver, until we enter streaming mode.
199  */
200 static void
201 WalSndHandshake(void)
202 {
203         StringInfoData input_message;
204         bool            replication_started = false;
205
206         initStringInfo(&input_message);
207
208         while (!replication_started)
209         {
210                 int                     firstchar;
211
212                 WalSndSetState(WALSNDSTATE_STARTUP);
213                 set_ps_display("idle", false);
214
215                 /* Wait for a command to arrive */
216                 firstchar = pq_getbyte();
217
218                 /*
219                  * Emergency bailout if postmaster has died.  This is to avoid the
220                  * necessity for manual cleanup of all postmaster children.
221                  */
222                 if (!PostmasterIsAlive())
223                         exit(1);
224
225                 /*
226                  * Check for any other interesting events that happened while we
227                  * slept.
228                  */
229                 if (got_SIGHUP)
230                 {
231                         got_SIGHUP = false;
232                         ProcessConfigFile(PGC_SIGHUP);
233                 }
234
235                 if (firstchar != EOF)
236                 {
237                         /*
238                          * Read the message contents. This is expected to be done without
239                          * blocking because we've been able to get message type code.
240                          */
241                         if (pq_getmessage(&input_message, 0))
242                                 firstchar = EOF;        /* suitable message already logged */
243                 }
244
245                 /* Handle the very limited subset of commands expected in this phase */
246                 switch (firstchar)
247                 {
248                         case 'Q':                       /* Query message */
249                                 {
250                                         const char *query_string;
251
252                                         query_string = pq_getmsgstring(&input_message);
253                                         pq_getmsgend(&input_message);
254
255                                         if (HandleReplicationCommand(query_string))
256                                                 replication_started = true;
257                                 }
258                                 break;
259
260                         case 'X':
261                                 /* standby is closing the connection */
262                                 proc_exit(0);
263
264                         case EOF:
265                                 /* standby disconnected unexpectedly */
266                                 ereport(COMMERROR,
267                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
268                                                  errmsg("unexpected EOF on standby connection")));
269                                 proc_exit(0);
270
271                         default:
272                                 ereport(FATAL,
273                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
274                                                  errmsg("invalid standby handshake message type %d", firstchar)));
275                 }
276         }
277 }
278
279 /*
280  * IDENTIFY_SYSTEM
281  */
282 static void
283 IdentifySystem(void)
284 {
285         StringInfoData buf;
286         char            sysid[32];
287         char            tli[11];
288         char            xpos[MAXFNAMELEN];
289         XLogRecPtr      logptr;
290
291         /*
292          * Reply with a result set with one row, three columns. First col is
293          * system ID, second is timeline ID, and third is current xlog location.
294          */
295
296         snprintf(sysid, sizeof(sysid), UINT64_FORMAT,
297                          GetSystemIdentifier());
298         snprintf(tli, sizeof(tli), "%u", ThisTimeLineID);
299
300         logptr = am_cascading_walsender ? GetStandbyFlushRecPtr() : GetInsertRecPtr();
301
302         snprintf(xpos, sizeof(xpos), "%X/%X",
303                          logptr.xlogid, logptr.xrecoff);
304
305         /* Send a RowDescription message */
306         pq_beginmessage(&buf, 'T');
307         pq_sendint(&buf, 3, 2);         /* 3 fields */
308
309         /* first field */
310         pq_sendstring(&buf, "systemid");        /* col name */
311         pq_sendint(&buf, 0, 4);         /* table oid */
312         pq_sendint(&buf, 0, 2);         /* attnum */
313         pq_sendint(&buf, TEXTOID, 4);           /* type oid */
314         pq_sendint(&buf, -1, 2);        /* typlen */
315         pq_sendint(&buf, 0, 4);         /* typmod */
316         pq_sendint(&buf, 0, 2);         /* format code */
317
318         /* second field */
319         pq_sendstring(&buf, "timeline");        /* col name */
320         pq_sendint(&buf, 0, 4);         /* table oid */
321         pq_sendint(&buf, 0, 2);         /* attnum */
322         pq_sendint(&buf, INT4OID, 4);           /* type oid */
323         pq_sendint(&buf, 4, 2);         /* typlen */
324         pq_sendint(&buf, 0, 4);         /* typmod */
325         pq_sendint(&buf, 0, 2);         /* format code */
326
327         /* third field */
328         pq_sendstring(&buf, "xlogpos");
329         pq_sendint(&buf, 0, 4);
330         pq_sendint(&buf, 0, 2);
331         pq_sendint(&buf, TEXTOID, 4);
332         pq_sendint(&buf, -1, 2);
333         pq_sendint(&buf, 0, 4);
334         pq_sendint(&buf, 0, 2);
335         pq_endmessage(&buf);
336
337         /* Send a DataRow message */
338         pq_beginmessage(&buf, 'D');
339         pq_sendint(&buf, 3, 2);         /* # of columns */
340         pq_sendint(&buf, strlen(sysid), 4); /* col1 len */
341         pq_sendbytes(&buf, (char *) &sysid, strlen(sysid));
342         pq_sendint(&buf, strlen(tli), 4);       /* col2 len */
343         pq_sendbytes(&buf, (char *) tli, strlen(tli));
344         pq_sendint(&buf, strlen(xpos), 4);      /* col3 len */
345         pq_sendbytes(&buf, (char *) xpos, strlen(xpos));
346
347         pq_endmessage(&buf);
348
349         /* Send CommandComplete and ReadyForQuery messages */
350         EndCommand("SELECT", DestRemote);
351         ReadyForQuery(DestRemote);
352         /* ReadyForQuery did pq_flush for us */
353 }
354
355 /*
356  * START_REPLICATION
357  */
358 static void
359 StartReplication(StartReplicationCmd *cmd)
360 {
361         StringInfoData buf;
362
363         /*
364          * Let postmaster know that we're streaming. Once we've declared us as a
365          * WAL sender process, postmaster will let us outlive the bgwriter and
366          * kill us last in the shutdown sequence, so we get a chance to stream all
367          * remaining WAL at shutdown, including the shutdown checkpoint. Note that
368          * there's no going back, and we mustn't write any WAL records after this.
369          */
370         MarkPostmasterChildWalSender();
371         SendPostmasterSignal(PMSIGNAL_ADVANCE_STATE_MACHINE);
372
373         /*
374          * When promoting a cascading standby, postmaster sends SIGUSR2 to
375          * any cascading walsenders to kill them. But there is a corner-case where
376          * such walsender fails to receive SIGUSR2 and survives a standby promotion
377          * unexpectedly. This happens when postmaster sends SIGUSR2 before
378          * the walsender marks itself as a WAL sender, because postmaster sends
379          * SIGUSR2 to only the processes marked as a WAL sender.
380          *
381          * To avoid this corner-case, if recovery is NOT in progress even though
382          * the walsender is cascading one, we do the same thing as SIGUSR2 signal
383          * handler does, i.e., set walsender_ready_to_stop to true. Which causes
384          * the walsender to end later.
385          *
386          * When terminating cascading walsenders, usually postmaster writes
387          * the log message announcing the terminations. But there is a race condition
388          * here. If there is no walsender except this process before reaching here,
389          * postmaster thinks that there is no walsender and suppresses that
390          * log message. To handle this case, we always emit that log message here.
391          * This might cause duplicate log messages, but which is less likely to happen,
392          * so it's not worth writing some code to suppress them.
393          */
394         if (am_cascading_walsender && !RecoveryInProgress())
395         {
396                 ereport(LOG,
397                                 (errmsg("terminating walsender process to force cascaded standby "
398                                                 "to update timeline and reconnect")));
399                 walsender_ready_to_stop = true;
400         }
401
402         /*
403          * We assume here that we're logging enough information in the WAL for
404          * log-shipping, since this is checked in PostmasterMain().
405          *
406          * NOTE: wal_level can only change at shutdown, so in most cases it is
407          * difficult for there to be WAL data that we can still see that was written
408          * at wal_level='minimal'.
409          */
410
411         /*
412          * When we first start replication the standby will be behind the primary.
413          * For some applications, for example, synchronous replication, it is
414          * important to have a clear state for this initial catchup mode, so we
415          * can trigger actions when we change streaming state later. We may stay
416          * in this state for a long time, which is exactly why we want to be able
417          * to monitor whether or not we are still here.
418          */
419         WalSndSetState(WALSNDSTATE_CATCHUP);
420
421         /* Send a CopyBothResponse message, and start streaming */
422         pq_beginmessage(&buf, 'W');
423         pq_sendbyte(&buf, 0);
424         pq_sendint(&buf, 0, 2);
425         pq_endmessage(&buf);
426         pq_flush();
427
428         /*
429          * Initialize position to the received one, then the xlog records begin to
430          * be shipped from that position
431          */
432         sentPtr = cmd->startpoint;
433 }
434
435 /*
436  * Execute an incoming replication command.
437  */
438 static bool
439 HandleReplicationCommand(const char *cmd_string)
440 {
441         bool            replication_started = false;
442         int                     parse_rc;
443         Node       *cmd_node;
444         MemoryContext cmd_context;
445         MemoryContext old_context;
446
447         elog(DEBUG1, "received replication command: %s", cmd_string);
448
449         cmd_context = AllocSetContextCreate(CurrentMemoryContext,
450                                                                                 "Replication command context",
451                                                                                 ALLOCSET_DEFAULT_MINSIZE,
452                                                                                 ALLOCSET_DEFAULT_INITSIZE,
453                                                                                 ALLOCSET_DEFAULT_MAXSIZE);
454         old_context = MemoryContextSwitchTo(cmd_context);
455
456         replication_scanner_init(cmd_string);
457         parse_rc = replication_yyparse();
458         if (parse_rc != 0)
459                 ereport(ERROR,
460                                 (errcode(ERRCODE_SYNTAX_ERROR),
461                                  (errmsg_internal("replication command parser returned %d",
462                                                                   parse_rc))));
463
464         cmd_node = replication_parse_result;
465
466         switch (cmd_node->type)
467         {
468                 case T_IdentifySystemCmd:
469                         IdentifySystem();
470                         break;
471
472                 case T_StartReplicationCmd:
473                         StartReplication((StartReplicationCmd *) cmd_node);
474
475                         /* break out of the loop */
476                         replication_started = true;
477                         break;
478
479                 case T_BaseBackupCmd:
480                         SendBaseBackup((BaseBackupCmd *) cmd_node);
481
482                         /* Send CommandComplete and ReadyForQuery messages */
483                         EndCommand("SELECT", DestRemote);
484                         ReadyForQuery(DestRemote);
485                         /* ReadyForQuery did pq_flush for us */
486                         break;
487
488                 default:
489                         ereport(FATAL,
490                                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
491                                          errmsg("invalid standby query string: %s", cmd_string)));
492         }
493
494         /* done */
495         MemoryContextSwitchTo(old_context);
496         MemoryContextDelete(cmd_context);
497
498         return replication_started;
499 }
500
501 /*
502  * Check if the remote end has closed the connection.
503  */
504 static void
505 ProcessRepliesIfAny(void)
506 {
507         unsigned char firstchar;
508         int                     r;
509         bool            received = false;
510
511         for (;;)
512         {
513                 r = pq_getbyte_if_available(&firstchar);
514                 if (r < 0)
515                 {
516                         /* unexpected error or EOF */
517                         ereport(COMMERROR,
518                                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
519                                          errmsg("unexpected EOF on standby connection")));
520                         proc_exit(0);
521                 }
522                 if (r == 0)
523                 {
524                         /* no data available without blocking */
525                         break;
526                 }
527
528                 /* Handle the very limited subset of commands expected in this phase */
529                 switch (firstchar)
530                 {
531                                 /*
532                                  * 'd' means a standby reply wrapped in a CopyData packet.
533                                  */
534                         case 'd':
535                                 ProcessStandbyMessage();
536                                 received = true;
537                                 break;
538
539                                 /*
540                                  * 'X' means that the standby is closing down the socket.
541                                  */
542                         case 'X':
543                                 proc_exit(0);
544
545                         default:
546                                 ereport(FATAL,
547                                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
548                                                  errmsg("invalid standby message type \"%c\"",
549                                                                 firstchar)));
550                 }
551         }
552
553         /*
554          * Save the last reply timestamp if we've received at least one reply.
555          */
556         if (received)
557                 last_reply_timestamp = GetCurrentTimestamp();
558 }
559
560 /*
561  * Process a status update message received from standby.
562  */
563 static void
564 ProcessStandbyMessage(void)
565 {
566         char            msgtype;
567
568         resetStringInfo(&reply_message);
569
570         /*
571          * Read the message contents.
572          */
573         if (pq_getmessage(&reply_message, 0))
574         {
575                 ereport(COMMERROR,
576                                 (errcode(ERRCODE_PROTOCOL_VIOLATION),
577                                  errmsg("unexpected EOF on standby connection")));
578                 proc_exit(0);
579         }
580
581         /*
582          * Check message type from the first byte.
583          */
584         msgtype = pq_getmsgbyte(&reply_message);
585
586         switch (msgtype)
587         {
588                 case 'r':
589                         ProcessStandbyReplyMessage();
590                         break;
591
592                 case 'h':
593                         ProcessStandbyHSFeedbackMessage();
594                         break;
595
596                 default:
597                         ereport(COMMERROR,
598                                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
599                                          errmsg("unexpected message type \"%c\"", msgtype)));
600                         proc_exit(0);
601         }
602 }
603
604 /*
605  * Regular reply from standby advising of WAL positions on standby server.
606  */
607 static void
608 ProcessStandbyReplyMessage(void)
609 {
610         StandbyReplyMessage reply;
611
612         pq_copymsgbytes(&reply_message, (char *) &reply, sizeof(StandbyReplyMessage));
613
614         elog(DEBUG2, "write %X/%X flush %X/%X apply %X/%X",
615                  reply.write.xlogid, reply.write.xrecoff,
616                  reply.flush.xlogid, reply.flush.xrecoff,
617                  reply.apply.xlogid, reply.apply.xrecoff);
618
619         /*
620          * Update shared state for this WalSender process based on reply data from
621          * standby.
622          */
623         {
624                 /* use volatile pointer to prevent code rearrangement */
625                 volatile WalSnd *walsnd = MyWalSnd;
626
627                 SpinLockAcquire(&walsnd->mutex);
628                 walsnd->write = reply.write;
629                 walsnd->flush = reply.flush;
630                 walsnd->apply = reply.apply;
631                 SpinLockRelease(&walsnd->mutex);
632         }
633
634         if (!am_cascading_walsender)
635                 SyncRepReleaseWaiters();
636 }
637
638 /*
639  * Hot Standby feedback
640  */
641 static void
642 ProcessStandbyHSFeedbackMessage(void)
643 {
644         StandbyHSFeedbackMessage reply;
645         TransactionId nextXid;
646         uint32          nextEpoch;
647
648         /* Decipher the reply message */
649         pq_copymsgbytes(&reply_message, (char *) &reply,
650                                         sizeof(StandbyHSFeedbackMessage));
651
652         elog(DEBUG2, "hot standby feedback xmin %u epoch %u",
653                  reply.xmin,
654                  reply.epoch);
655
656         /* Ignore invalid xmin (can't actually happen with current walreceiver) */
657         if (!TransactionIdIsNormal(reply.xmin))
658                 return;
659
660         /*
661          * Check that the provided xmin/epoch are sane, that is, not in the future
662          * and not so far back as to be already wrapped around.  Ignore if not.
663          *
664          * Epoch of nextXid should be same as standby, or if the counter has
665          * wrapped, then one greater than standby.
666          */
667         GetNextXidAndEpoch(&nextXid, &nextEpoch);
668
669         if (reply.xmin <= nextXid)
670         {
671                 if (reply.epoch != nextEpoch)
672                         return;
673         }
674         else
675         {
676                 if (reply.epoch + 1 != nextEpoch)
677                         return;
678         }
679
680         if (!TransactionIdPrecedesOrEquals(reply.xmin, nextXid))
681                 return;                                 /* epoch OK, but it's wrapped around */
682
683         /*
684          * Set the WalSender's xmin equal to the standby's requested xmin, so that
685          * the xmin will be taken into account by GetOldestXmin.  This will hold
686          * back the removal of dead rows and thereby prevent the generation of
687          * cleanup conflicts on the standby server.
688          *
689          * There is a small window for a race condition here: although we just
690          * checked that reply.xmin precedes nextXid, the nextXid could have gotten
691          * advanced between our fetching it and applying the xmin below, perhaps
692          * far enough to make reply.xmin wrap around.  In that case the xmin we
693          * set here would be "in the future" and have no effect.  No point in
694          * worrying about this since it's too late to save the desired data
695          * anyway.  Assuming that the standby sends us an increasing sequence of
696          * xmins, this could only happen during the first reply cycle, else our
697          * own xmin would prevent nextXid from advancing so far.
698          *
699          * We don't bother taking the ProcArrayLock here.  Setting the xmin field
700          * is assumed atomic, and there's no real need to prevent a concurrent
701          * GetOldestXmin.  (If we're moving our xmin forward, this is obviously
702          * safe, and if we're moving it backwards, well, the data is at risk
703          * already since a VACUUM could have just finished calling GetOldestXmin.)
704          */
705         MyPgXact->xmin = reply.xmin;
706 }
707
708 /* Main loop of walsender process */
709 static int
710 WalSndLoop(void)
711 {
712         char       *output_message;
713         bool            caughtup = false;
714
715         /*
716          * Allocate buffer that will be used for each output message.  We do this
717          * just once to reduce palloc overhead.  The buffer must be made large
718          * enough for maximum-sized messages.
719          */
720         output_message = palloc(1 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE);
721
722         /*
723          * Allocate buffer that will be used for processing reply messages.  As
724          * above, do this just once to reduce palloc overhead.
725          */
726         initStringInfo(&reply_message);
727
728         /* Initialize the last reply timestamp */
729         last_reply_timestamp = GetCurrentTimestamp();
730
731         /* Loop forever, unless we get an error */
732         for (;;)
733         {
734                 /* Clear any already-pending wakeups */
735                 ResetLatch(&MyWalSnd->latch);
736
737                 /*
738                  * Emergency bailout if postmaster has died.  This is to avoid the
739                  * necessity for manual cleanup of all postmaster children.
740                  */
741                 if (!PostmasterIsAlive())
742                         exit(1);
743
744                 /* Process any requests or signals received recently */
745                 if (got_SIGHUP)
746                 {
747                         got_SIGHUP = false;
748                         ProcessConfigFile(PGC_SIGHUP);
749                         SyncRepInitConfig();
750                 }
751
752                 /* Normal exit from the walsender is here */
753                 if (walsender_shutdown_requested)
754                 {
755                         /* Inform the standby that XLOG streaming is done */
756                         pq_puttextmessage('C', "COPY 0");
757                         pq_flush();
758
759                         proc_exit(0);
760                 }
761
762                 /* Check for input from the client */
763                 ProcessRepliesIfAny();
764
765                 /*
766                  * If we don't have any pending data in the output buffer, try to send
767                  * some more.  If there is some, we don't bother to call XLogSend
768                  * again until we've flushed it ... but we'd better assume we are not
769                  * caught up.
770                  */
771                 if (!pq_is_send_pending())
772                         XLogSend(output_message, &caughtup);
773                 else
774                         caughtup = false;
775
776                 /* Try to flush pending output to the client */
777                 if (pq_flush_if_writable() != 0)
778                         break;
779
780                 /* If nothing remains to be sent right now ... */
781                 if (caughtup && !pq_is_send_pending())
782                 {
783                         /*
784                          * If we're in catchup state, move to streaming.  This is an
785                          * important state change for users to know about, since before
786                          * this point data loss might occur if the primary dies and we
787                          * need to failover to the standby. The state change is also
788                          * important for synchronous replication, since commits that
789                          * started to wait at that point might wait for some time.
790                          */
791                         if (MyWalSnd->state == WALSNDSTATE_CATCHUP)
792                         {
793                                 ereport(DEBUG1,
794                                                 (errmsg("standby \"%s\" has now caught up with primary",
795                                                                 application_name)));
796                                 WalSndSetState(WALSNDSTATE_STREAMING);
797                         }
798
799                         /*
800                          * When SIGUSR2 arrives, we send any outstanding logs up to the
801                          * shutdown checkpoint record (i.e., the latest record) and exit.
802                          * This may be a normal termination at shutdown, or a promotion,
803                          * the walsender is not sure which.
804                          */
805                         if (walsender_ready_to_stop)
806                         {
807                                 /* ... let's just be real sure we're caught up ... */
808                                 XLogSend(output_message, &caughtup);
809                                 if (caughtup && !pq_is_send_pending())
810                                 {
811                                         walsender_shutdown_requested = true;
812                                         continue;               /* don't want to wait more */
813                                 }
814                         }
815                 }
816
817                 /*
818                  * We don't block if not caught up, unless there is unsent data
819                  * pending in which case we'd better block until the socket is
820                  * write-ready.  This test is only needed for the case where XLogSend
821                  * loaded a subset of the available data but then pq_flush_if_writable
822                  * flushed it all --- we should immediately try to send more.
823                  */
824                 if (caughtup || pq_is_send_pending())
825                 {
826                         TimestampTz finish_time = 0;
827                         long            sleeptime = -1;
828                         int                     wakeEvents;
829
830                         wakeEvents = WL_LATCH_SET | WL_POSTMASTER_DEATH |
831                                 WL_SOCKET_READABLE;
832                         if (pq_is_send_pending())
833                                 wakeEvents |= WL_SOCKET_WRITEABLE;
834
835                         /* Determine time until replication timeout */
836                         if (replication_timeout > 0)
837                         {
838                                 long            secs;
839                                 int                     usecs;
840
841                                 finish_time = TimestampTzPlusMilliseconds(last_reply_timestamp,
842                                                                                                                   replication_timeout);
843                                 TimestampDifference(GetCurrentTimestamp(),
844                                                                         finish_time, &secs, &usecs);
845                                 sleeptime = secs * 1000 + usecs / 1000;
846                                 /* Avoid Assert in WaitLatchOrSocket if timeout is past */
847                                 if (sleeptime < 0)
848                                         sleeptime = 0;
849                                 wakeEvents |= WL_TIMEOUT;
850                         }
851
852                         /* Sleep until something happens or replication timeout */
853                         WaitLatchOrSocket(&MyWalSnd->latch, wakeEvents,
854                                                           MyProcPort->sock, sleeptime);
855
856                         /*
857                          * Check for replication timeout.  Note we ignore the corner case
858                          * possibility that the client replied just as we reached the
859                          * timeout ... he's supposed to reply *before* that.
860                          */
861                         if (replication_timeout > 0 &&
862                                 GetCurrentTimestamp() >= finish_time)
863                         {
864                                 /*
865                                  * Since typically expiration of replication timeout means
866                                  * communication problem, we don't send the error message to
867                                  * the standby.
868                                  */
869                                 ereport(COMMERROR,
870                                                 (errmsg("terminating walsender process due to replication timeout")));
871                                 break;
872                         }
873                 }
874         }
875
876         /*
877          * Get here on send failure.  Clean up and exit.
878          *
879          * Reset whereToSendOutput to prevent ereport from attempting to send any
880          * more messages to the standby.
881          */
882         if (whereToSendOutput == DestRemote)
883                 whereToSendOutput = DestNone;
884
885         proc_exit(0);
886         return 1;                                       /* keep the compiler quiet */
887 }
888
889 /* Initialize a per-walsender data structure for this walsender process */
890 static void
891 InitWalSnd(void)
892 {
893         int                     i;
894
895         /*
896          * WalSndCtl should be set up already (we inherit this by fork() or
897          * EXEC_BACKEND mechanism from the postmaster).
898          */
899         Assert(WalSndCtl != NULL);
900         Assert(MyWalSnd == NULL);
901
902         /*
903          * Find a free walsender slot and reserve it. If this fails, we must be
904          * out of WalSnd structures.
905          */
906         for (i = 0; i < max_wal_senders; i++)
907         {
908                 /* use volatile pointer to prevent code rearrangement */
909                 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
910
911                 SpinLockAcquire(&walsnd->mutex);
912
913                 if (walsnd->pid != 0)
914                 {
915                         SpinLockRelease(&walsnd->mutex);
916                         continue;
917                 }
918                 else
919                 {
920                         /*
921                          * Found a free slot. Reserve it for us.
922                          */
923                         walsnd->pid = MyProcPid;
924                         MemSet(&walsnd->sentPtr, 0, sizeof(XLogRecPtr));
925                         walsnd->state = WALSNDSTATE_STARTUP;
926                         SpinLockRelease(&walsnd->mutex);
927                         /* don't need the lock anymore */
928                         OwnLatch((Latch *) &walsnd->latch);
929                         MyWalSnd = (WalSnd *) walsnd;
930
931                         break;
932                 }
933         }
934         if (MyWalSnd == NULL)
935                 ereport(FATAL,
936                                 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
937                                  errmsg("number of requested standby connections "
938                                                 "exceeds max_wal_senders (currently %d)",
939                                                 max_wal_senders)));
940
941         /* Arrange to clean up at walsender exit */
942         on_shmem_exit(WalSndKill, 0);
943 }
944
945 /* Destroy the per-walsender data structure for this walsender process */
946 static void
947 WalSndKill(int code, Datum arg)
948 {
949         Assert(MyWalSnd != NULL);
950
951         /*
952          * Mark WalSnd struct no longer in use. Assume that no lock is required
953          * for this.
954          */
955         MyWalSnd->pid = 0;
956         DisownLatch(&MyWalSnd->latch);
957
958         /* WalSnd struct isn't mine anymore */
959         MyWalSnd = NULL;
960 }
961
962 /*
963  * Read 'count' bytes from WAL into 'buf', starting at location 'startptr'
964  *
965  * XXX probably this should be improved to suck data directly from the
966  * WAL buffers when possible.
967  *
968  * Will open, and keep open, one WAL segment stored in the global file
969  * descriptor sendFile. This means if XLogRead is used once, there will
970  * always be one descriptor left open until the process ends, but never
971  * more than one.
972  */
973 void
974 XLogRead(char *buf, XLogRecPtr startptr, Size count)
975 {
976         char               *p;
977         XLogRecPtr      recptr;
978         Size                    nbytes;
979         uint32          lastRemovedLog;
980         uint32          lastRemovedSeg;
981         uint32          log;
982         uint32          seg;
983
984 retry:
985         p = buf;
986         recptr = startptr;
987         nbytes = count;
988
989         while (nbytes > 0)
990         {
991                 uint32          startoff;
992                 int                     segbytes;
993                 int                     readbytes;
994
995                 startoff = recptr.xrecoff % XLogSegSize;
996
997                 if (sendFile < 0 || !XLByteInSeg(recptr, sendId, sendSeg))
998                 {
999                         char            path[MAXPGPATH];
1000
1001                         /* Switch to another logfile segment */
1002                         if (sendFile >= 0)
1003                                 close(sendFile);
1004
1005                         XLByteToSeg(recptr, sendId, sendSeg);
1006                         XLogFilePath(path, ThisTimeLineID, sendId, sendSeg);
1007
1008                         sendFile = BasicOpenFile(path, O_RDONLY | PG_BINARY, 0);
1009                         if (sendFile < 0)
1010                         {
1011                                 /*
1012                                  * If the file is not found, assume it's because the standby
1013                                  * asked for a too old WAL segment that has already been
1014                                  * removed or recycled.
1015                                  */
1016                                 if (errno == ENOENT)
1017                                 {
1018                                         char            filename[MAXFNAMELEN];
1019
1020                                         XLogFileName(filename, ThisTimeLineID, sendId, sendSeg);
1021                                         ereport(ERROR,
1022                                                         (errcode_for_file_access(),
1023                                                          errmsg("requested WAL segment %s has already been removed",
1024                                                                         filename)));
1025                                 }
1026                                 else
1027                                         ereport(ERROR,
1028                                                         (errcode_for_file_access(),
1029                                                          errmsg("could not open file \"%s\" (log file %u, segment %u): %m",
1030                                                                         path, sendId, sendSeg)));
1031                         }
1032                         sendOff = 0;
1033                 }
1034
1035                 /* Need to seek in the file? */
1036                 if (sendOff != startoff)
1037                 {
1038                         if (lseek(sendFile, (off_t) startoff, SEEK_SET) < 0)
1039                                 ereport(ERROR,
1040                                                 (errcode_for_file_access(),
1041                                                  errmsg("could not seek in log file %u, segment %u to offset %u: %m",
1042                                                                 sendId, sendSeg, startoff)));
1043                         sendOff = startoff;
1044                 }
1045
1046                 /* How many bytes are within this segment? */
1047                 if (nbytes > (XLogSegSize - startoff))
1048                         segbytes = XLogSegSize - startoff;
1049                 else
1050                         segbytes = nbytes;
1051
1052                 readbytes = read(sendFile, p, segbytes);
1053                 if (readbytes <= 0)
1054                         ereport(ERROR,
1055                                         (errcode_for_file_access(),
1056                         errmsg("could not read from log file %u, segment %u, offset %u, "
1057                                    "length %lu: %m",
1058                                    sendId, sendSeg, sendOff, (unsigned long) segbytes)));
1059
1060                 /* Update state for read */
1061                 XLByteAdvance(recptr, readbytes);
1062
1063                 sendOff += readbytes;
1064                 nbytes -= readbytes;
1065                 p += readbytes;
1066         }
1067
1068         /*
1069          * After reading into the buffer, check that what we read was valid. We do
1070          * this after reading, because even though the segment was present when we
1071          * opened it, it might get recycled or removed while we read it. The
1072          * read() succeeds in that case, but the data we tried to read might
1073          * already have been overwritten with new WAL records.
1074          */
1075         XLogGetLastRemoved(&lastRemovedLog, &lastRemovedSeg);
1076         XLByteToSeg(startptr, log, seg);
1077         if (log < lastRemovedLog ||
1078                 (log == lastRemovedLog && seg <= lastRemovedSeg))
1079         {
1080                 char            filename[MAXFNAMELEN];
1081
1082                 XLogFileName(filename, ThisTimeLineID, log, seg);
1083                 ereport(ERROR,
1084                                 (errcode_for_file_access(),
1085                                  errmsg("requested WAL segment %s has already been removed",
1086                                                 filename)));
1087         }
1088
1089         /*
1090          * During recovery, the currently-open WAL file might be replaced with
1091          * the file of the same name retrieved from archive. So we always need
1092          * to check what we read was valid after reading into the buffer. If it's
1093          * invalid, we try to open and read the file again.
1094          */
1095         if (am_cascading_walsender)
1096         {
1097                 /* use volatile pointer to prevent code rearrangement */
1098                 volatile WalSnd *walsnd = MyWalSnd;
1099                 bool            reload;
1100
1101                 SpinLockAcquire(&walsnd->mutex);
1102                 reload = walsnd->needreload;
1103                 walsnd->needreload = false;
1104                 SpinLockRelease(&walsnd->mutex);
1105
1106                 if (reload && sendFile >= 0)
1107                 {
1108                         close(sendFile);
1109                         sendFile = -1;
1110
1111                         goto retry;
1112                 }
1113         }
1114 }
1115
1116 /*
1117  * Read up to MAX_SEND_SIZE bytes of WAL that's been flushed to disk,
1118  * but not yet sent to the client, and buffer it in the libpq output
1119  * buffer.
1120  *
1121  * msgbuf is a work area in which the output message is constructed.  It's
1122  * passed in just so we can avoid re-palloc'ing the buffer on each cycle.
1123  * It must be of size 1 + sizeof(WalDataMessageHeader) + MAX_SEND_SIZE.
1124  *
1125  * If there is no unsent WAL remaining, *caughtup is set to true, otherwise
1126  * *caughtup is set to false.
1127
1128  */
1129 static void
1130 XLogSend(char *msgbuf, bool *caughtup)
1131 {
1132         XLogRecPtr      SendRqstPtr;
1133         XLogRecPtr      startptr;
1134         XLogRecPtr      endptr;
1135         Size            nbytes;
1136         WalDataMessageHeader msghdr;
1137
1138         /*
1139          * Attempt to send all data that's already been written out and fsync'd to
1140          * disk.  We cannot go further than what's been written out given the
1141          * current implementation of XLogRead().  And in any case it's unsafe to
1142          * send WAL that is not securely down to disk on the master: if the master
1143          * subsequently crashes and restarts, slaves must not have applied any WAL
1144          * that gets lost on the master.
1145          */
1146         SendRqstPtr = am_cascading_walsender ? GetStandbyFlushRecPtr() : GetFlushRecPtr();
1147
1148         /* Quick exit if nothing to do */
1149         if (XLByteLE(SendRqstPtr, sentPtr))
1150         {
1151                 *caughtup = true;
1152                 return;
1153         }
1154
1155         /*
1156          * Figure out how much to send in one message. If there's no more than
1157          * MAX_SEND_SIZE bytes to send, send everything. Otherwise send
1158          * MAX_SEND_SIZE bytes, but round back to logfile or page boundary.
1159          *
1160          * The rounding is not only for performance reasons. Walreceiver relies on
1161          * the fact that we never split a WAL record across two messages. Since a
1162          * long WAL record is split at page boundary into continuation records,
1163          * page boundary is always a safe cut-off point. We also assume that
1164          * SendRqstPtr never points to the middle of a WAL record.
1165          */
1166         startptr = sentPtr;
1167         if (startptr.xrecoff >= XLogFileSize)
1168         {
1169                 /*
1170                  * crossing a logid boundary, skip the non-existent last log segment
1171                  * in previous logical log file.
1172                  */
1173                 startptr.xlogid += 1;
1174                 startptr.xrecoff = 0;
1175         }
1176
1177         endptr = startptr;
1178         XLByteAdvance(endptr, MAX_SEND_SIZE);
1179         if (endptr.xlogid != startptr.xlogid)
1180         {
1181                 /* Don't cross a logfile boundary within one message */
1182                 Assert(endptr.xlogid == startptr.xlogid + 1);
1183                 endptr.xlogid = startptr.xlogid;
1184                 endptr.xrecoff = XLogFileSize;
1185         }
1186
1187         /* if we went beyond SendRqstPtr, back off */
1188         if (XLByteLE(SendRqstPtr, endptr))
1189         {
1190                 endptr = SendRqstPtr;
1191                 *caughtup = true;
1192         }
1193         else
1194         {
1195                 /* round down to page boundary. */
1196                 endptr.xrecoff -= (endptr.xrecoff % XLOG_BLCKSZ);
1197                 *caughtup = false;
1198         }
1199
1200         nbytes = endptr.xrecoff - startptr.xrecoff;
1201         Assert(nbytes <= MAX_SEND_SIZE);
1202
1203         /*
1204          * OK to read and send the slice.
1205          */
1206         msgbuf[0] = 'w';
1207
1208         /*
1209          * Read the log directly into the output buffer to avoid extra memcpy
1210          * calls.
1211          */
1212         XLogRead(msgbuf + 1 + sizeof(WalDataMessageHeader), startptr, nbytes);
1213
1214         /*
1215          * We fill the message header last so that the send timestamp is taken as
1216          * late as possible.
1217          */
1218         msghdr.dataStart = startptr;
1219         msghdr.walEnd = SendRqstPtr;
1220         msghdr.sendTime = GetCurrentTimestamp();
1221
1222         memcpy(msgbuf + 1, &msghdr, sizeof(WalDataMessageHeader));
1223
1224         pq_putmessage_noblock('d', msgbuf, 1 + sizeof(WalDataMessageHeader) + nbytes);
1225
1226         sentPtr = endptr;
1227
1228         /* Update shared memory status */
1229         {
1230                 /* use volatile pointer to prevent code rearrangement */
1231                 volatile WalSnd *walsnd = MyWalSnd;
1232
1233                 SpinLockAcquire(&walsnd->mutex);
1234                 walsnd->sentPtr = sentPtr;
1235                 SpinLockRelease(&walsnd->mutex);
1236         }
1237
1238         /* Report progress of XLOG streaming in PS display */
1239         if (update_process_title)
1240         {
1241                 char            activitymsg[50];
1242
1243                 snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%X",
1244                                  sentPtr.xlogid, sentPtr.xrecoff);
1245                 set_ps_display(activitymsg, false);
1246         }
1247
1248         return;
1249 }
1250
1251 /*
1252  * Request walsenders to reload the currently-open WAL file
1253  */
1254 void
1255 WalSndRqstFileReload(void)
1256 {
1257         int                     i;
1258
1259         for (i = 0; i < max_wal_senders; i++)
1260         {
1261                 /* use volatile pointer to prevent code rearrangement */
1262                 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1263
1264                 if (walsnd->pid == 0)
1265                         continue;
1266
1267                 SpinLockAcquire(&walsnd->mutex);
1268                 walsnd->needreload = true;
1269                 SpinLockRelease(&walsnd->mutex);
1270         }
1271 }
1272
1273 /* SIGHUP: set flag to re-read config file at next convenient time */
1274 static void
1275 WalSndSigHupHandler(SIGNAL_ARGS)
1276 {
1277         int                     save_errno = errno;
1278
1279         got_SIGHUP = true;
1280         if (MyWalSnd)
1281                 SetLatch(&MyWalSnd->latch);
1282
1283         errno = save_errno;
1284 }
1285
1286 /* SIGTERM: set flag to shut down */
1287 static void
1288 WalSndShutdownHandler(SIGNAL_ARGS)
1289 {
1290         int                     save_errno = errno;
1291
1292         walsender_shutdown_requested = true;
1293         if (MyWalSnd)
1294                 SetLatch(&MyWalSnd->latch);
1295
1296         /*
1297          * Set the standard (non-walsender) state as well, so that we can
1298          * abort things like do_pg_stop_backup().
1299          */
1300         InterruptPending = true;
1301         ProcDiePending = true;
1302
1303         errno = save_errno;
1304 }
1305
1306 /*
1307  * WalSndQuickDieHandler() occurs when signalled SIGQUIT by the postmaster.
1308  *
1309  * Some backend has bought the farm,
1310  * so we need to stop what we're doing and exit.
1311  */
1312 static void
1313 WalSndQuickDieHandler(SIGNAL_ARGS)
1314 {
1315         PG_SETMASK(&BlockSig);
1316
1317         /*
1318          * We DO NOT want to run proc_exit() callbacks -- we're here because
1319          * shared memory may be corrupted, so we don't want to try to clean up our
1320          * transaction.  Just nail the windows shut and get out of town.  Now that
1321          * there's an atexit callback to prevent third-party code from breaking
1322          * things by calling exit() directly, we have to reset the callbacks
1323          * explicitly to make this work as intended.
1324          */
1325         on_exit_reset();
1326
1327         /*
1328          * Note we do exit(2) not exit(0).      This is to force the postmaster into a
1329          * system reset cycle if some idiot DBA sends a manual SIGQUIT to a random
1330          * backend.  This is necessary precisely because we don't clean up our
1331          * shared memory state.  (The "dead man switch" mechanism in pmsignal.c
1332          * should ensure the postmaster sees this as a crash, too, but no harm in
1333          * being doubly sure.)
1334          */
1335         exit(2);
1336 }
1337
1338 /* SIGUSR1: set flag to send WAL records */
1339 static void
1340 WalSndXLogSendHandler(SIGNAL_ARGS)
1341 {
1342         int                     save_errno = errno;
1343
1344         latch_sigusr1_handler();
1345
1346         errno = save_errno;
1347 }
1348
1349 /* SIGUSR2: set flag to do a last cycle and shut down afterwards */
1350 static void
1351 WalSndLastCycleHandler(SIGNAL_ARGS)
1352 {
1353         int                     save_errno = errno;
1354
1355         walsender_ready_to_stop = true;
1356         if (MyWalSnd)
1357                 SetLatch(&MyWalSnd->latch);
1358
1359         errno = save_errno;
1360 }
1361
1362 /* Set up signal handlers */
1363 void
1364 WalSndSignals(void)
1365 {
1366         /* Set up signal handlers */
1367         pqsignal(SIGHUP, WalSndSigHupHandler);          /* set flag to read config
1368                                                                                                  * file */
1369         pqsignal(SIGINT, SIG_IGN);      /* not used */
1370         pqsignal(SIGTERM, WalSndShutdownHandler);       /* request shutdown */
1371         pqsignal(SIGQUIT, WalSndQuickDieHandler);       /* hard crash time */
1372         pqsignal(SIGALRM, SIG_IGN);
1373         pqsignal(SIGPIPE, SIG_IGN);
1374         pqsignal(SIGUSR1, WalSndXLogSendHandler);       /* request WAL sending */
1375         pqsignal(SIGUSR2, WalSndLastCycleHandler);      /* request a last cycle and
1376                                                                                                  * shutdown */
1377
1378         /* Reset some signals that are accepted by postmaster but not here */
1379         pqsignal(SIGCHLD, SIG_DFL);
1380         pqsignal(SIGTTIN, SIG_DFL);
1381         pqsignal(SIGTTOU, SIG_DFL);
1382         pqsignal(SIGCONT, SIG_DFL);
1383         pqsignal(SIGWINCH, SIG_DFL);
1384 }
1385
1386 /* Report shared-memory space needed by WalSndShmemInit */
1387 Size
1388 WalSndShmemSize(void)
1389 {
1390         Size            size = 0;
1391
1392         size = offsetof(WalSndCtlData, walsnds);
1393         size = add_size(size, mul_size(max_wal_senders, sizeof(WalSnd)));
1394
1395         return size;
1396 }
1397
1398 /* Allocate and initialize walsender-related shared memory */
1399 void
1400 WalSndShmemInit(void)
1401 {
1402         bool            found;
1403         int                     i;
1404
1405         WalSndCtl = (WalSndCtlData *)
1406                 ShmemInitStruct("Wal Sender Ctl", WalSndShmemSize(), &found);
1407
1408         if (!found)
1409         {
1410                 /* First time through, so initialize */
1411                 MemSet(WalSndCtl, 0, WalSndShmemSize());
1412
1413                 SHMQueueInit(&(WalSndCtl->SyncRepQueue));
1414
1415                 for (i = 0; i < max_wal_senders; i++)
1416                 {
1417                         WalSnd     *walsnd = &WalSndCtl->walsnds[i];
1418
1419                         SpinLockInit(&walsnd->mutex);
1420                         InitSharedLatch(&walsnd->latch);
1421                 }
1422         }
1423 }
1424
1425 /* Wake up all walsenders */
1426 void
1427 WalSndWakeup(void)
1428 {
1429         int                     i;
1430
1431         for (i = 0; i < max_wal_senders; i++)
1432                 SetLatch(&WalSndCtl->walsnds[i].latch);
1433 }
1434
1435 /* Set state for current walsender (only called in walsender) */
1436 void
1437 WalSndSetState(WalSndState state)
1438 {
1439         /* use volatile pointer to prevent code rearrangement */
1440         volatile WalSnd *walsnd = MyWalSnd;
1441
1442         Assert(am_walsender);
1443
1444         if (walsnd->state == state)
1445                 return;
1446
1447         SpinLockAcquire(&walsnd->mutex);
1448         walsnd->state = state;
1449         SpinLockRelease(&walsnd->mutex);
1450 }
1451
1452 /*
1453  * Return a string constant representing the state. This is used
1454  * in system views, and should *not* be translated.
1455  */
1456 static const char *
1457 WalSndGetStateString(WalSndState state)
1458 {
1459         switch (state)
1460         {
1461                 case WALSNDSTATE_STARTUP:
1462                         return "startup";
1463                 case WALSNDSTATE_BACKUP:
1464                         return "backup";
1465                 case WALSNDSTATE_CATCHUP:
1466                         return "catchup";
1467                 case WALSNDSTATE_STREAMING:
1468                         return "streaming";
1469         }
1470         return "UNKNOWN";
1471 }
1472
1473
1474 /*
1475  * Returns activity of walsenders, including pids and xlog locations sent to
1476  * standby servers.
1477  */
1478 Datum
1479 pg_stat_get_wal_senders(PG_FUNCTION_ARGS)
1480 {
1481 #define PG_STAT_GET_WAL_SENDERS_COLS    8
1482         ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1483         TupleDesc       tupdesc;
1484         Tuplestorestate *tupstore;
1485         MemoryContext per_query_ctx;
1486         MemoryContext oldcontext;
1487         int                *sync_priority;
1488         int                     priority = 0;
1489         int                     sync_standby = -1;
1490         int                     i;
1491
1492         /* check to see if caller supports us returning a tuplestore */
1493         if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
1494                 ereport(ERROR,
1495                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1496                                  errmsg("set-valued function called in context that cannot accept a set")));
1497         if (!(rsinfo->allowedModes & SFRM_Materialize))
1498                 ereport(ERROR,
1499                                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1500                                  errmsg("materialize mode required, but it is not " \
1501                                                 "allowed in this context")));
1502
1503         /* Build a tuple descriptor for our result type */
1504         if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1505                 elog(ERROR, "return type must be a row type");
1506
1507         per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1508         oldcontext = MemoryContextSwitchTo(per_query_ctx);
1509
1510         tupstore = tuplestore_begin_heap(true, false, work_mem);
1511         rsinfo->returnMode = SFRM_Materialize;
1512         rsinfo->setResult = tupstore;
1513         rsinfo->setDesc = tupdesc;
1514
1515         MemoryContextSwitchTo(oldcontext);
1516
1517         /*
1518          * Get the priorities of sync standbys all in one go, to minimise lock
1519          * acquisitions and to allow us to evaluate who is the current sync
1520          * standby. This code must match the code in SyncRepReleaseWaiters().
1521          */
1522         sync_priority = palloc(sizeof(int) * max_wal_senders);
1523         LWLockAcquire(SyncRepLock, LW_SHARED);
1524         for (i = 0; i < max_wal_senders; i++)
1525         {
1526                 /* use volatile pointer to prevent code rearrangement */
1527                 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1528
1529                 if (walsnd->pid != 0)
1530                 {
1531                         sync_priority[i] = walsnd->sync_standby_priority;
1532
1533                         if (walsnd->state == WALSNDSTATE_STREAMING &&
1534                                 walsnd->sync_standby_priority > 0 &&
1535                                 (priority == 0 ||
1536                                  priority > walsnd->sync_standby_priority))
1537                         {
1538                                 priority = walsnd->sync_standby_priority;
1539                                 sync_standby = i;
1540                         }
1541                 }
1542         }
1543         LWLockRelease(SyncRepLock);
1544
1545         for (i = 0; i < max_wal_senders; i++)
1546         {
1547                 /* use volatile pointer to prevent code rearrangement */
1548                 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1549                 char            location[MAXFNAMELEN];
1550                 XLogRecPtr      sentPtr;
1551                 XLogRecPtr      write;
1552                 XLogRecPtr      flush;
1553                 XLogRecPtr      apply;
1554                 WalSndState state;
1555                 Datum           values[PG_STAT_GET_WAL_SENDERS_COLS];
1556                 bool            nulls[PG_STAT_GET_WAL_SENDERS_COLS];
1557
1558                 if (walsnd->pid == 0)
1559                         continue;
1560
1561                 SpinLockAcquire(&walsnd->mutex);
1562                 sentPtr = walsnd->sentPtr;
1563                 state = walsnd->state;
1564                 write = walsnd->write;
1565                 flush = walsnd->flush;
1566                 apply = walsnd->apply;
1567                 SpinLockRelease(&walsnd->mutex);
1568
1569                 memset(nulls, 0, sizeof(nulls));
1570                 values[0] = Int32GetDatum(walsnd->pid);
1571
1572                 if (!superuser())
1573                 {
1574                         /*
1575                          * Only superusers can see details. Other users only get the pid
1576                          * value to know it's a walsender, but no details.
1577                          */
1578                         MemSet(&nulls[1], true, PG_STAT_GET_WAL_SENDERS_COLS - 1);
1579                 }
1580                 else
1581                 {
1582                         values[1] = CStringGetTextDatum(WalSndGetStateString(state));
1583
1584                         snprintf(location, sizeof(location), "%X/%X",
1585                                          sentPtr.xlogid, sentPtr.xrecoff);
1586                         values[2] = CStringGetTextDatum(location);
1587
1588                         if (write.xlogid == 0 && write.xrecoff == 0)
1589                                 nulls[3] = true;
1590                         snprintf(location, sizeof(location), "%X/%X",
1591                                          write.xlogid, write.xrecoff);
1592                         values[3] = CStringGetTextDatum(location);
1593
1594                         if (flush.xlogid == 0 && flush.xrecoff == 0)
1595                                 nulls[4] = true;
1596                         snprintf(location, sizeof(location), "%X/%X",
1597                                          flush.xlogid, flush.xrecoff);
1598                         values[4] = CStringGetTextDatum(location);
1599
1600                         if (apply.xlogid == 0 && apply.xrecoff == 0)
1601                                 nulls[5] = true;
1602                         snprintf(location, sizeof(location), "%X/%X",
1603                                          apply.xlogid, apply.xrecoff);
1604                         values[5] = CStringGetTextDatum(location);
1605
1606                         values[6] = Int32GetDatum(sync_priority[i]);
1607
1608                         /*
1609                          * More easily understood version of standby state. This is purely
1610                          * informational, not different from priority.
1611                          */
1612                         if (sync_priority[i] == 0)
1613                                 values[7] = CStringGetTextDatum("async");
1614                         else if (i == sync_standby)
1615                                 values[7] = CStringGetTextDatum("sync");
1616                         else
1617                                 values[7] = CStringGetTextDatum("potential");
1618                 }
1619
1620                 tuplestore_putvalues(tupstore, tupdesc, values, nulls);
1621         }
1622         pfree(sync_priority);
1623
1624         /* clean up and return the tuplestore */
1625         tuplestore_donestoring(tupstore);
1626
1627         return (Datum) 0;
1628 }
1629
1630 /*
1631  * This isn't currently used for anything. Monitoring tools might be
1632  * interested in the future, and we'll need something like this in the
1633  * future for synchronous replication.
1634  */
1635 #ifdef NOT_USED
1636 /*
1637  * Returns the oldest Send position among walsenders. Or InvalidXLogRecPtr
1638  * if none.
1639  */
1640 XLogRecPtr
1641 GetOldestWALSendPointer(void)
1642 {
1643         XLogRecPtr      oldest = {0, 0};
1644         int                     i;
1645         bool            found = false;
1646
1647         for (i = 0; i < max_wal_senders; i++)
1648         {
1649                 /* use volatile pointer to prevent code rearrangement */
1650                 volatile WalSnd *walsnd = &WalSndCtl->walsnds[i];
1651                 XLogRecPtr      recptr;
1652
1653                 if (walsnd->pid == 0)
1654                         continue;
1655
1656                 SpinLockAcquire(&walsnd->mutex);
1657                 recptr = walsnd->sentPtr;
1658                 SpinLockRelease(&walsnd->mutex);
1659
1660                 if (recptr.xlogid == 0 && recptr.xrecoff == 0)
1661                         continue;
1662
1663                 if (!found || XLByteLT(recptr, oldest))
1664                         oldest = recptr;
1665                 found = true;
1666         }
1667         return oldest;
1668 }
1669
1670 #endif