PostgreSQL Source Code  git master
walreceiver.h File Reference
#include "access/xlog.h"
#include "access/xlogdefs.h"
#include "fmgr.h"
#include "getaddrinfo.h"
#include "replication/logicalproto.h"
#include "replication/walsender.h"
#include "storage/latch.h"
#include "storage/spin.h"
#include "pgtime.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, server_version)   WalReceiverFunctions->walrcv_identify_system(conn, primary_tli, server_version)
 
#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_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, int *server_version)
 
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 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()
 
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)
 
XLogRecPtr GetWalRcvWriteRecPtr (XLogRecPtr *latestChunkStart, TimeLineID *receiveTLI)
 
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 257 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 275 of file walreceiver.h.

Referenced by CreateSubscription(), and LogicalRepSyncTableStart().

◆ 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_conninfo

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

Definition at line 259 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 261 of file walreceiver.h.

Referenced by WalReceiverMain().

◆ walrcv_identify_system

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

Definition at line 263 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 265 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 271 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 273 of file walreceiver.h.

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

◆ walrcv_startstreaming

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

Definition at line 267 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 206 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 203 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 226 of file walreceiver.h.

◆ walrcv_disconnect_fn

typedef void(* walrcv_disconnect_fn) (WalReceiverConn *conn)

Definition at line 234 of file walreceiver.h.

◆ walrcv_endstreaming_fn

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

Definition at line 220 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 230 of file walreceiver.h.

◆ walrcv_get_conninfo_fn

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

Definition at line 207 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 208 of file walreceiver.h.

◆ walrcv_identify_system_fn

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

Definition at line 211 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 214 of file walreceiver.h.

◆ walrcv_receive_fn

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

Definition at line 222 of file walreceiver.h.

◆ walrcv_send_fn

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

Definition at line 224 of file walreceiver.h.

◆ walrcv_startstreaming_fn

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

Definition at line 218 of file walreceiver.h.

◆ WalRcvExecResult

◆ WalReceiverConn

Definition at line 171 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 178 of file walreceiver.h.

179 {
180  WALRCV_ERROR, /* There was error when executing the query. */
181  WALRCV_OK_COMMAND, /* Query executed utility or replication
182  * command. */
183  WALRCV_OK_TUPLES, /* Query returned tuples. */
184  WALRCV_OK_COPY_IN, /* Query started COPY FROM. */
185  WALRCV_OK_COPY_OUT, /* Query started COPY TO. */
186  WALRCV_OK_COPY_BOTH /* Query started COPY BOTH replication
187  * protocol. */
WalRcvExecStatus
Definition: walreceiver.h:178

◆ 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 318 of file walreceiverfuncs.c.

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

Referenced by ProcessWalSndrMessage(), and walrcv_clear_result().

319 {
320  WalRcvData *walrcv = WalRcv;
321  XLogRecPtr receivePtr;
322  XLogRecPtr replayPtr;
323 
324  long secs;
325  int usecs;
326 
327  TimestampTz chunkReplayStartTime;
328 
329  SpinLockAcquire(&walrcv->mutex);
330  receivePtr = walrcv->receivedUpto;
331  SpinLockRelease(&walrcv->mutex);
332 
333  replayPtr = GetXLogReplayRecPtr(NULL);
334 
335  if (receivePtr == replayPtr)
336  return 0;
337 
338  chunkReplayStartTime = GetCurrentChunkReplayStartTime();
339 
340  if (chunkReplayStartTime == 0)
341  return -1;
342 
343  TimestampDifference(chunkReplayStartTime,
345  &secs, &usecs);
346 
347  return (((int) secs * 1000) + (usecs / 1000));
348 }
slock_t mutex
Definition: walreceiver.h:137
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
int64 TimestampTz
Definition: timestamp.h:39
#define SpinLockAcquire(lock)
Definition: spin.h:62
TimestampTz GetCurrentChunkReplayStartTime(void)
Definition: xlog.c:6179
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
Definition: xlog.c:11184
XLogRecPtr receivedUpto
Definition: walreceiver.h:83
#define SpinLockRelease(lock)
Definition: spin.h:64
uint64 XLogRecPtr
Definition: xlogdefs.h:21
WalRcvData * WalRcv
void TimestampDifference(TimestampTz start_time, TimestampTz stop_time, long *secs, int *microsecs)
Definition: timestamp.c:1624

◆ GetReplicationTransferLatency()

int GetReplicationTransferLatency ( void  )

Definition at line 355 of file walreceiverfuncs.c.

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

Referenced by ProcessWalSndrMessage(), and walrcv_clear_result().

356 {
357  WalRcvData *walrcv = WalRcv;
358 
359  TimestampTz lastMsgSendTime;
360  TimestampTz lastMsgReceiptTime;
361 
362  long secs = 0;
363  int usecs = 0;
364  int ms;
365 
366  SpinLockAcquire(&walrcv->mutex);
367  lastMsgSendTime = walrcv->lastMsgSendTime;
368  lastMsgReceiptTime = walrcv->lastMsgReceiptTime;
369  SpinLockRelease(&walrcv->mutex);
370 
371  TimestampDifference(lastMsgSendTime,
372  lastMsgReceiptTime,
373  &secs, &usecs);
374 
375  ms = ((int) secs * 1000) + (usecs / 1000);
376 
377  return ms;
378 }
slock_t mutex
Definition: walreceiver.h:137
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:1624

◆ GetWalRcvWriteRecPtr()

XLogRecPtr GetWalRcvWriteRecPtr ( XLogRecPtr latestChunkStart,
TimeLineID receiveTLI 
)

Definition at line 297 of file walreceiverfuncs.c.

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

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

298 {
299  WalRcvData *walrcv = WalRcv;
300  XLogRecPtr recptr;
301 
302  SpinLockAcquire(&walrcv->mutex);
303  recptr = walrcv->receivedUpto;
304  if (latestChunkStart)
305  *latestChunkStart = walrcv->latestChunkStart;
306  if (receiveTLI)
307  *receiveTLI = walrcv->receivedTLI;
308  SpinLockRelease(&walrcv->mutex);
309 
310  return recptr;
311 }
slock_t mutex
Definition: walreceiver.h:137
TimeLineID receivedTLI
Definition: walreceiver.h:84
#define SpinLockAcquire(lock)
Definition: spin.h:62
XLogRecPtr latestChunkStart
Definition: walreceiver.h:92
XLogRecPtr receivedUpto
Definition: walreceiver.h:83
#define SpinLockRelease(lock)
Definition: spin.h:64
static TimeLineID receiveTLI
Definition: xlog.c:203
uint64 XLogRecPtr
Definition: xlogdefs.h:21
WalRcvData * WalRcv

◆ RequestXLogStreaming()

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

Definition at line 223 of file walreceiverfuncs.c.

References Assert, WalRcvData::conninfo, WalRcvData::latch, WalRcvData::latestChunkStart, MAXCONNINFO, WalRcvData::mutex, NAMEDATALEN, now(), PMSIGNAL_START_WALRECEIVER, WalRcvData::receivedTLI, WalRcvData::receivedUpto, 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().

225 {
226  WalRcvData *walrcv = WalRcv;
227  bool launch = false;
228  pg_time_t now = (pg_time_t) time(NULL);
229  Latch *latch;
230 
231  /*
232  * We always start at the beginning of the segment. That prevents a broken
233  * segment (i.e., with no records in the first half of a segment) from
234  * being created by XLOG streaming, which might cause trouble later on if
235  * the segment is e.g archived.
236  */
237  if (XLogSegmentOffset(recptr, wal_segment_size) != 0)
238  recptr -= XLogSegmentOffset(recptr, wal_segment_size);
239 
240  SpinLockAcquire(&walrcv->mutex);
241 
242  /* It better be stopped if we try to restart it */
243  Assert(walrcv->walRcvState == WALRCV_STOPPED ||
244  walrcv->walRcvState == WALRCV_WAITING);
245 
246  if (conninfo != NULL)
247  strlcpy((char *) walrcv->conninfo, conninfo, MAXCONNINFO);
248  else
249  walrcv->conninfo[0] = '\0';
250 
251  if (slotname != NULL)
252  strlcpy((char *) walrcv->slotname, slotname, NAMEDATALEN);
253  else
254  walrcv->slotname[0] = '\0';
255 
256  if (walrcv->walRcvState == WALRCV_STOPPED)
257  {
258  launch = true;
259  walrcv->walRcvState = WALRCV_STARTING;
260  }
261  else
262  walrcv->walRcvState = WALRCV_RESTARTING;
263  walrcv->startTime = now;
264 
265  /*
266  * If this is the first startup of walreceiver (on this timeline),
267  * initialize receivedUpto and latestChunkStart to the starting point.
268  */
269  if (walrcv->receiveStart == 0 || walrcv->receivedTLI != tli)
270  {
271  walrcv->receivedUpto = recptr;
272  walrcv->receivedTLI = tli;
273  walrcv->latestChunkStart = recptr;
274  }
275  walrcv->receiveStart = recptr;
276  walrcv->receiveStartTLI = tli;
277 
278  latch = walrcv->latch;
279 
280  SpinLockRelease(&walrcv->mutex);
281 
282  if (launch)
284  else if (latch)
285  SetLatch(latch);
286 }
int64 pg_time_t
Definition: pgtime.h:23
slock_t mutex
Definition: walreceiver.h:137
int wal_segment_size
Definition: xlog.c:113
WalRcvState walRcvState
Definition: walreceiver.h:64
TimeLineID receivedTLI
Definition: walreceiver.h:84
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
XLogRecPtr receivedUpto
Definition: walreceiver.h:83
TimeLineID receiveStartTLI
Definition: walreceiver.h:74
Latch * latch
Definition: walreceiver.h:135
#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
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
#define Assert(condition)
Definition: c.h:699
WalRcvData * WalRcv
void SendPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:113
XLogRecPtr receiveStart
Definition: walreceiver.h:73
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1534
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:137
WalRcvState walRcvState
Definition: walreceiver.h:64
#define kill(pid, sig)
Definition: win32_port.h:437
#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:148
bool WalRcvRunning(void)

◆ walrcv_clear_result()

static void walrcv_clear_result ( WalRcvExecResult walres)
inlinestatic

Definition at line 283 of file walreceiver.h.

References WalRcvExecResult::err, FreeTupleDesc(), GetReplicationApplyDelay(), GetReplicationTransferLatency(), GetWalRcvWriteRecPtr(), pfree(), pg_attribute_noreturn, 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().

284 {
285  if (!walres)
286  return;
287 
288  if (walres->err)
289  pfree(walres->err);
290 
291  if (walres->tuplestore)
292  tuplestore_end(walres->tuplestore);
293 
294  if (walres->tupledesc)
295  FreeTupleDesc(walres->tupledesc);
296 
297  pfree(walres);
298 }
void pfree(void *pointer)
Definition: mcxt.c:1031
TupleDesc tupledesc
Definition: walreceiver.h:199
Tuplestorestate * tuplestore
Definition: walreceiver.h:198
void tuplestore_end(Tuplestorestate *state)
Definition: tuplestore.c:453
void FreeTupleDesc(TupleDesc tupdesc)
Definition: tupdesc.c:311

◆ WalRcvForceReply()

void WalRcvForceReply ( void  )

Definition at line 1360 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().

1361 {
1362  Latch *latch;
1363 
1364  WalRcv->force_reply = true;
1365  /* fetching the latch pointer might not be atomic, so use spinlock */
1367  latch = WalRcv->latch;
1369  if (latch)
1370  SetLatch(latch);
1371 }
slock_t mutex
Definition: walreceiver.h:137
sig_atomic_t force_reply
Definition: walreceiver.h:144
#define SpinLockAcquire(lock)
Definition: spin.h:62
Definition: latch.h:110
Latch * latch
Definition: walreceiver.h:135
#define SpinLockRelease(lock)
Definition: spin.h:64
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
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(), 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:137
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:1534

◆ 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:137
WalRcvState walRcvState
Definition: walreceiver.h:64
#define SpinLockInit(lock)
Definition: spin.h:60
#define MemSet(start, val, len)
Definition: c.h:908
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:372
Latch * latch
Definition: walreceiver.h:135
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:475
size_t Size
Definition: c.h:433

◆ 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 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:137
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:1534

◆ WalReceiverMain()

void WalReceiverMain ( void  )

Definition at line 189 of file walreceiver.c.

References ARCHIVE_MODE_ALWAYS, Assert, BlockSig, buf, close, WalRcvData::conninfo, CurrentResourceOwner, DEBUG1, DisableWalRcvImmediateExit(), elog, EnableWalRcvImmediateExit(), ereport, errcode_for_file_access(), errdetail(), errmsg(), ERROR, FATAL, WalRcvData::force_reply, GetCurrentTimestamp(), GetSystemIdentifier(), GetXLogReplayRecPtr(), got_SIGHUP, initStringInfo(), 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_memory_barrier, PG_SETMASK, PGC_SIGHUP, PGINVALID_SOCKET, WalRcvStreamOptions::physical, WalRcvData::pid, pqsignal(), proc_exit(), ProcessConfigFile(), ProcessWalRcvInterrupts(), PGPROC::procLatch, WalRcvStreamOptions::proto, WalRcvData::ready_to_display, WalRcvData::receiveStart, WalRcvData::receiveStartTLI, RecoveryInProgress(), recvFile, recvFileTLI, recvSegNo, ResetLatch(), ResourceOwnerCreate(), WalRcvData::sender_host, WalRcvData::sender_port, server_version, SIG_DFL, SIG_IGN, SIGALRM, SIGCHLD, SIGCONT, SIGHUP, SIGPIPE, SIGQUIT, SIGTTIN, SIGTTOU, SIGUSR1, SIGUSR2, SIGWINCH, 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_endstreaming, 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(), WalRcvQuickDieHandler(), WalRcvShutdownHandler(), WalRcvSigHupHandler(), WalRcvSigUsr1Handler(), WalRcvData::walRcvState, WalRcvWaitForStartPosition(), WL_LATCH_SET, WL_POSTMASTER_DEATH, WL_SOCKET_READABLE, WL_TIMEOUT, XLogArchiveForceDone(), XLogArchiveMode, XLogArchiveNotify(), XLogFileName, XLogFileNameP(), XLogWalRcvFlush(), XLogWalRcvProcessMsg(), XLogWalRcvSendHSFeedback(), and XLogWalRcvSendReply().

Referenced by AuxiliaryProcessMain(), and walrcv_clear_result().

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

Variable Documentation

◆ hot_standby_feedback

bool hot_standby_feedback

Definition at line 77 of file walreceiver.c.

Referenced by XLogWalRcvSendHSFeedback().

◆ wal_receiver_status_interval

int wal_receiver_status_interval

Definition at line 75 of file walreceiver.c.

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

◆ wal_receiver_timeout

int wal_receiver_timeout

Definition at line 76 of file walreceiver.c.

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

◆ WalRcv

◆ WalReceiverFunctions

PGDLLIMPORT WalReceiverFunctionsType* WalReceiverFunctions

Definition at line 81 of file walreceiver.c.

Referenced by _PG_init().