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

1178{
1179 char *dbname;
1180
1181 /*
1182 * The slot synchronization needs a database connection for walrcv_exec to
1183 * work.
1184 */
1186 if (dbname == NULL)
1187 ereport(ERROR,
1189
1190 /*
1191 * translator: first %s is a connection option; second %s is a GUC
1192 * variable name
1193 */
1194 errmsg("replication slot synchronization requires \"%s\" to be specified in \"%s\"",
1195 "dbname", "primary_conninfo"));
1196 return dbname;
1197}
int errcode(int sqlerrcode)
Definition elog.c:863
int errmsg(const char *fmt,...)
Definition elog.c:1080
#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 1883 of file slotsync.c.

1884{
1885 return syncing_slots;
1886}
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 1534 of file slotsync.c.

1535{
1537 char *dbname;
1538 char *err;
1541
1543
1545
1547
1549
1550 /*
1551 * Create a per-backend PGPROC struct in shared memory. We must do this
1552 * before we access any shared memory.
1553 */
1554 InitProcess();
1555
1556 /*
1557 * Early initialization.
1558 */
1559 BaseInit();
1560
1562
1563 /*
1564 * If an exception is encountered, processing resumes here.
1565 *
1566 * We just need to clean up, report the error, and go away.
1567 *
1568 * If we do not have this handling here, then since this worker process
1569 * operates at the bottom of the exception stack, ERRORs turn into FATALs.
1570 * Therefore, we create our own exception handler to catch ERRORs.
1571 */
1572 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
1573 {
1574 /* since not using PG_TRY, must reset error stack by hand */
1576
1577 /* Prevents interrupts while cleaning up */
1579
1580 /* Report the error to the server log */
1582
1583 /*
1584 * We can now go away. Note that because we called InitProcess, a
1585 * callback was registered to do ProcKill, which will clean up
1586 * necessary state.
1587 */
1588 proc_exit(0);
1589 }
1590
1591 /* We can now handle ereport(ERROR) */
1593
1594 /* Setup signal handling */
1603
1605
1606 ereport(LOG, errmsg("slot sync worker started"));
1607
1608 /* Register it as soon as SlotSyncCtx->pid is initialized. */
1610
1611 /*
1612 * Establishes SIGALRM handler and initialize timeout module. It is needed
1613 * by InitPostgres to register different timeouts.
1614 */
1616
1617 /* Load the libpq-specific functions */
1618 load_file("libpqwalreceiver", false);
1619
1620 /*
1621 * Unblock signals (they were blocked when the postmaster forked us)
1622 */
1624
1625 /*
1626 * Set always-secure search path, so malicious users can't redirect user
1627 * code (e.g. operators).
1628 *
1629 * It's not strictly necessary since we won't be scanning or writing to
1630 * any user table locally, but it's good to retain it here for added
1631 * precaution.
1632 */
1633 SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
1634
1636
1637 /*
1638 * Connect to the database specified by the user in primary_conninfo. We
1639 * need a database connection for walrcv_exec to work which we use to
1640 * fetch slot information from the remote node. See comments atop
1641 * libpqrcv_exec.
1642 *
1643 * We do not specify a specific user here since the slot sync worker will
1644 * operate as a superuser. This is safe because the slot sync worker does
1645 * not interact with user tables, eliminating the risk of executing
1646 * arbitrary code within triggers.
1647 */
1649
1651
1653 if (cluster_name[0])
1654 appendStringInfo(&app_name, "%s_%s", cluster_name, "slotsync worker");
1655 else
1656 appendStringInfoString(&app_name, "slotsync worker");
1657
1658 /*
1659 * Establish the connection to the primary server for slot
1660 * synchronization.
1661 */
1662 wrconn = walrcv_connect(PrimaryConnInfo, false, false, false,
1663 app_name.data, &err);
1664
1665 if (!wrconn)
1666 ereport(ERROR,
1668 errmsg("synchronization worker \"%s\" could not connect to the primary server: %s",
1669 app_name.data, err));
1670
1671 pfree(app_name.data);
1672
1673 /*
1674 * Register the disconnection callback.
1675 *
1676 * XXX: This can be combined with previous cleanup registration of
1677 * slotsync_worker_onexit() but that will need the connection to be made
1678 * global and we want to avoid introducing global for this purpose.
1679 */
1681
1682 /*
1683 * Using the specified primary server connection, check that we are not a
1684 * cascading standby and slot configured in 'primary_slot_name' exists on
1685 * the primary server.
1686 */
1688
1689 /* Main loop to synchronize slots */
1690 for (;;)
1691 {
1692 bool some_slot_updated = false;
1693 bool started_tx = false;
1695
1697
1698 /*
1699 * The syscache access in fetch_remote_slots() needs a transaction
1700 * env.
1701 */
1702 if (!IsTransactionState())
1703 {
1705 started_tx = true;
1706 }
1707
1711
1712 if (started_tx)
1714
1716 }
1717
1718 /*
1719 * The slot sync worker can't get here because it will only stop when it
1720 * receives a stop request from the startup process, or when there is an
1721 * error.
1722 */
1723 Assert(false);
1724}
sigset_t UnBlockSig
Definition pqsignal.c:22
#define Assert(condition)
Definition c.h:873
void load_file(const char *filename, bool restricted)
Definition dfmgr.c:149
void EmitErrorReport(void)
Definition elog.c:1704
ErrorContextCallback * error_context_stack
Definition elog.c:95
sigjmp_buf * PG_exception_stack
Definition elog.c:97
#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:555
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
@ B_SLOTSYNC_WORKER
Definition miscadmin.h:348
BackendType MyBackendType
Definition miscinit.c:64
#define NIL
Definition pg_list.h:68
#define die(msg)
#define pqsignal
Definition port.h:547
void FloatExceptionHandler(SIGNAL_ARGS)
Definition postgres.c:3079
void StatementCancelHandler(SIGNAL_ARGS)
Definition postgres.c:3062
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:607
void InitPostgres(const char *in_dbname, Oid dboid, const char *username, Oid useroid, bits32 flags, char *out_dbname)
Definition postinit.c:710
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition procsignal.c:677
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:1388
static SlotSyncCtxStruct * SlotSyncCtx
Definition slotsync.c:114
char * CheckAndGetDbnameFromConninfo(void)
Definition slotsync.c:1177
static void ProcessSlotSyncInterrupts(void)
Definition slotsync.c:1353
static void wait_for_slot_activity(bool some_slot_updated)
Definition slotsync.c:1447
static void slotsync_worker_onexit(int code, Datum arg)
Definition slotsync.c:1401
static void validate_remote_info(WalReceiverConn *wrconn)
Definition slotsync.c:1099
static void check_and_set_sync_info(pid_t sync_process_pid)
Definition slotsync.c:1482
static List * fetch_remote_slots(WalReceiverConn *wrconn, List *slot_names)
Definition slotsync.c:921
static bool synchronize_slots(WalReceiverConn *wrconn, List *remote_slot_list, bool *slot_persistence_pending)
Definition slotsync.c:1063
void InitProcess(void)
Definition proc.c:395
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, B_SLOTSYNC_WORKER, 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, MyBackendType, 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 1785 of file slotsync.c.

1786{
1788
1790
1791 SlotSyncCtx->stopSignaled = true;
1792
1793 /*
1794 * Return if neither the slot sync worker is running nor the function
1795 * pg_sync_replication_slots() is executing.
1796 */
1797 if (!SlotSyncCtx->syncing)
1798 {
1801 return;
1802 }
1803
1805
1807
1808 /*
1809 * Signal process doing slotsync, if any. The process will stop upon
1810 * detecting that the stopSignaled flag is set to true.
1811 */
1814
1815 /* Wait for slot sync to end */
1816 for (;;)
1817 {
1818 int rc;
1819
1820 /* Wait a bit, we don't expect to have to wait long */
1821 rc = WaitLatch(MyLatch,
1824
1825 if (rc & WL_LATCH_SET)
1826 {
1829 }
1830
1832
1833 /* Ensure that no process is syncing the slots. */
1834 if (!SlotSyncCtx->syncing)
1835 break;
1836
1838 }
1839
1841
1843}
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:1733
#define SpinLockRelease(lock)
Definition spin.h:61
#define SpinLockAcquire(lock)
Definition spin.h:59
#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 1901 of file slotsync.c.

1902{
1903 Size size = SlotSyncShmemSize();
1904 bool found;
1905
1907 ShmemInitStruct("Slot Sync Data", size, &found);
1908
1909 if (!found)
1910 {
1911 memset(SlotSyncCtx, 0, size);
1914 }
1915}
size_t Size
Definition c.h:619
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition shmem.c:389
Size SlotSyncShmemSize(void)
Definition slotsync.c:1892
#define SpinLockInit(lock)
Definition spin.h:57

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

Referenced by CreateOrAttachShmemStructs().

◆ SlotSyncShmemSize()

Size SlotSyncShmemSize ( void  )
extern

Definition at line 1892 of file slotsync.c.

1893{
1894 return sizeof(SlotSyncCtxStruct);
1895}

Referenced by CalculateShmemSize(), and SlotSyncShmemInit().

◆ SlotSyncWorkerCanRestart()

bool SlotSyncWorkerCanRestart ( void  )
extern

Definition at line 1858 of file slotsync.c.

1859{
1860 time_t curtime = time(NULL);
1861
1862 /*
1863 * If first time through, or time somehow went backwards, always update
1864 * last_start_time to match the current clock and allow worker start.
1865 * Otherwise allow it only once enough time has elapsed.
1866 */
1867 if (SlotSyncCtx->last_start_time == 0 ||
1868 curtime < SlotSyncCtx->last_start_time ||
1870 {
1872 return true;
1873 }
1874 return false;
1875}
#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 1983 of file slotsync.c.

1984{
1986 {
1988 List *slot_names = NIL; /* List of slot names to track */
1989
1991
1992 /* Check for interrupts and config changes */
1994
1996
1997 /* Retry until all the slots are sync-ready */
1998 for (;;)
1999 {
2000 bool slot_persistence_pending = false;
2001 bool some_slot_updated = false;
2002
2003 /* Check for interrupts and config changes */
2005
2006 /* We must be in a valid transaction state */
2008
2009 /*
2010 * Fetch remote slot info for the given slot_names. If slot_names
2011 * is NIL, fetch all failover-enabled slots. Note that we reuse
2012 * slot_names from the first iteration; re-fetching all failover
2013 * slots each time could cause an endless loop. Instead of
2014 * reprocessing only the pending slots in each iteration, it's
2015 * better to process all the slots received in the first
2016 * iteration. This ensures that by the time we're done, all slots
2017 * reflect the latest values.
2018 */
2019 remote_slots = fetch_remote_slots(wrconn, slot_names);
2020
2021 /* Attempt to synchronize slots */
2024
2025 /*
2026 * If slot_persistence_pending is true, extract slot names for
2027 * future iterations (only needed if we haven't done it yet)
2028 */
2029 if (slot_names == NIL && slot_persistence_pending)
2030 slot_names = extract_slot_names(remote_slots);
2031
2032 /* Free the current remote_slots list */
2034
2035 /* Done if all slots are persisted i.e are sync-ready */
2037 break;
2038
2039 /* wait before retrying again */
2041 }
2042
2043 if (slot_names)
2044 list_free_deep(slot_names);
2045
2046 /* Cleanup the synced temporary slots */
2048
2049 /* We are done with sync, so reset sync flag */
2051 }
2053}
#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:857
static void slotsync_failure_callback(int code, Datum arg)
Definition slotsync.c:1921
static List * extract_slot_names(List *remote_slots)
Definition slotsync.c:1957
static void reset_syncing_flag(void)
Definition slotsync.c:1514

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

1205{
1206 /*
1207 * Logical slot sync/creation requires logical decoding to be enabled.
1208 */
1210 {
1211 ereport(elevel,
1213 errmsg("replication slot synchronization requires \"effective_wal_level\" >= \"logical\" on the primary"),
1214 errhint("To enable logical decoding on primary, set \"wal_level\" >= \"logical\" or create at least one logical slot when \"wal_level\" = \"replica\"."));
1215
1216 return false;
1217 }
1218
1219 /*
1220 * A physical replication slot(primary_slot_name) is required on the
1221 * primary to ensure that the rows needed by the standby are not removed
1222 * after restarting, so that the synchronized slot on the standby will not
1223 * be invalidated.
1224 */
1225 if (PrimarySlotName == NULL || *PrimarySlotName == '\0')
1226 {
1227 ereport(elevel,
1229 /* translator: %s is a GUC variable name */
1230 errmsg("replication slot synchronization requires \"%s\" to be set", "primary_slot_name"));
1231 return false;
1232 }
1233
1234 /*
1235 * hot_standby_feedback must be enabled to cooperate with the physical
1236 * replication slot, which allows informing the primary about the xmin and
1237 * catalog_xmin values on the standby.
1238 */
1240 {
1241 ereport(elevel,
1243 /* translator: %s is a GUC variable name */
1244 errmsg("replication slot synchronization requires \"%s\" to be enabled",
1245 "hot_standby_feedback"));
1246 return false;
1247 }
1248
1249 /*
1250 * The primary_conninfo is required to make connection to primary for
1251 * getting slots information.
1252 */
1253 if (PrimaryConnInfo == NULL || *PrimaryConnInfo == '\0')
1254 {
1255 ereport(elevel,
1257 /* translator: %s is a GUC variable name */
1258 errmsg("replication slot synchronization requires \"%s\" to be set",
1259 "primary_conninfo"));
1260 return false;
1261 }
1262
1263 return true;
1264}
int errhint(const char *fmt,...)
Definition elog.c:1330
bool IsLogicalDecodingEnabled(void)
Definition logicalctl.c:204
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