PostgreSQL Source Code  git master
slot.c File Reference
#include "postgres.h"
#include <unistd.h>
#include <sys/stat.h>
#include "access/transam.h"
#include "access/xlog_internal.h"
#include "common/string.h"
#include "miscadmin.h"
#include "pgstat.h"
#include "replication/slot.h"
#include "storage/fd.h"
#include "storage/proc.h"
#include "storage/procarray.h"
#include "utils/builtins.h"
Include dependency graph for slot.c:

Go to the source code of this file.

Data Structures

struct  ReplicationSlotOnDisk
 

Macros

#define ReplicationSlotOnDiskConstantSize   offsetof(ReplicationSlotOnDisk, slotdata)
 
#define SnapBuildOnDiskNotChecksummedSize   offsetof(ReplicationSlotOnDisk, version)
 
#define SnapBuildOnDiskChecksummedSize   sizeof(ReplicationSlotOnDisk) - SnapBuildOnDiskNotChecksummedSize
 
#define ReplicationSlotOnDiskV2Size   sizeof(ReplicationSlotOnDisk) - ReplicationSlotOnDiskConstantSize
 
#define SLOT_MAGIC   0x1051CA1 /* format identifier */
 
#define SLOT_VERSION   2 /* version for new files */
 

Typedefs

typedef struct ReplicationSlotOnDisk ReplicationSlotOnDisk
 

Functions

static void ReplicationSlotDropAcquired (void)
 
static void ReplicationSlotDropPtr (ReplicationSlot *slot)
 
static void RestoreSlotFromDisk (const char *name)
 
static void CreateSlotOnDisk (ReplicationSlot *slot)
 
static void SaveSlotToPath (ReplicationSlot *slot, const char *path, int elevel)
 
Size ReplicationSlotsShmemSize (void)
 
void ReplicationSlotsShmemInit (void)
 
bool ReplicationSlotValidateName (const char *name, int elevel)
 
void ReplicationSlotCreate (const char *name, bool db_specific, ReplicationSlotPersistency persistency, bool two_phase)
 
ReplicationSlotSearchNamedReplicationSlot (const char *name, bool need_lock)
 
void ReplicationSlotAcquire (const char *name, bool nowait)
 
void ReplicationSlotRelease (void)
 
void ReplicationSlotCleanup (void)
 
void ReplicationSlotDrop (const char *name, bool nowait)
 
void ReplicationSlotSave (void)
 
void ReplicationSlotMarkDirty (void)
 
void ReplicationSlotPersist (void)
 
void ReplicationSlotsComputeRequiredXmin (bool already_locked)
 
void ReplicationSlotsComputeRequiredLSN (void)
 
XLogRecPtr ReplicationSlotsComputeLogicalRestartLSN (void)
 
bool ReplicationSlotsCountDBSlots (Oid dboid, int *nslots, int *nactive)
 
void ReplicationSlotsDropDBSlots (Oid dboid)
 
void CheckSlotRequirements (void)
 
void ReplicationSlotReserveWal (void)
 
static bool InvalidatePossiblyObsoleteSlot (ReplicationSlot *s, XLogRecPtr oldestLSN, bool *invalidated)
 
bool InvalidateObsoleteReplicationSlots (XLogSegNo oldestSegno)
 
void CheckPointReplicationSlots (void)
 
void StartupReplicationSlots (void)
 

Variables

ReplicationSlotCtlDataReplicationSlotCtl = NULL
 
ReplicationSlotMyReplicationSlot = NULL
 
int max_replication_slots = 0
 

Macro Definition Documentation

◆ ReplicationSlotOnDiskConstantSize

#define ReplicationSlotOnDiskConstantSize   offsetof(ReplicationSlotOnDisk, slotdata)

Definition at line 77 of file slot.c.

Referenced by RestoreSlotFromDisk().

◆ ReplicationSlotOnDiskV2Size

#define ReplicationSlotOnDiskV2Size   sizeof(ReplicationSlotOnDisk) - ReplicationSlotOnDiskConstantSize

Definition at line 86 of file slot.c.

Referenced by RestoreSlotFromDisk(), and SaveSlotToPath().

◆ SLOT_MAGIC

#define SLOT_MAGIC   0x1051CA1 /* format identifier */

Definition at line 89 of file slot.c.

Referenced by RestoreSlotFromDisk(), and SaveSlotToPath().

◆ SLOT_VERSION

#define SLOT_VERSION   2 /* version for new files */

Definition at line 90 of file slot.c.

Referenced by RestoreSlotFromDisk(), and SaveSlotToPath().

◆ SnapBuildOnDiskChecksummedSize

#define SnapBuildOnDiskChecksummedSize   sizeof(ReplicationSlotOnDisk) - SnapBuildOnDiskNotChecksummedSize

Definition at line 83 of file slot.c.

Referenced by RestoreSlotFromDisk(), and SaveSlotToPath().

◆ SnapBuildOnDiskNotChecksummedSize

#define SnapBuildOnDiskNotChecksummedSize   offsetof(ReplicationSlotOnDisk, version)

Definition at line 80 of file slot.c.

Referenced by RestoreSlotFromDisk(), and SaveSlotToPath().

Typedef Documentation

◆ ReplicationSlotOnDisk

Function Documentation

◆ CheckPointReplicationSlots()

void CheckPointReplicationSlots ( void  )

Definition at line 1348 of file slot.c.

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

Referenced by CheckPointGuts().

1349 {
1350  int i;
1351 
1352  elog(DEBUG1, "performing replication slot checkpoint");
1353 
1354  /*
1355  * Prevent any slot from being created/dropped while we're active. As we
1356  * explicitly do *not* want to block iterating over replication_slots or
1357  * acquiring a slot we cannot take the control lock - but that's OK,
1358  * because holding ReplicationSlotAllocationLock is strictly stronger, and
1359  * enough to guarantee that nobody can change the in_use bits on us.
1360  */
1361  LWLockAcquire(ReplicationSlotAllocationLock, LW_SHARED);
1362 
1363  for (i = 0; i < max_replication_slots; i++)
1364  {
1366  char path[MAXPGPATH];
1367 
1368  if (!s->in_use)
1369  continue;
1370 
1371  /* save the slot to disk, locking is handled in SaveSlotToPath() */
1372  sprintf(path, "pg_replslot/%s", NameStr(s->data.name));
1373  SaveSlotToPath(s, path, LOG);
1374  }
1375  LWLockRelease(ReplicationSlotAllocationLock);
1376 }
ReplicationSlotCtlData * ReplicationSlotCtl
Definition: slot.c:93
#define DEBUG1
Definition: elog.h:25
ReplicationSlotPersistentData data
Definition: slot.h:147
#define LOG
Definition: elog.h:26
static void SaveSlotToPath(ReplicationSlot *slot, const char *path, int elevel)
Definition: slot.c:1504
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#define sprintf
Definition: port.h:218
#define MAXPGPATH
bool in_use
Definition: slot.h:123
int max_replication_slots
Definition: slot.c:99
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
#define elog(elevel,...)
Definition: elog.h:232
int i
#define NameStr(name)
Definition: c.h:681
ReplicationSlot replication_slots[1]
Definition: slot.h:180

◆ CheckSlotRequirements()

void CheckSlotRequirements ( void  )

Definition at line 1044 of file slot.c.

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

1045 {
1046  /*
1047  * NB: Adding a new requirement likely means that RestoreSlotFromDisk()
1048  * needs the same check.
1049  */
1050 
1051  if (max_replication_slots == 0)
1052  ereport(ERROR,
1053  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1054  errmsg("replication slots can only be used if max_replication_slots > 0")));
1055 
1057  ereport(ERROR,
1058  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1059  errmsg("replication slots can only be used if wal_level >= replica")));
1060 }
int wal_level
Definition: xlog.c:108
int errcode(int sqlerrcode)
Definition: elog.c:698
#define ERROR
Definition: elog.h:46
#define ereport(elevel,...)
Definition: elog.h:157
int max_replication_slots
Definition: slot.c:99
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ CreateSlotOnDisk()

static void CreateSlotOnDisk ( ReplicationSlot slot)
static

Definition at line 1443 of file slot.c.

References ReplicationSlot::data, ReplicationSlot::dirty, END_CRIT_SECTION, ereport, errcode_for_file_access(), errmsg(), ERROR, fsync_fname(), MakePGDirectory(), MAXPGPATH, ReplicationSlotPersistentData::name, NameStr, rmtree(), S_ISDIR, SaveSlotToPath(), sprintf, stat::st_mode, START_CRIT_SECTION, and stat.

Referenced by ReplicationSlotCreate().

1444 {
1445  char tmppath[MAXPGPATH];
1446  char path[MAXPGPATH];
1447  struct stat st;
1448 
1449  /*
1450  * No need to take out the io_in_progress_lock, nobody else can see this
1451  * slot yet, so nobody else will write. We're reusing SaveSlotToPath which
1452  * takes out the lock, if we'd take the lock here, we'd deadlock.
1453  */
1454 
1455  sprintf(path, "pg_replslot/%s", NameStr(slot->data.name));
1456  sprintf(tmppath, "pg_replslot/%s.tmp", NameStr(slot->data.name));
1457 
1458  /*
1459  * It's just barely possible that some previous effort to create or drop a
1460  * slot with this name left a temp directory lying around. If that seems
1461  * to be the case, try to remove it. If the rmtree() fails, we'll error
1462  * out at the MakePGDirectory() below, so we don't bother checking
1463  * success.
1464  */
1465  if (stat(tmppath, &st) == 0 && S_ISDIR(st.st_mode))
1466  rmtree(tmppath, true);
1467 
1468  /* Create and fsync the temporary slot directory. */
1469  if (MakePGDirectory(tmppath) < 0)
1470  ereport(ERROR,
1472  errmsg("could not create directory \"%s\": %m",
1473  tmppath)));
1474  fsync_fname(tmppath, true);
1475 
1476  /* Write the actual state file. */
1477  slot->dirty = true; /* signal that we really need to write */
1478  SaveSlotToPath(slot, tmppath, ERROR);
1479 
1480  /* Rename the directory into place. */
1481  if (rename(tmppath, path) != 0)
1482  ereport(ERROR,
1484  errmsg("could not rename file \"%s\" to \"%s\": %m",
1485  tmppath, path)));
1486 
1487  /*
1488  * If we'd now fail - really unlikely - we wouldn't know whether this slot
1489  * would persist after an OS crash or not - so, force a restart. The
1490  * restart would try to fsync this again till it works.
1491  */
1493 
1494  fsync_fname(path, true);
1495  fsync_fname("pg_replslot", true);
1496 
1497  END_CRIT_SECTION();
1498 }
#define END_CRIT_SECTION()
Definition: miscadmin.h:149
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:666
#define START_CRIT_SECTION()
Definition: miscadmin.h:147
ReplicationSlotPersistentData data
Definition: slot.h:147
static void SaveSlotToPath(ReplicationSlot *slot, const char *path, int elevel)
Definition: slot.c:1504
#define sprintf
Definition: port.h:218
#define ERROR
Definition: elog.h:46
#define MAXPGPATH
int errcode_for_file_access(void)
Definition: elog.c:721
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:42
#define ereport(elevel,...)
Definition: elog.h:157
int MakePGDirectory(const char *directoryName)
Definition: fd.c:3735
#define S_ISDIR(m)
Definition: win32_port.h:316
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define NameStr(name)
Definition: c.h:681
bool dirty
Definition: slot.h:130
#define stat
Definition: win32_port.h:275

◆ InvalidateObsoleteReplicationSlots()

bool InvalidateObsoleteReplicationSlots ( XLogSegNo  oldestSegno)

Definition at line 1305 of file slot.c.

References i, ReplicationSlot::in_use, InvalidatePossiblyObsoleteSlot(), LW_SHARED, LWLockAcquire(), LWLockRelease(), max_replication_slots, ReplicationSlotCtlData::replication_slots, ReplicationSlotsComputeRequiredLSN(), ReplicationSlotsComputeRequiredXmin(), wal_segment_size, and XLogSegNoOffsetToRecPtr.

Referenced by CreateCheckPoint(), and CreateRestartPoint().

1306 {
1307  XLogRecPtr oldestLSN;
1308  bool invalidated = false;
1309 
1310  XLogSegNoOffsetToRecPtr(oldestSegno, 0, wal_segment_size, oldestLSN);
1311 
1312 restart:
1313  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
1314  for (int i = 0; i < max_replication_slots; i++)
1315  {
1317 
1318  if (!s->in_use)
1319  continue;
1320 
1321  if (InvalidatePossiblyObsoleteSlot(s, oldestLSN, &invalidated))
1322  {
1323  /* if the lock was released, start from scratch */
1324  goto restart;
1325  }
1326  }
1327  LWLockRelease(ReplicationSlotControlLock);
1328 
1329  /*
1330  * If any slots have been invalidated, recalculate the resource limits.
1331  */
1332  if (invalidated)
1333  {
1336  }
1337 
1338  return invalidated;
1339 }
ReplicationSlotCtlData * ReplicationSlotCtl
Definition: slot.c:93
int wal_segment_size
Definition: xlog.c:119
static bool InvalidatePossiblyObsoleteSlot(ReplicationSlot *s, XLogRecPtr oldestLSN, bool *invalidated)
Definition: slot.c:1152
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
void ReplicationSlotsComputeRequiredLSN(void)
Definition: slot.c:817
bool in_use
Definition: slot.h:123
int max_replication_slots
Definition: slot.c:99
#define XLogSegNoOffsetToRecPtr(segno, offset, wal_segsz_bytes, dest)
uint64 XLogRecPtr
Definition: xlogdefs.h:21
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
int i
ReplicationSlot replication_slots[1]
Definition: slot.h:180
void ReplicationSlotsComputeRequiredXmin(bool already_locked)
Definition: slot.c:767

◆ InvalidatePossiblyObsoleteSlot()

static bool InvalidatePossiblyObsoleteSlot ( ReplicationSlot s,
XLogRecPtr  oldestLSN,
bool invalidated 
)
static

Definition at line 1152 of file slot.c.

References ReplicationSlot::active_cv, ReplicationSlot::active_pid, Assert, ConditionVariablePrepareToSleep(), ConditionVariableSleep(), ReplicationSlot::data, ereport, errmsg(), ReplicationSlot::in_use, ReplicationSlotPersistentData::invalidated_at, InvalidXLogRecPtr, kill, LOG, LSN_FORMAT_ARGS, LW_SHARED, LWLockAcquire(), LWLockHeldByMe(), LWLockHeldByMeInMode(), LWLockRelease(), ReplicationSlot::mutex, MyProcPid, ReplicationSlotPersistentData::name, NameStr, ReplicationSlotMarkDirty(), ReplicationSlotRelease(), ReplicationSlotSave(), ReplicationSlotPersistentData::restart_lsn, SpinLockAcquire, SpinLockRelease, WAIT_EVENT_REPLICATION_SLOT_DROP, and XLogRecPtrIsInvalid.

Referenced by InvalidateObsoleteReplicationSlots().

1154 {
1155  int last_signaled_pid = 0;
1156  bool released_lock = false;
1157 
1158  for (;;)
1159  {
1160  XLogRecPtr restart_lsn;
1161  NameData slotname;
1162  int active_pid = 0;
1163 
1164  Assert(LWLockHeldByMeInMode(ReplicationSlotControlLock, LW_SHARED));
1165 
1166  if (!s->in_use)
1167  {
1168  if (released_lock)
1169  LWLockRelease(ReplicationSlotControlLock);
1170  break;
1171  }
1172 
1173  /*
1174  * Check if the slot needs to be invalidated. If it needs to be
1175  * invalidated, and is not currently acquired, acquire it and mark it
1176  * as having been invalidated. We do this with the spinlock held to
1177  * avoid race conditions -- for example the restart_lsn could move
1178  * forward, or the slot could be dropped.
1179  */
1180  SpinLockAcquire(&s->mutex);
1181 
1182  restart_lsn = s->data.restart_lsn;
1183 
1184  /*
1185  * If the slot is already invalid or is fresh enough, we don't need to
1186  * do anything.
1187  */
1188  if (XLogRecPtrIsInvalid(restart_lsn) || restart_lsn >= oldestLSN)
1189  {
1190  SpinLockRelease(&s->mutex);
1191  if (released_lock)
1192  LWLockRelease(ReplicationSlotControlLock);
1193  break;
1194  }
1195 
1196  slotname = s->data.name;
1197  active_pid = s->active_pid;
1198 
1199  /*
1200  * If the slot can be acquired, do so and mark it invalidated
1201  * immediately. Otherwise we'll signal the owning process, below, and
1202  * retry.
1203  */
1204  if (active_pid == 0)
1205  {
1206  MyReplicationSlot = s;
1207  s->active_pid = MyProcPid;
1208  s->data.invalidated_at = restart_lsn;
1210 
1211  /* Let caller know */
1212  *invalidated = true;
1213  }
1214 
1215  SpinLockRelease(&s->mutex);
1216 
1217  if (active_pid != 0)
1218  {
1219  /*
1220  * Prepare the sleep on the slot's condition variable before
1221  * releasing the lock, to close a possible race condition if the
1222  * slot is released before the sleep below.
1223  */
1225 
1226  LWLockRelease(ReplicationSlotControlLock);
1227  released_lock = true;
1228 
1229  /*
1230  * Signal to terminate the process that owns the slot, if we
1231  * haven't already signalled it. (Avoidance of repeated
1232  * signalling is the only reason for there to be a loop in this
1233  * routine; otherwise we could rely on caller's restart loop.)
1234  *
1235  * There is the race condition that other process may own the slot
1236  * after its current owner process is terminated and before this
1237  * process owns it. To handle that, we signal only if the PID of
1238  * the owning process has changed from the previous time. (This
1239  * logic assumes that the same PID is not reused very quickly.)
1240  */
1241  if (last_signaled_pid != active_pid)
1242  {
1243  ereport(LOG,
1244  (errmsg("terminating process %d to release replication slot \"%s\"",
1245  active_pid, NameStr(slotname))));
1246 
1247  (void) kill(active_pid, SIGTERM);
1248  last_signaled_pid = active_pid;
1249  }
1250 
1251  /* Wait until the slot is released. */
1254 
1255  /*
1256  * Re-acquire lock and start over; we expect to invalidate the
1257  * slot next time (unless another process acquires the slot in the
1258  * meantime).
1259  */
1260  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
1261  continue;
1262  }
1263  else
1264  {
1265  /*
1266  * We hold the slot now and have already invalidated it; flush it
1267  * to ensure that state persists.
1268  *
1269  * Don't want to hold ReplicationSlotControlLock across file
1270  * system operations, so release it now but be sure to tell caller
1271  * to restart from scratch.
1272  */
1273  LWLockRelease(ReplicationSlotControlLock);
1274  released_lock = true;
1275 
1276  /* Make sure the invalidated state persists across server restart */
1280 
1281  ereport(LOG,
1282  (errmsg("invalidating slot \"%s\" because its restart_lsn %X/%X exceeds max_slot_wal_keep_size",
1283  NameStr(slotname),
1284  LSN_FORMAT_ARGS(restart_lsn))));
1285 
1286  /* done with this slot for now */
1287  break;
1288  }
1289  }
1290 
1291  Assert(released_lock == !LWLockHeldByMe(ReplicationSlotControlLock));
1292 
1293  return released_lock;
1294 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1937
int MyProcPid
Definition: globals.c:43
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1919
#define kill(pid, sig)
Definition: win32_port.h:454
void ReplicationSlotSave(void)
Definition: slot.c:710
ReplicationSlotPersistentData data
Definition: slot.h:147
#define LOG
Definition: elog.h:26
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
void ConditionVariablePrepareToSleep(ConditionVariable *cv)
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
Definition: c.h:675
void ReplicationSlotRelease(void)
Definition: slot.c:469
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
bool in_use
Definition: slot.h:123
#define SpinLockRelease(lock)
Definition: spin.h:64
#define ereport(elevel,...)
Definition: elog.h:157
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
void ConditionVariableSleep(ConditionVariable *cv, uint32 wait_event_info)
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:804
XLogRecPtr restart_lsn
Definition: slot.h:73
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
ConditionVariable active_cv
Definition: slot.h:153
int errmsg(const char *fmt,...)
Definition: elog.c:909
pid_t active_pid
Definition: slot.h:126
#define NameStr(name)
Definition: c.h:681
XLogRecPtr invalidated_at
Definition: slot.h:76
slock_t mutex
Definition: slot.h:120
void ReplicationSlotMarkDirty(void)
Definition: slot.c:728

◆ ReplicationSlotAcquire()

void ReplicationSlotAcquire ( const char *  name,
bool  nowait 
)

Definition at line 380 of file slot.c.

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

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

381 {
382  ReplicationSlot *s;
383  int active_pid;
384 
385  AssertArg(name != NULL);
386 
387 retry:
388  Assert(MyReplicationSlot == NULL);
389 
390  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
391 
392  /*
393  * Search for the slot with the specified name if the slot to acquire is
394  * not given. If the slot is not found, we either return -1 or error out.
395  */
396  s = SearchNamedReplicationSlot(name, false);
397  if (s == NULL || !s->in_use)
398  {
399  LWLockRelease(ReplicationSlotControlLock);
400 
401  ereport(ERROR,
402  (errcode(ERRCODE_UNDEFINED_OBJECT),
403  errmsg("replication slot \"%s\" does not exist",
404  name)));
405  }
406 
407  /*
408  * This is the slot we want; check if it's active under some other
409  * process. In single user mode, we don't need this check.
410  */
411  if (IsUnderPostmaster)
412  {
413  /*
414  * Get ready to sleep on the slot in case it is active. (We may end
415  * up not sleeping, but we don't want to do this while holding the
416  * spinlock.)
417  */
418  if (!nowait)
420 
421  SpinLockAcquire(&s->mutex);
422  if (s->active_pid == 0)
423  s->active_pid = MyProcPid;
424  active_pid = s->active_pid;
425  SpinLockRelease(&s->mutex);
426  }
427  else
428  active_pid = MyProcPid;
429  LWLockRelease(ReplicationSlotControlLock);
430 
431  /*
432  * If we found the slot but it's already active in another process, we
433  * wait until the owning process signals us that it's been released, or
434  * error out.
435  */
436  if (active_pid != MyProcPid)
437  {
438  if (!nowait)
439  {
440  /* Wait here until we get signaled, and then restart */
444  goto retry;
445  }
446 
447  ereport(ERROR,
448  (errcode(ERRCODE_OBJECT_IN_USE),
449  errmsg("replication slot \"%s\" is active for PID %d",
450  NameStr(s->data.name), active_pid)));
451  }
452  else if (!nowait)
453  ConditionVariableCancelSleep(); /* no sleep needed after all */
454 
455  /* Let everybody know we've modified this slot */
457 
458  /* We made this slot active, so it's ours now. */
459  MyReplicationSlot = s;
460 }
ReplicationSlot * SearchNamedReplicationSlot(const char *name, bool need_lock)
Definition: slot.c:348
int MyProcPid
Definition: globals.c:43
void ConditionVariableBroadcast(ConditionVariable *cv)
int errcode(int sqlerrcode)
Definition: elog.c:698
ReplicationSlotPersistentData data
Definition: slot.h:147
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
void ConditionVariablePrepareToSleep(ConditionVariable *cv)
#define SpinLockAcquire(lock)
Definition: spin.h:62
void ConditionVariableCancelSleep(void)
#define ERROR
Definition: elog.h:46
bool IsUnderPostmaster
Definition: globals.c:112
#define AssertArg(condition)
Definition: c.h:806
bool in_use
Definition: slot.h:123
#define SpinLockRelease(lock)
Definition: spin.h:64
#define ereport(elevel,...)
Definition: elog.h:157
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
void ConditionVariableSleep(ConditionVariable *cv, uint32 wait_event_info)
#define Assert(condition)
Definition: c.h:804
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
ConditionVariable active_cv
Definition: slot.h:153
const char * name
Definition: encode.c:515
int errmsg(const char *fmt,...)
Definition: elog.c:909
pid_t active_pid
Definition: slot.h:126
#define NameStr(name)
Definition: c.h:681
slock_t mutex
Definition: slot.h:120

◆ ReplicationSlotCleanup()

void ReplicationSlotCleanup ( void  )

Definition at line 525 of file slot.c.

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, ReplicationSlotPersistentData::persistency, ReplicationSlotCtlData::replication_slots, ReplicationSlotDropPtr(), RS_TEMPORARY, SpinLockAcquire, and SpinLockRelease.

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

526 {
527  int i;
528 
529  Assert(MyReplicationSlot == NULL);
530 
531 restart:
532  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
533  for (i = 0; i < max_replication_slots; i++)
534  {
536 
537  if (!s->in_use)
538  continue;
539 
540  SpinLockAcquire(&s->mutex);
541  if (s->active_pid == MyProcPid)
542  {
544  SpinLockRelease(&s->mutex);
545  LWLockRelease(ReplicationSlotControlLock); /* avoid deadlock */
546 
548 
550  goto restart;
551  }
552  else
553  SpinLockRelease(&s->mutex);
554  }
555 
556  LWLockRelease(ReplicationSlotControlLock);
557 }
ReplicationSlotCtlData * ReplicationSlotCtl
Definition: slot.c:93
int MyProcPid
Definition: globals.c:43
ReplicationSlotPersistency persistency
Definition: slot.h:54
void ConditionVariableBroadcast(ConditionVariable *cv)
static void ReplicationSlotDropPtr(ReplicationSlot *slot)
Definition: slot.c:593
ReplicationSlotPersistentData data
Definition: slot.h:147
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#define SpinLockAcquire(lock)
Definition: spin.h:62
bool in_use
Definition: slot.h:123
#define SpinLockRelease(lock)
Definition: spin.h:64
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
int max_replication_slots
Definition: slot.c:99
#define Assert(condition)
Definition: c.h:804
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
ConditionVariable active_cv
Definition: slot.h:153
pid_t active_pid
Definition: slot.h:126
int i
ReplicationSlot replication_slots[1]
Definition: slot.h:180
slock_t mutex
Definition: slot.h:120

◆ ReplicationSlotCreate()

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

Definition at line 226 of file slot.c.

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, ReplicationSlotPersistentData::name, NameStr, namestrcpy(), ReplicationSlotPersistentData::persistency, pgstat_report_replslot_create(), ReplicationSlotCtlData::replication_slots, 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().

228 {
229  ReplicationSlot *slot = NULL;
230  int i;
231 
232  Assert(MyReplicationSlot == NULL);
233 
235 
236  /*
237  * If some other backend ran this code concurrently with us, we'd likely
238  * both allocate the same slot, and that would be bad. We'd also be at
239  * risk of missing a name collision. Also, we don't want to try to create
240  * a new slot while somebody's busy cleaning up an old one, because we
241  * might both be monkeying with the same directory.
242  */
243  LWLockAcquire(ReplicationSlotAllocationLock, LW_EXCLUSIVE);
244 
245  /*
246  * Check for name collision, and identify an allocatable slot. We need to
247  * hold ReplicationSlotControlLock in shared mode for this, so that nobody
248  * else can change the in_use flags while we're looking at them.
249  */
250  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
251  for (i = 0; i < max_replication_slots; i++)
252  {
254 
255  if (s->in_use && strcmp(name, NameStr(s->data.name)) == 0)
256  ereport(ERROR,
258  errmsg("replication slot \"%s\" already exists", name)));
259  if (!s->in_use && slot == NULL)
260  slot = s;
261  }
262  LWLockRelease(ReplicationSlotControlLock);
263 
264  /* If all slots are in use, we're out of luck. */
265  if (slot == NULL)
266  ereport(ERROR,
267  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
268  errmsg("all replication slots are in use"),
269  errhint("Free one or increase max_replication_slots.")));
270 
271  /*
272  * Since this slot is not in use, nobody should be looking at any part of
273  * it other than the in_use field unless they're trying to allocate it.
274  * And since we hold ReplicationSlotAllocationLock, nobody except us can
275  * be doing that. So it's safe to initialize the slot.
276  */
277  Assert(!slot->in_use);
278  Assert(slot->active_pid == 0);
279 
280  /* first initialize persistent data */
281  memset(&slot->data, 0, sizeof(ReplicationSlotPersistentData));
282  namestrcpy(&slot->data.name, name);
283  slot->data.database = db_specific ? MyDatabaseId : InvalidOid;
284  slot->data.persistency = persistency;
285  slot->data.two_phase = two_phase;
287 
288  /* and then data only present in shared memory */
289  slot->just_dirtied = false;
290  slot->dirty = false;
297 
298  /*
299  * Create the slot on disk. We haven't actually marked the slot allocated
300  * yet, so no special cleanup is required if this errors out.
301  */
302  CreateSlotOnDisk(slot);
303 
304  /*
305  * We need to briefly prevent any other backend from iterating over the
306  * slots while we flip the in_use flag. We also need to set the active
307  * flag while holding the ControlLock as otherwise a concurrent
308  * ReplicationSlotAcquire() could acquire the slot as well.
309  */
310  LWLockAcquire(ReplicationSlotControlLock, LW_EXCLUSIVE);
311 
312  slot->in_use = true;
313 
314  /* We can now mark the slot active, and that makes it our slot. */
315  SpinLockAcquire(&slot->mutex);
316  Assert(slot->active_pid == 0);
317  slot->active_pid = MyProcPid;
318  SpinLockRelease(&slot->mutex);
319  MyReplicationSlot = slot;
320 
321  LWLockRelease(ReplicationSlotControlLock);
322 
323  /*
324  * Create statistics entry for the new logical slot. We don't collect any
325  * stats for physical slots, so no need to create an entry for the same.
326  * See ReplicationSlotDropPtr for why we need to do this before releasing
327  * ReplicationSlotAllocationLock.
328  */
329  if (SlotIsLogical(slot))
331 
332  /*
333  * Now that the slot has been marked as in_use and active, it's safe to
334  * let somebody else try to allocate a slot.
335  */
336  LWLockRelease(ReplicationSlotAllocationLock);
337 
338  /* Let everybody know we've modified this slot */
340 }
ReplicationSlotCtlData * ReplicationSlotCtl
Definition: slot.c:93
TransactionId candidate_catalog_xmin
Definition: slot.h:162
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
int MyProcPid
Definition: globals.c:43
int errhint(const char *fmt,...)
Definition: elog.c:1156
void namestrcpy(Name name, const char *str)
Definition: name.c:233
ReplicationSlotPersistency persistency
Definition: slot.h:54
void ConditionVariableBroadcast(ConditionVariable *cv)
int errcode(int sqlerrcode)
Definition: elog.c:698
ReplicationSlotPersistentData data
Definition: slot.h:147
static void CreateSlotOnDisk(ReplicationSlot *slot)
Definition: slot.c:1443
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
bool ReplicationSlotValidateName(const char *name, int elevel)
Definition: slot.c:172
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define ERROR
Definition: elog.h:46
TransactionId effective_xmin
Definition: slot.h:143
XLogRecPtr candidate_restart_valid
Definition: slot.h:164
#define InvalidTransactionId
Definition: transam.h:31
#define SlotIsLogical(slot)
Definition: slot.h:169
bool in_use
Definition: slot.h:123
#define SpinLockRelease(lock)
Definition: spin.h:64
bool just_dirtied
Definition: slot.h:129
TransactionId effective_catalog_xmin
Definition: slot.h:144
Oid MyDatabaseId
Definition: globals.c:88
static bool two_phase
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
int max_replication_slots
Definition: slot.c:99
#define Assert(condition)
Definition: c.h:804
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
ConditionVariable active_cv
Definition: slot.h:153
const char * name
Definition: encode.c:515
XLogRecPtr candidate_xmin_lsn
Definition: slot.h:163
void pgstat_report_replslot_create(const char *slotname)
Definition: pgstat.c:1837
int errmsg(const char *fmt,...)
Definition: elog.c:909
pid_t active_pid
Definition: slot.h:126
int i
#define NameStr(name)
Definition: c.h:681
ReplicationSlot replication_slots[1]
Definition: slot.h:180
slock_t mutex
Definition: slot.h:120
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
bool dirty
Definition: slot.h:130
XLogRecPtr candidate_restart_lsn
Definition: slot.h:165
XLogRecPtr two_phase_at
Definition: slot.h:90

◆ ReplicationSlotDrop()

void ReplicationSlotDrop ( const char *  name,
bool  nowait 
)

Definition at line 563 of file slot.c.

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

Referenced by DropReplicationSlot(), and pg_drop_replication_slot().

564 {
565  Assert(MyReplicationSlot == NULL);
566 
567  ReplicationSlotAcquire(name, nowait);
568 
570 }
void ReplicationSlotAcquire(const char *name, bool nowait)
Definition: slot.c:380
static void ReplicationSlotDropAcquired(void)
Definition: slot.c:576
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
#define Assert(condition)
Definition: c.h:804
const char * name
Definition: encode.c:515

◆ ReplicationSlotDropAcquired()

static void ReplicationSlotDropAcquired ( void  )
static

Definition at line 576 of file slot.c.

References Assert, MyReplicationSlot, and ReplicationSlotDropPtr().

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

577 {
579 
580  Assert(MyReplicationSlot != NULL);
581 
582  /* slot isn't acquired anymore */
583  MyReplicationSlot = NULL;
584 
586 }
static void ReplicationSlotDropPtr(ReplicationSlot *slot)
Definition: slot.c:593
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
#define Assert(condition)
Definition: c.h:804

◆ ReplicationSlotDropPtr()

static void ReplicationSlotDropPtr ( ReplicationSlot slot)
static

Definition at line 593 of file slot.c.

References ReplicationSlot::active_cv, ReplicationSlot::active_pid, ConditionVariableBroadcast(), ReplicationSlot::data, END_CRIT_SECTION, ereport, errcode_for_file_access(), errmsg(), ERROR, fsync_fname(), ReplicationSlot::in_use, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), MAXPGPATH, ReplicationSlot::mutex, ReplicationSlotPersistentData::name, NameStr, ReplicationSlotPersistentData::persistency, pgstat_report_replslot_drop(), ReplicationSlotsComputeRequiredLSN(), ReplicationSlotsComputeRequiredXmin(), rmtree(), RS_PERSISTENT, SlotIsLogical, SpinLockAcquire, SpinLockRelease, sprintf, START_CRIT_SECTION, and WARNING.

Referenced by ReplicationSlotCleanup(), and ReplicationSlotDropAcquired().

594 {
595  char path[MAXPGPATH];
596  char tmppath[MAXPGPATH];
597 
598  /*
599  * If some other backend ran this code concurrently with us, we might try
600  * to delete a slot with a certain name while someone else was trying to
601  * create a slot with the same name.
602  */
603  LWLockAcquire(ReplicationSlotAllocationLock, LW_EXCLUSIVE);
604 
605  /* Generate pathnames. */
606  sprintf(path, "pg_replslot/%s", NameStr(slot->data.name));
607  sprintf(tmppath, "pg_replslot/%s.tmp", NameStr(slot->data.name));
608 
609  /*
610  * Rename the slot directory on disk, so that we'll no longer recognize
611  * this as a valid slot. Note that if this fails, we've got to mark the
612  * slot inactive before bailing out. If we're dropping an ephemeral or a
613  * temporary slot, we better never fail hard as the caller won't expect
614  * the slot to survive and this might get called during error handling.
615  */
616  if (rename(path, tmppath) == 0)
617  {
618  /*
619  * We need to fsync() the directory we just renamed and its parent to
620  * make sure that our changes are on disk in a crash-safe fashion. If
621  * fsync() fails, we can't be sure whether the changes are on disk or
622  * not. For now, we handle that by panicking;
623  * StartupReplicationSlots() will try to straighten it out after
624  * restart.
625  */
627  fsync_fname(tmppath, true);
628  fsync_fname("pg_replslot", true);
630  }
631  else
632  {
633  bool fail_softly = slot->data.persistency != RS_PERSISTENT;
634 
635  SpinLockAcquire(&slot->mutex);
636  slot->active_pid = 0;
637  SpinLockRelease(&slot->mutex);
638 
639  /* wake up anyone waiting on this slot */
641 
642  ereport(fail_softly ? WARNING : ERROR,
644  errmsg("could not rename file \"%s\" to \"%s\": %m",
645  path, tmppath)));
646  }
647 
648  /*
649  * The slot is definitely gone. Lock out concurrent scans of the array
650  * long enough to kill it. It's OK to clear the active PID here without
651  * grabbing the mutex because nobody else can be scanning the array here,
652  * and nobody can be attached to this slot and thus access it without
653  * scanning the array.
654  *
655  * Also wake up processes waiting for it.
656  */
657  LWLockAcquire(ReplicationSlotControlLock, LW_EXCLUSIVE);
658  slot->active_pid = 0;
659  slot->in_use = false;
660  LWLockRelease(ReplicationSlotControlLock);
662 
663  /*
664  * Slot is dead and doesn't prevent resource removal anymore, recompute
665  * limits.
666  */
669 
670  /*
671  * If removing the directory fails, the worst thing that will happen is
672  * that the user won't be able to create a new slot with the same name
673  * until the next server restart. We warn about it, but that's all.
674  */
675  if (!rmtree(tmppath, true))
677  (errmsg("could not remove directory \"%s\"", tmppath)));
678 
679  /*
680  * Send a message to drop the replication slot to the stats collector.
681  * Since there is no guarantee of the order of message transfer on a UDP
682  * connection, it's possible that a message for creating a new slot
683  * reaches before a message for removing the old slot. We send the drop
684  * and create messages while holding ReplicationSlotAllocationLock to
685  * reduce that possibility. If the messages reached in reverse, we would
686  * lose one statistics update message. But the next update message will
687  * create the statistics for the replication slot.
688  *
689  * XXX In case, the messages for creation and drop slot of the same name
690  * get lost and create happens before (auto)vacuum cleans up the dead
691  * slot, the stats will be accumulated into the old slot. One can imagine
692  * having OIDs for each slot to avoid the accumulation of stats but that
693  * doesn't seem worth doing as in practice this won't happen frequently.
694  */
695  if (SlotIsLogical(slot))
697 
698  /*
699  * We release this at the very end, so that nobody starts trying to create
700  * a slot while we're still cleaning up the detritus of the old one.
701  */
702  LWLockRelease(ReplicationSlotAllocationLock);
703 }
#define END_CRIT_SECTION()
Definition: miscadmin.h:149
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:666
ReplicationSlotPersistency persistency
Definition: slot.h:54
#define START_CRIT_SECTION()
Definition: miscadmin.h:147
void ConditionVariableBroadcast(ConditionVariable *cv)
ReplicationSlotPersistentData data
Definition: slot.h:147
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#define sprintf
Definition: port.h:218
#define SpinLockAcquire(lock)
Definition: spin.h:62
void ReplicationSlotsComputeRequiredLSN(void)
Definition: slot.c:817
#define ERROR
Definition: elog.h:46
#define MAXPGPATH
int errcode_for_file_access(void)
Definition: elog.c:721
#define SlotIsLogical(slot)
Definition: slot.h:169
#define WARNING
Definition: elog.h:40
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:42
bool in_use
Definition: slot.h:123
#define SpinLockRelease(lock)
Definition: spin.h:64
#define ereport(elevel,...)
Definition: elog.h:157
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
ConditionVariable active_cv
Definition: slot.h:153
void pgstat_report_replslot_drop(const char *slotname)
Definition: pgstat.c:1855
int errmsg(const char *fmt,...)
Definition: elog.c:909
pid_t active_pid
Definition: slot.h:126
#define NameStr(name)
Definition: c.h:681
slock_t mutex
Definition: slot.h:120
void ReplicationSlotsComputeRequiredXmin(bool already_locked)
Definition: slot.c:767

◆ ReplicationSlotMarkDirty()

◆ ReplicationSlotPersist()

void ReplicationSlotPersist ( void  )

Definition at line 745 of file slot.c.

References Assert, ReplicationSlot::data, ReplicationSlot::mutex, MyReplicationSlot, ReplicationSlotPersistentData::persistency, ReplicationSlotMarkDirty(), ReplicationSlotSave(), RS_PERSISTENT, SpinLockAcquire, and SpinLockRelease.

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

746 {
748 
749  Assert(slot != NULL);
751 
752  SpinLockAcquire(&slot->mutex);
754  SpinLockRelease(&slot->mutex);
755 
758 }
ReplicationSlotPersistency persistency
Definition: slot.h:54
void ReplicationSlotSave(void)
Definition: slot.c:710
ReplicationSlotPersistentData data
Definition: slot.h:147
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
#define Assert(condition)
Definition: c.h:804
slock_t mutex
Definition: slot.h:120
void ReplicationSlotMarkDirty(void)
Definition: slot.c:728

◆ ReplicationSlotRelease()

void ReplicationSlotRelease ( void  )

Definition at line 469 of file slot.c.

References ReplicationSlot::active_cv, ReplicationSlot::active_pid, Assert, ConditionVariableBroadcast(), ReplicationSlot::data, ReplicationSlot::effective_xmin, InvalidTransactionId, LW_SHARED, 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(), ProcKill(), StartLogicalReplication(), StartReplication(), and WalSndErrorCleanup().

470 {
472 
473  Assert(slot != NULL && slot->active_pid != 0);
474 
475  if (slot->data.persistency == RS_EPHEMERAL)
476  {
477  /*
478  * Delete the slot. There is no !PANIC case where this is allowed to
479  * fail, all that may happen is an incomplete cleanup of the on-disk
480  * data.
481  */
483  }
484 
485  /*
486  * If slot needed to temporarily restrain both data and catalog xmin to
487  * create the catalog snapshot, remove that temporary constraint.
488  * Snapshots can only be exported while the initial snapshot is still
489  * acquired.
490  */
491  if (!TransactionIdIsValid(slot->data.xmin) &&
493  {
494  SpinLockAcquire(&slot->mutex);
496  SpinLockRelease(&slot->mutex);
498  }
499 
500  if (slot->data.persistency == RS_PERSISTENT)
501  {
502  /*
503  * Mark persistent slot inactive. We're not freeing it, just
504  * disconnecting, but wake up others that may be waiting for it.
505  */
506  SpinLockAcquire(&slot->mutex);
507  slot->active_pid = 0;
508  SpinLockRelease(&slot->mutex);
510  }
511 
512  MyReplicationSlot = NULL;
513 
514  /* might not have been set when we've been a plain slot */
515  LWLockAcquire(ProcArrayLock, LW_SHARED);
518  LWLockRelease(ProcArrayLock);
519 }
#define PROC_IN_LOGICAL_DECODING
Definition: proc.h:61
PGPROC * MyProc
Definition: proc.c:68
ReplicationSlotPersistency persistency
Definition: slot.h:54
void ConditionVariableBroadcast(ConditionVariable *cv)
PROC_HDR * ProcGlobal
Definition: proc.c:80
uint8 statusFlags
Definition: proc.h:189
ReplicationSlotPersistentData data
Definition: slot.h:147
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#define SpinLockAcquire(lock)
Definition: spin.h:62
static void ReplicationSlotDropAcquired(void)
Definition: slot.c:576
TransactionId effective_xmin
Definition: slot.h:143
#define InvalidTransactionId
Definition: transam.h:31
TransactionId xmin
Definition: slot.h:62
#define SpinLockRelease(lock)
Definition: spin.h:64
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
#define Assert(condition)
Definition: c.h:804
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
ConditionVariable active_cv
Definition: slot.h:153
pid_t active_pid
Definition: slot.h:126
int pgxactoff
Definition: proc.h:148
uint8 * statusFlags
Definition: proc.h:333
slock_t mutex
Definition: slot.h:120
#define TransactionIdIsValid(xid)
Definition: transam.h:41
void ReplicationSlotsComputeRequiredXmin(bool already_locked)
Definition: slot.c:767

◆ ReplicationSlotReserveWal()

void ReplicationSlotReserveWal ( void  )

Definition at line 1069 of file slot.c.

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

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

1070 {
1072 
1073  Assert(slot != NULL);
1075 
1076  /*
1077  * The replication slot mechanism is used to prevent removal of required
1078  * WAL. As there is no interlock between this routine and checkpoints, WAL
1079  * segments could concurrently be removed when a now stale return value of
1080  * ReplicationSlotsComputeRequiredLSN() is used. In the unlikely case that
1081  * this happens we'll just retry.
1082  */
1083  while (true)
1084  {
1085  XLogSegNo segno;
1086  XLogRecPtr restart_lsn;
1087 
1088  /*
1089  * For logical slots log a standby snapshot and start logical decoding
1090  * at exactly that position. That allows the slot to start up more
1091  * quickly.
1092  *
1093  * That's not needed (or indeed helpful) for physical slots as they'll
1094  * start replay at the last logged checkpoint anyway. Instead return
1095  * the location of the last redo LSN. While that slightly increases
1096  * the chance that we have to retry, it's where a base backup has to
1097  * start replay at.
1098  */
1099  if (!RecoveryInProgress() && SlotIsLogical(slot))
1100  {
1101  XLogRecPtr flushptr;
1102 
1103  /* start at current insert position */
1104  restart_lsn = GetXLogInsertRecPtr();
1105  SpinLockAcquire(&slot->mutex);
1106  slot->data.restart_lsn = restart_lsn;
1107  SpinLockRelease(&slot->mutex);
1108 
1109  /* make sure we have enough information to start */
1110  flushptr = LogStandbySnapshot();
1111 
1112  /* and make sure it's fsynced to disk */
1113  XLogFlush(flushptr);
1114  }
1115  else
1116  {
1117  restart_lsn = GetRedoRecPtr();
1118  SpinLockAcquire(&slot->mutex);
1119  slot->data.restart_lsn = restart_lsn;
1120  SpinLockRelease(&slot->mutex);
1121  }
1122 
1123  /* prevent WAL removal as fast as possible */
1125 
1126  /*
1127  * If all required WAL is still there, great, otherwise retry. The
1128  * slot should prevent further removal of WAL, unless there's a
1129  * concurrent ReplicationSlotsComputeRequiredLSN() after we've written
1130  * the new restart_lsn above, so normally we should never need to loop
1131  * more than twice.
1132  */
1134  if (XLogGetLastRemovedSegno() < segno)
1135  break;
1136  }
1137 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
int wal_segment_size
Definition: xlog.c:119
ReplicationSlotPersistentData data
Definition: slot.h:147
bool RecoveryInProgress(void)
Definition: xlog.c:8248
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2881
#define SpinLockAcquire(lock)
Definition: spin.h:62
XLogSegNo XLogGetLastRemovedSegno(void)
Definition: xlog.c:4026
void ReplicationSlotsComputeRequiredLSN(void)
Definition: slot.c:817
XLogRecPtr LogStandbySnapshot(void)
Definition: standby.c:1220
XLogRecPtr GetXLogInsertRecPtr(void)
Definition: xlog.c:11792
uint64 XLogSegNo
Definition: xlogdefs.h:48
#define SlotIsLogical(slot)
Definition: slot.h:169
#define SpinLockRelease(lock)
Definition: spin.h:64
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:804
XLogRecPtr restart_lsn
Definition: slot.h:73
XLogRecPtr GetRedoRecPtr(void)
Definition: xlog.c:8540
slock_t mutex
Definition: slot.h:120
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)

◆ ReplicationSlotSave()

void ReplicationSlotSave ( void  )

Definition at line 710 of file slot.c.

References Assert, ReplicationSlot::data, ERROR, MAXPGPATH, ReplicationSlotPersistentData::name, NameStr, SaveSlotToPath(), and sprintf.

Referenced by copy_replication_slot(), create_physical_replication_slot(), CreateDecodingContext(), CreateInitDecodingContext(), CreateReplicationSlot(), InvalidatePossiblyObsoleteSlot(), LogicalConfirmReceivedLocation(), and ReplicationSlotPersist().

711 {
712  char path[MAXPGPATH];
713 
714  Assert(MyReplicationSlot != NULL);
715 
716  sprintf(path, "pg_replslot/%s", NameStr(MyReplicationSlot->data.name));
718 }
ReplicationSlotPersistentData data
Definition: slot.h:147
static void SaveSlotToPath(ReplicationSlot *slot, const char *path, int elevel)
Definition: slot.c:1504
#define sprintf
Definition: port.h:218
#define ERROR
Definition: elog.h:46
#define MAXPGPATH
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
#define Assert(condition)
Definition: c.h:804
#define NameStr(name)
Definition: c.h:681

◆ ReplicationSlotsComputeLogicalRestartLSN()

XLogRecPtr ReplicationSlotsComputeLogicalRestartLSN ( void  )

Definition at line 860 of file slot.c.

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

Referenced by CheckPointLogicalRewriteHeap(), and CheckPointSnapBuild().

861 {
862  XLogRecPtr result = InvalidXLogRecPtr;
863  int i;
864 
865  if (max_replication_slots <= 0)
866  return InvalidXLogRecPtr;
867 
868  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
869 
870  for (i = 0; i < max_replication_slots; i++)
871  {
872  ReplicationSlot *s;
873  XLogRecPtr restart_lsn;
874 
876 
877  /* cannot change while ReplicationSlotCtlLock is held */
878  if (!s->in_use)
879  continue;
880 
881  /* we're only interested in logical slots */
882  if (!SlotIsLogical(s))
883  continue;
884 
885  /* read once, it's ok if it increases while we're checking */
886  SpinLockAcquire(&s->mutex);
887  restart_lsn = s->data.restart_lsn;
888  SpinLockRelease(&s->mutex);
889 
890  if (restart_lsn == InvalidXLogRecPtr)
891  continue;
892 
893  if (result == InvalidXLogRecPtr ||
894  restart_lsn < result)
895  result = restart_lsn;
896  }
897 
898  LWLockRelease(ReplicationSlotControlLock);
899 
900  return result;
901 }
ReplicationSlotCtlData * ReplicationSlotCtl
Definition: slot.c:93
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
ReplicationSlotPersistentData data
Definition: slot.h:147
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SlotIsLogical(slot)
Definition: slot.h:169
bool in_use
Definition: slot.h:123
#define SpinLockRelease(lock)
Definition: spin.h:64
int max_replication_slots
Definition: slot.c:99
uint64 XLogRecPtr
Definition: xlogdefs.h:21
XLogRecPtr restart_lsn
Definition: slot.h:73
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
int i
ReplicationSlot replication_slots[1]
Definition: slot.h:180
slock_t mutex
Definition: slot.h:120

◆ ReplicationSlotsComputeRequiredLSN()

void ReplicationSlotsComputeRequiredLSN ( void  )

Definition at line 817 of file slot.c.

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

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

818 {
819  int i;
820  XLogRecPtr min_required = InvalidXLogRecPtr;
821 
822  Assert(ReplicationSlotCtl != NULL);
823 
824  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
825  for (i = 0; i < max_replication_slots; i++)
826  {
828  XLogRecPtr restart_lsn;
829 
830  if (!s->in_use)
831  continue;
832 
833  SpinLockAcquire(&s->mutex);
834  restart_lsn = s->data.restart_lsn;
835  SpinLockRelease(&s->mutex);
836 
837  if (restart_lsn != InvalidXLogRecPtr &&
838  (min_required == InvalidXLogRecPtr ||
839  restart_lsn < min_required))
840  min_required = restart_lsn;
841  }
842  LWLockRelease(ReplicationSlotControlLock);
843 
844  XLogSetReplicationSlotMinimumLSN(min_required);
845 }
ReplicationSlotCtlData * ReplicationSlotCtl
Definition: slot.c:93
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
ReplicationSlotPersistentData data
Definition: slot.h:147
void XLogSetReplicationSlotMinimumLSN(XLogRecPtr lsn)
Definition: xlog.c:2763
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#define SpinLockAcquire(lock)
Definition: spin.h:62
bool in_use
Definition: slot.h:123
#define SpinLockRelease(lock)
Definition: spin.h:64
int max_replication_slots
Definition: slot.c:99
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:804
XLogRecPtr restart_lsn
Definition: slot.h:73
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
int i
ReplicationSlot replication_slots[1]
Definition: slot.h:180
slock_t mutex
Definition: slot.h:120

◆ ReplicationSlotsComputeRequiredXmin()

void ReplicationSlotsComputeRequiredXmin ( bool  already_locked)

Definition at line 767 of file slot.c.

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

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

768 {
769  int i;
771  TransactionId agg_catalog_xmin = InvalidTransactionId;
772 
773  Assert(ReplicationSlotCtl != NULL);
774 
775  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
776 
777  for (i = 0; i < max_replication_slots; i++)
778  {
780  TransactionId effective_xmin;
781  TransactionId effective_catalog_xmin;
782 
783  if (!s->in_use)
784  continue;
785 
786  SpinLockAcquire(&s->mutex);
787  effective_xmin = s->effective_xmin;
788  effective_catalog_xmin = s->effective_catalog_xmin;
789  SpinLockRelease(&s->mutex);
790 
791  /* check the data xmin */
792  if (TransactionIdIsValid(effective_xmin) &&
793  (!TransactionIdIsValid(agg_xmin) ||
794  TransactionIdPrecedes(effective_xmin, agg_xmin)))
795  agg_xmin = effective_xmin;
796 
797  /* check the catalog xmin */
798  if (TransactionIdIsValid(effective_catalog_xmin) &&
799  (!TransactionIdIsValid(agg_catalog_xmin) ||
800  TransactionIdPrecedes(effective_catalog_xmin, agg_catalog_xmin)))
801  agg_catalog_xmin = effective_catalog_xmin;
802  }
803 
804  LWLockRelease(ReplicationSlotControlLock);
805 
806  ProcArraySetReplicationSlotXmin(agg_xmin, agg_catalog_xmin, already_locked);
807 }
ReplicationSlotCtlData * ReplicationSlotCtl
Definition: slot.c:93
uint32 TransactionId
Definition: c.h:587
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#define SpinLockAcquire(lock)
Definition: spin.h:62
TransactionId effective_xmin
Definition: slot.h:143
#define InvalidTransactionId
Definition: transam.h:31
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
bool in_use
Definition: slot.h:123
#define SpinLockRelease(lock)
Definition: spin.h:64
TransactionId effective_catalog_xmin
Definition: slot.h:144
int max_replication_slots
Definition: slot.c:99
#define Assert(condition)
Definition: c.h:804
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
int i
void ProcArraySetReplicationSlotXmin(TransactionId xmin, TransactionId catalog_xmin, bool already_locked)
Definition: procarray.c:3868
ReplicationSlot replication_slots[1]
Definition: slot.h:180
slock_t mutex
Definition: slot.h:120
#define TransactionIdIsValid(xid)
Definition: transam.h:41

◆ ReplicationSlotsCountDBSlots()

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

Definition at line 912 of file slot.c.

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

Referenced by dropdb().

913 {
914  int i;
915 
916  *nslots = *nactive = 0;
917 
918  if (max_replication_slots <= 0)
919  return false;
920 
921  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
922  for (i = 0; i < max_replication_slots; i++)
923  {
924  ReplicationSlot *s;
925 
927 
928  /* cannot change while ReplicationSlotCtlLock is held */
929  if (!s->in_use)
930  continue;
931 
932  /* only logical slots are database specific, skip */
933  if (!SlotIsLogical(s))
934  continue;
935 
936  /* not our database, skip */
937  if (s->data.database != dboid)
938  continue;
939 
940  /* count slots with spinlock held */
941  SpinLockAcquire(&s->mutex);
942  (*nslots)++;
943  if (s->active_pid != 0)
944  (*nactive)++;
945  SpinLockRelease(&s->mutex);
946  }
947  LWLockRelease(ReplicationSlotControlLock);
948 
949  if (*nslots > 0)
950  return true;
951  return false;
952 }
ReplicationSlotCtlData * ReplicationSlotCtl
Definition: slot.c:93
ReplicationSlotPersistentData data
Definition: slot.h:147
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define SlotIsLogical(slot)
Definition: slot.h:169
bool in_use
Definition: slot.h:123
#define SpinLockRelease(lock)
Definition: spin.h:64
int max_replication_slots
Definition: slot.c:99
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
pid_t active_pid
Definition: slot.h:126
int i
ReplicationSlot replication_slots[1]
Definition: slot.h:180
slock_t mutex
Definition: slot.h:120

◆ ReplicationSlotsDropDBSlots()

void ReplicationSlotsDropDBSlots ( Oid  dboid)

Definition at line 968 of file slot.c.

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, ReplicationSlotPersistentData::name, NameStr, ReplicationSlotCtlData::replication_slots, ReplicationSlotDropAcquired(), SlotIsLogical, SpinLockAcquire, and SpinLockRelease.

Referenced by dbase_redo(), and dropdb().

969 {
970  int i;
971 
972  if (max_replication_slots <= 0)
973  return;
974 
975 restart:
976  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
977  for (i = 0; i < max_replication_slots; i++)
978  {
979  ReplicationSlot *s;
980  char *slotname;
981  int active_pid;
982 
984 
985  /* cannot change while ReplicationSlotCtlLock is held */
986  if (!s->in_use)
987  continue;
988 
989  /* only logical slots are database specific, skip */
990  if (!SlotIsLogical(s))
991  continue;
992 
993  /* not our database, skip */
994  if (s->data.database != dboid)
995  continue;
996 
997  /* acquire slot, so ReplicationSlotDropAcquired can be reused */
998  SpinLockAcquire(&s->mutex);
999  /* can't change while ReplicationSlotControlLock is held */
1000  slotname = NameStr(s->data.name);
1001  active_pid = s->active_pid;
1002  if (active_pid == 0)
1003  {
1004  MyReplicationSlot = s;
1005  s->active_pid = MyProcPid;
1006  }
1007  SpinLockRelease(&s->mutex);
1008 
1009  /*
1010  * Even though we hold an exclusive lock on the database object a
1011  * logical slot for that DB can still be active, e.g. if it's
1012  * concurrently being dropped by a backend connected to another DB.
1013  *
1014  * That's fairly unlikely in practice, so we'll just bail out.
1015  */
1016  if (active_pid)
1017  ereport(ERROR,
1018  (errcode(ERRCODE_OBJECT_IN_USE),
1019  errmsg("replication slot \"%s\" is active for PID %d",
1020  slotname, active_pid)));
1021 
1022  /*
1023  * To avoid duplicating ReplicationSlotDropAcquired() and to avoid
1024  * holding ReplicationSlotControlLock over filesystem operations,
1025  * release ReplicationSlotControlLock and use
1026  * ReplicationSlotDropAcquired.
1027  *
1028  * As that means the set of slots could change, restart scan from the
1029  * beginning each time we release the lock.
1030  */
1031  LWLockRelease(ReplicationSlotControlLock);
1033  goto restart;
1034  }
1035  LWLockRelease(ReplicationSlotControlLock);
1036 }
ReplicationSlotCtlData * ReplicationSlotCtl
Definition: slot.c:93
int MyProcPid
Definition: globals.c:43
int errcode(int sqlerrcode)
Definition: elog.c:698
ReplicationSlotPersistentData data
Definition: slot.h:147
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#define SpinLockAcquire(lock)
Definition: spin.h:62
static void ReplicationSlotDropAcquired(void)
Definition: slot.c:576
#define ERROR
Definition: elog.h:46
#define SlotIsLogical(slot)
Definition: slot.h:169
bool in_use
Definition: slot.h:123
#define SpinLockRelease(lock)
Definition: spin.h:64
#define ereport(elevel,...)
Definition: elog.h:157
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
int max_replication_slots
Definition: slot.c:99
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
int errmsg(const char *fmt,...)
Definition: elog.c:909
pid_t active_pid
Definition: slot.h:126
int i
#define NameStr(name)
Definition: c.h:681
ReplicationSlot replication_slots[1]
Definition: slot.h:180
slock_t mutex
Definition: slot.h:120

◆ ReplicationSlotsShmemInit()

void ReplicationSlotsShmemInit ( void  )

Definition at line 132 of file slot.c.

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, ReplicationSlotsShmemSize(), ShmemInitStruct(), and SpinLockInit.

Referenced by CreateSharedMemoryAndSemaphores().

133 {
134  bool found;
135 
136  if (max_replication_slots == 0)
137  return;
138 
140  ShmemInitStruct("ReplicationSlot Ctl", ReplicationSlotsShmemSize(),
141  &found);
142 
143  if (!found)
144  {
145  int i;
146 
147  /* First time through, so initialize */
149 
150  for (i = 0; i < max_replication_slots; i++)
151  {
153 
154  /* everything else is zeroed by the memset above */
155  SpinLockInit(&slot->mutex);
159  }
160  }
161 }
ReplicationSlotCtlData * ReplicationSlotCtl
Definition: slot.c:93
Size ReplicationSlotsShmemSize(void)
Definition: slot.c:114
#define SpinLockInit(lock)
Definition: spin.h:60
#define MemSet(start, val, len)
Definition: c.h:1008
void ConditionVariableInit(ConditionVariable *cv)
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:396
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition: lwlock.c:736
int max_replication_slots
Definition: slot.c:99
ConditionVariable active_cv
Definition: slot.h:153
int i
ReplicationSlot replication_slots[1]
Definition: slot.h:180
slock_t mutex
Definition: slot.h:120
LWLock io_in_progress_lock
Definition: slot.h:150

◆ ReplicationSlotsShmemSize()

Size ReplicationSlotsShmemSize ( void  )

Definition at line 114 of file slot.c.

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

Referenced by CreateSharedMemoryAndSemaphores(), and ReplicationSlotsShmemInit().

115 {
116  Size size = 0;
117 
118  if (max_replication_slots == 0)
119  return size;
120 
121  size = offsetof(ReplicationSlotCtlData, replication_slots);
122  size = add_size(size,
124 
125  return size;
126 }
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
int max_replication_slots
Definition: slot.c:99
size_t Size
Definition: c.h:540
#define offsetof(type, field)
Definition: c.h:727

◆ ReplicationSlotValidateName()

bool ReplicationSlotValidateName ( const char *  name,
int  elevel 
)

Definition at line 172 of file slot.c.

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

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

173 {
174  const char *cp;
175 
176  if (strlen(name) == 0)
177  {
178  ereport(elevel,
179  (errcode(ERRCODE_INVALID_NAME),
180  errmsg("replication slot name \"%s\" is too short",
181  name)));
182  return false;
183  }
184 
185  if (strlen(name) >= NAMEDATALEN)
186  {
187  ereport(elevel,
188  (errcode(ERRCODE_NAME_TOO_LONG),
189  errmsg("replication slot name \"%s\" is too long",
190  name)));
191  return false;
192  }
193 
194  for (cp = name; *cp; cp++)
195  {
196  if (!((*cp >= 'a' && *cp <= 'z')
197  || (*cp >= '0' && *cp <= '9')
198  || (*cp == '_')))
199  {
200  ereport(elevel,
201  (errcode(ERRCODE_INVALID_NAME),
202  errmsg("replication slot name \"%s\" contains invalid character",
203  name),
204  errhint("Replication slot names may only contain lower case letters, numbers, and the underscore character.")));
205  return false;
206  }
207  }
208  return true;
209 }
int errhint(const char *fmt,...)
Definition: elog.c:1156
int errcode(int sqlerrcode)
Definition: elog.c:698
#define NAMEDATALEN
static int elevel
Definition: vacuumlazy.c:403
#define ereport(elevel,...)
Definition: elog.h:157
const char * name
Definition: encode.c:515
int errmsg(const char *fmt,...)
Definition: elog.c:909

◆ RestoreSlotFromDisk()

static void RestoreSlotFromDisk ( const char *  name)
static

Definition at line 1658 of file slot.c.

References ReplicationSlot::active_pid, ReplicationSlot::candidate_catalog_xmin, ReplicationSlot::candidate_restart_lsn, ReplicationSlot::candidate_restart_valid, ReplicationSlot::candidate_xmin_lsn, ReplicationSlotPersistentData::catalog_xmin, ReplicationSlotOnDisk::checksum, CloseTransientFile(), COMP_CRC32C, ReplicationSlot::data, ReplicationSlotPersistentData::database, DEBUG1, ReplicationSlot::effective_catalog_xmin, ReplicationSlot::effective_xmin, elog, END_CRIT_SECTION, EQ_CRC32C, ereport, errcode(), ERRCODE_DATA_CORRUPTED, errcode_for_file_access(), errhint(), errmsg(), FATAL, fd(), FIN_CRC32C, fsync_fname(), i, ReplicationSlot::in_use, INIT_CRC32C, InvalidOid, InvalidTransactionId, InvalidXLogRecPtr, ReplicationSlotOnDisk::length, ReplicationSlotOnDisk::magic, max_replication_slots, MAXPGPATH, ReplicationSlotPersistentData::name, NameStr, OpenTransientFile(), PANIC, ReplicationSlotPersistentData::persistency, PG_BINARY, pg_fsync(), pgstat_report_wait_end(), pgstat_report_wait_start(), read, ReplicationSlotCtlData::replication_slots, ReplicationSlotOnDiskConstantSize, ReplicationSlotOnDiskV2Size, rmtree(), RS_PERSISTENT, SLOT_MAGIC, SLOT_VERSION, ReplicationSlotOnDisk::slotdata, SnapBuildOnDiskChecksummedSize, SnapBuildOnDiskNotChecksummedSize, sprintf, START_CRIT_SECTION, ReplicationSlotOnDisk::version, WAIT_EVENT_REPLICATION_SLOT_READ, WAIT_EVENT_REPLICATION_SLOT_RESTORE_SYNC, wal_level, WAL_LEVEL_LOGICAL, WAL_LEVEL_REPLICA, WARNING, and ReplicationSlotPersistentData::xmin.

Referenced by StartupReplicationSlots().

1659 {
1661  int i;
1662  char slotdir[MAXPGPATH + 12];
1663  char path[MAXPGPATH + 22];
1664  int fd;
1665  bool restored = false;
1666  int readBytes;
1667  pg_crc32c checksum;
1668 
1669  /* no need to lock here, no concurrent access allowed yet */
1670 
1671  /* delete temp file if it exists */
1672  sprintf(slotdir, "pg_replslot/%s", name);
1673  sprintf(path, "%s/state.tmp", slotdir);
1674  if (unlink(path) < 0 && errno != ENOENT)
1675  ereport(PANIC,
1677  errmsg("could not remove file \"%s\": %m", path)));
1678 
1679  sprintf(path, "%s/state", slotdir);
1680 
1681  elog(DEBUG1, "restoring replication slot from \"%s\"", path);
1682 
1683  /* on some operating systems fsyncing a file requires O_RDWR */
1684  fd = OpenTransientFile(path, O_RDWR | PG_BINARY);
1685 
1686  /*
1687  * We do not need to handle this as we are rename()ing the directory into
1688  * place only after we fsync()ed the state file.
1689  */
1690  if (fd < 0)
1691  ereport(PANIC,
1693  errmsg("could not open file \"%s\": %m", path)));
1694 
1695  /*
1696  * Sync state file before we're reading from it. We might have crashed
1697  * while it wasn't synced yet and we shouldn't continue on that basis.
1698  */
1700  if (pg_fsync(fd) != 0)
1701  ereport(PANIC,
1703  errmsg("could not fsync file \"%s\": %m",
1704  path)));
1706 
1707  /* Also sync the parent directory */
1709  fsync_fname(slotdir, true);
1710  END_CRIT_SECTION();
1711 
1712  /* read part of statefile that's guaranteed to be version independent */
1714  readBytes = read(fd, &cp, ReplicationSlotOnDiskConstantSize);
1716  if (readBytes != ReplicationSlotOnDiskConstantSize)
1717  {
1718  if (readBytes < 0)
1719  ereport(PANIC,
1721  errmsg("could not read file \"%s\": %m", path)));
1722  else
1723  ereport(PANIC,
1725  errmsg("could not read file \"%s\": read %d of %zu",
1726  path, readBytes,
1728  }
1729 
1730  /* verify magic */
1731  if (cp.magic != SLOT_MAGIC)
1732  ereport(PANIC,
1734  errmsg("replication slot file \"%s\" has wrong magic number: %u instead of %u",
1735  path, cp.magic, SLOT_MAGIC)));
1736 
1737  /* verify version */
1738  if (cp.version != SLOT_VERSION)
1739  ereport(PANIC,
1741  errmsg("replication slot file \"%s\" has unsupported version %u",
1742  path, cp.version)));
1743 
1744  /* boundary check on length */
1746  ereport(PANIC,
1748  errmsg("replication slot file \"%s\" has corrupted length %u",
1749  path, cp.length)));
1750 
1751  /* Now that we know the size, read the entire file */
1753  readBytes = read(fd,
1754  (char *) &cp + ReplicationSlotOnDiskConstantSize,
1755  cp.length);
1757  if (readBytes != cp.length)
1758  {
1759  if (readBytes < 0)
1760  ereport(PANIC,
1762  errmsg("could not read file \"%s\": %m", path)));
1763  else
1764  ereport(PANIC,
1766  errmsg("could not read file \"%s\": read %d of %zu",
1767  path, readBytes, (Size) cp.length)));
1768  }
1769 
1770  if (CloseTransientFile(fd) != 0)
1771  ereport(PANIC,
1773  errmsg("could not close file \"%s\": %m", path)));
1774 
1775  /* now verify the CRC */
1776  INIT_CRC32C(checksum);
1777  COMP_CRC32C(checksum,
1778  (char *) &cp + SnapBuildOnDiskNotChecksummedSize,
1780  FIN_CRC32C(checksum);
1781 
1782  if (!EQ_CRC32C(checksum, cp.checksum))
1783  ereport(PANIC,
1784  (errmsg("checksum mismatch for replication slot file \"%s\": is %u, should be %u",
1785  path, checksum, cp.checksum)));
1786 
1787  /*
1788  * If we crashed with an ephemeral slot active, don't restore but delete
1789  * it.
1790  */
1792  {
1793  if (!rmtree(slotdir, true))
1794  {
1795  ereport(WARNING,
1796  (errmsg("could not remove directory \"%s\"",
1797  slotdir)));
1798  }
1799  fsync_fname("pg_replslot", true);
1800  return;
1801  }
1802 
1803  /*
1804  * Verify that requirements for the specific slot type are met. That's
1805  * important because if these aren't met we're not guaranteed to retain
1806  * all the necessary resources for the slot.
1807  *
1808  * NB: We have to do so *after* the above checks for ephemeral slots,
1809  * because otherwise a slot that shouldn't exist anymore could prevent
1810  * restarts.
1811  *
1812  * NB: Changing the requirements here also requires adapting
1813  * CheckSlotRequirements() and CheckLogicalDecodingRequirements().
1814  */
1816  ereport(FATAL,
1817  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1818  errmsg("logical replication slot \"%s\" exists, but wal_level < logical",
1819  NameStr(cp.slotdata.name)),
1820  errhint("Change wal_level to be logical or higher.")));
1821  else if (wal_level < WAL_LEVEL_REPLICA)
1822  ereport(FATAL,
1823  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1824  errmsg("physical replication slot \"%s\" exists, but wal_level < replica",
1825  NameStr(cp.slotdata.name)),
1826  errhint("Change wal_level to be replica or higher.")));
1827 
1828  /* nothing can be active yet, don't lock anything */
1829  for (i = 0; i < max_replication_slots; i++)
1830  {
1831  ReplicationSlot *slot;
1832 
1834 
1835  if (slot->in_use)
1836  continue;
1837 
1838  /* restore the entire set of persistent data */
1839  memcpy(&slot->data, &cp.slotdata,
1841 
1842  /* initialize in memory state */
1843  slot->effective_xmin = cp.slotdata.xmin;
1845 
1850 
1851  slot->in_use = true;
1852  slot->active_pid = 0;
1853 
1854  restored = true;
1855  break;
1856  }
1857 
1858  if (!restored)
1859  ereport(FATAL,
1860  (errmsg("too many replication slots active before shutdown"),
1861  errhint("Increase max_replication_slots and try again.")));
1862 }
#define INIT_CRC32C(crc)
Definition: pg_crc32c.h:41
ReplicationSlotCtlData * ReplicationSlotCtl
Definition: slot.c:93
TransactionId candidate_catalog_xmin
Definition: slot.h:162
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define DEBUG1
Definition: elog.h:25
int errhint(const char *fmt,...)
Definition: elog.c:1156
static void pgstat_report_wait_end(void)
Definition: wait_event.h:278
#define SLOT_MAGIC
Definition: slot.c:89
uint32 pg_crc32c
Definition: pg_crc32c.h:38
int wal_level
Definition: xlog.c:108
#define END_CRIT_SECTION()
Definition: miscadmin.h:149
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:666
ReplicationSlotPersistency persistency
Definition: slot.h:54
#define START_CRIT_SECTION()
Definition: miscadmin.h:147
int errcode(int sqlerrcode)
Definition: elog.c:698
#define SnapBuildOnDiskNotChecksummedSize
Definition: slot.c:80
ReplicationSlotPersistentData data
Definition: slot.h:147
#define PANIC
Definition: elog.h:50
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1271
#define sprintf
Definition: port.h:218
ReplicationSlotPersistentData slotdata
Definition: slot.c:73
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2467
#define FATAL
Definition: elog.h:49
#define MAXPGPATH
TransactionId effective_xmin
Definition: slot.h:143
XLogRecPtr candidate_restart_valid
Definition: slot.h:164
int errcode_for_file_access(void)
Definition: elog.c:721
TransactionId catalog_xmin
Definition: slot.h:70
#define InvalidTransactionId
Definition: transam.h:31
TransactionId xmin
Definition: slot.h:62
#define EQ_CRC32C(c1, c2)
Definition: pg_crc32c.h:42
pg_crc32c checksum
Definition: slot.c:62
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:262
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:47
int CloseTransientFile(int fd)
Definition: fd.c:2644
#define WARNING
Definition: elog.h:40
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:42
bool in_use
Definition: slot.h:123
TransactionId effective_catalog_xmin
Definition: slot.h:144
#define SLOT_VERSION
Definition: slot.c:90
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
int max_replication_slots
Definition: slot.c:99
#define ReplicationSlotOnDiskV2Size
Definition: slot.c:86
#define ReplicationSlotOnDiskConstantSize
Definition: slot.c:77
size_t Size
Definition: c.h:540
uint32 version
Definition: slot.c:65
#define SnapBuildOnDiskChecksummedSize
Definition: slot.c:83
const char * name
Definition: encode.c:515
XLogRecPtr candidate_xmin_lsn
Definition: slot.h:163
int errmsg(const char *fmt,...)
Definition: elog.c:909
pid_t active_pid
Definition: slot.h:126
#define elog(elevel,...)
Definition: elog.h:232
int i
#define NameStr(name)
Definition: c.h:681
int pg_fsync(int fd)
Definition: fd.c:352
ReplicationSlot replication_slots[1]
Definition: slot.h:180
#define COMP_CRC32C(crc, data, len)
Definition: pg_crc32c.h:89
#define FIN_CRC32C(crc)
Definition: pg_crc32c.h:94
#define read(a, b, c)
Definition: win32.h:13
XLogRecPtr candidate_restart_lsn
Definition: slot.h:165

◆ SaveSlotToPath()

static void SaveSlotToPath ( ReplicationSlot slot,
const char *  path,
int  elevel 
)
static

Definition at line 1504 of file slot.c.

References ReplicationSlotOnDisk::checksum, CloseTransientFile(), COMP_CRC32C, ReplicationSlot::data, ReplicationSlot::dirty, END_CRIT_SECTION, ereport, errcode_for_file_access(), errmsg(), fd(), FIN_CRC32C, fsync_fname(), INIT_CRC32C, ReplicationSlot::io_in_progress_lock, ReplicationSlot::just_dirtied, ReplicationSlotOnDisk::length, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), ReplicationSlotOnDisk::magic, MAXPGPATH, ReplicationSlot::mutex, OpenTransientFile(), PG_BINARY, pg_fsync(), pgstat_report_wait_end(), pgstat_report_wait_start(), ReplicationSlotOnDiskV2Size, SLOT_MAGIC, SLOT_VERSION, ReplicationSlotOnDisk::slotdata, SnapBuildOnDiskChecksummedSize, SnapBuildOnDiskNotChecksummedSize, SpinLockAcquire, SpinLockRelease, sprintf, START_CRIT_SECTION, ReplicationSlotOnDisk::version, WAIT_EVENT_REPLICATION_SLOT_SYNC, WAIT_EVENT_REPLICATION_SLOT_WRITE, and write.

Referenced by CheckPointReplicationSlots(), CreateSlotOnDisk(), and ReplicationSlotSave().

1505 {
1506  char tmppath[MAXPGPATH];
1507  char path[MAXPGPATH];
1508  int fd;
1510  bool was_dirty;
1511 
1512  /* first check whether there's something to write out */
1513  SpinLockAcquire(&slot->mutex);
1514  was_dirty = slot->dirty;
1515  slot->just_dirtied = false;
1516  SpinLockRelease(&slot->mutex);
1517 
1518  /* and don't do anything if there's nothing to write */
1519  if (!was_dirty)
1520  return;
1521 
1523 
1524  /* silence valgrind :( */
1525  memset(&cp, 0, sizeof(ReplicationSlotOnDisk));
1526 
1527  sprintf(tmppath, "%s/state.tmp", dir);
1528  sprintf(path, "%s/state", dir);
1529 
1530  fd = OpenTransientFile(tmppath, O_CREAT | O_EXCL | O_WRONLY | PG_BINARY);
1531  if (fd < 0)
1532  {
1533  /*
1534  * If not an ERROR, then release the lock before returning. In case
1535  * of an ERROR, the error recovery path automatically releases the
1536  * lock, but no harm in explicitly releasing even in that case. Note
1537  * that LWLockRelease() could affect errno.
1538  */
1539  int save_errno = errno;
1540 
1542  errno = save_errno;
1543  ereport(elevel,
1545  errmsg("could not create file \"%s\": %m",
1546  tmppath)));
1547  return;
1548  }
1549 
1550  cp.magic = SLOT_MAGIC;
1551  INIT_CRC32C(cp.checksum);
1552  cp.version = SLOT_VERSION;
1554 
1555  SpinLockAcquire(&slot->mutex);
1556 
1557  memcpy(&cp.slotdata, &slot->data, sizeof(ReplicationSlotPersistentData));
1558 
1559  SpinLockRelease(&slot->mutex);
1560 
1561  COMP_CRC32C(cp.checksum,
1562  (char *) (&cp) + SnapBuildOnDiskNotChecksummedSize,
1564  FIN_CRC32C(cp.checksum);
1565 
1566  errno = 0;
1568  if ((write(fd, &cp, sizeof(cp))) != sizeof(cp))
1569  {
1570  int save_errno = errno;
1571 
1573  CloseTransientFile(fd);
1575 
1576  /* if write didn't set errno, assume problem is no disk space */
1577  errno = save_errno ? save_errno : ENOSPC;
1578  ereport(elevel,
1580  errmsg("could not write to file \"%s\": %m",
1581  tmppath)));
1582  return;
1583  }
1585 
1586  /* fsync the temporary file */
1588  if (pg_fsync(fd) != 0)
1589  {
1590  int save_errno = errno;
1591 
1593  CloseTransientFile(fd);
1595  errno = save_errno;
1596  ereport(elevel,
1598  errmsg("could not fsync file \"%s\": %m",
1599  tmppath)));
1600  return;
1601  }
1603 
1604  if (CloseTransientFile(fd) != 0)
1605  {
1606  int save_errno = errno;
1607 
1609  errno = save_errno;
1610  ereport(elevel,
1612  errmsg("could not close file \"%s\": %m",
1613  tmppath)));
1614  return;
1615  }
1616 
1617  /* rename to permanent file, fsync file and directory */
1618  if (rename(tmppath, path) != 0)
1619  {
1620  int save_errno = errno;
1621 
1623  errno = save_errno;
1624  ereport(elevel,
1626  errmsg("could not rename file \"%s\" to \"%s\": %m",
1627  tmppath, path)));
1628  return;
1629  }
1630 
1631  /*
1632  * Check CreateSlotOnDisk() for the reasoning of using a critical section.
1633  */
1635 
1636  fsync_fname(path, false);
1637  fsync_fname(dir, true);
1638  fsync_fname("pg_replslot", true);
1639 
1640  END_CRIT_SECTION();
1641 
1642  /*
1643  * Successfully wrote, unset dirty bit, unless somebody dirtied again
1644  * already.
1645  */
1646  SpinLockAcquire(&slot->mutex);
1647  if (!slot->just_dirtied)
1648  slot->dirty = false;
1649  SpinLockRelease(&slot->mutex);
1650 
1652 }
#define INIT_CRC32C(crc)
Definition: pg_crc32c.h:41
static void pgstat_report_wait_end(void)
Definition: wait_event.h:278
#define write(a, b, c)
Definition: win32.h:14
#define SLOT_MAGIC
Definition: slot.c:89
#define END_CRIT_SECTION()
Definition: miscadmin.h:149
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:666
#define START_CRIT_SECTION()
Definition: miscadmin.h:147
#define SnapBuildOnDiskNotChecksummedSize
Definition: slot.c:80
ReplicationSlotPersistentData data
Definition: slot.h:147
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1271
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#define sprintf
Definition: port.h:218
#define SpinLockAcquire(lock)
Definition: spin.h:62
ReplicationSlotPersistentData slotdata
Definition: slot.c:73
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2467
#define MAXPGPATH
int errcode_for_file_access(void)
Definition: elog.c:721
pg_crc32c checksum
Definition: slot.c:62
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:262
int CloseTransientFile(int fd)
Definition: fd.c:2644
static int elevel
Definition: vacuumlazy.c:403
#define SpinLockRelease(lock)
Definition: spin.h:64
bool just_dirtied
Definition: slot.h:129
#define SLOT_VERSION
Definition: slot.c:90
#define ereport(elevel,...)
Definition: elog.h:157
#define ReplicationSlotOnDiskV2Size
Definition: slot.c:86
uint32 version
Definition: slot.c:65
#define SnapBuildOnDiskChecksummedSize
Definition: slot.c:83
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
int errmsg(const char *fmt,...)
Definition: elog.c:909
int pg_fsync(int fd)
Definition: fd.c:352
slock_t mutex
Definition: slot.h:120
#define COMP_CRC32C(crc, data, len)
Definition: pg_crc32c.h:89
#define FIN_CRC32C(crc)
Definition: pg_crc32c.h:94
bool dirty
Definition: slot.h:130
LWLock io_in_progress_lock
Definition: slot.h:150

◆ SearchNamedReplicationSlot()

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

Definition at line 348 of file slot.c.

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

Referenced by pg_stat_reset_replication_slot(), pgstat_vacuum_stat(), and ReplicationSlotAcquire().

349 {
350  int i;
351  ReplicationSlot *slot = NULL;
352 
353  if (need_lock)
354  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
355 
356  for (i = 0; i < max_replication_slots; i++)
357  {
359 
360  if (s->in_use && strcmp(name, NameStr(s->data.name)) == 0)
361  {
362  slot = s;
363  break;
364  }
365  }
366 
367  if (need_lock)
368  LWLockRelease(ReplicationSlotControlLock);
369 
370  return slot;
371 }
ReplicationSlotCtlData * ReplicationSlotCtl
Definition: slot.c:93
ReplicationSlotPersistentData data
Definition: slot.h:147
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
bool in_use
Definition: slot.h:123
int max_replication_slots
Definition: slot.c:99
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
const char * name
Definition: encode.c:515
int i
#define NameStr(name)
Definition: c.h:681
ReplicationSlot replication_slots[1]
Definition: slot.h:180

◆ StartupReplicationSlots()

void StartupReplicationSlots ( void  )

Definition at line 1383 of file slot.c.

References AllocateDir(), dirent::d_name, DEBUG1, elog, ereport, errmsg(), FreeDir(), fsync_fname(), lstat, max_replication_slots, MAXPGPATH, pg_str_endswith(), ReadDir(), ReplicationSlotsComputeRequiredLSN(), ReplicationSlotsComputeRequiredXmin(), RestoreSlotFromDisk(), rmtree(), S_ISDIR, snprintf, stat::st_mode, and WARNING.

Referenced by StartupXLOG().

1384 {
1385  DIR *replication_dir;
1386  struct dirent *replication_de;
1387 
1388  elog(DEBUG1, "starting up replication slots");
1389 
1390  /* restore all slots by iterating over all on-disk entries */
1391  replication_dir = AllocateDir("pg_replslot");
1392  while ((replication_de = ReadDir(replication_dir, "pg_replslot")) != NULL)
1393  {
1394  struct stat statbuf;
1395  char path[MAXPGPATH + 12];
1396 
1397  if (strcmp(replication_de->d_name, ".") == 0 ||
1398  strcmp(replication_de->d_name, "..") == 0)
1399  continue;
1400 
1401  snprintf(path, sizeof(path), "pg_replslot/%s", replication_de->d_name);
1402 
1403  /* we're only creating directories here, skip if it's not our's */
1404  if (lstat(path, &statbuf) == 0 && !S_ISDIR(statbuf.st_mode))
1405  continue;
1406 
1407  /* we crashed while a slot was being setup or deleted, clean up */
1408  if (pg_str_endswith(replication_de->d_name, ".tmp"))
1409  {
1410  if (!rmtree(path, true))
1411  {
1412  ereport(WARNING,
1413  (errmsg("could not remove directory \"%s\"",
1414  path)));
1415  continue;
1416  }
1417  fsync_fname("pg_replslot", true);
1418  continue;
1419  }
1420 
1421  /* looks like a slot in a normal state, restore */
1422  RestoreSlotFromDisk(replication_de->d_name);
1423  }
1424  FreeDir(replication_dir);
1425 
1426  /* currently no slots exist, we're done. */
1427  if (max_replication_slots <= 0)
1428  return;
1429 
1430  /* Now that we have recovered all the data, compute replication xmin */
1433 }
static void RestoreSlotFromDisk(const char *name)
Definition: slot.c:1658
#define DEBUG1
Definition: elog.h:25
bool pg_str_endswith(const char *str, const char *end)
Definition: string.c:31
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:666
Definition: dirent.h:9
void ReplicationSlotsComputeRequiredLSN(void)
Definition: slot.c:817
Definition: dirent.c:25
#define MAXPGPATH
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2678
#define WARNING
Definition: elog.h:40
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:42
#define ereport(elevel,...)
Definition: elog.h:157
int max_replication_slots
Definition: slot.c:99
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2744
#define S_ISDIR(m)
Definition: win32_port.h:316
#define lstat(path, sb)
Definition: win32_port.h:276
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
char d_name[MAX_PATH]
Definition: dirent.h:15
#define snprintf
Definition: port.h:216
void ReplicationSlotsComputeRequiredXmin(bool already_locked)
Definition: slot.c:767
int FreeDir(DIR *dir)
Definition: fd.c:2796

Variable Documentation

◆ max_replication_slots

◆ MyReplicationSlot

◆ ReplicationSlotCtl

ReplicationSlotCtlData* ReplicationSlotCtl = NULL

Definition at line 93 of file slot.c.

Referenced by copy_replication_slot(), and pg_get_replication_slots().