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

Go to the source code of this file.

Functions

charCheckAndGetDbnameFromConninfo (void)
 
bool ValidateSlotSyncParams (int elevel)
 
pg_noreturn void ReplSlotSyncWorkerMain (const void *startup_data, size_t startup_data_len)
 
void ShutDownSlotSync (void)
 
bool SlotSyncWorkerCanRestart (void)
 
bool IsSyncingReplicationSlots (void)
 
Size SlotSyncShmemSize (void)
 
void SlotSyncShmemInit (void)
 
void SyncReplicationSlots (WalReceiverConn *wrconn)
 

Variables

PGDLLIMPORT bool sync_replication_slots
 
PGDLLIMPORT charPrimaryConnInfo
 
PGDLLIMPORT charPrimarySlotName
 

Function Documentation

◆ CheckAndGetDbnameFromConninfo()

char * CheckAndGetDbnameFromConninfo ( void  )
extern

Definition at line 1121 of file slotsync.c.

1122{
1123 char *dbname;
1124
1125 /*
1126 * The slot synchronization needs a database connection for walrcv_exec to
1127 * work.
1128 */
1130 if (dbname == NULL)
1131 ereport(ERROR,
1133
1134 /*
1135 * translator: first %s is a connection option; second %s is a GUC
1136 * variable name
1137 */
1138 errmsg("replication slot synchronization requires \"%s\" to be specified in \"%s\"",
1139 "dbname", "primary_conninfo"));
1140 return dbname;
1141}
int errcode(int sqlerrcode)
Definition elog.c:874
#define ERROR
Definition elog.h:39
#define ereport(elevel,...)
Definition elog.h:150
static char * errmsg
static int fb(int x)
char * dbname
Definition streamutil.c:49
#define walrcv_get_dbname_from_conninfo(conninfo)
char * PrimaryConnInfo

References dbname, ereport, errcode(), errmsg, ERROR, fb(), PrimaryConnInfo, and walrcv_get_dbname_from_conninfo.

Referenced by pg_sync_replication_slots(), and ReplSlotSyncWorkerMain().

◆ IsSyncingReplicationSlots()

bool IsSyncingReplicationSlots ( void  )
extern

Definition at line 1825 of file slotsync.c.

1826{
1827 return syncing_slots;
1828}
static bool syncing_slots
Definition slotsync.c:142

References syncing_slots.

Referenced by CreateDecodingContext(), GetStandbyFlushRecPtr(), and ReplicationSlotCreate().

◆ ReplSlotSyncWorkerMain()

pg_noreturn void ReplSlotSyncWorkerMain ( const void startup_data,
size_t  startup_data_len 
)
extern

Definition at line 1478 of file slotsync.c.

1479{
1481 char *dbname;
1482 char *err;
1485
1487
1489
1491
1492 /*
1493 * Create a per-backend PGPROC struct in shared memory. We must do this
1494 * before we access any shared memory.
1495 */
1496 InitProcess();
1497
1498 /*
1499 * Early initialization.
1500 */
1501 BaseInit();
1502
1504
1505 /*
1506 * If an exception is encountered, processing resumes here.
1507 *
1508 * We just need to clean up, report the error, and go away.
1509 *
1510 * If we do not have this handling here, then since this worker process
1511 * operates at the bottom of the exception stack, ERRORs turn into FATALs.
1512 * Therefore, we create our own exception handler to catch ERRORs.
1513 */
1514 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
1515 {
1516 /* since not using PG_TRY, must reset error stack by hand */
1518
1519 /* Prevents interrupts while cleaning up */
1521
1522 /* Report the error to the server log */
1524
1525 /*
1526 * We can now go away. Note that because we called InitProcess, a
1527 * callback was registered to do ProcKill, which will clean up
1528 * necessary state.
1529 */
1530 proc_exit(0);
1531 }
1532
1533 /* We can now handle ereport(ERROR) */
1535
1536 /* Setup signal handling */
1545
1547
1548 ereport(LOG, errmsg("slot sync worker started"));
1549
1550 /* Register it as soon as SlotSyncCtx->pid is initialized. */
1552
1553 /*
1554 * Establishes SIGALRM handler and initialize timeout module. It is needed
1555 * by InitPostgres to register different timeouts.
1556 */
1558
1559 /* Load the libpq-specific functions */
1560 load_file("libpqwalreceiver", false);
1561
1562 /*
1563 * Unblock signals (they were blocked when the postmaster forked us)
1564 */
1566
1567 /*
1568 * Set always-secure search path, so malicious users can't redirect user
1569 * code (e.g. operators).
1570 *
1571 * It's not strictly necessary since we won't be scanning or writing to
1572 * any user table locally, but it's good to retain it here for added
1573 * precaution.
1574 */
1575 SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
1576
1578
1579 /*
1580 * Connect to the database specified by the user in primary_conninfo. We
1581 * need a database connection for walrcv_exec to work which we use to
1582 * fetch slot information from the remote node. See comments atop
1583 * libpqrcv_exec.
1584 *
1585 * We do not specify a specific user here since the slot sync worker will
1586 * operate as a superuser. This is safe because the slot sync worker does
1587 * not interact with user tables, eliminating the risk of executing
1588 * arbitrary code within triggers.
1589 */
1591
1593
1595 if (cluster_name[0])
1596 appendStringInfo(&app_name, "%s_%s", cluster_name, "slotsync worker");
1597 else
1598 appendStringInfoString(&app_name, "slotsync worker");
1599
1600 /*
1601 * Establish the connection to the primary server for slot
1602 * synchronization.
1603 */
1604 wrconn = walrcv_connect(PrimaryConnInfo, false, false, false,
1605 app_name.data, &err);
1606
1607 if (!wrconn)
1608 ereport(ERROR,
1610 errmsg("synchronization worker \"%s\" could not connect to the primary server: %s",
1611 app_name.data, err));
1612
1613 pfree(app_name.data);
1614
1615 /*
1616 * Register the disconnection callback.
1617 *
1618 * XXX: This can be combined with previous cleanup registration of
1619 * slotsync_worker_onexit() but that will need the connection to be made
1620 * global and we want to avoid introducing global for this purpose.
1621 */
1623
1624 /*
1625 * Using the specified primary server connection, check that we are not a
1626 * cascading standby and slot configured in 'primary_slot_name' exists on
1627 * the primary server.
1628 */
1630
1631 /* Main loop to synchronize slots */
1632 for (;;)
1633 {
1634 bool some_slot_updated = false;
1635 bool started_tx = false;
1637
1639
1640 /*
1641 * The syscache access in fetch_remote_slots() needs a transaction
1642 * env.
1643 */
1644 if (!IsTransactionState())
1645 {
1647 started_tx = true;
1648 }
1649
1653
1654 if (started_tx)
1656
1658 }
1659
1660 /*
1661 * The slot sync worker can't get here because it will only stop when it
1662 * receives a stop request from the startup process, or when there is an
1663 * error.
1664 */
1665 Assert(false);
1666}
sigset_t UnBlockSig
Definition pqsignal.c:22
#define Assert(condition)
Definition c.h:945
void load_file(const char *filename, bool restricted)
Definition dfmgr.c:149
void EmitErrorReport(void)
Definition elog.c:1882
ErrorContextCallback * error_context_stack
Definition elog.c:99
sigjmp_buf * PG_exception_stack
Definition elog.c:101
#define LOG
Definition elog.h:31
void err(int eval, const char *fmt,...)
Definition err.c:43
int MyProcPid
Definition globals.c:47
void SetConfigOption(const char *name, const char *value, GucContext context, GucSource source)
Definition guc.c:4228
@ PGC_S_OVERRIDE
Definition guc.h:123
@ PGC_SUSET
Definition guc.h:78
char * cluster_name
Definition guc_tables.c:564
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition interrupt.c:61
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition ipc.c:344
void proc_exit(int code)
Definition ipc.c:105
void list_free_deep(List *list)
Definition list.c:1560
void pfree(void *pointer)
Definition mcxt.c:1616
@ NormalProcessing
Definition miscadmin.h:472
@ InitProcessing
Definition miscadmin.h:471
#define GetProcessingMode()
Definition miscadmin.h:481
#define HOLD_INTERRUPTS()
Definition miscadmin.h:134
#define SetProcessingMode(mode)
Definition miscadmin.h:483
#define NIL
Definition pg_list.h:68
#define die(msg)
#define pqsignal
Definition port.h:547
void FloatExceptionHandler(SIGNAL_ARGS)
Definition postgres.c:3059
void StatementCancelHandler(SIGNAL_ARGS)
Definition postgres.c:3042
static Datum PointerGetDatum(const void *X)
Definition postgres.h:342
uint64_t Datum
Definition postgres.h:70
#define InvalidOid
void BaseInit(void)
Definition postinit.c:616
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
Definition postinit.c:719
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition procsignal.c:680
void init_ps_display(const char *fixed_part)
Definition ps_status.c:285
static void slotsync_worker_disconnect(int code, Datum arg)
Definition slotsync.c:1332
static SlotSyncCtxStruct * SlotSyncCtx
Definition slotsync.c:119
char * CheckAndGetDbnameFromConninfo(void)
Definition slotsync.c:1121
static void ProcessSlotSyncInterrupts(void)
Definition slotsync.c:1297
static void wait_for_slot_activity(bool some_slot_updated)
Definition slotsync.c:1391
static void slotsync_worker_onexit(int code, Datum arg)
Definition slotsync.c:1345
static void validate_remote_info(WalReceiverConn *wrconn)
Definition slotsync.c:1043
static void check_and_set_sync_info(pid_t sync_process_pid)
Definition slotsync.c:1426
static List * fetch_remote_slots(WalReceiverConn *wrconn, List *slot_names)
Definition slotsync.c:865
static bool synchronize_slots(WalReceiverConn *wrconn, List *remote_slot_list, bool *slot_persistence_pending)
Definition slotsync.c:1007
void InitProcess(void)
Definition proc.c:380
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition stringinfo.c:145
void appendStringInfoString(StringInfo str, const char *s)
Definition stringinfo.c:230
void initStringInfo(StringInfo str)
Definition stringinfo.c:97
Definition pg_list.h:54
void InitializeTimeouts(void)
Definition timeout.c:470
static WalReceiverConn * wrconn
Definition walreceiver.c:95
#define walrcv_connect(conninfo, replication, logical, must_use_password, appname, err)
#define SIGCHLD
Definition win32_port.h:168
#define SIGHUP
Definition win32_port.h:158
#define SIGPIPE
Definition win32_port.h:163
#define SIGUSR1
Definition win32_port.h:170
#define SIGUSR2
Definition win32_port.h:171
bool IsTransactionState(void)
Definition xact.c:389
void StartTransactionCommand(void)
Definition xact.c:3081
void CommitTransactionCommand(void)
Definition xact.c:3179

References appendStringInfo(), appendStringInfoString(), Assert, BaseInit(), before_shmem_exit(), check_and_set_sync_info(), CheckAndGetDbnameFromConninfo(), cluster_name, CommitTransactionCommand(), dbname, die, EmitErrorReport(), ereport, err(), errcode(), errmsg, ERROR, error_context_stack, fb(), fetch_remote_slots(), FloatExceptionHandler(), GetProcessingMode, HOLD_INTERRUPTS, init_ps_display(), InitializeTimeouts(), InitPostgres(), InitProcess(), InitProcessing, initStringInfo(), InvalidOid, IsTransactionState(), list_free_deep(), load_file(), LOG, MyProcPid, NIL, NormalProcessing, pfree(), PG_exception_stack, PGC_S_OVERRIDE, PGC_SUSET, PointerGetDatum(), pqsignal, PrimaryConnInfo, proc_exit(), ProcessSlotSyncInterrupts(), procsignal_sigusr1_handler(), SetConfigOption(), SetProcessingMode, SIGCHLD, SIGHUP, SignalHandlerForConfigReload(), SIGPIPE, SIGUSR1, SIGUSR2, slotsync_worker_disconnect(), slotsync_worker_onexit(), SlotSyncCtx, StartTransactionCommand(), StatementCancelHandler(), synchronize_slots(), UnBlockSig, validate_remote_info(), wait_for_slot_activity(), walrcv_connect, and wrconn.

◆ ShutDownSlotSync()

void ShutDownSlotSync ( void  )
extern

Definition at line 1727 of file slotsync.c.

1728{
1730
1732
1733 SlotSyncCtx->stopSignaled = true;
1734
1735 /*
1736 * Return if neither the slot sync worker is running nor the function
1737 * pg_sync_replication_slots() is executing.
1738 */
1739 if (!SlotSyncCtx->syncing)
1740 {
1743 return;
1744 }
1745
1747
1749
1750 /*
1751 * Signal process doing slotsync, if any. The process will stop upon
1752 * detecting that the stopSignaled flag is set to true.
1753 */
1756
1757 /* Wait for slot sync to end */
1758 for (;;)
1759 {
1760 int rc;
1761
1762 /* Wait a bit, we don't expect to have to wait long */
1763 rc = WaitLatch(MyLatch,
1766
1767 if (rc & WL_LATCH_SET)
1768 {
1771 }
1772
1774
1775 /* Ensure that no process is syncing the slots. */
1776 if (!SlotSyncCtx->syncing)
1777 break;
1778
1780 }
1781
1783
1785}
struct Latch * MyLatch
Definition globals.c:63
void ResetLatch(Latch *latch)
Definition latch.c:374
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition latch.c:172
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:123
#define InvalidPid
Definition miscadmin.h:32
static void update_synced_slots_inactive_since(void)
Definition slotsync.c:1675
static void SpinLockRelease(volatile slock_t *lock)
Definition spin.h:62
static void SpinLockAcquire(volatile slock_t *lock)
Definition spin.h:56
#define WL_TIMEOUT
#define WL_EXIT_ON_PM_DEATH
#define WL_LATCH_SET
#define kill(pid, sig)
Definition win32_port.h:490

References CHECK_FOR_INTERRUPTS, fb(), InvalidPid, kill, SlotSyncCtxStruct::mutex, MyLatch, SlotSyncCtxStruct::pid, ResetLatch(), SIGUSR1, SlotSyncCtx, SpinLockAcquire(), SpinLockRelease(), SlotSyncCtxStruct::stopSignaled, SlotSyncCtxStruct::syncing, update_synced_slots_inactive_since(), WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, and WL_TIMEOUT.

Referenced by FinishWalRecovery().

◆ SlotSyncShmemInit()

void SlotSyncShmemInit ( void  )
extern

Definition at line 1843 of file slotsync.c.

1844{
1845 Size size = SlotSyncShmemSize();
1846 bool found;
1847
1849 ShmemInitStruct("Slot Sync Data", size, &found);
1850
1851 if (!found)
1852 {
1853 memset(SlotSyncCtx, 0, size);
1856 }
1857}
size_t Size
Definition c.h:691
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition shmem.c:381
Size SlotSyncShmemSize(void)
Definition slotsync.c:1834
static void SpinLockInit(volatile slock_t *lock)
Definition spin.h:50

References fb(), InvalidPid, SlotSyncCtxStruct::mutex, SlotSyncCtxStruct::pid, ShmemInitStruct(), SlotSyncCtx, SlotSyncShmemSize(), and SpinLockInit().

Referenced by CreateOrAttachShmemStructs().

◆ SlotSyncShmemSize()

Size SlotSyncShmemSize ( void  )
extern

Definition at line 1834 of file slotsync.c.

1835{
1836 return sizeof(SlotSyncCtxStruct);
1837}

Referenced by CalculateShmemSize(), and SlotSyncShmemInit().

◆ SlotSyncWorkerCanRestart()

bool SlotSyncWorkerCanRestart ( void  )
extern

Definition at line 1800 of file slotsync.c.

1801{
1802 time_t curtime = time(NULL);
1803
1804 /*
1805 * If first time through, or time somehow went backwards, always update
1806 * last_start_time to match the current clock and allow worker start.
1807 * Otherwise allow it only once enough time has elapsed.
1808 */
1809 if (SlotSyncCtx->last_start_time == 0 ||
1810 curtime < SlotSyncCtx->last_start_time ||
1812 {
1814 return true;
1815 }
1816 return false;
1817}
#define SLOTSYNC_RESTART_INTERVAL_SEC
Definition slotsync.c:135
time_t last_start_time
Definition slotsync.c:115

References fb(), SlotSyncCtxStruct::last_start_time, SLOTSYNC_RESTART_INTERVAL_SEC, and SlotSyncCtx.

Referenced by LaunchMissingBackgroundProcesses().

◆ SyncReplicationSlots()

void SyncReplicationSlots ( WalReceiverConn wrconn)
extern

Definition at line 1925 of file slotsync.c.

1926{
1928 {
1930 List *slot_names = NIL; /* List of slot names to track */
1931
1933
1934 /* Check for interrupts and config changes */
1936
1938
1939 /* Retry until all the slots are sync-ready */
1940 for (;;)
1941 {
1942 bool slot_persistence_pending = false;
1943 bool some_slot_updated = false;
1944
1945 /* Check for interrupts and config changes */
1947
1948 /* We must be in a valid transaction state */
1950
1951 /*
1952 * Fetch remote slot info for the given slot_names. If slot_names
1953 * is NIL, fetch all failover-enabled slots. Note that we reuse
1954 * slot_names from the first iteration; re-fetching all failover
1955 * slots each time could cause an endless loop. Instead of
1956 * reprocessing only the pending slots in each iteration, it's
1957 * better to process all the slots received in the first
1958 * iteration. This ensures that by the time we're done, all slots
1959 * reflect the latest values.
1960 */
1961 remote_slots = fetch_remote_slots(wrconn, slot_names);
1962
1963 /* Attempt to synchronize slots */
1966
1967 /*
1968 * If slot_persistence_pending is true, extract slot names for
1969 * future iterations (only needed if we haven't done it yet)
1970 */
1971 if (slot_names == NIL && slot_persistence_pending)
1972 slot_names = extract_slot_names(remote_slots);
1973
1974 /* Free the current remote_slots list */
1976
1977 /* Done if all slots are persisted i.e are sync-ready */
1979 break;
1980
1981 /* wait before retrying again */
1983 }
1984
1985 if (slot_names)
1986 list_free_deep(slot_names);
1987
1988 /* Cleanup the synced temporary slots */
1990
1991 /* We are done with sync, so reset sync flag */
1993 }
1995}
#define PG_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition ipc.h:47
#define PG_END_ENSURE_ERROR_CLEANUP(cleanup_function, arg)
Definition ipc.h:52
void ReplicationSlotCleanup(bool synced_only)
Definition slot.c:861
static void slotsync_failure_callback(int code, Datum arg)
Definition slotsync.c:1863
static List * extract_slot_names(List *remote_slots)
Definition slotsync.c:1899
static void reset_syncing_flag(void)
Definition slotsync.c:1458

References Assert, check_and_set_sync_info(), extract_slot_names(), fb(), fetch_remote_slots(), IsTransactionState(), list_free_deep(), MyProcPid, NIL, PG_END_ENSURE_ERROR_CLEANUP, PG_ENSURE_ERROR_CLEANUP, PointerGetDatum(), ProcessSlotSyncInterrupts(), ReplicationSlotCleanup(), reset_syncing_flag(), slotsync_failure_callback(), synchronize_slots(), validate_remote_info(), wait_for_slot_activity(), and wrconn.

Referenced by pg_sync_replication_slots().

◆ ValidateSlotSyncParams()

bool ValidateSlotSyncParams ( int  elevel)
extern

Definition at line 1148 of file slotsync.c.

1149{
1150 /*
1151 * Logical slot sync/creation requires logical decoding to be enabled.
1152 */
1154 {
1155 ereport(elevel,
1157 errmsg("replication slot synchronization requires \"effective_wal_level\" >= \"logical\" on the primary"),
1158 errhint("To enable logical decoding on primary, set \"wal_level\" >= \"logical\" or create at least one logical slot when \"wal_level\" = \"replica\"."));
1159
1160 return false;
1161 }
1162
1163 /*
1164 * A physical replication slot(primary_slot_name) is required on the
1165 * primary to ensure that the rows needed by the standby are not removed
1166 * after restarting, so that the synchronized slot on the standby will not
1167 * be invalidated.
1168 */
1169 if (PrimarySlotName == NULL || *PrimarySlotName == '\0')
1170 {
1171 ereport(elevel,
1173 /* translator: %s is a GUC variable name */
1174 errmsg("replication slot synchronization requires \"%s\" to be set", "primary_slot_name"));
1175 return false;
1176 }
1177
1178 /*
1179 * hot_standby_feedback must be enabled to cooperate with the physical
1180 * replication slot, which allows informing the primary about the xmin and
1181 * catalog_xmin values on the standby.
1182 */
1184 {
1185 ereport(elevel,
1187 /* translator: %s is a GUC variable name */
1188 errmsg("replication slot synchronization requires \"%s\" to be enabled",
1189 "hot_standby_feedback"));
1190 return false;
1191 }
1192
1193 /*
1194 * The primary_conninfo is required to make connection to primary for
1195 * getting slots information.
1196 */
1197 if (PrimaryConnInfo == NULL || *PrimaryConnInfo == '\0')
1198 {
1199 ereport(elevel,
1201 /* translator: %s is a GUC variable name */
1202 errmsg("replication slot synchronization requires \"%s\" to be set",
1203 "primary_conninfo"));
1204 return false;
1205 }
1206
1207 return true;
1208}
int errhint(const char *fmt,...) pg_attribute_printf(1
bool IsLogicalDecodingEnabled(void)
Definition logicalctl.c:205
bool hot_standby_feedback
Definition walreceiver.c:92
char * PrimarySlotName

References ereport, errcode(), errhint(), errmsg, fb(), hot_standby_feedback, IsLogicalDecodingEnabled(), PrimaryConnInfo, and PrimarySlotName.

Referenced by LaunchMissingBackgroundProcesses(), and pg_sync_replication_slots().

Variable Documentation

◆ PrimaryConnInfo

◆ PrimarySlotName

◆ sync_replication_slots

PGDLLIMPORT bool sync_replication_slots
extern