PostgreSQL Source Code  git master
logical.h File Reference
Include dependency graph for logical.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  LogicalDecodingContext
 

Typedefs

typedef void(* LogicalOutputPluginWriterWrite) (struct LogicalDecodingContext *lr, XLogRecPtr Ptr, TransactionId xid, bool last_write)
 
typedef LogicalOutputPluginWriterWrite LogicalOutputPluginWriterPrepareWrite
 
typedef void(* LogicalOutputPluginWriterUpdateProgress) (struct LogicalDecodingContext *lr, XLogRecPtr Ptr, TransactionId xid)
 
typedef struct LogicalDecodingContext LogicalDecodingContext
 

Functions

void CheckLogicalDecodingRequirements (void)
 
LogicalDecodingContextCreateInitDecodingContext (const char *plugin, List *output_plugin_options, bool need_full_snapshot, XLogRecPtr restart_lsn, XLogReaderRoutine *xl_routine, LogicalOutputPluginWriterPrepareWrite prepare_write, LogicalOutputPluginWriterWrite do_write, LogicalOutputPluginWriterUpdateProgress update_progress)
 
LogicalDecodingContextCreateDecodingContext (XLogRecPtr start_lsn, List *output_plugin_options, bool fast_forward, XLogReaderRoutine *xl_routine, LogicalOutputPluginWriterPrepareWrite prepare_write, LogicalOutputPluginWriterWrite do_write, LogicalOutputPluginWriterUpdateProgress update_progress)
 
void DecodingContextFindStartpoint (LogicalDecodingContext *ctx)
 
bool DecodingContextReady (LogicalDecodingContext *ctx)
 
void FreeDecodingContext (LogicalDecodingContext *ctx)
 
void LogicalIncreaseXminForSlot (XLogRecPtr lsn, TransactionId xmin)
 
void LogicalIncreaseRestartDecodingForSlot (XLogRecPtr current_lsn, XLogRecPtr restart_lsn)
 
void LogicalConfirmReceivedLocation (XLogRecPtr lsn)
 
bool filter_prepare_cb_wrapper (LogicalDecodingContext *ctx, TransactionId xid, const char *gid)
 
bool filter_by_origin_cb_wrapper (LogicalDecodingContext *ctx, RepOriginId origin_id)
 
void ResetLogicalStreamingState (void)
 
void UpdateDecodingStats (LogicalDecodingContext *ctx)
 

Typedef Documentation

◆ LogicalDecodingContext

◆ LogicalOutputPluginWriterPrepareWrite

◆ LogicalOutputPluginWriterUpdateProgress

typedef void(* LogicalOutputPluginWriterUpdateProgress) (struct LogicalDecodingContext *lr, XLogRecPtr Ptr, TransactionId xid)

Definition at line 27 of file logical.h.

◆ LogicalOutputPluginWriterWrite

typedef void(* LogicalOutputPluginWriterWrite) (struct LogicalDecodingContext *lr, XLogRecPtr Ptr, TransactionId xid, bool last_write)

Definition at line 19 of file logical.h.

Function Documentation

◆ CheckLogicalDecodingRequirements()

void CheckLogicalDecodingRequirements ( void  )

Definition at line 103 of file logical.c.

References CheckSlotRequirements(), ereport, errcode(), errmsg(), ERROR, InvalidOid, MyDatabaseId, RecoveryInProgress(), wal_level, and WAL_LEVEL_LOGICAL.

Referenced by copy_replication_slot(), CreateReplicationSlot(), pg_create_logical_replication_slot(), pg_logical_slot_get_changes_guts(), and StartLogicalReplication().

104 {
106 
107  /*
108  * NB: Adding a new requirement likely means that RestoreSlotFromDisk()
109  * needs the same check.
110  */
111 
113  ereport(ERROR,
114  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
115  errmsg("logical decoding requires wal_level >= logical")));
116 
117  if (MyDatabaseId == InvalidOid)
118  ereport(ERROR,
119  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
120  errmsg("logical decoding requires a database connection")));
121 
122  /* ----
123  * TODO: We got to change that someday soon...
124  *
125  * There's basically three things missing to allow this:
126  * 1) We need to be able to correctly and quickly identify the timeline a
127  * LSN belongs to
128  * 2) We need to force hot_standby_feedback to be enabled at all times so
129  * the primary cannot remove rows we need.
130  * 3) support dropping replication slots referring to a database, in
131  * dbase_redo. There can't be any active ones due to HS recovery
132  * conflicts, so that should be relatively easy.
133  * ----
134  */
135  if (RecoveryInProgress())
136  ereport(ERROR,
137  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
138  errmsg("logical decoding cannot be used while in recovery")));
139 }
void CheckSlotRequirements(void)
Definition: slot.c:1044
int wal_level
Definition: xlog.c:108
int errcode(int sqlerrcode)
Definition: elog.c:698
bool RecoveryInProgress(void)
Definition: xlog.c:8220
#define ERROR
Definition: elog.h:46
Oid MyDatabaseId
Definition: globals.c:88
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ CreateDecodingContext()

LogicalDecodingContext* CreateDecodingContext ( XLogRecPtr  start_lsn,
List output_plugin_options,
bool  fast_forward,
XLogReaderRoutine xl_routine,
LogicalOutputPluginWriterPrepareWrite  prepare_write,
LogicalOutputPluginWriterWrite  do_write,
LogicalOutputPluginWriterUpdateProgress  update_progress 
)

Definition at line 478 of file logical.c.

References LogicalDecodingContext::callbacks, ReplicationSlotPersistentData::confirmed_flush, LogicalDecodingContext::context, LogicalErrorCallbackState::ctx, ReplicationSlot::data, ReplicationSlotPersistentData::database, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, InvalidTransactionId, InvalidXLogRecPtr, LOG, LSN_FORMAT_ARGS, MemoryContextSwitchTo(), MyDatabaseId, MyReplicationSlot, ReplicationSlotPersistentData::name, NameStr, LogicalDecodingContext::options, ReorderBuffer::output_rewrites, OutputPluginOptions::receive_rewrites, LogicalDecodingContext::reorder, ReplicationSlotMarkDirty(), ReplicationSlotSave(), ReplicationSlotPersistentData::restart_lsn, SlotIsPhysical, SnapBuildSetTwoPhaseAt(), LogicalDecodingContext::snapshot_builder, OutputPluginCallbacks::startup_cb, startup_cb_wrapper(), StartupDecodingContext(), ReplicationSlotPersistentData::two_phase, ReplicationSlotPersistentData::two_phase_at, LogicalDecodingContext::twophase, and LogicalDecodingContext::twophase_opt_given.

Referenced by pg_logical_replication_slot_advance(), pg_logical_slot_get_changes_guts(), and StartLogicalReplication().

485 {
487  ReplicationSlot *slot;
488  MemoryContext old_context;
489 
490  /* shorter lines... */
491  slot = MyReplicationSlot;
492 
493  /* first some sanity checks that are unlikely to be violated */
494  if (slot == NULL)
495  elog(ERROR, "cannot perform logical decoding without an acquired slot");
496 
497  /* make sure the passed slot is suitable, these are user facing errors */
498  if (SlotIsPhysical(slot))
499  ereport(ERROR,
500  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
501  errmsg("cannot use physical replication slot for logical decoding")));
502 
503  if (slot->data.database != MyDatabaseId)
504  ereport(ERROR,
505  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
506  errmsg("replication slot \"%s\" was not created in this database",
507  NameStr(slot->data.name))));
508 
509  if (start_lsn == InvalidXLogRecPtr)
510  {
511  /* continue from last position */
512  start_lsn = slot->data.confirmed_flush;
513  }
514  else if (start_lsn < slot->data.confirmed_flush)
515  {
516  /*
517  * It might seem like we should error out in this case, but it's
518  * pretty common for a client to acknowledge a LSN it doesn't have to
519  * do anything for, and thus didn't store persistently, because the
520  * xlog records didn't result in anything relevant for logical
521  * decoding. Clients have to be able to do that to support synchronous
522  * replication.
523  *
524  * Starting at a different LSN than requested might not catch certain
525  * kinds of client errors; so the client may wish to check that
526  * confirmed_flush_lsn matches its expectations.
527  */
528  elog(LOG, "%X/%X has been already streamed, forwarding to %X/%X",
529  LSN_FORMAT_ARGS(start_lsn),
531 
532  start_lsn = slot->data.confirmed_flush;
533  }
534 
535  ctx = StartupDecodingContext(output_plugin_options,
536  start_lsn, InvalidTransactionId, false,
537  fast_forward, xl_routine, prepare_write,
538  do_write, update_progress);
539 
540  /* call output plugin initialization callback */
541  old_context = MemoryContextSwitchTo(ctx->context);
542  if (ctx->callbacks.startup_cb != NULL)
543  startup_cb_wrapper(ctx, &ctx->options, false);
544  MemoryContextSwitchTo(old_context);
545 
546  /*
547  * We allow decoding of prepared transactions when the two_phase is
548  * enabled at the time of slot creation, or when the two_phase option is
549  * given at the streaming start, provided the plugin supports all the
550  * callbacks for two-phase.
551  */
552  ctx->twophase &= (slot->data.two_phase || ctx->twophase_opt_given);
553 
554  /* Mark slot to allow two_phase decoding if not already marked */
555  if (ctx->twophase && !slot->data.two_phase)
556  {
557  slot->data.two_phase = true;
558  slot->data.two_phase_at = start_lsn;
561  SnapBuildSetTwoPhaseAt(ctx->snapshot_builder, start_lsn);
562  }
563 
565 
566  ereport(LOG,
567  (errmsg("starting logical decoding for slot \"%s\"",
568  NameStr(slot->data.name)),
569  errdetail("Streaming transactions committing after %X/%X, reading WAL from %X/%X.",
571  LSN_FORMAT_ARGS(slot->data.restart_lsn))));
572 
573  return ctx;
574 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
struct ReorderBuffer * reorder
Definition: logical.h:42
OutputPluginOptions options
Definition: logical.h:53
OutputPluginCallbacks callbacks
Definition: logical.h:52
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:698
MemoryContext context
Definition: logical.h:35
void ReplicationSlotSave(void)
Definition: slot.c:710
ReplicationSlotPersistentData data
Definition: slot.h:147
#define LOG
Definition: elog.h:26
#define SlotIsPhysical(slot)
Definition: slot.h:168
XLogRecPtr confirmed_flush
Definition: slot.h:84
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
#define ERROR
Definition: elog.h:46
static void startup_cb_wrapper(LogicalDecodingContext *ctx, OutputPluginOptions *opt, bool is_init)
Definition: logical.c:728
int errdetail(const char *fmt,...)
Definition: elog.c:1042
#define InvalidTransactionId
Definition: transam.h:31
void SnapBuildSetTwoPhaseAt(SnapBuild *builder, XLogRecPtr ptr)
Definition: snapbuild.c:385
Oid MyDatabaseId
Definition: globals.c:88
#define ereport(elevel,...)
Definition: elog.h:157
struct SnapBuild * snapshot_builder
Definition: logical.h:43
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
XLogRecPtr restart_lsn
Definition: slot.h:73
LogicalDecodeStartupCB startup_cb
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
#define NameStr(name)
Definition: c.h:681
void ReplicationSlotMarkDirty(void)
Definition: slot.c:728
static LogicalDecodingContext * StartupDecodingContext(List *output_plugin_options, XLogRecPtr start_lsn, TransactionId xmin_horizon, bool need_full_snapshot, bool fast_forward, XLogReaderRoutine *xl_routine, LogicalOutputPluginWriterPrepareWrite prepare_write, LogicalOutputPluginWriterWrite do_write, LogicalOutputPluginWriterUpdateProgress update_progress)
Definition: logical.c:146
XLogRecPtr two_phase_at
Definition: slot.h:90

◆ CreateInitDecodingContext()

LogicalDecodingContext* CreateInitDecodingContext ( const char *  plugin,
List output_plugin_options,
bool  need_full_snapshot,
XLogRecPtr  restart_lsn,
XLogReaderRoutine xl_routine,
LogicalOutputPluginWriterPrepareWrite  prepare_write,
LogicalOutputPluginWriterWrite  do_write,
LogicalOutputPluginWriterUpdateProgress  update_progress 
)

Definition at line 318 of file logical.c.

References LogicalDecodingContext::callbacks, ReplicationSlotPersistentData::catalog_xmin, LogicalDecodingContext::context, LogicalErrorCallbackState::ctx, ReplicationSlot::data, ReplicationSlotPersistentData::database, ReplicationSlot::effective_catalog_xmin, ReplicationSlot::effective_xmin, elog, ereport, errcode(), errmsg(), ERROR, GetOldestSafeDecodingTransactionId(), GetTopTransactionIdIfAny(), InvalidTransactionId, IsTransactionState(), LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MemoryContextSwitchTo(), ReplicationSlot::mutex, MyDatabaseId, MyReplicationSlot, ReplicationSlotPersistentData::name, NameStr, namestrcpy(), NIL, LogicalDecodingContext::options, ReorderBuffer::output_rewrites, ReplicationSlotPersistentData::plugin, OutputPluginOptions::receive_rewrites, LogicalDecodingContext::reorder, ReplicationSlotMarkDirty(), ReplicationSlotReserveWal(), ReplicationSlotSave(), ReplicationSlotsComputeRequiredXmin(), ReplicationSlotPersistentData::restart_lsn, SlotIsPhysical, SpinLockAcquire, SpinLockRelease, OutputPluginCallbacks::startup_cb, startup_cb_wrapper(), StartupDecodingContext(), ReplicationSlotPersistentData::two_phase, LogicalDecodingContext::twophase, and XLogRecPtrIsInvalid.

Referenced by create_logical_replication_slot(), and CreateReplicationSlot().

326 {
327  TransactionId xmin_horizon = InvalidTransactionId;
328  ReplicationSlot *slot;
329  NameData plugin_name;
331  MemoryContext old_context;
332 
333  /* shorter lines... */
334  slot = MyReplicationSlot;
335 
336  /* first some sanity checks that are unlikely to be violated */
337  if (slot == NULL)
338  elog(ERROR, "cannot perform logical decoding without an acquired slot");
339 
340  if (plugin == NULL)
341  elog(ERROR, "cannot initialize logical decoding without a specified plugin");
342 
343  /* Make sure the passed slot is suitable. These are user facing errors. */
344  if (SlotIsPhysical(slot))
345  ereport(ERROR,
346  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
347  errmsg("cannot use physical replication slot for logical decoding")));
348 
349  if (slot->data.database != MyDatabaseId)
350  ereport(ERROR,
351  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
352  errmsg("replication slot \"%s\" was not created in this database",
353  NameStr(slot->data.name))));
354 
355  if (IsTransactionState() &&
357  ereport(ERROR,
358  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
359  errmsg("cannot create logical replication slot in transaction that has performed writes")));
360 
361  /*
362  * Register output plugin name with slot. We need the mutex to avoid
363  * concurrent reading of a partially copied string. But we don't want any
364  * complicated code while holding a spinlock, so do namestrcpy() outside.
365  */
366  namestrcpy(&plugin_name, plugin);
367  SpinLockAcquire(&slot->mutex);
368  slot->data.plugin = plugin_name;
369  SpinLockRelease(&slot->mutex);
370 
371  if (XLogRecPtrIsInvalid(restart_lsn))
373  else
374  {
375  SpinLockAcquire(&slot->mutex);
376  slot->data.restart_lsn = restart_lsn;
377  SpinLockRelease(&slot->mutex);
378  }
379 
380  /* ----
381  * This is a bit tricky: We need to determine a safe xmin horizon to start
382  * decoding from, to avoid starting from a running xacts record referring
383  * to xids whose rows have been vacuumed or pruned
384  * already. GetOldestSafeDecodingTransactionId() returns such a value, but
385  * without further interlock its return value might immediately be out of
386  * date.
387  *
388  * So we have to acquire the ProcArrayLock to prevent computation of new
389  * xmin horizons by other backends, get the safe decoding xid, and inform
390  * the slot machinery about the new limit. Once that's done the
391  * ProcArrayLock can be released as the slot machinery now is
392  * protecting against vacuum.
393  *
394  * Note that, temporarily, the data, not just the catalog, xmin has to be
395  * reserved if a data snapshot is to be exported. Otherwise the initial
396  * data snapshot created here is not guaranteed to be valid. After that
397  * the data xmin doesn't need to be managed anymore and the global xmin
398  * should be recomputed. As we are fine with losing the pegged data xmin
399  * after crash - no chance a snapshot would get exported anymore - we can
400  * get away with just setting the slot's
401  * effective_xmin. ReplicationSlotRelease will reset it again.
402  *
403  * ----
404  */
405  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
406 
407  xmin_horizon = GetOldestSafeDecodingTransactionId(!need_full_snapshot);
408 
409  SpinLockAcquire(&slot->mutex);
410  slot->effective_catalog_xmin = xmin_horizon;
411  slot->data.catalog_xmin = xmin_horizon;
412  if (need_full_snapshot)
413  slot->effective_xmin = xmin_horizon;
414  SpinLockRelease(&slot->mutex);
415 
417 
418  LWLockRelease(ProcArrayLock);
419 
422 
423  ctx = StartupDecodingContext(NIL, restart_lsn, xmin_horizon,
424  need_full_snapshot, false,
425  xl_routine, prepare_write, do_write,
426  update_progress);
427 
428  /* call output plugin initialization callback */
429  old_context = MemoryContextSwitchTo(ctx->context);
430  if (ctx->callbacks.startup_cb != NULL)
431  startup_cb_wrapper(ctx, &ctx->options, true);
432  MemoryContextSwitchTo(old_context);
433 
434  /*
435  * We allow decoding of prepared transactions when the two_phase is
436  * enabled at the time of slot creation, or when the two_phase option is
437  * given at the streaming start, provided the plugin supports all the
438  * callbacks for two-phase.
439  */
440  ctx->twophase &= slot->data.two_phase;
441 
443 
444  return ctx;
445 }
#define NIL
Definition: pg_list.h:65
static const char * plugin
TransactionId GetOldestSafeDecodingTransactionId(bool catalogOnly)
Definition: procarray.c:2947
struct ReorderBuffer * reorder
Definition: logical.h:42
uint32 TransactionId
Definition: c.h:587
void namestrcpy(Name name, const char *str)
Definition: name.c:233
OutputPluginOptions options
Definition: logical.h:53
OutputPluginCallbacks callbacks
Definition: logical.h:52
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:698
MemoryContext context
Definition: logical.h:35
void ReplicationSlotSave(void)
Definition: slot.c:710
ReplicationSlotPersistentData data
Definition: slot.h:147
#define SlotIsPhysical(slot)
Definition: slot.h:168
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#define SpinLockAcquire(lock)
Definition: spin.h:62
void ReplicationSlotReserveWal(void)
Definition: slot.c:1081
#define ERROR
Definition: elog.h:46
static void startup_cb_wrapper(LogicalDecodingContext *ctx, OutputPluginOptions *opt, bool is_init)
Definition: logical.c:728
TransactionId effective_xmin
Definition: slot.h:143
Definition: c.h:675
TransactionId catalog_xmin
Definition: slot.h:70
#define InvalidTransactionId
Definition: transam.h:31
TransactionId GetTopTransactionIdIfAny(void)
Definition: xact.c:425
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
#define SpinLockRelease(lock)
Definition: spin.h:64
TransactionId effective_catalog_xmin
Definition: slot.h:144
Oid MyDatabaseId
Definition: globals.c:88
#define ereport(elevel,...)
Definition: elog.h:157
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
XLogRecPtr restart_lsn
Definition: slot.h:73
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
bool IsTransactionState(void)
Definition: xact.c:371
LogicalDecodeStartupCB startup_cb
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
#define NameStr(name)
Definition: c.h:681
slock_t mutex
Definition: slot.h:120
void ReplicationSlotsComputeRequiredXmin(bool already_locked)
Definition: slot.c:767
void ReplicationSlotMarkDirty(void)
Definition: slot.c:728
static LogicalDecodingContext * StartupDecodingContext(List *output_plugin_options, XLogRecPtr start_lsn, TransactionId xmin_horizon, bool need_full_snapshot, bool fast_forward, XLogReaderRoutine *xl_routine, LogicalOutputPluginWriterPrepareWrite prepare_write, LogicalOutputPluginWriterWrite do_write, LogicalOutputPluginWriterUpdateProgress update_progress)
Definition: logical.c:146

◆ DecodingContextFindStartpoint()

void DecodingContextFindStartpoint ( LogicalDecodingContext ctx)

Definition at line 589 of file logical.c.

References CHECK_FOR_INTERRUPTS, ReplicationSlotPersistentData::confirmed_flush, ReplicationSlot::data, DEBUG1, DecodingContextReady(), elog, XLogReaderState::EndRecPtr, ERROR, LogicalDecodingProcessRecord(), LSN_FORMAT_ARGS, ReplicationSlot::mutex, LogicalDecodingContext::reader, ReplicationSlotPersistentData::restart_lsn, LogicalDecodingContext::slot, SpinLockAcquire, SpinLockRelease, ReplicationSlotPersistentData::two_phase, ReplicationSlotPersistentData::two_phase_at, XLogBeginRead(), and XLogReadRecord().

Referenced by create_logical_replication_slot(), and CreateReplicationSlot().

590 {
591  ReplicationSlot *slot = ctx->slot;
592 
593  /* Initialize from where to start reading WAL. */
594  XLogBeginRead(ctx->reader, slot->data.restart_lsn);
595 
596  elog(DEBUG1, "searching for logical decoding starting point, starting at %X/%X",
598 
599  /* Wait for a consistent starting point */
600  for (;;)
601  {
602  XLogRecord *record;
603  char *err = NULL;
604 
605  /* the read_page callback waits for new WAL */
606  record = XLogReadRecord(ctx->reader, &err);
607  if (err)
608  elog(ERROR, "%s", err);
609  if (!record)
610  elog(ERROR, "no record found"); /* shouldn't happen */
611 
613 
614  /* only continue till we found a consistent spot */
615  if (DecodingContextReady(ctx))
616  break;
617 
619  }
620 
621  SpinLockAcquire(&slot->mutex);
622  slot->data.confirmed_flush = ctx->reader->EndRecPtr;
623  if (slot->data.two_phase)
624  slot->data.two_phase_at = ctx->reader->EndRecPtr;
625  SpinLockRelease(&slot->mutex);
626 }
#define DEBUG1
Definition: elog.h:25
bool DecodingContextReady(LogicalDecodingContext *ctx)
Definition: logical.c:580
ReplicationSlotPersistentData data
Definition: slot.h:147
XLogRecPtr confirmed_flush
Definition: slot.h:84
XLogRecPtr EndRecPtr
Definition: xlogreader.h:176
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
XLogRecord * XLogReadRecord(XLogReaderState *state, char **errormsg)
Definition: xlogreader.c:271
#define ERROR
Definition: elog.h:46
void LogicalDecodingProcessRecord(LogicalDecodingContext *ctx, XLogReaderState *record)
Definition: decode.c:106
void XLogBeginRead(XLogReaderState *state, XLogRecPtr RecPtr)
Definition: xlogreader.c:243
#define SpinLockRelease(lock)
Definition: spin.h:64
XLogRecPtr restart_lsn
Definition: slot.h:73
XLogReaderState * reader
Definition: logical.h:41
ReplicationSlot * slot
Definition: logical.h:38
#define elog(elevel,...)
Definition: elog.h:232
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
slock_t mutex
Definition: slot.h:120
XLogRecPtr two_phase_at
Definition: slot.h:90

◆ DecodingContextReady()

bool DecodingContextReady ( LogicalDecodingContext ctx)

Definition at line 580 of file logical.c.

References SNAPBUILD_CONSISTENT, SnapBuildCurrentState(), and LogicalDecodingContext::snapshot_builder.

Referenced by DecodingContextFindStartpoint().

581 {
583 }
SnapBuildState SnapBuildCurrentState(SnapBuild *builder)
Definition: snapbuild.c:367
struct SnapBuild * snapshot_builder
Definition: logical.h:43

◆ filter_by_origin_cb_wrapper()

bool filter_by_origin_cb_wrapper ( LogicalDecodingContext ctx,
RepOriginId  origin_id 
)

Definition at line 1140 of file logical.c.

References LogicalDecodingContext::accept_writes, ErrorContextCallback::arg, Assert, ErrorContextCallback::callback, LogicalErrorCallbackState::callback_name, LogicalDecodingContext::callbacks, LogicalErrorCallbackState::ctx, error_context_stack, LogicalDecodingContext::fast_forward, OutputPluginCallbacks::filter_by_origin_cb, InvalidXLogRecPtr, output_plugin_error_callback(), ErrorContextCallback::previous, and LogicalErrorCallbackState::report_location.

Referenced by FilterByOrigin().

1141 {
1143  ErrorContextCallback errcallback;
1144  bool ret;
1145 
1146  Assert(!ctx->fast_forward);
1147 
1148  /* Push callback + info on the error context stack */
1149  state.ctx = ctx;
1150  state.callback_name = "filter_by_origin";
1152  errcallback.callback = output_plugin_error_callback;
1153  errcallback.arg = (void *) &state;
1154  errcallback.previous = error_context_stack;
1155  error_context_stack = &errcallback;
1156 
1157  /* set output state */
1158  ctx->accept_writes = false;
1159 
1160  /* do the actual work: call callback */
1161  ret = ctx->callbacks.filter_by_origin_cb(ctx, origin_id);
1162 
1163  /* Pop the error context stack */
1164  error_context_stack = errcallback.previous;
1165 
1166  return ret;
1167 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
OutputPluginCallbacks callbacks
Definition: logical.h:52
void(* callback)(void *arg)
Definition: elog.h:247
struct ErrorContextCallback * previous
Definition: elog.h:246
const char * callback_name
Definition: logical.c:50
ErrorContextCallback * error_context_stack
Definition: elog.c:93
#define Assert(condition)
Definition: c.h:804
Definition: regguts.h:317
XLogRecPtr report_location
Definition: logical.c:51
LogicalDecodingContext * ctx
Definition: logical.c:49
static void output_plugin_error_callback(void *arg)
Definition: logical.c:709
LogicalDecodeFilterByOriginCB filter_by_origin_cb

◆ filter_prepare_cb_wrapper()

bool filter_prepare_cb_wrapper ( LogicalDecodingContext ctx,
TransactionId  xid,
const char *  gid 
)

Definition at line 1109 of file logical.c.

References LogicalDecodingContext::accept_writes, ErrorContextCallback::arg, Assert, ErrorContextCallback::callback, LogicalErrorCallbackState::callback_name, LogicalDecodingContext::callbacks, LogicalErrorCallbackState::ctx, error_context_stack, LogicalDecodingContext::fast_forward, OutputPluginCallbacks::filter_prepare_cb, InvalidXLogRecPtr, output_plugin_error_callback(), ErrorContextCallback::previous, and LogicalErrorCallbackState::report_location.

Referenced by FilterPrepare().

1111 {
1113  ErrorContextCallback errcallback;
1114  bool ret;
1115 
1116  Assert(!ctx->fast_forward);
1117 
1118  /* Push callback + info on the error context stack */
1119  state.ctx = ctx;
1120  state.callback_name = "filter_prepare";
1122  errcallback.callback = output_plugin_error_callback;
1123  errcallback.arg = (void *) &state;
1124  errcallback.previous = error_context_stack;
1125  error_context_stack = &errcallback;
1126 
1127  /* set output state */
1128  ctx->accept_writes = false;
1129 
1130  /* do the actual work: call callback */
1131  ret = ctx->callbacks.filter_prepare_cb(ctx, xid, gid);
1132 
1133  /* Pop the error context stack */
1134  error_context_stack = errcallback.previous;
1135 
1136  return ret;
1137 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
OutputPluginCallbacks callbacks
Definition: logical.h:52
void(* callback)(void *arg)
Definition: elog.h:247
struct ErrorContextCallback * previous
Definition: elog.h:246
const char * callback_name
Definition: logical.c:50
ErrorContextCallback * error_context_stack
Definition: elog.c:93
LogicalDecodeFilterPrepareCB filter_prepare_cb
#define Assert(condition)
Definition: c.h:804
Definition: regguts.h:317
XLogRecPtr report_location
Definition: logical.c:51
LogicalDecodingContext * ctx
Definition: logical.c:49
static void output_plugin_error_callback(void *arg)
Definition: logical.c:709

◆ FreeDecodingContext()

void FreeDecodingContext ( LogicalDecodingContext ctx)

Definition at line 633 of file logical.c.

References LogicalDecodingContext::callbacks, LogicalDecodingContext::context, FreeSnapshotBuilder(), MemoryContextDelete(), LogicalDecodingContext::reader, LogicalDecodingContext::reorder, ReorderBufferFree(), OutputPluginCallbacks::shutdown_cb, shutdown_cb_wrapper(), LogicalDecodingContext::snapshot_builder, and XLogReaderFree().

Referenced by create_logical_replication_slot(), CreateReplicationSlot(), pg_logical_replication_slot_advance(), pg_logical_slot_get_changes_guts(), and StartLogicalReplication().

634 {
635  if (ctx->callbacks.shutdown_cb != NULL)
636  shutdown_cb_wrapper(ctx);
637 
640  XLogReaderFree(ctx->reader);
642 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
struct ReorderBuffer * reorder
Definition: logical.h:42
OutputPluginCallbacks callbacks
Definition: logical.h:52
void ReorderBufferFree(ReorderBuffer *rb)
MemoryContext context
Definition: logical.h:35
static void shutdown_cb_wrapper(LogicalDecodingContext *ctx)
Definition: logical.c:755
void XLogReaderFree(XLogReaderState *state)
Definition: xlogreader.c:142
void FreeSnapshotBuilder(SnapBuild *builder)
Definition: snapbuild.c:323
struct SnapBuild * snapshot_builder
Definition: logical.h:43
LogicalDecodeShutdownCB shutdown_cb
XLogReaderState * reader
Definition: logical.h:41

◆ LogicalConfirmReceivedLocation()

void LogicalConfirmReceivedLocation ( XLogRecPtr  lsn)

Definition at line 1706 of file logical.c.

References Assert, ReplicationSlot::candidate_catalog_xmin, ReplicationSlot::candidate_restart_lsn, ReplicationSlot::candidate_restart_valid, ReplicationSlot::candidate_xmin_lsn, ReplicationSlotPersistentData::catalog_xmin, ReplicationSlotPersistentData::confirmed_flush, ReplicationSlot::data, DEBUG1, ReplicationSlot::effective_catalog_xmin, elog, InvalidTransactionId, InvalidXLogRecPtr, ReplicationSlot::mutex, MyReplicationSlot, ReplicationSlotMarkDirty(), ReplicationSlotSave(), ReplicationSlotsComputeRequiredLSN(), ReplicationSlotsComputeRequiredXmin(), ReplicationSlotPersistentData::restart_lsn, SpinLockAcquire, SpinLockRelease, and TransactionIdIsValid.

Referenced by LogicalIncreaseRestartDecodingForSlot(), LogicalIncreaseXminForSlot(), pg_logical_replication_slot_advance(), pg_logical_slot_get_changes_guts(), and ProcessStandbyReplyMessage().

1707 {
1708  Assert(lsn != InvalidXLogRecPtr);
1709 
1710  /* Do an unlocked check for candidate_lsn first. */
1713  {
1714  bool updated_xmin = false;
1715  bool updated_restart = false;
1716 
1718 
1720 
1721  /* if we're past the location required for bumping xmin, do so */
1724  {
1725  /*
1726  * We have to write the changed xmin to disk *before* we change
1727  * the in-memory value, otherwise after a crash we wouldn't know
1728  * that some catalog tuples might have been removed already.
1729  *
1730  * Ensure that by first writing to ->xmin and only update
1731  * ->effective_xmin once the new state is synced to disk. After a
1732  * crash ->effective_xmin is set to ->xmin.
1733  */
1736  {
1740  updated_xmin = true;
1741  }
1742  }
1743 
1746  {
1748 
1752  updated_restart = true;
1753  }
1754 
1756 
1757  /* first write new xmin to disk, so we know what's up after a crash */
1758  if (updated_xmin || updated_restart)
1759  {
1762  elog(DEBUG1, "updated xmin: %u restart: %u", updated_xmin, updated_restart);
1763  }
1764 
1765  /*
1766  * Now the new xmin is safely on disk, we can let the global value
1767  * advance. We do not take ProcArrayLock or similar since we only
1768  * advance xmin here and there's not much harm done by a concurrent
1769  * computation missing that.
1770  */
1771  if (updated_xmin)
1772  {
1776 
1779  }
1780  }
1781  else
1782  {
1786  }
1787 }
TransactionId candidate_catalog_xmin
Definition: slot.h:162
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define DEBUG1
Definition: elog.h:25
void ReplicationSlotSave(void)
Definition: slot.c:710
ReplicationSlotPersistentData data
Definition: slot.h:147
XLogRecPtr confirmed_flush
Definition: slot.h:84
#define SpinLockAcquire(lock)
Definition: spin.h:62
void ReplicationSlotsComputeRequiredLSN(void)
Definition: slot.c:817
XLogRecPtr candidate_restart_valid
Definition: slot.h:164
TransactionId catalog_xmin
Definition: slot.h:70
#define InvalidTransactionId
Definition: transam.h:31
#define SpinLockRelease(lock)
Definition: spin.h:64
TransactionId effective_catalog_xmin
Definition: slot.h:144
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
#define Assert(condition)
Definition: c.h:804
XLogRecPtr restart_lsn
Definition: slot.h:73
XLogRecPtr candidate_xmin_lsn
Definition: slot.h:163
#define elog(elevel,...)
Definition: elog.h:232
slock_t mutex
Definition: slot.h:120
#define TransactionIdIsValid(xid)
Definition: transam.h:41
void ReplicationSlotsComputeRequiredXmin(bool already_locked)
Definition: slot.c:767
XLogRecPtr candidate_restart_lsn
Definition: slot.h:165
void ReplicationSlotMarkDirty(void)
Definition: slot.c:728

◆ LogicalIncreaseRestartDecodingForSlot()

void LogicalIncreaseRestartDecodingForSlot ( XLogRecPtr  current_lsn,
XLogRecPtr  restart_lsn 
)

Definition at line 1632 of file logical.c.

References Assert, ReplicationSlot::candidate_restart_lsn, ReplicationSlot::candidate_restart_valid, ReplicationSlotPersistentData::confirmed_flush, ReplicationSlot::data, DEBUG1, elog, InvalidXLogRecPtr, LogicalConfirmReceivedLocation(), LSN_FORMAT_ARGS, ReplicationSlot::mutex, MyReplicationSlot, SpinLockAcquire, and SpinLockRelease.

Referenced by SnapBuildProcessRunningXacts().

1633 {
1634  bool updated_lsn = false;
1635  ReplicationSlot *slot;
1636 
1637  slot = MyReplicationSlot;
1638 
1639  Assert(slot != NULL);
1640  Assert(restart_lsn != InvalidXLogRecPtr);
1641  Assert(current_lsn != InvalidXLogRecPtr);
1642 
1643  SpinLockAcquire(&slot->mutex);
1644 
1645  /* don't overwrite if have a newer restart lsn */
1646  if (restart_lsn <= slot->data.restart_lsn)
1647  {
1648  }
1649 
1650  /*
1651  * We might have already flushed far enough to directly accept this lsn,
1652  * in this case there is no need to check for existing candidate LSNs
1653  */
1654  else if (current_lsn <= slot->data.confirmed_flush)
1655  {
1656  slot->candidate_restart_valid = current_lsn;
1657  slot->candidate_restart_lsn = restart_lsn;
1658 
1659  /* our candidate can directly be used */
1660  updated_lsn = true;
1661  }
1662 
1663  /*
1664  * Only increase if the previous values have been applied, otherwise we
1665  * might never end up updating if the receiver acks too slowly. A missed
1666  * value here will just cause some extra effort after reconnecting.
1667  */
1669  {
1670  slot->candidate_restart_valid = current_lsn;
1671  slot->candidate_restart_lsn = restart_lsn;
1672  SpinLockRelease(&slot->mutex);
1673 
1674  elog(DEBUG1, "got new restart lsn %X/%X at %X/%X",
1675  LSN_FORMAT_ARGS(restart_lsn),
1676  LSN_FORMAT_ARGS(current_lsn));
1677  }
1678  else
1679  {
1680  XLogRecPtr candidate_restart_lsn;
1681  XLogRecPtr candidate_restart_valid;
1682  XLogRecPtr confirmed_flush;
1683 
1684  candidate_restart_lsn = slot->candidate_restart_lsn;
1685  candidate_restart_valid = slot->candidate_restart_valid;
1686  confirmed_flush = slot->data.confirmed_flush;
1687  SpinLockRelease(&slot->mutex);
1688 
1689  elog(DEBUG1, "failed to increase restart lsn: proposed %X/%X, after %X/%X, current candidate %X/%X, current after %X/%X, flushed up to %X/%X",
1690  LSN_FORMAT_ARGS(restart_lsn),
1691  LSN_FORMAT_ARGS(current_lsn),
1692  LSN_FORMAT_ARGS(candidate_restart_lsn),
1693  LSN_FORMAT_ARGS(candidate_restart_valid),
1694  LSN_FORMAT_ARGS(confirmed_flush));
1695  }
1696 
1697  /* candidates are already valid with the current flush position, apply */
1698  if (updated_lsn)
1700 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define DEBUG1
Definition: elog.h:25
ReplicationSlotPersistentData data
Definition: slot.h:147
XLogRecPtr confirmed_flush
Definition: slot.h:84
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
XLogRecPtr candidate_restart_valid
Definition: slot.h:164
#define SpinLockRelease(lock)
Definition: spin.h:64
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:804
void LogicalConfirmReceivedLocation(XLogRecPtr lsn)
Definition: logical.c:1706
#define elog(elevel,...)
Definition: elog.h:232
slock_t mutex
Definition: slot.h:120
XLogRecPtr candidate_restart_lsn
Definition: slot.h:165

◆ LogicalIncreaseXminForSlot()

void LogicalIncreaseXminForSlot ( XLogRecPtr  lsn,
TransactionId  xmin 
)

Definition at line 1564 of file logical.c.

References Assert, ReplicationSlot::candidate_catalog_xmin, ReplicationSlot::candidate_xmin_lsn, ReplicationSlotPersistentData::catalog_xmin, ReplicationSlotPersistentData::confirmed_flush, ReplicationSlot::data, DEBUG1, elog, InvalidXLogRecPtr, LogicalConfirmReceivedLocation(), LSN_FORMAT_ARGS, ReplicationSlot::mutex, MyReplicationSlot, SpinLockAcquire, SpinLockRelease, and TransactionIdPrecedesOrEquals().

Referenced by SnapBuildProcessRunningXacts().

1565 {
1566  bool updated_xmin = false;
1567  ReplicationSlot *slot;
1568  bool got_new_xmin = false;
1569 
1570  slot = MyReplicationSlot;
1571 
1572  Assert(slot != NULL);
1573 
1574  SpinLockAcquire(&slot->mutex);
1575 
1576  /*
1577  * don't overwrite if we already have a newer xmin. This can happen if we
1578  * restart decoding in a slot.
1579  */
1581  {
1582  }
1583 
1584  /*
1585  * If the client has already confirmed up to this lsn, we directly can
1586  * mark this as accepted. This can happen if we restart decoding in a
1587  * slot.
1588  */
1589  else if (current_lsn <= slot->data.confirmed_flush)
1590  {
1591  slot->candidate_catalog_xmin = xmin;
1592  slot->candidate_xmin_lsn = current_lsn;
1593 
1594  /* our candidate can directly be used */
1595  updated_xmin = true;
1596  }
1597 
1598  /*
1599  * Only increase if the previous values have been applied, otherwise we
1600  * might never end up updating if the receiver acks too slowly.
1601  */
1602  else if (slot->candidate_xmin_lsn == InvalidXLogRecPtr)
1603  {
1604  slot->candidate_catalog_xmin = xmin;
1605  slot->candidate_xmin_lsn = current_lsn;
1606 
1607  /*
1608  * Log new xmin at an appropriate log level after releasing the
1609  * spinlock.
1610  */
1611  got_new_xmin = true;
1612  }
1613  SpinLockRelease(&slot->mutex);
1614 
1615  if (got_new_xmin)
1616  elog(DEBUG1, "got new catalog xmin %u at %X/%X", xmin,
1617  LSN_FORMAT_ARGS(current_lsn));
1618 
1619  /* candidate already valid with the current flush position, apply */
1620  if (updated_xmin)
1622 }
TransactionId candidate_catalog_xmin
Definition: slot.h:162
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define DEBUG1
Definition: elog.h:25
ReplicationSlotPersistentData data
Definition: slot.h:147
XLogRecPtr confirmed_flush
Definition: slot.h:84
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:319
TransactionId catalog_xmin
Definition: slot.h:70
#define SpinLockRelease(lock)
Definition: spin.h:64
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
#define Assert(condition)
Definition: c.h:804
void LogicalConfirmReceivedLocation(XLogRecPtr lsn)
Definition: logical.c:1706
XLogRecPtr candidate_xmin_lsn
Definition: slot.h:163
#define elog(elevel,...)
Definition: elog.h:232
slock_t mutex
Definition: slot.h:120

◆ ResetLogicalStreamingState()

void ResetLogicalStreamingState ( void  )

Definition at line 1793 of file logical.c.

References bsysscan, CheckXidAlive, and InvalidTransactionId.

Referenced by AbortSubTransaction(), and AbortTransaction().

1794 {
1796  bsysscan = false;
1797 }
bool bsysscan
Definition: xact.c:96
#define InvalidTransactionId
Definition: transam.h:31
TransactionId CheckXidAlive
Definition: xact.c:95

◆ UpdateDecodingStats()

void UpdateDecodingStats ( LogicalDecodingContext ctx)

Definition at line 1803 of file logical.c.

References ReplicationSlot::data, DEBUG2, elog, ReplicationSlotPersistentData::name, NameStr, namestrcpy(), pgstat_report_replslot(), LogicalDecodingContext::reorder, LogicalDecodingContext::slot, PgStat_StatReplSlotEntry::slotname, PgStat_StatReplSlotEntry::spill_bytes, PgStat_StatReplSlotEntry::spill_count, PgStat_StatReplSlotEntry::spill_txns, ReorderBuffer::spillBytes, ReorderBuffer::spillCount, ReorderBuffer::spillTxns, PgStat_StatReplSlotEntry::stream_bytes, PgStat_StatReplSlotEntry::stream_count, PgStat_StatReplSlotEntry::stream_txns, ReorderBuffer::streamBytes, ReorderBuffer::streamCount, ReorderBuffer::streamTxns, PgStat_StatReplSlotEntry::total_bytes, PgStat_StatReplSlotEntry::total_txns, ReorderBuffer::totalBytes, and ReorderBuffer::totalTxns.

Referenced by DecodeAbort(), DecodeCommit(), DecodePrepare(), ReorderBufferSerializeTXN(), and ReorderBufferStreamTXN().

1804 {
1805  ReorderBuffer *rb = ctx->reorder;
1806  PgStat_StatReplSlotEntry repSlotStat;
1807 
1808  /* Nothing to do if we don't have any replication stats to be sent. */
1809  if (rb->spillBytes <= 0 && rb->streamBytes <= 0 && rb->totalBytes <= 0)
1810  return;
1811 
1812  elog(DEBUG2, "UpdateDecodingStats: updating stats %p %lld %lld %lld %lld %lld %lld %lld %lld",
1813  rb,
1814  (long long) rb->spillTxns,
1815  (long long) rb->spillCount,
1816  (long long) rb->spillBytes,
1817  (long long) rb->streamTxns,
1818  (long long) rb->streamCount,
1819  (long long) rb->streamBytes,
1820  (long long) rb->totalTxns,
1821  (long long) rb->totalBytes);
1822 
1823  namestrcpy(&repSlotStat.slotname, NameStr(ctx->slot->data.name));
1824  repSlotStat.spill_txns = rb->spillTxns;
1825  repSlotStat.spill_count = rb->spillCount;
1826  repSlotStat.spill_bytes = rb->spillBytes;
1827  repSlotStat.stream_txns = rb->streamTxns;
1828  repSlotStat.stream_count = rb->streamCount;
1829  repSlotStat.stream_bytes = rb->streamBytes;
1830  repSlotStat.total_txns = rb->totalTxns;
1831  repSlotStat.total_bytes = rb->totalBytes;
1832 
1833  pgstat_report_replslot(&repSlotStat);
1834 
1835  rb->spillTxns = 0;
1836  rb->spillCount = 0;
1837  rb->spillBytes = 0;
1838  rb->streamTxns = 0;
1839  rb->streamCount = 0;
1840  rb->streamBytes = 0;
1841  rb->totalTxns = 0;
1842  rb->totalBytes = 0;
1843 }
struct ReorderBuffer * reorder
Definition: logical.h:42
PgStat_Counter spill_bytes
Definition: pgstat.h:921
void namestrcpy(Name name, const char *str)
Definition: name.c:233
ReplicationSlotPersistentData data
Definition: slot.h:147
#define DEBUG2
Definition: elog.h:24
PgStat_Counter total_bytes
Definition: pgstat.h:926
PgStat_Counter stream_bytes
Definition: pgstat.h:924
PgStat_Counter spill_txns
Definition: pgstat.h:919
void pgstat_report_replslot(const PgStat_StatReplSlotEntry *repSlotStat)
Definition: pgstat.c:1813
PgStat_Counter spill_count
Definition: pgstat.h:920
ReplicationSlot * slot
Definition: logical.h:38
PgStat_Counter stream_count
Definition: pgstat.h:923
#define elog(elevel,...)
Definition: elog.h:232
#define NameStr(name)
Definition: c.h:681
PgStat_Counter total_txns
Definition: pgstat.h:925
PgStat_Counter stream_txns
Definition: pgstat.h:922