PostgreSQL Source Code  git master
walreceiver.h File Reference
#include "access/xlog.h"
#include "access/xlogdefs.h"
#include "fmgr.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_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 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 38 of file walreceiver.h.

Referenced by StartupXLOG(), and XLogWalRcvFlush().

◆ MAXCONNINFO

#define MAXCONNINFO   1024

Definition at line 35 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 245 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 261 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 247 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 249 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 251 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 257 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 259 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 253 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 198 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 195 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 215 of file walreceiver.h.

◆ walrcv_disconnect_fn

typedef void(* walrcv_disconnect_fn) (WalReceiverConn *conn)

Definition at line 223 of file walreceiver.h.

◆ walrcv_endstreaming_fn

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

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

◆ walrcv_get_conninfo_fn

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

Definition at line 199 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 200 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 203 of file walreceiver.h.

◆ walrcv_receive_fn

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

Definition at line 211 of file walreceiver.h.

◆ walrcv_send_fn

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

Definition at line 213 of file walreceiver.h.

◆ walrcv_startstreaming_fn

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

Definition at line 207 of file walreceiver.h.

◆ WalRcvExecResult

◆ WalReceiverConn

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

171 {
172  WALRCV_ERROR, /* There was error when executing the query. */
173  WALRCV_OK_COMMAND, /* Query executed utility or replication
174  * command. */
175  WALRCV_OK_TUPLES, /* Query returned tuples. */
176  WALRCV_OK_COPY_IN, /* Query started COPY FROM. */
177  WALRCV_OK_COPY_OUT, /* Query started COPY TO. */
178  WALRCV_OK_COPY_BOTH /* Query started COPY BOTH replication
179  * protocol. */
WalRcvExecStatus
Definition: walreceiver.h:170

◆ WalRcvState

Enumerator
WALRCV_STOPPED 
WALRCV_STARTING 
WALRCV_STREAMING 
WALRCV_WAITING 
WALRCV_RESTARTING 
WALRCV_STOPPING 

Definition at line 43 of file walreceiver.h.

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

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:129
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:6159
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
Definition: xlog.c:11125
XLogRecPtr receivedUpto
Definition: walreceiver.h:82
#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:129
int64 TimestampTz
Definition: timestamp.h:39
TimestampTz lastMsgReceiptTime
Definition: walreceiver.h:97
TimestampTz lastMsgSendTime
Definition: walreceiver.h:96
#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:129
TimeLineID receivedTLI
Definition: walreceiver.h:83
#define SpinLockAcquire(lock)
Definition: spin.h:62
XLogRecPtr latestChunkStart
Definition: walreceiver.h:91
XLogRecPtr receivedUpto
Definition: walreceiver.h:82
#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:129
int wal_segment_size
Definition: xlog.c:113
WalRcvState walRcvState
Definition: walreceiver.h:63
TimeLineID receivedTLI
Definition: walreceiver.h:83
pg_time_t startTime
Definition: walreceiver.h:64
#define NAMEDATALEN
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define MAXCONNINFO
Definition: walreceiver.h:35
XLogRecPtr latestChunkStart
Definition: walreceiver.h:91
Definition: latch.h:110
XLogRecPtr receivedUpto
Definition: walreceiver.h:82
TimeLineID receiveStartTLI
Definition: walreceiver.h:73
Latch * latch
Definition: walreceiver.h:127
#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:670
WalRcvData * WalRcv
void SendPostmasterSignal(PMSignalReason reason)
Definition: pmsignal.c:113
XLogRecPtr receiveStart
Definition: walreceiver.h:72
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1534
char slotname[NAMEDATALEN]
Definition: walreceiver.h:115
char conninfo[MAXCONNINFO]
Definition: walreceiver.h:109

◆ 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:129
WalRcvState walRcvState
Definition: walreceiver.h:63
#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:62
#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 269 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().

270 {
271  if (!walres)
272  return;
273 
274  if (walres->err)
275  pfree(walres->err);
276 
277  if (walres->tuplestore)
278  tuplestore_end(walres->tuplestore);
279 
280  if (walres->tupledesc)
281  FreeTupleDesc(walres->tupledesc);
282 
283  pfree(walres);
284 }
void pfree(void *pointer)
Definition: mcxt.c:949
TupleDesc tupledesc
Definition: walreceiver.h:191
Tuplestorestate * tuplestore
Definition: walreceiver.h:190
void tuplestore_end(Tuplestorestate *state)
Definition: tuplestore.c:453
void FreeTupleDesc(TupleDesc tupdesc)
Definition: tupdesc.c:251

◆ WalRcvForceReply()

void WalRcvForceReply ( void  )

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

1347 {
1348  Latch *latch;
1349 
1350  WalRcv->force_reply = true;
1351  /* fetching the latch pointer might not be atomic, so use spinlock */
1353  latch = WalRcv->latch;
1355  if (latch)
1356  SetLatch(latch);
1357 }
slock_t mutex
Definition: walreceiver.h:129
sig_atomic_t force_reply
Definition: walreceiver.h:136
#define SpinLockAcquire(lock)
Definition: spin.h:62
Definition: latch.h:110
Latch * latch
Definition: walreceiver.h:127
#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:129
WalRcvState walRcvState
Definition: walreceiver.h:63
pg_time_t startTime
Definition: walreceiver.h:64
WalRcvState
Definition: walreceiver.h:43
#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:129
WalRcvState walRcvState
Definition: walreceiver.h:63
#define SpinLockInit(lock)
Definition: spin.h:60
#define MemSet(start, val, len)
Definition: c.h:853
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:372
Latch * latch
Definition: walreceiver.h:127
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:404

◆ 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:129
WalRcvState walRcvState
Definition: walreceiver.h:63
pg_time_t startTime
Definition: walreceiver.h:64
WalRcvState
Definition: walreceiver.h:43
#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 188 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, 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(), 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_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().

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

Variable Documentation

◆ hot_standby_feedback

bool hot_standby_feedback

Definition at line 76 of file walreceiver.c.

Referenced by XLogWalRcvSendHSFeedback().

◆ wal_receiver_status_interval

int wal_receiver_status_interval

Definition at line 74 of file walreceiver.c.

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

◆ wal_receiver_timeout

int wal_receiver_timeout

Definition at line 75 of file walreceiver.c.

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

◆ WalRcv

◆ WalReceiverFunctions

PGDLLIMPORT WalReceiverFunctionsType* WalReceiverFunctions

Definition at line 80 of file walreceiver.c.

Referenced by _PG_init().