LCOV - code coverage report
Current view: top level - src/backend/replication - walreceiver.c (source / functions) Coverage Total Hit
Test: PostgreSQL 19devel Lines: 86.3 % 525 453
Test Date: 2026-05-04 08:16:33 Functions: 100.0 % 15 15
Legend: Lines:     hit not hit

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

Generated by: LCOV version 2.0-1