LCOV - differential code coverage report
Current view: top level - src/backend/replication - walreceiver.c (source / functions) Coverage Total Hit UNC LBC UIC UBC GBC GIC GNC CBC EUB ECB DUB DCB
Current: Differential Code Coverage HEAD vs 15 Lines: 75.2 % 525 395 7 46 66 11 20 224 48 103 98 231 1 15
Current Date: 2023-04-08 15:15:32 Functions: 93.8 % 16 15 1 14 1 1 15
Baseline: 15
Baseline Date: 2023-04-08 15:09:40
Legend: Lines: hit not hit

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

Generated by: LCOV version v1.16-55-g56c0a2a