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 1116 of file slotsync.c.

1117{
1118 char *dbname;
1119
1120 /*
1121 * The slot synchronization needs a database connection for walrcv_exec to
1122 * work.
1123 */
1125 if (dbname == NULL)
1126 ereport(ERROR,
1128
1129 /*
1130 * translator: first %s is a connection option; second %s is a GUC
1131 * variable name
1132 */
1133 errmsg("replication slot synchronization requires \"%s\" to be specified in \"%s\"",
1134 "dbname", "primary_conninfo"));
1135 return dbname;
1136}
int errcode(int sqlerrcode)
Definition elog.c:874
int errmsg(const char *fmt,...)
Definition elog.c:1093
#define ERROR
Definition elog.h:39
#define ereport(elevel,...)
Definition elog.h:150
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 1820 of file slotsync.c.

1821{
1822 return syncing_slots;
1823}
static bool syncing_slots
Definition slotsync.c:137

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 1473 of file slotsync.c.

1474{
1476 char *dbname;
1477 char *err;
1480
1482
1484
1486
1487 /*
1488 * Create a per-backend PGPROC struct in shared memory. We must do this
1489 * before we access any shared memory.
1490 */
1491 InitProcess();
1492
1493 /*
1494 * Early initialization.
1495 */
1496 BaseInit();
1497
1499
1500 /*
1501 * If an exception is encountered, processing resumes here.
1502 *
1503 * We just need to clean up, report the error, and go away.
1504 *
1505 * If we do not have this handling here, then since this worker process
1506 * operates at the bottom of the exception stack, ERRORs turn into FATALs.
1507 * Therefore, we create our own exception handler to catch ERRORs.
1508 */
1509 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
1510 {
1511 /* since not using PG_TRY, must reset error stack by hand */
1513
1514 /* Prevents interrupts while cleaning up */
1516
1517 /* Report the error to the server log */
1519
1520 /*
1521 * We can now go away. Note that because we called InitProcess, a
1522 * callback was registered to do ProcKill, which will clean up
1523 * necessary state.
1524 */
1525 proc_exit(0);
1526 }
1527
1528 /* We can now handle ereport(ERROR) */
1530
1531 /* Setup signal handling */
1540
1542
1543 ereport(LOG, errmsg("slot sync worker started"));
1544
1545 /* Register it as soon as SlotSyncCtx->pid is initialized. */
1547
1548 /*
1549 * Establishes SIGALRM handler and initialize timeout module. It is needed
1550 * by InitPostgres to register different timeouts.
1551 */
1553
1554 /* Load the libpq-specific functions */
1555 load_file("libpqwalreceiver", false);
1556
1557 /*
1558 * Unblock signals (they were blocked when the postmaster forked us)
1559 */
1561
1562 /*
1563 * Set always-secure search path, so malicious users can't redirect user
1564 * code (e.g. operators).
1565 *
1566 * It's not strictly necessary since we won't be scanning or writing to
1567 * any user table locally, but it's good to retain it here for added
1568 * precaution.
1569 */
1570 SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
1571
1573
1574 /*
1575 * Connect to the database specified by the user in primary_conninfo. We
1576 * need a database connection for walrcv_exec to work which we use to
1577 * fetch slot information from the remote node. See comments atop
1578 * libpqrcv_exec.
1579 *
1580 * We do not specify a specific user here since the slot sync worker will
1581 * operate as a superuser. This is safe because the slot sync worker does
1582 * not interact with user tables, eliminating the risk of executing
1583 * arbitrary code within triggers.
1584 */
1586
1588
1590 if (cluster_name[0])
1591 appendStringInfo(&app_name, "%s_%s", cluster_name, "slotsync worker");
1592 else
1593 appendStringInfoString(&app_name, "slotsync worker");
1594
1595 /*
1596 * Establish the connection to the primary server for slot
1597 * synchronization.
1598 */
1599 wrconn = walrcv_connect(PrimaryConnInfo, false, false, false,
1600 app_name.data, &err);
1601
1602 if (!wrconn)
1603 ereport(ERROR,
1605 errmsg("synchronization worker \"%s\" could not connect to the primary server: %s",
1606 app_name.data, err));
1607
1608 pfree(app_name.data);
1609
1610 /*
1611 * Register the disconnection callback.
1612 *
1613 * XXX: This can be combined with previous cleanup registration of
1614 * slotsync_worker_onexit() but that will need the connection to be made
1615 * global and we want to avoid introducing global for this purpose.
1616 */
1618
1619 /*
1620 * Using the specified primary server connection, check that we are not a
1621 * cascading standby and slot configured in 'primary_slot_name' exists on
1622 * the primary server.
1623 */
1625
1626 /* Main loop to synchronize slots */
1627 for (;;)
1628 {
1629 bool some_slot_updated = false;
1630 bool started_tx = false;
1632
1634
1635 /*
1636 * The syscache access in fetch_remote_slots() needs a transaction
1637 * env.
1638 */
1639 if (!IsTransactionState())
1640 {
1642 started_tx = true;
1643 }
1644
1648
1649 if (started_tx)
1651
1653 }
1654
1655 /*
1656 * The slot sync worker can't get here because it will only stop when it
1657 * receives a stop request from the startup process, or when there is an
1658 * error.
1659 */
1660 Assert(false);
1661}
sigset_t UnBlockSig
Definition pqsignal.c:22
#define Assert(condition)
Definition c.h:885
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:4196
@ 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:3058
void StatementCancelHandler(SIGNAL_ARGS)
Definition postgres.c:3041
static Datum PointerGetDatum(const void *X)
Definition postgres.h:352
uint64_t Datum
Definition postgres.h:70
#define InvalidOid
void BaseInit(void)
Definition postinit.c:615
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
Definition postinit.c:718
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition procsignal.c:679
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:1327
static SlotSyncCtxStruct * SlotSyncCtx
Definition slotsync.c:114
char * CheckAndGetDbnameFromConninfo(void)
Definition slotsync.c:1116
static void ProcessSlotSyncInterrupts(void)
Definition slotsync.c:1292
static void wait_for_slot_activity(bool some_slot_updated)
Definition slotsync.c:1386
static void slotsync_worker_onexit(int code, Datum arg)
Definition slotsync.c:1340
static void validate_remote_info(WalReceiverConn *wrconn)
Definition slotsync.c:1038
static void check_and_set_sync_info(pid_t sync_process_pid)
Definition slotsync.c:1421
static List * fetch_remote_slots(WalReceiverConn *wrconn, List *slot_names)
Definition slotsync.c:860
static bool synchronize_slots(WalReceiverConn *wrconn, List *remote_slot_list, bool *slot_persistence_pending)
Definition slotsync.c:1002
void InitProcess(void)
Definition proc.c:379
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:94
#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:388
void StartTransactionCommand(void)
Definition xact.c:3080
void CommitTransactionCommand(void)
Definition xact.c:3178

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 1722 of file slotsync.c.

1723{
1725
1727
1728 SlotSyncCtx->stopSignaled = true;
1729
1730 /*
1731 * Return if neither the slot sync worker is running nor the function
1732 * pg_sync_replication_slots() is executing.
1733 */
1734 if (!SlotSyncCtx->syncing)
1735 {
1738 return;
1739 }
1740
1742
1744
1745 /*
1746 * Signal process doing slotsync, if any. The process will stop upon
1747 * detecting that the stopSignaled flag is set to true.
1748 */
1751
1752 /* Wait for slot sync to end */
1753 for (;;)
1754 {
1755 int rc;
1756
1757 /* Wait a bit, we don't expect to have to wait long */
1758 rc = WaitLatch(MyLatch,
1761
1762 if (rc & WL_LATCH_SET)
1763 {
1766 }
1767
1769
1770 /* Ensure that no process is syncing the slots. */
1771 if (!SlotSyncCtx->syncing)
1772 break;
1773
1775 }
1776
1778
1780}
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:1670
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 1838 of file slotsync.c.

1839{
1840 Size size = SlotSyncShmemSize();
1841 bool found;
1842
1844 ShmemInitStruct("Slot Sync Data", size, &found);
1845
1846 if (!found)
1847 {
1848 memset(SlotSyncCtx, 0, size);
1851 }
1852}
size_t Size
Definition c.h:631
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition shmem.c:378
Size SlotSyncShmemSize(void)
Definition slotsync.c:1829
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 1829 of file slotsync.c.

1830{
1831 return sizeof(SlotSyncCtxStruct);
1832}

Referenced by CalculateShmemSize(), and SlotSyncShmemInit().

◆ SlotSyncWorkerCanRestart()

bool SlotSyncWorkerCanRestart ( void  )
extern

Definition at line 1795 of file slotsync.c.

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

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

Referenced by LaunchMissingBackgroundProcesses().

◆ SyncReplicationSlots()

void SyncReplicationSlots ( WalReceiverConn wrconn)
extern

Definition at line 1920 of file slotsync.c.

1921{
1923 {
1925 List *slot_names = NIL; /* List of slot names to track */
1926
1928
1929 /* Check for interrupts and config changes */
1931
1933
1934 /* Retry until all the slots are sync-ready */
1935 for (;;)
1936 {
1937 bool slot_persistence_pending = false;
1938 bool some_slot_updated = false;
1939
1940 /* Check for interrupts and config changes */
1942
1943 /* We must be in a valid transaction state */
1945
1946 /*
1947 * Fetch remote slot info for the given slot_names. If slot_names
1948 * is NIL, fetch all failover-enabled slots. Note that we reuse
1949 * slot_names from the first iteration; re-fetching all failover
1950 * slots each time could cause an endless loop. Instead of
1951 * reprocessing only the pending slots in each iteration, it's
1952 * better to process all the slots received in the first
1953 * iteration. This ensures that by the time we're done, all slots
1954 * reflect the latest values.
1955 */
1956 remote_slots = fetch_remote_slots(wrconn, slot_names);
1957
1958 /* Attempt to synchronize slots */
1961
1962 /*
1963 * If slot_persistence_pending is true, extract slot names for
1964 * future iterations (only needed if we haven't done it yet)
1965 */
1966 if (slot_names == NIL && slot_persistence_pending)
1967 slot_names = extract_slot_names(remote_slots);
1968
1969 /* Free the current remote_slots list */
1971
1972 /* Done if all slots are persisted i.e are sync-ready */
1974 break;
1975
1976 /* wait before retrying again */
1978 }
1979
1980 if (slot_names)
1981 list_free_deep(slot_names);
1982
1983 /* Cleanup the synced temporary slots */
1985
1986 /* We are done with sync, so reset sync flag */
1988 }
1990}
#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:860
static void slotsync_failure_callback(int code, Datum arg)
Definition slotsync.c:1858
static List * extract_slot_names(List *remote_slots)
Definition slotsync.c:1894
static void reset_syncing_flag(void)
Definition slotsync.c:1453

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 1143 of file slotsync.c.

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