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

Go to the source code of this file.

Data Structures

struct  ReplicationSlotPersistentData
 
struct  ReplicationSlot
 
struct  ReplicationSlotCtlData
 

Macros

#define SlotIsPhysical(slot)   ((slot)->data.database == InvalidOid)
 
#define SlotIsLogical(slot)   ((slot)->data.database != InvalidOid)
 

Typedefs

typedef enum ReplicationSlotPersistency ReplicationSlotPersistency
 
typedef enum ReplicationSlotInvalidationCause ReplicationSlotInvalidationCause
 
typedef struct ReplicationSlotPersistentData ReplicationSlotPersistentData
 
typedef struct ReplicationSlot ReplicationSlot
 
typedef struct ReplicationSlotCtlData ReplicationSlotCtlData
 

Enumerations

enum  ReplicationSlotPersistency { RS_PERSISTENT , RS_EPHEMERAL , RS_TEMPORARY }
 
enum  ReplicationSlotInvalidationCause { RS_INVAL_NONE , RS_INVAL_WAL_REMOVED , RS_INVAL_HORIZON , RS_INVAL_WAL_LEVEL }
 

Functions

Size ReplicationSlotsShmemSize (void)
 
void ReplicationSlotsShmemInit (void)
 
void ReplicationSlotCreate (const char *name, bool db_specific, ReplicationSlotPersistency persistency, bool two_phase, bool failover, bool synced)
 
void ReplicationSlotPersist (void)
 
void ReplicationSlotDrop (const char *name, bool nowait)
 
void ReplicationSlotDropAcquired (void)
 
void ReplicationSlotAlter (const char *name, bool failover)
 
void ReplicationSlotAcquire (const char *name, bool nowait)
 
void ReplicationSlotRelease (void)
 
void ReplicationSlotCleanup (void)
 
void ReplicationSlotSave (void)
 
void ReplicationSlotMarkDirty (void)
 
void ReplicationSlotInitialize (void)
 
bool ReplicationSlotValidateName (const char *name, int elevel)
 
void ReplicationSlotReserveWal (void)
 
void ReplicationSlotsComputeRequiredXmin (bool already_locked)
 
void ReplicationSlotsComputeRequiredLSN (void)
 
XLogRecPtr ReplicationSlotsComputeLogicalRestartLSN (void)
 
bool ReplicationSlotsCountDBSlots (Oid dboid, int *nslots, int *nactive)
 
void ReplicationSlotsDropDBSlots (Oid dboid)
 
bool InvalidateObsoleteReplicationSlots (ReplicationSlotInvalidationCause cause, XLogSegNo oldestSegno, Oid dboid, TransactionId snapshotConflictHorizon)
 
ReplicationSlotSearchNamedReplicationSlot (const char *name, bool need_lock)
 
int ReplicationSlotIndex (ReplicationSlot *slot)
 
bool ReplicationSlotName (int index, Name name)
 
void ReplicationSlotNameForTablesync (Oid suboid, Oid relid, char *syncslotname, Size szslot)
 
void ReplicationSlotDropAtPubNode (WalReceiverConn *wrconn, char *slotname, bool missing_ok)
 
void StartupReplicationSlots (void)
 
void CheckPointReplicationSlots (bool is_shutdown)
 
void CheckSlotRequirements (void)
 
void CheckSlotPermissions (void)
 
ReplicationSlotInvalidationCause GetSlotInvalidationCause (const char *invalidation_reason)
 
bool SlotExistsInStandbySlotNames (const char *slot_name)
 
bool StandbySlotsHaveCaughtup (XLogRecPtr wait_for_lsn, int elevel)
 
void WaitForStandbyConfirmation (XLogRecPtr wait_for_lsn)
 

Variables

PGDLLIMPORT const char *const SlotInvalidationCauses []
 
PGDLLIMPORT ReplicationSlotCtlDataReplicationSlotCtl
 
PGDLLIMPORT ReplicationSlotMyReplicationSlot
 
PGDLLIMPORT int max_replication_slots
 
PGDLLIMPORT char * standby_slot_names
 

Macro Definition Documentation

◆ SlotIsLogical

#define SlotIsLogical (   slot)    ((slot)->data.database != InvalidOid)

Definition at line 210 of file slot.h.

◆ SlotIsPhysical

#define SlotIsPhysical (   slot)    ((slot)->data.database == InvalidOid)

Definition at line 209 of file slot.h.

Typedef Documentation

◆ ReplicationSlot

◆ ReplicationSlotCtlData

◆ ReplicationSlotInvalidationCause

◆ ReplicationSlotPersistency

◆ ReplicationSlotPersistentData

Enumeration Type Documentation

◆ ReplicationSlotInvalidationCause

Enumerator
RS_INVAL_NONE 
RS_INVAL_WAL_REMOVED 
RS_INVAL_HORIZON 
RS_INVAL_WAL_LEVEL 

Definition at line 47 of file slot.h.

48 {
50  /* required WAL has been removed */
52  /* required rows have been removed */
54  /* wal_level insufficient for slot */
ReplicationSlotInvalidationCause
Definition: slot.h:48
@ RS_INVAL_WAL_REMOVED
Definition: slot.h:51
@ RS_INVAL_HORIZON
Definition: slot.h:53
@ RS_INVAL_WAL_LEVEL
Definition: slot.h:55
@ RS_INVAL_NONE
Definition: slot.h:49

◆ ReplicationSlotPersistency

Enumerator
RS_PERSISTENT 
RS_EPHEMERAL 
RS_TEMPORARY 

Definition at line 33 of file slot.h.

34 {
ReplicationSlotPersistency
Definition: slot.h:34
@ RS_PERSISTENT
Definition: slot.h:35
@ RS_EPHEMERAL
Definition: slot.h:36
@ RS_TEMPORARY
Definition: slot.h:37

Function Documentation

◆ CheckPointReplicationSlots()

void CheckPointReplicationSlots ( bool  is_shutdown)

Definition at line 1835 of file slot.c.

1836 {
1837  int i;
1838 
1839  elog(DEBUG1, "performing replication slot checkpoint");
1840 
1841  /*
1842  * Prevent any slot from being created/dropped while we're active. As we
1843  * explicitly do *not* want to block iterating over replication_slots or
1844  * acquiring a slot we cannot take the control lock - but that's OK,
1845  * because holding ReplicationSlotAllocationLock is strictly stronger, and
1846  * enough to guarantee that nobody can change the in_use bits on us.
1847  */
1848  LWLockAcquire(ReplicationSlotAllocationLock, LW_SHARED);
1849 
1850  for (i = 0; i < max_replication_slots; i++)
1851  {
1853  char path[MAXPGPATH];
1854 
1855  if (!s->in_use)
1856  continue;
1857 
1858  /* save the slot to disk, locking is handled in SaveSlotToPath() */
1859  sprintf(path, "pg_replslot/%s", NameStr(s->data.name));
1860 
1861  /*
1862  * Slot's data is not flushed each time the confirmed_flush LSN is
1863  * updated as that could lead to frequent writes. However, we decide
1864  * to force a flush of all logical slot's data at the time of shutdown
1865  * if the confirmed_flush LSN is changed since we last flushed it to
1866  * disk. This helps in avoiding an unnecessary retreat of the
1867  * confirmed_flush LSN after restart.
1868  */
1869  if (is_shutdown && SlotIsLogical(s))
1870  {
1871  SpinLockAcquire(&s->mutex);
1872 
1874 
1875  if (s->data.invalidated == RS_INVAL_NONE &&
1877  {
1878  s->just_dirtied = true;
1879  s->dirty = true;
1880  }
1881  SpinLockRelease(&s->mutex);
1882  }
1883 
1884  SaveSlotToPath(s, path, LOG);
1885  }
1886  LWLockRelease(ReplicationSlotAllocationLock);
1887 }
#define NameStr(name)
Definition: c.h:746
#define Assert(condition)
Definition: c.h:858
#define LOG
Definition: elog.h:31
#define DEBUG1
Definition: elog.h:30
#define elog(elevel,...)
Definition: elog.h:224
int i
Definition: isn.c:73
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1170
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1783
@ LW_SHARED
Definition: lwlock.h:115
#define MAXPGPATH
#define sprintf
Definition: port.h:240
static void SaveSlotToPath(ReplicationSlot *slot, const char *dir, int elevel)
Definition: slot.c:2016
int max_replication_slots
Definition: slot.c:141
ReplicationSlotCtlData * ReplicationSlotCtl
Definition: slot.c:135
#define SlotIsLogical(slot)
Definition: slot.h:210
#define SpinLockRelease(lock)
Definition: spin.h:64
#define SpinLockAcquire(lock)
Definition: spin.h:62
ReplicationSlot replication_slots[1]
Definition: slot.h:221
XLogRecPtr confirmed_flush
Definition: slot.h:104
ReplicationSlotInvalidationCause invalidated
Definition: slot.h:96
slock_t mutex
Definition: slot.h:151
XLogRecPtr last_saved_confirmed_flush
Definition: slot.h:203
bool in_use
Definition: slot.h:154
bool just_dirtied
Definition: slot.h:160
bool dirty
Definition: slot.h:161
ReplicationSlotPersistentData data
Definition: slot.h:178

References Assert, ReplicationSlotPersistentData::confirmed_flush, ReplicationSlot::data, DEBUG1, ReplicationSlot::dirty, elog, i, ReplicationSlot::in_use, ReplicationSlotPersistentData::invalidated, ReplicationSlot::just_dirtied, ReplicationSlot::last_saved_confirmed_flush, LOG, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_replication_slots, MAXPGPATH, ReplicationSlot::mutex, ReplicationSlotPersistentData::name, NameStr, ReplicationSlotCtlData::replication_slots, ReplicationSlotCtl, RS_INVAL_NONE, SaveSlotToPath(), SlotIsLogical, SpinLockAcquire, SpinLockRelease, and sprintf.

Referenced by CheckPointGuts().

◆ CheckSlotPermissions()

void CheckSlotPermissions ( void  )

Definition at line 1380 of file slot.c.

1381 {
1382  if (!has_rolreplication(GetUserId()))
1383  ereport(ERROR,
1384  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1385  errmsg("permission denied to use replication slots"),
1386  errdetail("Only roles with the %s attribute may use replication slots.",
1387  "REPLICATION")));
1388 }
int errdetail(const char *fmt,...)
Definition: elog.c:1205
int errcode(int sqlerrcode)
Definition: elog.c:859
int errmsg(const char *fmt,...)
Definition: elog.c:1072
#define ERROR
Definition: elog.h:39
#define ereport(elevel,...)
Definition: elog.h:149
Oid GetUserId(void)
Definition: miscinit.c:514
bool has_rolreplication(Oid roleid)
Definition: miscinit.c:711

References ereport, errcode(), errdetail(), errmsg(), ERROR, GetUserId(), and has_rolreplication().

Referenced by copy_replication_slot(), pg_create_logical_replication_slot(), pg_create_physical_replication_slot(), pg_drop_replication_slot(), pg_logical_slot_get_changes_guts(), pg_replication_slot_advance(), and pg_sync_replication_slots().

◆ CheckSlotRequirements()

void CheckSlotRequirements ( void  )

Definition at line 1358 of file slot.c.

1359 {
1360  /*
1361  * NB: Adding a new requirement likely means that RestoreSlotFromDisk()
1362  * needs the same check.
1363  */
1364 
1365  if (max_replication_slots == 0)
1366  ereport(ERROR,
1367  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1368  errmsg("replication slots can only be used if max_replication_slots > 0")));
1369 
1371  ereport(ERROR,
1372  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1373  errmsg("replication slots can only be used if wal_level >= replica")));
1374 }
int wal_level
Definition: xlog.c:131
@ WAL_LEVEL_REPLICA
Definition: xlog.h:73

References ereport, errcode(), errmsg(), ERROR, max_replication_slots, wal_level, and WAL_LEVEL_REPLICA.

Referenced by CheckLogicalDecodingRequirements(), copy_replication_slot(), pg_create_physical_replication_slot(), and pg_drop_replication_slot().

◆ GetSlotInvalidationCause()

ReplicationSlotInvalidationCause GetSlotInvalidationCause ( const char *  invalidation_reason)

Definition at line 2390 of file slot.c.

2391 {
2394  bool found PG_USED_FOR_ASSERTS_ONLY = false;
2395 
2396  Assert(invalidation_reason);
2397 
2398  for (cause = RS_INVAL_NONE; cause <= RS_INVAL_MAX_CAUSES; cause++)
2399  {
2400  if (strcmp(SlotInvalidationCauses[cause], invalidation_reason) == 0)
2401  {
2402  found = true;
2403  result = cause;
2404  break;
2405  }
2406  }
2407 
2408  Assert(found);
2409  return result;
2410 }
#define PG_USED_FOR_ASSERTS_ONLY
Definition: c.h:182
#define RS_INVAL_MAX_CAUSES
Definition: slot.c:113
const char *const SlotInvalidationCauses[]
Definition: slot.c:105

References Assert, PG_USED_FOR_ASSERTS_ONLY, RS_INVAL_MAX_CAUSES, RS_INVAL_NONE, and SlotInvalidationCauses.

Referenced by synchronize_slots().

◆ InvalidateObsoleteReplicationSlots()

bool InvalidateObsoleteReplicationSlots ( ReplicationSlotInvalidationCause  cause,
XLogSegNo  oldestSegno,
Oid  dboid,
TransactionId  snapshotConflictHorizon 
)

Definition at line 1779 of file slot.c.

1782 {
1783  XLogRecPtr oldestLSN;
1784  bool invalidated = false;
1785 
1786  Assert(cause != RS_INVAL_HORIZON || TransactionIdIsValid(snapshotConflictHorizon));
1787  Assert(cause != RS_INVAL_WAL_REMOVED || oldestSegno > 0);
1788  Assert(cause != RS_INVAL_NONE);
1789 
1790  if (max_replication_slots == 0)
1791  return invalidated;
1792 
1793  XLogSegNoOffsetToRecPtr(oldestSegno, 0, wal_segment_size, oldestLSN);
1794 
1795 restart:
1796  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
1797  for (int i = 0; i < max_replication_slots; i++)
1798  {
1800 
1801  if (!s->in_use)
1802  continue;
1803 
1804  if (InvalidatePossiblyObsoleteSlot(cause, s, oldestLSN, dboid,
1805  snapshotConflictHorizon,
1806  &invalidated))
1807  {
1808  /* if the lock was released, start from scratch */
1809  goto restart;
1810  }
1811  }
1812  LWLockRelease(ReplicationSlotControlLock);
1813 
1814  /*
1815  * If any slots have been invalidated, recalculate the resource limits.
1816  */
1817  if (invalidated)
1818  {
1821  }
1822 
1823  return invalidated;
1824 }
void ReplicationSlotsComputeRequiredXmin(bool already_locked)
Definition: slot.c:1045
void ReplicationSlotsComputeRequiredLSN(void)
Definition: slot.c:1101
static bool InvalidatePossiblyObsoleteSlot(ReplicationSlotInvalidationCause cause, ReplicationSlot *s, XLogRecPtr oldestLSN, Oid dboid, TransactionId snapshotConflictHorizon, bool *invalidated)
Definition: slot.c:1539
#define TransactionIdIsValid(xid)
Definition: transam.h:41
int wal_segment_size
Definition: xlog.c:143
#define XLogSegNoOffsetToRecPtr(segno, offset, wal_segsz_bytes, dest)
uint64 XLogRecPtr
Definition: xlogdefs.h:21

References Assert, i, ReplicationSlot::in_use, InvalidatePossiblyObsoleteSlot(), LW_SHARED, LWLockAcquire(), LWLockRelease(), max_replication_slots, ReplicationSlotCtlData::replication_slots, ReplicationSlotCtl, ReplicationSlotsComputeRequiredLSN(), ReplicationSlotsComputeRequiredXmin(), RS_INVAL_HORIZON, RS_INVAL_NONE, RS_INVAL_WAL_REMOVED, TransactionIdIsValid, wal_segment_size, and XLogSegNoOffsetToRecPtr.

Referenced by CreateCheckPoint(), CreateRestartPoint(), ResolveRecoveryConflictWithSnapshot(), and xlog_redo().

◆ ReplicationSlotAcquire()

void ReplicationSlotAcquire ( const char *  name,
bool  nowait 
)

Definition at line 540 of file slot.c.

541 {
542  ReplicationSlot *s;
543  int active_pid;
544 
545  Assert(name != NULL);
546 
547 retry:
548  Assert(MyReplicationSlot == NULL);
549 
550  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
551 
552  /* Check if the slot exits with the given name. */
553  s = SearchNamedReplicationSlot(name, false);
554  if (s == NULL || !s->in_use)
555  {
556  LWLockRelease(ReplicationSlotControlLock);
557 
558  ereport(ERROR,
559  (errcode(ERRCODE_UNDEFINED_OBJECT),
560  errmsg("replication slot \"%s\" does not exist",
561  name)));
562  }
563 
564  /*
565  * This is the slot we want; check if it's active under some other
566  * process. In single user mode, we don't need this check.
567  */
568  if (IsUnderPostmaster)
569  {
570  /*
571  * Get ready to sleep on the slot in case it is active. (We may end
572  * up not sleeping, but we don't want to do this while holding the
573  * spinlock.)
574  */
575  if (!nowait)
577 
578  SpinLockAcquire(&s->mutex);
579  if (s->active_pid == 0)
580  s->active_pid = MyProcPid;
581  active_pid = s->active_pid;
582  SpinLockRelease(&s->mutex);
583  }
584  else
585  active_pid = MyProcPid;
586  LWLockRelease(ReplicationSlotControlLock);
587 
588  /*
589  * If we found the slot but it's already active in another process, we
590  * wait until the owning process signals us that it's been released, or
591  * error out.
592  */
593  if (active_pid != MyProcPid)
594  {
595  if (!nowait)
596  {
597  /* Wait here until we get signaled, and then restart */
599  WAIT_EVENT_REPLICATION_SLOT_DROP);
601  goto retry;
602  }
603 
604  ereport(ERROR,
605  (errcode(ERRCODE_OBJECT_IN_USE),
606  errmsg("replication slot \"%s\" is active for PID %d",
607  NameStr(s->data.name), active_pid)));
608  }
609  else if (!nowait)
610  ConditionVariableCancelSleep(); /* no sleep needed after all */
611 
612  /* Let everybody know we've modified this slot */
614 
615  /* We made this slot active, so it's ours now. */
616  MyReplicationSlot = s;
617 
618  /*
619  * The call to pgstat_acquire_replslot() protects against stats for a
620  * different slot, from before a restart or such, being present during
621  * pgstat_report_replslot().
622  */
623  if (SlotIsLogical(s))
625 
626  /*
627  * Reset the time since the slot has become inactive as the slot is active
628  * now.
629  */
630  SpinLockAcquire(&s->mutex);
631  s->inactive_since = 0;
632  SpinLockRelease(&s->mutex);
633 
634  if (am_walsender)
635  {
637  SlotIsLogical(s)
638  ? errmsg("acquired logical replication slot \"%s\"",
639  NameStr(s->data.name))
640  : errmsg("acquired physical replication slot \"%s\"",
641  NameStr(s->data.name)));
642  }
643 }
bool ConditionVariableCancelSleep(void)
void ConditionVariableBroadcast(ConditionVariable *cv)
void ConditionVariablePrepareToSleep(ConditionVariable *cv)
void ConditionVariableSleep(ConditionVariable *cv, uint32 wait_event_info)
int MyProcPid
Definition: globals.c:45
bool IsUnderPostmaster
Definition: globals.c:117
void pgstat_acquire_replslot(ReplicationSlot *slot)
ReplicationSlot * SearchNamedReplicationSlot(const char *name, bool need_lock)
Definition: slot.c:464
ReplicationSlot * MyReplicationSlot
Definition: slot.c:138
pid_t active_pid
Definition: slot.h:157
ConditionVariable active_cv
Definition: slot.h:184
TimestampTz inactive_since
Definition: slot.h:206
const char * name
bool am_walsender
Definition: walsender.c:115
bool log_replication_commands
Definition: walsender.c:125

References ReplicationSlot::active_cv, ReplicationSlot::active_pid, am_walsender, Assert, ConditionVariableBroadcast(), ConditionVariableCancelSleep(), ConditionVariablePrepareToSleep(), ConditionVariableSleep(), ReplicationSlot::data, DEBUG1, ereport, errcode(), errmsg(), ERROR, ReplicationSlot::in_use, ReplicationSlot::inactive_since, IsUnderPostmaster, LOG, log_replication_commands, LW_SHARED, LWLockAcquire(), LWLockRelease(), ReplicationSlot::mutex, MyProcPid, MyReplicationSlot, name, ReplicationSlotPersistentData::name, NameStr, pgstat_acquire_replslot(), SearchNamedReplicationSlot(), SlotIsLogical, SpinLockAcquire, and SpinLockRelease.

Referenced by binary_upgrade_logical_slot_has_caught_up(), drop_local_obsolete_slots(), pg_logical_slot_get_changes_guts(), pg_replication_slot_advance(), ReplicationSlotAlter(), ReplicationSlotDrop(), StartLogicalReplication(), StartReplication(), and synchronize_one_slot().

◆ ReplicationSlotAlter()

void ReplicationSlotAlter ( const char *  name,
bool  failover 
)

Definition at line 803 of file slot.c.

804 {
805  Assert(MyReplicationSlot == NULL);
806 
808 
810  ereport(ERROR,
811  errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
812  errmsg("cannot use %s with a physical replication slot",
813  "ALTER_REPLICATION_SLOT"));
814 
815  if (RecoveryInProgress())
816  {
817  /*
818  * Do not allow users to alter the slots which are currently being
819  * synced from the primary to the standby.
820  */
822  ereport(ERROR,
823  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
824  errmsg("cannot alter replication slot \"%s\"", name),
825  errdetail("This slot is being synced from the primary server."));
826 
827  /*
828  * Do not allow users to enable failover on the standby as we do not
829  * support sync to the cascading standby.
830  */
831  if (failover)
832  ereport(ERROR,
833  errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
834  errmsg("cannot enable failover for a replication slot"
835  " on the standby"));
836  }
837 
838  /*
839  * Do not allow users to enable failover for temporary slots as we do not
840  * support syncing temporary slots to the standby.
841  */
842  if (failover && MyReplicationSlot->data.persistency == RS_TEMPORARY)
843  ereport(ERROR,
844  errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
845  errmsg("cannot enable failover for a temporary replication slot"));
846 
847  if (MyReplicationSlot->data.failover != failover)
848  {
850  MyReplicationSlot->data.failover = failover;
852 
855  }
856 
858 }
void ReplicationSlotMarkDirty(void)
Definition: slot.c:1006
void ReplicationSlotAcquire(const char *name, bool nowait)
Definition: slot.c:540
void ReplicationSlotSave(void)
Definition: slot.c:988
void ReplicationSlotRelease(void)
Definition: slot.c:652
#define SlotIsPhysical(slot)
Definition: slot.h:209
ReplicationSlotPersistency persistency
Definition: slot.h:74
bool RecoveryInProgress(void)
Definition: xlog.c:6290

References Assert, ReplicationSlot::data, ereport, errcode(), errdetail(), errmsg(), ERROR, ReplicationSlotPersistentData::failover, ReplicationSlot::mutex, MyReplicationSlot, name, ReplicationSlotPersistentData::persistency, RecoveryInProgress(), ReplicationSlotAcquire(), ReplicationSlotMarkDirty(), ReplicationSlotRelease(), ReplicationSlotSave(), RS_TEMPORARY, SlotIsPhysical, SpinLockAcquire, SpinLockRelease, and ReplicationSlotPersistentData::synced.

Referenced by AlterReplicationSlot().

◆ ReplicationSlotCleanup()

void ReplicationSlotCleanup ( void  )

Definition at line 742 of file slot.c.

743 {
744  int i;
745 
746  Assert(MyReplicationSlot == NULL);
747 
748 restart:
749  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
750  for (i = 0; i < max_replication_slots; i++)
751  {
753 
754  if (!s->in_use)
755  continue;
756 
757  SpinLockAcquire(&s->mutex);
758  if (s->active_pid == MyProcPid)
759  {
761  SpinLockRelease(&s->mutex);
762  LWLockRelease(ReplicationSlotControlLock); /* avoid deadlock */
763 
765 
767  goto restart;
768  }
769  else
770  SpinLockRelease(&s->mutex);
771  }
772 
773  LWLockRelease(ReplicationSlotControlLock);
774 }
static void ReplicationSlotDropPtr(ReplicationSlot *slot)
Definition: slot.c:881

References ReplicationSlot::active_cv, ReplicationSlot::active_pid, Assert, ConditionVariableBroadcast(), ReplicationSlot::data, i, ReplicationSlot::in_use, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_replication_slots, ReplicationSlot::mutex, MyProcPid, MyReplicationSlot, ReplicationSlotPersistentData::persistency, ReplicationSlotCtlData::replication_slots, ReplicationSlotCtl, ReplicationSlotDropPtr(), RS_TEMPORARY, SpinLockAcquire, and SpinLockRelease.

Referenced by PostgresMain(), ReplicationSlotShmemExit(), and WalSndErrorCleanup().

◆ ReplicationSlotCreate()

void ReplicationSlotCreate ( const char *  name,
bool  db_specific,
ReplicationSlotPersistency  persistency,
bool  two_phase,
bool  failover,
bool  synced 
)

Definition at line 309 of file slot.c.

312 {
313  ReplicationSlot *slot = NULL;
314  int i;
315 
316  Assert(MyReplicationSlot == NULL);
317 
319 
320  if (failover)
321  {
322  /*
323  * Do not allow users to create the failover enabled slots on the
324  * standby as we do not support sync to the cascading standby.
325  *
326  * However, failover enabled slots can be created during slot
327  * synchronization because we need to retain the same values as the
328  * remote slot.
329  */
331  ereport(ERROR,
332  errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
333  errmsg("cannot enable failover for a replication slot created on the standby"));
334 
335  /*
336  * Do not allow users to create failover enabled temporary slots,
337  * because temporary slots will not be synced to the standby.
338  *
339  * However, failover enabled temporary slots can be created during
340  * slot synchronization. See the comments atop slotsync.c for details.
341  */
342  if (persistency == RS_TEMPORARY && !IsSyncingReplicationSlots())
343  ereport(ERROR,
344  errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
345  errmsg("cannot enable failover for a temporary replication slot"));
346  }
347 
348  /*
349  * If some other backend ran this code concurrently with us, we'd likely
350  * both allocate the same slot, and that would be bad. We'd also be at
351  * risk of missing a name collision. Also, we don't want to try to create
352  * a new slot while somebody's busy cleaning up an old one, because we
353  * might both be monkeying with the same directory.
354  */
355  LWLockAcquire(ReplicationSlotAllocationLock, LW_EXCLUSIVE);
356 
357  /*
358  * Check for name collision, and identify an allocatable slot. We need to
359  * hold ReplicationSlotControlLock in shared mode for this, so that nobody
360  * else can change the in_use flags while we're looking at them.
361  */
362  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
363  for (i = 0; i < max_replication_slots; i++)
364  {
366 
367  if (s->in_use && strcmp(name, NameStr(s->data.name)) == 0)
368  ereport(ERROR,
370  errmsg("replication slot \"%s\" already exists", name)));
371  if (!s->in_use && slot == NULL)
372  slot = s;
373  }
374  LWLockRelease(ReplicationSlotControlLock);
375 
376  /* If all slots are in use, we're out of luck. */
377  if (slot == NULL)
378  ereport(ERROR,
379  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
380  errmsg("all replication slots are in use"),
381  errhint("Free one or increase max_replication_slots.")));
382 
383  /*
384  * Since this slot is not in use, nobody should be looking at any part of
385  * it other than the in_use field unless they're trying to allocate it.
386  * And since we hold ReplicationSlotAllocationLock, nobody except us can
387  * be doing that. So it's safe to initialize the slot.
388  */
389  Assert(!slot->in_use);
390  Assert(slot->active_pid == 0);
391 
392  /* first initialize persistent data */
393  memset(&slot->data, 0, sizeof(ReplicationSlotPersistentData));
394  namestrcpy(&slot->data.name, name);
395  slot->data.database = db_specific ? MyDatabaseId : InvalidOid;
396  slot->data.persistency = persistency;
397  slot->data.two_phase = two_phase;
399  slot->data.failover = failover;
400  slot->data.synced = synced;
401 
402  /* and then data only present in shared memory */
403  slot->just_dirtied = false;
404  slot->dirty = false;
412  slot->inactive_since = 0;
413 
414  /*
415  * Create the slot on disk. We haven't actually marked the slot allocated
416  * yet, so no special cleanup is required if this errors out.
417  */
418  CreateSlotOnDisk(slot);
419 
420  /*
421  * We need to briefly prevent any other backend from iterating over the
422  * slots while we flip the in_use flag. We also need to set the active
423  * flag while holding the ControlLock as otherwise a concurrent
424  * ReplicationSlotAcquire() could acquire the slot as well.
425  */
426  LWLockAcquire(ReplicationSlotControlLock, LW_EXCLUSIVE);
427 
428  slot->in_use = true;
429 
430  /* We can now mark the slot active, and that makes it our slot. */
431  SpinLockAcquire(&slot->mutex);
432  Assert(slot->active_pid == 0);
433  slot->active_pid = MyProcPid;
434  SpinLockRelease(&slot->mutex);
435  MyReplicationSlot = slot;
436 
437  LWLockRelease(ReplicationSlotControlLock);
438 
439  /*
440  * Create statistics entry for the new logical slot. We don't collect any
441  * stats for physical slots, so no need to create an entry for the same.
442  * See ReplicationSlotDropPtr for why we need to do this before releasing
443  * ReplicationSlotAllocationLock.
444  */
445  if (SlotIsLogical(slot))
447 
448  /*
449  * Now that the slot has been marked as in_use and active, it's safe to
450  * let somebody else try to allocate a slot.
451  */
452  LWLockRelease(ReplicationSlotAllocationLock);
453 
454  /* Let everybody know we've modified this slot */
456 }
int errhint(const char *fmt,...)
Definition: elog.c:1319
Oid MyDatabaseId
Definition: globals.c:91
@ LW_EXCLUSIVE
Definition: lwlock.h:114
void namestrcpy(Name name, const char *str)
Definition: name.c:233
static bool two_phase
void pgstat_create_replslot(ReplicationSlot *slot)
#define InvalidOid
Definition: postgres_ext.h:36
static void CreateSlotOnDisk(ReplicationSlot *slot)
Definition: slot.c:1955
bool ReplicationSlotValidateName(const char *name, int elevel)
Definition: slot.c:252
bool IsSyncingReplicationSlots(void)
Definition: slotsync.c:1569
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
XLogRecPtr candidate_xmin_lsn
Definition: slot.h:194
TransactionId effective_catalog_xmin
Definition: slot.h:175
XLogRecPtr candidate_restart_valid
Definition: slot.h:195
TransactionId effective_xmin
Definition: slot.h:174
XLogRecPtr candidate_restart_lsn
Definition: slot.h:196
TransactionId candidate_catalog_xmin
Definition: slot.h:193
#define InvalidTransactionId
Definition: transam.h:31
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28

References ReplicationSlot::active_cv, ReplicationSlot::active_pid, Assert, ReplicationSlot::candidate_catalog_xmin, ReplicationSlot::candidate_restart_lsn, ReplicationSlot::candidate_restart_valid, ReplicationSlot::candidate_xmin_lsn, ConditionVariableBroadcast(), CreateSlotOnDisk(), ReplicationSlot::data, ReplicationSlotPersistentData::database, ReplicationSlot::dirty, ReplicationSlot::effective_catalog_xmin, ReplicationSlot::effective_xmin, ereport, errcode(), ERRCODE_DUPLICATE_OBJECT, errhint(), errmsg(), ERROR, ReplicationSlotPersistentData::failover, i, ReplicationSlot::in_use, ReplicationSlot::inactive_since, InvalidOid, InvalidTransactionId, InvalidXLogRecPtr, IsSyncingReplicationSlots(), ReplicationSlot::just_dirtied, ReplicationSlot::last_saved_confirmed_flush, LW_EXCLUSIVE, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_replication_slots, ReplicationSlot::mutex, MyDatabaseId, MyProcPid, MyReplicationSlot, name, ReplicationSlotPersistentData::name, NameStr, namestrcpy(), ReplicationSlotPersistentData::persistency, pgstat_create_replslot(), RecoveryInProgress(), ReplicationSlotCtlData::replication_slots, ReplicationSlotCtl, ReplicationSlotValidateName(), RS_TEMPORARY, SlotIsLogical, SpinLockAcquire, SpinLockRelease, ReplicationSlotPersistentData::synced, two_phase, ReplicationSlotPersistentData::two_phase, and ReplicationSlotPersistentData::two_phase_at.

Referenced by create_logical_replication_slot(), create_physical_replication_slot(), CreateReplicationSlot(), and synchronize_one_slot().

◆ ReplicationSlotDrop()

void ReplicationSlotDrop ( const char *  name,
bool  nowait 
)

Definition at line 780 of file slot.c.

781 {
782  Assert(MyReplicationSlot == NULL);
783 
784  ReplicationSlotAcquire(name, nowait);
785 
786  /*
787  * Do not allow users to drop the slots which are currently being synced
788  * from the primary to the standby.
789  */
791  ereport(ERROR,
792  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
793  errmsg("cannot drop replication slot \"%s\"", name),
794  errdetail("This slot is being synced from the primary server."));
795 
797 }
void ReplicationSlotDropAcquired(void)
Definition: slot.c:864

References Assert, ReplicationSlot::data, ereport, errcode(), errdetail(), errmsg(), ERROR, MyReplicationSlot, name, RecoveryInProgress(), ReplicationSlotAcquire(), ReplicationSlotDropAcquired(), and ReplicationSlotPersistentData::synced.

Referenced by DropReplicationSlot(), and pg_drop_replication_slot().

◆ ReplicationSlotDropAcquired()

void ReplicationSlotDropAcquired ( void  )

Definition at line 864 of file slot.c.

865 {
867 
868  Assert(MyReplicationSlot != NULL);
869 
870  /* slot isn't acquired anymore */
871  MyReplicationSlot = NULL;
872 
874 }

References Assert, MyReplicationSlot, and ReplicationSlotDropPtr().

Referenced by drop_local_obsolete_slots(), ReplicationSlotDrop(), ReplicationSlotRelease(), and ReplicationSlotsDropDBSlots().

◆ ReplicationSlotDropAtPubNode()

void ReplicationSlotDropAtPubNode ( WalReceiverConn wrconn,
char *  slotname,
bool  missing_ok 
)

Definition at line 1842 of file subscriptioncmds.c.

1843 {
1844  StringInfoData cmd;
1845 
1846  Assert(wrconn);
1847 
1848  load_file("libpqwalreceiver", false);
1849 
1850  initStringInfo(&cmd);
1851  appendStringInfo(&cmd, "DROP_REPLICATION_SLOT %s WAIT", quote_identifier(slotname));
1852 
1853  PG_TRY();
1854  {
1856 
1857  res = walrcv_exec(wrconn, cmd.data, 0, NULL);
1858 
1859  if (res->status == WALRCV_OK_COMMAND)
1860  {
1861  /* NOTICE. Success. */
1862  ereport(NOTICE,
1863  (errmsg("dropped replication slot \"%s\" on publisher",
1864  slotname)));
1865  }
1866  else if (res->status == WALRCV_ERROR &&
1867  missing_ok &&
1868  res->sqlstate == ERRCODE_UNDEFINED_OBJECT)
1869  {
1870  /* LOG. Error, but missing_ok = true. */
1871  ereport(LOG,
1872  (errmsg("could not drop replication slot \"%s\" on publisher: %s",
1873  slotname, res->err)));
1874  }
1875  else
1876  {
1877  /* ERROR. */
1878  ereport(ERROR,
1879  (errcode(ERRCODE_CONNECTION_FAILURE),
1880  errmsg("could not drop replication slot \"%s\" on publisher: %s",
1881  slotname, res->err)));
1882  }
1883 
1885  }
1886  PG_FINALLY();
1887  {
1888  pfree(cmd.data);
1889  }
1890  PG_END_TRY();
1891 }
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:144
#define PG_TRY(...)
Definition: elog.h:370
#define PG_END_TRY(...)
Definition: elog.h:395
#define NOTICE
Definition: elog.h:35
#define PG_FINALLY(...)
Definition: elog.h:387
void pfree(void *pointer)
Definition: mcxt.c:1520
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:12623
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:97
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
static WalReceiverConn * wrconn
Definition: walreceiver.c:92
@ WALRCV_OK_COMMAND
Definition: walreceiver.h:204
@ WALRCV_ERROR
Definition: walreceiver.h:203
static void walrcv_clear_result(WalRcvExecResult *walres)
Definition: walreceiver.h:468
#define walrcv_exec(conn, exec, nRetTypes, retTypes)
Definition: walreceiver.h:462

References appendStringInfo(), Assert, StringInfoData::data, ereport, errcode(), errmsg(), ERROR, initStringInfo(), load_file(), LOG, NOTICE, pfree(), PG_END_TRY, PG_FINALLY, PG_TRY, quote_identifier(), res, walrcv_clear_result(), WALRCV_ERROR, walrcv_exec, WALRCV_OK_COMMAND, and wrconn.

Referenced by AlterSubscription_refresh(), DropSubscription(), LogicalRepSyncTableStart(), and process_syncing_tables_for_sync().

◆ ReplicationSlotIndex()

int ReplicationSlotIndex ( ReplicationSlot slot)

◆ ReplicationSlotInitialize()

void ReplicationSlotInitialize ( void  )

Definition at line 224 of file slot.c.

225 {
227 }
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:337
static void ReplicationSlotShmemExit(int code, Datum arg)
Definition: slot.c:233

References before_shmem_exit(), and ReplicationSlotShmemExit().

Referenced by BaseInit().

◆ ReplicationSlotMarkDirty()

◆ ReplicationSlotName()

bool ReplicationSlotName ( int  index,
Name  name 
)

Definition at line 513 of file slot.c.

514 {
515  ReplicationSlot *slot;
516  bool found;
517 
519 
520  /*
521  * Ensure that the slot cannot be dropped while we copy the name. Don't
522  * need the spinlock as the name of an existing slot cannot change.
523  */
524  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
525  found = slot->in_use;
526  if (slot->in_use)
527  namestrcpy(name, NameStr(slot->data.name));
528  LWLockRelease(ReplicationSlotControlLock);
529 
530  return found;
531 }
Definition: type.h:95

References ReplicationSlot::data, ReplicationSlot::in_use, LW_SHARED, LWLockAcquire(), LWLockRelease(), name, ReplicationSlotPersistentData::name, NameStr, namestrcpy(), ReplicationSlotCtlData::replication_slots, and ReplicationSlotCtl.

Referenced by pgstat_replslot_to_serialized_name_cb().

◆ ReplicationSlotNameForTablesync()

void ReplicationSlotNameForTablesync ( Oid  suboid,
Oid  relid,
char *  syncslotname,
Size  szslot 
)

Definition at line 1260 of file tablesync.c.

1262 {
1263  snprintf(syncslotname, szslot, "pg_%u_sync_%u_" UINT64_FORMAT, suboid,
1264  relid, GetSystemIdentifier());
1265 }
#define UINT64_FORMAT
Definition: c.h:549
#define snprintf
Definition: port.h:238
uint64 GetSystemIdentifier(void)
Definition: xlog.c:4535

References GetSystemIdentifier(), snprintf, and UINT64_FORMAT.

Referenced by AlterSubscription_refresh(), DropSubscription(), LogicalRepSyncTableStart(), process_syncing_tables_for_sync(), and ReportSlotConnectionError().

◆ ReplicationSlotPersist()

◆ ReplicationSlotRelease()

void ReplicationSlotRelease ( void  )

Definition at line 652 of file slot.c.

653 {
655  char *slotname = NULL; /* keep compiler quiet */
656  bool is_logical = false; /* keep compiler quiet */
657  TimestampTz now = 0;
658 
659  Assert(slot != NULL && slot->active_pid != 0);
660 
661  if (am_walsender)
662  {
663  slotname = pstrdup(NameStr(slot->data.name));
664  is_logical = SlotIsLogical(slot);
665  }
666 
667  if (slot->data.persistency == RS_EPHEMERAL)
668  {
669  /*
670  * Delete the slot. There is no !PANIC case where this is allowed to
671  * fail, all that may happen is an incomplete cleanup of the on-disk
672  * data.
673  */
675  }
676 
677  /*
678  * If slot needed to temporarily restrain both data and catalog xmin to
679  * create the catalog snapshot, remove that temporary constraint.
680  * Snapshots can only be exported while the initial snapshot is still
681  * acquired.
682  */
683  if (!TransactionIdIsValid(slot->data.xmin) &&
685  {
686  SpinLockAcquire(&slot->mutex);
688  SpinLockRelease(&slot->mutex);
690  }
691 
692  /*
693  * Set the time since the slot has become inactive. We get the current
694  * time beforehand to avoid system call while holding the spinlock.
695  */
697 
698  if (slot->data.persistency == RS_PERSISTENT)
699  {
700  /*
701  * Mark persistent slot inactive. We're not freeing it, just
702  * disconnecting, but wake up others that may be waiting for it.
703  */
704  SpinLockAcquire(&slot->mutex);
705  slot->active_pid = 0;
706  slot->inactive_since = now;
707  SpinLockRelease(&slot->mutex);
709  }
710  else
711  {
712  SpinLockAcquire(&slot->mutex);
713  slot->inactive_since = now;
714  SpinLockRelease(&slot->mutex);
715  }
716 
717  MyReplicationSlot = NULL;
718 
719  /* might not have been set when we've been a plain slot */
720  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
723  LWLockRelease(ProcArrayLock);
724 
725  if (am_walsender)
726  {
728  is_logical
729  ? errmsg("released logical replication slot \"%s\"",
730  slotname)
731  : errmsg("released physical replication slot \"%s\"",
732  slotname));
733 
734  pfree(slotname);
735  }
736 }
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1654
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1618
int64 TimestampTz
Definition: timestamp.h:39
char * pstrdup(const char *in)
Definition: mcxt.c:1695
#define PROC_IN_LOGICAL_DECODING
Definition: proc.h:61
PGPROC * MyProc
Definition: proc.c:66
PROC_HDR * ProcGlobal
Definition: proc.c:78
uint8 statusFlags
Definition: proc.h:238
int pgxactoff
Definition: proc.h:180
uint8 * statusFlags
Definition: proc.h:395
TransactionId xmin
Definition: slot.h:82

References ReplicationSlot::active_cv, ReplicationSlot::active_pid, am_walsender, Assert, ConditionVariableBroadcast(), ReplicationSlot::data, DEBUG1, ReplicationSlot::effective_xmin, ereport, errmsg(), GetCurrentTimestamp(), ReplicationSlot::inactive_since, InvalidTransactionId, LOG, log_replication_commands, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), ReplicationSlot::mutex, MyProc, MyReplicationSlot, ReplicationSlotPersistentData::name, NameStr, now(), ReplicationSlotPersistentData::persistency, pfree(), PGPROC::pgxactoff, PROC_IN_LOGICAL_DECODING, ProcGlobal, pstrdup(), ReplicationSlotDropAcquired(), ReplicationSlotsComputeRequiredXmin(), RS_EPHEMERAL, RS_PERSISTENT, SlotIsLogical, SpinLockAcquire, SpinLockRelease, PGPROC::statusFlags, PROC_HDR::statusFlags, TransactionIdIsValid, and ReplicationSlotPersistentData::xmin.

Referenced by binary_upgrade_logical_slot_has_caught_up(), copy_replication_slot(), CreateReplicationSlot(), InvalidatePossiblyObsoleteSlot(), pg_create_logical_replication_slot(), pg_create_physical_replication_slot(), pg_logical_slot_get_changes_guts(), pg_replication_slot_advance(), PostgresMain(), ReplicationSlotAlter(), ReplicationSlotShmemExit(), StartLogicalReplication(), StartReplication(), synchronize_one_slot(), and WalSndErrorCleanup().

◆ ReplicationSlotReserveWal()

void ReplicationSlotReserveWal ( void  )

Definition at line 1397 of file slot.c.

1398 {
1400 
1401  Assert(slot != NULL);
1403 
1404  /*
1405  * The replication slot mechanism is used to prevent removal of required
1406  * WAL. As there is no interlock between this routine and checkpoints, WAL
1407  * segments could concurrently be removed when a now stale return value of
1408  * ReplicationSlotsComputeRequiredLSN() is used. In the unlikely case that
1409  * this happens we'll just retry.
1410  */
1411  while (true)
1412  {
1413  XLogSegNo segno;
1414  XLogRecPtr restart_lsn;
1415 
1416  /*
1417  * For logical slots log a standby snapshot and start logical decoding
1418  * at exactly that position. That allows the slot to start up more
1419  * quickly. But on a standby we cannot do WAL writes, so just use the
1420  * replay pointer; effectively, an attempt to create a logical slot on
1421  * standby will cause it to wait for an xl_running_xact record to be
1422  * logged independently on the primary, so that a snapshot can be
1423  * built using the record.
1424  *
1425  * None of this is needed (or indeed helpful) for physical slots as
1426  * they'll start replay at the last logged checkpoint anyway. Instead
1427  * return the location of the last redo LSN. While that slightly
1428  * increases the chance that we have to retry, it's where a base
1429  * backup has to start replay at.
1430  */
1431  if (SlotIsPhysical(slot))
1432  restart_lsn = GetRedoRecPtr();
1433  else if (RecoveryInProgress())
1434  restart_lsn = GetXLogReplayRecPtr(NULL);
1435  else
1436  restart_lsn = GetXLogInsertRecPtr();
1437 
1438  SpinLockAcquire(&slot->mutex);
1439  slot->data.restart_lsn = restart_lsn;
1440  SpinLockRelease(&slot->mutex);
1441 
1442  /* prevent WAL removal as fast as possible */
1444 
1445  /*
1446  * If all required WAL is still there, great, otherwise retry. The
1447  * slot should prevent further removal of WAL, unless there's a
1448  * concurrent ReplicationSlotsComputeRequiredLSN() after we've written
1449  * the new restart_lsn above, so normally we should never need to loop
1450  * more than twice.
1451  */
1453  if (XLogGetLastRemovedSegno() < segno)
1454  break;
1455  }
1456 
1457  if (!RecoveryInProgress() && SlotIsLogical(slot))
1458  {
1459  XLogRecPtr flushptr;
1460 
1461  /* make sure we have enough information to start */
1462  flushptr = LogStandbySnapshot();
1463 
1464  /* and make sure it's fsynced to disk */
1465  XLogFlush(flushptr);
1466  }
1467 }
XLogRecPtr LogStandbySnapshot(void)
Definition: standby.c:1285
XLogRecPtr restart_lsn
Definition: slot.h:93
XLogSegNo XLogGetLastRemovedSegno(void)
Definition: xlog.c:3747
XLogRecPtr GetRedoRecPtr(void)
Definition: xlog.c:6393
XLogRecPtr GetXLogInsertRecPtr(void)
Definition: xlog.c:9355
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2791
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)
uint64 XLogSegNo
Definition: xlogdefs.h:48
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)

References Assert, ReplicationSlot::data, GetRedoRecPtr(), GetXLogInsertRecPtr(), GetXLogReplayRecPtr(), InvalidXLogRecPtr, LogStandbySnapshot(), ReplicationSlot::mutex, MyReplicationSlot, RecoveryInProgress(), ReplicationSlotsComputeRequiredLSN(), ReplicationSlotPersistentData::restart_lsn, SlotIsLogical, SlotIsPhysical, SpinLockAcquire, SpinLockRelease, wal_segment_size, XLByteToSeg, XLogFlush(), and XLogGetLastRemovedSegno().

Referenced by create_physical_replication_slot(), CreateInitDecodingContext(), and CreateReplicationSlot().

◆ ReplicationSlotSave()

◆ ReplicationSlotsComputeLogicalRestartLSN()

XLogRecPtr ReplicationSlotsComputeLogicalRestartLSN ( void  )

Definition at line 1150 of file slot.c.

1151 {
1152  XLogRecPtr result = InvalidXLogRecPtr;
1153  int i;
1154 
1155  if (max_replication_slots <= 0)
1156  return InvalidXLogRecPtr;
1157 
1158  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
1159 
1160  for (i = 0; i < max_replication_slots; i++)
1161  {
1162  ReplicationSlot *s;
1163  XLogRecPtr restart_lsn;
1164  bool invalidated;
1165 
1167 
1168  /* cannot change while ReplicationSlotCtlLock is held */
1169  if (!s->in_use)
1170  continue;
1171 
1172  /* we're only interested in logical slots */
1173  if (!SlotIsLogical(s))
1174  continue;
1175 
1176  /* read once, it's ok if it increases while we're checking */
1177  SpinLockAcquire(&s->mutex);
1178  restart_lsn = s->data.restart_lsn;
1179  invalidated = s->data.invalidated != RS_INVAL_NONE;
1180  SpinLockRelease(&s->mutex);
1181 
1182  /* invalidated slots need not apply */
1183  if (invalidated)
1184  continue;
1185 
1186  if (restart_lsn == InvalidXLogRecPtr)
1187  continue;
1188 
1189  if (result == InvalidXLogRecPtr ||
1190  restart_lsn < result)
1191  result = restart_lsn;
1192  }
1193 
1194  LWLockRelease(ReplicationSlotControlLock);
1195 
1196  return result;
1197 }

References ReplicationSlot::data, i, ReplicationSlot::in_use, ReplicationSlotPersistentData::invalidated, InvalidXLogRecPtr, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_replication_slots, ReplicationSlot::mutex, ReplicationSlotCtlData::replication_slots, ReplicationSlotCtl, ReplicationSlotPersistentData::restart_lsn, RS_INVAL_NONE, SlotIsLogical, SpinLockAcquire, and SpinLockRelease.

Referenced by CheckPointLogicalRewriteHeap(), and CheckPointSnapBuild().

◆ ReplicationSlotsComputeRequiredLSN()

void ReplicationSlotsComputeRequiredLSN ( void  )

Definition at line 1101 of file slot.c.

1102 {
1103  int i;
1104  XLogRecPtr min_required = InvalidXLogRecPtr;
1105 
1106  Assert(ReplicationSlotCtl != NULL);
1107 
1108  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
1109  for (i = 0; i < max_replication_slots; i++)
1110  {
1112  XLogRecPtr restart_lsn;
1113  bool invalidated;
1114 
1115  if (!s->in_use)
1116  continue;
1117 
1118  SpinLockAcquire(&s->mutex);
1119  restart_lsn = s->data.restart_lsn;
1120  invalidated = s->data.invalidated != RS_INVAL_NONE;
1121  SpinLockRelease(&s->mutex);
1122 
1123  /* invalidated slots need not apply */
1124  if (invalidated)
1125  continue;
1126 
1127  if (restart_lsn != InvalidXLogRecPtr &&
1128  (min_required == InvalidXLogRecPtr ||
1129  restart_lsn < min_required))
1130  min_required = restart_lsn;
1131  }
1132  LWLockRelease(ReplicationSlotControlLock);
1133 
1134  XLogSetReplicationSlotMinimumLSN(min_required);
1135 }
void XLogSetReplicationSlotMinimumLSN(XLogRecPtr lsn)
Definition: xlog.c:2677

References Assert, ReplicationSlot::data, i, ReplicationSlot::in_use, ReplicationSlotPersistentData::invalidated, InvalidXLogRecPtr, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_replication_slots, ReplicationSlot::mutex, ReplicationSlotCtlData::replication_slots, ReplicationSlotCtl, ReplicationSlotPersistentData::restart_lsn, RS_INVAL_NONE, SpinLockAcquire, SpinLockRelease, and XLogSetReplicationSlotMinimumLSN().

Referenced by copy_replication_slot(), InvalidateObsoleteReplicationSlots(), LogicalConfirmReceivedLocation(), pg_replication_slot_advance(), PhysicalConfirmReceivedLocation(), ReplicationSlotDropPtr(), ReplicationSlotReserveWal(), reserve_wal_for_local_slot(), StartupReplicationSlots(), and update_local_synced_slot().

◆ ReplicationSlotsComputeRequiredXmin()

void ReplicationSlotsComputeRequiredXmin ( bool  already_locked)

Definition at line 1045 of file slot.c.

1046 {
1047  int i;
1049  TransactionId agg_catalog_xmin = InvalidTransactionId;
1050 
1051  Assert(ReplicationSlotCtl != NULL);
1052 
1053  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
1054 
1055  for (i = 0; i < max_replication_slots; i++)
1056  {
1058  TransactionId effective_xmin;
1059  TransactionId effective_catalog_xmin;
1060  bool invalidated;
1061 
1062  if (!s->in_use)
1063  continue;
1064 
1065  SpinLockAcquire(&s->mutex);
1066  effective_xmin = s->effective_xmin;
1067  effective_catalog_xmin = s->effective_catalog_xmin;
1068  invalidated = s->data.invalidated != RS_INVAL_NONE;
1069  SpinLockRelease(&s->mutex);
1070 
1071  /* invalidated slots need not apply */
1072  if (invalidated)
1073  continue;
1074 
1075  /* check the data xmin */
1076  if (TransactionIdIsValid(effective_xmin) &&
1077  (!TransactionIdIsValid(agg_xmin) ||
1078  TransactionIdPrecedes(effective_xmin, agg_xmin)))
1079  agg_xmin = effective_xmin;
1080 
1081  /* check the catalog xmin */
1082  if (TransactionIdIsValid(effective_catalog_xmin) &&
1083  (!TransactionIdIsValid(agg_catalog_xmin) ||
1084  TransactionIdPrecedes(effective_catalog_xmin, agg_catalog_xmin)))
1085  agg_catalog_xmin = effective_catalog_xmin;
1086  }
1087 
1088  LWLockRelease(ReplicationSlotControlLock);
1089 
1090  ProcArraySetReplicationSlotXmin(agg_xmin, agg_catalog_xmin, already_locked);
1091 }
uint32 TransactionId
Definition: c.h:652
void ProcArraySetReplicationSlotXmin(TransactionId xmin, TransactionId catalog_xmin, bool already_locked)
Definition: procarray.c:3927
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:280

References Assert, ReplicationSlot::data, ReplicationSlot::effective_catalog_xmin, ReplicationSlot::effective_xmin, i, ReplicationSlot::in_use, ReplicationSlotPersistentData::invalidated, InvalidTransactionId, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_replication_slots, ReplicationSlot::mutex, ProcArraySetReplicationSlotXmin(), ReplicationSlotCtlData::replication_slots, ReplicationSlotCtl, RS_INVAL_NONE, SpinLockAcquire, SpinLockRelease, TransactionIdIsValid, and TransactionIdPrecedes().

Referenced by copy_replication_slot(), CreateInitDecodingContext(), InvalidateObsoleteReplicationSlots(), LogicalConfirmReceivedLocation(), pg_replication_slot_advance(), PhysicalReplicationSlotNewXmin(), ReplicationSlotDropPtr(), ReplicationSlotRelease(), StartupReplicationSlots(), synchronize_one_slot(), and update_local_synced_slot().

◆ ReplicationSlotsCountDBSlots()

bool ReplicationSlotsCountDBSlots ( Oid  dboid,
int *  nslots,
int *  nactive 
)

Definition at line 1208 of file slot.c.

1209 {
1210  int i;
1211 
1212  *nslots = *nactive = 0;
1213 
1214  if (max_replication_slots <= 0)
1215  return false;
1216 
1217  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
1218  for (i = 0; i < max_replication_slots; i++)
1219  {
1220  ReplicationSlot *s;
1221 
1223 
1224  /* cannot change while ReplicationSlotCtlLock is held */
1225  if (!s->in_use)
1226  continue;
1227 
1228  /* only logical slots are database specific, skip */
1229  if (!SlotIsLogical(s))
1230  continue;
1231 
1232  /* not our database, skip */
1233  if (s->data.database != dboid)
1234  continue;
1235 
1236  /* NB: intentionally counting invalidated slots */
1237 
1238  /* count slots with spinlock held */
1239  SpinLockAcquire(&s->mutex);
1240  (*nslots)++;
1241  if (s->active_pid != 0)
1242  (*nactive)++;
1243  SpinLockRelease(&s->mutex);
1244  }
1245  LWLockRelease(ReplicationSlotControlLock);
1246 
1247  if (*nslots > 0)
1248  return true;
1249  return false;
1250 }

References ReplicationSlot::active_pid, ReplicationSlot::data, ReplicationSlotPersistentData::database, i, ReplicationSlot::in_use, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_replication_slots, ReplicationSlot::mutex, ReplicationSlotCtlData::replication_slots, ReplicationSlotCtl, SlotIsLogical, SpinLockAcquire, and SpinLockRelease.

Referenced by dropdb().

◆ ReplicationSlotsDropDBSlots()

void ReplicationSlotsDropDBSlots ( Oid  dboid)

Definition at line 1266 of file slot.c.

1267 {
1268  int i;
1269 
1270  if (max_replication_slots <= 0)
1271  return;
1272 
1273 restart:
1274  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
1275  for (i = 0; i < max_replication_slots; i++)
1276  {
1277  ReplicationSlot *s;
1278  char *slotname;
1279  int active_pid;
1280 
1282 
1283  /* cannot change while ReplicationSlotCtlLock is held */
1284  if (!s->in_use)
1285  continue;
1286 
1287  /* only logical slots are database specific, skip */
1288  if (!SlotIsLogical(s))
1289  continue;
1290 
1291  /* not our database, skip */
1292  if (s->data.database != dboid)
1293  continue;
1294 
1295  /* NB: intentionally including invalidated slots */
1296 
1297  /* acquire slot, so ReplicationSlotDropAcquired can be reused */
1298  SpinLockAcquire(&s->mutex);
1299  /* can't change while ReplicationSlotControlLock is held */
1300  slotname = NameStr(s->data.name);
1301  active_pid = s->active_pid;
1302  if (active_pid == 0)
1303  {
1304  MyReplicationSlot = s;
1305  s->active_pid = MyProcPid;
1306  }
1307  SpinLockRelease(&s->mutex);
1308 
1309  /*
1310  * Even though we hold an exclusive lock on the database object a
1311  * logical slot for that DB can still be active, e.g. if it's
1312  * concurrently being dropped by a backend connected to another DB.
1313  *
1314  * That's fairly unlikely in practice, so we'll just bail out.
1315  *
1316  * The slot sync worker holds a shared lock on the database before
1317  * operating on synced logical slots to avoid conflict with the drop
1318  * happening here. The persistent synced slots are thus safe but there
1319  * is a possibility that the slot sync worker has created a temporary
1320  * slot (which stays active even on release) and we are trying to drop
1321  * that here. In practice, the chances of hitting this scenario are
1322  * less as during slot synchronization, the temporary slot is
1323  * immediately converted to persistent and thus is safe due to the
1324  * shared lock taken on the database. So, we'll just bail out in such
1325  * a case.
1326  *
1327  * XXX: We can consider shutting down the slot sync worker before
1328  * trying to drop synced temporary slots here.
1329  */
1330  if (active_pid)
1331  ereport(ERROR,
1332  (errcode(ERRCODE_OBJECT_IN_USE),
1333  errmsg("replication slot \"%s\" is active for PID %d",
1334  slotname, active_pid)));
1335 
1336  /*
1337  * To avoid duplicating ReplicationSlotDropAcquired() and to avoid
1338  * holding ReplicationSlotControlLock over filesystem operations,
1339  * release ReplicationSlotControlLock and use
1340  * ReplicationSlotDropAcquired.
1341  *
1342  * As that means the set of slots could change, restart scan from the
1343  * beginning each time we release the lock.
1344  */
1345  LWLockRelease(ReplicationSlotControlLock);
1347  goto restart;
1348  }
1349  LWLockRelease(ReplicationSlotControlLock);
1350 }

References ReplicationSlot::active_pid, ReplicationSlot::data, ReplicationSlotPersistentData::database, ereport, errcode(), errmsg(), ERROR, i, ReplicationSlot::in_use, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_replication_slots, ReplicationSlot::mutex, MyProcPid, MyReplicationSlot, ReplicationSlotPersistentData::name, NameStr, ReplicationSlotCtlData::replication_slots, ReplicationSlotCtl, ReplicationSlotDropAcquired(), SlotIsLogical, SpinLockAcquire, and SpinLockRelease.

Referenced by dbase_redo(), and dropdb().

◆ ReplicationSlotsShmemInit()

void ReplicationSlotsShmemInit ( void  )

Definition at line 189 of file slot.c.

190 {
191  bool found;
192 
193  if (max_replication_slots == 0)
194  return;
195 
197  ShmemInitStruct("ReplicationSlot Ctl", ReplicationSlotsShmemSize(),
198  &found);
199 
200  if (!found)
201  {
202  int i;
203 
204  /* First time through, so initialize */
206 
207  for (i = 0; i < max_replication_slots; i++)
208  {
210 
211  /* everything else is zeroed by the memset above */
212  SpinLockInit(&slot->mutex);
216  }
217  }
218 }
#define MemSet(start, val, len)
Definition: c.h:1020
void ConditionVariableInit(ConditionVariable *cv)
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition: lwlock.c:709
@ LWTRANCHE_REPLICATION_SLOT_IO
Definition: lwlock.h:189
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:387
Size ReplicationSlotsShmemSize(void)
Definition: slot.c:171
#define SpinLockInit(lock)
Definition: spin.h:60
LWLock io_in_progress_lock
Definition: slot.h:181

References ReplicationSlot::active_cv, ConditionVariableInit(), i, ReplicationSlot::io_in_progress_lock, LWLockInitialize(), LWTRANCHE_REPLICATION_SLOT_IO, max_replication_slots, MemSet, ReplicationSlot::mutex, ReplicationSlotCtlData::replication_slots, ReplicationSlotCtl, ReplicationSlotsShmemSize(), ShmemInitStruct(), and SpinLockInit.

Referenced by CreateOrAttachShmemStructs().

◆ ReplicationSlotsShmemSize()

Size ReplicationSlotsShmemSize ( void  )

Definition at line 171 of file slot.c.

172 {
173  Size size = 0;
174 
175  if (max_replication_slots == 0)
176  return size;
177 
178  size = offsetof(ReplicationSlotCtlData, replication_slots);
179  size = add_size(size,
181 
182  return size;
183 }
size_t Size
Definition: c.h:605
Size add_size(Size s1, Size s2)
Definition: shmem.c:493
Size mul_size(Size s1, Size s2)
Definition: shmem.c:510
static pg_noinline void Size size
Definition: slab.c:607

References add_size(), max_replication_slots, mul_size(), and size.

Referenced by CalculateShmemSize(), and ReplicationSlotsShmemInit().

◆ ReplicationSlotValidateName()

bool ReplicationSlotValidateName ( const char *  name,
int  elevel 
)

Definition at line 252 of file slot.c.

253 {
254  const char *cp;
255 
256  if (strlen(name) == 0)
257  {
258  ereport(elevel,
259  (errcode(ERRCODE_INVALID_NAME),
260  errmsg("replication slot name \"%s\" is too short",
261  name)));
262  return false;
263  }
264 
265  if (strlen(name) >= NAMEDATALEN)
266  {
267  ereport(elevel,
268  (errcode(ERRCODE_NAME_TOO_LONG),
269  errmsg("replication slot name \"%s\" is too long",
270  name)));
271  return false;
272  }
273 
274  for (cp = name; *cp; cp++)
275  {
276  if (!((*cp >= 'a' && *cp <= 'z')
277  || (*cp >= '0' && *cp <= '9')
278  || (*cp == '_')))
279  {
280  ereport(elevel,
281  (errcode(ERRCODE_INVALID_NAME),
282  errmsg("replication slot name \"%s\" contains invalid character",
283  name),
284  errhint("Replication slot names may only contain lower case letters, numbers, and the underscore character.")));
285  return false;
286  }
287  }
288  return true;
289 }
#define NAMEDATALEN

References ereport, errcode(), errhint(), errmsg(), name, and NAMEDATALEN.

Referenced by check_primary_slot_name(), parse_subscription_options(), ReplicationSlotCreate(), and StartupReorderBuffer().

◆ SearchNamedReplicationSlot()

ReplicationSlot* SearchNamedReplicationSlot ( const char *  name,
bool  need_lock 
)

Definition at line 464 of file slot.c.

465 {
466  int i;
467  ReplicationSlot *slot = NULL;
468 
469  if (need_lock)
470  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
471 
472  for (i = 0; i < max_replication_slots; i++)
473  {
475 
476  if (s->in_use && strcmp(name, NameStr(s->data.name)) == 0)
477  {
478  slot = s;
479  break;
480  }
481  }
482 
483  if (need_lock)
484  LWLockRelease(ReplicationSlotControlLock);
485 
486  return slot;
487 }

References ReplicationSlot::data, i, ReplicationSlot::in_use, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_replication_slots, name, ReplicationSlotPersistentData::name, NameStr, ReplicationSlotCtlData::replication_slots, and ReplicationSlotCtl.

Referenced by get_replslot_index(), pg_ls_replslotdir(), pgstat_reset_replslot(), ReadReplicationSlot(), ReplicationSlotAcquire(), StandbySlotsHaveCaughtup(), synchronize_one_slot(), and validate_standby_slots().

◆ SlotExistsInStandbySlotNames()

bool SlotExistsInStandbySlotNames ( const char *  slot_name)

Definition at line 2545 of file slot.c.

2546 {
2547  const char *standby_slot_name;
2548 
2549  /* Return false if there is no value in standby_slot_names */
2550  if (standby_slot_names_config == NULL)
2551  return false;
2552 
2553  /*
2554  * XXX: We are not expecting this list to be long so a linear search
2555  * shouldn't hurt but if that turns out not to be true then we can cache
2556  * this information for each WalSender as well.
2557  */
2558  standby_slot_name = standby_slot_names_config->slot_names;
2559  for (int i = 0; i < standby_slot_names_config->nslotnames; i++)
2560  {
2561  if (strcmp(standby_slot_name, slot_name) == 0)
2562  return true;
2563 
2564  standby_slot_name += strlen(standby_slot_name) + 1;
2565  }
2566 
2567  return false;
2568 }
static StandbySlotNamesConfigData * standby_slot_names_config
Definition: slot.c:151
char slot_names[FLEXIBLE_ARRAY_MEMBER]
Definition: slot.c:99

References i, StandbySlotNamesConfigData::nslotnames, StandbySlotNamesConfigData::slot_names, and standby_slot_names_config.

Referenced by PhysicalWakeupLogicalWalSnd().

◆ StandbySlotsHaveCaughtup()

bool StandbySlotsHaveCaughtup ( XLogRecPtr  wait_for_lsn,
int  elevel 
)

Definition at line 2578 of file slot.c.

2579 {
2580  const char *name;
2581  int caught_up_slot_num = 0;
2582  XLogRecPtr min_restart_lsn = InvalidXLogRecPtr;
2583 
2584  /*
2585  * Don't need to wait for the standbys to catch up if there is no value in
2586  * standby_slot_names.
2587  */
2588  if (standby_slot_names_config == NULL)
2589  return true;
2590 
2591  /*
2592  * Don't need to wait for the standbys to catch up if we are on a standby
2593  * server, since we do not support syncing slots to cascading standbys.
2594  */
2595  if (RecoveryInProgress())
2596  return true;
2597 
2598  /*
2599  * Don't need to wait for the standbys to catch up if they are already
2600  * beyond the specified WAL location.
2601  */
2603  ss_oldest_flush_lsn >= wait_for_lsn)
2604  return true;
2605 
2606  /*
2607  * To prevent concurrent slot dropping and creation while filtering the
2608  * slots, take the ReplicationSlotControlLock outside of the loop.
2609  */
2610  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
2611 
2613  for (int i = 0; i < standby_slot_names_config->nslotnames; i++)
2614  {
2615  XLogRecPtr restart_lsn;
2616  bool invalidated;
2617  bool inactive;
2618  ReplicationSlot *slot;
2619 
2620  slot = SearchNamedReplicationSlot(name, false);
2621 
2622  if (!slot)
2623  {
2624  /*
2625  * If a slot name provided in standby_slot_names does not exist,
2626  * report a message and exit the loop. A user can specify a slot
2627  * name that does not exist just before the server startup. The
2628  * GUC check_hook(validate_standby_slots) cannot validate such a
2629  * slot during startup as the ReplicationSlotCtl shared memory is
2630  * not initialized at that time. It is also possible for a user to
2631  * drop the slot in standby_slot_names afterwards.
2632  */
2633  ereport(elevel,
2634  errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2635  errmsg("replication slot \"%s\" specified in parameter %s does not exist",
2636  name, "standby_slot_names"),
2637  errdetail("Logical replication is waiting on the standby associated with \"%s\".",
2638  name),
2639  errhint("Consider creating the slot \"%s\" or amend parameter %s.",
2640  name, "standby_slot_names"));
2641  break;
2642  }
2643 
2644  if (SlotIsLogical(slot))
2645  {
2646  /*
2647  * If a logical slot name is provided in standby_slot_names,
2648  * report a message and exit the loop. Similar to the non-existent
2649  * case, a user can specify a logical slot name in
2650  * standby_slot_names before the server startup, or drop an
2651  * existing physical slot and recreate a logical slot with the
2652  * same name.
2653  */
2654  ereport(elevel,
2655  errcode(ERRCODE_INVALID_PARAMETER_VALUE),
2656  errmsg("cannot have logical replication slot \"%s\" in parameter %s",
2657  name, "standby_slot_names"),
2658  errdetail("Logical replication is waiting for correction on \"%s\".",
2659  name),
2660  errhint("Consider removing logical slot \"%s\" from parameter %s.",
2661  name, "standby_slot_names"));
2662  break;
2663  }
2664 
2665  SpinLockAcquire(&slot->mutex);
2666  restart_lsn = slot->data.restart_lsn;
2667  invalidated = slot->data.invalidated != RS_INVAL_NONE;
2668  inactive = slot->active_pid == 0;
2669  SpinLockRelease(&slot->mutex);
2670 
2671  if (invalidated)
2672  {
2673  /* Specified physical slot has been invalidated */
2674  ereport(elevel,
2675  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2676  errmsg("physical slot \"%s\" specified in parameter %s has been invalidated",
2677  name, "standby_slot_names"),
2678  errdetail("Logical replication is waiting on the standby associated with \"%s\".",
2679  name),
2680  errhint("Consider dropping and recreating the slot \"%s\" or amend parameter %s.",
2681  name, "standby_slot_names"));
2682  break;
2683  }
2684 
2685  if (XLogRecPtrIsInvalid(restart_lsn) || restart_lsn < wait_for_lsn)
2686  {
2687  /* Log a message if no active_pid for this physical slot */
2688  if (inactive)
2689  ereport(elevel,
2690  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2691  errmsg("replication slot \"%s\" specified in parameter %s does not have active_pid",
2692  name, "standby_slot_names"),
2693  errdetail("Logical replication is waiting on the standby associated with \"%s\".",
2694  name),
2695  errhint("Consider starting standby associated with \"%s\" or amend parameter %s.",
2696  name, "standby_slot_names"));
2697 
2698  /* Continue if the current slot hasn't caught up. */
2699  break;
2700  }
2701 
2702  Assert(restart_lsn >= wait_for_lsn);
2703 
2704  if (XLogRecPtrIsInvalid(min_restart_lsn) ||
2705  min_restart_lsn > restart_lsn)
2706  min_restart_lsn = restart_lsn;
2707 
2708  caught_up_slot_num++;
2709 
2710  name += strlen(name) + 1;
2711  }
2712 
2713  LWLockRelease(ReplicationSlotControlLock);
2714 
2715  /*
2716  * Return false if not all the standbys have caught up to the specified
2717  * WAL location.
2718  */
2719  if (caught_up_slot_num != standby_slot_names_config->nslotnames)
2720  return false;
2721 
2722  /* The ss_oldest_flush_lsn must not retreat. */
2724  min_restart_lsn >= ss_oldest_flush_lsn);
2725 
2726  ss_oldest_flush_lsn = min_restart_lsn;
2727 
2728  return true;
2729 }
static XLogRecPtr ss_oldest_flush_lsn
Definition: slot.c:157
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29

References ReplicationSlot::active_pid, Assert, ReplicationSlot::data, ereport, errcode(), errdetail(), errhint(), errmsg(), i, ReplicationSlotPersistentData::invalidated, InvalidXLogRecPtr, LW_SHARED, LWLockAcquire(), LWLockRelease(), ReplicationSlot::mutex, name, StandbySlotNamesConfigData::nslotnames, RecoveryInProgress(), ReplicationSlotPersistentData::restart_lsn, RS_INVAL_NONE, SearchNamedReplicationSlot(), StandbySlotNamesConfigData::slot_names, SlotIsLogical, SpinLockAcquire, SpinLockRelease, ss_oldest_flush_lsn, standby_slot_names_config, and XLogRecPtrIsInvalid.

Referenced by NeedToWaitForStandbys(), and WaitForStandbyConfirmation().

◆ StartupReplicationSlots()

void StartupReplicationSlots ( void  )

Definition at line 1894 of file slot.c.

1895 {
1896  DIR *replication_dir;
1897  struct dirent *replication_de;
1898 
1899  elog(DEBUG1, "starting up replication slots");
1900 
1901  /* restore all slots by iterating over all on-disk entries */
1902  replication_dir = AllocateDir("pg_replslot");
1903  while ((replication_de = ReadDir(replication_dir, "pg_replslot")) != NULL)
1904  {
1905  char path[MAXPGPATH + 12];
1906  PGFileType de_type;
1907 
1908  if (strcmp(replication_de->d_name, ".") == 0 ||
1909  strcmp(replication_de->d_name, "..") == 0)
1910  continue;
1911 
1912  snprintf(path, sizeof(path), "pg_replslot/%s", replication_de->d_name);
1913  de_type = get_dirent_type(path, replication_de, false, DEBUG1);
1914 
1915  /* we're only creating directories here, skip if it's not our's */
1916  if (de_type != PGFILETYPE_ERROR && de_type != PGFILETYPE_DIR)
1917  continue;
1918 
1919  /* we crashed while a slot was being setup or deleted, clean up */
1920  if (pg_str_endswith(replication_de->d_name, ".tmp"))
1921  {
1922  if (!rmtree(path, true))
1923  {
1924  ereport(WARNING,
1925  (errmsg("could not remove directory \"%s\"",
1926  path)));
1927  continue;
1928  }
1929  fsync_fname("pg_replslot", true);
1930  continue;
1931  }
1932 
1933  /* looks like a slot in a normal state, restore */
1934  RestoreSlotFromDisk(replication_de->d_name);
1935  }
1936  FreeDir(replication_dir);
1937 
1938  /* currently no slots exist, we're done. */
1939  if (max_replication_slots <= 0)
1940  return;
1941 
1942  /* Now that we have recovered all the data, compute replication xmin */
1945 }
#define WARNING
Definition: elog.h:36
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2909
int FreeDir(DIR *dir)
Definition: fd.c:2961
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:756
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2843
PGFileType get_dirent_type(const char *path, const struct dirent *de, bool look_through_symlinks, int elevel)
Definition: file_utils.c:525
PGFileType
Definition: file_utils.h:19
@ PGFILETYPE_DIR
Definition: file_utils.h:23
@ PGFILETYPE_ERROR
Definition: file_utils.h:20
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:50
static void RestoreSlotFromDisk(const char *name)
Definition: slot.c:2171
bool pg_str_endswith(const char *str, const char *end)
Definition: string.c:32
Definition: dirent.c:26
Definition: dirent.h:10
char d_name[MAX_PATH]
Definition: dirent.h:15

References AllocateDir(), dirent::d_name, DEBUG1, elog, ereport, errmsg(), FreeDir(), fsync_fname(), get_dirent_type(), max_replication_slots, MAXPGPATH, pg_str_endswith(), PGFILETYPE_DIR, PGFILETYPE_ERROR, ReadDir(), ReplicationSlotsComputeRequiredLSN(), ReplicationSlotsComputeRequiredXmin(), RestoreSlotFromDisk(), rmtree(), snprintf, and WARNING.

Referenced by StartupXLOG().

◆ WaitForStandbyConfirmation()

void WaitForStandbyConfirmation ( XLogRecPtr  wait_for_lsn)

Definition at line 2738 of file slot.c.

2739 {
2740  /*
2741  * Don't need to wait for the standby to catch up if the current acquired
2742  * slot is not a logical failover slot, or there is no value in
2743  * standby_slot_names.
2744  */
2746  return;
2747 
2749 
2750  for (;;)
2751  {
2753 
2754  if (ConfigReloadPending)
2755  {
2756  ConfigReloadPending = false;
2758  }
2759 
2760  /* Exit if done waiting for every slot. */
2761  if (StandbySlotsHaveCaughtup(wait_for_lsn, WARNING))
2762  break;
2763 
2764  /*
2765  * Wait for the slots in the standby_slot_names to catch up, but use a
2766  * timeout (1s) so we can also check if the standby_slot_names has
2767  * been changed.
2768  */
2770  WAIT_EVENT_WAIT_FOR_STANDBY_CONFIRMATION);
2771  }
2772 
2774 }
bool ConditionVariableTimedSleep(ConditionVariable *cv, long timeout, uint32 wait_event_info)
@ PGC_SIGHUP
Definition: guc.h:71
void ProcessConfigFile(GucContext context)
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:27
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
bool StandbySlotsHaveCaughtup(XLogRecPtr wait_for_lsn, int elevel)
Definition: slot.c:2578
ConditionVariable wal_confirm_rcv_cv
WalSndCtlData * WalSndCtl
Definition: walsender.c:109

References CHECK_FOR_INTERRUPTS, ConditionVariableCancelSleep(), ConditionVariablePrepareToSleep(), ConditionVariableTimedSleep(), ConfigReloadPending, ReplicationSlot::data, ReplicationSlotPersistentData::failover, MyReplicationSlot, PGC_SIGHUP, ProcessConfigFile(), standby_slot_names_config, StandbySlotsHaveCaughtup(), WalSndCtlData::wal_confirm_rcv_cv, WalSndCtl, and WARNING.

Referenced by LogicalSlotAdvanceAndCheckSnapState(), and pg_logical_slot_get_changes_guts().

Variable Documentation

◆ max_replication_slots

◆ MyReplicationSlot

PGDLLIMPORT ReplicationSlot* MyReplicationSlot
extern

Definition at line 138 of file slot.c.

Referenced by binary_upgrade_logical_slot_has_caught_up(), copy_replication_slot(), create_logical_replication_slot(), create_physical_replication_slot(), CreateDecodingContext(), CreateInitDecodingContext(), CreateReplicationSlot(), InvalidatePossiblyObsoleteSlot(), LogicalConfirmReceivedLocation(), LogicalIncreaseRestartDecodingForSlot(), LogicalIncreaseXminForSlot(), LogicalReplicationSlotHasPendingWal(), LogicalSlotAdvanceAndCheckSnapState(), NeedToWaitForStandbys(), pg_create_logical_replication_slot(), pg_create_physical_replication_slot(), pg_logical_slot_get_changes_guts(), pg_physical_replication_slot_advance(), pg_replication_slot_advance(), PhysicalConfirmReceivedLocation(), PhysicalReplicationSlotNewXmin(), PhysicalWakeupLogicalWalSnd(), PostgresMain(), ProcessStandbyHSFeedbackMessage(), ProcessStandbyReplyMessage(), ReorderBufferAllocate(), ReorderBufferFree(), ReorderBufferRestoreChanges(), ReorderBufferRestoreCleanup(), ReorderBufferSerializedPath(), ReorderBufferSerializeTXN(), ReplicationSlotAcquire(), ReplicationSlotAlter(), ReplicationSlotCleanup(), ReplicationSlotCreate(), ReplicationSlotDrop(), ReplicationSlotDropAcquired(), ReplicationSlotMarkDirty(), ReplicationSlotPersist(), ReplicationSlotRelease(), ReplicationSlotReserveWal(), ReplicationSlotSave(), ReplicationSlotsDropDBSlots(), ReplicationSlotShmemExit(), reserve_wal_for_local_slot(), StartLogicalReplication(), StartReplication(), StartupDecodingContext(), synchronize_one_slot(), update_and_persist_local_synced_slot(), update_local_synced_slot(), WaitForStandbyConfirmation(), and WalSndErrorCleanup().

◆ ReplicationSlotCtl

◆ SlotInvalidationCauses

PGDLLIMPORT const char* const SlotInvalidationCauses[]
extern

Definition at line 105 of file slot.c.

Referenced by GetSlotInvalidationCause(), and pg_get_replication_slots().

◆ standby_slot_names

PGDLLIMPORT char* standby_slot_names
extern

Definition at line 148 of file slot.c.