LCOV - code coverage report
Current view: top level - src/backend/replication - walreceiver.c (source / functions) Coverage Total Hit
Test: Code coverage Lines: 0.0 % 636 0
Test Date: 2026-01-26 10:56:24 Functions: 0.0 % 15 0
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 0.0 % 420 0

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

Generated by: LCOV version 2.3.2-1