PostgreSQL Source Code git master
Loading...
Searching...
No Matches
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 PG_REPLSLOT_DIR   "pg_replslot"
 
#define CONFLICT_DETECTION_SLOT   "pg_conflict_detection"
 
#define RS_INVAL_MAX_CAUSES   4
 
#define SlotIsPhysical(slot)   ((slot)->data.database == InvalidOid)
 
#define SlotIsLogical(slot)   ((slot)->data.database != InvalidOid)
 

Typedefs

typedef enum ReplicationSlotPersistency ReplicationSlotPersistency
 
typedef enum ReplicationSlotInvalidationCause ReplicationSlotInvalidationCause
 
typedef enum SlotSyncSkipReason SlotSyncSkipReason
 
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 = 0 , RS_INVAL_WAL_REMOVED = (1 << 0) , RS_INVAL_HORIZON = (1 << 1) , RS_INVAL_WAL_LEVEL = (1 << 2) ,
  RS_INVAL_IDLE_TIMEOUT = (1 << 3)
}
 
enum  SlotSyncSkipReason {
  SS_SKIP_NONE , SS_SKIP_WAL_NOT_FLUSHED , SS_SKIP_WAL_OR_ROWS_REMOVED , SS_SKIP_NO_CONSISTENT_SNAPSHOT ,
  SS_SKIP_INVALID
}
 

Functions

static void ReplicationSlotSetInactiveSince (ReplicationSlot *s, TimestampTz ts, bool acquire_lock)
 
void ReplicationSlotCreate (const char *name, bool db_specific, ReplicationSlotPersistency persistency, bool two_phase, bool repack, bool failover, bool synced)
 
void ReplicationSlotPersist (void)
 
void ReplicationSlotDrop (const char *name, bool nowait)
 
void ReplicationSlotDropAcquired (void)
 
void ReplicationSlotAlter (const char *name, const bool *failover, const bool *two_phase)
 
void ReplicationSlotAcquire (const char *name, bool nowait, bool error_if_invalid)
 
void ReplicationSlotRelease (void)
 
void ReplicationSlotCleanup (bool synced_only)
 
void ReplicationSlotSave (void)
 
void ReplicationSlotMarkDirty (void)
 
void ReplicationSlotInitialize (void)
 
bool ReplicationSlotValidateName (const char *name, bool allow_reserved_name, int elevel)
 
bool ReplicationSlotValidateNameInternal (const char *name, bool allow_reserved_name, int *err_code, char **err_msg, char **err_hint)
 
void ReplicationSlotReserveWal (void)
 
void ReplicationSlotsComputeRequiredXmin (bool already_locked)
 
void ReplicationSlotsComputeRequiredLSN (void)
 
XLogRecPtr ReplicationSlotsComputeLogicalRestartLSN (void)
 
bool ReplicationSlotsCountDBSlots (Oid dboid, int *nslots, int *nactive)
 
bool CheckLogicalSlotExists (void)
 
void ReplicationSlotsDropDBSlots (Oid dboid)
 
bool InvalidateObsoleteReplicationSlots (uint32 possible_causes, 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 (bool repack)
 
void CheckSlotPermissions (void)
 
ReplicationSlotInvalidationCause GetSlotInvalidationCause (const char *cause_name)
 
const charGetSlotInvalidationCauseName (ReplicationSlotInvalidationCause cause)
 
bool SlotExistsInSyncStandbySlots (const char *slot_name)
 
bool StandbySlotsHaveCaughtup (XLogRecPtr wait_for_lsn, int elevel)
 
void WaitForStandbyConfirmation (XLogRecPtr wait_for_lsn)
 

Variables

PGDLLIMPORT ReplicationSlotCtlDataReplicationSlotCtl
 
PGDLLIMPORT ReplicationSlotMyReplicationSlot
 
PGDLLIMPORT int max_replication_slots
 
PGDLLIMPORT int max_repack_replication_slots
 
PGDLLIMPORT charsynchronized_standby_slots
 
PGDLLIMPORT int idle_replication_slot_timeout_secs
 

Macro Definition Documentation

◆ CONFLICT_DETECTION_SLOT

#define CONFLICT_DETECTION_SLOT   "pg_conflict_detection"

Definition at line 28 of file slot.h.

◆ PG_REPLSLOT_DIR

#define PG_REPLSLOT_DIR   "pg_replslot"

Definition at line 21 of file slot.h.

◆ RS_INVAL_MAX_CAUSES

#define RS_INVAL_MAX_CAUSES   4

Definition at line 72 of file slot.h.

◆ SlotIsLogical

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

Definition at line 288 of file slot.h.

◆ SlotIsPhysical

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

Definition at line 287 of file slot.h.

Typedef Documentation

◆ ReplicationSlot

◆ ReplicationSlotCtlData

◆ ReplicationSlotInvalidationCause

◆ ReplicationSlotPersistency

◆ ReplicationSlotPersistentData

◆ SlotSyncSkipReason

Enumeration Type Documentation

◆ ReplicationSlotInvalidationCause

Enumerator
RS_INVAL_NONE 
RS_INVAL_WAL_REMOVED 
RS_INVAL_HORIZON 
RS_INVAL_WAL_LEVEL 
RS_INVAL_IDLE_TIMEOUT 

Definition at line 58 of file slot.h.

59{
60 RS_INVAL_NONE = 0,
61 /* required WAL has been removed */
62 RS_INVAL_WAL_REMOVED = (1 << 0),
63 /* required rows have been removed */
64 RS_INVAL_HORIZON = (1 << 1),
65 /* wal_level insufficient for slot */
66 RS_INVAL_WAL_LEVEL = (1 << 2),
67 /* idle slot timeout has occurred */
68 RS_INVAL_IDLE_TIMEOUT = (1 << 3),
ReplicationSlotInvalidationCause
Definition slot.h:59
@ RS_INVAL_WAL_REMOVED
Definition slot.h:62
@ RS_INVAL_IDLE_TIMEOUT
Definition slot.h:68
@ RS_INVAL_HORIZON
Definition slot.h:64
@ RS_INVAL_WAL_LEVEL
Definition slot.h:66
@ RS_INVAL_NONE
Definition slot.h:60

◆ ReplicationSlotPersistency

Enumerator
RS_PERSISTENT 
RS_EPHEMERAL 
RS_TEMPORARY 

Definition at line 43 of file slot.h.

44{
ReplicationSlotPersistency
Definition slot.h:44
@ RS_PERSISTENT
Definition slot.h:45
@ RS_EPHEMERAL
Definition slot.h:46
@ RS_TEMPORARY
Definition slot.h:47

◆ SlotSyncSkipReason

Enumerator
SS_SKIP_NONE 
SS_SKIP_WAL_NOT_FLUSHED 
SS_SKIP_WAL_OR_ROWS_REMOVED 
SS_SKIP_NO_CONSISTENT_SNAPSHOT 
SS_SKIP_INVALID 

Definition at line 80 of file slot.h.

81{
82 SS_SKIP_NONE, /* No skip */
83 SS_SKIP_WAL_NOT_FLUSHED, /* Standby did not flush the wal corresponding
84 * to confirmed flush of remote slot */
85 SS_SKIP_WAL_OR_ROWS_REMOVED, /* Remote slot is behind; required WAL or
86 * rows may be removed or at risk */
87 SS_SKIP_NO_CONSISTENT_SNAPSHOT, /* Standby could not build a consistent
88 * snapshot */
89 SS_SKIP_INVALID /* Local slot is invalid */
SlotSyncSkipReason
Definition slot.h:81
@ SS_SKIP_WAL_NOT_FLUSHED
Definition slot.h:83
@ SS_SKIP_NO_CONSISTENT_SNAPSHOT
Definition slot.h:87
@ SS_SKIP_NONE
Definition slot.h:82
@ SS_SKIP_INVALID
Definition slot.h:89
@ SS_SKIP_WAL_OR_ROWS_REMOVED
Definition slot.h:85

Function Documentation

◆ CheckLogicalSlotExists()

bool CheckLogicalSlotExists ( void  )
extern

Definition at line 1623 of file slot.c.

1624{
1625 bool found = false;
1626
1628 return false;
1629
1632 {
1633 ReplicationSlot *s;
1634 bool invalidated;
1635
1637
1638 /* cannot change while ReplicationSlotCtlLock is held */
1639 if (!s->in_use)
1640 continue;
1641
1642 if (SlotIsPhysical(s))
1643 continue;
1644
1646 invalidated = s->data.invalidated != RS_INVAL_NONE;
1648
1649 if (invalidated)
1650 continue;
1651
1652 found = true;
1653 break;
1654 }
1656
1657 return found;
1658}
int i
Definition isn.c:77
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1150
void LWLockRelease(LWLock *lock)
Definition lwlock.c:1767
@ LW_SHARED
Definition lwlock.h:105
static int fb(int x)
int max_replication_slots
Definition slot.c:161
ReplicationSlotCtlData * ReplicationSlotCtl
Definition slot.c:147
int max_repack_replication_slots
Definition slot.c:163
#define SlotIsPhysical(slot)
Definition slot.h:287
static void SpinLockRelease(volatile slock_t *lock)
Definition spin.h:62
static void SpinLockAcquire(volatile slock_t *lock)
Definition spin.h:56
ReplicationSlot replication_slots[1]
Definition slot.h:299
ReplicationSlotInvalidationCause invalidated
Definition slot.h:128
slock_t mutex
Definition slot.h:183
bool in_use
Definition slot.h:186
ReplicationSlotPersistentData data
Definition slot.h:213

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

Referenced by DisableLogicalDecoding(), and UpdateLogicalDecodingStatusEndOfRecovery().

◆ CheckPointReplicationSlots()

void CheckPointReplicationSlots ( bool  is_shutdown)
extern

Definition at line 2324 of file slot.c.

2325{
2326 int i;
2327 bool last_saved_restart_lsn_updated = false;
2328
2329 elog(DEBUG1, "performing replication slot checkpoint");
2330
2331 /*
2332 * Prevent any slot from being created/dropped while we're active. As we
2333 * explicitly do *not* want to block iterating over replication_slots or
2334 * acquiring a slot we cannot take the control lock - but that's OK,
2335 * because holding ReplicationSlotAllocationLock is strictly stronger, and
2336 * enough to guarantee that nobody can change the in_use bits on us.
2337 *
2338 * Additionally, acquiring the Allocation lock is necessary to serialize
2339 * the slot flush process with concurrent slot WAL reservation. This
2340 * ensures that the WAL position being reserved is either flushed to disk
2341 * or is beyond or equal to the redo pointer of the current checkpoint
2342 * (See ReplicationSlotReserveWal for details).
2343 */
2345
2347 {
2349 char path[MAXPGPATH];
2350
2351 if (!s->in_use)
2352 continue;
2353
2354 /* save the slot to disk, locking is handled in SaveSlotToPath() */
2355 sprintf(path, "%s/%s", PG_REPLSLOT_DIR, NameStr(s->data.name));
2356
2357 /*
2358 * Slot's data is not flushed each time the confirmed_flush LSN is
2359 * updated as that could lead to frequent writes. However, we decide
2360 * to force a flush of all logical slot's data at the time of shutdown
2361 * if the confirmed_flush LSN is changed since we last flushed it to
2362 * disk. This helps in avoiding an unnecessary retreat of the
2363 * confirmed_flush LSN after restart.
2364 */
2365 if (is_shutdown && SlotIsLogical(s))
2366 {
2368
2369 if (s->data.invalidated == RS_INVAL_NONE &&
2371 {
2372 s->just_dirtied = true;
2373 s->dirty = true;
2374 }
2376 }
2377
2378 /*
2379 * Track if we're going to update slot's last_saved_restart_lsn. We
2380 * need this to know if we need to recompute the required LSN.
2381 */
2384
2385 SaveSlotToPath(s, path, LOG);
2386 }
2388
2389 /*
2390 * Recompute the required LSN if SaveSlotToPath() updated
2391 * last_saved_restart_lsn for any slot.
2392 */
2395}
#define NameStr(name)
Definition c.h:835
#define LOG
Definition elog.h:32
#define DEBUG1
Definition elog.h:31
#define elog(elevel,...)
Definition elog.h:228
#define MAXPGPATH
#define sprintf
Definition port.h:262
static void SaveSlotToPath(ReplicationSlot *slot, const char *dir, int elevel)
Definition slot.c:2524
void ReplicationSlotsComputeRequiredLSN(void)
Definition slot.c:1308
#define PG_REPLSLOT_DIR
Definition slot.h:21
#define SlotIsLogical(slot)
Definition slot.h:288
XLogRecPtr last_saved_confirmed_flush
Definition slot.h:238
bool just_dirtied
Definition slot.h:195
XLogRecPtr last_saved_restart_lsn
Definition slot.h:271

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

Referenced by CheckPointGuts().

◆ CheckSlotPermissions()

void CheckSlotPermissions ( void  )
extern

Definition at line 1694 of file slot.c.

1695{
1697 ereport(ERROR,
1699 errmsg("permission denied to use replication slots"),
1700 errdetail("Only roles with the %s attribute may use replication slots.",
1701 "REPLICATION")));
1702}
int errcode(int sqlerrcode)
Definition elog.c:874
int errdetail(const char *fmt,...) pg_attribute_printf(1
#define ERROR
Definition elog.h:40
#define ereport(elevel,...)
Definition elog.h:152
Oid GetUserId(void)
Definition miscinit.c:470
bool has_rolreplication(Oid roleid)
Definition miscinit.c:689
static char * errmsg

References ereport, errcode(), errdetail(), errmsg, ERROR, fb(), 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(), pg_sync_replication_slots(), and repack_setup_logical_decoding().

◆ CheckSlotRequirements()

void CheckSlotRequirements ( bool  repack)
extern

Definition at line 1665 of file slot.c.

1666{
1667 /*
1668 * NB: Adding a new requirement likely means that RestoreSlotFromDisk()
1669 * needs the same check.
1670 */
1671
1672 if (!repack && max_replication_slots == 0)
1673 ereport(ERROR,
1675 errmsg("replication slots can only be used if \"%s\" > 0",
1676 "max_replication_slots"));
1677
1679 ereport(ERROR,
1681 errmsg("REPACK can only be used if \"%s\" > 0",
1682 "max_repack_replication_slots"));
1683
1685 ereport(ERROR,
1687 errmsg("replication slots can only be used if \"wal_level\" >= \"replica\"")));
1688}
int wal_level
Definition xlog.c:138
@ WAL_LEVEL_REPLICA
Definition xlog.h:77

References ereport, errcode(), errmsg, ERROR, fb(), max_repack_replication_slots, 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 cause_name)
extern

Definition at line 2936 of file slot.c.

2937{
2938 Assert(cause_name);
2939
2940 /* Search lookup table for the cause having this name */
2941 for (int i = 0; i <= RS_INVAL_MAX_CAUSES; i++)
2942 {
2943 if (strcmp(SlotInvalidationCauses[i].cause_name, cause_name) == 0)
2945 }
2946
2947 Assert(false);
2948 return RS_INVAL_NONE; /* to keep compiler quiet */
2949}
#define Assert(condition)
Definition c.h:943
static const SlotInvalidationCauseMap SlotInvalidationCauses[]
Definition slot.c:115
#define RS_INVAL_MAX_CAUSES
Definition slot.h:72
ReplicationSlotInvalidationCause cause
Definition slot.c:111

References Assert, SlotInvalidationCauseMap::cause, fb(), i, RS_INVAL_MAX_CAUSES, RS_INVAL_NONE, and SlotInvalidationCauses.

Referenced by fetch_remote_slots().

◆ GetSlotInvalidationCauseName()

const char * GetSlotInvalidationCauseName ( ReplicationSlotInvalidationCause  cause)
extern

Definition at line 2956 of file slot.c.

2957{
2958 /* Search lookup table for the name of this cause */
2959 for (int i = 0; i <= RS_INVAL_MAX_CAUSES; i++)
2960 {
2961 if (SlotInvalidationCauses[i].cause == cause)
2963 }
2964
2965 Assert(false);
2966 return "none"; /* to keep compiler quiet */
2967}
const char * cause_name
Definition slot.c:112

References Assert, SlotInvalidationCauseMap::cause_name, i, RS_INVAL_MAX_CAUSES, and SlotInvalidationCauses.

Referenced by pg_get_replication_slots(), and ReplicationSlotAcquire().

◆ InvalidateObsoleteReplicationSlots()

bool InvalidateObsoleteReplicationSlots ( uint32  possible_causes,
XLogSegNo  oldestSegno,
Oid  dboid,
TransactionId  snapshotConflictHorizon 
)
extern

Definition at line 2220 of file slot.c.

2223{
2225 bool invalidated = false;
2226 bool invalidated_logical = false;
2228
2229 Assert(!(possible_causes & RS_INVAL_HORIZON) || TransactionIdIsValid(snapshotConflictHorizon));
2232
2234 return invalidated;
2235
2237
2238restart:
2242 {
2244 bool released_lock = false;
2245
2246 if (!s->in_use)
2247 continue;
2248
2249 /* Prevent invalidation of logical slots during binary upgrade */
2251 {
2255
2256 continue;
2257 }
2258
2260 dboid, snapshotConflictHorizon,
2261 &released_lock))
2262 {
2264
2265 /* Remember we have invalidated a physical or logical slot */
2266 invalidated = true;
2267
2268 /*
2269 * Additionally, remember we have invalidated a logical slot as we
2270 * can request disabling logical decoding later.
2271 */
2272 if (SlotIsLogical(s))
2273 invalidated_logical = true;
2274 }
2275 else
2276 {
2277 /*
2278 * We need to check if the slot is invalidated here since
2279 * InvalidatePossiblyObsoleteSlot() returns false also if the slot
2280 * is already invalidated.
2281 */
2286 }
2287
2288 /* if the lock was released, start from scratch */
2289 if (released_lock)
2290 goto restart;
2291 }
2293
2294 /*
2295 * If any slots have been invalidated, recalculate the resource limits.
2296 */
2297 if (invalidated)
2298 {
2301 }
2302
2303 /*
2304 * Request the checkpointer to disable logical decoding if no valid
2305 * logical slots remain. If called by the checkpointer during a
2306 * checkpoint, only the request is initiated; actual deactivation is
2307 * deferred until after the checkpoint completes.
2308 */
2311
2312 return invalidated;
2313}
bool IsBinaryUpgrade
Definition globals.c:123
void RequestDisableLogicalDecoding(void)
Definition logicalctl.c:431
static bool InvalidatePossiblyObsoleteSlot(uint32 possible_causes, ReplicationSlot *s, XLogRecPtr oldestLSN, Oid dboid, TransactionId snapshotConflictHorizon, bool *released_lock_out)
Definition slot.c:1980
void ReplicationSlotsComputeRequiredXmin(bool already_locked)
Definition slot.c:1226
#define TransactionIdIsValid(xid)
Definition transam.h:41
int wal_segment_size
Definition xlog.c:150
#define XLogSegNoOffsetToRecPtr(segno, offset, wal_segsz_bytes, dest)
uint64 XLogRecPtr
Definition xlogdefs.h:21

References Assert, ReplicationSlot::data, fb(), i, ReplicationSlot::in_use, ReplicationSlotPersistentData::invalidated, InvalidatePossiblyObsoleteSlot(), IsBinaryUpgrade, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_repack_replication_slots, max_replication_slots, ReplicationSlot::mutex, ReplicationSlotCtlData::replication_slots, ReplicationSlotCtl, ReplicationSlotsComputeRequiredLSN(), ReplicationSlotsComputeRequiredXmin(), RequestDisableLogicalDecoding(), RS_INVAL_HORIZON, RS_INVAL_NONE, RS_INVAL_WAL_REMOVED, SlotIsLogical, SpinLockAcquire(), SpinLockRelease(), TransactionIdIsValid, wal_segment_size, and XLogSegNoOffsetToRecPtr.

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

◆ ReplicationSlotAcquire()

void ReplicationSlotAcquire ( const char name,
bool  nowait,
bool  error_if_invalid 
)
extern

Definition at line 629 of file slot.c.

630{
632 ProcNumber active_proc;
633 int active_pid;
634
635 Assert(name != NULL);
636
637retry:
639
641
642 /* Check if the slot exists with the given name. */
644 if (s == NULL || !s->in_use)
645 {
647
650 errmsg("replication slot \"%s\" does not exist",
651 name)));
652 }
653
654 /*
655 * Do not allow users to acquire the reserved slot. This scenario may
656 * occur if the launcher that owns the slot has terminated unexpectedly
657 * due to an error, and a backend process attempts to reuse the slot.
658 */
662 errmsg("cannot acquire replication slot \"%s\"", name),
663 errdetail("The slot is reserved for conflict detection and can only be acquired by logical replication launcher."));
664
665 /*
666 * This is the slot we want; check if it's active under some other
667 * process. In single user mode, we don't need this check.
668 */
670 {
671 /*
672 * Get ready to sleep on the slot in case it is active. (We may end
673 * up not sleeping, but we don't want to do this while holding the
674 * spinlock.)
675 */
676 if (!nowait)
678
679 /*
680 * It is important to reset the inactive_since under spinlock here to
681 * avoid race conditions with slot invalidation. See comments related
682 * to inactive_since in InvalidatePossiblyObsoleteSlot.
683 */
687 active_proc = s->active_proc;
690 }
691 else
692 {
693 s->active_proc = active_proc = MyProcNumber;
695 }
696 active_pid = GetPGProcByNumber(active_proc)->pid;
698
699 /*
700 * If we found the slot but it's already active in another process, we
701 * wait until the owning process signals us that it's been released, or
702 * error out.
703 */
704 if (active_proc != MyProcNumber)
705 {
706 if (!nowait)
707 {
708 /* Wait here until we get signaled, and then restart */
712 goto retry;
713 }
714
717 errmsg("replication slot \"%s\" is active for PID %d",
718 NameStr(s->data.name), active_pid)));
719 }
720 else if (!nowait)
721 ConditionVariableCancelSleep(); /* no sleep needed after all */
722
723 /* We made this slot active, so it's ours now. */
725
726 /*
727 * We need to check for invalidation after making the slot ours to avoid
728 * the possible race condition with the checkpointer that can otherwise
729 * invalidate the slot immediately after the check.
730 */
734 errmsg("can no longer access replication slot \"%s\"",
735 NameStr(s->data.name)),
736 errdetail("This replication slot has been invalidated due to \"%s\".",
738
739 /* Let everybody know we've modified this slot */
741
742 /*
743 * The call to pgstat_acquire_replslot() protects against stats for a
744 * different slot, from before a restart or such, being present during
745 * pgstat_report_replslot().
746 */
747 if (SlotIsLogical(s))
749
750
751 if (am_walsender)
752 {
755 ? errmsg("acquired logical replication slot \"%s\"",
756 NameStr(s->data.name))
757 : errmsg("acquired physical replication slot \"%s\"",
758 NameStr(s->data.name)));
759 }
760}
bool ConditionVariableCancelSleep(void)
void ConditionVariableBroadcast(ConditionVariable *cv)
void ConditionVariablePrepareToSleep(ConditionVariable *cv)
void ConditionVariableSleep(ConditionVariable *cv, uint32 wait_event_info)
ProcNumber MyProcNumber
Definition globals.c:92
bool IsUnderPostmaster
Definition globals.c:122
bool IsLogicalLauncher(void)
Definition launcher.c:1587
const void * data
void pgstat_acquire_replslot(ReplicationSlot *slot)
#define GetPGProcByNumber(n)
Definition proc.h:504
#define INVALID_PROC_NUMBER
Definition procnumber.h:26
int ProcNumber
Definition procnumber.h:24
ReplicationSlot * MyReplicationSlot
Definition slot.c:158
ReplicationSlot * SearchNamedReplicationSlot(const char *name, bool need_lock)
Definition slot.c:548
const char * GetSlotInvalidationCauseName(ReplicationSlotInvalidationCause cause)
Definition slot.c:2956
static bool IsSlotForConflictCheck(const char *name)
Definition slot.c:360
static void ReplicationSlotSetInactiveSince(ReplicationSlot *s, TimestampTz ts, bool acquire_lock)
Definition slot.h:306
ConditionVariable active_cv
Definition slot.h:219
ProcNumber active_proc
Definition slot.h:192
const char * name
bool am_walsender
Definition walsender.c:135
bool log_replication_commands
Definition walsender.c:150

References ReplicationSlot::active_cv, ReplicationSlot::active_proc, am_walsender, Assert, ConditionVariableBroadcast(), ConditionVariableCancelSleep(), ConditionVariablePrepareToSleep(), ConditionVariableSleep(), ReplicationSlot::data, DEBUG1, ereport, errcode(), errdetail(), errmsg, ERROR, fb(), GetPGProcByNumber, GetSlotInvalidationCauseName(), ReplicationSlot::in_use, INVALID_PROC_NUMBER, ReplicationSlotPersistentData::invalidated, IsLogicalLauncher(), IsSlotForConflictCheck(), IsUnderPostmaster, LOG, log_replication_commands, LW_SHARED, LWLockAcquire(), LWLockRelease(), ReplicationSlot::mutex, MyProcNumber, MyReplicationSlot, name, ReplicationSlotPersistentData::name, NameStr, pgstat_acquire_replslot(), ReplicationSlotSetInactiveSince(), RS_INVAL_NONE, SearchNamedReplicationSlot(), SlotIsLogical, SpinLockAcquire(), and SpinLockRelease().

Referenced by acquire_conflict_slot_if_exists(), binary_upgrade_check_logical_slot_pending_wal(), 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,
const bool failover,
const bool two_phase 
)
extern

Definition at line 960 of file slot.c.

962{
963 bool update_slot = false;
964
967
968 ReplicationSlotAcquire(name, false, true);
969
973 errmsg("cannot use %s with a physical replication slot",
974 "ALTER_REPLICATION_SLOT"));
975
976 if (RecoveryInProgress())
977 {
978 /*
979 * Do not allow users to alter the slots which are currently being
980 * synced from the primary to the standby.
981 */
985 errmsg("cannot alter replication slot \"%s\"", name),
986 errdetail("This replication slot is being synchronized from the primary server."));
987
988 /*
989 * Do not allow users to enable failover on the standby as we do not
990 * support sync to the cascading standby.
991 */
992 if (failover && *failover)
995 errmsg("cannot enable failover for a replication slot"
996 " on the standby"));
997 }
998
999 if (failover)
1000 {
1001 /*
1002 * Do not allow users to enable failover for temporary slots as we do
1003 * not support syncing temporary slots to the standby.
1004 */
1006 ereport(ERROR,
1008 errmsg("cannot enable failover for a temporary replication slot"));
1009
1011 {
1015
1016 update_slot = true;
1017 }
1018 }
1019
1021 {
1025
1026 update_slot = true;
1027 }
1028
1029 if (update_slot)
1030 {
1033 }
1034
1036}
static bool two_phase
static bool failover
void ReplicationSlotAcquire(const char *name, bool nowait, bool error_if_invalid)
Definition slot.c:629
void ReplicationSlotMarkDirty(void)
Definition slot.c:1184
void ReplicationSlotSave(void)
Definition slot.c:1166
void ReplicationSlotRelease(void)
Definition slot.c:769
ReplicationSlotPersistency persistency
Definition slot.h:106
bool RecoveryInProgress(void)
Definition xlog.c:6830

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

Referenced by AlterReplicationSlot().

◆ ReplicationSlotCleanup()

void ReplicationSlotCleanup ( bool  synced_only)
extern

Definition at line 868 of file slot.c.

869{
870 int i;
872 bool dropped_logical = false;
873
875
876restart:
880 {
882
883 if (!s->in_use)
884 continue;
885
887
890
891 if ((s->active_proc == MyProcNumber &&
892 (!synced_only || s->data.synced)))
893 {
896 LWLockRelease(ReplicationSlotControlLock); /* avoid deadlock */
897
898 if (SlotIsLogical(s))
899 dropped_logical = true;
900
902
904 goto restart;
905 }
906 else
908 }
909
911
914}
static void ReplicationSlotDropPtr(ReplicationSlot *slot)
Definition slot.c:1059

References ReplicationSlot::active_cv, ReplicationSlot::active_proc, Assert, ConditionVariableBroadcast(), ReplicationSlot::data, fb(), i, ReplicationSlot::in_use, ReplicationSlotPersistentData::invalidated, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_repack_replication_slots, max_replication_slots, ReplicationSlot::mutex, MyProcNumber, MyReplicationSlot, ReplicationSlotPersistentData::persistency, ReplicationSlotCtlData::replication_slots, ReplicationSlotCtl, ReplicationSlotDropPtr(), RequestDisableLogicalDecoding(), RS_INVAL_NONE, RS_TEMPORARY, SlotIsLogical, SpinLockAcquire(), SpinLockRelease(), and ReplicationSlotPersistentData::synced.

Referenced by PostgresMain(), ReplicationSlotShmemExit(), slotsync_failure_callback(), slotsync_worker_onexit(), SyncReplicationSlots(), and WalSndErrorCleanup().

◆ ReplicationSlotCreate()

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

Definition at line 378 of file slot.c.

381{
382 ReplicationSlot *slot = NULL;
383 int startpoint,
384 endpoint;
385
387
388 /*
389 * The logical launcher or pg_upgrade may create or migrate an internal
390 * slot, so using a reserved name is allowed in these cases.
391 */
393 ERROR);
394
395 if (failover)
396 {
397 /*
398 * Do not allow users to create the failover enabled slots on the
399 * standby as we do not support sync to the cascading standby.
400 *
401 * However, failover enabled slots can be created during slot
402 * synchronization because we need to retain the same values as the
403 * remote slot.
404 */
408 errmsg("cannot enable failover for a replication slot created on the standby"));
409
410 /*
411 * Do not allow users to create failover enabled temporary slots,
412 * because temporary slots will not be synced to the standby.
413 *
414 * However, failover enabled temporary slots can be created during
415 * slot synchronization. See the comments atop slotsync.c for details.
416 */
417 if (persistency == RS_TEMPORARY && !IsSyncingReplicationSlots())
420 errmsg("cannot enable failover for a temporary replication slot"));
421 }
422
423 /*
424 * If some other backend ran this code concurrently with us, we'd likely
425 * both allocate the same slot, and that would be bad. We'd also be at
426 * risk of missing a name collision. Also, we don't want to try to create
427 * a new slot while somebody's busy cleaning up an old one, because we
428 * might both be monkeying with the same directory.
429 */
431
432 /*
433 * Check for name collision (across the whole array), and identify an
434 * allocatable slot (in the array slice specific to our current use case:
435 * either general, or REPACK only). We need to hold
436 * ReplicationSlotControlLock in shared mode for this, so that nobody else
437 * can change the in_use flags while we're looking at them.
438 */
440 startpoint = !repack ? 0 : max_replication_slots;
443 {
445
446 if (s->in_use && strcmp(name, NameStr(s->data.name)) == 0)
449 errmsg("replication slot \"%s\" already exists", name)));
450
451 if (i >= startpoint && i < endpoint &&
452 !s->in_use && slot == NULL)
453 slot = s;
454 }
456
457 /* If all slots are in use, we're out of luck. */
458 if (slot == NULL)
461 errmsg("all replication slots are in use"),
462 errhint("Free one or increase \"%s\".",
463 repack ? "max_repack_replication_slots" : "max_replication_slots")));
464
465 /*
466 * Since this slot is not in use, nobody should be looking at any part of
467 * it other than the in_use field unless they're trying to allocate it.
468 * And since we hold ReplicationSlotAllocationLock, nobody except us can
469 * be doing that. So it's safe to initialize the slot.
470 */
471 Assert(!slot->in_use);
473
474 /* first initialize persistent data */
475 memset(&slot->data, 0, sizeof(ReplicationSlotPersistentData));
476 namestrcpy(&slot->data.name, name);
478 slot->data.persistency = persistency;
479 slot->data.two_phase = two_phase;
481 slot->data.failover = failover;
482 slot->data.synced = synced;
483
484 /* and then data only present in shared memory */
485 slot->just_dirtied = false;
486 slot->dirty = false;
495 slot->inactive_since = 0;
497
498 /*
499 * Create the slot on disk. We haven't actually marked the slot allocated
500 * yet, so no special cleanup is required if this errors out.
501 */
502 CreateSlotOnDisk(slot);
503
504 /*
505 * We need to briefly prevent any other backend from iterating over the
506 * slots while we flip the in_use flag. We also need to set the active
507 * flag while holding the ControlLock as otherwise a concurrent
508 * ReplicationSlotAcquire() could acquire the slot as well.
509 */
511
512 slot->in_use = true;
513
514 /* We can now mark the slot active, and that makes it our slot. */
515 SpinLockAcquire(&slot->mutex);
518 SpinLockRelease(&slot->mutex);
519 MyReplicationSlot = slot;
520
522
523 /*
524 * Create statistics entry for the new logical slot. We don't collect any
525 * stats for physical slots, so no need to create an entry for the same.
526 * See ReplicationSlotDropPtr for why we need to do this before releasing
527 * ReplicationSlotAllocationLock.
528 */
529 if (SlotIsLogical(slot))
531
532 /*
533 * Now that the slot has been marked as in_use and active, it's safe to
534 * let somebody else try to allocate a slot.
535 */
537
538 /* Let everybody know we've modified this slot */
540}
int errhint(const char *fmt,...) pg_attribute_printf(1
Oid MyDatabaseId
Definition globals.c:96
@ LW_EXCLUSIVE
Definition lwlock.h:104
void namestrcpy(Name name, const char *str)
Definition name.c:233
void pgstat_create_replslot(ReplicationSlot *slot)
#define InvalidOid
static void CreateSlotOnDisk(ReplicationSlot *slot)
Definition slot.c:2463
bool ReplicationSlotValidateName(const char *name, bool allow_reserved_name, int elevel)
Definition slot.c:265
bool IsSyncingReplicationSlots(void)
Definition slotsync.c:1897
#define ERRCODE_DUPLICATE_OBJECT
Definition streamutil.c:30
XLogRecPtr candidate_xmin_lsn
Definition slot.h:229
TransactionId effective_catalog_xmin
Definition slot.h:210
XLogRecPtr candidate_restart_valid
Definition slot.h:230
SlotSyncSkipReason slotsync_skip_reason
Definition slot.h:284
TransactionId effective_xmin
Definition slot.h:209
XLogRecPtr candidate_restart_lsn
Definition slot.h:231
TransactionId candidate_catalog_xmin
Definition slot.h:228
TimestampTz inactive_since
Definition slot.h:245
#define InvalidTransactionId
Definition transam.h:31
#define InvalidXLogRecPtr
Definition xlogdefs.h:28

References ReplicationSlot::active_cv, ReplicationSlot::active_proc, 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, failover, ReplicationSlotPersistentData::failover, fb(), i, ReplicationSlot::in_use, ReplicationSlot::inactive_since, INVALID_PROC_NUMBER, InvalidOid, InvalidTransactionId, InvalidXLogRecPtr, IsBinaryUpgrade, IsLogicalLauncher(), IsSyncingReplicationSlots(), ReplicationSlot::just_dirtied, ReplicationSlot::last_saved_confirmed_flush, ReplicationSlot::last_saved_restart_lsn, LW_EXCLUSIVE, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_repack_replication_slots, max_replication_slots, ReplicationSlot::mutex, MyDatabaseId, MyProcNumber, MyReplicationSlot, name, ReplicationSlotPersistentData::name, NameStr, namestrcpy(), ReplicationSlotPersistentData::persistency, pgstat_create_replslot(), RecoveryInProgress(), ReplicationSlotCtlData::replication_slots, ReplicationSlotCtl, ReplicationSlotValidateName(), RS_TEMPORARY, SlotIsLogical, ReplicationSlot::slotsync_skip_reason, SpinLockAcquire(), SpinLockRelease(), SS_SKIP_NONE, ReplicationSlotPersistentData::synced, two_phase, ReplicationSlotPersistentData::two_phase, and ReplicationSlotPersistentData::two_phase_at.

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

◆ ReplicationSlotDrop()

void ReplicationSlotDrop ( const char name,
bool  nowait 
)
extern

Definition at line 920 of file slot.c.

921{
922 bool is_logical;
923
925
926 ReplicationSlotAcquire(name, nowait, false);
927
928 /*
929 * Do not allow users to drop the slots which are currently being synced
930 * from the primary to the standby.
931 */
935 errmsg("cannot drop replication slot \"%s\"", name),
936 errdetail("This replication slot is being synchronized from the primary server."));
937
939
941
942 if (is_logical)
944}
void ReplicationSlotDropAcquired(void)
Definition slot.c:1042

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

Referenced by DropReplicationSlot(), and pg_drop_replication_slot().

◆ ReplicationSlotDropAcquired()

void ReplicationSlotDropAcquired ( void  )
extern

◆ ReplicationSlotDropAtPubNode()

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

Definition at line 2496 of file subscriptioncmds.c.

2497{
2498 StringInfoData cmd;
2499
2500 Assert(wrconn);
2501
2502 load_file("libpqwalreceiver", false);
2503
2504 initStringInfo(&cmd);
2505 appendStringInfo(&cmd, "DROP_REPLICATION_SLOT %s WAIT", quote_identifier(slotname));
2506
2507 PG_TRY();
2508 {
2509 WalRcvExecResult *res;
2510
2511 res = walrcv_exec(wrconn, cmd.data, 0, NULL);
2512
2513 if (res->status == WALRCV_OK_COMMAND)
2514 {
2515 /* NOTICE. Success. */
2517 (errmsg("dropped replication slot \"%s\" on publisher",
2518 slotname)));
2519 }
2520 else if (res->status == WALRCV_ERROR &&
2521 missing_ok &&
2523 {
2524 /* LOG. Error, but missing_ok = true. */
2525 ereport(LOG,
2526 (errmsg("could not drop replication slot \"%s\" on publisher: %s",
2527 slotname, res->err)));
2528 }
2529 else
2530 {
2531 /* ERROR. */
2532 ereport(ERROR,
2534 errmsg("could not drop replication slot \"%s\" on publisher: %s",
2535 slotname, res->err)));
2536 }
2537
2539 }
2540 PG_FINALLY();
2541 {
2542 pfree(cmd.data);
2543 }
2544 PG_END_TRY();
2545}
void load_file(const char *filename, bool restricted)
Definition dfmgr.c:149
#define PG_TRY(...)
Definition elog.h:374
#define PG_END_TRY(...)
Definition elog.h:399
#define NOTICE
Definition elog.h:36
#define PG_FINALLY(...)
Definition elog.h:391
void pfree(void *pointer)
Definition mcxt.c:1616
const char * quote_identifier(const char *ident)
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition stringinfo.c:145
void initStringInfo(StringInfo str)
Definition stringinfo.c:97
WalRcvExecStatus status
static WalReceiverConn * wrconn
Definition walreceiver.c:95
@ WALRCV_OK_COMMAND
@ WALRCV_ERROR
static void walrcv_clear_result(WalRcvExecResult *walres)
#define walrcv_exec(conn, exec, nRetTypes, retTypes)

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

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

◆ ReplicationSlotIndex()

◆ ReplicationSlotInitialize()

void ReplicationSlotInitialize ( void  )
extern

Definition at line 240 of file slot.c.

241{
243}
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition ipc.c:344
static void ReplicationSlotShmemExit(int code, Datum arg)
Definition slot.c:249

References before_shmem_exit(), and ReplicationSlotShmemExit().

Referenced by BaseInit().

◆ ReplicationSlotMarkDirty()

◆ ReplicationSlotName()

bool ReplicationSlotName ( int  index,
Name  name 
)
extern

Definition at line 598 of file slot.c.

599{
600 ReplicationSlot *slot;
601 bool found;
602
604
605 /*
606 * Ensure that the slot cannot be dropped while we copy the name. Don't
607 * need the spinlock as the name of an existing slot cannot change.
608 */
610 found = slot->in_use;
611 if (slot->in_use)
614
615 return found;
616}
Definition type.h:96

References ReplicationSlot::data, fb(), 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 
)
extern

Definition at line 1235 of file tablesync.c.

1237{
1238 snprintf(syncslotname, szslot, "pg_%u_sync_%u_" UINT64_FORMAT, suboid,
1239 relid, GetSystemIdentifier());
1240}
#define UINT64_FORMAT
Definition c.h:635
#define snprintf
Definition port.h:260
uint64 GetSystemIdentifier(void)
Definition xlog.c:4647

References fb(), GetSystemIdentifier(), snprintf, and UINT64_FORMAT.

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

◆ ReplicationSlotPersist()

◆ ReplicationSlotRelease()

void ReplicationSlotRelease ( void  )
extern

Definition at line 769 of file slot.c.

770{
772 char *slotname = NULL; /* keep compiler quiet */
773 bool is_logical;
774 TimestampTz now = 0;
775
776 Assert(slot != NULL && slot->active_proc != INVALID_PROC_NUMBER);
777
779
780 if (am_walsender)
781 slotname = pstrdup(NameStr(slot->data.name));
782
783 if (slot->data.persistency == RS_EPHEMERAL)
784 {
785 /*
786 * Delete the slot. There is no !PANIC case where this is allowed to
787 * fail, all that may happen is an incomplete cleanup of the on-disk
788 * data.
789 */
791
792 /*
793 * Request to disable logical decoding, even though this slot may not
794 * have been the last logical slot. The checkpointer will verify if
795 * logical decoding should actually be disabled.
796 */
797 if (is_logical)
799 }
800
801 /*
802 * If slot needed to temporarily restrain both data and catalog xmin to
803 * create the catalog snapshot, remove that temporary constraint.
804 * Snapshots can only be exported while the initial snapshot is still
805 * acquired.
806 */
807 if (!TransactionIdIsValid(slot->data.xmin) &&
809 {
810 SpinLockAcquire(&slot->mutex);
812 SpinLockRelease(&slot->mutex);
814 }
815
816 /*
817 * Set the time since the slot has become inactive. We get the current
818 * time beforehand to avoid system call while holding the spinlock.
819 */
821
822 if (slot->data.persistency == RS_PERSISTENT)
823 {
824 /*
825 * Mark persistent slot inactive. We're not freeing it, just
826 * disconnecting, but wake up others that may be waiting for it.
827 */
828 SpinLockAcquire(&slot->mutex);
831 SpinLockRelease(&slot->mutex);
833 }
834 else
836
838
839 /* might not have been set when we've been a plain slot */
844
845 if (am_walsender)
846 {
849 ? errmsg("released logical replication slot \"%s\"",
850 slotname)
851 : errmsg("released physical replication slot \"%s\"",
852 slotname));
853
854 pfree(slotname);
855 }
856}
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1639
Datum now(PG_FUNCTION_ARGS)
Definition timestamp.c:1603
int64 TimestampTz
Definition timestamp.h:39
char * pstrdup(const char *in)
Definition mcxt.c:1781
PGPROC * MyProc
Definition proc.c:71
PROC_HDR * ProcGlobal
Definition proc.c:74
uint8 statusFlags
Definition proc.h:210
int pgxactoff
Definition proc.h:207
uint8 * statusFlags
Definition proc.h:456

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

Referenced by binary_upgrade_check_logical_slot_pending_wal(), binary_upgrade_create_conflict_detection_slot(), 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(), slotsync_failure_callback(), slotsync_worker_onexit(), StartLogicalReplication(), StartReplication(), synchronize_one_slot(), and WalSndErrorCleanup().

◆ ReplicationSlotReserveWal()

void ReplicationSlotReserveWal ( void  )
extern

Definition at line 1711 of file slot.c.

1712{
1714 XLogSegNo segno;
1715 XLogRecPtr restart_lsn;
1716
1717 Assert(slot != NULL);
1720
1721 /*
1722 * The replication slot mechanism is used to prevent the removal of
1723 * required WAL.
1724 *
1725 * Acquire an exclusive lock to prevent the checkpoint process from
1726 * concurrently computing the minimum slot LSN (see
1727 * CheckPointReplicationSlots). This ensures that the WAL reserved for
1728 * replication cannot be removed during a checkpoint.
1729 *
1730 * The mechanism is reliable because if WAL reservation occurs first, the
1731 * checkpoint must wait for the restart_lsn update before determining the
1732 * minimum non-removable LSN. On the other hand, if the checkpoint happens
1733 * first, subsequent WAL reservations will select positions at or beyond
1734 * the redo pointer of that checkpoint.
1735 */
1737
1738 /*
1739 * For logical slots log a standby snapshot and start logical decoding at
1740 * exactly that position. That allows the slot to start up more quickly.
1741 * But on a standby we cannot do WAL writes, so just use the replay
1742 * pointer; effectively, an attempt to create a logical slot on standby
1743 * will cause it to wait for an xl_running_xact record to be logged
1744 * independently on the primary, so that a snapshot can be built using the
1745 * record.
1746 *
1747 * None of this is needed (or indeed helpful) for physical slots as
1748 * they'll start replay at the last logged checkpoint anyway. Instead,
1749 * return the location of the last redo LSN, where a base backup has to
1750 * start replay at.
1751 */
1752 if (SlotIsPhysical(slot))
1753 restart_lsn = GetRedoRecPtr();
1754 else if (RecoveryInProgress())
1755 restart_lsn = GetXLogReplayRecPtr(NULL);
1756 else
1757 restart_lsn = GetXLogInsertRecPtr();
1758
1759 SpinLockAcquire(&slot->mutex);
1760 slot->data.restart_lsn = restart_lsn;
1761 SpinLockRelease(&slot->mutex);
1762
1763 /* prevent WAL removal as fast as possible */
1765
1766 /* Checkpoint shouldn't remove the required WAL. */
1768 if (XLogGetLastRemovedSegno() >= segno)
1769 elog(ERROR, "WAL required by replication slot %s has been removed concurrently",
1770 NameStr(slot->data.name));
1771
1773
1774 if (!RecoveryInProgress() && SlotIsLogical(slot))
1775 {
1777
1778 /* make sure we have enough information to start */
1780
1781 /* and make sure it's fsynced to disk */
1783 }
1784}
XLogRecPtr LogStandbySnapshot(Oid dbid)
Definition standby.c:1303
XLogSegNo XLogGetLastRemovedSegno(void)
Definition xlog.c:3813
XLogRecPtr GetRedoRecPtr(void)
Definition xlog.c:6933
XLogRecPtr GetXLogInsertRecPtr(void)
Definition xlog.c:10108
void XLogFlush(XLogRecPtr record)
Definition xlog.c:2801
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)
#define XLogRecPtrIsValid(r)
Definition xlogdefs.h:29
uint64 XLogSegNo
Definition xlogdefs.h:52
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)

References Assert, ReplicationSlot::data, elog, ERROR, fb(), GetRedoRecPtr(), GetXLogInsertRecPtr(), GetXLogReplayRecPtr(), InvalidOid, ReplicationSlot::last_saved_restart_lsn, LogStandbySnapshot(), LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), ReplicationSlot::mutex, MyReplicationSlot, ReplicationSlotPersistentData::name, NameStr, RecoveryInProgress(), ReplicationSlotsComputeRequiredLSN(), ReplicationSlotPersistentData::restart_lsn, SlotIsLogical, SlotIsPhysical, SpinLockAcquire(), SpinLockRelease(), wal_segment_size, XLByteToSeg, XLogFlush(), XLogGetLastRemovedSegno(), and XLogRecPtrIsValid.

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

◆ ReplicationSlotSave()

◆ ReplicationSlotsComputeLogicalRestartLSN()

XLogRecPtr ReplicationSlotsComputeLogicalRestartLSN ( void  )
extern

Definition at line 1378 of file slot.c.

1379{
1381 int i;
1382
1384 return InvalidXLogRecPtr;
1385
1387
1389 {
1390 ReplicationSlot *s;
1391 XLogRecPtr restart_lsn;
1392 XLogRecPtr last_saved_restart_lsn;
1393 bool invalidated;
1394 ReplicationSlotPersistency persistency;
1395
1397
1398 /* cannot change while ReplicationSlotCtlLock is held */
1399 if (!s->in_use)
1400 continue;
1401
1402 /* we're only interested in logical slots */
1403 if (!SlotIsLogical(s))
1404 continue;
1405
1406 /* read once, it's ok if it increases while we're checking */
1408 persistency = s->data.persistency;
1409 restart_lsn = s->data.restart_lsn;
1410 invalidated = s->data.invalidated != RS_INVAL_NONE;
1411 last_saved_restart_lsn = s->last_saved_restart_lsn;
1413
1414 /* invalidated slots need not apply */
1415 if (invalidated)
1416 continue;
1417
1418 /*
1419 * For persistent slot use last_saved_restart_lsn to compute the
1420 * oldest LSN for removal of WAL segments. The segments between
1421 * last_saved_restart_lsn and restart_lsn might be needed by a
1422 * persistent slot in the case of database crash. Non-persistent
1423 * slots can't survive the database crash, so we don't care about
1424 * last_saved_restart_lsn for them.
1425 */
1426 if (persistency == RS_PERSISTENT)
1427 {
1428 if (XLogRecPtrIsValid(last_saved_restart_lsn) &&
1429 restart_lsn > last_saved_restart_lsn)
1430 {
1431 restart_lsn = last_saved_restart_lsn;
1432 }
1433 }
1434
1435 if (!XLogRecPtrIsValid(restart_lsn))
1436 continue;
1437
1438 if (!XLogRecPtrIsValid(result) ||
1439 restart_lsn < result)
1440 result = restart_lsn;
1441 }
1442
1444
1445 return result;
1446}
uint32 result

References ReplicationSlot::data, fb(), i, ReplicationSlot::in_use, ReplicationSlotPersistentData::invalidated, InvalidXLogRecPtr, ReplicationSlot::last_saved_restart_lsn, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_repack_replication_slots, max_replication_slots, ReplicationSlot::mutex, ReplicationSlotPersistentData::persistency, ReplicationSlotCtlData::replication_slots, ReplicationSlotCtl, ReplicationSlotPersistentData::restart_lsn, result, RS_INVAL_NONE, RS_PERSISTENT, SlotIsLogical, SpinLockAcquire(), SpinLockRelease(), and XLogRecPtrIsValid.

Referenced by CheckPointLogicalRewriteHeap(), and CheckPointSnapBuild().

◆ ReplicationSlotsComputeRequiredLSN()

void ReplicationSlotsComputeRequiredLSN ( void  )
extern

Definition at line 1308 of file slot.c.

1309{
1310 int i;
1312
1314
1317 {
1319 XLogRecPtr restart_lsn;
1320 XLogRecPtr last_saved_restart_lsn;
1321 bool invalidated;
1322 ReplicationSlotPersistency persistency;
1323
1324 if (!s->in_use)
1325 continue;
1326
1328 persistency = s->data.persistency;
1329 restart_lsn = s->data.restart_lsn;
1330 invalidated = s->data.invalidated != RS_INVAL_NONE;
1331 last_saved_restart_lsn = s->last_saved_restart_lsn;
1333
1334 /* invalidated slots need not apply */
1335 if (invalidated)
1336 continue;
1337
1338 /*
1339 * For persistent slot use last_saved_restart_lsn to compute the
1340 * oldest LSN for removal of WAL segments. The segments between
1341 * last_saved_restart_lsn and restart_lsn might be needed by a
1342 * persistent slot in the case of database crash. Non-persistent
1343 * slots can't survive the database crash, so we don't care about
1344 * last_saved_restart_lsn for them.
1345 */
1346 if (persistency == RS_PERSISTENT)
1347 {
1348 if (XLogRecPtrIsValid(last_saved_restart_lsn) &&
1349 restart_lsn > last_saved_restart_lsn)
1350 {
1351 restart_lsn = last_saved_restart_lsn;
1352 }
1353 }
1354
1355 if (XLogRecPtrIsValid(restart_lsn) &&
1357 restart_lsn < min_required))
1358 min_required = restart_lsn;
1359 }
1361
1363}
void XLogSetReplicationSlotMinimumLSN(XLogRecPtr lsn)
Definition xlog.c:2687

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

Referenced by CheckPointReplicationSlots(), 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)
extern

Definition at line 1226 of file slot.c.

1227{
1228 int i;
1231
1236
1237 /*
1238 * Hold the ReplicationSlotControlLock until after updating the slot xmin
1239 * values, so no backend updates the initial xmin for newly created slot
1240 * concurrently. A shared lock is used here to minimize lock contention,
1241 * especially when many slots exist and advancements occur frequently.
1242 * This is safe since an exclusive lock is taken during initial slot xmin
1243 * update in slot creation.
1244 *
1245 * One might think that we can hold the ProcArrayLock exclusively and
1246 * update the slot xmin values, but it could increase lock contention on
1247 * the ProcArrayLock, which is not great since this function can be called
1248 * at non-negligible frequency.
1249 *
1250 * Concurrent invocation of this function may cause the computed slot xmin
1251 * to regress. However, this is harmless because tuples prior to the most
1252 * recent xmin are no longer useful once advancement occurs (see
1253 * LogicalConfirmReceivedLocation where the slot's xmin value is flushed
1254 * before updating the effective_xmin). Thus, such regression merely
1255 * prevents VACUUM from prematurely removing tuples without causing the
1256 * early deletion of required data.
1257 */
1258 if (!already_locked)
1260
1262 {
1264 TransactionId effective_xmin;
1265 TransactionId effective_catalog_xmin;
1266 bool invalidated;
1267
1268 if (!s->in_use)
1269 continue;
1270
1272 effective_xmin = s->effective_xmin;
1273 effective_catalog_xmin = s->effective_catalog_xmin;
1274 invalidated = s->data.invalidated != RS_INVAL_NONE;
1276
1277 /* invalidated slots need not apply */
1278 if (invalidated)
1279 continue;
1280
1281 /* check the data xmin */
1282 if (TransactionIdIsValid(effective_xmin) &&
1284 TransactionIdPrecedes(effective_xmin, agg_xmin)))
1285 agg_xmin = effective_xmin;
1286
1287 /* check the catalog xmin */
1288 if (TransactionIdIsValid(effective_catalog_xmin) &&
1290 TransactionIdPrecedes(effective_catalog_xmin, agg_catalog_xmin)))
1291 agg_catalog_xmin = effective_catalog_xmin;
1292 }
1293
1295
1296 if (!already_locked)
1298}
uint32 TransactionId
Definition c.h:736
bool LWLockHeldByMeInMode(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1929
void ProcArraySetReplicationSlotXmin(TransactionId xmin, TransactionId catalog_xmin, bool already_locked)
Definition procarray.c:3963
static bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition transam.h:263

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

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

◆ ReplicationSlotsCountDBSlots()

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

Definition at line 1457 of file slot.c.

1458{
1459 int i;
1460
1461 *nslots = *nactive = 0;
1462
1464 return false;
1465
1468 {
1469 ReplicationSlot *s;
1470
1472
1473 /* cannot change while ReplicationSlotCtlLock is held */
1474 if (!s->in_use)
1475 continue;
1476
1477 /* only logical slots are database specific, skip */
1478 if (!SlotIsLogical(s))
1479 continue;
1480
1481 /* not our database, skip */
1482 if (s->data.database != dboid)
1483 continue;
1484
1485 /* NB: intentionally counting invalidated slots */
1486
1487 /* count slots with spinlock held */
1489 (*nslots)++;
1491 (*nactive)++;
1493 }
1495
1496 if (*nslots > 0)
1497 return true;
1498 return false;
1499}

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

Referenced by dropdb().

◆ ReplicationSlotsDropDBSlots()

void ReplicationSlotsDropDBSlots ( Oid  dboid)
extern

Definition at line 1518 of file slot.c.

1519{
1520 int i;
1522 bool dropped = false;
1523
1525 return;
1526
1527restart:
1531 {
1532 ReplicationSlot *s;
1533 char *slotname;
1534 ProcNumber active_proc;
1535
1537
1538 /* cannot change while ReplicationSlotCtlLock is held */
1539 if (!s->in_use)
1540 continue;
1541
1542 /* only logical slots are database specific, skip */
1543 if (!SlotIsLogical(s))
1544 continue;
1545
1546 /*
1547 * Check logical slots on other databases too so we can disable
1548 * logical decoding only if no slots in the cluster.
1549 */
1553
1554 /* not our database, skip */
1555 if (s->data.database != dboid)
1556 continue;
1557
1558 /* NB: intentionally including invalidated slots to drop */
1559
1560 /* acquire slot, so ReplicationSlotDropAcquired can be reused */
1562 /* can't change while ReplicationSlotControlLock is held */
1563 slotname = NameStr(s->data.name);
1564 active_proc = s->active_proc;
1565 if (active_proc == INVALID_PROC_NUMBER)
1566 {
1569 }
1571
1572 /*
1573 * Even though we hold an exclusive lock on the database object a
1574 * logical slot for that DB can still be active, e.g. if it's
1575 * concurrently being dropped by a backend connected to another DB.
1576 *
1577 * That's fairly unlikely in practice, so we'll just bail out.
1578 *
1579 * The slot sync worker holds a shared lock on the database before
1580 * operating on synced logical slots to avoid conflict with the drop
1581 * happening here. The persistent synced slots are thus safe but there
1582 * is a possibility that the slot sync worker has created a temporary
1583 * slot (which stays active even on release) and we are trying to drop
1584 * that here. In practice, the chances of hitting this scenario are
1585 * less as during slot synchronization, the temporary slot is
1586 * immediately converted to persistent and thus is safe due to the
1587 * shared lock taken on the database. So, we'll just bail out in such
1588 * a case.
1589 *
1590 * XXX: We can consider shutting down the slot sync worker before
1591 * trying to drop synced temporary slots here.
1592 */
1593 if (active_proc != INVALID_PROC_NUMBER)
1594 ereport(ERROR,
1596 errmsg("replication slot \"%s\" is active for PID %d",
1597 slotname, GetPGProcByNumber(active_proc)->pid)));
1598
1599 /*
1600 * To avoid duplicating ReplicationSlotDropAcquired() and to avoid
1601 * holding ReplicationSlotControlLock over filesystem operations,
1602 * release ReplicationSlotControlLock and use
1603 * ReplicationSlotDropAcquired.
1604 *
1605 * As that means the set of slots could change, restart scan from the
1606 * beginning each time we release the lock.
1607 */
1610 dropped = true;
1611 goto restart;
1612 }
1614
1615 if (dropped && !found_valid_logicalslot)
1617}

References ReplicationSlot::active_proc, ReplicationSlot::data, ReplicationSlotPersistentData::database, ereport, errcode(), errmsg, ERROR, fb(), GetPGProcByNumber, i, ReplicationSlot::in_use, INVALID_PROC_NUMBER, ReplicationSlotPersistentData::invalidated, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_repack_replication_slots, max_replication_slots, ReplicationSlot::mutex, MyProcNumber, MyReplicationSlot, ReplicationSlotPersistentData::name, NameStr, ReplicationSlotCtlData::replication_slots, ReplicationSlotCtl, ReplicationSlotDropAcquired(), RequestDisableLogicalDecoding(), RS_INVAL_NONE, SlotIsLogical, SpinLockAcquire(), and SpinLockRelease().

Referenced by dbase_redo(), and dropdb().

◆ ReplicationSlotSetInactiveSince()

◆ ReplicationSlotValidateName()

bool ReplicationSlotValidateName ( const char name,
bool  allow_reserved_name,
int  elevel 
)
extern

Definition at line 265 of file slot.c.

267{
268 int err_code;
269 char *err_msg = NULL;
270 char *err_hint = NULL;
271
273 &err_code, &err_msg, &err_hint))
274 {
275 /*
276 * Use errmsg_internal() and errhint_internal() instead of errmsg()
277 * and errhint(), since the messages from
278 * ReplicationSlotValidateNameInternal() are already translated. This
279 * avoids double translation.
280 */
281 ereport(elevel,
283 errmsg_internal("%s", err_msg),
284 (err_hint != NULL) ? errhint_internal("%s", err_hint) : 0);
285
286 pfree(err_msg);
287 if (err_hint != NULL)
289 return false;
290 }
291
292 return true;
293}
int int errmsg_internal(const char *fmt,...) pg_attribute_printf(1
int int errhint_internal(const char *fmt,...) pg_attribute_printf(1
bool ReplicationSlotValidateNameInternal(const char *name, bool allow_reserved_name, int *err_code, char **err_msg, char **err_hint)
Definition slot.c:310

References ereport, errcode(), errhint_internal(), errmsg_internal(), fb(), name, pfree(), and ReplicationSlotValidateNameInternal().

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

◆ ReplicationSlotValidateNameInternal()

bool ReplicationSlotValidateNameInternal ( const char name,
bool  allow_reserved_name,
int err_code,
char **  err_msg,
char **  err_hint 
)
extern

Definition at line 310 of file slot.c.

312{
313 const char *cp;
314
315 if (strlen(name) == 0)
316 {
318 *err_msg = psprintf(_("replication slot name \"%s\" is too short"), name);
319 *err_hint = NULL;
320 return false;
321 }
322
323 if (strlen(name) >= NAMEDATALEN)
324 {
326 *err_msg = psprintf(_("replication slot name \"%s\" is too long"), name);
327 *err_hint = NULL;
328 return false;
329 }
330
331 for (cp = name; *cp; cp++)
332 {
333 if (!((*cp >= 'a' && *cp <= 'z')
334 || (*cp >= '0' && *cp <= '9')
335 || (*cp == '_')))
336 {
338 *err_msg = psprintf(_("replication slot name \"%s\" contains invalid character"), name);
339 *err_hint = psprintf(_("Replication slot names may only contain lower case letters, numbers, and the underscore character."));
340 return false;
341 }
342 }
343
345 {
347 *err_msg = psprintf(_("replication slot name \"%s\" is reserved"), name);
348 *err_hint = psprintf(_("The name \"%s\" is reserved for the conflict detection slot."),
350 return false;
351 }
352
353 return true;
354}
#define _(x)
Definition elog.c:95
#define NAMEDATALEN
char * psprintf(const char *fmt,...)
Definition psprintf.c:43
#define CONFLICT_DETECTION_SLOT
Definition slot.h:28

References _, CONFLICT_DETECTION_SLOT, fb(), IsSlotForConflictCheck(), name, NAMEDATALEN, and psprintf().

Referenced by check_primary_slot_name(), ReplicationSlotValidateName(), and validate_sync_standby_slots().

◆ SearchNamedReplicationSlot()

◆ SlotExistsInSyncStandbySlots()

bool SlotExistsInSyncStandbySlots ( const char slot_name)
extern

Definition at line 3080 of file slot.c.

3081{
3082 const char *standby_slot_name;
3083
3084 /* Return false if there is no value in synchronized_standby_slots */
3086 return false;
3087
3088 /*
3089 * XXX: We are not expecting this list to be long so a linear search
3090 * shouldn't hurt but if that turns out not to be true then we can cache
3091 * this information for each WalSender as well.
3092 */
3094 for (int i = 0; i < synchronized_standby_slots_config->nslotnames; i++)
3095 {
3096 if (strcmp(standby_slot_name, slot_name) == 0)
3097 return true;
3098
3100 }
3101
3102 return false;
3103}
static SyncStandbySlotsConfigData * synchronized_standby_slots_config
Definition slot.c:179
char slot_names[FLEXIBLE_ARRAY_MEMBER]
Definition slot.c:103

References fb(), i, SyncStandbySlotsConfigData::nslotnames, SyncStandbySlotsConfigData::slot_names, and synchronized_standby_slots_config.

Referenced by PhysicalWakeupLogicalWalSnd().

◆ StandbySlotsHaveCaughtup()

bool StandbySlotsHaveCaughtup ( XLogRecPtr  wait_for_lsn,
int  elevel 
)
extern

Definition at line 3113 of file slot.c.

3114{
3115 const char *name;
3116 int caught_up_slot_num = 0;
3118
3119 /*
3120 * Don't need to wait for the standbys to catch up if there is no value in
3121 * synchronized_standby_slots.
3122 */
3124 return true;
3125
3126 /*
3127 * Don't need to wait for the standbys to catch up if we are on a standby
3128 * server, since we do not support syncing slots to cascading standbys.
3129 */
3130 if (RecoveryInProgress())
3131 return true;
3132
3133 /*
3134 * Don't need to wait for the standbys to catch up if they are already
3135 * beyond the specified WAL location.
3136 */
3139 return true;
3140
3141 /*
3142 * To prevent concurrent slot dropping and creation while filtering the
3143 * slots, take the ReplicationSlotControlLock outside of the loop.
3144 */
3146
3148 for (int i = 0; i < synchronized_standby_slots_config->nslotnames; i++)
3149 {
3150 XLogRecPtr restart_lsn;
3151 bool invalidated;
3152 bool inactive;
3153 ReplicationSlot *slot;
3154
3155 slot = SearchNamedReplicationSlot(name, false);
3156
3157 /*
3158 * If a slot name provided in synchronized_standby_slots does not
3159 * exist, report a message and exit the loop.
3160 */
3161 if (!slot)
3162 {
3163 ereport(elevel,
3165 errmsg("replication slot \"%s\" specified in parameter \"%s\" does not exist",
3166 name, "synchronized_standby_slots"),
3167 errdetail("Logical replication is waiting on the standby associated with replication slot \"%s\".",
3168 name),
3169 errhint("Create the replication slot \"%s\" or amend parameter \"%s\".",
3170 name, "synchronized_standby_slots"));
3171 break;
3172 }
3173
3174 /* Same as above: if a slot is not physical, exit the loop. */
3175 if (SlotIsLogical(slot))
3176 {
3177 ereport(elevel,
3179 errmsg("cannot specify logical replication slot \"%s\" in parameter \"%s\"",
3180 name, "synchronized_standby_slots"),
3181 errdetail("Logical replication is waiting for correction on replication slot \"%s\".",
3182 name),
3183 errhint("Remove the logical replication slot \"%s\" from parameter \"%s\".",
3184 name, "synchronized_standby_slots"));
3185 break;
3186 }
3187
3188 SpinLockAcquire(&slot->mutex);
3189 restart_lsn = slot->data.restart_lsn;
3190 invalidated = slot->data.invalidated != RS_INVAL_NONE;
3192 SpinLockRelease(&slot->mutex);
3193
3194 if (invalidated)
3195 {
3196 /* Specified physical slot has been invalidated */
3197 ereport(elevel,
3199 errmsg("physical replication slot \"%s\" specified in parameter \"%s\" has been invalidated",
3200 name, "synchronized_standby_slots"),
3201 errdetail("Logical replication is waiting on the standby associated with replication slot \"%s\".",
3202 name),
3203 errhint("Drop and recreate the replication slot \"%s\", or amend parameter \"%s\".",
3204 name, "synchronized_standby_slots"));
3205 break;
3206 }
3207
3208 if (!XLogRecPtrIsValid(restart_lsn) || restart_lsn < wait_for_lsn)
3209 {
3210 /* Log a message if no active_pid for this physical slot */
3211 if (inactive)
3212 ereport(elevel,
3214 errmsg("replication slot \"%s\" specified in parameter \"%s\" does not have active_pid",
3215 name, "synchronized_standby_slots"),
3216 errdetail("Logical replication is waiting on the standby associated with replication slot \"%s\".",
3217 name),
3218 errhint("Start the standby associated with the replication slot \"%s\", or amend parameter \"%s\".",
3219 name, "synchronized_standby_slots"));
3220
3221 /* Continue if the current slot hasn't caught up. */
3222 break;
3223 }
3224
3225 Assert(restart_lsn >= wait_for_lsn);
3226
3228 min_restart_lsn > restart_lsn)
3229 min_restart_lsn = restart_lsn;
3230
3232
3233 name += strlen(name) + 1;
3234 }
3235
3237
3238 /*
3239 * Return false if not all the standbys have caught up to the specified
3240 * WAL location.
3241 */
3243 return false;
3244
3245 /* The ss_oldest_flush_lsn must not retreat. */
3248
3250
3251 return true;
3252}
static XLogRecPtr ss_oldest_flush_lsn
Definition slot.c:185

References ReplicationSlot::active_proc, Assert, ReplicationSlot::data, ereport, errcode(), errdetail(), errhint(), errmsg, fb(), i, INVALID_PROC_NUMBER, ReplicationSlotPersistentData::invalidated, InvalidXLogRecPtr, LW_SHARED, LWLockAcquire(), LWLockRelease(), ReplicationSlot::mutex, name, SyncStandbySlotsConfigData::nslotnames, RecoveryInProgress(), ReplicationSlotPersistentData::restart_lsn, RS_INVAL_NONE, SearchNamedReplicationSlot(), SyncStandbySlotsConfigData::slot_names, SlotIsLogical, SpinLockAcquire(), SpinLockRelease(), ss_oldest_flush_lsn, synchronized_standby_slots_config, and XLogRecPtrIsValid.

Referenced by NeedToWaitForStandbys(), and WaitForStandbyConfirmation().

◆ StartupReplicationSlots()

void StartupReplicationSlots ( void  )
extern

Definition at line 2402 of file slot.c.

2403{
2405 struct dirent *replication_de;
2406
2407 elog(DEBUG1, "starting up replication slots");
2408
2409 /* restore all slots by iterating over all on-disk entries */
2412 {
2413 char path[MAXPGPATH + sizeof(PG_REPLSLOT_DIR)];
2415
2416 if (strcmp(replication_de->d_name, ".") == 0 ||
2417 strcmp(replication_de->d_name, "..") == 0)
2418 continue;
2419
2420 snprintf(path, sizeof(path), "%s/%s", PG_REPLSLOT_DIR, replication_de->d_name);
2422
2423 /* we're only creating directories here, skip if it's not our's */
2425 continue;
2426
2427 /* we crashed while a slot was being setup or deleted, clean up */
2428 if (pg_str_endswith(replication_de->d_name, ".tmp"))
2429 {
2430 if (!rmtree(path, true))
2431 {
2433 (errmsg("could not remove directory \"%s\"",
2434 path)));
2435 continue;
2436 }
2438 continue;
2439 }
2440
2441 /* looks like a slot in a normal state, restore */
2443 }
2445
2446 /* currently no slots exist, we're done. */
2448 return;
2449
2450 /* Now that we have recovered all the data, compute replication xmin */
2453}
#define WARNING
Definition elog.h:37
int FreeDir(DIR *dir)
Definition fd.c:3009
void fsync_fname(const char *fname, bool isdir)
Definition fd.c:757
DIR * AllocateDir(const char *dirname)
Definition fd.c:2891
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition fd.c:2957
PGFileType get_dirent_type(const char *path, const struct dirent *de, bool look_through_symlinks, int elevel)
Definition file_utils.c:547
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:2687
bool pg_str_endswith(const char *str, const char *end)
Definition string.c:31
Definition dirent.c:26

References AllocateDir(), DEBUG1, elog, ereport, errmsg, fb(), FreeDir(), fsync_fname(), get_dirent_type(), max_repack_replication_slots, max_replication_slots, MAXPGPATH, PG_REPLSLOT_DIR, 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)
extern

Definition at line 3261 of file slot.c.

3262{
3263 /*
3264 * Don't need to wait for the standby to catch up if the current acquired
3265 * slot is not a logical failover slot, or there is no value in
3266 * synchronized_standby_slots.
3267 */
3269 return;
3270
3272
3273 for (;;)
3274 {
3276
3278 {
3279 ConfigReloadPending = false;
3281 }
3282
3283 /* Exit if done waiting for every slot. */
3285 break;
3286
3287 /*
3288 * Wait for the slots in the synchronized_standby_slots to catch up,
3289 * but use a timeout (1s) so we can also check if the
3290 * synchronized_standby_slots has been changed.
3291 */
3294 }
3295
3297}
bool ConditionVariableTimedSleep(ConditionVariable *cv, long timeout, uint32 wait_event_info)
void ProcessConfigFile(GucContext context)
Definition guc-file.l:120
@ PGC_SIGHUP
Definition guc.h:75
volatile sig_atomic_t ConfigReloadPending
Definition interrupt.c:27
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:125
bool StandbySlotsHaveCaughtup(XLogRecPtr wait_for_lsn, int elevel)
Definition slot.c:3113
ConditionVariable wal_confirm_rcv_cv
WalSndCtlData * WalSndCtl
Definition walsender.c:121

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

Referenced by LogicalSlotAdvanceAndCheckSnapState(), and pg_logical_slot_get_changes_guts().

Variable Documentation

◆ idle_replication_slot_timeout_secs

PGDLLIMPORT int idle_replication_slot_timeout_secs
extern

◆ max_repack_replication_slots

◆ max_replication_slots

◆ MyReplicationSlot

PGDLLIMPORT ReplicationSlot* MyReplicationSlot
extern

Definition at line 158 of file slot.c.

Referenced by abort_logical_decoding_activation(), ApplyLauncherMain(), binary_upgrade_check_logical_slot_pending_wal(), compute_min_nonremovable_xid(), copy_replication_slot(), create_logical_replication_slot(), create_physical_replication_slot(), CreateConflictDetectionSlot(), CreateDecodingContext(), CreateInitDecodingContext(), CreateReplicationSlot(), DisableLogicalDecodingIfNecessary(), EnsureLogicalDecodingEnabled(), init_conflict_slot_xmin(), InvalidatePossiblyObsoleteSlot(), LogicalConfirmReceivedLocation(), LogicalIncreaseRestartDecodingForSlot(), LogicalIncreaseXminForSlot(), logicalrep_worker_launch(), LogicalReplicationSlotCheckPendingWal(), 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(), slotsync_failure_callback(), slotsync_worker_onexit(), StartLogicalReplication(), StartReplication(), StartupDecodingContext(), synchronize_one_slot(), update_and_persist_local_synced_slot(), update_conflict_slot_xmin(), update_local_synced_slot(), update_slotsync_skip_stats(), WaitForStandbyConfirmation(), and WalSndErrorCleanup().

◆ ReplicationSlotCtl

◆ synchronized_standby_slots

PGDLLIMPORT char* synchronized_standby_slots
extern

Definition at line 176 of file slot.c.