LCOV - code coverage report
Current view: top level - src/backend/replication - walreceiver.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13beta1 Lines: 355 493 72.0 %
Date: 2020-06-03 11:07:14 Functions: 14 16 87.5 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * walreceiver.c
       4             :  *
       5             :  * The WAL receiver process (walreceiver) is new as of Postgres 9.0. It
       6             :  * is the process in the standby server that takes charge of receiving
       7             :  * XLOG records from a primary server during streaming replication.
       8             :  *
       9             :  * When the startup process determines that it's time to start streaming,
      10             :  * it instructs postmaster to start walreceiver. Walreceiver first connects
      11             :  * to the primary server (it will be served by a walsender process
      12             :  * in the primary server), and then keeps receiving XLOG records and
      13             :  * writing them to the disk as long as the connection is alive. As XLOG
      14             :  * records are received and flushed to disk, it updates the
      15             :  * WalRcv->flushedUpto variable in shared memory, to inform the startup
      16             :  * process of how far it can proceed with XLOG replay.
      17             :  *
      18             :  * A WAL receiver cannot directly load GUC parameters used when establishing
      19             :  * its connection to the primary. Instead it relies on parameter values
      20             :  * that are passed down by the startup process when streaming is requested.
      21             :  * This applies, for example, to the replication slot and the connection
      22             :  * string to be used for the connection with the primary.
      23             :  *
      24             :  * If the primary server ends streaming, but doesn't disconnect, walreceiver
      25             :  * goes into "waiting" mode, and waits for the startup process to give new
      26             :  * instructions. The startup process will treat that the same as
      27             :  * disconnection, and will rescan the archive/pg_wal directory. But when the
      28             :  * startup process wants to try streaming replication again, it will just
      29             :  * nudge the existing walreceiver process that's waiting, instead of launching
      30             :  * a new one.
      31             :  *
      32             :  * Normal termination is by SIGTERM, which instructs the walreceiver to
      33             :  * exit(0). Emergency termination is by SIGQUIT; like any postmaster child
      34             :  * process, the walreceiver will simply abort and exit on SIGQUIT. A close
      35             :  * of the connection and a FATAL error are treated not as a crash but as
      36             :  * normal operation.
      37             :  *
      38             :  * This file contains the server-facing parts of walreceiver. The libpq-
      39             :  * specific parts are in the libpqwalreceiver module. It's loaded
      40             :  * dynamically to avoid linking the server with libpq.
      41             :  *
      42             :  * Portions Copyright (c) 2010-2020, PostgreSQL Global Development Group
      43             :  *
      44             :  *
      45             :  * IDENTIFICATION
      46             :  *    src/backend/replication/walreceiver.c
      47             :  *
      48             :  *-------------------------------------------------------------------------
      49             :  */
      50             : #include "postgres.h"
      51             : 
      52             : #include <unistd.h>
      53             : 
      54             : #include "access/htup_details.h"
      55             : #include "access/timeline.h"
      56             : #include "access/transam.h"
      57             : #include "access/xlog_internal.h"
      58             : #include "access/xlogarchive.h"
      59             : #include "catalog/pg_authid.h"
      60             : #include "catalog/pg_type.h"
      61             : #include "common/ip.h"
      62             : #include "funcapi.h"
      63             : #include "libpq/pqformat.h"
      64             : #include "libpq/pqsignal.h"
      65             : #include "miscadmin.h"
      66             : #include "pgstat.h"
      67             : #include "postmaster/interrupt.h"
      68             : #include "replication/walreceiver.h"
      69             : #include "replication/walsender.h"
      70             : #include "storage/ipc.h"
      71             : #include "storage/pmsignal.h"
      72             : #include "storage/procarray.h"
      73             : #include "storage/procsignal.h"
      74             : #include "utils/acl.h"
      75             : #include "utils/builtins.h"
      76             : #include "utils/guc.h"
      77             : #include "utils/pg_lsn.h"
      78             : #include "utils/ps_status.h"
      79             : #include "utils/resowner.h"
      80             : #include "utils/timestamp.h"
      81             : 
      82             : 
      83             : /*
      84             :  * GUC variables.  (Other variables that affect walreceiver are in xlog.c
      85             :  * because they're passed down from the startup process, for better
      86             :  * synchronization.)
      87             :  */
      88             : int         wal_receiver_status_interval;
      89             : int         wal_receiver_timeout;
      90             : bool        hot_standby_feedback;
      91             : 
      92             : /* libpqwalreceiver connection */
      93             : static WalReceiverConn *wrconn = NULL;
      94             : WalReceiverFunctionsType *WalReceiverFunctions = NULL;
      95             : 
      96             : #define NAPTIME_PER_CYCLE 100   /* max sleep time between cycles (100ms) */
      97             : 
      98             : /*
      99             :  * These variables are used similarly to openLogFile/SegNo,
     100             :  * but for walreceiver to write the XLOG. recvFileTLI is the TimeLineID
     101             :  * corresponding the filename of recvFile.
     102             :  */
     103             : static int  recvFile = -1;
     104             : static TimeLineID recvFileTLI = 0;
     105             : static XLogSegNo recvSegNo = 0;
     106             : 
     107             : /*
     108             :  * Flags set by interrupt handlers of walreceiver for later service in the
     109             :  * main loop.
     110             :  */
     111             : static volatile sig_atomic_t got_SIGHUP = false;
     112             : static volatile sig_atomic_t got_SIGTERM = false;
     113             : 
     114             : /*
     115             :  * LogstreamResult indicates the byte positions that we have already
     116             :  * written/fsynced.
     117             :  */
     118             : static struct
     119             : {
     120             :     XLogRecPtr  Write;          /* last byte + 1 written out in the standby */
     121             :     XLogRecPtr  Flush;          /* last byte + 1 flushed in the standby */
     122             : }           LogstreamResult;
     123             : 
     124             : static StringInfoData reply_message;
     125             : static StringInfoData incoming_message;
     126             : 
     127             : /* Prototypes for private functions */
     128             : static void WalRcvFetchTimeLineHistoryFiles(TimeLineID first, TimeLineID last);
     129             : static void WalRcvWaitForStartPosition(XLogRecPtr *startpoint, TimeLineID *startpointTLI);
     130             : static void WalRcvDie(int code, Datum arg);
     131             : static void XLogWalRcvProcessMsg(unsigned char type, char *buf, Size len);
     132             : static void XLogWalRcvWrite(char *buf, Size nbytes, XLogRecPtr recptr);
     133             : static void XLogWalRcvFlush(bool dying);
     134             : static void XLogWalRcvSendReply(bool force, bool requestReply);
     135             : static void XLogWalRcvSendHSFeedback(bool immed);
     136             : static void ProcessWalSndrMessage(XLogRecPtr walEnd, TimestampTz sendTime);
     137             : 
     138             : /* Signal handlers */
     139             : static void WalRcvSigHupHandler(SIGNAL_ARGS);
     140             : static void WalRcvShutdownHandler(SIGNAL_ARGS);
     141             : 
     142             : 
     143             : /*
     144             :  * Process any interrupts the walreceiver process may have received.
     145             :  * This should be called any time the process's latch has become set.
     146             :  *
     147             :  * Currently, only SIGTERM is of interest.  We can't just exit(1) within the
     148             :  * SIGTERM signal handler, because the signal might arrive in the middle of
     149             :  * some critical operation, like while we're holding a spinlock.  Instead, the
     150             :  * signal handler sets a flag variable as well as setting the process's latch.
     151             :  * We must check the flag (by calling ProcessWalRcvInterrupts) anytime the
     152             :  * latch has become set.  Operations that could block for a long time, such as
     153             :  * reading from a remote server, must pay attention to the latch too; see
     154             :  * libpqrcv_PQgetResult for example.
     155             :  */
     156             : void
     157        3444 : ProcessWalRcvInterrupts(void)
     158             : {
     159             :     /*
     160             :      * Although walreceiver interrupt handling doesn't use the same scheme as
     161             :      * regular backends, call CHECK_FOR_INTERRUPTS() to make sure we receive
     162             :      * any incoming signals on Win32, and also to make sure we process any
     163             :      * barrier events.
     164             :      */
     165        3444 :     CHECK_FOR_INTERRUPTS();
     166             : 
     167        3444 :     if (got_SIGTERM)
     168             :     {
     169          52 :         ereport(FATAL,
     170             :                 (errcode(ERRCODE_ADMIN_SHUTDOWN),
     171             :                  errmsg("terminating walreceiver process due to administrator command")));
     172             :     }
     173        3392 : }
     174             : 
     175             : 
     176             : /* Main entry point for walreceiver process */
     177             : void
     178         200 : WalReceiverMain(void)
     179             : {
     180             :     char        conninfo[MAXCONNINFO];
     181             :     char       *tmp_conninfo;
     182             :     char        slotname[NAMEDATALEN];
     183             :     bool        is_temp_slot;
     184             :     XLogRecPtr  startpoint;
     185             :     TimeLineID  startpointTLI;
     186             :     TimeLineID  primaryTLI;
     187             :     bool        first_stream;
     188         200 :     WalRcvData *walrcv = WalRcv;
     189             :     TimestampTz last_recv_timestamp;
     190             :     TimestampTz now;
     191             :     bool        ping_sent;
     192             :     char       *err;
     193         200 :     char       *sender_host = NULL;
     194         200 :     int         sender_port = 0;
     195             : 
     196             :     /*
     197             :      * WalRcv should be set up already (if we are a backend, we inherit this
     198             :      * by fork() or EXEC_BACKEND mechanism from the postmaster).
     199             :      */
     200             :     Assert(walrcv != NULL);
     201             : 
     202         200 :     now = GetCurrentTimestamp();
     203             : 
     204             :     /*
     205             :      * Mark walreceiver as running in shared memory.
     206             :      *
     207             :      * Do this as early as possible, so that if we fail later on, we'll set
     208             :      * state to STOPPED. If we die before this, the startup process will keep
     209             :      * waiting for us to start up, until it times out.
     210             :      */
     211         200 :     SpinLockAcquire(&walrcv->mutex);
     212             :     Assert(walrcv->pid == 0);
     213         200 :     switch (walrcv->walRcvState)
     214             :     {
     215           0 :         case WALRCV_STOPPING:
     216             :             /* If we've already been requested to stop, don't start up. */
     217           0 :             walrcv->walRcvState = WALRCV_STOPPED;
     218             :             /* fall through */
     219             : 
     220           8 :         case WALRCV_STOPPED:
     221           8 :             SpinLockRelease(&walrcv->mutex);
     222           8 :             proc_exit(1);
     223             :             break;
     224             : 
     225         192 :         case WALRCV_STARTING:
     226             :             /* The usual case */
     227         192 :             break;
     228             : 
     229           0 :         case WALRCV_WAITING:
     230             :         case WALRCV_STREAMING:
     231             :         case WALRCV_RESTARTING:
     232             :         default:
     233             :             /* Shouldn't happen */
     234           0 :             SpinLockRelease(&walrcv->mutex);
     235           0 :             elog(PANIC, "walreceiver still running according to shared memory state");
     236             :     }
     237             :     /* Advertise our PID so that the startup process can kill us */
     238         192 :     walrcv->pid = MyProcPid;
     239         192 :     walrcv->walRcvState = WALRCV_STREAMING;
     240             : 
     241             :     /* Fetch information required to start streaming */
     242         192 :     walrcv->ready_to_display = false;
     243         192 :     strlcpy(conninfo, (char *) walrcv->conninfo, MAXCONNINFO);
     244         192 :     strlcpy(slotname, (char *) walrcv->slotname, NAMEDATALEN);
     245         192 :     is_temp_slot = walrcv->is_temp_slot;
     246         192 :     startpoint = walrcv->receiveStart;
     247         192 :     startpointTLI = walrcv->receiveStartTLI;
     248             : 
     249             :     /*
     250             :      * At most one of is_temp_slot and slotname can be set; otherwise,
     251             :      * RequestXLogStreaming messed up.
     252             :      */
     253             :     Assert(!is_temp_slot || (slotname[0] == '\0'));
     254             : 
     255             :     /* Initialise to a sanish value */
     256         192 :     walrcv->lastMsgSendTime =
     257         192 :         walrcv->lastMsgReceiptTime = walrcv->latestWalEndTime = now;
     258             : 
     259             :     /* Report the latch to use to awaken this process */
     260         192 :     walrcv->latch = &MyProc->procLatch;
     261             : 
     262         192 :     SpinLockRelease(&walrcv->mutex);
     263             : 
     264         192 :     pg_atomic_init_u64(&WalRcv->writtenUpto, 0);
     265             : 
     266             :     /* Arrange to clean up at walreceiver exit */
     267         192 :     on_shmem_exit(WalRcvDie, 0);
     268             : 
     269             :     /* Properly accept or ignore signals the postmaster might send us */
     270         192 :     pqsignal(SIGHUP, WalRcvSigHupHandler);  /* set flag to read config file */
     271         192 :     pqsignal(SIGINT, SIG_IGN);
     272         192 :     pqsignal(SIGTERM, WalRcvShutdownHandler);   /* request shutdown */
     273         192 :     pqsignal(SIGQUIT, SignalHandlerForCrashExit);
     274         192 :     pqsignal(SIGALRM, SIG_IGN);
     275         192 :     pqsignal(SIGPIPE, SIG_IGN);
     276         192 :     pqsignal(SIGUSR1, procsignal_sigusr1_handler);
     277         192 :     pqsignal(SIGUSR2, SIG_IGN);
     278             : 
     279             :     /* Reset some signals that are accepted by postmaster but not here */
     280         192 :     pqsignal(SIGCHLD, SIG_DFL);
     281             : 
     282             :     /* We allow SIGQUIT (quickdie) at all times */
     283         192 :     sigdelset(&BlockSig, SIGQUIT);
     284             : 
     285             :     /* Load the libpq-specific functions */
     286         192 :     load_file("libpqwalreceiver", false);
     287         192 :     if (WalReceiverFunctions == NULL)
     288           0 :         elog(ERROR, "libpqwalreceiver didn't initialize correctly");
     289             : 
     290             :     /* Unblock signals (they were blocked when the postmaster forked us) */
     291         192 :     PG_SETMASK(&UnBlockSig);
     292             : 
     293             :     /* Establish the connection to the primary for XLOG streaming */
     294         192 :     wrconn = walrcv_connect(conninfo, false, cluster_name[0] ? cluster_name : "walreceiver", &err);
     295         192 :     if (!wrconn)
     296          72 :         ereport(ERROR,
     297             :                 (errmsg("could not connect to the primary server: %s", err)));
     298             : 
     299             :     /*
     300             :      * Save user-visible connection string.  This clobbers the original
     301             :      * conninfo, for security. Also save host and port of the sender server
     302             :      * this walreceiver is connected to.
     303             :      */
     304         120 :     tmp_conninfo = walrcv_get_conninfo(wrconn);
     305         120 :     walrcv_get_senderinfo(wrconn, &sender_host, &sender_port);
     306         120 :     SpinLockAcquire(&walrcv->mutex);
     307         120 :     memset(walrcv->conninfo, 0, MAXCONNINFO);
     308         120 :     if (tmp_conninfo)
     309         120 :         strlcpy((char *) walrcv->conninfo, tmp_conninfo, MAXCONNINFO);
     310             : 
     311         120 :     memset(walrcv->sender_host, 0, NI_MAXHOST);
     312         120 :     if (sender_host)
     313         120 :         strlcpy((char *) walrcv->sender_host, sender_host, NI_MAXHOST);
     314             : 
     315         120 :     walrcv->sender_port = sender_port;
     316         120 :     walrcv->ready_to_display = true;
     317         120 :     SpinLockRelease(&walrcv->mutex);
     318             : 
     319         120 :     if (tmp_conninfo)
     320         120 :         pfree(tmp_conninfo);
     321             : 
     322         120 :     if (sender_host)
     323         120 :         pfree(sender_host);
     324             : 
     325         120 :     first_stream = true;
     326             :     for (;;)
     327          10 :     {
     328             :         char       *primary_sysid;
     329             :         char        standby_sysid[32];
     330             :         WalRcvStreamOptions options;
     331             : 
     332             :         /*
     333             :          * Check that we're connected to a valid server using the
     334             :          * IDENTIFY_SYSTEM replication command.
     335             :          */
     336         130 :         primary_sysid = walrcv_identify_system(wrconn, &primaryTLI);
     337             : 
     338         130 :         snprintf(standby_sysid, sizeof(standby_sysid), UINT64_FORMAT,
     339             :                  GetSystemIdentifier());
     340         130 :         if (strcmp(primary_sysid, standby_sysid) != 0)
     341             :         {
     342           0 :             ereport(ERROR,
     343             :                     (errmsg("database system identifier differs between the primary and standby"),
     344             :                      errdetail("The primary's identifier is %s, the standby's identifier is %s.",
     345             :                                primary_sysid, standby_sysid)));
     346             :         }
     347             : 
     348             :         /*
     349             :          * Confirm that the current timeline of the primary is the same or
     350             :          * ahead of ours.
     351             :          */
     352         130 :         if (primaryTLI < startpointTLI)
     353           0 :             ereport(ERROR,
     354             :                     (errmsg("highest timeline %u of the primary is behind recovery timeline %u",
     355             :                             primaryTLI, startpointTLI)));
     356             : 
     357             :         /*
     358             :          * Get any missing history files. We do this always, even when we're
     359             :          * not interested in that timeline, so that if we're promoted to
     360             :          * become the master later on, we don't select the same timeline that
     361             :          * was already used in the current master. This isn't bullet-proof -
     362             :          * you'll need some external software to manage your cluster if you
     363             :          * need to ensure that a unique timeline id is chosen in every case,
     364             :          * but let's avoid the confusion of timeline id collisions where we
     365             :          * can.
     366             :          */
     367         130 :         WalRcvFetchTimeLineHistoryFiles(startpointTLI, primaryTLI);
     368             : 
     369             :         /*
     370             :          * Create temporary replication slot if requested, and update slot
     371             :          * name in shared memory.  (Note the slot name cannot already be set
     372             :          * in this case.)
     373             :          */
     374         130 :         if (is_temp_slot)
     375             :         {
     376           0 :             snprintf(slotname, sizeof(slotname),
     377             :                      "pg_walreceiver_%lld",
     378           0 :                      (long long int) walrcv_get_backend_pid(wrconn));
     379             : 
     380           0 :             walrcv_create_slot(wrconn, slotname, true, 0, NULL);
     381             : 
     382           0 :             SpinLockAcquire(&walrcv->mutex);
     383           0 :             strlcpy(walrcv->slotname, slotname, NAMEDATALEN);
     384           0 :             SpinLockRelease(&walrcv->mutex);
     385             :         }
     386             : 
     387             :         /*
     388             :          * Start streaming.
     389             :          *
     390             :          * We'll try to start at the requested starting point and timeline,
     391             :          * even if it's different from the server's latest timeline. In case
     392             :          * we've already reached the end of the old timeline, the server will
     393             :          * finish the streaming immediately, and we will go back to await
     394             :          * orders from the startup process. If recovery_target_timeline is
     395             :          * 'latest', the startup process will scan pg_wal and find the new
     396             :          * history file, bump recovery target timeline, and ask us to restart
     397             :          * on the new timeline.
     398             :          */
     399         130 :         options.logical = false;
     400         130 :         options.startpoint = startpoint;
     401         130 :         options.slotname = slotname[0] != '\0' ? slotname : NULL;
     402         130 :         options.proto.physical.startpointTLI = startpointTLI;
     403         130 :         ThisTimeLineID = startpointTLI;
     404         130 :         if (walrcv_startstreaming(wrconn, &options))
     405             :         {
     406         130 :             if (first_stream)
     407         120 :                 ereport(LOG,
     408             :                         (errmsg("started streaming WAL from primary at %X/%X on timeline %u",
     409             :                                 (uint32) (startpoint >> 32), (uint32) startpoint,
     410             :                                 startpointTLI)));
     411             :             else
     412          10 :                 ereport(LOG,
     413             :                         (errmsg("restarted WAL streaming at %X/%X on timeline %u",
     414             :                                 (uint32) (startpoint >> 32), (uint32) startpoint,
     415             :                                 startpointTLI)));
     416         130 :             first_stream = false;
     417             : 
     418             :             /* Initialize LogstreamResult and buffers for processing messages */
     419         130 :             LogstreamResult.Write = LogstreamResult.Flush = GetXLogReplayRecPtr(NULL);
     420         130 :             initStringInfo(&reply_message);
     421         130 :             initStringInfo(&incoming_message);
     422             : 
     423             :             /* Initialize the last recv timestamp */
     424         130 :             last_recv_timestamp = GetCurrentTimestamp();
     425         130 :             ping_sent = false;
     426             : 
     427             :             /* Loop until end-of-streaming or error */
     428             :             for (;;)
     429        2052 :             {
     430             :                 char       *buf;
     431             :                 int         len;
     432        2182 :                 bool        endofwal = false;
     433        2182 :                 pgsocket    wait_fd = PGINVALID_SOCKET;
     434             :                 int         rc;
     435             : 
     436             :                 /*
     437             :                  * Exit walreceiver if we're not in recovery. This should not
     438             :                  * happen, but cross-check the status here.
     439             :                  */
     440        2182 :                 if (!RecoveryInProgress())
     441           0 :                     ereport(FATAL,
     442             :                             (errmsg("cannot continue WAL streaming, recovery has already ended")));
     443             : 
     444             :                 /* Process any requests or signals received recently */
     445        2182 :                 ProcessWalRcvInterrupts();
     446             : 
     447        2182 :                 if (got_SIGHUP)
     448             :                 {
     449          10 :                     got_SIGHUP = false;
     450          10 :                     ProcessConfigFile(PGC_SIGHUP);
     451          10 :                     XLogWalRcvSendHSFeedback(true);
     452             :                 }
     453             : 
     454             :                 /* See if we can read data immediately */
     455        2182 :                 len = walrcv_receive(wrconn, &buf, &wait_fd);
     456        2144 :                 if (len != 0)
     457             :                 {
     458             :                     /*
     459             :                      * Process the received data, and any subsequent data we
     460             :                      * can read without blocking.
     461             :                      */
     462             :                     for (;;)
     463             :                     {
     464        1684 :                         if (len > 0)
     465             :                         {
     466             :                             /*
     467             :                              * Something was received from master, so reset
     468             :                              * timeout
     469             :                              */
     470        1056 :                             last_recv_timestamp = GetCurrentTimestamp();
     471        1056 :                             ping_sent = false;
     472        1056 :                             XLogWalRcvProcessMsg(buf[0], &buf[1], len - 1);
     473             :                         }
     474         628 :                         else if (len == 0)
     475         590 :                             break;
     476          38 :                         else if (len < 0)
     477             :                         {
     478          38 :                             ereport(LOG,
     479             :                                     (errmsg("replication terminated by primary server"),
     480             :                                      errdetail("End of WAL reached on timeline %u at %X/%X.",
     481             :                                                startpointTLI,
     482             :                                                (uint32) (LogstreamResult.Write >> 32), (uint32) LogstreamResult.Write)));
     483          38 :                             endofwal = true;
     484          38 :                             break;
     485             :                         }
     486        1056 :                         len = walrcv_receive(wrconn, &buf, &wait_fd);
     487             :                     }
     488             : 
     489             :                     /* Let the master know that we received some data. */
     490         628 :                     XLogWalRcvSendReply(false, false);
     491             : 
     492             :                     /*
     493             :                      * If we've written some records, flush them to disk and
     494             :                      * let the startup process and primary server know about
     495             :                      * them.
     496             :                      */
     497         628 :                     XLogWalRcvFlush(false);
     498             :                 }
     499             : 
     500             :                 /* Check if we need to exit the streaming loop. */
     501        2142 :                 if (endofwal)
     502          38 :                     break;
     503             : 
     504             :                 /*
     505             :                  * Ideally we would reuse a WaitEventSet object repeatedly
     506             :                  * here to avoid the overheads of WaitLatchOrSocket on epoll
     507             :                  * systems, but we can't be sure that libpq (or any other
     508             :                  * walreceiver implementation) has the same socket (even if
     509             :                  * the fd is the same number, it may have been closed and
     510             :                  * reopened since the last time).  In future, if there is a
     511             :                  * function for removing sockets from WaitEventSet, then we
     512             :                  * could add and remove just the socket each time, potentially
     513             :                  * avoiding some system calls.
     514             :                  */
     515             :                 Assert(wait_fd != PGINVALID_SOCKET);
     516        2104 :                 rc = WaitLatchOrSocket(walrcv->latch,
     517             :                                        WL_EXIT_ON_PM_DEATH | WL_SOCKET_READABLE |
     518             :                                        WL_TIMEOUT | WL_LATCH_SET,
     519             :                                        wait_fd,
     520             :                                        NAPTIME_PER_CYCLE,
     521             :                                        WAIT_EVENT_WAL_RECEIVER_MAIN);
     522        2104 :                 if (rc & WL_LATCH_SET)
     523             :                 {
     524         558 :                     ResetLatch(walrcv->latch);
     525         558 :                     ProcessWalRcvInterrupts();
     526             : 
     527         506 :                     if (walrcv->force_reply)
     528             :                     {
     529             :                         /*
     530             :                          * The recovery process has asked us to send apply
     531             :                          * feedback now.  Make sure the flag is really set to
     532             :                          * false in shared memory before sending the reply, so
     533             :                          * we don't miss a new request for a reply.
     534             :                          */
     535         506 :                         walrcv->force_reply = false;
     536         506 :                         pg_memory_barrier();
     537         506 :                         XLogWalRcvSendReply(true, false);
     538             :                     }
     539             :                 }
     540        2052 :                 if (rc & WL_TIMEOUT)
     541             :                 {
     542             :                     /*
     543             :                      * We didn't receive anything new. If we haven't heard
     544             :                      * anything from the server for more than
     545             :                      * wal_receiver_timeout / 2, ping the server. Also, if
     546             :                      * it's been longer than wal_receiver_status_interval
     547             :                      * since the last update we sent, send a status update to
     548             :                      * the master anyway, to report any progress in applying
     549             :                      * WAL.
     550             :                      */
     551         698 :                     bool        requestReply = false;
     552             : 
     553             :                     /*
     554             :                      * Check if time since last receive from standby has
     555             :                      * reached the configured limit.
     556             :                      */
     557         698 :                     if (wal_receiver_timeout > 0)
     558             :                     {
     559         698 :                         TimestampTz now = GetCurrentTimestamp();
     560             :                         TimestampTz timeout;
     561             : 
     562         698 :                         timeout =
     563         698 :                             TimestampTzPlusMilliseconds(last_recv_timestamp,
     564             :                                                         wal_receiver_timeout);
     565             : 
     566         698 :                         if (now >= timeout)
     567           0 :                             ereport(ERROR,
     568             :                                     (errmsg("terminating walreceiver due to timeout")));
     569             : 
     570             :                         /*
     571             :                          * We didn't receive anything new, for half of
     572             :                          * receiver replication timeout. Ping the server.
     573             :                          */
     574         698 :                         if (!ping_sent)
     575             :                         {
     576         698 :                             timeout = TimestampTzPlusMilliseconds(last_recv_timestamp,
     577             :                                                                   (wal_receiver_timeout / 2));
     578         698 :                             if (now >= timeout)
     579             :                             {
     580           0 :                                 requestReply = true;
     581           0 :                                 ping_sent = true;
     582             :                             }
     583             :                         }
     584             :                     }
     585             : 
     586         698 :                     XLogWalRcvSendReply(requestReply, requestReply);
     587         698 :                     XLogWalRcvSendHSFeedback(false);
     588             :                 }
     589             :             }
     590             : 
     591             :             /*
     592             :              * The backend finished streaming. Exit streaming COPY-mode from
     593             :              * our side, too.
     594             :              */
     595          38 :             walrcv_endstreaming(wrconn, &primaryTLI);
     596             : 
     597             :             /*
     598             :              * If the server had switched to a new timeline that we didn't
     599             :              * know about when we began streaming, fetch its timeline history
     600             :              * file now.
     601             :              */
     602          10 :             WalRcvFetchTimeLineHistoryFiles(startpointTLI, primaryTLI);
     603             :         }
     604             :         else
     605           0 :             ereport(LOG,
     606             :                     (errmsg("primary server contains no more WAL on requested timeline %u",
     607             :                             startpointTLI)));
     608             : 
     609             :         /*
     610             :          * End of WAL reached on the requested timeline. Close the last
     611             :          * segment, and await for new orders from the startup process.
     612             :          */
     613          10 :         if (recvFile >= 0)
     614             :         {
     615             :             char        xlogfname[MAXFNAMELEN];
     616             : 
     617          10 :             XLogWalRcvFlush(false);
     618          10 :             XLogFileName(xlogfname, recvFileTLI, recvSegNo, wal_segment_size);
     619          10 :             if (close(recvFile) != 0)
     620           0 :                 ereport(PANIC,
     621             :                         (errcode_for_file_access(),
     622             :                          errmsg("could not close log segment %s: %m",
     623             :                                 xlogfname)));
     624             : 
     625             :             /*
     626             :              * Create .done file forcibly to prevent the streamed segment from
     627             :              * being archived later.
     628             :              */
     629          10 :             if (XLogArchiveMode != ARCHIVE_MODE_ALWAYS)
     630          10 :                 XLogArchiveForceDone(xlogfname);
     631             :             else
     632           0 :                 XLogArchiveNotify(xlogfname);
     633             :         }
     634          10 :         recvFile = -1;
     635             : 
     636          10 :         elog(DEBUG1, "walreceiver ended streaming and awaits new instructions");
     637          10 :         WalRcvWaitForStartPosition(&startpoint, &startpointTLI);
     638             :     }
     639             :     /* not reached */
     640             : }
     641             : 
     642             : /*
     643             :  * Wait for startup process to set receiveStart and receiveStartTLI.
     644             :  */
     645             : static void
     646          10 : WalRcvWaitForStartPosition(XLogRecPtr *startpoint, TimeLineID *startpointTLI)
     647             : {
     648          10 :     WalRcvData *walrcv = WalRcv;
     649             :     int         state;
     650             : 
     651          10 :     SpinLockAcquire(&walrcv->mutex);
     652          10 :     state = walrcv->walRcvState;
     653          10 :     if (state != WALRCV_STREAMING)
     654             :     {
     655           0 :         SpinLockRelease(&walrcv->mutex);
     656           0 :         if (state == WALRCV_STOPPING)
     657           0 :             proc_exit(0);
     658             :         else
     659           0 :             elog(FATAL, "unexpected walreceiver state");
     660             :     }
     661          10 :     walrcv->walRcvState = WALRCV_WAITING;
     662          10 :     walrcv->receiveStart = InvalidXLogRecPtr;
     663          10 :     walrcv->receiveStartTLI = 0;
     664          10 :     SpinLockRelease(&walrcv->mutex);
     665             : 
     666          10 :     set_ps_display("idle");
     667             : 
     668             :     /*
     669             :      * nudge startup process to notice that we've stopped streaming and are
     670             :      * now waiting for instructions.
     671             :      */
     672          10 :     WakeupRecovery();
     673             :     for (;;)
     674             :     {
     675          20 :         ResetLatch(walrcv->latch);
     676             : 
     677          20 :         ProcessWalRcvInterrupts();
     678             : 
     679          20 :         SpinLockAcquire(&walrcv->mutex);
     680             :         Assert(walrcv->walRcvState == WALRCV_RESTARTING ||
     681             :                walrcv->walRcvState == WALRCV_WAITING ||
     682             :                walrcv->walRcvState == WALRCV_STOPPING);
     683          20 :         if (walrcv->walRcvState == WALRCV_RESTARTING)
     684             :         {
     685             :             /*
     686             :              * No need to handle changes in primary_conninfo or
     687             :              * primary_slotname here. Startup process will signal us to
     688             :              * terminate in case those change.
     689             :              */
     690          10 :             *startpoint = walrcv->receiveStart;
     691          10 :             *startpointTLI = walrcv->receiveStartTLI;
     692          10 :             walrcv->walRcvState = WALRCV_STREAMING;
     693          10 :             SpinLockRelease(&walrcv->mutex);
     694          10 :             break;
     695             :         }
     696          10 :         if (walrcv->walRcvState == WALRCV_STOPPING)
     697             :         {
     698             :             /*
     699             :              * We should've received SIGTERM if the startup process wants us
     700             :              * to die, but might as well check it here too.
     701             :              */
     702           0 :             SpinLockRelease(&walrcv->mutex);
     703           0 :             exit(1);
     704             :         }
     705          10 :         SpinLockRelease(&walrcv->mutex);
     706             : 
     707          10 :         (void) WaitLatch(walrcv->latch, WL_LATCH_SET | WL_EXIT_ON_PM_DEATH, 0,
     708             :                          WAIT_EVENT_WAL_RECEIVER_WAIT_START);
     709             :     }
     710             : 
     711          10 :     if (update_process_title)
     712             :     {
     713             :         char        activitymsg[50];
     714             : 
     715          20 :         snprintf(activitymsg, sizeof(activitymsg), "restarting at %X/%X",
     716          10 :                  (uint32) (*startpoint >> 32),
     717          10 :                  (uint32) *startpoint);
     718          10 :         set_ps_display(activitymsg);
     719             :     }
     720          10 : }
     721             : 
     722             : /*
     723             :  * Fetch any missing timeline history files between 'first' and 'last'
     724             :  * (inclusive) from the server.
     725             :  */
     726             : static void
     727         140 : WalRcvFetchTimeLineHistoryFiles(TimeLineID first, TimeLineID last)
     728             : {
     729             :     TimeLineID  tli;
     730             : 
     731         300 :     for (tli = first; tli <= last; tli++)
     732             :     {
     733             :         /* there's no history file for timeline 1 */
     734         160 :         if (tli != 1 && !existsTimeLineHistory(tli))
     735             :         {
     736             :             char       *fname;
     737             :             char       *content;
     738             :             int         len;
     739             :             char        expectedfname[MAXFNAMELEN];
     740             : 
     741          10 :             ereport(LOG,
     742             :                     (errmsg("fetching timeline history file for timeline %u from primary server",
     743             :                             tli)));
     744             : 
     745          10 :             walrcv_readtimelinehistoryfile(wrconn, tli, &fname, &content, &len);
     746             : 
     747             :             /*
     748             :              * Check that the filename on the master matches what we
     749             :              * calculated ourselves. This is just a sanity check, it should
     750             :              * always match.
     751             :              */
     752          10 :             TLHistoryFileName(expectedfname, tli);
     753          10 :             if (strcmp(fname, expectedfname) != 0)
     754           0 :                 ereport(ERROR,
     755             :                         (errcode(ERRCODE_PROTOCOL_VIOLATION),
     756             :                          errmsg_internal("primary reported unexpected file name for timeline history file of timeline %u",
     757             :                                          tli)));
     758             : 
     759             :             /*
     760             :              * Write the file to pg_wal.
     761             :              */
     762          10 :             writeTimeLineHistoryFile(tli, content, len);
     763             : 
     764          10 :             pfree(fname);
     765          10 :             pfree(content);
     766             :         }
     767             :     }
     768         140 : }
     769             : 
     770             : /*
     771             :  * Mark us as STOPPED in shared memory at exit.
     772             :  */
     773             : static void
     774         192 : WalRcvDie(int code, Datum arg)
     775             : {
     776         192 :     WalRcvData *walrcv = WalRcv;
     777             : 
     778             :     /* Ensure that all WAL records received are flushed to disk */
     779         192 :     XLogWalRcvFlush(true);
     780             : 
     781             :     /* Mark ourselves inactive in shared memory */
     782         192 :     SpinLockAcquire(&walrcv->mutex);
     783             :     Assert(walrcv->walRcvState == WALRCV_STREAMING ||
     784             :            walrcv->walRcvState == WALRCV_RESTARTING ||
     785             :            walrcv->walRcvState == WALRCV_STARTING ||
     786             :            walrcv->walRcvState == WALRCV_WAITING ||
     787             :            walrcv->walRcvState == WALRCV_STOPPING);
     788             :     Assert(walrcv->pid == MyProcPid);
     789         192 :     walrcv->walRcvState = WALRCV_STOPPED;
     790         192 :     walrcv->pid = 0;
     791         192 :     walrcv->ready_to_display = false;
     792         192 :     walrcv->latch = NULL;
     793         192 :     SpinLockRelease(&walrcv->mutex);
     794             : 
     795             :     /* Terminate the connection gracefully. */
     796         192 :     if (wrconn != NULL)
     797         120 :         walrcv_disconnect(wrconn);
     798             : 
     799             :     /* Wake up the startup process to notice promptly that we're gone */
     800         192 :     WakeupRecovery();
     801         192 : }
     802             : 
     803             : /* SIGHUP: set flag to re-read config file at next convenient time */
     804             : static void
     805          12 : WalRcvSigHupHandler(SIGNAL_ARGS)
     806             : {
     807          12 :     got_SIGHUP = true;
     808          12 : }
     809             : 
     810             : 
     811             : /* SIGTERM: set flag for ProcessWalRcvInterrupts */
     812             : static void
     813          56 : WalRcvShutdownHandler(SIGNAL_ARGS)
     814             : {
     815          56 :     int         save_errno = errno;
     816             : 
     817          56 :     got_SIGTERM = true;
     818             : 
     819          56 :     if (WalRcv->latch)
     820          54 :         SetLatch(WalRcv->latch);
     821             : 
     822          56 :     errno = save_errno;
     823          56 : }
     824             : 
     825             : /*
     826             :  * Accept the message from XLOG stream, and process it.
     827             :  */
     828             : static void
     829        1056 : XLogWalRcvProcessMsg(unsigned char type, char *buf, Size len)
     830             : {
     831             :     int         hdrlen;
     832             :     XLogRecPtr  dataStart;
     833             :     XLogRecPtr  walEnd;
     834             :     TimestampTz sendTime;
     835             :     bool        replyRequested;
     836             : 
     837        1056 :     resetStringInfo(&incoming_message);
     838             : 
     839        1056 :     switch (type)
     840             :     {
     841        1056 :         case 'w':               /* WAL records */
     842             :             {
     843             :                 /* copy message to StringInfo */
     844        1056 :                 hdrlen = sizeof(int64) + sizeof(int64) + sizeof(int64);
     845        1056 :                 if (len < hdrlen)
     846           0 :                     ereport(ERROR,
     847             :                             (errcode(ERRCODE_PROTOCOL_VIOLATION),
     848             :                              errmsg_internal("invalid WAL message received from primary")));
     849        1056 :                 appendBinaryStringInfo(&incoming_message, buf, hdrlen);
     850             : 
     851             :                 /* read the fields */
     852        1056 :                 dataStart = pq_getmsgint64(&incoming_message);
     853        1056 :                 walEnd = pq_getmsgint64(&incoming_message);
     854        1056 :                 sendTime = pq_getmsgint64(&incoming_message);
     855        1056 :                 ProcessWalSndrMessage(walEnd, sendTime);
     856             : 
     857        1056 :                 buf += hdrlen;
     858        1056 :                 len -= hdrlen;
     859        1056 :                 XLogWalRcvWrite(buf, len, dataStart);
     860        1056 :                 break;
     861             :             }
     862           0 :         case 'k':               /* Keepalive */
     863             :             {
     864             :                 /* copy message to StringInfo */
     865           0 :                 hdrlen = sizeof(int64) + sizeof(int64) + sizeof(char);
     866           0 :                 if (len != hdrlen)
     867           0 :                     ereport(ERROR,
     868             :                             (errcode(ERRCODE_PROTOCOL_VIOLATION),
     869             :                              errmsg_internal("invalid keepalive message received from primary")));
     870           0 :                 appendBinaryStringInfo(&incoming_message, buf, hdrlen);
     871             : 
     872             :                 /* read the fields */
     873           0 :                 walEnd = pq_getmsgint64(&incoming_message);
     874           0 :                 sendTime = pq_getmsgint64(&incoming_message);
     875           0 :                 replyRequested = pq_getmsgbyte(&incoming_message);
     876             : 
     877           0 :                 ProcessWalSndrMessage(walEnd, sendTime);
     878             : 
     879             :                 /* If the primary requested a reply, send one immediately */
     880           0 :                 if (replyRequested)
     881           0 :                     XLogWalRcvSendReply(true, false);
     882           0 :                 break;
     883             :             }
     884           0 :         default:
     885           0 :             ereport(ERROR,
     886             :                     (errcode(ERRCODE_PROTOCOL_VIOLATION),
     887             :                      errmsg_internal("invalid replication message type %d",
     888             :                                      type)));
     889             :     }
     890        1056 : }
     891             : 
     892             : /*
     893             :  * Write XLOG data to disk.
     894             :  */
     895             : static void
     896        1056 : XLogWalRcvWrite(char *buf, Size nbytes, XLogRecPtr recptr)
     897             : {
     898             :     int         startoff;
     899             :     int         byteswritten;
     900             : 
     901        2112 :     while (nbytes > 0)
     902             :     {
     903             :         int         segbytes;
     904             : 
     905        1056 :         if (recvFile < 0 || !XLByteInSeg(recptr, recvSegNo, wal_segment_size))
     906             :         {
     907             :             bool        use_existent;
     908             : 
     909             :             /*
     910             :              * fsync() and close current file before we switch to next one. We
     911             :              * would otherwise have to reopen this file to fsync it later
     912             :              */
     913         136 :             if (recvFile >= 0)
     914             :             {
     915             :                 char        xlogfname[MAXFNAMELEN];
     916             : 
     917          38 :                 XLogWalRcvFlush(false);
     918             : 
     919          38 :                 XLogFileName(xlogfname, recvFileTLI, recvSegNo, wal_segment_size);
     920             : 
     921             :                 /*
     922             :                  * XLOG segment files will be re-read by recovery in startup
     923             :                  * process soon, so we don't advise the OS to release cache
     924             :                  * pages associated with the file like XLogFileClose() does.
     925             :                  */
     926          38 :                 if (close(recvFile) != 0)
     927           0 :                     ereport(PANIC,
     928             :                             (errcode_for_file_access(),
     929             :                              errmsg("could not close log segment %s: %m",
     930             :                                     xlogfname)));
     931             : 
     932             :                 /*
     933             :                  * Create .done file forcibly to prevent the streamed segment
     934             :                  * from being archived later.
     935             :                  */
     936          38 :                 if (XLogArchiveMode != ARCHIVE_MODE_ALWAYS)
     937          38 :                     XLogArchiveForceDone(xlogfname);
     938             :                 else
     939           0 :                     XLogArchiveNotify(xlogfname);
     940             :             }
     941         136 :             recvFile = -1;
     942             : 
     943             :             /* Create/use new log file */
     944         136 :             XLByteToSeg(recptr, recvSegNo, wal_segment_size);
     945         136 :             use_existent = true;
     946         136 :             recvFile = XLogFileInit(recvSegNo, &use_existent, true);
     947         136 :             recvFileTLI = ThisTimeLineID;
     948             :         }
     949             : 
     950             :         /* Calculate the start offset of the received logs */
     951        1056 :         startoff = XLogSegmentOffset(recptr, wal_segment_size);
     952             : 
     953        1056 :         if (startoff + nbytes > wal_segment_size)
     954           0 :             segbytes = wal_segment_size - startoff;
     955             :         else
     956        1056 :             segbytes = nbytes;
     957             : 
     958             :         /* OK to write the logs */
     959        1056 :         errno = 0;
     960             : 
     961        1056 :         byteswritten = pg_pwrite(recvFile, buf, segbytes, (off_t) startoff);
     962        1056 :         if (byteswritten <= 0)
     963             :         {
     964             :             char        xlogfname[MAXFNAMELEN];
     965             :             int         save_errno;
     966             : 
     967             :             /* if write didn't set errno, assume no disk space */
     968           0 :             if (errno == 0)
     969           0 :                 errno = ENOSPC;
     970             : 
     971           0 :             save_errno = errno;
     972           0 :             XLogFileName(xlogfname, recvFileTLI, recvSegNo, wal_segment_size);
     973           0 :             errno = save_errno;
     974           0 :             ereport(PANIC,
     975             :                     (errcode_for_file_access(),
     976             :                      errmsg("could not write to log segment %s "
     977             :                             "at offset %u, length %lu: %m",
     978             :                             xlogfname, startoff, (unsigned long) segbytes)));
     979             :         }
     980             : 
     981             :         /* Update state for write */
     982        1056 :         recptr += byteswritten;
     983             : 
     984        1056 :         nbytes -= byteswritten;
     985        1056 :         buf += byteswritten;
     986             : 
     987        1056 :         LogstreamResult.Write = recptr;
     988             :     }
     989             : 
     990             :     /* Update shared-memory status */
     991        1056 :     pg_atomic_write_u64(&WalRcv->writtenUpto, LogstreamResult.Write);
     992        1056 : }
     993             : 
     994             : /*
     995             :  * Flush the log to disk.
     996             :  *
     997             :  * If we're in the midst of dying, it's unwise to do anything that might throw
     998             :  * an error, so we skip sending a reply in that case.
     999             :  */
    1000             : static void
    1001         868 : XLogWalRcvFlush(bool dying)
    1002             : {
    1003         868 :     if (LogstreamResult.Flush < LogstreamResult.Write)
    1004             :     {
    1005         610 :         WalRcvData *walrcv = WalRcv;
    1006             : 
    1007         610 :         issue_xlog_fsync(recvFile, recvSegNo);
    1008             : 
    1009         610 :         LogstreamResult.Flush = LogstreamResult.Write;
    1010             : 
    1011             :         /* Update shared-memory status */
    1012         610 :         SpinLockAcquire(&walrcv->mutex);
    1013         610 :         if (walrcv->flushedUpto < LogstreamResult.Flush)
    1014             :         {
    1015         610 :             walrcv->latestChunkStart = walrcv->flushedUpto;
    1016         610 :             walrcv->flushedUpto = LogstreamResult.Flush;
    1017         610 :             walrcv->receivedTLI = ThisTimeLineID;
    1018             :         }
    1019         610 :         SpinLockRelease(&walrcv->mutex);
    1020             : 
    1021             :         /* Signal the startup process and walsender that new WAL has arrived */
    1022         610 :         WakeupRecovery();
    1023         610 :         if (AllowCascadeReplication())
    1024         610 :             WalSndWakeup();
    1025             : 
    1026             :         /* Report XLOG streaming progress in PS display */
    1027         610 :         if (update_process_title)
    1028             :         {
    1029             :             char        activitymsg[50];
    1030             : 
    1031        1220 :             snprintf(activitymsg, sizeof(activitymsg), "streaming %X/%X",
    1032         610 :                      (uint32) (LogstreamResult.Write >> 32),
    1033         610 :                      (uint32) LogstreamResult.Write);
    1034         610 :             set_ps_display(activitymsg);
    1035             :         }
    1036             : 
    1037             :         /* Also let the master know that we made some progress */
    1038         610 :         if (!dying)
    1039             :         {
    1040         608 :             XLogWalRcvSendReply(false, false);
    1041         608 :             XLogWalRcvSendHSFeedback(false);
    1042             :         }
    1043             :     }
    1044         868 : }
    1045             : 
    1046             : /*
    1047             :  * Send reply message to primary, indicating our current WAL locations, oldest
    1048             :  * xmin and the current time.
    1049             :  *
    1050             :  * If 'force' is not set, the message is only sent if enough time has
    1051             :  * passed since last status update to reach wal_receiver_status_interval.
    1052             :  * If wal_receiver_status_interval is disabled altogether and 'force' is
    1053             :  * false, this is a no-op.
    1054             :  *
    1055             :  * If 'requestReply' is true, requests the server to reply immediately upon
    1056             :  * receiving this message. This is used for heartbeats, when approaching
    1057             :  * wal_receiver_timeout.
    1058             :  */
    1059             : static void
    1060        2440 : XLogWalRcvSendReply(bool force, bool requestReply)
    1061             : {
    1062             :     static XLogRecPtr writePtr = 0;
    1063             :     static XLogRecPtr flushPtr = 0;
    1064             :     XLogRecPtr  applyPtr;
    1065             :     static TimestampTz sendTime = 0;
    1066             :     TimestampTz now;
    1067             : 
    1068             :     /*
    1069             :      * If the user doesn't want status to be reported to the master, be sure
    1070             :      * to exit before doing anything at all.
    1071             :      */
    1072        2440 :     if (!force && wal_receiver_status_interval <= 0)
    1073           0 :         return;
    1074             : 
    1075             :     /* Get current timestamp. */
    1076        2440 :     now = GetCurrentTimestamp();
    1077             : 
    1078             :     /*
    1079             :      * We can compare the write and flush positions to the last message we
    1080             :      * sent without taking any lock, but the apply position requires a spin
    1081             :      * lock, so we don't check that unless something else has changed or 10
    1082             :      * seconds have passed.  This means that the apply WAL location will
    1083             :      * appear, from the master's point of view, to lag slightly, but since
    1084             :      * this is only for reporting purposes and only on idle systems, that's
    1085             :      * probably OK.
    1086             :      */
    1087        2440 :     if (!force
    1088        1934 :         && writePtr == LogstreamResult.Write
    1089        1276 :         && flushPtr == LogstreamResult.Flush
    1090         698 :         && !TimestampDifferenceExceeds(sendTime, now,
    1091             :                                        wal_receiver_status_interval * 1000))
    1092         698 :         return;
    1093        1742 :     sendTime = now;
    1094             : 
    1095             :     /* Construct a new message */
    1096        1742 :     writePtr = LogstreamResult.Write;
    1097        1742 :     flushPtr = LogstreamResult.Flush;
    1098        1742 :     applyPtr = GetXLogReplayRecPtr(NULL);
    1099             : 
    1100        1742 :     resetStringInfo(&reply_message);
    1101        1742 :     pq_sendbyte(&reply_message, 'r');
    1102        1742 :     pq_sendint64(&reply_message, writePtr);
    1103        1742 :     pq_sendint64(&reply_message, flushPtr);
    1104        1742 :     pq_sendint64(&reply_message, applyPtr);
    1105        1742 :     pq_sendint64(&reply_message, GetCurrentTimestamp());
    1106        1742 :     pq_sendbyte(&reply_message, requestReply ? 1 : 0);
    1107             : 
    1108             :     /* Send it */
    1109        1742 :     elog(DEBUG2, "sending write %X/%X flush %X/%X apply %X/%X%s",
    1110             :          (uint32) (writePtr >> 32), (uint32) writePtr,
    1111             :          (uint32) (flushPtr >> 32), (uint32) flushPtr,
    1112             :          (uint32) (applyPtr >> 32), (uint32) applyPtr,
    1113             :          requestReply ? " (reply requested)" : "");
    1114             : 
    1115        1742 :     walrcv_send(wrconn, reply_message.data, reply_message.len);
    1116             : }
    1117             : 
    1118             : /*
    1119             :  * Send hot standby feedback message to primary, plus the current time,
    1120             :  * in case they don't have a watch.
    1121             :  *
    1122             :  * If the user disables feedback, send one final message to tell sender
    1123             :  * to forget about the xmin on this standby. We also send this message
    1124             :  * on first connect because a previous connection might have set xmin
    1125             :  * on a replication slot. (If we're not using a slot it's harmless to
    1126             :  * send a feedback message explicitly setting InvalidTransactionId).
    1127             :  */
    1128             : static void
    1129        1316 : XLogWalRcvSendHSFeedback(bool immed)
    1130             : {
    1131             :     TimestampTz now;
    1132             :     FullTransactionId nextFullXid;
    1133             :     TransactionId nextXid;
    1134             :     uint32      xmin_epoch,
    1135             :                 catalog_xmin_epoch;
    1136             :     TransactionId xmin,
    1137             :                 catalog_xmin;
    1138             :     static TimestampTz sendTime = 0;
    1139             : 
    1140             :     /* initially true so we always send at least one feedback message */
    1141             :     static bool master_has_standby_xmin = true;
    1142             : 
    1143             :     /*
    1144             :      * If the user doesn't want status to be reported to the master, be sure
    1145             :      * to exit before doing anything at all.
    1146             :      */
    1147        1316 :     if ((wal_receiver_status_interval <= 0 || !hot_standby_feedback) &&
    1148        1202 :         !master_has_standby_xmin)
    1149        1190 :         return;
    1150             : 
    1151             :     /* Get current timestamp. */
    1152         226 :     now = GetCurrentTimestamp();
    1153             : 
    1154         226 :     if (!immed)
    1155             :     {
    1156             :         /*
    1157             :          * Send feedback at most once per wal_receiver_status_interval.
    1158             :          */
    1159         216 :         if (!TimestampDifferenceExceeds(sendTime, now,
    1160             :                                         wal_receiver_status_interval * 1000))
    1161         100 :             return;
    1162         116 :         sendTime = now;
    1163             :     }
    1164             : 
    1165             :     /*
    1166             :      * If Hot Standby is not yet accepting connections there is nothing to
    1167             :      * send. Check this after the interval has expired to reduce number of
    1168             :      * calls.
    1169             :      *
    1170             :      * Bailing out here also ensures that we don't send feedback until we've
    1171             :      * read our own replication slot state, so we don't tell the master to
    1172             :      * discard needed xmin or catalog_xmin from any slots that may exist on
    1173             :      * this replica.
    1174             :      */
    1175         126 :     if (!HotStandbyActive())
    1176           0 :         return;
    1177             : 
    1178             :     /*
    1179             :      * Make the expensive call to get the oldest xmin once we are certain
    1180             :      * everything else has been checked.
    1181             :      */
    1182         126 :     if (hot_standby_feedback)
    1183             :     {
    1184             :         TransactionId slot_xmin;
    1185             : 
    1186             :         /*
    1187             :          * Usually GetOldestXmin() would include both global replication slot
    1188             :          * xmin and catalog_xmin in its calculations, but we want to derive
    1189             :          * separate values for each of those. So we ask for an xmin that
    1190             :          * excludes the catalog_xmin.
    1191             :          */
    1192          14 :         xmin = GetOldestXmin(NULL,
    1193             :                              PROCARRAY_FLAGS_DEFAULT | PROCARRAY_SLOTS_XMIN);
    1194             : 
    1195          14 :         ProcArrayGetReplicationSlotXmin(&slot_xmin, &catalog_xmin);
    1196             : 
    1197          18 :         if (TransactionIdIsValid(slot_xmin) &&
    1198           4 :             TransactionIdPrecedes(slot_xmin, xmin))
    1199           4 :             xmin = slot_xmin;
    1200             :     }
    1201             :     else
    1202             :     {
    1203         112 :         xmin = InvalidTransactionId;
    1204         112 :         catalog_xmin = InvalidTransactionId;
    1205             :     }
    1206             : 
    1207             :     /*
    1208             :      * Get epoch and adjust if nextXid and oldestXmin are different sides of
    1209             :      * the epoch boundary.
    1210             :      */
    1211         126 :     nextFullXid = ReadNextFullTransactionId();
    1212         126 :     nextXid = XidFromFullTransactionId(nextFullXid);
    1213         126 :     xmin_epoch = EpochFromFullTransactionId(nextFullXid);
    1214         126 :     catalog_xmin_epoch = xmin_epoch;
    1215         126 :     if (nextXid < xmin)
    1216           0 :         xmin_epoch--;
    1217         126 :     if (nextXid < catalog_xmin)
    1218           0 :         catalog_xmin_epoch--;
    1219             : 
    1220         126 :     elog(DEBUG2, "sending hot standby feedback xmin %u epoch %u catalog_xmin %u catalog_xmin_epoch %u",
    1221             :          xmin, xmin_epoch, catalog_xmin, catalog_xmin_epoch);
    1222             : 
    1223             :     /* Construct the message and send it. */
    1224         126 :     resetStringInfo(&reply_message);
    1225         126 :     pq_sendbyte(&reply_message, 'h');
    1226         126 :     pq_sendint64(&reply_message, GetCurrentTimestamp());
    1227         126 :     pq_sendint32(&reply_message, xmin);
    1228         126 :     pq_sendint32(&reply_message, xmin_epoch);
    1229         126 :     pq_sendint32(&reply_message, catalog_xmin);
    1230         126 :     pq_sendint32(&reply_message, catalog_xmin_epoch);
    1231         126 :     walrcv_send(wrconn, reply_message.data, reply_message.len);
    1232         126 :     if (TransactionIdIsValid(xmin) || TransactionIdIsValid(catalog_xmin))
    1233          14 :         master_has_standby_xmin = true;
    1234             :     else
    1235         112 :         master_has_standby_xmin = false;
    1236             : }
    1237             : 
    1238             : /*
    1239             :  * Update shared memory status upon receiving a message from primary.
    1240             :  *
    1241             :  * 'walEnd' and 'sendTime' are the end-of-WAL and timestamp of the latest
    1242             :  * message, reported by primary.
    1243             :  */
    1244             : static void
    1245        1056 : ProcessWalSndrMessage(XLogRecPtr walEnd, TimestampTz sendTime)
    1246             : {
    1247        1056 :     WalRcvData *walrcv = WalRcv;
    1248             : 
    1249        1056 :     TimestampTz lastMsgReceiptTime = GetCurrentTimestamp();
    1250             : 
    1251             :     /* Update shared-memory status */
    1252        1056 :     SpinLockAcquire(&walrcv->mutex);
    1253        1056 :     if (walrcv->latestWalEnd < walEnd)
    1254         608 :         walrcv->latestWalEndTime = sendTime;
    1255        1056 :     walrcv->latestWalEnd = walEnd;
    1256        1056 :     walrcv->lastMsgSendTime = sendTime;
    1257        1056 :     walrcv->lastMsgReceiptTime = lastMsgReceiptTime;
    1258        1056 :     SpinLockRelease(&walrcv->mutex);
    1259             : 
    1260        1056 :     if (log_min_messages <= DEBUG2)
    1261             :     {
    1262             :         char       *sendtime;
    1263             :         char       *receipttime;
    1264             :         int         applyDelay;
    1265             : 
    1266             :         /* Copy because timestamptz_to_str returns a static buffer */
    1267          16 :         sendtime = pstrdup(timestamptz_to_str(sendTime));
    1268          16 :         receipttime = pstrdup(timestamptz_to_str(lastMsgReceiptTime));
    1269          16 :         applyDelay = GetReplicationApplyDelay();
    1270             : 
    1271             :         /* apply delay is not available */
    1272          16 :         if (applyDelay == -1)
    1273           0 :             elog(DEBUG2, "sendtime %s receipttime %s replication apply delay (N/A) transfer latency %d ms",
    1274             :                  sendtime,
    1275             :                  receipttime,
    1276             :                  GetReplicationTransferLatency());
    1277             :         else
    1278          16 :             elog(DEBUG2, "sendtime %s receipttime %s replication apply delay %d ms transfer latency %d ms",
    1279             :                  sendtime,
    1280             :                  receipttime,
    1281             :                  applyDelay,
    1282             :                  GetReplicationTransferLatency());
    1283             : 
    1284          16 :         pfree(sendtime);
    1285          16 :         pfree(receipttime);
    1286             :     }
    1287        1056 : }
    1288             : 
    1289             : /*
    1290             :  * Wake up the walreceiver main loop.
    1291             :  *
    1292             :  * This is called by the startup process whenever interesting xlog records
    1293             :  * are applied, so that walreceiver can check if it needs to send an apply
    1294             :  * notification back to the master which may be waiting in a COMMIT with
    1295             :  * synchronous_commit = remote_apply.
    1296             :  */
    1297             : void
    1298         550 : WalRcvForceReply(void)
    1299             : {
    1300             :     Latch      *latch;
    1301             : 
    1302         550 :     WalRcv->force_reply = true;
    1303             :     /* fetching the latch pointer might not be atomic, so use spinlock */
    1304         550 :     SpinLockAcquire(&WalRcv->mutex);
    1305         550 :     latch = WalRcv->latch;
    1306         550 :     SpinLockRelease(&WalRcv->mutex);
    1307         550 :     if (latch)
    1308         422 :         SetLatch(latch);
    1309         550 : }
    1310             : 
    1311             : /*
    1312             :  * Return a string constant representing the state. This is used
    1313             :  * in system functions and views, and should *not* be translated.
    1314             :  */
    1315             : static const char *
    1316           0 : WalRcvGetStateString(WalRcvState state)
    1317             : {
    1318           0 :     switch (state)
    1319             :     {
    1320           0 :         case WALRCV_STOPPED:
    1321           0 :             return "stopped";
    1322           0 :         case WALRCV_STARTING:
    1323           0 :             return "starting";
    1324           0 :         case WALRCV_STREAMING:
    1325           0 :             return "streaming";
    1326           0 :         case WALRCV_WAITING:
    1327           0 :             return "waiting";
    1328           0 :         case WALRCV_RESTARTING:
    1329           0 :             return "restarting";
    1330           0 :         case WALRCV_STOPPING:
    1331           0 :             return "stopping";
    1332             :     }
    1333           0 :     return "UNKNOWN";
    1334             : }
    1335             : 
    1336             : /*
    1337             :  * Returns activity of WAL receiver, including pid, state and xlog locations
    1338             :  * received from the WAL sender of another server.
    1339             :  */
    1340             : Datum
    1341           0 : pg_stat_get_wal_receiver(PG_FUNCTION_ARGS)
    1342             : {
    1343             :     TupleDesc   tupdesc;
    1344             :     Datum      *values;
    1345             :     bool       *nulls;
    1346             :     int         pid;
    1347             :     bool        ready_to_display;
    1348             :     WalRcvState state;
    1349             :     XLogRecPtr  receive_start_lsn;
    1350             :     TimeLineID  receive_start_tli;
    1351             :     XLogRecPtr  written_lsn;
    1352             :     XLogRecPtr  flushed_lsn;
    1353             :     TimeLineID  received_tli;
    1354             :     TimestampTz last_send_time;
    1355             :     TimestampTz last_receipt_time;
    1356             :     XLogRecPtr  latest_end_lsn;
    1357             :     TimestampTz latest_end_time;
    1358             :     char        sender_host[NI_MAXHOST];
    1359           0 :     int         sender_port = 0;
    1360             :     char        slotname[NAMEDATALEN];
    1361             :     char        conninfo[MAXCONNINFO];
    1362             : 
    1363             :     /* Take a lock to ensure value consistency */
    1364           0 :     SpinLockAcquire(&WalRcv->mutex);
    1365           0 :     pid = (int) WalRcv->pid;
    1366           0 :     ready_to_display = WalRcv->ready_to_display;
    1367           0 :     state = WalRcv->walRcvState;
    1368           0 :     receive_start_lsn = WalRcv->receiveStart;
    1369           0 :     receive_start_tli = WalRcv->receiveStartTLI;
    1370           0 :     written_lsn = pg_atomic_read_u64(&WalRcv->writtenUpto);
    1371           0 :     flushed_lsn = WalRcv->flushedUpto;
    1372           0 :     received_tli = WalRcv->receivedTLI;
    1373           0 :     last_send_time = WalRcv->lastMsgSendTime;
    1374           0 :     last_receipt_time = WalRcv->lastMsgReceiptTime;
    1375           0 :     latest_end_lsn = WalRcv->latestWalEnd;
    1376           0 :     latest_end_time = WalRcv->latestWalEndTime;
    1377           0 :     strlcpy(slotname, (char *) WalRcv->slotname, sizeof(slotname));
    1378           0 :     strlcpy(sender_host, (char *) WalRcv->sender_host, sizeof(sender_host));
    1379           0 :     sender_port = WalRcv->sender_port;
    1380           0 :     strlcpy(conninfo, (char *) WalRcv->conninfo, sizeof(conninfo));
    1381           0 :     SpinLockRelease(&WalRcv->mutex);
    1382             : 
    1383             :     /*
    1384             :      * No WAL receiver (or not ready yet), just return a tuple with NULL
    1385             :      * values
    1386             :      */
    1387           0 :     if (pid == 0 || !ready_to_display)
    1388           0 :         PG_RETURN_NULL();
    1389             : 
    1390             :     /* determine result type */
    1391           0 :     if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
    1392           0 :         elog(ERROR, "return type must be a row type");
    1393             : 
    1394           0 :     values = palloc0(sizeof(Datum) * tupdesc->natts);
    1395           0 :     nulls = palloc0(sizeof(bool) * tupdesc->natts);
    1396             : 
    1397             :     /* Fetch values */
    1398           0 :     values[0] = Int32GetDatum(pid);
    1399             : 
    1400           0 :     if (!is_member_of_role(GetUserId(), DEFAULT_ROLE_READ_ALL_STATS))
    1401             :     {
    1402             :         /*
    1403             :          * Only superusers and members of pg_read_all_stats can see details.
    1404             :          * Other users only get the pid value to know whether it is a WAL
    1405             :          * receiver, but no details.
    1406             :          */
    1407           0 :         MemSet(&nulls[1], true, sizeof(bool) * (tupdesc->natts - 1));
    1408             :     }
    1409             :     else
    1410             :     {
    1411           0 :         values[1] = CStringGetTextDatum(WalRcvGetStateString(state));
    1412             : 
    1413           0 :         if (XLogRecPtrIsInvalid(receive_start_lsn))
    1414           0 :             nulls[2] = true;
    1415             :         else
    1416           0 :             values[2] = LSNGetDatum(receive_start_lsn);
    1417           0 :         values[3] = Int32GetDatum(receive_start_tli);
    1418           0 :         if (XLogRecPtrIsInvalid(written_lsn))
    1419           0 :             nulls[4] = true;
    1420             :         else
    1421           0 :             values[4] = LSNGetDatum(written_lsn);
    1422           0 :         if (XLogRecPtrIsInvalid(flushed_lsn))
    1423           0 :             nulls[5] = true;
    1424             :         else
    1425           0 :             values[5] = LSNGetDatum(flushed_lsn);
    1426           0 :         values[6] = Int32GetDatum(received_tli);
    1427           0 :         if (last_send_time == 0)
    1428           0 :             nulls[7] = true;
    1429             :         else
    1430           0 :             values[7] = TimestampTzGetDatum(last_send_time);
    1431           0 :         if (last_receipt_time == 0)
    1432           0 :             nulls[8] = true;
    1433             :         else
    1434           0 :             values[8] = TimestampTzGetDatum(last_receipt_time);
    1435           0 :         if (XLogRecPtrIsInvalid(latest_end_lsn))
    1436           0 :             nulls[9] = true;
    1437             :         else
    1438           0 :             values[9] = LSNGetDatum(latest_end_lsn);
    1439           0 :         if (latest_end_time == 0)
    1440           0 :             nulls[10] = true;
    1441             :         else
    1442           0 :             values[10] = TimestampTzGetDatum(latest_end_time);
    1443           0 :         if (*slotname == '\0')
    1444           0 :             nulls[11] = true;
    1445             :         else
    1446           0 :             values[11] = CStringGetTextDatum(slotname);
    1447           0 :         if (*sender_host == '\0')
    1448           0 :             nulls[12] = true;
    1449             :         else
    1450           0 :             values[12] = CStringGetTextDatum(sender_host);
    1451           0 :         if (sender_port == 0)
    1452           0 :             nulls[13] = true;
    1453             :         else
    1454           0 :             values[13] = Int32GetDatum(sender_port);
    1455           0 :         if (*conninfo == '\0')
    1456           0 :             nulls[14] = true;
    1457             :         else
    1458           0 :             values[14] = CStringGetTextDatum(conninfo);
    1459             :     }
    1460             : 
    1461             :     /* Returns the record as Datum */
    1462           0 :     PG_RETURN_DATUM(HeapTupleGetDatum(heap_form_tuple(tupdesc, values, nulls)));
    1463             : }

Generated by: LCOV version 1.13