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