LCOV - differential code coverage report
Current view: top level - src/backend/replication - walreceiver.c (source / functions) Coverage Total Hit UNC LBC UIC UBC GBC GIC GNC CBC EUB ECB DUB DCB
Current: bed3ffbf9d952be6c7d739d068cdce44c046dfb7 vs 574581b50ac9c63dd9e4abebb731a3b67e5b50f6 Lines: 86.6 % 538 466 4 68 1 52 413 1 1 43
Current Date: 2026-05-05 10:23:31 +0900 Functions: 100.0 % 15 15 11 4 2
Baseline: lcov-20260505-025707-baseline Branches: 61.1 % 342 209 10 2 2 119 6 1 26 176 10 10 7 17
Baseline Date: 2026-05-05 10:27:06 +0900 Line coverage date bins:
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
(1,7] days: 100.0 % 3 3 3
(7,30] days: 90.0 % 10 9 1 9
(30,360] days: 93.0 % 43 40 3 40
(360..) days: 85.9 % 482 414 68 1 413 1
Function coverage date bins:
(30,360] days: 100.0 % 2 2 2
(360..) days: 100.0 % 13 13 9 4
Branch coverage date bins:
(7,30] days: 100.0 % 2 2 2
(30,360] days: 70.6 % 34 24 10 24
(360..) days: 56.1 % 326 183 2 2 119 6 1 176 10 10

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

Generated by: LCOV version 2.5.0-beta