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

Generated by: LCOV version 1.14