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)
 
void ReplicationSlotPersist (void)
 
void ReplicationSlotDrop (const char *name, bool nowait)
 
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 (void)
 
void CheckSlotRequirements (void)
 
void CheckSlotPermissions (void)
 

Variables

PGDLLIMPORT ReplicationSlotCtlDataReplicationSlotCtl
 
PGDLLIMPORT ReplicationSlotMyReplicationSlot
 
PGDLLIMPORT int max_replication_slots
 

Macro Definition Documentation

◆ SlotIsLogical

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

Definition at line 184 of file slot.h.

◆ SlotIsPhysical

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

Definition at line 183 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 44 of file slot.h.

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

◆ 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 ( void  )

Definition at line 1572 of file slot.c.

1573 {
1574  int i;
1575 
1576  elog(DEBUG1, "performing replication slot checkpoint");
1577 
1578  /*
1579  * Prevent any slot from being created/dropped while we're active. As we
1580  * explicitly do *not* want to block iterating over replication_slots or
1581  * acquiring a slot we cannot take the control lock - but that's OK,
1582  * because holding ReplicationSlotAllocationLock is strictly stronger, and
1583  * enough to guarantee that nobody can change the in_use bits on us.
1584  */
1585  LWLockAcquire(ReplicationSlotAllocationLock, LW_SHARED);
1586 
1587  for (i = 0; i < max_replication_slots; i++)
1588  {
1590  char path[MAXPGPATH];
1591 
1592  if (!s->in_use)
1593  continue;
1594 
1595  /* save the slot to disk, locking is handled in SaveSlotToPath() */
1596  sprintf(path, "pg_replslot/%s", NameStr(s->data.name));
1597  SaveSlotToPath(s, path, LOG);
1598  }
1599  LWLockRelease(ReplicationSlotAllocationLock);
1600 }
#define NameStr(name)
Definition: c.h:730
#define LOG
Definition: elog.h:31
#define DEBUG1
Definition: elog.h:30
int i
Definition: isn.c:73
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1195
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
@ LW_SHARED
Definition: lwlock.h:117
#define MAXPGPATH
#define sprintf
Definition: port.h:240
static void SaveSlotToPath(ReplicationSlot *slot, const char *dir, int elevel)
Definition: slot.c:1729
int max_replication_slots
Definition: slot.c:102
ReplicationSlotCtlData * ReplicationSlotCtl
Definition: slot.c:96
ReplicationSlot replication_slots[1]
Definition: slot.h:195
bool in_use
Definition: slot.h:138
ReplicationSlotPersistentData data
Definition: slot.h:162

References ReplicationSlot::data, DEBUG1, elog(), i, ReplicationSlot::in_use, LOG, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_replication_slots, MAXPGPATH, ReplicationSlotPersistentData::name, NameStr, ReplicationSlotCtlData::replication_slots, ReplicationSlotCtl, SaveSlotToPath(), and sprintf.

Referenced by CheckPointGuts().

◆ CheckSlotPermissions()

void CheckSlotPermissions ( void  )

Definition at line 1157 of file slot.c.

1158 {
1159  if (!has_rolreplication(GetUserId()))
1160  ereport(ERROR,
1161  (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
1162  errmsg("permission denied to use replication slots"),
1163  errdetail("Only roles with the %s attribute may use replication slots.",
1164  "REPLICATION")));
1165 }
int errdetail(const char *fmt,...)
Definition: elog.c:1202
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 GetUserId(void)
Definition: miscinit.c:510
bool has_rolreplication(Oid roleid)
Definition: miscinit.c:707

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(), and pg_replication_slot_advance().

◆ CheckSlotRequirements()

void CheckSlotRequirements ( void  )

Definition at line 1135 of file slot.c.

1136 {
1137  /*
1138  * NB: Adding a new requirement likely means that RestoreSlotFromDisk()
1139  * needs the same check.
1140  */
1141 
1142  if (max_replication_slots == 0)
1143  ereport(ERROR,
1144  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1145  errmsg("replication slots can only be used if max_replication_slots > 0")));
1146 
1148  ereport(ERROR,
1149  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1150  errmsg("replication slots can only be used if wal_level >= replica")));
1151 }
int wal_level
Definition: xlog.c:134
@ WAL_LEVEL_REPLICA
Definition: xlog.h:70

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

◆ InvalidateObsoleteReplicationSlots()

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

Definition at line 1518 of file slot.c.

1521 {
1522  XLogRecPtr oldestLSN;
1523  bool invalidated = false;
1524 
1525  Assert(cause != RS_INVAL_HORIZON || TransactionIdIsValid(snapshotConflictHorizon));
1526  Assert(cause != RS_INVAL_WAL_REMOVED || oldestSegno > 0);
1527  Assert(cause != RS_INVAL_NONE);
1528 
1529  if (max_replication_slots == 0)
1530  return invalidated;
1531 
1532  XLogSegNoOffsetToRecPtr(oldestSegno, 0, wal_segment_size, oldestLSN);
1533 
1534 restart:
1535  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
1536  for (int i = 0; i < max_replication_slots; i++)
1537  {
1539 
1540  if (!s->in_use)
1541  continue;
1542 
1543  if (InvalidatePossiblyObsoleteSlot(cause, s, oldestLSN, dboid,
1544  snapshotConflictHorizon,
1545  &invalidated))
1546  {
1547  /* if the lock was released, start from scratch */
1548  goto restart;
1549  }
1550  }
1551  LWLockRelease(ReplicationSlotControlLock);
1552 
1553  /*
1554  * If any slots have been invalidated, recalculate the resource limits.
1555  */
1556  if (invalidated)
1557  {
1560  }
1561 
1562  return invalidated;
1563 }
Assert(fmt[strlen(fmt) - 1] !='\n')
void ReplicationSlotsComputeRequiredXmin(bool already_locked)
Definition: slot.c:836
void ReplicationSlotsComputeRequiredLSN(void)
Definition: slot.c:892
static bool InvalidatePossiblyObsoleteSlot(ReplicationSlotInvalidationCause cause, ReplicationSlot *s, XLogRecPtr oldestLSN, Oid dboid, TransactionId snapshotConflictHorizon, bool *invalidated)
Definition: slot.c:1309
#define TransactionIdIsValid(xid)
Definition: transam.h:41
int wal_segment_size
Definition: xlog.c:146
#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 451 of file slot.c.

452 {
453  ReplicationSlot *s;
454  int active_pid;
455 
456  Assert(name != NULL);
457 
458 retry:
459  Assert(MyReplicationSlot == NULL);
460 
461  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
462 
463  /*
464  * Search for the slot with the specified name if the slot to acquire is
465  * not given. If the slot is not found, we either return -1 or error out.
466  */
467  s = SearchNamedReplicationSlot(name, false);
468  if (s == NULL || !s->in_use)
469  {
470  LWLockRelease(ReplicationSlotControlLock);
471 
472  ereport(ERROR,
473  (errcode(ERRCODE_UNDEFINED_OBJECT),
474  errmsg("replication slot \"%s\" does not exist",
475  name)));
476  }
477 
478  /*
479  * This is the slot we want; check if it's active under some other
480  * process. In single user mode, we don't need this check.
481  */
482  if (IsUnderPostmaster)
483  {
484  /*
485  * Get ready to sleep on the slot in case it is active. (We may end
486  * up not sleeping, but we don't want to do this while holding the
487  * spinlock.)
488  */
489  if (!nowait)
491 
492  SpinLockAcquire(&s->mutex);
493  if (s->active_pid == 0)
494  s->active_pid = MyProcPid;
495  active_pid = s->active_pid;
496  SpinLockRelease(&s->mutex);
497  }
498  else
499  active_pid = MyProcPid;
500  LWLockRelease(ReplicationSlotControlLock);
501 
502  /*
503  * If we found the slot but it's already active in another process, we
504  * wait until the owning process signals us that it's been released, or
505  * error out.
506  */
507  if (active_pid != MyProcPid)
508  {
509  if (!nowait)
510  {
511  /* Wait here until we get signaled, and then restart */
515  goto retry;
516  }
517 
518  ereport(ERROR,
519  (errcode(ERRCODE_OBJECT_IN_USE),
520  errmsg("replication slot \"%s\" is active for PID %d",
521  NameStr(s->data.name), active_pid)));
522  }
523  else if (!nowait)
524  ConditionVariableCancelSleep(); /* no sleep needed after all */
525 
526  /* Let everybody know we've modified this slot */
528 
529  /* We made this slot active, so it's ours now. */
530  MyReplicationSlot = s;
531 
532  /*
533  * The call to pgstat_acquire_replslot() protects against stats for a
534  * different slot, from before a restart or such, being present during
535  * pgstat_report_replslot().
536  */
537  if (SlotIsLogical(s))
539 }
void ConditionVariableBroadcast(ConditionVariable *cv)
void ConditionVariablePrepareToSleep(ConditionVariable *cv)
void ConditionVariableSleep(ConditionVariable *cv, uint32 wait_event_info)
void ConditionVariableCancelSleep(void)
const char * name
Definition: encode.c:571
int MyProcPid
Definition: globals.c:44
bool IsUnderPostmaster
Definition: globals.c:113
void pgstat_acquire_replslot(ReplicationSlot *slot)
ReplicationSlot * SearchNamedReplicationSlot(const char *name, bool need_lock)
Definition: slot.c:375
ReplicationSlot * MyReplicationSlot
Definition: slot.c:99
#define SlotIsLogical(slot)
Definition: slot.h:184
#define SpinLockRelease(lock)
Definition: spin.h:64
#define SpinLockAcquire(lock)
Definition: spin.h:62
slock_t mutex
Definition: slot.h:135
pid_t active_pid
Definition: slot.h:141
ConditionVariable active_cv
Definition: slot.h:168
@ WAIT_EVENT_REPLICATION_SLOT_DROP
Definition: wait_event.h:128

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

Referenced by pg_logical_slot_get_changes_guts(), pg_replication_slot_advance(), ReplicationSlotDrop(), StartLogicalReplication(), and StartReplication().

◆ ReplicationSlotCleanup()

void ReplicationSlotCleanup ( void  )

Definition at line 604 of file slot.c.

605 {
606  int i;
607 
608  Assert(MyReplicationSlot == NULL);
609 
610 restart:
611  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
612  for (i = 0; i < max_replication_slots; i++)
613  {
615 
616  if (!s->in_use)
617  continue;
618 
619  SpinLockAcquire(&s->mutex);
620  if (s->active_pid == MyProcPid)
621  {
623  SpinLockRelease(&s->mutex);
624  LWLockRelease(ReplicationSlotControlLock); /* avoid deadlock */
625 
627 
629  goto restart;
630  }
631  else
632  SpinLockRelease(&s->mutex);
633  }
634 
635  LWLockRelease(ReplicationSlotControlLock);
636 }
static void ReplicationSlotDropPtr(ReplicationSlot *slot)
Definition: slot.c:672
ReplicationSlotPersistency persistency
Definition: slot.h:69

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 
)

Definition at line 253 of file slot.c.

255 {
256  ReplicationSlot *slot = NULL;
257  int i;
258 
259  Assert(MyReplicationSlot == NULL);
260 
262 
263  /*
264  * If some other backend ran this code concurrently with us, we'd likely
265  * both allocate the same slot, and that would be bad. We'd also be at
266  * risk of missing a name collision. Also, we don't want to try to create
267  * a new slot while somebody's busy cleaning up an old one, because we
268  * might both be monkeying with the same directory.
269  */
270  LWLockAcquire(ReplicationSlotAllocationLock, LW_EXCLUSIVE);
271 
272  /*
273  * Check for name collision, and identify an allocatable slot. We need to
274  * hold ReplicationSlotControlLock in shared mode for this, so that nobody
275  * else can change the in_use flags while we're looking at them.
276  */
277  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
278  for (i = 0; i < max_replication_slots; i++)
279  {
281 
282  if (s->in_use && strcmp(name, NameStr(s->data.name)) == 0)
283  ereport(ERROR,
285  errmsg("replication slot \"%s\" already exists", name)));
286  if (!s->in_use && slot == NULL)
287  slot = s;
288  }
289  LWLockRelease(ReplicationSlotControlLock);
290 
291  /* If all slots are in use, we're out of luck. */
292  if (slot == NULL)
293  ereport(ERROR,
294  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
295  errmsg("all replication slots are in use"),
296  errhint("Free one or increase max_replication_slots.")));
297 
298  /*
299  * Since this slot is not in use, nobody should be looking at any part of
300  * it other than the in_use field unless they're trying to allocate it.
301  * And since we hold ReplicationSlotAllocationLock, nobody except us can
302  * be doing that. So it's safe to initialize the slot.
303  */
304  Assert(!slot->in_use);
305  Assert(slot->active_pid == 0);
306 
307  /* first initialize persistent data */
308  memset(&slot->data, 0, sizeof(ReplicationSlotPersistentData));
309  namestrcpy(&slot->data.name, name);
310  slot->data.database = db_specific ? MyDatabaseId : InvalidOid;
311  slot->data.persistency = persistency;
312  slot->data.two_phase = two_phase;
314 
315  /* and then data only present in shared memory */
316  slot->just_dirtied = false;
317  slot->dirty = false;
324 
325  /*
326  * Create the slot on disk. We haven't actually marked the slot allocated
327  * yet, so no special cleanup is required if this errors out.
328  */
329  CreateSlotOnDisk(slot);
330 
331  /*
332  * We need to briefly prevent any other backend from iterating over the
333  * slots while we flip the in_use flag. We also need to set the active
334  * flag while holding the ControlLock as otherwise a concurrent
335  * ReplicationSlotAcquire() could acquire the slot as well.
336  */
337  LWLockAcquire(ReplicationSlotControlLock, LW_EXCLUSIVE);
338 
339  slot->in_use = true;
340 
341  /* We can now mark the slot active, and that makes it our slot. */
342  SpinLockAcquire(&slot->mutex);
343  Assert(slot->active_pid == 0);
344  slot->active_pid = MyProcPid;
345  SpinLockRelease(&slot->mutex);
346  MyReplicationSlot = slot;
347 
348  LWLockRelease(ReplicationSlotControlLock);
349 
350  /*
351  * Create statistics entry for the new logical slot. We don't collect any
352  * stats for physical slots, so no need to create an entry for the same.
353  * See ReplicationSlotDropPtr for why we need to do this before releasing
354  * ReplicationSlotAllocationLock.
355  */
356  if (SlotIsLogical(slot))
358 
359  /*
360  * Now that the slot has been marked as in_use and active, it's safe to
361  * let somebody else try to allocate a slot.
362  */
363  LWLockRelease(ReplicationSlotAllocationLock);
364 
365  /* Let everybody know we've modified this slot */
367 }
int errhint(const char *fmt,...)
Definition: elog.c:1316
Oid MyDatabaseId
Definition: globals.c:89
@ LW_EXCLUSIVE
Definition: lwlock.h:116
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:1668
bool ReplicationSlotValidateName(const char *name, int elevel)
Definition: slot.c:199
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
XLogRecPtr candidate_xmin_lsn
Definition: slot.h:178
TransactionId effective_catalog_xmin
Definition: slot.h:159
XLogRecPtr candidate_restart_valid
Definition: slot.h:179
TransactionId effective_xmin
Definition: slot.h:158
bool just_dirtied
Definition: slot.h:144
XLogRecPtr candidate_restart_lsn
Definition: slot.h:180
TransactionId candidate_catalog_xmin
Definition: slot.h:177
bool dirty
Definition: slot.h:145
#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, i, ReplicationSlot::in_use, InvalidOid, InvalidTransactionId, InvalidXLogRecPtr, ReplicationSlot::just_dirtied, LW_EXCLUSIVE, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_replication_slots, ReplicationSlot::mutex, MyDatabaseId, MyProcPid, MyReplicationSlot, name, ReplicationSlotPersistentData::name, NameStr, namestrcpy(), ReplicationSlotPersistentData::persistency, pgstat_create_replslot(), ReplicationSlotCtlData::replication_slots, ReplicationSlotCtl, ReplicationSlotValidateName(), SlotIsLogical, SpinLockAcquire, SpinLockRelease, two_phase, ReplicationSlotPersistentData::two_phase, and ReplicationSlotPersistentData::two_phase_at.

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

◆ ReplicationSlotDrop()

void ReplicationSlotDrop ( const char *  name,
bool  nowait 
)

Definition at line 642 of file slot.c.

643 {
644  Assert(MyReplicationSlot == NULL);
645 
646  ReplicationSlotAcquire(name, nowait);
647 
649 }
void ReplicationSlotAcquire(const char *name, bool nowait)
Definition: slot.c:451
static void ReplicationSlotDropAcquired(void)
Definition: slot.c:655

References Assert(), MyReplicationSlot, name, ReplicationSlotAcquire(), and ReplicationSlotDropAcquired().

Referenced by DropReplicationSlot(), and pg_drop_replication_slot().

◆ ReplicationSlotDropAtPubNode()

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

Definition at line 1754 of file subscriptioncmds.c.

1755 {
1756  StringInfoData cmd;
1757 
1758  Assert(wrconn);
1759 
1760  load_file("libpqwalreceiver", false);
1761 
1762  initStringInfo(&cmd);
1763  appendStringInfo(&cmd, "DROP_REPLICATION_SLOT %s WAIT", quote_identifier(slotname));
1764 
1765  PG_TRY();
1766  {
1768 
1769  res = walrcv_exec(wrconn, cmd.data, 0, NULL);
1770 
1771  if (res->status == WALRCV_OK_COMMAND)
1772  {
1773  /* NOTICE. Success. */
1774  ereport(NOTICE,
1775  (errmsg("dropped replication slot \"%s\" on publisher",
1776  slotname)));
1777  }
1778  else if (res->status == WALRCV_ERROR &&
1779  missing_ok &&
1780  res->sqlstate == ERRCODE_UNDEFINED_OBJECT)
1781  {
1782  /* LOG. Error, but missing_ok = true. */
1783  ereport(LOG,
1784  (errmsg("could not drop replication slot \"%s\" on publisher: %s",
1785  slotname, res->err)));
1786  }
1787  else
1788  {
1789  /* ERROR. */
1790  ereport(ERROR,
1791  (errcode(ERRCODE_CONNECTION_FAILURE),
1792  errmsg("could not drop replication slot \"%s\" on publisher: %s",
1793  slotname, res->err)));
1794  }
1795 
1797  }
1798  PG_FINALLY();
1799  {
1800  pfree(cmd.data);
1801  }
1802  PG_END_TRY();
1803 }
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:1456
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11930
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
static WalReceiverConn * wrconn
Definition: walreceiver.c:95
@ WALRCV_OK_COMMAND
Definition: walreceiver.h:205
@ WALRCV_ERROR
Definition: walreceiver.h:204
static void walrcv_clear_result(WalRcvExecResult *walres)
Definition: walreceiver.h:442
#define walrcv_exec(conn, exec, nRetTypes, retTypes)
Definition: walreceiver.h:436

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 171 of file slot.c.

172 {
174 }
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:333
static void ReplicationSlotShmemExit(int code, Datum arg)
Definition: slot.c:180

References before_shmem_exit(), and ReplicationSlotShmemExit().

Referenced by BaseInit().

◆ ReplicationSlotMarkDirty()

◆ ReplicationSlotName()

bool ReplicationSlotName ( int  index,
Name  name 
)

Definition at line 424 of file slot.c.

425 {
426  ReplicationSlot *slot;
427  bool found;
428 
430 
431  /*
432  * Ensure that the slot cannot be dropped while we copy the name. Don't
433  * need the spinlock as the name of an existing slot cannot change.
434  */
435  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
436  found = slot->in_use;
437  if (slot->in_use)
438  namestrcpy(name, NameStr(slot->data.name));
439  LWLockRelease(ReplicationSlotControlLock);
440 
441  return found;
442 }
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 1228 of file tablesync.c.

1230 {
1231  snprintf(syncslotname, szslot, "pg_%u_sync_%u_" UINT64_FORMAT, suboid,
1232  relid, GetSystemIdentifier());
1233 }
#define UINT64_FORMAT
Definition: c.h:533
#define snprintf
Definition: port.h:238
uint64 GetSystemIdentifier(void)
Definition: xlog.c:4180

References GetSystemIdentifier(), snprintf, and UINT64_FORMAT.

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

◆ ReplicationSlotPersist()

void ReplicationSlotPersist ( void  )

◆ ReplicationSlotRelease()

void ReplicationSlotRelease ( void  )

Definition at line 548 of file slot.c.

549 {
551 
552  Assert(slot != NULL && slot->active_pid != 0);
553 
554  if (slot->data.persistency == RS_EPHEMERAL)
555  {
556  /*
557  * Delete the slot. There is no !PANIC case where this is allowed to
558  * fail, all that may happen is an incomplete cleanup of the on-disk
559  * data.
560  */
562  }
563 
564  /*
565  * If slot needed to temporarily restrain both data and catalog xmin to
566  * create the catalog snapshot, remove that temporary constraint.
567  * Snapshots can only be exported while the initial snapshot is still
568  * acquired.
569  */
570  if (!TransactionIdIsValid(slot->data.xmin) &&
572  {
573  SpinLockAcquire(&slot->mutex);
575  SpinLockRelease(&slot->mutex);
577  }
578 
579  if (slot->data.persistency == RS_PERSISTENT)
580  {
581  /*
582  * Mark persistent slot inactive. We're not freeing it, just
583  * disconnecting, but wake up others that may be waiting for it.
584  */
585  SpinLockAcquire(&slot->mutex);
586  slot->active_pid = 0;
587  SpinLockRelease(&slot->mutex);
589  }
590 
591  MyReplicationSlot = NULL;
592 
593  /* might not have been set when we've been a plain slot */
594  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
597  LWLockRelease(ProcArrayLock);
598 }
#define PROC_IN_LOGICAL_DECODING
Definition: proc.h:60
PGPROC * MyProc
Definition: proc.c:66
PROC_HDR * ProcGlobal
Definition: proc.c:78
uint8 statusFlags
Definition: proc.h:233
int pgxactoff
Definition: proc.h:188
uint8 * statusFlags
Definition: proc.h:377
TransactionId xmin
Definition: slot.h:77

References ReplicationSlot::active_cv, ReplicationSlot::active_pid, Assert(), ConditionVariableBroadcast(), ReplicationSlot::data, ReplicationSlot::effective_xmin, InvalidTransactionId, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), ReplicationSlot::mutex, MyProc, MyReplicationSlot, ReplicationSlotPersistentData::persistency, PGPROC::pgxactoff, PROC_IN_LOGICAL_DECODING, ProcGlobal, ReplicationSlotDropAcquired(), ReplicationSlotsComputeRequiredXmin(), RS_EPHEMERAL, RS_PERSISTENT, SpinLockAcquire, SpinLockRelease, PGPROC::statusFlags, PROC_HDR::statusFlags, TransactionIdIsValid, and ReplicationSlotPersistentData::xmin.

Referenced by 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(), ReplicationSlotShmemExit(), StartLogicalReplication(), StartReplication(), and WalSndErrorCleanup().

◆ ReplicationSlotReserveWal()

void ReplicationSlotReserveWal ( void  )

Definition at line 1174 of file slot.c.

1175 {
1177 
1178  Assert(slot != NULL);
1180 
1181  /*
1182  * The replication slot mechanism is used to prevent removal of required
1183  * WAL. As there is no interlock between this routine and checkpoints, WAL
1184  * segments could concurrently be removed when a now stale return value of
1185  * ReplicationSlotsComputeRequiredLSN() is used. In the unlikely case that
1186  * this happens we'll just retry.
1187  */
1188  while (true)
1189  {
1190  XLogSegNo segno;
1191  XLogRecPtr restart_lsn;
1192 
1193  /*
1194  * For logical slots log a standby snapshot and start logical decoding
1195  * at exactly that position. That allows the slot to start up more
1196  * quickly. But on a standby we cannot do WAL writes, so just use the
1197  * replay pointer; effectively, an attempt to create a logical slot on
1198  * standby will cause it to wait for an xl_running_xact record to be
1199  * logged independently on the primary, so that a snapshot can be
1200  * built using the record.
1201  *
1202  * None of this is needed (or indeed helpful) for physical slots as
1203  * they'll start replay at the last logged checkpoint anyway. Instead
1204  * return the location of the last redo LSN. While that slightly
1205  * increases the chance that we have to retry, it's where a base
1206  * backup has to start replay at.
1207  */
1208  if (SlotIsPhysical(slot))
1209  restart_lsn = GetRedoRecPtr();
1210  else if (RecoveryInProgress())
1211  restart_lsn = GetXLogReplayRecPtr(NULL);
1212  else
1213  restart_lsn = GetXLogInsertRecPtr();
1214 
1215  SpinLockAcquire(&slot->mutex);
1216  slot->data.restart_lsn = restart_lsn;
1217  SpinLockRelease(&slot->mutex);
1218 
1219  /* prevent WAL removal as fast as possible */
1221 
1222  /*
1223  * If all required WAL is still there, great, otherwise retry. The
1224  * slot should prevent further removal of WAL, unless there's a
1225  * concurrent ReplicationSlotsComputeRequiredLSN() after we've written
1226  * the new restart_lsn above, so normally we should never need to loop
1227  * more than twice.
1228  */
1230  if (XLogGetLastRemovedSegno() < segno)
1231  break;
1232  }
1233 
1234  if (!RecoveryInProgress() && SlotIsLogical(slot))
1235  {
1236  XLogRecPtr flushptr;
1237 
1238  /* make sure we have enough information to start */
1239  flushptr = LogStandbySnapshot();
1240 
1241  /* and make sure it's fsynced to disk */
1242  XLogFlush(flushptr);
1243  }
1244 }
#define SlotIsPhysical(slot)
Definition: slot.h:183
XLogRecPtr LogStandbySnapshot(void)
Definition: standby.c:1278
XLogRecPtr restart_lsn
Definition: slot.h:88
bool RecoveryInProgress(void)
Definition: xlog.c:5921
XLogSegNo XLogGetLastRemovedSegno(void)
Definition: xlog.c:3469
XLogRecPtr GetRedoRecPtr(void)
Definition: xlog.c:6024
XLogRecPtr GetXLogInsertRecPtr(void)
Definition: xlog.c:8896
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2513
#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 941 of file slot.c.

942 {
943  XLogRecPtr result = InvalidXLogRecPtr;
944  int i;
945 
946  if (max_replication_slots <= 0)
947  return InvalidXLogRecPtr;
948 
949  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
950 
951  for (i = 0; i < max_replication_slots; i++)
952  {
953  ReplicationSlot *s;
954  XLogRecPtr restart_lsn;
955  bool invalidated;
956 
958 
959  /* cannot change while ReplicationSlotCtlLock is held */
960  if (!s->in_use)
961  continue;
962 
963  /* we're only interested in logical slots */
964  if (!SlotIsLogical(s))
965  continue;
966 
967  /* read once, it's ok if it increases while we're checking */
968  SpinLockAcquire(&s->mutex);
969  restart_lsn = s->data.restart_lsn;
970  invalidated = s->data.invalidated != RS_INVAL_NONE;
971  SpinLockRelease(&s->mutex);
972 
973  /* invalidated slots need not apply */
974  if (invalidated)
975  continue;
976 
977  if (restart_lsn == InvalidXLogRecPtr)
978  continue;
979 
980  if (result == InvalidXLogRecPtr ||
981  restart_lsn < result)
982  result = restart_lsn;
983  }
984 
985  LWLockRelease(ReplicationSlotControlLock);
986 
987  return result;
988 }
ReplicationSlotInvalidationCause invalidated
Definition: slot.h:91

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 892 of file slot.c.

893 {
894  int i;
895  XLogRecPtr min_required = InvalidXLogRecPtr;
896 
897  Assert(ReplicationSlotCtl != NULL);
898 
899  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
900  for (i = 0; i < max_replication_slots; i++)
901  {
903  XLogRecPtr restart_lsn;
904  bool invalidated;
905 
906  if (!s->in_use)
907  continue;
908 
909  SpinLockAcquire(&s->mutex);
910  restart_lsn = s->data.restart_lsn;
911  invalidated = s->data.invalidated != RS_INVAL_NONE;
912  SpinLockRelease(&s->mutex);
913 
914  /* invalidated slots need not apply */
915  if (invalidated)
916  continue;
917 
918  if (restart_lsn != InvalidXLogRecPtr &&
919  (min_required == InvalidXLogRecPtr ||
920  restart_lsn < min_required))
921  min_required = restart_lsn;
922  }
923  LWLockRelease(ReplicationSlotControlLock);
924 
925  XLogSetReplicationSlotMinimumLSN(min_required);
926 }
void XLogSetReplicationSlotMinimumLSN(XLogRecPtr lsn)
Definition: xlog.c:2399

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(), and StartupReplicationSlots().

◆ ReplicationSlotsComputeRequiredXmin()

void ReplicationSlotsComputeRequiredXmin ( bool  already_locked)

Definition at line 836 of file slot.c.

837 {
838  int i;
840  TransactionId agg_catalog_xmin = InvalidTransactionId;
841 
842  Assert(ReplicationSlotCtl != NULL);
843 
844  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
845 
846  for (i = 0; i < max_replication_slots; i++)
847  {
849  TransactionId effective_xmin;
850  TransactionId effective_catalog_xmin;
851  bool invalidated;
852 
853  if (!s->in_use)
854  continue;
855 
856  SpinLockAcquire(&s->mutex);
857  effective_xmin = s->effective_xmin;
858  effective_catalog_xmin = s->effective_catalog_xmin;
859  invalidated = s->data.invalidated != RS_INVAL_NONE;
860  SpinLockRelease(&s->mutex);
861 
862  /* invalidated slots need not apply */
863  if (invalidated)
864  continue;
865 
866  /* check the data xmin */
867  if (TransactionIdIsValid(effective_xmin) &&
868  (!TransactionIdIsValid(agg_xmin) ||
869  TransactionIdPrecedes(effective_xmin, agg_xmin)))
870  agg_xmin = effective_xmin;
871 
872  /* check the catalog xmin */
873  if (TransactionIdIsValid(effective_catalog_xmin) &&
874  (!TransactionIdIsValid(agg_catalog_xmin) ||
875  TransactionIdPrecedes(effective_catalog_xmin, agg_catalog_xmin)))
876  agg_catalog_xmin = effective_catalog_xmin;
877  }
878 
879  LWLockRelease(ReplicationSlotControlLock);
880 
881  ProcArraySetReplicationSlotXmin(agg_xmin, agg_catalog_xmin, already_locked);
882 }
uint32 TransactionId
Definition: c.h:636
void ProcArraySetReplicationSlotXmin(TransactionId xmin, TransactionId catalog_xmin, bool already_locked)
Definition: procarray.c:3876
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(), and StartupReplicationSlots().

◆ ReplicationSlotsCountDBSlots()

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

Definition at line 999 of file slot.c.

1000 {
1001  int i;
1002 
1003  *nslots = *nactive = 0;
1004 
1005  if (max_replication_slots <= 0)
1006  return false;
1007 
1008  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
1009  for (i = 0; i < max_replication_slots; i++)
1010  {
1011  ReplicationSlot *s;
1012 
1014 
1015  /* cannot change while ReplicationSlotCtlLock is held */
1016  if (!s->in_use)
1017  continue;
1018 
1019  /* only logical slots are database specific, skip */
1020  if (!SlotIsLogical(s))
1021  continue;
1022 
1023  /* not our database, skip */
1024  if (s->data.database != dboid)
1025  continue;
1026 
1027  /* NB: intentionally counting invalidated slots */
1028 
1029  /* count slots with spinlock held */
1030  SpinLockAcquire(&s->mutex);
1031  (*nslots)++;
1032  if (s->active_pid != 0)
1033  (*nactive)++;
1034  SpinLockRelease(&s->mutex);
1035  }
1036  LWLockRelease(ReplicationSlotControlLock);
1037 
1038  if (*nslots > 0)
1039  return true;
1040  return false;
1041 }

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 1057 of file slot.c.

1058 {
1059  int i;
1060 
1061  if (max_replication_slots <= 0)
1062  return;
1063 
1064 restart:
1065  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
1066  for (i = 0; i < max_replication_slots; i++)
1067  {
1068  ReplicationSlot *s;
1069  char *slotname;
1070  int active_pid;
1071 
1073 
1074  /* cannot change while ReplicationSlotCtlLock is held */
1075  if (!s->in_use)
1076  continue;
1077 
1078  /* only logical slots are database specific, skip */
1079  if (!SlotIsLogical(s))
1080  continue;
1081 
1082  /* not our database, skip */
1083  if (s->data.database != dboid)
1084  continue;
1085 
1086  /* NB: intentionally including invalidated slots */
1087 
1088  /* acquire slot, so ReplicationSlotDropAcquired can be reused */
1089  SpinLockAcquire(&s->mutex);
1090  /* can't change while ReplicationSlotControlLock is held */
1091  slotname = NameStr(s->data.name);
1092  active_pid = s->active_pid;
1093  if (active_pid == 0)
1094  {
1095  MyReplicationSlot = s;
1096  s->active_pid = MyProcPid;
1097  }
1098  SpinLockRelease(&s->mutex);
1099 
1100  /*
1101  * Even though we hold an exclusive lock on the database object a
1102  * logical slot for that DB can still be active, e.g. if it's
1103  * concurrently being dropped by a backend connected to another DB.
1104  *
1105  * That's fairly unlikely in practice, so we'll just bail out.
1106  */
1107  if (active_pid)
1108  ereport(ERROR,
1109  (errcode(ERRCODE_OBJECT_IN_USE),
1110  errmsg("replication slot \"%s\" is active for PID %d",
1111  slotname, active_pid)));
1112 
1113  /*
1114  * To avoid duplicating ReplicationSlotDropAcquired() and to avoid
1115  * holding ReplicationSlotControlLock over filesystem operations,
1116  * release ReplicationSlotControlLock and use
1117  * ReplicationSlotDropAcquired.
1118  *
1119  * As that means the set of slots could change, restart scan from the
1120  * beginning each time we release the lock.
1121  */
1122  LWLockRelease(ReplicationSlotControlLock);
1124  goto restart;
1125  }
1126  LWLockRelease(ReplicationSlotControlLock);
1127 }

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 136 of file slot.c.

137 {
138  bool found;
139 
140  if (max_replication_slots == 0)
141  return;
142 
144  ShmemInitStruct("ReplicationSlot Ctl", ReplicationSlotsShmemSize(),
145  &found);
146 
147  if (!found)
148  {
149  int i;
150 
151  /* First time through, so initialize */
153 
154  for (i = 0; i < max_replication_slots; i++)
155  {
157 
158  /* everything else is zeroed by the memset above */
159  SpinLockInit(&slot->mutex);
163  }
164  }
165 }
#define MemSet(start, val, len)
Definition: c.h:1004
void ConditionVariableInit(ConditionVariable *cv)
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition: lwlock.c:730
@ LWTRANCHE_REPLICATION_SLOT_IO
Definition: lwlock.h:191
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:396
Size ReplicationSlotsShmemSize(void)
Definition: slot.c:118
#define SpinLockInit(lock)
Definition: spin.h:60
LWLock io_in_progress_lock
Definition: slot.h:165

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

◆ ReplicationSlotsShmemSize()

Size ReplicationSlotsShmemSize ( void  )

Definition at line 118 of file slot.c.

119 {
120  Size size = 0;
121 
122  if (max_replication_slots == 0)
123  return size;
124 
125  size = offsetof(ReplicationSlotCtlData, replication_slots);
126  size = add_size(size,
128 
129  return size;
130 }
size_t Size
Definition: c.h:589
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519

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

Referenced by CalculateShmemSize(), and ReplicationSlotsShmemInit().

◆ ReplicationSlotValidateName()

bool ReplicationSlotValidateName ( const char *  name,
int  elevel 
)

Definition at line 199 of file slot.c.

200 {
201  const char *cp;
202 
203  if (strlen(name) == 0)
204  {
205  ereport(elevel,
206  (errcode(ERRCODE_INVALID_NAME),
207  errmsg("replication slot name \"%s\" is too short",
208  name)));
209  return false;
210  }
211 
212  if (strlen(name) >= NAMEDATALEN)
213  {
214  ereport(elevel,
215  (errcode(ERRCODE_NAME_TOO_LONG),
216  errmsg("replication slot name \"%s\" is too long",
217  name)));
218  return false;
219  }
220 
221  for (cp = name; *cp; cp++)
222  {
223  if (!((*cp >= 'a' && *cp <= 'z')
224  || (*cp >= '0' && *cp <= '9')
225  || (*cp == '_')))
226  {
227  ereport(elevel,
228  (errcode(ERRCODE_INVALID_NAME),
229  errmsg("replication slot name \"%s\" contains invalid character",
230  name),
231  errhint("Replication slot names may only contain lower case letters, numbers, and the underscore character.")));
232  return false;
233  }
234  }
235  return true;
236 }
#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 375 of file slot.c.

376 {
377  int i;
378  ReplicationSlot *slot = NULL;
379 
380  if (need_lock)
381  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
382 
383  for (i = 0; i < max_replication_slots; i++)
384  {
386 
387  if (s->in_use && strcmp(name, NameStr(s->data.name)) == 0)
388  {
389  slot = s;
390  break;
391  }
392  }
393 
394  if (need_lock)
395  LWLockRelease(ReplicationSlotControlLock);
396 
397  return slot;
398 }

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(), and ReplicationSlotAcquire().

◆ StartupReplicationSlots()

void StartupReplicationSlots ( void  )

Definition at line 1607 of file slot.c.

1608 {
1609  DIR *replication_dir;
1610  struct dirent *replication_de;
1611 
1612  elog(DEBUG1, "starting up replication slots");
1613 
1614  /* restore all slots by iterating over all on-disk entries */
1615  replication_dir = AllocateDir("pg_replslot");
1616  while ((replication_de = ReadDir(replication_dir, "pg_replslot")) != NULL)
1617  {
1618  char path[MAXPGPATH + 12];
1619  PGFileType de_type;
1620 
1621  if (strcmp(replication_de->d_name, ".") == 0 ||
1622  strcmp(replication_de->d_name, "..") == 0)
1623  continue;
1624 
1625  snprintf(path, sizeof(path), "pg_replslot/%s", replication_de->d_name);
1626  de_type = get_dirent_type(path, replication_de, false, DEBUG1);
1627 
1628  /* we're only creating directories here, skip if it's not our's */
1629  if (de_type != PGFILETYPE_ERROR && de_type != PGFILETYPE_DIR)
1630  continue;
1631 
1632  /* we crashed while a slot was being setup or deleted, clean up */
1633  if (pg_str_endswith(replication_de->d_name, ".tmp"))
1634  {
1635  if (!rmtree(path, true))
1636  {
1637  ereport(WARNING,
1638  (errmsg("could not remove directory \"%s\"",
1639  path)));
1640  continue;
1641  }
1642  fsync_fname("pg_replslot", true);
1643  continue;
1644  }
1645 
1646  /* looks like a slot in a normal state, restore */
1647  RestoreSlotFromDisk(replication_de->d_name);
1648  }
1649  FreeDir(replication_dir);
1650 
1651  /* currently no slots exist, we're done. */
1652  if (max_replication_slots <= 0)
1653  return;
1654 
1655  /* Now that we have recovered all the data, compute replication xmin */
1658 }
#define WARNING
Definition: elog.h:36
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2806
int FreeDir(DIR *dir)
Definition: fd.c:2858
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:667
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2740
PGFileType get_dirent_type(const char *path, const struct dirent *de, bool look_through_symlinks, int elevel)
Definition: file_utils.c:406
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:1883
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().

Variable Documentation

◆ max_replication_slots

◆ MyReplicationSlot

◆ ReplicationSlotCtl