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, bool skipped_xact)
 
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 current_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)
 
bool LogicalReplicationSlotHasPendingWal (XLogRecPtr end_of_wal)
 

Typedef Documentation

◆ LogicalDecodingContext

◆ LogicalOutputPluginWriterPrepareWrite

◆ LogicalOutputPluginWriterUpdateProgress

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

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 110 of file logical.c.

111 {
113 
114  /*
115  * NB: Adding a new requirement likely means that RestoreSlotFromDisk()
116  * needs the same check.
117  */
118 
120  ereport(ERROR,
121  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
122  errmsg("logical decoding requires wal_level >= logical")));
123 
124  if (MyDatabaseId == InvalidOid)
125  ereport(ERROR,
126  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
127  errmsg("logical decoding requires a database connection")));
128 
129  if (RecoveryInProgress())
130  {
131  /*
132  * This check may have race conditions, but whenever
133  * XLOG_PARAMETER_CHANGE indicates that wal_level has changed, we
134  * verify that there are no existing logical replication slots. And to
135  * avoid races around creating a new slot,
136  * CheckLogicalDecodingRequirements() is called once before creating
137  * the slot, and once when logical decoding is initially starting up.
138  */
140  ereport(ERROR,
141  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
142  errmsg("logical decoding on standby requires wal_level >= logical on the primary")));
143  }
144 }
int errcode(int sqlerrcode)
Definition: elog.c:858
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
Oid MyDatabaseId
Definition: globals.c:89
#define InvalidOid
Definition: postgres_ext.h:36
void CheckSlotRequirements(void)
Definition: slot.c:1166
bool RecoveryInProgress(void)
Definition: xlog.c:6037
int wal_level
Definition: xlog.c:134
WalLevel GetActiveWalLevelOnStandby(void)
Definition: xlog.c:4590
@ WAL_LEVEL_LOGICAL
Definition: xlog.h:74

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

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

◆ 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 496 of file logical.c.

503 {
505  ReplicationSlot *slot;
506  MemoryContext old_context;
507 
508  /* shorter lines... */
509  slot = MyReplicationSlot;
510 
511  /* first some sanity checks that are unlikely to be violated */
512  if (slot == NULL)
513  elog(ERROR, "cannot perform logical decoding without an acquired slot");
514 
515  /* make sure the passed slot is suitable, these are user facing errors */
516  if (SlotIsPhysical(slot))
517  ereport(ERROR,
518  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
519  errmsg("cannot use physical replication slot for logical decoding")));
520 
521  if (slot->data.database != MyDatabaseId)
522  ereport(ERROR,
523  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
524  errmsg("replication slot \"%s\" was not created in this database",
525  NameStr(slot->data.name))));
526 
527  /*
528  * Check if slot has been invalidated due to max_slot_wal_keep_size. Avoid
529  * "cannot get changes" wording in this errmsg because that'd be
530  * confusingly ambiguous about no changes being available when called from
531  * pg_logical_slot_get_changes_guts().
532  */
534  ereport(ERROR,
535  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
536  errmsg("can no longer get changes from replication slot \"%s\"",
538  errdetail("This slot has been invalidated because it exceeded the maximum reserved size.")));
539 
541  ereport(ERROR,
542  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
543  errmsg("can no longer get changes from replication slot \"%s\"",
545  errdetail("This slot has been invalidated because it was conflicting with recovery.")));
546 
549 
550  if (start_lsn == InvalidXLogRecPtr)
551  {
552  /* continue from last position */
553  start_lsn = slot->data.confirmed_flush;
554  }
555  else if (start_lsn < slot->data.confirmed_flush)
556  {
557  /*
558  * It might seem like we should error out in this case, but it's
559  * pretty common for a client to acknowledge a LSN it doesn't have to
560  * do anything for, and thus didn't store persistently, because the
561  * xlog records didn't result in anything relevant for logical
562  * decoding. Clients have to be able to do that to support synchronous
563  * replication.
564  *
565  * Starting at a different LSN than requested might not catch certain
566  * kinds of client errors; so the client may wish to check that
567  * confirmed_flush_lsn matches its expectations.
568  */
569  elog(LOG, "%X/%X has been already streamed, forwarding to %X/%X",
570  LSN_FORMAT_ARGS(start_lsn),
572 
573  start_lsn = slot->data.confirmed_flush;
574  }
575 
576  ctx = StartupDecodingContext(output_plugin_options,
577  start_lsn, InvalidTransactionId, false,
578  fast_forward, xl_routine, prepare_write,
579  do_write, update_progress);
580 
581  /* call output plugin initialization callback */
582  old_context = MemoryContextSwitchTo(ctx->context);
583  if (ctx->callbacks.startup_cb != NULL)
584  startup_cb_wrapper(ctx, &ctx->options, false);
585  MemoryContextSwitchTo(old_context);
586 
587  /*
588  * We allow decoding of prepared transactions when the two_phase is
589  * enabled at the time of slot creation, or when the two_phase option is
590  * given at the streaming start, provided the plugin supports all the
591  * callbacks for two-phase.
592  */
593  ctx->twophase &= (slot->data.two_phase || ctx->twophase_opt_given);
594 
595  /* Mark slot to allow two_phase decoding if not already marked */
596  if (ctx->twophase && !slot->data.two_phase)
597  {
598  SpinLockAcquire(&slot->mutex);
599  slot->data.two_phase = true;
600  slot->data.two_phase_at = start_lsn;
601  SpinLockRelease(&slot->mutex);
604  SnapBuildSetTwoPhaseAt(ctx->snapshot_builder, start_lsn);
605  }
606 
608 
609  ereport(LOG,
610  (errmsg("starting logical decoding for slot \"%s\"",
611  NameStr(slot->data.name)),
612  errdetail("Streaming transactions committing after %X/%X, reading WAL from %X/%X.",
614  LSN_FORMAT_ARGS(slot->data.restart_lsn))));
615 
616  return ctx;
617 }
#define NameStr(name)
Definition: c.h:735
int errdetail(const char *fmt,...)
Definition: elog.c:1202
#define LOG
Definition: elog.h:31
Assert(fmt[strlen(fmt) - 1] !='\n')
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:151
static void startup_cb_wrapper(LogicalDecodingContext *ctx, OutputPluginOptions *opt, bool is_init)
Definition: logical.c:773
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
const void * data
void ReplicationSlotMarkDirty(void)
Definition: slot.c:828
ReplicationSlot * MyReplicationSlot
Definition: slot.c:99
void ReplicationSlotSave(void)
Definition: slot.c:810
#define SlotIsPhysical(slot)
Definition: slot.h:190
@ RS_INVAL_WAL_REMOVED
Definition: slot.h:48
@ RS_INVAL_NONE
Definition: slot.h:46
void SnapBuildSetTwoPhaseAt(SnapBuild *builder, XLogRecPtr ptr)
Definition: snapbuild.c:425
#define SpinLockRelease(lock)
Definition: spin.h:64
#define SpinLockAcquire(lock)
Definition: spin.h:62
OutputPluginOptions options
Definition: logical.h:54
MemoryContext context
Definition: logical.h:36
struct SnapBuild * snapshot_builder
Definition: logical.h:44
OutputPluginCallbacks callbacks
Definition: logical.h:53
struct ReorderBuffer * reorder
Definition: logical.h:43
LogicalDecodeStartupCB startup_cb
XLogRecPtr restart_lsn
Definition: slot.h:88
XLogRecPtr confirmed_flush
Definition: slot.h:99
ReplicationSlotInvalidationCause invalidated
Definition: slot.h:91
slock_t mutex
Definition: slot.h:135
ReplicationSlotPersistentData data
Definition: slot.h:162
#define InvalidTransactionId
Definition: transam.h:31
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28

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

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

◆ 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 330 of file logical.c.

338 {
339  TransactionId xmin_horizon = InvalidTransactionId;
340  ReplicationSlot *slot;
341  NameData plugin_name;
343  MemoryContext old_context;
344 
345  /*
346  * On a standby, this check is also required while creating the slot.
347  * Check the comments in the function.
348  */
350 
351  /* shorter lines... */
352  slot = MyReplicationSlot;
353 
354  /* first some sanity checks that are unlikely to be violated */
355  if (slot == NULL)
356  elog(ERROR, "cannot perform logical decoding without an acquired slot");
357 
358  if (plugin == NULL)
359  elog(ERROR, "cannot initialize logical decoding without a specified plugin");
360 
361  /* Make sure the passed slot is suitable. These are user facing errors. */
362  if (SlotIsPhysical(slot))
363  ereport(ERROR,
364  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
365  errmsg("cannot use physical replication slot for logical decoding")));
366 
367  if (slot->data.database != MyDatabaseId)
368  ereport(ERROR,
369  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
370  errmsg("replication slot \"%s\" was not created in this database",
371  NameStr(slot->data.name))));
372 
373  if (IsTransactionState() &&
375  ereport(ERROR,
376  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
377  errmsg("cannot create logical replication slot in transaction that has performed writes")));
378 
379  /*
380  * Register output plugin name with slot. We need the mutex to avoid
381  * concurrent reading of a partially copied string. But we don't want any
382  * complicated code while holding a spinlock, so do namestrcpy() outside.
383  */
384  namestrcpy(&plugin_name, plugin);
385  SpinLockAcquire(&slot->mutex);
386  slot->data.plugin = plugin_name;
387  SpinLockRelease(&slot->mutex);
388 
389  if (XLogRecPtrIsInvalid(restart_lsn))
391  else
392  {
393  SpinLockAcquire(&slot->mutex);
394  slot->data.restart_lsn = restart_lsn;
395  SpinLockRelease(&slot->mutex);
396  }
397 
398  /* ----
399  * This is a bit tricky: We need to determine a safe xmin horizon to start
400  * decoding from, to avoid starting from a running xacts record referring
401  * to xids whose rows have been vacuumed or pruned
402  * already. GetOldestSafeDecodingTransactionId() returns such a value, but
403  * without further interlock its return value might immediately be out of
404  * date.
405  *
406  * So we have to acquire the ProcArrayLock to prevent computation of new
407  * xmin horizons by other backends, get the safe decoding xid, and inform
408  * the slot machinery about the new limit. Once that's done the
409  * ProcArrayLock can be released as the slot machinery now is
410  * protecting against vacuum.
411  *
412  * Note that, temporarily, the data, not just the catalog, xmin has to be
413  * reserved if a data snapshot is to be exported. Otherwise the initial
414  * data snapshot created here is not guaranteed to be valid. After that
415  * the data xmin doesn't need to be managed anymore and the global xmin
416  * should be recomputed. As we are fine with losing the pegged data xmin
417  * after crash - no chance a snapshot would get exported anymore - we can
418  * get away with just setting the slot's
419  * effective_xmin. ReplicationSlotRelease will reset it again.
420  *
421  * ----
422  */
423  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
424 
425  xmin_horizon = GetOldestSafeDecodingTransactionId(!need_full_snapshot);
426 
427  SpinLockAcquire(&slot->mutex);
428  slot->effective_catalog_xmin = xmin_horizon;
429  slot->data.catalog_xmin = xmin_horizon;
430  if (need_full_snapshot)
431  slot->effective_xmin = xmin_horizon;
432  SpinLockRelease(&slot->mutex);
433 
435 
436  LWLockRelease(ProcArrayLock);
437 
440 
441  ctx = StartupDecodingContext(NIL, restart_lsn, xmin_horizon,
442  need_full_snapshot, false,
443  xl_routine, prepare_write, do_write,
444  update_progress);
445 
446  /* call output plugin initialization callback */
447  old_context = MemoryContextSwitchTo(ctx->context);
448  if (ctx->callbacks.startup_cb != NULL)
449  startup_cb_wrapper(ctx, &ctx->options, true);
450  MemoryContextSwitchTo(old_context);
451 
452  /*
453  * We allow decoding of prepared transactions when the two_phase is
454  * enabled at the time of slot creation, or when the two_phase option is
455  * given at the streaming start, provided the plugin supports all the
456  * callbacks for two-phase.
457  */
458  ctx->twophase &= slot->data.two_phase;
459 
461 
462  return ctx;
463 }
uint32 TransactionId
Definition: c.h:641
void CheckLogicalDecodingRequirements(void)
Definition: logical.c:110
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1195
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1808
@ LW_EXCLUSIVE
Definition: lwlock.h:116
void namestrcpy(Name name, const char *str)
Definition: name.c:233
#define NIL
Definition: pg_list.h:68
static const char * plugin
TransactionId GetOldestSafeDecodingTransactionId(bool catalogOnly)
Definition: procarray.c:2909
void ReplicationSlotReserveWal(void)
Definition: slot.c:1205
void ReplicationSlotsComputeRequiredXmin(bool already_locked)
Definition: slot.c:867
TransactionId catalog_xmin
Definition: slot.h:85
TransactionId effective_catalog_xmin
Definition: slot.h:159
TransactionId effective_xmin
Definition: slot.h:158
Definition: c.h:730
bool IsTransactionState(void)
Definition: xact.c:378
TransactionId GetTopTransactionIdIfAny(void)
Definition: xact.c:432
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29

References LogicalDecodingContext::callbacks, ReplicationSlotPersistentData::catalog_xmin, CheckLogicalDecodingRequirements(), LogicalDecodingContext::context, 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, plugin, 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().

◆ DecodingContextFindStartpoint()

void DecodingContextFindStartpoint ( LogicalDecodingContext ctx)

Definition at line 632 of file logical.c.

633 {
634  ReplicationSlot *slot = ctx->slot;
635 
636  /* Initialize from where to start reading WAL. */
637  XLogBeginRead(ctx->reader, slot->data.restart_lsn);
638 
639  elog(DEBUG1, "searching for logical decoding starting point, starting at %X/%X",
641 
642  /* Wait for a consistent starting point */
643  for (;;)
644  {
645  XLogRecord *record;
646  char *err = NULL;
647 
648  /* the read_page callback waits for new WAL */
649  record = XLogReadRecord(ctx->reader, &err);
650  if (err)
651  elog(ERROR, "could not find logical decoding starting point: %s", err);
652  if (!record)
653  elog(ERROR, "could not find logical decoding starting point");
654 
656 
657  /* only continue till we found a consistent spot */
658  if (DecodingContextReady(ctx))
659  break;
660 
662  }
663 
664  SpinLockAcquire(&slot->mutex);
665  slot->data.confirmed_flush = ctx->reader->EndRecPtr;
666  if (slot->data.two_phase)
667  slot->data.two_phase_at = ctx->reader->EndRecPtr;
668  SpinLockRelease(&slot->mutex);
669 }
void LogicalDecodingProcessRecord(LogicalDecodingContext *ctx, XLogReaderState *record)
Definition: decode.c:91
#define DEBUG1
Definition: elog.h:30
void err(int eval, const char *fmt,...)
Definition: err.c:43
bool DecodingContextReady(LogicalDecodingContext *ctx)
Definition: logical.c:623
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
XLogReaderState * reader
Definition: logical.h:42
ReplicationSlot * slot
Definition: logical.h:39
XLogRecPtr EndRecPtr
Definition: xlogreader.h:207
XLogRecord * XLogReadRecord(XLogReaderState *state, char **errormsg)
Definition: xlogreader.c:391
void XLogBeginRead(XLogReaderState *state, XLogRecPtr RecPtr)
Definition: xlogreader.c:233

References CHECK_FOR_INTERRUPTS, ReplicationSlotPersistentData::confirmed_flush, ReplicationSlot::data, DEBUG1, DecodingContextReady(), elog(), XLogReaderState::EndRecPtr, err(), 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().

◆ DecodingContextReady()

bool DecodingContextReady ( LogicalDecodingContext ctx)

Definition at line 623 of file logical.c.

624 {
626 }
SnapBuildState SnapBuildCurrentState(SnapBuild *builder)
Definition: snapbuild.c:407
@ SNAPBUILD_CONSISTENT
Definition: snapbuild.h:46

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

Referenced by DecodingContextFindStartpoint().

◆ filter_by_origin_cb_wrapper()

bool filter_by_origin_cb_wrapper ( LogicalDecodingContext ctx,
RepOriginId  origin_id 
)

Definition at line 1198 of file logical.c.

1199 {
1201  ErrorContextCallback errcallback;
1202  bool ret;
1203 
1204  Assert(!ctx->fast_forward);
1205 
1206  /* Push callback + info on the error context stack */
1207  state.ctx = ctx;
1208  state.callback_name = "filter_by_origin";
1209  state.report_location = InvalidXLogRecPtr;
1210  errcallback.callback = output_plugin_error_callback;
1211  errcallback.arg = (void *) &state;
1212  errcallback.previous = error_context_stack;
1213  error_context_stack = &errcallback;
1214 
1215  /* set output state */
1216  ctx->accept_writes = false;
1217  ctx->end_xact = false;
1218 
1219  /* do the actual work: call callback */
1220  ret = ctx->callbacks.filter_by_origin_cb(ctx, origin_id);
1221 
1222  /* Pop the error context stack */
1223  error_context_stack = errcallback.previous;
1224 
1225  return ret;
1226 }
ErrorContextCallback * error_context_stack
Definition: elog.c:95
static void output_plugin_error_callback(void *arg)
Definition: logical.c:754
struct ErrorContextCallback * previous
Definition: elog.h:295
void(* callback)(void *arg)
Definition: elog.h:296
LogicalDecodeFilterByOriginCB filter_by_origin_cb
Definition: regguts.h:323

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

Referenced by FilterByOrigin().

◆ filter_prepare_cb_wrapper()

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

Definition at line 1166 of file logical.c.

1168 {
1170  ErrorContextCallback errcallback;
1171  bool ret;
1172 
1173  Assert(!ctx->fast_forward);
1174 
1175  /* Push callback + info on the error context stack */
1176  state.ctx = ctx;
1177  state.callback_name = "filter_prepare";
1178  state.report_location = InvalidXLogRecPtr;
1179  errcallback.callback = output_plugin_error_callback;
1180  errcallback.arg = (void *) &state;
1181  errcallback.previous = error_context_stack;
1182  error_context_stack = &errcallback;
1183 
1184  /* set output state */
1185  ctx->accept_writes = false;
1186  ctx->end_xact = false;
1187 
1188  /* do the actual work: call callback */
1189  ret = ctx->callbacks.filter_prepare_cb(ctx, xid, gid);
1190 
1191  /* Pop the error context stack */
1192  error_context_stack = errcallback.previous;
1193 
1194  return ret;
1195 }
LogicalDecodeFilterPrepareCB filter_prepare_cb

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

Referenced by FilterPrepare().

◆ FreeDecodingContext()

void FreeDecodingContext ( LogicalDecodingContext ctx)

◆ LogicalConfirmReceivedLocation()

void LogicalConfirmReceivedLocation ( XLogRecPtr  lsn)

Definition at line 1817 of file logical.c.

1818 {
1819  Assert(lsn != InvalidXLogRecPtr);
1820 
1821  /* Do an unlocked check for candidate_lsn first. */
1824  {
1825  bool updated_xmin = false;
1826  bool updated_restart = false;
1827 
1829 
1831 
1832  /* if we're past the location required for bumping xmin, do so */
1835  {
1836  /*
1837  * We have to write the changed xmin to disk *before* we change
1838  * the in-memory value, otherwise after a crash we wouldn't know
1839  * that some catalog tuples might have been removed already.
1840  *
1841  * Ensure that by first writing to ->xmin and only update
1842  * ->effective_xmin once the new state is synced to disk. After a
1843  * crash ->effective_xmin is set to ->xmin.
1844  */
1847  {
1851  updated_xmin = true;
1852  }
1853  }
1854 
1857  {
1859 
1863  updated_restart = true;
1864  }
1865 
1867 
1868  /* first write new xmin to disk, so we know what's up after a crash */
1869  if (updated_xmin || updated_restart)
1870  {
1873  elog(DEBUG1, "updated xmin: %u restart: %u", updated_xmin, updated_restart);
1874  }
1875 
1876  /*
1877  * Now the new xmin is safely on disk, we can let the global value
1878  * advance. We do not take ProcArrayLock or similar since we only
1879  * advance xmin here and there's not much harm done by a concurrent
1880  * computation missing that.
1881  */
1882  if (updated_xmin)
1883  {
1887 
1890  }
1891  }
1892  else
1893  {
1897  }
1898 }
void ReplicationSlotsComputeRequiredLSN(void)
Definition: slot.c:923
XLogRecPtr candidate_xmin_lsn
Definition: slot.h:178
XLogRecPtr candidate_restart_valid
Definition: slot.h:179
XLogRecPtr candidate_restart_lsn
Definition: slot.h:180
TransactionId candidate_catalog_xmin
Definition: slot.h:177
#define TransactionIdIsValid(xid)
Definition: transam.h:41

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().

◆ LogicalIncreaseRestartDecodingForSlot()

void LogicalIncreaseRestartDecodingForSlot ( XLogRecPtr  current_lsn,
XLogRecPtr  restart_lsn 
)

Definition at line 1743 of file logical.c.

1744 {
1745  bool updated_lsn = false;
1746  ReplicationSlot *slot;
1747 
1748  slot = MyReplicationSlot;
1749 
1750  Assert(slot != NULL);
1751  Assert(restart_lsn != InvalidXLogRecPtr);
1752  Assert(current_lsn != InvalidXLogRecPtr);
1753 
1754  SpinLockAcquire(&slot->mutex);
1755 
1756  /* don't overwrite if have a newer restart lsn */
1757  if (restart_lsn <= slot->data.restart_lsn)
1758  {
1759  }
1760 
1761  /*
1762  * We might have already flushed far enough to directly accept this lsn,
1763  * in this case there is no need to check for existing candidate LSNs
1764  */
1765  else if (current_lsn <= slot->data.confirmed_flush)
1766  {
1767  slot->candidate_restart_valid = current_lsn;
1768  slot->candidate_restart_lsn = restart_lsn;
1769 
1770  /* our candidate can directly be used */
1771  updated_lsn = true;
1772  }
1773 
1774  /*
1775  * Only increase if the previous values have been applied, otherwise we
1776  * might never end up updating if the receiver acks too slowly. A missed
1777  * value here will just cause some extra effort after reconnecting.
1778  */
1780  {
1781  slot->candidate_restart_valid = current_lsn;
1782  slot->candidate_restart_lsn = restart_lsn;
1783  SpinLockRelease(&slot->mutex);
1784 
1785  elog(DEBUG1, "got new restart lsn %X/%X at %X/%X",
1786  LSN_FORMAT_ARGS(restart_lsn),
1787  LSN_FORMAT_ARGS(current_lsn));
1788  }
1789  else
1790  {
1791  XLogRecPtr candidate_restart_lsn;
1792  XLogRecPtr candidate_restart_valid;
1793  XLogRecPtr confirmed_flush;
1794 
1795  candidate_restart_lsn = slot->candidate_restart_lsn;
1796  candidate_restart_valid = slot->candidate_restart_valid;
1797  confirmed_flush = slot->data.confirmed_flush;
1798  SpinLockRelease(&slot->mutex);
1799 
1800  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",
1801  LSN_FORMAT_ARGS(restart_lsn),
1802  LSN_FORMAT_ARGS(current_lsn),
1803  LSN_FORMAT_ARGS(candidate_restart_lsn),
1804  LSN_FORMAT_ARGS(candidate_restart_valid),
1805  LSN_FORMAT_ARGS(confirmed_flush));
1806  }
1807 
1808  /* candidates are already valid with the current flush position, apply */
1809  if (updated_lsn)
1811 }
void LogicalConfirmReceivedLocation(XLogRecPtr lsn)
Definition: logical.c:1817
uint64 XLogRecPtr
Definition: xlogdefs.h:21

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

Referenced by SnapBuildProcessRunningXacts().

◆ LogicalIncreaseXminForSlot()

void LogicalIncreaseXminForSlot ( XLogRecPtr  current_lsn,
TransactionId  xmin 
)

Definition at line 1675 of file logical.c.

1676 {
1677  bool updated_xmin = false;
1678  ReplicationSlot *slot;
1679  bool got_new_xmin = false;
1680 
1681  slot = MyReplicationSlot;
1682 
1683  Assert(slot != NULL);
1684 
1685  SpinLockAcquire(&slot->mutex);
1686 
1687  /*
1688  * don't overwrite if we already have a newer xmin. This can happen if we
1689  * restart decoding in a slot.
1690  */
1692  {
1693  }
1694 
1695  /*
1696  * If the client has already confirmed up to this lsn, we directly can
1697  * mark this as accepted. This can happen if we restart decoding in a
1698  * slot.
1699  */
1700  else if (current_lsn <= slot->data.confirmed_flush)
1701  {
1702  slot->candidate_catalog_xmin = xmin;
1703  slot->candidate_xmin_lsn = current_lsn;
1704 
1705  /* our candidate can directly be used */
1706  updated_xmin = true;
1707  }
1708 
1709  /*
1710  * Only increase if the previous values have been applied, otherwise we
1711  * might never end up updating if the receiver acks too slowly.
1712  */
1713  else if (slot->candidate_xmin_lsn == InvalidXLogRecPtr)
1714  {
1715  slot->candidate_catalog_xmin = xmin;
1716  slot->candidate_xmin_lsn = current_lsn;
1717 
1718  /*
1719  * Log new xmin at an appropriate log level after releasing the
1720  * spinlock.
1721  */
1722  got_new_xmin = true;
1723  }
1724  SpinLockRelease(&slot->mutex);
1725 
1726  if (got_new_xmin)
1727  elog(DEBUG1, "got new catalog xmin %u at %X/%X", xmin,
1728  LSN_FORMAT_ARGS(current_lsn));
1729 
1730  /* candidate already valid with the current flush position, apply */
1731  if (updated_xmin)
1733 }
bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:299

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

Referenced by SnapBuildProcessRunningXacts().

◆ LogicalReplicationSlotHasPendingWal()

bool LogicalReplicationSlotHasPendingWal ( XLogRecPtr  end_of_wal)

Definition at line 1961 of file logical.c.

1962 {
1963  bool has_pending_wal = false;
1964 
1966 
1967  PG_TRY();
1968  {
1970 
1971  /*
1972  * Create our decoding context in fast_forward mode, passing start_lsn
1973  * as InvalidXLogRecPtr, so that we start processing from the slot's
1974  * confirmed_flush.
1975  */
1977  NIL,
1978  true, /* fast_forward */
1979  XL_ROUTINE(.page_read = read_local_xlog_page,
1980  .segment_open = wal_segment_open,
1981  .segment_close = wal_segment_close),
1982  NULL, NULL, NULL);
1983 
1984  /*
1985  * Start reading at the slot's restart_lsn, which we know points to a
1986  * valid record.
1987  */
1989 
1990  /* Invalidate non-timetravel entries */
1992 
1993  /* Loop until the end of WAL or some changes are processed */
1994  while (!has_pending_wal && ctx->reader->EndRecPtr < end_of_wal)
1995  {
1996  XLogRecord *record;
1997  char *errm = NULL;
1998 
1999  record = XLogReadRecord(ctx->reader, &errm);
2000 
2001  if (errm)
2002  elog(ERROR, "could not find record for logical decoding: %s", errm);
2003 
2004  if (record != NULL)
2006 
2007  has_pending_wal = ctx->processing_required;
2008 
2010  }
2011 
2012  /* Clean up */
2013  FreeDecodingContext(ctx);
2015  }
2016  PG_CATCH();
2017  {
2018  /* clear all timetravel entries */
2020 
2021  PG_RE_THROW();
2022  }
2023  PG_END_TRY();
2024 
2025  return has_pending_wal;
2026 }
#define PG_RE_THROW()
Definition: elog.h:411
#define PG_TRY(...)
Definition: elog.h:370
#define PG_END_TRY(...)
Definition: elog.h:395
#define PG_CATCH(...)
Definition: elog.h:380
void InvalidateSystemCaches(void)
Definition: inval.c:793
void FreeDecodingContext(LogicalDecodingContext *ctx)
Definition: logical.c:676
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: logical.c:496
#define XL_ROUTINE(...)
Definition: xlogreader.h:117
void wal_segment_close(XLogReaderState *state)
Definition: xlogutils.c:844
void wal_segment_open(XLogReaderState *state, XLogSegNo nextSegNo, TimeLineID *tli_p)
Definition: xlogutils.c:819
int read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *cur_page)
Definition: xlogutils.c:863

References Assert(), CHECK_FOR_INTERRUPTS, CreateDecodingContext(), ReplicationSlot::data, elog(), XLogReaderState::EndRecPtr, ERROR, FreeDecodingContext(), InvalidateSystemCaches(), InvalidXLogRecPtr, LogicalDecodingProcessRecord(), MyReplicationSlot, NIL, PG_CATCH, PG_END_TRY, PG_RE_THROW, PG_TRY, LogicalDecodingContext::processing_required, read_local_xlog_page(), LogicalDecodingContext::reader, ReplicationSlotPersistentData::restart_lsn, wal_segment_close(), wal_segment_open(), XL_ROUTINE, XLogBeginRead(), and XLogReadRecord().

Referenced by binary_upgrade_logical_slot_has_caught_up().

◆ ResetLogicalStreamingState()

void ResetLogicalStreamingState ( void  )

Definition at line 1904 of file logical.c.

1905 {
1907  bsysscan = false;
1908 }
bool bsysscan
Definition: xact.c:100
TransactionId CheckXidAlive
Definition: xact.c:99

References bsysscan, CheckXidAlive, and InvalidTransactionId.

Referenced by AbortSubTransaction(), and AbortTransaction().

◆ UpdateDecodingStats()

void UpdateDecodingStats ( LogicalDecodingContext ctx)

Definition at line 1914 of file logical.c.

1915 {
1916  ReorderBuffer *rb = ctx->reorder;
1917  PgStat_StatReplSlotEntry repSlotStat;
1918 
1919  /* Nothing to do if we don't have any replication stats to be sent. */
1920  if (rb->spillBytes <= 0 && rb->streamBytes <= 0 && rb->totalBytes <= 0)
1921  return;
1922 
1923  elog(DEBUG2, "UpdateDecodingStats: updating stats %p %lld %lld %lld %lld %lld %lld %lld %lld",
1924  rb,
1925  (long long) rb->spillTxns,
1926  (long long) rb->spillCount,
1927  (long long) rb->spillBytes,
1928  (long long) rb->streamTxns,
1929  (long long) rb->streamCount,
1930  (long long) rb->streamBytes,
1931  (long long) rb->totalTxns,
1932  (long long) rb->totalBytes);
1933 
1934  repSlotStat.spill_txns = rb->spillTxns;
1935  repSlotStat.spill_count = rb->spillCount;
1936  repSlotStat.spill_bytes = rb->spillBytes;
1937  repSlotStat.stream_txns = rb->streamTxns;
1938  repSlotStat.stream_count = rb->streamCount;
1939  repSlotStat.stream_bytes = rb->streamBytes;
1940  repSlotStat.total_txns = rb->totalTxns;
1941  repSlotStat.total_bytes = rb->totalBytes;
1942 
1943  pgstat_report_replslot(ctx->slot, &repSlotStat);
1944 
1945  rb->spillTxns = 0;
1946  rb->spillCount = 0;
1947  rb->spillBytes = 0;
1948  rb->streamTxns = 0;
1949  rb->streamCount = 0;
1950  rb->streamBytes = 0;
1951  rb->totalTxns = 0;
1952  rb->totalBytes = 0;
1953 }
#define DEBUG2
Definition: elog.h:29
void pgstat_report_replslot(ReplicationSlot *slot, const PgStat_StatReplSlotEntry *repSlotStat)
PgStat_Counter stream_count
Definition: pgstat.h:370
PgStat_Counter total_txns
Definition: pgstat.h:372
PgStat_Counter total_bytes
Definition: pgstat.h:373
PgStat_Counter spill_txns
Definition: pgstat.h:366
PgStat_Counter stream_txns
Definition: pgstat.h:369
PgStat_Counter spill_count
Definition: pgstat.h:367
PgStat_Counter stream_bytes
Definition: pgstat.h:371
PgStat_Counter spill_bytes
Definition: pgstat.h:368

References DEBUG2, elog(), pgstat_report_replslot(), LogicalDecodingContext::reorder, LogicalDecodingContext::slot, 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().