PostgreSQL Source Code  git master
walreceiver.h File Reference
#include "access/xlog.h"
#include "access/xlogdefs.h"
#include "getaddrinfo.h"
#include "pgtime.h"
#include "port/atomics.h"
#include "replication/logicalproto.h"
#include "replication/walsender.h"
#include "storage/latch.h"
#include "storage/spin.h"
#include "utils/tuplestore.h"
Include dependency graph for walreceiver.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  WalRcvData
 
struct  WalRcvStreamOptions
 
struct  WalRcvExecResult
 
struct  WalReceiverFunctionsType
 

Macros

#define MAXCONNINFO   1024
 
#define AllowCascadeReplication()   (EnableHotStandby && max_wal_senders > 0)
 
#define walrcv_connect(conninfo, logical, appname, err)   WalReceiverFunctions->walrcv_connect(conninfo, logical, appname, err)
 
#define walrcv_check_conninfo(conninfo)   WalReceiverFunctions->walrcv_check_conninfo(conninfo)
 
#define walrcv_get_conninfo(conn)   WalReceiverFunctions->walrcv_get_conninfo(conn)
 
#define walrcv_get_senderinfo(conn, sender_host, sender_port)   WalReceiverFunctions->walrcv_get_senderinfo(conn, sender_host, sender_port)
 
#define walrcv_identify_system(conn, primary_tli)   WalReceiverFunctions->walrcv_identify_system(conn, primary_tli)
 
#define walrcv_server_version(conn)   WalReceiverFunctions->walrcv_server_version(conn)
 
#define walrcv_readtimelinehistoryfile(conn, tli, filename, content, size)   WalReceiverFunctions->walrcv_readtimelinehistoryfile(conn, tli, filename, content, size)
 
#define walrcv_startstreaming(conn, options)   WalReceiverFunctions->walrcv_startstreaming(conn, options)
 
#define walrcv_endstreaming(conn, next_tli)   WalReceiverFunctions->walrcv_endstreaming(conn, next_tli)
 
#define walrcv_receive(conn, buffer, wait_fd)   WalReceiverFunctions->walrcv_receive(conn, buffer, wait_fd)
 
#define walrcv_send(conn, buffer, nbytes)   WalReceiverFunctions->walrcv_send(conn, buffer, nbytes)
 
#define walrcv_create_slot(conn, slotname, temporary, snapshot_action, lsn)   WalReceiverFunctions->walrcv_create_slot(conn, slotname, temporary, snapshot_action, lsn)
 
#define walrcv_get_backend_pid(conn)   WalReceiverFunctions->walrcv_get_backend_pid(conn)
 
#define walrcv_exec(conn, exec, nRetTypes, retTypes)   WalReceiverFunctions->walrcv_exec(conn, exec, nRetTypes, retTypes)
 
#define walrcv_disconnect(conn)   WalReceiverFunctions->walrcv_disconnect(conn)
 

Typedefs

typedef struct WalReceiverConn WalReceiverConn
 
typedef struct WalRcvExecResult WalRcvExecResult
 
typedef WalReceiverConn *(* walrcv_connect_fn) (const char *conninfo, bool logical, const char *appname, char **err)
 
typedef void(* walrcv_check_conninfo_fn) (const char *conninfo)
 
typedef char *(* walrcv_get_conninfo_fn) (WalReceiverConn *conn)
 
typedef void(* walrcv_get_senderinfo_fn) (WalReceiverConn *conn, char **sender_host, int *sender_port)
 
typedef char *(* walrcv_identify_system_fn) (WalReceiverConn *conn, TimeLineID *primary_tli)
 
typedef int(* walrcv_server_version_fn) (WalReceiverConn *conn)
 
typedef void(* walrcv_readtimelinehistoryfile_fn) (WalReceiverConn *conn, TimeLineID tli, char **filename, char **content, int *size)
 
typedef bool(* walrcv_startstreaming_fn) (WalReceiverConn *conn, const WalRcvStreamOptions *options)
 
typedef void(* walrcv_endstreaming_fn) (WalReceiverConn *conn, TimeLineID *next_tli)
 
typedef int(* walrcv_receive_fn) (WalReceiverConn *conn, char **buffer, pgsocket *wait_fd)
 
typedef void(* walrcv_send_fn) (WalReceiverConn *conn, const char *buffer, int nbytes)
 
typedef char *(* walrcv_create_slot_fn) (WalReceiverConn *conn, const char *slotname, bool temporary, CRSSnapshotAction snapshot_action, XLogRecPtr *lsn)
 
typedef pid_t(* walrcv_get_backend_pid_fn) (WalReceiverConn *conn)
 
typedef WalRcvExecResult *(* walrcv_exec_fn) (WalReceiverConn *conn, const char *query, const int nRetTypes, const Oid *retTypes)
 
typedef void(* walrcv_disconnect_fn) (WalReceiverConn *conn)
 
typedef struct WalReceiverFunctionsType WalReceiverFunctionsType
 

Enumerations

enum  WalRcvState {
  WALRCV_STOPPED, WALRCV_STARTING, WALRCV_STREAMING, WALRCV_WAITING,
  WALRCV_RESTARTING, WALRCV_STOPPING
}
 
enum  WalRcvExecStatus {
  WALRCV_ERROR, WALRCV_OK_COMMAND, WALRCV_OK_TUPLES, WALRCV_OK_COPY_IN,
  WALRCV_OK_COPY_OUT, WALRCV_OK_COPY_BOTH
}
 

Functions

static void walrcv_clear_result (WalRcvExecResult *walres)
 
void WalReceiverMain (void) pg_attribute_noreturn()
 
void ProcessWalRcvInterrupts (void)
 
Size WalRcvShmemSize (void)
 
void WalRcvShmemInit (void)
 
void ShutdownWalRcv (void)
 
bool WalRcvStreaming (void)
 
bool WalRcvRunning (void)
 
void RequestXLogStreaming (TimeLineID tli, XLogRecPtr recptr, const char *conninfo, const char *slotname, bool create_temp_slot)
 
XLogRecPtr GetWalRcvFlushRecPtr (XLogRecPtr *latestChunkStart, TimeLineID *receiveTLI)
 
XLogRecPtr GetWalRcvWriteRecPtr (void)
 
int GetReplicationApplyDelay (void)
 
int GetReplicationTransferLatency (void)
 
void WalRcvForceReply (void)
 

Variables

int wal_receiver_status_interval
 
int wal_receiver_timeout
 
bool hot_standby_feedback
 
WalRcvDataWalRcv
 
PGDLLIMPORT WalReceiverFunctionsTypeWalReceiverFunctions
 

Macro Definition Documentation

◆ AllowCascadeReplication

#define AllowCascadeReplication ( )    (EnableHotStandby && max_wal_senders > 0)

Definition at line 39 of file walreceiver.h.

Referenced by StartupXLOG(), and XLogWalRcvFlush().

◆ MAXCONNINFO

#define MAXCONNINFO   1024

Definition at line 36 of file walreceiver.h.

Referenced by pg_stat_get_wal_receiver(), RequestXLogStreaming(), and WalReceiverMain().

◆ walrcv_check_conninfo

#define walrcv_check_conninfo (   conninfo)    WalReceiverFunctions->walrcv_check_conninfo(conninfo)

Definition at line 399 of file walreceiver.h.

Referenced by AlterSubscription(), and CreateSubscription().

◆ walrcv_connect

#define walrcv_connect (   conninfo,
  logical,
  appname,
  err 
)    WalReceiverFunctions->walrcv_connect(conninfo, logical, appname, err)

◆ walrcv_create_slot

#define walrcv_create_slot (   conn,
  slotname,
  temporary,
  snapshot_action,
  lsn 
)    WalReceiverFunctions->walrcv_create_slot(conn, slotname, temporary, snapshot_action, lsn)

Definition at line 419 of file walreceiver.h.

Referenced by CreateSubscription(), LogicalRepSyncTableStart(), and WalReceiverMain().

◆ walrcv_disconnect

#define walrcv_disconnect (   conn)    WalReceiverFunctions->walrcv_disconnect(conn)

◆ walrcv_endstreaming

#define walrcv_endstreaming (   conn,
  next_tli 
)    WalReceiverFunctions->walrcv_endstreaming(conn, next_tli)

◆ walrcv_exec

#define walrcv_exec (   conn,
  exec,
  nRetTypes,
  retTypes 
)    WalReceiverFunctions->walrcv_exec(conn, exec, nRetTypes, retTypes)

◆ walrcv_get_backend_pid

#define walrcv_get_backend_pid (   conn)    WalReceiverFunctions->walrcv_get_backend_pid(conn)

Definition at line 421 of file walreceiver.h.

Referenced by WalReceiverMain().

◆ walrcv_get_conninfo

#define walrcv_get_conninfo (   conn)    WalReceiverFunctions->walrcv_get_conninfo(conn)

Definition at line 401 of file walreceiver.h.

Referenced by WalReceiverMain().

◆ walrcv_get_senderinfo

#define walrcv_get_senderinfo (   conn,
  sender_host,
  sender_port 
)    WalReceiverFunctions->walrcv_get_senderinfo(conn, sender_host, sender_port)

Definition at line 403 of file walreceiver.h.

Referenced by WalReceiverMain().

◆ walrcv_identify_system

#define walrcv_identify_system (   conn,
  primary_tli 
)    WalReceiverFunctions->walrcv_identify_system(conn, primary_tli)

Definition at line 405 of file walreceiver.h.

Referenced by ApplyWorkerMain(), and WalReceiverMain().

◆ walrcv_readtimelinehistoryfile

#define walrcv_readtimelinehistoryfile (   conn,
  tli,
  filename,
  content,
  size 
)    WalReceiverFunctions->walrcv_readtimelinehistoryfile(conn, tli, filename, content, size)

Definition at line 409 of file walreceiver.h.

Referenced by WalRcvFetchTimeLineHistoryFiles().

◆ walrcv_receive

#define walrcv_receive (   conn,
  buffer,
  wait_fd 
)    WalReceiverFunctions->walrcv_receive(conn, buffer, wait_fd)

Definition at line 415 of file walreceiver.h.

Referenced by copy_read_data(), LogicalRepApplyLoop(), and WalReceiverMain().

◆ walrcv_send

#define walrcv_send (   conn,
  buffer,
  nbytes 
)    WalReceiverFunctions->walrcv_send(conn, buffer, nbytes)

Definition at line 417 of file walreceiver.h.

Referenced by send_feedback(), XLogWalRcvSendHSFeedback(), and XLogWalRcvSendReply().

◆ walrcv_server_version

#define walrcv_server_version (   conn)    WalReceiverFunctions->walrcv_server_version(conn)

Definition at line 407 of file walreceiver.h.

Referenced by fetch_remote_table_info().

◆ walrcv_startstreaming

#define walrcv_startstreaming (   conn,
  options 
)    WalReceiverFunctions->walrcv_startstreaming(conn, options)

Definition at line 411 of file walreceiver.h.

Referenced by ApplyWorkerMain(), and WalReceiverMain().

Typedef Documentation

◆ walrcv_check_conninfo_fn

typedef void(* walrcv_check_conninfo_fn) (const char *conninfo)

Definition at line 240 of file walreceiver.h.

◆ walrcv_connect_fn

typedef WalReceiverConn*(* walrcv_connect_fn) (const char *conninfo, bool logical, const char *appname, char **err)

Definition at line 230 of file walreceiver.h.

◆ walrcv_create_slot_fn

typedef char*(* walrcv_create_slot_fn) (WalReceiverConn *conn, const char *slotname, bool temporary, CRSSnapshotAction snapshot_action, XLogRecPtr *lsn)

Definition at line 343 of file walreceiver.h.

◆ walrcv_disconnect_fn

typedef void(* walrcv_disconnect_fn) (WalReceiverConn *conn)

Definition at line 374 of file walreceiver.h.

◆ walrcv_endstreaming_fn

typedef void(* walrcv_endstreaming_fn) (WalReceiverConn *conn, TimeLineID *next_tli)

Definition at line 308 of file walreceiver.h.

◆ walrcv_exec_fn

typedef WalRcvExecResult*(* walrcv_exec_fn) (WalReceiverConn *conn, const char *query, const int nRetTypes, const Oid *retTypes)

Definition at line 364 of file walreceiver.h.

◆ walrcv_get_backend_pid_fn

typedef pid_t(* walrcv_get_backend_pid_fn) (WalReceiverConn *conn)

Definition at line 354 of file walreceiver.h.

◆ walrcv_get_conninfo_fn

typedef char*(* walrcv_get_conninfo_fn) (WalReceiverConn *conn)

Definition at line 248 of file walreceiver.h.

◆ walrcv_get_senderinfo_fn

typedef void(* walrcv_get_senderinfo_fn) (WalReceiverConn *conn, char **sender_host, int *sender_port)

Definition at line 257 of file walreceiver.h.

◆ walrcv_identify_system_fn

typedef char*(* walrcv_identify_system_fn) (WalReceiverConn *conn, TimeLineID *primary_tli)

Definition at line 268 of file walreceiver.h.

◆ walrcv_readtimelinehistoryfile_fn

typedef void(* walrcv_readtimelinehistoryfile_fn) (WalReceiverConn *conn, TimeLineID tli, char **filename, char **content, int *size)

Definition at line 285 of file walreceiver.h.

◆ walrcv_receive_fn

typedef int(* walrcv_receive_fn) (WalReceiverConn *conn, char **buffer, pgsocket *wait_fd)

Definition at line 319 of file walreceiver.h.

◆ walrcv_send_fn

typedef void(* walrcv_send_fn) (WalReceiverConn *conn, const char *buffer, int nbytes)

Definition at line 329 of file walreceiver.h.

◆ walrcv_server_version_fn

typedef int(* walrcv_server_version_fn) (WalReceiverConn *conn)

Definition at line 276 of file walreceiver.h.

◆ walrcv_startstreaming_fn

typedef bool(* walrcv_startstreaming_fn) (WalReceiverConn *conn, const WalRcvStreamOptions *options)

Definition at line 299 of file walreceiver.h.

◆ WalRcvExecResult

◆ WalReceiverConn

Definition at line 186 of file walreceiver.h.

◆ WalReceiverFunctionsType

Enumeration Type Documentation

◆ WalRcvExecStatus

Enumerator
WALRCV_ERROR 
WALRCV_OK_COMMAND 
WALRCV_OK_TUPLES 
WALRCV_OK_COPY_IN 
WALRCV_OK_COPY_OUT 
WALRCV_OK_COPY_BOTH 

Definition at line 193 of file walreceiver.h.

194 {
195  WALRCV_ERROR, /* There was error when executing the query. */
196  WALRCV_OK_COMMAND, /* Query executed utility or replication
197  * command. */
198  WALRCV_OK_TUPLES, /* Query returned tuples. */
199  WALRCV_OK_COPY_IN, /* Query started COPY FROM. */
200  WALRCV_OK_COPY_OUT, /* Query started COPY TO. */
201  WALRCV_OK_COPY_BOTH /* Query started COPY BOTH replication
202  * protocol. */
WalRcvExecStatus
Definition: walreceiver.h:193

◆ WalRcvState

Enumerator
WALRCV_STOPPED 
WALRCV_STARTING 
WALRCV_STREAMING 
WALRCV_WAITING 
WALRCV_RESTARTING 
WALRCV_STOPPING 

Definition at line 44 of file walreceiver.h.

45 {
46  WALRCV_STOPPED, /* stopped and mustn't start up again */
47  WALRCV_STARTING, /* launched, but the process hasn't
48  * initialized yet */
49  WALRCV_STREAMING, /* walreceiver is streaming */
50  WALRCV_WAITING, /* stopped streaming, waiting for orders */
51  WALRCV_RESTARTING, /* asked to restart streaming */
52  WALRCV_STOPPING /* requested to stop, but still running */
53 } WalRcvState;
WalRcvState
Definition: walreceiver.h:44

Function Documentation

◆ GetReplicationApplyDelay()

int GetReplicationApplyDelay ( void  )

Definition at line 348 of file walreceiverfuncs.c.

References WalRcvData::flushedUpto, GetCurrentChunkReplayStartTime(), GetCurrentTimestamp(), GetXLogReplayRecPtr(), WalRcvData::mutex, SpinLockAcquire, SpinLockRelease, TimestampDifference(), and WalRcv.

Referenced by ProcessWalSndrMessage(), and walrcv_clear_result().

349 {
350  WalRcvData *walrcv = WalRcv;
351  XLogRecPtr receivePtr;
352  XLogRecPtr replayPtr;
353 
354  long secs;
355  int usecs;
356 
357  TimestampTz chunkReplayStartTime;
358 
359  SpinLockAcquire(&walrcv->mutex);
360  receivePtr = walrcv->flushedUpto;
361  SpinLockRelease(&walrcv->mutex);
362 
363  replayPtr = GetXLogReplayRecPtr(NULL);
364 
365  if (receivePtr == replayPtr)
366  return 0;
367 
368  chunkReplayStartTime = GetCurrentChunkReplayStartTime();
369 
370  if (chunkReplayStartTime == 0)
371  return -1;
372 
373  TimestampDifference(chunkReplayStartTime,
375  &secs, &usecs);
376 
377  return (((int) secs * 1000) + (usecs / 1000));
378 }
slock_t mutex
Definition: walreceiver.h:143
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1574
int64 TimestampTz
Definition: timestamp.h:39
#define SpinLockAcquire(lock)
Definition: spin.h:62
TimestampTz GetCurrentChunkReplayStartTime(void)
Definition: xlog.c:6203
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
Definition: xlog.c:11475
#define SpinLockRelease(lock)
Definition: spin.h:64
uint64 XLogRecPtr
Definition: xlogdefs.h:21
WalRcvData * WalRcv
XLogRecPtr flushedUpto
Definition: walreceiver.h:83
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1648

◆ GetReplicationTransferLatency()

int GetReplicationTransferLatency ( void  )

Definition at line 385 of file walreceiverfuncs.c.

References WalRcvData::lastMsgReceiptTime, WalRcvData::lastMsgSendTime, WalRcvData::mutex, SpinLockAcquire, SpinLockRelease, TimestampDifference(), and WalRcv.

Referenced by ProcessWalSndrMessage(), and walrcv_clear_result().

386 {
387  WalRcvData *walrcv = WalRcv;
388 
389  TimestampTz lastMsgSendTime;
390  TimestampTz lastMsgReceiptTime;
391 
392  long secs = 0;
393  int usecs = 0;
394  int ms;
395 
396  SpinLockAcquire(&walrcv->mutex);
397  lastMsgSendTime = walrcv->lastMsgSendTime;
398  lastMsgReceiptTime = walrcv->lastMsgReceiptTime;
399  SpinLockRelease(&walrcv->mutex);
400 
401  TimestampDifference(lastMsgSendTime,
402  lastMsgReceiptTime,
403  &secs, &usecs);
404 
405  ms = ((int) secs * 1000) + (usecs / 1000);
406 
407  return ms;
408 }
slock_t mutex
Definition: walreceiver.h:143
int64 TimestampTz
Definition: timestamp.h:39
TimestampTz lastMsgReceiptTime
Definition: walreceiver.h:98
TimestampTz lastMsgSendTime
Definition: walreceiver.h:97
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
WalRcvData * WalRcv
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1648

◆ GetWalRcvFlushRecPtr()

XLogRecPtr GetWalRcvFlushRecPtr ( XLogRecPtr latestChunkStart,
TimeLineID receiveTLI 
)

Definition at line 315 of file walreceiverfuncs.c.

References WalRcvData::flushedUpto, WalRcvData::latestChunkStart, WalRcvData::mutex, WalRcvData::receivedTLI, SpinLockAcquire, SpinLockRelease, and WalRcv.

Referenced by CreateRestartPoint(), GetStandbyFlushRecPtr(), pg_last_wal_receive_lsn(), WaitForWALToBecomeAvailable(), and walrcv_clear_result().

316 {
317  WalRcvData *walrcv = WalRcv;
318  XLogRecPtr recptr;
319 
320  SpinLockAcquire(&walrcv->mutex);
321  recptr = walrcv->flushedUpto;
322  if (latestChunkStart)
323  *latestChunkStart = walrcv->latestChunkStart;
324  if (receiveTLI)
325  *receiveTLI = walrcv->receivedTLI;
326  SpinLockRelease(&walrcv->mutex);
327 
328  return recptr;
329 }
slock_t mutex
Definition: walreceiver.h:143
TimeLineID receivedTLI
Definition: walreceiver.h:84
#define SpinLockAcquire(lock)
Definition: spin.h:62
XLogRecPtr latestChunkStart
Definition: walreceiver.h:92
#define SpinLockRelease(lock)
Definition: spin.h:64
static TimeLineID receiveTLI
Definition: xlog.c:213
uint64 XLogRecPtr
Definition: xlogdefs.h:21
WalRcvData * WalRcv
XLogRecPtr flushedUpto
Definition: walreceiver.h:83

◆ GetWalRcvWriteRecPtr()

XLogRecPtr GetWalRcvWriteRecPtr ( void  )

Definition at line 336 of file walreceiverfuncs.c.

References pg_atomic_read_u64(), WalRcv, and WalRcvData::writtenUpto.

Referenced by walrcv_clear_result().

337 {
338  WalRcvData *walrcv = WalRcv;
339 
340  return pg_atomic_read_u64(&walrcv->writtenUpto);
341 }
pg_atomic_uint64 writtenUpto
Definition: walreceiver.h:151
WalRcvData * WalRcv
static uint64 pg_atomic_read_u64(volatile pg_atomic_uint64 *ptr)
Definition: atomics.h:429

◆ ProcessWalRcvInterrupts()

void ProcessWalRcvInterrupts ( void  )

Definition at line 157 of file walreceiver.c.

References CHECK_FOR_INTERRUPTS, ereport, errcode(), errmsg(), FATAL, and got_SIGTERM.

Referenced by libpqrcv_connect(), libpqrcv_PQgetResult(), libpqrcv_processTuples(), walrcv_clear_result(), WalRcvWaitForStartPosition(), and WalReceiverMain().

158 {
159  /*
160  * Although walreceiver interrupt handling doesn't use the same scheme as
161  * regular backends, call CHECK_FOR_INTERRUPTS() to make sure we receive
162  * any incoming signals on Win32, and also to make sure we process any
163  * barrier events.
164  */
166 
167  if (got_SIGTERM)
168  {
169  ereport(FATAL,
170  (errcode(ERRCODE_ADMIN_SHUTDOWN),
171  errmsg("terminating walreceiver process due to administrator command")));
172  }
173 }
int errcode(int sqlerrcode)
Definition: elog.c:610
#define FATAL
Definition: elog.h:52
#define ereport(elevel,...)
Definition: elog.h:144
int errmsg(const char *fmt,...)
Definition: elog.c:824
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
static volatile sig_atomic_t got_SIGTERM
Definition: walreceiver.c:112

◆ RequestXLogStreaming()

void RequestXLogStreaming ( TimeLineID  tli,
XLogRecPtr  recptr,
const char *  conninfo,
const char *  slotname,
bool  create_temp_slot 
)

Definition at line 229 of file walreceiverfuncs.c.

References Assert, WalRcvData::conninfo, WalRcvData::flushedUpto, WalRcvData::is_temp_slot, WalRcvData::latch, WalRcvData::latestChunkStart, MAXCONNINFO, WalRcvData::mutex, NAMEDATALEN, now(), PMSIGNAL_START_WALRECEIVER, WalRcvData::receivedTLI, WalRcvData::receiveStart, WalRcvData::receiveStartTLI, SendPostmasterSignal(), SetLatch(), WalRcvData::slotname, SpinLockAcquire, SpinLockRelease, WalRcvData::startTime, strlcpy(), wal_segment_size, WalRcv, WALRCV_RESTARTING, WALRCV_STARTING, WALRCV_STOPPED, WALRCV_WAITING, WalRcvData::walRcvState, and XLogSegmentOffset.

Referenced by WaitForWALToBecomeAvailable(), and walrcv_clear_result().

231 {
232  WalRcvData *walrcv = WalRcv;
233  bool launch = false;
234  pg_time_t now = (pg_time_t) time(NULL);
235  Latch *latch;
236 
237  /*
238  * We always start at the beginning of the segment. That prevents a broken
239  * segment (i.e., with no records in the first half of a segment) from
240  * being created by XLOG streaming, which might cause trouble later on if
241  * the segment is e.g archived.
242  */
243  if (XLogSegmentOffset(recptr, wal_segment_size) != 0)
244  recptr -= XLogSegmentOffset(recptr, wal_segment_size);
245 
246  SpinLockAcquire(&walrcv->mutex);
247 
248  /* It better be stopped if we try to restart it */
249  Assert(walrcv->walRcvState == WALRCV_STOPPED ||
250  walrcv->walRcvState == WALRCV_WAITING);
251 
252  if (conninfo != NULL)
253  strlcpy((char *) walrcv->conninfo, conninfo, MAXCONNINFO);
254  else
255  walrcv->conninfo[0] = '\0';
256 
257  /*
258  * Use configured replication slot if present, and ignore the value of
259  * create_temp_slot as the slot name should be persistent. Otherwise, use
260  * create_temp_slot to determine whether this WAL receiver should create a
261  * temporary slot by itself and use it, or not.
262  */
263  if (slotname != NULL && slotname[0] != '\0')
264  {
265  strlcpy((char *) walrcv->slotname, slotname, NAMEDATALEN);
266  walrcv->is_temp_slot = false;
267  }
268  else
269  {
270  walrcv->slotname[0] = '\0';
271  walrcv->is_temp_slot = create_temp_slot;
272  }
273 
274  if (walrcv->walRcvState == WALRCV_STOPPED)
275  {
276  launch = true;
277  walrcv->walRcvState = WALRCV_STARTING;
278  }
279  else
280  walrcv->walRcvState = WALRCV_RESTARTING;
281  walrcv->startTime = now;
282 
283  /*
284  * If this is the first startup of walreceiver (on this timeline),
285  * initialize flushedUpto and latestChunkStart to the starting point.
286  */
287  if (walrcv->receiveStart == 0 || walrcv->receivedTLI != tli)
288  {
289  walrcv->flushedUpto = recptr;
290  walrcv->receivedTLI = tli;
291  walrcv->latestChunkStart = recptr;
292  }
293  walrcv->receiveStart = recptr;
294  walrcv->receiveStartTLI = tli;
295 
296  latch = walrcv->latch;
297 
298  SpinLockRelease(&walrcv->mutex);
299 
300  if (launch)
302  else if (latch)
303  SetLatch(latch);
304 }
int64 pg_time_t
Definition: pgtime.h:23
slock_t mutex
Definition: walreceiver.h:143
int wal_segment_size
Definition: xlog.c:116
WalRcvState walRcvState
Definition: walreceiver.h:64
TimeLineID receivedTLI
Definition: walreceiver.h:84
void SetLatch(Latch *latch)
Definition: latch.c:505
pg_time_t startTime
Definition: walreceiver.h:65
#define NAMEDATALEN
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define MAXCONNINFO
Definition: walreceiver.h:36
XLogRecPtr latestChunkStart
Definition: walreceiver.h:92
Definition: latch.h:110
TimeLineID receiveStartTLI
Definition: walreceiver.h:74
Latch * latch
Definition: walreceiver.h:141
#define SpinLockRelease(lock)
Definition: spin.h:64
#define XLogSegmentOffset(xlogptr, wal_segsz_bytes)
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define Assert(condition)
Definition: c.h:745
bool is_temp_slot
Definition: walreceiver.h:129
WalRcvData * WalRcv
void SendPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:146
XLogRecPtr receiveStart
Definition: walreceiver.h:73
XLogRecPtr flushedUpto
Definition: walreceiver.h:83
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1538
char slotname[NAMEDATALEN]
Definition: walreceiver.h:123
char conninfo[MAXCONNINFO]
Definition: walreceiver.h:110

◆ ShutdownWalRcv()

void ShutdownWalRcv ( void  )

Definition at line 163 of file walreceiverfuncs.c.

References HandleStartupProcInterrupts(), kill, WalRcvData::mutex, pg_usleep(), WalRcvData::pid, SpinLockAcquire, SpinLockRelease, WalRcv, WALRCV_RESTARTING, WALRCV_STARTING, WALRCV_STOPPED, WALRCV_STOPPING, WALRCV_STREAMING, WALRCV_WAITING, WalRcvRunning(), and WalRcvData::walRcvState.

Referenced by StartupXLOG(), WaitForWALToBecomeAvailable(), and walrcv_clear_result().

164 {
165  WalRcvData *walrcv = WalRcv;
166  pid_t walrcvpid = 0;
167 
168  /*
169  * Request walreceiver to stop. Walreceiver will switch to WALRCV_STOPPED
170  * mode once it's finished, and will also request postmaster to not
171  * restart itself.
172  */
173  SpinLockAcquire(&walrcv->mutex);
174  switch (walrcv->walRcvState)
175  {
176  case WALRCV_STOPPED:
177  break;
178  case WALRCV_STARTING:
179  walrcv->walRcvState = WALRCV_STOPPED;
180  break;
181 
182  case WALRCV_STREAMING:
183  case WALRCV_WAITING:
184  case WALRCV_RESTARTING:
185  walrcv->walRcvState = WALRCV_STOPPING;
186  /* fall through */
187  case WALRCV_STOPPING:
188  walrcvpid = walrcv->pid;
189  break;
190  }
191  SpinLockRelease(&walrcv->mutex);
192 
193  /*
194  * Signal walreceiver process if it was still running.
195  */
196  if (walrcvpid != 0)
197  kill(walrcvpid, SIGTERM);
198 
199  /*
200  * Wait for walreceiver to acknowledge its death by setting state to
201  * WALRCV_STOPPED.
202  */
203  while (WalRcvRunning())
204  {
205  /*
206  * This possibly-long loop needs to handle interrupts of startup
207  * process.
208  */
210 
211  pg_usleep(100000); /* 100ms */
212  }
213 }
slock_t mutex
Definition: walreceiver.h:143
WalRcvState walRcvState
Definition: walreceiver.h:64
#define kill(pid, sig)
Definition: win32_port.h:426
#define SpinLockAcquire(lock)
Definition: spin.h:62
void pg_usleep(long microsec)
Definition: signal.c:53
pid_t pid
Definition: walreceiver.h:63
#define SpinLockRelease(lock)
Definition: spin.h:64
WalRcvData * WalRcv
void HandleStartupProcInterrupts(void)
Definition: startup.c:135
bool WalRcvRunning(void)

◆ walrcv_clear_result()

static void walrcv_clear_result ( WalRcvExecResult walres)
inlinestatic

Definition at line 429 of file walreceiver.h.

References WalRcvExecResult::err, FreeTupleDesc(), GetReplicationApplyDelay(), GetReplicationTransferLatency(), GetWalRcvFlushRecPtr(), GetWalRcvWriteRecPtr(), pfree(), pg_attribute_noreturn, ProcessWalRcvInterrupts(), receiveTLI, RequestXLogStreaming(), ShutdownWalRcv(), WalRcvExecResult::tupledesc, WalRcvExecResult::tuplestore, tuplestore_end(), WalRcvForceReply(), WalRcvRunning(), WalRcvShmemInit(), WalRcvShmemSize(), WalRcvStreaming(), and WalReceiverMain().

Referenced by copy_table(), DropSubscription(), fetch_remote_table_info(), fetch_table_list(), and LogicalRepSyncTableStart().

430 {
431  if (!walres)
432  return;
433 
434  if (walres->err)
435  pfree(walres->err);
436 
437  if (walres->tuplestore)
438  tuplestore_end(walres->tuplestore);
439 
440  if (walres->tupledesc)
441  FreeTupleDesc(walres->tupledesc);
442 
443  pfree(walres);
444 }
void pfree(void *pointer)
Definition: mcxt.c:1056
TupleDesc tupledesc
Definition: walreceiver.h:214
Tuplestorestate * tuplestore
Definition: walreceiver.h:213
void tuplestore_end(Tuplestorestate *state)
Definition: tuplestore.c:453
void FreeTupleDesc(TupleDesc tupdesc)
Definition: tupdesc.c:313

◆ WalRcvForceReply()

void WalRcvForceReply ( void  )

Definition at line 1283 of file walreceiver.c.

References WalRcvData::force_reply, WalRcvData::latch, WalRcvData::mutex, SetLatch(), SpinLockAcquire, SpinLockRelease, and WalRcv.

Referenced by StartupXLOG(), WaitForWALToBecomeAvailable(), and walrcv_clear_result().

1284 {
1285  Latch *latch;
1286 
1287  WalRcv->force_reply = true;
1288  /* fetching the latch pointer might not be atomic, so use spinlock */
1290  latch = WalRcv->latch;
1292  if (latch)
1293  SetLatch(latch);
1294 }
slock_t mutex
Definition: walreceiver.h:143
sig_atomic_t force_reply
Definition: walreceiver.h:158
void SetLatch(Latch *latch)
Definition: latch.c:505
#define SpinLockAcquire(lock)
Definition: spin.h:62
Definition: latch.h:110
Latch * latch
Definition: walreceiver.h:141
#define SpinLockRelease(lock)
Definition: spin.h:64
WalRcvData * WalRcv

◆ WalRcvRunning()

bool WalRcvRunning ( void  )

Definition at line 72 of file walreceiverfuncs.c.

References WalRcvData::mutex, now(), SpinLockAcquire, SpinLockRelease, WalRcvData::startTime, WalRcv, WALRCV_STARTING, WALRCV_STARTUP_TIMEOUT, WALRCV_STOPPED, and WalRcvData::walRcvState.

Referenced by ShutdownWalRcv(), StartupRequestWalReceiverRestart(), and walrcv_clear_result().

73 {
74  WalRcvData *walrcv = WalRcv;
76  pg_time_t startTime;
77 
78  SpinLockAcquire(&walrcv->mutex);
79 
80  state = walrcv->walRcvState;
81  startTime = walrcv->startTime;
82 
83  SpinLockRelease(&walrcv->mutex);
84 
85  /*
86  * If it has taken too long for walreceiver to start up, give up. Setting
87  * the state to STOPPED ensures that if walreceiver later does start up
88  * after all, it will see that it's not supposed to be running and die
89  * without doing anything.
90  */
91  if (state == WALRCV_STARTING)
92  {
93  pg_time_t now = (pg_time_t) time(NULL);
94 
95  if ((now - startTime) > WALRCV_STARTUP_TIMEOUT)
96  {
97  SpinLockAcquire(&walrcv->mutex);
98 
99  if (walrcv->walRcvState == WALRCV_STARTING)
100  state = walrcv->walRcvState = WALRCV_STOPPED;
101 
102  SpinLockRelease(&walrcv->mutex);
103  }
104  }
105 
106  if (state != WALRCV_STOPPED)
107  return true;
108  else
109  return false;
110 }
int64 pg_time_t
Definition: pgtime.h:23
slock_t mutex
Definition: walreceiver.h:143
WalRcvState walRcvState
Definition: walreceiver.h:64
pg_time_t startTime
Definition: walreceiver.h:65
WalRcvState
Definition: walreceiver.h:44
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
#define WALRCV_STARTUP_TIMEOUT
Definition: regguts.h:298
WalRcvData * WalRcv
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1538

◆ WalRcvShmemInit()

void WalRcvShmemInit ( void  )

Definition at line 53 of file walreceiverfuncs.c.

References WalRcvData::latch, MemSet, WalRcvData::mutex, ShmemInitStruct(), SpinLockInit, WALRCV_STOPPED, WalRcvShmemSize(), and WalRcvData::walRcvState.

Referenced by CreateSharedMemoryAndSemaphores(), and walrcv_clear_result().

54 {
55  bool found;
56 
57  WalRcv = (WalRcvData *)
58  ShmemInitStruct("Wal Receiver Ctl", WalRcvShmemSize(), &found);
59 
60  if (!found)
61  {
62  /* First time through, so initialize */
66  WalRcv->latch = NULL;
67  }
68 }
slock_t mutex
Definition: walreceiver.h:143
WalRcvState walRcvState
Definition: walreceiver.h:64
#define SpinLockInit(lock)
Definition: spin.h:60
#define MemSet(start, val, len)
Definition: c.h:949
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:392
Latch * latch
Definition: walreceiver.h:141
Size WalRcvShmemSize(void)
WalRcvData * WalRcv

◆ WalRcvShmemSize()

Size WalRcvShmemSize ( void  )

Definition at line 42 of file walreceiverfuncs.c.

References add_size().

Referenced by CreateSharedMemoryAndSemaphores(), walrcv_clear_result(), and WalRcvShmemInit().

43 {
44  Size size = 0;
45 
46  size = add_size(size, sizeof(WalRcvData));
47 
48  return size;
49 }
Size add_size(Size s1, Size s2)
Definition: shmem.c:498
size_t Size
Definition: c.h:473

◆ WalRcvStreaming()

bool WalRcvStreaming ( void  )

Definition at line 117 of file walreceiverfuncs.c.

References WalRcvData::mutex, now(), SpinLockAcquire, SpinLockRelease, WalRcvData::startTime, WalRcv, WALRCV_RESTARTING, WALRCV_STARTING, WALRCV_STARTUP_TIMEOUT, WALRCV_STOPPED, WALRCV_STREAMING, and WalRcvData::walRcvState.

Referenced by StartupXLOG(), WaitForWALToBecomeAvailable(), and walrcv_clear_result().

118 {
119  WalRcvData *walrcv = WalRcv;
121  pg_time_t startTime;
122 
123  SpinLockAcquire(&walrcv->mutex);
124 
125  state = walrcv->walRcvState;
126  startTime = walrcv->startTime;
127 
128  SpinLockRelease(&walrcv->mutex);
129 
130  /*
131  * If it has taken too long for walreceiver to start up, give up. Setting
132  * the state to STOPPED ensures that if walreceiver later does start up
133  * after all, it will see that it's not supposed to be running and die
134  * without doing anything.
135  */
136  if (state == WALRCV_STARTING)
137  {
138  pg_time_t now = (pg_time_t) time(NULL);
139 
140  if ((now - startTime) > WALRCV_STARTUP_TIMEOUT)
141  {
142  SpinLockAcquire(&walrcv->mutex);
143 
144  if (walrcv->walRcvState == WALRCV_STARTING)
145  state = walrcv->walRcvState = WALRCV_STOPPED;
146 
147  SpinLockRelease(&walrcv->mutex);
148  }
149  }
150 
151  if (state == WALRCV_STREAMING || state == WALRCV_STARTING ||
152  state == WALRCV_RESTARTING)
153  return true;
154  else
155  return false;
156 }
int64 pg_time_t
Definition: pgtime.h:23
slock_t mutex
Definition: walreceiver.h:143
WalRcvState walRcvState
Definition: walreceiver.h:64
pg_time_t startTime
Definition: walreceiver.h:65
WalRcvState
Definition: walreceiver.h:44
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
#define WALRCV_STARTUP_TIMEOUT
Definition: regguts.h:298
WalRcvData * WalRcv
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1538

◆ WalReceiverMain()

void WalReceiverMain ( void  )

Definition at line 178 of file walreceiver.c.

References ARCHIVE_MODE_ALWAYS, Assert, BlockSig, buf, close, cluster_name, WalRcvData::conninfo, DEBUG1, elog, ereport, errcode_for_file_access(), errdetail(), errmsg(), ERROR, FATAL, WalRcvData::force_reply, GetCurrentTimestamp(), GetSystemIdentifier(), GetXLogReplayRecPtr(), got_SIGHUP, initStringInfo(), WalRcvData::is_temp_slot, WalRcvData::lastMsgReceiptTime, WalRcvData::lastMsgSendTime, WalRcvData::latch, WalRcvData::latestWalEndTime, load_file(), LOG, WalRcvStreamOptions::logical, LogstreamResult, MAXCONNINFO, MAXFNAMELEN, WalRcvData::mutex, MyProc, MyProcPid, NAMEDATALEN, NAPTIME_PER_CYCLE, NI_MAXHOST, now(), on_shmem_exit(), options, PANIC, pfree(), pg_atomic_init_u64(), pg_memory_barrier, PG_SETMASK, PGC_SIGHUP, PGINVALID_SOCKET, WalRcvStreamOptions::physical, WalRcvData::pid, pqsignal(), proc_exit(), ProcessConfigFile(), ProcessWalRcvInterrupts(), PGPROC::procLatch, procsignal_sigusr1_handler(), WalRcvStreamOptions::proto, WalRcvData::ready_to_display, WalRcvData::receiveStart, WalRcvData::receiveStartTLI, RecoveryInProgress(), recvFile, recvFileTLI, recvSegNo, ResetLatch(), WalRcvData::sender_host, WalRcvData::sender_port, SIG_DFL, SIG_IGN, SIGALRM, SIGCHLD, SIGHUP, SignalHandlerForCrashExit(), SIGPIPE, SIGQUIT, SIGUSR1, SIGUSR2, WalRcvData::slotname, WalRcvStreamOptions::slotname, snprintf, SpinLockAcquire, SpinLockRelease, WalRcvStreamOptions::startpoint, strlcpy(), ThisTimeLineID, TimestampTzPlusMilliseconds, UINT64_FORMAT, UnBlockSig, WAIT_EVENT_WAL_RECEIVER_MAIN, WaitLatchOrSocket(), wal_receiver_timeout, wal_segment_size, WalRcv, walrcv_connect, walrcv_create_slot, walrcv_endstreaming, walrcv_get_backend_pid, walrcv_get_conninfo, walrcv_get_senderinfo, walrcv_identify_system, walrcv_receive, WALRCV_RESTARTING, WALRCV_STARTING, walrcv_startstreaming, WALRCV_STOPPED, WALRCV_STOPPING, WALRCV_STREAMING, WALRCV_WAITING, WalRcvDie(), WalRcvFetchTimeLineHistoryFiles(), WalRcvShutdownHandler(), WalRcvSigHupHandler(), WalRcvData::walRcvState, WalRcvWaitForStartPosition(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, WL_SOCKET_READABLE, WL_TIMEOUT, WalRcvData::writtenUpto, XLogArchiveForceDone(), XLogArchiveMode, XLogArchiveNotify(), XLogFileName, XLogWalRcvFlush(), XLogWalRcvProcessMsg(), XLogWalRcvSendHSFeedback(), and XLogWalRcvSendReply().

Referenced by AuxiliaryProcessMain(), and walrcv_clear_result().

179 {
180  char conninfo[MAXCONNINFO];
181  char *tmp_conninfo;
182  char slotname[NAMEDATALEN];
183  bool is_temp_slot;
184  XLogRecPtr startpoint;
185  TimeLineID startpointTLI;
186  TimeLineID primaryTLI;
187  bool first_stream;
188  WalRcvData *walrcv = WalRcv;
189  TimestampTz last_recv_timestamp;
191  bool ping_sent;
192  char *err;
193  char *sender_host = NULL;
194  int sender_port = 0;
195 
196  /*
197  * WalRcv should be set up already (if we are a backend, we inherit this
198  * by fork() or EXEC_BACKEND mechanism from the postmaster).
199  */
200  Assert(walrcv != NULL);
201 
202  now = GetCurrentTimestamp();
203 
204  /*
205  * Mark walreceiver as running in shared memory.
206  *
207  * Do this as early as possible, so that if we fail later on, we'll set
208  * state to STOPPED. If we die before this, the startup process will keep
209  * waiting for us to start up, until it times out.
210  */
211  SpinLockAcquire(&walrcv->mutex);
212  Assert(walrcv->pid == 0);
213  switch (walrcv->walRcvState)
214  {
215  case WALRCV_STOPPING:
216  /* If we've already been requested to stop, don't start up. */
217  walrcv->walRcvState = WALRCV_STOPPED;
218  /* fall through */
219 
220  case WALRCV_STOPPED:
221  SpinLockRelease(&walrcv->mutex);
222  proc_exit(1);
223  break;
224 
225  case WALRCV_STARTING:
226  /* The usual case */
227  break;
228 
229  case WALRCV_WAITING:
230  case WALRCV_STREAMING:
231  case WALRCV_RESTARTING:
232  default:
233  /* Shouldn't happen */
234  SpinLockRelease(&walrcv->mutex);
235  elog(PANIC, "walreceiver still running according to shared memory state");
236  }
237  /* Advertise our PID so that the startup process can kill us */
238  walrcv->pid = MyProcPid;
239  walrcv->walRcvState = WALRCV_STREAMING;
240 
241  /* Fetch information required to start streaming */
242  walrcv->ready_to_display = false;
243  strlcpy(conninfo, (char *) walrcv->conninfo, MAXCONNINFO);
244  strlcpy(slotname, (char *) walrcv->slotname, NAMEDATALEN);
245  is_temp_slot = walrcv->is_temp_slot;
246  startpoint = walrcv->receiveStart;
247  startpointTLI = walrcv->receiveStartTLI;
248 
249  /*
250  * At most one of is_temp_slot and slotname can be set; otherwise,
251  * RequestXLogStreaming messed up.
252  */
253  Assert(!is_temp_slot || (slotname[0] == '\0'));
254 
255  /* Initialise to a sanish value */
256  walrcv->lastMsgSendTime =
257  walrcv->lastMsgReceiptTime = walrcv->latestWalEndTime = now;
258 
259  /* Report the latch to use to awaken this process */
260  walrcv->latch = &MyProc->procLatch;
261 
262  SpinLockRelease(&walrcv->mutex);
263 
265 
266  /* Arrange to clean up at walreceiver exit */
268 
269  /* Properly accept or ignore signals the postmaster might send us */
270  pqsignal(SIGHUP, WalRcvSigHupHandler); /* set flag to read config file */
271  pqsignal(SIGINT, SIG_IGN);
272  pqsignal(SIGTERM, WalRcvShutdownHandler); /* request shutdown */
278 
279  /* Reset some signals that are accepted by postmaster but not here */
281 
282  /* We allow SIGQUIT (quickdie) at all times */
283  sigdelset(&BlockSig, SIGQUIT);
284 
285  /* Load the libpq-specific functions */
286  load_file("libpqwalreceiver", false);
287  if (WalReceiverFunctions == NULL)
288  elog(ERROR, "libpqwalreceiver didn't initialize correctly");
289 
290  /* Unblock signals (they were blocked when the postmaster forked us) */
292 
293  /* Establish the connection to the primary for XLOG streaming */
294  wrconn = walrcv_connect(conninfo, false, cluster_name[0] ? cluster_name : "walreceiver", &err);
295  if (!wrconn)
296  ereport(ERROR,
297  (errmsg("could not connect to the primary server: %s", err)));
298 
299  /*
300  * Save user-visible connection string. This clobbers the original
301  * conninfo, for security. Also save host and port of the sender server
302  * this walreceiver is connected to.
303  */
304  tmp_conninfo = walrcv_get_conninfo(wrconn);
305  walrcv_get_senderinfo(wrconn, &sender_host, &sender_port);
306  SpinLockAcquire(&walrcv->mutex);
307  memset(walrcv->conninfo, 0, MAXCONNINFO);
308  if (tmp_conninfo)
309  strlcpy((char *) walrcv->conninfo, tmp_conninfo, MAXCONNINFO);
310 
311  memset(walrcv->sender_host, 0, NI_MAXHOST);
312  if (sender_host)
313  strlcpy((char *) walrcv->sender_host, sender_host, NI_MAXHOST);
314 
315  walrcv->sender_port = sender_port;
316  walrcv->ready_to_display = true;
317  SpinLockRelease(&walrcv->mutex);
318 
319  if (tmp_conninfo)
320  pfree(tmp_conninfo);
321 
322  if (sender_host)
323  pfree(sender_host);
324 
325  first_stream = true;
326  for (;;)
327  {
328  char *primary_sysid;
329  char standby_sysid[32];
331 
332  /*
333  * Check that we're connected to a valid server using the
334  * IDENTIFY_SYSTEM replication command.
335  */
336  primary_sysid = walrcv_identify_system(wrconn, &primaryTLI);
337 
338  snprintf(standby_sysid, sizeof(standby_sysid), UINT64_FORMAT,
340  if (strcmp(primary_sysid, standby_sysid) != 0)
341  {
342  ereport(ERROR,
343  (errmsg("database system identifier differs between the primary and standby"),
344  errdetail("The primary's identifier is %s, the standby's identifier is %s.",
345  primary_sysid, standby_sysid)));
346  }
347 
348  /*
349  * Confirm that the current timeline of the primary is the same or
350  * ahead of ours.
351  */
352  if (primaryTLI < startpointTLI)
353  ereport(ERROR,
354  (errmsg("highest timeline %u of the primary is behind recovery timeline %u",
355  primaryTLI, startpointTLI)));
356 
357  /*
358  * Get any missing history files. We do this always, even when we're
359  * not interested in that timeline, so that if we're promoted to
360  * become the primary later on, we don't select the same timeline that
361  * was already used in the current primary. This isn't bullet-proof -
362  * you'll need some external software to manage your cluster if you
363  * need to ensure that a unique timeline id is chosen in every case,
364  * but let's avoid the confusion of timeline id collisions where we
365  * can.
366  */
367  WalRcvFetchTimeLineHistoryFiles(startpointTLI, primaryTLI);
368 
369  /*
370  * Create temporary replication slot if requested, and update slot
371  * name in shared memory. (Note the slot name cannot already be set
372  * in this case.)
373  */
374  if (is_temp_slot)
375  {
376  snprintf(slotname, sizeof(slotname),
377  "pg_walreceiver_%lld",
378  (long long int) walrcv_get_backend_pid(wrconn));
379 
380  walrcv_create_slot(wrconn, slotname, true, 0, NULL);
381 
382  SpinLockAcquire(&walrcv->mutex);
383  strlcpy(walrcv->slotname, slotname, NAMEDATALEN);
384  SpinLockRelease(&walrcv->mutex);
385  }
386 
387  /*
388  * Start streaming.
389  *
390  * We'll try to start at the requested starting point and timeline,
391  * even if it's different from the server's latest timeline. In case
392  * we've already reached the end of the old timeline, the server will
393  * finish the streaming immediately, and we will go back to await
394  * orders from the startup process. If recovery_target_timeline is
395  * 'latest', the startup process will scan pg_wal and find the new
396  * history file, bump recovery target timeline, and ask us to restart
397  * on the new timeline.
398  */
399  options.logical = false;
400  options.startpoint = startpoint;
401  options.slotname = slotname[0] != '\0' ? slotname : NULL;
402  options.proto.physical.startpointTLI = startpointTLI;
403  ThisTimeLineID = startpointTLI;
404  if (walrcv_startstreaming(wrconn, &options))
405  {
406  if (first_stream)
407  ereport(LOG,
408  (errmsg("started streaming WAL from primary at %X/%X on timeline %u",
409  (uint32) (startpoint >> 32), (uint32) startpoint,
410  startpointTLI)));
411  else
412  ereport(LOG,
413  (errmsg("restarted WAL streaming at %X/%X on timeline %u",
414  (uint32) (startpoint >> 32), (uint32) startpoint,
415  startpointTLI)));
416  first_stream = false;
417 
418  /* Initialize LogstreamResult and buffers for processing messages */
422 
423  /* Initialize the last recv timestamp */
424  last_recv_timestamp = GetCurrentTimestamp();
425  ping_sent = false;
426 
427  /* Loop until end-of-streaming or error */
428  for (;;)
429  {
430  char *buf;
431  int len;
432  bool endofwal = false;
433  pgsocket wait_fd = PGINVALID_SOCKET;
434  int rc;
435 
436  /*
437  * Exit walreceiver if we're not in recovery. This should not
438  * happen, but cross-check the status here.
439  */
440  if (!RecoveryInProgress())
441  ereport(FATAL,
442  (errmsg("cannot continue WAL streaming, recovery has already ended")));
443 
444  /* Process any requests or signals received recently */
446 
447  if (got_SIGHUP)
448  {
449  got_SIGHUP = false;
452  }
453 
454  /* See if we can read data immediately */
455  len = walrcv_receive(wrconn, &buf, &wait_fd);
456  if (len != 0)
457  {
458  /*
459  * Process the received data, and any subsequent data we
460  * can read without blocking.
461  */
462  for (;;)
463  {
464  if (len > 0)
465  {
466  /*
467  * Something was received from primary, so reset
468  * timeout
469  */
470  last_recv_timestamp = GetCurrentTimestamp();
471  ping_sent = false;
472  XLogWalRcvProcessMsg(buf[0], &buf[1], len - 1);
473  }
474  else if (len == 0)
475  break;
476  else if (len < 0)
477  {
478  ereport(LOG,
479  (errmsg("replication terminated by primary server"),
480  errdetail("End of WAL reached on timeline %u at %X/%X.",
481  startpointTLI,
482  (uint32) (LogstreamResult.Write >> 32), (uint32) LogstreamResult.Write)));
483  endofwal = true;
484  break;
485  }
486  len = walrcv_receive(wrconn, &buf, &wait_fd);
487  }
488 
489  /* Let the primary know that we received some data. */
490  XLogWalRcvSendReply(false, false);
491 
492  /*
493  * If we've written some records, flush them to disk and
494  * let the startup process and primary server know about
495  * them.
496  */
497  XLogWalRcvFlush(false);
498  }
499 
500  /* Check if we need to exit the streaming loop. */
501  if (endofwal)
502  break;
503 
504  /*
505  * Ideally we would reuse a WaitEventSet object repeatedly
506  * here to avoid the overheads of WaitLatchOrSocket on epoll
507  * systems, but we can't be sure that libpq (or any other
508  * walreceiver implementation) has the same socket (even if
509  * the fd is the same number, it may have been closed and
510  * reopened since the last time). In future, if there is a
511  * function for removing sockets from WaitEventSet, then we
512  * could add and remove just the socket each time, potentially
513  * avoiding some system calls.
514  */
515  Assert(wait_fd != PGINVALID_SOCKET);
516  rc = WaitLatchOrSocket(walrcv->latch,
519  wait_fd,
522  if (rc & WL_LATCH_SET)
523  {
524  ResetLatch(walrcv->latch);
526 
527  if (walrcv->force_reply)
528  {
529  /*
530  * The recovery process has asked us to send apply
531  * feedback now. Make sure the flag is really set to
532  * false in shared memory before sending the reply, so
533  * we don't miss a new request for a reply.
534  */
535  walrcv->force_reply = false;
537  XLogWalRcvSendReply(true, false);
538  }
539  }
540  if (rc & WL_TIMEOUT)
541  {
542  /*
543  * We didn't receive anything new. If we haven't heard
544  * anything from the server for more than
545  * wal_receiver_timeout / 2, ping the server. Also, if
546  * it's been longer than wal_receiver_status_interval
547  * since the last update we sent, send a status update to
548  * the primary anyway, to report any progress in applying
549  * WAL.
550  */
551  bool requestReply = false;
552 
553  /*
554  * Check if time since last receive from standby has
555  * reached the configured limit.
556  */
557  if (wal_receiver_timeout > 0)
558  {
560  TimestampTz timeout;
561 
562  timeout =
563  TimestampTzPlusMilliseconds(last_recv_timestamp,
565 
566  if (now >= timeout)
567  ereport(ERROR,
568  (errmsg("terminating walreceiver due to timeout")));
569 
570  /*
571  * We didn't receive anything new, for half of
572  * receiver replication timeout. Ping the server.
573  */
574  if (!ping_sent)
575  {
576  timeout = TimestampTzPlusMilliseconds(last_recv_timestamp,
577  (wal_receiver_timeout / 2));
578  if (now >= timeout)
579  {
580  requestReply = true;
581  ping_sent = true;
582  }
583  }
584  }
585 
586  XLogWalRcvSendReply(requestReply, requestReply);
588  }
589  }
590 
591  /*
592  * The backend finished streaming. Exit streaming COPY-mode from
593  * our side, too.
594  */
595  walrcv_endstreaming(wrconn, &primaryTLI);
596 
597  /*
598  * If the server had switched to a new timeline that we didn't
599  * know about when we began streaming, fetch its timeline history
600  * file now.
601  */
602  WalRcvFetchTimeLineHistoryFiles(startpointTLI, primaryTLI);
603  }
604  else
605  ereport(LOG,
606  (errmsg("primary server contains no more WAL on requested timeline %u",
607  startpointTLI)));
608 
609  /*
610  * End of WAL reached on the requested timeline. Close the last
611  * segment, and await for new orders from the startup process.
612  */
613  if (recvFile >= 0)
614  {
615  char xlogfname[MAXFNAMELEN];
616 
617  XLogWalRcvFlush(false);
619  if (close(recvFile) != 0)
620  ereport(PANIC,
622  errmsg("could not close log segment %s: %m",
623  xlogfname)));
624 
625  /*
626  * Create .done file forcibly to prevent the streamed segment from
627  * being archived later.
628  */
630  XLogArchiveForceDone(xlogfname);
631  else
632  XLogArchiveNotify(xlogfname);
633  }
634  recvFile = -1;
635 
636  elog(DEBUG1, "walreceiver ended streaming and awaits new instructions");
637  WalRcvWaitForStartPosition(&startpoint, &startpointTLI);
638  }
639  /* not reached */
640 }
int sender_port
Definition: walreceiver.h:117
#define SIGQUIT
Definition: win32_port.h:154
static void WalRcvFetchTimeLineHistoryFiles(TimeLineID first, TimeLineID last)
Definition: walreceiver.c:727
#define walrcv_get_conninfo(conn)
Definition: walreceiver.h:401
#define walrcv_endstreaming(conn, next_tli)
Definition: walreceiver.h:413
#define DEBUG1
Definition: elog.h:25
int MyProcPid
Definition: globals.c:40
uint32 TimeLineID
Definition: xlogdefs.h:52
slock_t mutex
Definition: walreceiver.h:143
#define WL_TIMEOUT
Definition: latch.h:127
void ProcessConfigFile(GucContext context)
int wal_segment_size
Definition: xlog.c:116
#define SIGUSR1
Definition: win32_port.h:165
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1574
#define SIGCHLD
Definition: win32_port.h:163
PGPROC * MyProc
Definition: proc.c:67
int64 TimestampTz
Definition: timestamp.h:39
static void WalRcvWaitForStartPosition(XLogRecPtr *startpoint, TimeLineID *startpointTLI)
Definition: walreceiver.c:646
sig_atomic_t force_reply
Definition: walreceiver.h:158
#define walrcv_identify_system(conn, primary_tli)
Definition: walreceiver.h:405
WalRcvState walRcvState
Definition: walreceiver.h:64
static StringInfoData incoming_message
Definition: walreceiver.c:125
static void XLogWalRcvSendHSFeedback(bool immed)
Definition: walreceiver.c:1129
#define walrcv_receive(conn, buffer, wait_fd)
Definition: walreceiver.h:415
void ProcessWalRcvInterrupts(void)
Definition: walreceiver.c:157
static void WalRcvSigHupHandler(SIGNAL_ARGS)
Definition: walreceiver.c:805
#define walrcv_startstreaming(conn, options)
Definition: walreceiver.h:411
union WalRcvStreamOptions::@104 proto
void proc_exit(int code)
Definition: ipc.c:104
#define WL_SOCKET_READABLE
Definition: latch.h:125
static void XLogWalRcvProcessMsg(unsigned char type, char *buf, Size len)
Definition: walreceiver.c:829
#define SIGPIPE
Definition: win32_port.h:158
#define SIGUSR2
Definition: win32_port.h:166
#define LOG
Definition: elog.h:26
bool RecoveryInProgress(void)
Definition: xlog.c:8069
#define walrcv_create_slot(conn, slotname, temporary, snapshot_action, lsn)
Definition: walreceiver.h:419
#define PANIC
Definition: elog.h:53
#define NAPTIME_PER_CYCLE
Definition: walreceiver.c:96
TimestampTz lastMsgReceiptTime
Definition: walreceiver.h:98
void ResetLatch(Latch *latch)
Definition: latch.c:588
TimestampTz lastMsgSendTime
Definition: walreceiver.h:97
#define PG_SETMASK(mask)
Definition: pqsignal.h:19
int wal_receiver_timeout
Definition: walreceiver.c:89
Latch procLatch
Definition: proc.h:121
static WalReceiverConn * wrconn
Definition: walreceiver.c:93
pg_atomic_uint64 writtenUpto
Definition: walreceiver.h:151
#define NAMEDATALEN
#define SpinLockAcquire(lock)
Definition: spin.h:62
static StringInfoData reply_message
Definition: walreceiver.c:124
void XLogArchiveNotify(const char *xlog)
Definition: xlogarchive.c:466
void SignalHandlerForCrashExit(SIGNAL_ARGS)
Definition: interrupt.c:72
void pfree(void *pointer)
Definition: mcxt.c:1056
static void pg_atomic_init_u64(volatile pg_atomic_uint64 *ptr, uint64 val)
Definition: atomics.h:415
#define NI_MAXHOST
Definition: getaddrinfo.h:88
#define ERROR
Definition: elog.h:43
#define FATAL
Definition: elog.h:52
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
Definition: xlog.c:11475
pid_t pid
Definition: walreceiver.h:63
#define MAXCONNINFO
Definition: walreceiver.h:36
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:361
static char * buf
Definition: pg_test_fsync.c:67
int XLogArchiveMode
Definition: xlog.c:94
int errdetail(const char *fmt,...)
Definition: elog.c:957
static struct @24 LogstreamResult
int errcode_for_file_access(void)
Definition: elog.c:633
#define SIGHUP
Definition: win32_port.h:153
XLogRecPtr startpoint
Definition: walreceiver.h:168
int WaitLatchOrSocket(Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition: latch.c:438
unsigned int uint32
Definition: c.h:374
int pgsocket
Definition: port.h:31
sigset_t UnBlockSig
Definition: pqsignal.c:22
static volatile sig_atomic_t got_SIGHUP
Definition: walreceiver.c:111
TimeLineID receiveStartTLI
Definition: walreceiver.h:74
static TimeLineID recvFileTLI
Definition: walreceiver.c:104
#define walrcv_get_backend_pid(conn)
Definition: walreceiver.h:421
Definition: guc.h:72
char * cluster_name
Definition: guc.c:555
Latch * latch
Definition: walreceiver.h:141
#define SIG_IGN
Definition: win32_port.h:150
static char ** options
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
static XLogSegNo recvSegNo
Definition: walreceiver.c:105
#define MAXFNAMELEN
#define SpinLockRelease(lock)
Definition: spin.h:64
sigset_t BlockSig
Definition: pqsignal.c:22
void XLogArchiveForceDone(const char *xlog)
Definition: xlogarchive.c:516
WalReceiverFunctionsType * WalReceiverFunctions
Definition: walreceiver.c:94
#define PGINVALID_SOCKET
Definition: port.h:33
static void XLogWalRcvSendReply(bool force, bool requestReply)
Definition: walreceiver.c:1060
bool ready_to_display
Definition: walreceiver.h:132
TimestampTz latestWalEndTime
Definition: walreceiver.h:104
static void WalRcvShutdownHandler(SIGNAL_ARGS)
Definition: walreceiver.c:813
TimeLineID ThisTimeLineID
Definition: xlog.c:191
#define TimestampTzPlusMilliseconds(tz, ms)
Definition: timestamp.h:56
#define ereport(elevel,...)
Definition: elog.h:144
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
size_t strlcpy(char *dst, const char *src, size_t siz)
Definition: strlcpy.c:45
#define pg_memory_barrier()
Definition: atomics.h:145
#define SIG_DFL
Definition: win32_port.h:148
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:745
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:146
#define XLogFileName(fname, tli, logSegNo, wal_segsz_bytes)
#define SIGALRM
Definition: win32_port.h:159
bool is_temp_slot
Definition: walreceiver.h:129
static void XLogWalRcvFlush(bool dying)
Definition: walreceiver.c:1001
WalRcvData * WalRcv
uint64 GetSystemIdentifier(void)
Definition: xlog.c:4910
char sender_host[NI_MAXHOST]
Definition: walreceiver.h:116
int errmsg(const char *fmt,...)
Definition: elog.c:824
static void WalRcvDie(int code, Datum arg)
Definition: walreceiver.c:774
#define elog(elevel,...)
Definition: elog.h:214
#define walrcv_get_senderinfo(conn, sender_host, sender_port)
Definition: walreceiver.h:403
struct WalRcvStreamOptions::@104::@105 physical
#define close(a)
Definition: win32.h:12
XLogRecPtr receiveStart
Definition: walreceiver.h:73
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition: procsignal.c:551
static int recvFile
Definition: walreceiver.c:103
#define snprintf
Definition: port.h:193
#define WL_LATCH_SET
Definition: latch.h:124
#define UINT64_FORMAT
Definition: c.h:417
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1538
char slotname[NAMEDATALEN]
Definition: walreceiver.h:123
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:129
char conninfo[MAXCONNINFO]
Definition: walreceiver.h:110
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:397

Variable Documentation

◆ hot_standby_feedback

bool hot_standby_feedback

Definition at line 90 of file walreceiver.c.

Referenced by XLogWalRcvSendHSFeedback().

◆ wal_receiver_status_interval

int wal_receiver_status_interval

Definition at line 88 of file walreceiver.c.

Referenced by send_feedback(), XLogWalRcvSendHSFeedback(), and XLogWalRcvSendReply().

◆ wal_receiver_timeout

int wal_receiver_timeout

Definition at line 89 of file walreceiver.c.

Referenced by logicalrep_worker_launch(), LogicalRepApplyLoop(), and WalReceiverMain().

◆ WalRcv

◆ WalReceiverFunctions

PGDLLIMPORT WalReceiverFunctionsType* WalReceiverFunctions

Definition at line 94 of file walreceiver.c.

Referenced by _PG_init().