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