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