Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : * slotsync.c
3 : : * Functionality for synchronizing slots to a standby server from the
4 : : * primary server.
5 : : *
6 : : * Copyright (c) 2024-2026, PostgreSQL Global Development Group
7 : : *
8 : : * IDENTIFICATION
9 : : * src/backend/replication/logical/slotsync.c
10 : : *
11 : : * This file contains the code for slot synchronization on a physical standby
12 : : * to fetch logical failover slots information from the primary server, create
13 : : * the slots on the standby and synchronize them periodically.
14 : : *
15 : : * Slot synchronization can be performed either automatically by enabling slot
16 : : * sync worker or manually by calling SQL function pg_sync_replication_slots().
17 : : *
18 : : * If the WAL corresponding to the remote's restart_lsn is not available on the
19 : : * physical standby or the remote's catalog_xmin precedes the oldest xid for
20 : : * which it is guaranteed that rows wouldn't have been removed then we cannot
21 : : * create the local standby slot because that would mean moving the local slot
22 : : * backward and decoding won't be possible via such a slot. In this case, the
23 : : * slot will be marked as RS_TEMPORARY. Once the primary server catches up,
24 : : * the slot will be marked as RS_PERSISTENT (which means sync-ready) after
25 : : * which slot sync worker can perform the sync periodically or user can call
26 : : * pg_sync_replication_slots() periodically to perform the syncs.
27 : : *
28 : : * If synchronized slots fail to build a consistent snapshot from the
29 : : * restart_lsn before reaching confirmed_flush_lsn, they would become
30 : : * unreliable after promotion due to potential data loss from changes
31 : : * before reaching a consistent point. This can happen because the slots can
32 : : * be synced at some random time and we may not reach the consistent point
33 : : * at the same WAL location as the primary. So, we mark such slots as
34 : : * RS_TEMPORARY. Once the decoding from corresponding LSNs can reach a
35 : : * consistent point, they will be marked as RS_PERSISTENT.
36 : : *
37 : : * If the WAL prior to the remote slot's confirmed_flush_lsn has not been
38 : : * flushed on the standby, the slot is marked as RS_TEMPORARY. Once the standby
39 : : * catches up and flushes that WAL, the slot will be marked as RS_PERSISTENT.
40 : : *
41 : : * The slot sync worker waits for some time before the next synchronization,
42 : : * with the duration varying based on whether any slots were updated during
43 : : * the last cycle. Refer to the comments above wait_for_slot_activity() for
44 : : * more details.
45 : : *
46 : : * If the SQL function pg_sync_replication_slots() is used to sync the slots,
47 : : * and if the slots are not ready to be synced and are marked as RS_TEMPORARY
48 : : * because of any of the reasons mentioned above, then the SQL function also
49 : : * waits and retries until the slots are marked as RS_PERSISTENT (which means
50 : : * sync-ready). Refer to the comments in SyncReplicationSlots() for more
51 : : * details.
52 : : *
53 : : * Any standby synchronized slots will be dropped if they no longer need
54 : : * to be synchronized. See comment atop drop_local_obsolete_slots() for more
55 : : * details.
56 : : *---------------------------------------------------------------------------
57 : : */
58 : :
59 : : #include "postgres.h"
60 : :
61 : : #include <time.h>
62 : :
63 : : #include "access/xlog_internal.h"
64 : : #include "access/xlogrecovery.h"
65 : : #include "catalog/pg_database.h"
66 : : #include "libpq/pqsignal.h"
67 : : #include "pgstat.h"
68 : : #include "postmaster/interrupt.h"
69 : : #include "replication/logical.h"
70 : : #include "replication/logicalctl.h"
71 : : #include "replication/slotsync.h"
72 : : #include "replication/snapbuild.h"
73 : : #include "storage/ipc.h"
74 : : #include "storage/lmgr.h"
75 : : #include "storage/proc.h"
76 : : #include "storage/procarray.h"
77 : : #include "storage/subsystems.h"
78 : : #include "tcop/tcopprot.h"
79 : : #include "utils/builtins.h"
80 : : #include "utils/memutils.h"
81 : : #include "utils/pg_lsn.h"
82 : : #include "utils/ps_status.h"
83 : : #include "utils/timeout.h"
84 : : #include "utils/wait_event.h"
85 : :
86 : : /*
87 : : * Struct for sharing information to control slot synchronization.
88 : : *
89 : : * The 'pid' is either the slot sync worker's pid or the backend's pid running
90 : : * the SQL function pg_sync_replication_slots(). On promotion, the startup
91 : : * process sets 'stopSignaled' and uses this 'pid' to signal the synchronizing
92 : : * process with PROCSIG_SLOTSYNC_MESSAGE and also to wake it up so that the
93 : : * process can immediately stop its synchronizing work.
94 : : * Setting 'stopSignaled' on the other hand is used to handle the race
95 : : * condition when the postmaster has not noticed the promotion yet and thus may
96 : : * end up restarting the slot sync worker. If 'stopSignaled' is set, the worker
97 : : * will exit in such a case. The SQL function pg_sync_replication_slots() will
98 : : * also error out if this flag is set. Note that we don't need to reset this
99 : : * variable as after promotion the slot sync worker won't be restarted because
100 : : * the pmState changes to PM_RUN from PM_HOT_STANDBY and we don't support
101 : : * demoting primary without restarting the server.
102 : : * See LaunchMissingBackgroundProcesses.
103 : : *
104 : : * The 'syncing' flag is needed to prevent concurrent slot syncs to avoid slot
105 : : * overwrites.
106 : : *
107 : : * The 'last_start_time' is needed by postmaster to start the slot sync worker
108 : : * once per SLOTSYNC_RESTART_INTERVAL_SEC. In cases where an immediate restart
109 : : * is expected (e.g., slot sync GUCs change), slot sync worker will reset
110 : : * last_start_time before exiting, so that postmaster can start the worker
111 : : * without waiting for SLOTSYNC_RESTART_INTERVAL_SEC.
112 : : */
113 : : typedef struct SlotSyncCtxStruct
114 : : {
115 : : pid_t pid;
116 : : bool stopSignaled;
117 : : bool syncing;
118 : : time_t last_start_time;
119 : : slock_t mutex;
120 : : } SlotSyncCtxStruct;
121 : :
122 : : static SlotSyncCtxStruct *SlotSyncCtx = NULL;
123 : :
124 : : static void SlotSyncShmemRequest(void *arg);
125 : : static void SlotSyncShmemInit(void *arg);
126 : :
127 : : const ShmemCallbacks SlotSyncShmemCallbacks = {
128 : : .request_fn = SlotSyncShmemRequest,
129 : : .init_fn = SlotSyncShmemInit,
130 : : };
131 : :
132 : : /* GUC variable */
133 : : bool sync_replication_slots = false;
134 : :
135 : : /*
136 : : * The sleep time (ms) between slot-sync cycles varies dynamically
137 : : * (within a MIN/MAX range) according to slot activity. See
138 : : * wait_for_slot_activity() for details.
139 : : */
140 : : #define MIN_SLOTSYNC_WORKER_NAPTIME_MS 200
141 : : #define MAX_SLOTSYNC_WORKER_NAPTIME_MS 30000 /* 30s */
142 : :
143 : : static long sleep_ms = MIN_SLOTSYNC_WORKER_NAPTIME_MS;
144 : :
145 : : /* The restart interval for slot sync work used by postmaster */
146 : : #define SLOTSYNC_RESTART_INTERVAL_SEC 10
147 : :
148 : : /*
149 : : * Flag to tell if we are syncing replication slots. Unlike the 'syncing' flag
150 : : * in SlotSyncCtxStruct, this flag is true only if the current process is
151 : : * performing slot synchronization.
152 : : */
153 : : static bool syncing_slots = false;
154 : :
155 : : /*
156 : : * Interrupt flag set when PROCSIG_SLOTSYNC_MESSAGE is received, asking the
157 : : * slotsync worker or pg_sync_replication_slots() to stop because
158 : : * standby promotion has been triggered.
159 : : */
160 : : volatile sig_atomic_t SlotSyncShutdownPending = false;
161 : :
162 : : /*
163 : : * Structure to hold information fetched from the primary server about a logical
164 : : * replication slot.
165 : : */
166 : : typedef struct RemoteSlot
167 : : {
168 : : char *name;
169 : : char *plugin;
170 : : char *database;
171 : : bool two_phase;
172 : : bool failover;
173 : : XLogRecPtr restart_lsn;
174 : : XLogRecPtr confirmed_lsn;
175 : : XLogRecPtr two_phase_at;
176 : : TransactionId catalog_xmin;
177 : :
178 : : /* RS_INVAL_NONE if valid, or the reason of invalidation */
179 : : ReplicationSlotInvalidationCause invalidated;
180 : : } RemoteSlot;
181 : :
182 : : static void slotsync_failure_callback(int code, Datum arg);
183 : : static void update_synced_slots_inactive_since(void);
184 : :
185 : : /*
186 : : * Update slot sync skip stats. This function requires the caller to acquire
187 : : * the slot.
188 : : */
189 : : static void
190 : 58 : update_slotsync_skip_stats(SlotSyncSkipReason skip_reason)
191 : : {
192 : : ReplicationSlot *slot;
193 : :
194 : : Assert(MyReplicationSlot);
195 : :
196 : 58 : slot = MyReplicationSlot;
197 : :
198 : : /*
199 : : * Update the slot sync related stats in pg_stat_replication_slots when a
200 : : * slot sync is skipped
201 : : */
202 [ + + ]: 58 : if (skip_reason != SS_SKIP_NONE)
203 : 9 : pgstat_report_replslotsync(slot);
204 : :
205 : : /* Update the slot sync skip reason */
206 [ + + ]: 58 : if (slot->slotsync_skip_reason != skip_reason)
207 : : {
208 : 6 : SpinLockAcquire(&slot->mutex);
209 : 6 : slot->slotsync_skip_reason = skip_reason;
210 : 6 : SpinLockRelease(&slot->mutex);
211 : : }
212 : 58 : }
213 : :
214 : : /*
215 : : * If necessary, update the local synced slot's metadata based on the data
216 : : * from the remote slot.
217 : : *
218 : : * If no update was needed (the data of the remote slot is the same as the
219 : : * local slot) return false, otherwise true.
220 : : */
221 : : static bool
222 : 58 : update_local_synced_slot(RemoteSlot *remote_slot, Oid remote_dbid)
223 : : {
224 : 58 : ReplicationSlot *slot = MyReplicationSlot;
225 : 58 : bool updated_xmin_or_lsn = false;
226 : 58 : bool updated_config = false;
227 : 58 : SlotSyncSkipReason skip_reason = SS_SKIP_NONE;
228 : 58 : XLogRecPtr latestFlushPtr = GetStandbyFlushRecPtr(NULL);
229 : :
230 : : Assert(slot->data.invalidated == RS_INVAL_NONE);
231 : :
232 : : /*
233 : : * Make sure that concerned WAL is received and flushed before syncing
234 : : * slot to target lsn received from the primary server.
235 : : */
236 [ - + ]: 58 : if (remote_slot->confirmed_lsn > latestFlushPtr)
237 : : {
238 : 0 : update_slotsync_skip_stats(SS_SKIP_WAL_NOT_FLUSHED);
239 : :
240 : : /*
241 : : * Can get here only if GUC 'synchronized_standby_slots' on the
242 : : * primary server was not configured correctly.
243 : : */
244 [ # # ]: 0 : ereport(LOG,
245 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
246 : : errmsg("skipping slot synchronization because the received slot sync"
247 : : " LSN %X/%08X for slot \"%s\" is ahead of the standby position %X/%08X",
248 : : LSN_FORMAT_ARGS(remote_slot->confirmed_lsn),
249 : : remote_slot->name,
250 : : LSN_FORMAT_ARGS(latestFlushPtr)));
251 : :
252 : 0 : return false;
253 : : }
254 : :
255 : : /*
256 : : * Don't overwrite if we already have a newer catalog_xmin and
257 : : * restart_lsn.
258 : : */
259 [ + + + + ]: 110 : if (remote_slot->restart_lsn < slot->data.restart_lsn ||
260 : 52 : TransactionIdPrecedes(remote_slot->catalog_xmin,
261 : : slot->data.catalog_xmin))
262 : : {
263 : : /* Update slot sync skip stats */
264 : 9 : update_slotsync_skip_stats(SS_SKIP_WAL_OR_ROWS_REMOVED);
265 : :
266 : : /*
267 : : * This can happen in following situations:
268 : : *
269 : : * If the slot is temporary, it means either the initial WAL location
270 : : * reserved for the local slot is ahead of the remote slot's
271 : : * restart_lsn or the initial xmin_horizon computed for the local slot
272 : : * is ahead of the remote slot.
273 : : *
274 : : * If the slot is persistent, both restart_lsn and catalog_xmin of the
275 : : * synced slot could still be ahead of the remote slot. Since we use
276 : : * slot advance functionality to keep snapbuild/slot updated, it is
277 : : * possible that the restart_lsn and catalog_xmin are advanced to a
278 : : * later position than it has on the primary. This can happen when
279 : : * slot advancing machinery finds running xacts record after reaching
280 : : * the consistent state at a later point than the primary where it
281 : : * serializes the snapshot and updates the restart_lsn.
282 : : *
283 : : * We LOG the message if the slot is temporary as it can help the user
284 : : * to understand why the slot is not sync-ready. In the case of a
285 : : * persistent slot, it would be a more common case and won't directly
286 : : * impact the users, so we used DEBUG1 level to log the message.
287 : : */
288 [ + - + - ]: 9 : ereport(slot->data.persistency == RS_TEMPORARY ? LOG : DEBUG1,
289 : : errmsg("could not synchronize replication slot \"%s\"",
290 : : remote_slot->name),
291 : : errdetail("Synchronization could lead to data loss, because the remote slot needs WAL at LSN %X/%08X and catalog xmin %u, but the standby has LSN %X/%08X and catalog xmin %u.",
292 : : LSN_FORMAT_ARGS(remote_slot->restart_lsn),
293 : : remote_slot->catalog_xmin,
294 : : LSN_FORMAT_ARGS(slot->data.restart_lsn),
295 : : slot->data.catalog_xmin));
296 : :
297 : : /*
298 : : * Skip updating the configuration. This is required to avoid syncing
299 : : * two_phase_at without syncing confirmed_lsn. Otherwise, the prepared
300 : : * transaction between old confirmed_lsn and two_phase_at will
301 : : * unexpectedly get decoded and sent to the downstream after
302 : : * promotion. See comments in ReorderBufferFinishPrepared.
303 : : */
304 : 9 : return false;
305 : : }
306 : :
307 : : /*
308 : : * Attempt to sync LSNs and xmins only if remote slot is ahead of local
309 : : * slot.
310 : : */
311 [ + + ]: 49 : if (remote_slot->confirmed_lsn > slot->data.confirmed_flush ||
312 [ + + - + ]: 69 : remote_slot->restart_lsn > slot->data.restart_lsn ||
313 : 34 : TransactionIdFollows(remote_slot->catalog_xmin,
314 : : slot->data.catalog_xmin))
315 : : {
316 : : /*
317 : : * We can't directly copy the remote slot's LSN or xmin unless there
318 : : * exists a consistent snapshot at that point. Otherwise, after
319 : : * promotion, the slots may not reach a consistent point before the
320 : : * confirmed_flush_lsn which can lead to a data loss. To avoid data
321 : : * loss, we let slot machinery advance the slot which ensures that
322 : : * snapbuilder/slot statuses are updated properly.
323 : : */
324 [ + + ]: 15 : if (SnapBuildSnapshotExists(remote_slot->restart_lsn))
325 : : {
326 : : /*
327 : : * Update the slot info directly if there is a serialized snapshot
328 : : * at the restart_lsn, as the slot can quickly reach consistency
329 : : * at restart_lsn by restoring the snapshot.
330 : : */
331 : 4 : SpinLockAcquire(&slot->mutex);
332 : 4 : slot->data.restart_lsn = remote_slot->restart_lsn;
333 : 4 : slot->data.confirmed_flush = remote_slot->confirmed_lsn;
334 : 4 : slot->data.catalog_xmin = remote_slot->catalog_xmin;
335 : 4 : SpinLockRelease(&slot->mutex);
336 : :
337 : 4 : updated_xmin_or_lsn = true;
338 : : }
339 : : else
340 : : {
341 : : bool found_consistent_snapshot;
342 : 11 : XLogRecPtr old_confirmed_lsn = slot->data.confirmed_flush;
343 : 11 : XLogRecPtr old_restart_lsn = slot->data.restart_lsn;
344 : 11 : TransactionId old_catalog_xmin = slot->data.catalog_xmin;
345 : :
346 : 11 : LogicalSlotAdvanceAndCheckSnapState(remote_slot->confirmed_lsn,
347 : : &found_consistent_snapshot);
348 : :
349 : : /* Sanity check */
350 [ - + ]: 11 : if (slot->data.confirmed_flush != remote_slot->confirmed_lsn)
351 [ # # ]: 0 : ereport(ERROR,
352 : : errmsg_internal("synchronized confirmed_flush for slot \"%s\" differs from remote slot",
353 : : remote_slot->name),
354 : : errdetail_internal("Remote slot has LSN %X/%08X but local slot has LSN %X/%08X.",
355 : : LSN_FORMAT_ARGS(remote_slot->confirmed_lsn),
356 : : LSN_FORMAT_ARGS(slot->data.confirmed_flush)));
357 : :
358 : : /*
359 : : * If we can't reach a consistent snapshot, the slot won't be
360 : : * persisted. See update_and_persist_local_synced_slot().
361 : : */
362 [ - + ]: 11 : if (!found_consistent_snapshot)
363 : : {
364 : : Assert(MyReplicationSlot->data.persistency == RS_TEMPORARY);
365 : :
366 [ # # ]: 0 : ereport(LOG,
367 : : errmsg("could not synchronize replication slot \"%s\"",
368 : : remote_slot->name),
369 : : errdetail("Synchronization could lead to data loss, because the standby could not build a consistent snapshot to decode WALs at LSN %X/%08X.",
370 : : LSN_FORMAT_ARGS(slot->data.restart_lsn)));
371 : :
372 : 0 : skip_reason = SS_SKIP_NO_CONSISTENT_SNAPSHOT;
373 : : }
374 : :
375 : : /*
376 : : * It is possible that the slot's xmin or LSNs are not updated,
377 : : * when the synced slot has reached consistent snapshot state or
378 : : * cannot build one at all.
379 : : */
380 : 11 : updated_xmin_or_lsn = (old_confirmed_lsn != slot->data.confirmed_flush ||
381 [ - + - - ]: 11 : old_restart_lsn != slot->data.restart_lsn ||
382 [ # # ]: 0 : old_catalog_xmin != slot->data.catalog_xmin);
383 : : }
384 : : }
385 : :
386 : : /* Update slot sync skip stats */
387 : 49 : update_slotsync_skip_stats(skip_reason);
388 : :
389 [ + - ]: 49 : if (remote_dbid != slot->data.database ||
390 [ + + ]: 49 : remote_slot->two_phase != slot->data.two_phase ||
391 [ + - ]: 48 : remote_slot->failover != slot->data.failover ||
392 [ + - ]: 48 : strcmp(remote_slot->plugin, NameStr(slot->data.plugin)) != 0 ||
393 [ - + ]: 48 : remote_slot->two_phase_at != slot->data.two_phase_at)
394 : : {
395 : : NameData plugin_name;
396 : :
397 : : /* Avoid expensive operations while holding a spinlock. */
398 : 1 : namestrcpy(&plugin_name, remote_slot->plugin);
399 : :
400 : 1 : SpinLockAcquire(&slot->mutex);
401 : 1 : slot->data.plugin = plugin_name;
402 : 1 : slot->data.database = remote_dbid;
403 : 1 : slot->data.two_phase = remote_slot->two_phase;
404 : 1 : slot->data.two_phase_at = remote_slot->two_phase_at;
405 : 1 : slot->data.failover = remote_slot->failover;
406 : 1 : SpinLockRelease(&slot->mutex);
407 : :
408 : 1 : updated_config = true;
409 : :
410 : : /*
411 : : * Ensure that there is no risk of sending prepared transactions
412 : : * unexpectedly after the promotion.
413 : : */
414 : : Assert(slot->data.two_phase_at <= slot->data.confirmed_flush);
415 : : }
416 : :
417 : : /*
418 : : * We have to write the changed xmin to disk *before* we change the
419 : : * in-memory value, otherwise after a crash we wouldn't know that some
420 : : * catalog tuples might have been removed already.
421 : : */
422 [ + + + + ]: 49 : if (updated_config || updated_xmin_or_lsn)
423 : : {
424 : 16 : ReplicationSlotMarkDirty();
425 : 16 : ReplicationSlotSave();
426 : : }
427 : :
428 : : /*
429 : : * Now the new xmin is safely on disk, we can let the global value
430 : : * advance. We do not take ProcArrayLock or similar since we only advance
431 : : * xmin here and there's not much harm done by a concurrent computation
432 : : * missing that.
433 : : */
434 [ + + ]: 49 : if (updated_xmin_or_lsn)
435 : : {
436 : 15 : SpinLockAcquire(&slot->mutex);
437 : 15 : slot->effective_catalog_xmin = remote_slot->catalog_xmin;
438 : 15 : SpinLockRelease(&slot->mutex);
439 : :
440 : 15 : ReplicationSlotsComputeRequiredXmin(false);
441 : 15 : ReplicationSlotsComputeRequiredLSN();
442 : : }
443 : :
444 [ + + + + ]: 49 : return updated_config || updated_xmin_or_lsn;
445 : : }
446 : :
447 : : /*
448 : : * Get the list of local logical slots that are synchronized from the
449 : : * primary server.
450 : : */
451 : : static List *
452 : 37 : get_local_synced_slots(void)
453 : : {
454 : 37 : List *local_slots = NIL;
455 : :
456 : 37 : LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
457 : :
458 [ + + ]: 592 : for (int i = 0; i < max_replication_slots + max_repack_replication_slots; i++)
459 : : {
460 : 555 : ReplicationSlot *s = &ReplicationSlotCtl->replication_slots[i];
461 : :
462 : : /* Check if it is a synchronized slot */
463 [ + + + + ]: 555 : if (s->in_use && s->data.synced)
464 : : {
465 : : Assert(SlotIsLogical(s));
466 : 52 : local_slots = lappend(local_slots, s);
467 : : }
468 : : }
469 : :
470 : 37 : LWLockRelease(ReplicationSlotControlLock);
471 : :
472 : 37 : return local_slots;
473 : : }
474 : :
475 : : /*
476 : : * Helper function to check if local_slot is required to be retained.
477 : : *
478 : : * Return false either if local_slot does not exist in the remote_slots list
479 : : * or is invalidated while the corresponding remote slot is still valid,
480 : : * otherwise true.
481 : : */
482 : : static bool
483 : 52 : local_sync_slot_required(ReplicationSlot *local_slot, List *remote_slots)
484 : : {
485 : 52 : bool remote_exists = false;
486 : 52 : bool locally_invalidated = false;
487 : :
488 [ + + + + : 125 : foreach_ptr(RemoteSlot, remote_slot, remote_slots)
+ + ]
489 : : {
490 [ + + ]: 71 : if (strcmp(remote_slot->name, NameStr(local_slot->data.name)) == 0)
491 : : {
492 : 50 : remote_exists = true;
493 : :
494 : : /*
495 : : * If remote slot is not invalidated but local slot is marked as
496 : : * invalidated, then set locally_invalidated flag.
497 : : */
498 : 50 : SpinLockAcquire(&local_slot->mutex);
499 : 50 : locally_invalidated =
500 [ + - ]: 100 : (remote_slot->invalidated == RS_INVAL_NONE) &&
501 [ + + ]: 50 : (local_slot->data.invalidated != RS_INVAL_NONE);
502 : 50 : SpinLockRelease(&local_slot->mutex);
503 : :
504 : 50 : break;
505 : : }
506 : : }
507 : :
508 [ + + + + ]: 52 : return (remote_exists && !locally_invalidated);
509 : : }
510 : :
511 : : /*
512 : : * Drop local obsolete slots.
513 : : *
514 : : * Drop the local slots that no longer need to be synced i.e. these either do
515 : : * not exist on the primary or are no longer enabled for failover.
516 : : *
517 : : * Additionally, drop any slots that are valid on the primary but got
518 : : * invalidated on the standby. This situation may occur due to the following
519 : : * reasons:
520 : : * - The 'max_slot_wal_keep_size' on the standby is insufficient to retain WAL
521 : : * records from the restart_lsn of the slot.
522 : : * - 'primary_slot_name' is temporarily reset to null and the physical slot is
523 : : * removed.
524 : : * These dropped slots will get recreated in next sync-cycle and it is okay to
525 : : * drop and recreate such slots as long as these are not consumable on the
526 : : * standby (which is the case currently).
527 : : *
528 : : * Note: Change of 'wal_level' on the primary server to a level lower than
529 : : * logical may also result in slot invalidation and removal on the standby.
530 : : * This is because such 'wal_level' change is only possible if the logical
531 : : * slots are removed on the primary server, so it's expected to see the
532 : : * slots being invalidated and removed on the standby too (and re-created
533 : : * if they are re-created on the primary server).
534 : : */
535 : : static void
536 : 37 : drop_local_obsolete_slots(List *remote_slot_list)
537 : : {
538 : 37 : List *local_slots = get_local_synced_slots();
539 : :
540 [ + + + + : 126 : foreach_ptr(ReplicationSlot, local_slot, local_slots)
+ + ]
541 : : {
542 : : /* Drop the local slot if it is not required to be retained. */
543 [ + + ]: 52 : if (!local_sync_slot_required(local_slot, remote_slot_list))
544 : : {
545 : 3 : Oid slot_database = local_slot->data.database;
546 : : bool synced_slot;
547 : :
548 : : /*
549 : : * Use shared lock to prevent a conflict with
550 : : * ReplicationSlotsDropDBSlots(), trying to drop the same slot
551 : : * during a drop-database operation.
552 : : */
553 : 3 : LockSharedObject(DatabaseRelationId, slot_database, 0,
554 : : AccessShareLock);
555 : :
556 : : /*
557 : : * In the small window between getting the slot to drop and
558 : : * locking the database, there is a possibility of a parallel
559 : : * database drop by the startup process and the creation of a new
560 : : * slot by the user. This new user-created slot may end up using
561 : : * the same shared memory as that of 'local_slot'.
562 : : *
563 : : * Because local_slot still points to a reusable slot-array entry,
564 : : * its fields (name, database OID, invalidation state) may already
565 : : * describe such a replacement slot by the time we reach here.
566 : : * That means the drop decision made by local_sync_slot_required()
567 : : * above could have been based on the replacement slot's data, and
568 : : * slot_database could refer to an unrelated database. The recheck
569 : : * below keeps us from actually dropping a user-created
570 : : * replacement slot; the residual risk is confined to this cycle
571 : : * (for example, briefly locking an unrelated database) and is
572 : : * acceptable because the race is rare and non-fatal.
573 : : */
574 : 3 : SpinLockAcquire(&local_slot->mutex);
575 [ + - + - ]: 3 : synced_slot = local_slot->in_use && local_slot->data.synced;
576 : 3 : SpinLockRelease(&local_slot->mutex);
577 : :
578 [ + - ]: 3 : if (synced_slot)
579 : : {
580 : 3 : NameData slot_name = local_slot->data.name;
581 : :
582 : : /*
583 : : * Now acquire and drop the slot. Note we purposely don't
584 : : * request logical decoding to be disabled here: since this is
585 : : * a standby, which derives its logical decoding state from
586 : : * the primary, it would be wrong to do so.
587 : : */
588 : 3 : ReplicationSlotAcquire(NameStr(slot_name), true, false);
589 : 3 : ReplicationSlotDropAcquired(false);
590 : :
591 [ + - ]: 3 : ereport(LOG,
592 : : errmsg("dropped replication slot \"%s\" of database with OID %u",
593 : : NameStr(slot_name),
594 : : slot_database));
595 : : }
596 : :
597 : 3 : UnlockSharedObject(DatabaseRelationId, slot_database, 0,
598 : : AccessShareLock);
599 : : }
600 : : }
601 : 37 : }
602 : :
603 : : /*
604 : : * Reserve WAL for the currently active local slot using the specified WAL
605 : : * location (restart_lsn).
606 : : *
607 : : * If the given WAL location has been removed or is at risk of removal,
608 : : * reserve WAL using the oldest segment that is non-removable.
609 : : */
610 : : static void
611 : 9 : reserve_wal_for_local_slot(XLogRecPtr restart_lsn)
612 : : {
613 : : XLogRecPtr slot_min_lsn;
614 : : XLogRecPtr min_safe_lsn;
615 : : XLogSegNo segno;
616 : 9 : ReplicationSlot *slot = MyReplicationSlot;
617 : :
618 : : Assert(slot != NULL);
619 : : Assert(!XLogRecPtrIsValid(slot->data.restart_lsn));
620 : :
621 : : /*
622 : : * Acquire an exclusive lock to prevent the checkpoint process from
623 : : * concurrently calculating the minimum slot LSN (see
624 : : * CheckPointReplicationSlots), ensuring that if WAL reservation occurs
625 : : * first, the checkpoint must wait for the restart_lsn update before
626 : : * calculating the minimum LSN.
627 : : *
628 : : * Note: Unlike ReplicationSlotReserveWal(), this lock does not protect a
629 : : * newly synced slot from being invalidated if a concurrent checkpoint has
630 : : * invoked CheckPointReplicationSlots() before the WAL reservation here.
631 : : * This can happen because the initial restart_lsn received from the
632 : : * remote server can precede the redo pointer. Therefore, when selecting
633 : : * the initial restart_lsn, we consider using the redo pointer or the
634 : : * minimum slot LSN (if those values are greater than the remote
635 : : * restart_lsn) instead of relying solely on the remote value.
636 : : */
637 : 9 : LWLockAcquire(ReplicationSlotAllocationLock, LW_EXCLUSIVE);
638 : :
639 : : /*
640 : : * Determine the minimum non-removable LSN by comparing the redo pointer
641 : : * with the minimum slot LSN.
642 : : *
643 : : * The minimum slot LSN is considered because the redo pointer advances at
644 : : * every checkpoint, even when replication slots are present on the
645 : : * standby. In such scenarios, the redo pointer can exceed the remote
646 : : * restart_lsn, while WALs preceding the remote restart_lsn remain
647 : : * protected by a local replication slot.
648 : : */
649 : 9 : min_safe_lsn = GetRedoRecPtr();
650 : 9 : slot_min_lsn = XLogGetReplicationSlotMinimumLSN();
651 : :
652 [ + + - + ]: 9 : if (XLogRecPtrIsValid(slot_min_lsn) && min_safe_lsn > slot_min_lsn)
653 : 0 : min_safe_lsn = slot_min_lsn;
654 : :
655 : : /*
656 : : * If the minimum safe LSN is greater than the given restart_lsn, use it
657 : : * as the initial restart_lsn for the newly synced slot. Otherwise, use
658 : : * the given remote restart_lsn.
659 : : */
660 : 9 : SpinLockAcquire(&slot->mutex);
661 : 9 : slot->data.restart_lsn = Max(restart_lsn, min_safe_lsn);
662 : 9 : SpinLockRelease(&slot->mutex);
663 : :
664 : 9 : ReplicationSlotsComputeRequiredLSN();
665 : :
666 : 9 : XLByteToSeg(slot->data.restart_lsn, segno, wal_segment_size);
667 [ - + ]: 9 : if (XLogGetLastRemovedSegno() >= segno)
668 [ # # ]: 0 : elog(ERROR, "WAL required by replication slot %s has been removed concurrently",
669 : : NameStr(slot->data.name));
670 : :
671 : 9 : LWLockRelease(ReplicationSlotAllocationLock);
672 : 9 : }
673 : :
674 : : /*
675 : : * If the remote restart_lsn and catalog_xmin have caught up with the
676 : : * local ones, then update the LSNs and persist the local synced slot for
677 : : * future synchronization; otherwise, do nothing.
678 : : *
679 : : * *slot_persistence_pending is set to true if any of the slots fail to
680 : : * persist.
681 : : *
682 : : * Return true if the slot is marked as RS_PERSISTENT (sync-ready), otherwise
683 : : * false.
684 : : */
685 : : static bool
686 : 16 : update_and_persist_local_synced_slot(RemoteSlot *remote_slot, Oid remote_dbid,
687 : : bool *slot_persistence_pending)
688 : : {
689 : 16 : ReplicationSlot *slot = MyReplicationSlot;
690 : :
691 : : /* Slotsync skip stats are handled in function update_local_synced_slot() */
692 : 16 : (void) update_local_synced_slot(remote_slot, remote_dbid);
693 : :
694 : : /*
695 : : * Check if the slot cannot be synchronized. Refer to the comment atop the
696 : : * file for details on this check.
697 : : */
698 [ + + ]: 16 : if (slot->slotsync_skip_reason != SS_SKIP_NONE)
699 : : {
700 : : /*
701 : : * We reach this point when the remote slot didn't catch up to locally
702 : : * reserved position, or it cannot reach the consistent point from the
703 : : * restart_lsn, or the WAL prior to the remote confirmed flush LSN has
704 : : * not been received and flushed.
705 : : *
706 : : * We do not drop the slot because the restart_lsn and confirmed_lsn
707 : : * can be ahead of the current location when recreating the slot in
708 : : * the next cycle. It may take more time to create such a slot or
709 : : * reach the consistent point. Therefore, we keep this slot and
710 : : * attempt the synchronization in the next cycle.
711 : : *
712 : : * We also update the slot_persistence_pending parameter, so the SQL
713 : : * function can retry.
714 : : */
715 [ + + ]: 9 : if (slot_persistence_pending)
716 : 3 : *slot_persistence_pending = true;
717 : :
718 : 9 : return false;
719 : : }
720 : :
721 : : /*
722 : : * Do not persist the slot if logical decoding got disabled concurrently.
723 : : * This can happen if the last logical slot on the primary was dropped and
724 : : * the corresponding XLOG_LOGICAL_DECODING_STATUS_CHANGE record was
725 : : * replayed after we fetched the remote slot information: WAL records
726 : : * following the slot's restart_lsn might lack the information required by
727 : : * logical decoding, and the slot invalidation performed when replaying
728 : : * the record could not find our slot as it was not created yet.
729 : : *
730 : : * It is important to perform this check after creating the slot and
731 : : * before persisting it. This way, even if the status change record is
732 : : * replayed after this check, the replay will invalidate our slot.
733 : : *
734 : : * If the check fails, we keep the temporary slot and let the caller
735 : : * retry; the next cycle fetches the remote slot information again and
736 : : * will drop this slot as the remote slot no longer exists.
737 : : *
738 : : * XXX: this check cannot detect the case where logical decoding is
739 : : * already re-enabled by a slot creation on the primary at this point.
740 : : * Detecting that would require comparing the slot's restart_lsn with the
741 : : * LSN at which logical decoding was last enabled.
742 : : */
743 [ - + ]: 7 : if (!IsLogicalDecodingEnabled())
744 : : {
745 [ # # ]: 0 : ereport(LOG,
746 : : errmsg("could not synchronize replication slot \"%s\"",
747 : : remote_slot->name),
748 : : errdetail("Logical decoding was concurrently disabled."));
749 : :
750 [ # # ]: 0 : if (slot_persistence_pending)
751 : 0 : *slot_persistence_pending = true;
752 : :
753 : 0 : return false;
754 : : }
755 : :
756 : 7 : ReplicationSlotPersist();
757 : :
758 [ + - ]: 7 : ereport(LOG,
759 : : errmsg("newly created replication slot \"%s\" is sync-ready now",
760 : : remote_slot->name));
761 : :
762 : 7 : return true;
763 : : }
764 : :
765 : : /*
766 : : * Synchronize a single slot to the given position.
767 : : *
768 : : * This creates a new slot if there is no existing one and updates the
769 : : * metadata of the slot as per the data received from the primary server.
770 : : *
771 : : * The slot is created as a temporary slot and stays in the same state until the
772 : : * remote_slot catches up with locally reserved position and local slot is
773 : : * updated. The slot is then persisted and is considered as sync-ready for
774 : : * periodic syncs.
775 : : *
776 : : * *slot_persistence_pending is set to true if any of the slots fail to
777 : : * persist.
778 : : *
779 : : * Returns TRUE if the local slot is updated.
780 : : */
781 : : static bool
782 : 58 : synchronize_one_slot(RemoteSlot *remote_slot, Oid remote_dbid,
783 : : bool *slot_persistence_pending)
784 : : {
785 : : ReplicationSlot *slot;
786 : 58 : bool slot_updated = false;
787 : :
788 : : /* Search for the named slot */
789 [ + + ]: 58 : if ((slot = SearchNamedReplicationSlot(remote_slot->name, true)))
790 : : {
791 : : bool synced;
792 : :
793 : 49 : SpinLockAcquire(&slot->mutex);
794 : 49 : synced = slot->data.synced;
795 : 49 : SpinLockRelease(&slot->mutex);
796 : :
797 : : /* User-created slot with the same name exists, raise ERROR. */
798 [ - + ]: 49 : if (!synced)
799 [ # # ]: 0 : ereport(ERROR,
800 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
801 : : errmsg("exiting from slot synchronization because same"
802 : : " name slot \"%s\" already exists on the standby",
803 : : remote_slot->name));
804 : :
805 : : /*
806 : : * The slot has been synchronized before.
807 : : *
808 : : * It is important to acquire the slot here before checking
809 : : * invalidation. If we don't acquire the slot first, there could be a
810 : : * race condition that the local slot could be invalidated just after
811 : : * checking the 'invalidated' flag here and we could end up
812 : : * overwriting 'invalidated' flag to remote_slot's value. See
813 : : * InvalidatePossiblyObsoleteSlot() where it invalidates slot directly
814 : : * if the slot is not acquired by other processes.
815 : : *
816 : : * XXX: If it ever turns out that slot acquire/release is costly for
817 : : * cases when none of the slot properties is changed then we can do a
818 : : * pre-check to ensure that at least one of the slot properties is
819 : : * changed before acquiring the slot.
820 : : */
821 : 49 : ReplicationSlotAcquire(remote_slot->name, true, false);
822 : :
823 : : Assert(slot == MyReplicationSlot);
824 : :
825 : : /*
826 : : * Copy the invalidation cause from remote only if local slot is not
827 : : * invalidated locally, we don't want to overwrite existing one.
828 : : */
829 [ + - ]: 49 : if (slot->data.invalidated == RS_INVAL_NONE &&
830 [ - + ]: 49 : remote_slot->invalidated != RS_INVAL_NONE)
831 : : {
832 : 0 : SpinLockAcquire(&slot->mutex);
833 : 0 : slot->data.invalidated = remote_slot->invalidated;
834 : 0 : SpinLockRelease(&slot->mutex);
835 : :
836 : : /* Make sure the invalidated state persists across server restart */
837 : 0 : ReplicationSlotMarkDirty();
838 : 0 : ReplicationSlotSave();
839 : :
840 : 0 : slot_updated = true;
841 : : }
842 : :
843 : : /* Skip the sync of an invalidated slot */
844 [ - + ]: 49 : if (slot->data.invalidated != RS_INVAL_NONE)
845 : : {
846 : 0 : update_slotsync_skip_stats(SS_SKIP_INVALID);
847 : :
848 : 0 : ReplicationSlotRelease();
849 : 0 : return slot_updated;
850 : : }
851 : :
852 : : /* Slot not ready yet, let's attempt to make it sync-ready now. */
853 [ + + ]: 49 : if (slot->data.persistency == RS_TEMPORARY)
854 : : {
855 : 7 : slot_updated = update_and_persist_local_synced_slot(remote_slot,
856 : : remote_dbid,
857 : : slot_persistence_pending);
858 : : }
859 : :
860 : : /* Slot ready for sync, so sync it. */
861 : : else
862 : : {
863 : : /*
864 : : * Sanity check: As long as the invalidations are handled
865 : : * appropriately as above, this should never happen.
866 : : *
867 : : * We don't need to check restart_lsn here. See the comments in
868 : : * update_local_synced_slot() for details.
869 : : */
870 [ - + ]: 42 : if (remote_slot->confirmed_lsn < slot->data.confirmed_flush)
871 [ # # ]: 0 : ereport(ERROR,
872 : : errmsg_internal("cannot synchronize local slot \"%s\"",
873 : : remote_slot->name),
874 : : errdetail_internal("Local slot's start streaming location LSN(%X/%08X) is ahead of remote slot's LSN(%X/%08X).",
875 : : LSN_FORMAT_ARGS(slot->data.confirmed_flush),
876 : : LSN_FORMAT_ARGS(remote_slot->confirmed_lsn)));
877 : :
878 : 42 : slot_updated = update_local_synced_slot(remote_slot, remote_dbid);
879 : : }
880 : : }
881 : : /* Otherwise create the slot first. */
882 : : else
883 : : {
884 : : NameData plugin_name;
885 : 9 : TransactionId xmin_horizon = InvalidTransactionId;
886 : :
887 : : /* Skip creating the local slot if remote_slot is invalidated already */
888 [ - + ]: 9 : if (remote_slot->invalidated != RS_INVAL_NONE)
889 : 0 : return false;
890 : :
891 : : /*
892 : : * We create temporary slots instead of ephemeral slots here because
893 : : * we want the slots to survive after releasing them. This is done to
894 : : * avoid dropping and re-creating the slots in each synchronization
895 : : * cycle if the restart_lsn or catalog_xmin of the remote slot has not
896 : : * caught up.
897 : : */
898 : 9 : ReplicationSlotCreate(remote_slot->name, true, RS_TEMPORARY,
899 : 9 : remote_slot->two_phase,
900 : : false,
901 : 9 : remote_slot->failover,
902 : : true);
903 : :
904 : : /* For shorter lines. */
905 : 9 : slot = MyReplicationSlot;
906 : :
907 : : /* Avoid expensive operations while holding a spinlock. */
908 : 9 : namestrcpy(&plugin_name, remote_slot->plugin);
909 : :
910 : 9 : SpinLockAcquire(&slot->mutex);
911 : 9 : slot->data.database = remote_dbid;
912 : 9 : slot->data.plugin = plugin_name;
913 : 9 : SpinLockRelease(&slot->mutex);
914 : :
915 : 9 : reserve_wal_for_local_slot(remote_slot->restart_lsn);
916 : :
917 : 9 : LWLockAcquire(ReplicationSlotControlLock, LW_EXCLUSIVE);
918 : 9 : LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
919 : 9 : xmin_horizon = GetOldestSafeDecodingTransactionId(true);
920 : 9 : SpinLockAcquire(&slot->mutex);
921 : 9 : slot->effective_catalog_xmin = xmin_horizon;
922 : 9 : slot->data.catalog_xmin = xmin_horizon;
923 : 9 : SpinLockRelease(&slot->mutex);
924 : 9 : ReplicationSlotsComputeRequiredXmin(true);
925 : 9 : LWLockRelease(ProcArrayLock);
926 : 9 : LWLockRelease(ReplicationSlotControlLock);
927 : :
928 : 9 : update_and_persist_local_synced_slot(remote_slot, remote_dbid,
929 : : slot_persistence_pending);
930 : :
931 : 9 : slot_updated = true;
932 : : }
933 : :
934 : 58 : ReplicationSlotRelease();
935 : :
936 : 58 : return slot_updated;
937 : : }
938 : :
939 : : /*
940 : : * Fetch remote slots.
941 : : *
942 : : * If slot_names is NIL, fetches all failover logical slots from the
943 : : * primary server, otherwise fetches only the ones with names in slot_names.
944 : : *
945 : : * Returns a list of remote slot information structures, or NIL if none
946 : : * are found.
947 : : */
948 : : static List *
949 : 39 : fetch_remote_slots(WalReceiverConn *wrconn, List *slot_names)
950 : : {
951 : : #define SLOTSYNC_COLUMN_COUNT 10
952 : 39 : Oid slotRow[SLOTSYNC_COLUMN_COUNT] = {TEXTOID, TEXTOID, LSNOID,
953 : : LSNOID, XIDOID, BOOLOID, LSNOID, BOOLOID, TEXTOID, TEXTOID};
954 : :
955 : : WalRcvExecResult *res;
956 : : TupleTableSlot *tupslot;
957 : 39 : List *remote_slot_list = NIL;
958 : : StringInfoData query;
959 : :
960 : 39 : initStringInfo(&query);
961 : 39 : appendStringInfoString(&query,
962 : : "SELECT slot_name, plugin, confirmed_flush_lsn,"
963 : : " restart_lsn, catalog_xmin, two_phase,"
964 : : " two_phase_at, failover,"
965 : : " database, invalidation_reason"
966 : : " FROM pg_catalog.pg_replication_slots"
967 : : " WHERE failover and NOT temporary");
968 : :
969 [ + + ]: 39 : if (slot_names != NIL)
970 : : {
971 : 3 : bool first_slot = true;
972 : :
973 : : /*
974 : : * Construct the query to fetch only the specified slots
975 : : */
976 : 3 : appendStringInfoString(&query, " AND slot_name IN (");
977 : :
978 [ + - + + : 9 : foreach_ptr(char, slot_name, slot_names)
+ + ]
979 : : {
980 [ - + ]: 3 : if (!first_slot)
981 : 0 : appendStringInfoString(&query, ", ");
982 : :
983 : 3 : appendStringInfoString(&query, quote_literal_cstr(slot_name));
984 : 3 : first_slot = false;
985 : : }
986 : 3 : appendStringInfoChar(&query, ')');
987 : : }
988 : :
989 : : /* Execute the query */
990 : 39 : res = walrcv_exec(wrconn, query.data, SLOTSYNC_COLUMN_COUNT, slotRow);
991 : 39 : pfree(query.data);
992 [ + + ]: 39 : if (res->status != WALRCV_OK_TUPLES)
993 [ + - ]: 2 : ereport(ERROR,
994 : : errmsg("could not fetch failover logical slots info from the primary server: %s",
995 : : res->err));
996 : :
997 : 37 : tupslot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
998 [ + + ]: 95 : while (tuplestore_gettupleslot(res->tuplestore, true, false, tupslot))
999 : : {
1000 : : bool isnull;
1001 : 58 : RemoteSlot *remote_slot = palloc0_object(RemoteSlot);
1002 : : Datum d;
1003 : 58 : int col = 0;
1004 : :
1005 : 58 : remote_slot->name = TextDatumGetCString(slot_getattr(tupslot, ++col,
1006 : : &isnull));
1007 : : Assert(!isnull);
1008 : :
1009 : 58 : remote_slot->plugin = TextDatumGetCString(slot_getattr(tupslot, ++col,
1010 : : &isnull));
1011 : : Assert(!isnull);
1012 : :
1013 : : /*
1014 : : * It is possible to get null values for LSN and Xmin if slot is
1015 : : * invalidated on the primary server, so handle accordingly.
1016 : : */
1017 : 58 : d = slot_getattr(tupslot, ++col, &isnull);
1018 [ + - ]: 58 : remote_slot->confirmed_lsn = isnull ? InvalidXLogRecPtr :
1019 : 58 : DatumGetLSN(d);
1020 : :
1021 : 58 : d = slot_getattr(tupslot, ++col, &isnull);
1022 [ + - ]: 58 : remote_slot->restart_lsn = isnull ? InvalidXLogRecPtr : DatumGetLSN(d);
1023 : :
1024 : 58 : d = slot_getattr(tupslot, ++col, &isnull);
1025 [ + - ]: 58 : remote_slot->catalog_xmin = isnull ? InvalidTransactionId :
1026 : 58 : DatumGetTransactionId(d);
1027 : :
1028 : 58 : remote_slot->two_phase = DatumGetBool(slot_getattr(tupslot, ++col,
1029 : : &isnull));
1030 : : Assert(!isnull);
1031 : :
1032 : 58 : d = slot_getattr(tupslot, ++col, &isnull);
1033 [ + + ]: 58 : remote_slot->two_phase_at = isnull ? InvalidXLogRecPtr : DatumGetLSN(d);
1034 : :
1035 : 58 : remote_slot->failover = DatumGetBool(slot_getattr(tupslot, ++col,
1036 : : &isnull));
1037 : : Assert(!isnull);
1038 : :
1039 : 58 : remote_slot->database = TextDatumGetCString(slot_getattr(tupslot,
1040 : : ++col, &isnull));
1041 : : Assert(!isnull);
1042 : :
1043 : 58 : d = slot_getattr(tupslot, ++col, &isnull);
1044 [ - + ]: 58 : remote_slot->invalidated = isnull ? RS_INVAL_NONE :
1045 : 0 : GetSlotInvalidationCause(TextDatumGetCString(d));
1046 : :
1047 : : /* Sanity check */
1048 : : Assert(col == SLOTSYNC_COLUMN_COUNT);
1049 : :
1050 : : /*
1051 : : * If restart_lsn, confirmed_lsn or catalog_xmin is invalid but the
1052 : : * slot is valid, that means we have fetched the remote_slot in its
1053 : : * RS_EPHEMERAL state. In such a case, don't sync it; we can always
1054 : : * sync it in the next sync cycle when the remote_slot is persisted
1055 : : * and has valid lsn(s) and xmin values.
1056 : : *
1057 : : * XXX: In future, if we plan to expose 'slot->data.persistency' in
1058 : : * pg_replication_slots view, then we can avoid fetching RS_EPHEMERAL
1059 : : * slots in the first place.
1060 : : */
1061 [ + - ]: 58 : if ((!XLogRecPtrIsValid(remote_slot->restart_lsn) ||
1062 [ + - ]: 58 : !XLogRecPtrIsValid(remote_slot->confirmed_lsn) ||
1063 [ - + ]: 58 : !TransactionIdIsValid(remote_slot->catalog_xmin)) &&
1064 [ # # ]: 0 : remote_slot->invalidated == RS_INVAL_NONE)
1065 : 0 : pfree(remote_slot);
1066 : : else
1067 : : /* Create list of remote slots */
1068 : 58 : remote_slot_list = lappend(remote_slot_list, remote_slot);
1069 : :
1070 : 58 : ExecClearTuple(tupslot);
1071 : : }
1072 : :
1073 : 37 : ExecDropSingleTupleTableSlot(tupslot);
1074 : 37 : walrcv_clear_result(res);
1075 : :
1076 : 37 : return remote_slot_list;
1077 : : }
1078 : :
1079 : : /*
1080 : : * Synchronize slots.
1081 : : *
1082 : : * This function takes a list of remote slots and synchronizes them locally. It
1083 : : * creates the slots if not present on the standby and updates existing ones.
1084 : : *
1085 : : * If slot_persistence_pending is not NULL, it will be set to true if one or
1086 : : * more slots could not be persisted. This allows callers such as
1087 : : * SyncReplicationSlots() to retry those slots.
1088 : : *
1089 : : * Returns TRUE if any of the slots gets updated in this sync-cycle.
1090 : : */
1091 : : static bool
1092 : 37 : synchronize_slots(WalReceiverConn *wrconn, List *remote_slot_list,
1093 : : bool *slot_persistence_pending)
1094 : : {
1095 : 37 : bool some_slot_updated = false;
1096 : :
1097 : : /* Drop local slots that no longer need to be synced. */
1098 : 37 : drop_local_obsolete_slots(remote_slot_list);
1099 : :
1100 : : /* Now sync the slots locally */
1101 [ + + + + : 132 : foreach_ptr(RemoteSlot, remote_slot, remote_slot_list)
+ + ]
1102 : : {
1103 : 58 : Oid remote_dbid = get_database_oid(remote_slot->database, false);
1104 : :
1105 : : /*
1106 : : * Use shared lock to prevent a conflict with
1107 : : * ReplicationSlotsDropDBSlots(), trying to drop the same slot during
1108 : : * a drop-database operation.
1109 : : */
1110 : 58 : LockSharedObject(DatabaseRelationId, remote_dbid, 0, AccessShareLock);
1111 : :
1112 : 58 : some_slot_updated |= synchronize_one_slot(remote_slot, remote_dbid,
1113 : : slot_persistence_pending);
1114 : :
1115 : 58 : UnlockSharedObject(DatabaseRelationId, remote_dbid, 0, AccessShareLock);
1116 : : }
1117 : :
1118 : 37 : return some_slot_updated;
1119 : : }
1120 : :
1121 : : /*
1122 : : * Checks the remote server info.
1123 : : *
1124 : : * We ensure that the 'primary_slot_name' exists on the remote server and the
1125 : : * remote server is not a standby node.
1126 : : */
1127 : : static void
1128 : 16 : validate_remote_info(WalReceiverConn *wrconn)
1129 : : {
1130 : : #define PRIMARY_INFO_OUTPUT_COL_COUNT 2
1131 : : WalRcvExecResult *res;
1132 : 16 : Oid slotRow[PRIMARY_INFO_OUTPUT_COL_COUNT] = {BOOLOID, BOOLOID};
1133 : : StringInfoData cmd;
1134 : : bool isnull;
1135 : : TupleTableSlot *tupslot;
1136 : : bool remote_in_recovery;
1137 : : bool primary_slot_valid;
1138 : 16 : bool started_tx = false;
1139 : :
1140 : 16 : initStringInfo(&cmd);
1141 : 16 : appendStringInfo(&cmd,
1142 : : "SELECT pg_is_in_recovery(), count(*) = 1"
1143 : : " FROM pg_catalog.pg_replication_slots"
1144 : : " WHERE slot_type='physical' AND slot_name=%s",
1145 : : quote_literal_cstr(PrimarySlotName));
1146 : :
1147 : : /* The syscache access in walrcv_exec() needs a transaction env. */
1148 [ + + ]: 16 : if (!IsTransactionState())
1149 : : {
1150 : 6 : StartTransactionCommand();
1151 : 6 : started_tx = true;
1152 : : }
1153 : :
1154 : 16 : res = walrcv_exec(wrconn, cmd.data, PRIMARY_INFO_OUTPUT_COL_COUNT, slotRow);
1155 : 16 : pfree(cmd.data);
1156 : :
1157 [ - + ]: 16 : if (res->status != WALRCV_OK_TUPLES)
1158 [ # # ]: 0 : ereport(ERROR,
1159 : : errmsg("could not fetch primary slot name \"%s\" info from the primary server: %s",
1160 : : PrimarySlotName, res->err),
1161 : : errhint("Check if \"primary_slot_name\" is configured correctly."));
1162 : :
1163 : 16 : tupslot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
1164 [ - + ]: 16 : if (!tuplestore_gettupleslot(res->tuplestore, true, false, tupslot))
1165 [ # # ]: 0 : elog(ERROR,
1166 : : "failed to fetch tuple for the primary server slot specified by \"primary_slot_name\"");
1167 : :
1168 : 16 : remote_in_recovery = DatumGetBool(slot_getattr(tupslot, 1, &isnull));
1169 : : Assert(!isnull);
1170 : :
1171 : : /*
1172 : : * Slot sync is currently not supported on a cascading standby. This is
1173 : : * because if we allow it, the primary server needs to wait for all the
1174 : : * cascading standbys, otherwise, logical subscribers can still be ahead
1175 : : * of one of the cascading standbys which we plan to promote. Thus, to
1176 : : * avoid this additional complexity, we restrict it for the time being.
1177 : : */
1178 [ + + ]: 16 : if (remote_in_recovery)
1179 [ + - ]: 1 : ereport(ERROR,
1180 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1181 : : errmsg("cannot synchronize replication slots from a standby server"));
1182 : :
1183 : 15 : primary_slot_valid = DatumGetBool(slot_getattr(tupslot, 2, &isnull));
1184 : : Assert(!isnull);
1185 : :
1186 [ - + ]: 15 : if (!primary_slot_valid)
1187 [ # # ]: 0 : ereport(ERROR,
1188 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1189 : : /* translator: second %s is a GUC variable name */
1190 : : errmsg("replication slot \"%s\" specified by \"%s\" does not exist on primary server",
1191 : : PrimarySlotName, "primary_slot_name"));
1192 : :
1193 : 15 : ExecDropSingleTupleTableSlot(tupslot);
1194 : 15 : walrcv_clear_result(res);
1195 : :
1196 [ + + ]: 15 : if (started_tx)
1197 : 6 : CommitTransactionCommand();
1198 : 15 : }
1199 : :
1200 : : /*
1201 : : * Checks if dbname is specified in 'primary_conninfo'.
1202 : : *
1203 : : * Error out if not specified otherwise return it.
1204 : : */
1205 : : char *
1206 : 17 : CheckAndGetDbnameFromConninfo(void)
1207 : : {
1208 : : char *dbname;
1209 : :
1210 : : /*
1211 : : * The slot synchronization needs a database connection for walrcv_exec to
1212 : : * work.
1213 : : */
1214 : 17 : dbname = walrcv_get_dbname_from_conninfo(PrimaryConnInfo);
1215 [ + + ]: 17 : if (dbname == NULL)
1216 [ + - ]: 1 : ereport(ERROR,
1217 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1218 : :
1219 : : /*
1220 : : * translator: first %s is a connection option; second %s is a GUC
1221 : : * variable name
1222 : : */
1223 : : errmsg("replication slot synchronization requires \"%s\" to be specified in \"%s\"",
1224 : : "dbname", "primary_conninfo"));
1225 : 16 : return dbname;
1226 : : }
1227 : :
1228 : : /*
1229 : : * Return true if all necessary GUCs for slot synchronization are set
1230 : : * appropriately, otherwise, return false.
1231 : : */
1232 : : bool
1233 : 29 : ValidateSlotSyncParams(int elevel)
1234 : : {
1235 : : /*
1236 : : * Logical slot sync/creation requires logical decoding to be enabled.
1237 : : */
1238 [ - + ]: 29 : if (!IsLogicalDecodingEnabled())
1239 : : {
1240 [ # # ]: 0 : ereport(elevel,
1241 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1242 : : errmsg("replication slot synchronization requires \"effective_wal_level\" >= \"logical\" on the primary"),
1243 : : errhint("To enable logical decoding on primary, set \"wal_level\" >= \"logical\" or create at least one logical slot when \"wal_level\" = \"replica\"."));
1244 : :
1245 : 0 : return false;
1246 : : }
1247 : :
1248 : : /*
1249 : : * A physical replication slot(primary_slot_name) is required on the
1250 : : * primary to ensure that the rows needed by the standby are not removed
1251 : : * after restarting, so that the synchronized slot on the standby will not
1252 : : * be invalidated.
1253 : : */
1254 [ + - - + ]: 29 : if (PrimarySlotName == NULL || *PrimarySlotName == '\0')
1255 : : {
1256 [ # # ]: 0 : ereport(elevel,
1257 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1258 : : /* translator: %s is a GUC variable name */
1259 : : errmsg("replication slot synchronization requires \"%s\" to be set", "primary_slot_name"));
1260 : 0 : return false;
1261 : : }
1262 : :
1263 : : /*
1264 : : * hot_standby_feedback must be enabled to cooperate with the physical
1265 : : * replication slot, which allows informing the primary about the xmin and
1266 : : * catalog_xmin values on the standby.
1267 : : */
1268 [ + + ]: 29 : if (!hot_standby_feedback)
1269 : : {
1270 [ + - ]: 1 : ereport(elevel,
1271 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1272 : : /* translator: %s is a GUC variable name */
1273 : : errmsg("replication slot synchronization requires \"%s\" to be enabled",
1274 : : "hot_standby_feedback"));
1275 : 1 : return false;
1276 : : }
1277 : :
1278 : : /*
1279 : : * The primary_conninfo is required to make connection to primary for
1280 : : * getting slots information.
1281 : : */
1282 [ + - - + ]: 28 : if (PrimaryConnInfo == NULL || *PrimaryConnInfo == '\0')
1283 : : {
1284 [ # # ]: 0 : ereport(elevel,
1285 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1286 : : /* translator: %s is a GUC variable name */
1287 : : errmsg("replication slot synchronization requires \"%s\" to be set",
1288 : : "primary_conninfo"));
1289 : 0 : return false;
1290 : : }
1291 : :
1292 : 28 : return true;
1293 : : }
1294 : :
1295 : : /*
1296 : : * Re-read the config file for slot synchronization.
1297 : : *
1298 : : * Exit or throw error if relevant GUCs have changed depending on whether
1299 : : * called from slot sync worker or from the SQL function pg_sync_replication_slots()
1300 : : */
1301 : : static void
1302 : 1 : slotsync_reread_config(void)
1303 : : {
1304 : 1 : char *old_primary_conninfo = pstrdup(PrimaryConnInfo);
1305 : 1 : char *old_primary_slotname = pstrdup(PrimarySlotName);
1306 : 1 : bool old_sync_replication_slots = sync_replication_slots;
1307 : 1 : bool old_hot_standby_feedback = hot_standby_feedback;
1308 : : bool conninfo_changed;
1309 : : bool primary_slotname_changed;
1310 : 1 : bool is_slotsync_worker = AmLogicalSlotSyncWorkerProcess();
1311 : 1 : bool parameter_changed = false;
1312 : :
1313 : : if (is_slotsync_worker)
1314 : : Assert(sync_replication_slots);
1315 : :
1316 : 1 : ConfigReloadPending = false;
1317 : 1 : ProcessConfigFile(PGC_SIGHUP);
1318 : :
1319 : 1 : conninfo_changed = strcmp(old_primary_conninfo, PrimaryConnInfo) != 0;
1320 : 1 : primary_slotname_changed = strcmp(old_primary_slotname, PrimarySlotName) != 0;
1321 : 1 : pfree(old_primary_conninfo);
1322 : 1 : pfree(old_primary_slotname);
1323 : :
1324 [ - + ]: 1 : if (old_sync_replication_slots != sync_replication_slots)
1325 : : {
1326 [ # # ]: 0 : if (is_slotsync_worker)
1327 : : {
1328 [ # # ]: 0 : ereport(LOG,
1329 : : /* translator: %s is a GUC variable name */
1330 : : errmsg("replication slot synchronization worker will stop because \"%s\" is disabled",
1331 : : "sync_replication_slots"));
1332 : :
1333 : 0 : proc_exit(0);
1334 : : }
1335 : :
1336 : 0 : parameter_changed = true;
1337 : : }
1338 : : else
1339 : : {
1340 [ + - + - ]: 1 : if (conninfo_changed ||
1341 : 1 : primary_slotname_changed ||
1342 [ + - ]: 1 : (old_hot_standby_feedback != hot_standby_feedback))
1343 : : {
1344 : :
1345 [ + - ]: 1 : if (is_slotsync_worker)
1346 : : {
1347 [ + - ]: 1 : ereport(LOG,
1348 : : errmsg("replication slot synchronization worker will restart because of a parameter change"));
1349 : :
1350 : : /*
1351 : : * Reset the last-start time for this worker so that the
1352 : : * postmaster can restart it without waiting for
1353 : : * SLOTSYNC_RESTART_INTERVAL_SEC.
1354 : : */
1355 : 1 : SlotSyncCtx->last_start_time = 0;
1356 : :
1357 : 1 : proc_exit(0);
1358 : : }
1359 : :
1360 : 0 : parameter_changed = true;
1361 : : }
1362 : : }
1363 : :
1364 : : /*
1365 : : * If we have reached here with a parameter change, we must be running in
1366 : : * SQL function, emit error in such a case.
1367 : : */
1368 [ # # ]: 0 : if (parameter_changed)
1369 : : {
1370 : : Assert(!is_slotsync_worker);
1371 [ # # ]: 0 : ereport(ERROR,
1372 : : errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1373 : : errmsg("replication slot synchronization will stop because of a parameter change"));
1374 : : }
1375 : :
1376 : 0 : }
1377 : :
1378 : : /*
1379 : : * Handle receipt of an interrupt indicating a slotsync shutdown message.
1380 : : *
1381 : : * This is called within the SIGUSR1 handler. All we do here is set a flag
1382 : : * that will cause the next CHECK_FOR_INTERRUPTS() to invoke
1383 : : * ProcessSlotSyncMessage().
1384 : : */
1385 : : void
1386 : 1 : HandleSlotSyncMessageInterrupt(void)
1387 : : {
1388 : 1 : InterruptPending = true;
1389 : 1 : SlotSyncShutdownPending = true;
1390 : : /* latch will be set by procsignal_sigusr1_handler */
1391 : 1 : }
1392 : :
1393 : : /*
1394 : : * Handle a PROCSIG_SLOTSYNC_MESSAGE signal, called from ProcessInterrupts().
1395 : : *
1396 : : * If the current process is the slotsync background worker, log a message
1397 : : * and exit cleanly. If it is a backend executing pg_sync_replication_slots(),
1398 : : * raise an error, unless the sync has already finished, in which case there
1399 : : * is no need to interrupt the caller.
1400 : : */
1401 : : void
1402 : 1 : ProcessSlotSyncMessage(void)
1403 : : {
1404 : 1 : SlotSyncShutdownPending = false;
1405 : :
1406 [ + - ]: 1 : if (AmLogicalSlotSyncWorkerProcess())
1407 : : {
1408 [ + - ]: 1 : ereport(LOG,
1409 : : errmsg("replication slot synchronization worker will stop because promotion is triggered"));
1410 : 1 : proc_exit(0);
1411 : : }
1412 : : else
1413 : : {
1414 : : /*
1415 : : * If sync has already completed, there is no need to interrupt the
1416 : : * caller with an error.
1417 : : */
1418 [ # # ]: 0 : if (!IsSyncingReplicationSlots())
1419 : 0 : return;
1420 : :
1421 [ # # ]: 0 : ereport(ERROR,
1422 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1423 : : errmsg("replication slot synchronization will stop because promotion is triggered"));
1424 : : }
1425 : : }
1426 : :
1427 : : /*
1428 : : * Connection cleanup function for slotsync worker.
1429 : : *
1430 : : * Called on slotsync worker exit.
1431 : : */
1432 : : static void
1433 : 6 : slotsync_worker_disconnect(int code, Datum arg)
1434 : : {
1435 : 6 : WalReceiverConn *wrconn = (WalReceiverConn *) DatumGetPointer(arg);
1436 : :
1437 : 6 : walrcv_disconnect(wrconn);
1438 : 6 : }
1439 : :
1440 : : /*
1441 : : * Cleanup function for slotsync worker.
1442 : : *
1443 : : * Called on slotsync worker exit.
1444 : : */
1445 : : static void
1446 : 6 : slotsync_worker_onexit(int code, Datum arg)
1447 : : {
1448 : : /*
1449 : : * We need to do slots cleanup here just like WalSndErrorCleanup() does.
1450 : : *
1451 : : * The startup process during promotion invokes ShutDownSlotSync() which
1452 : : * waits for slot sync to finish and it does that by checking the
1453 : : * 'syncing' flag. Thus the slot sync worker must be done with slots'
1454 : : * release and cleanup to avoid any dangling temporary slots or active
1455 : : * slots before it marks itself as finished syncing.
1456 : : */
1457 : :
1458 : : /* Make sure active replication slots are released */
1459 [ - + ]: 6 : if (MyReplicationSlot != NULL)
1460 : 0 : ReplicationSlotRelease();
1461 : :
1462 : : /* Also cleanup the temporary slots. */
1463 : 6 : ReplicationSlotCleanup(false);
1464 : :
1465 : 6 : SpinLockAcquire(&SlotSyncCtx->mutex);
1466 : :
1467 : 6 : SlotSyncCtx->pid = InvalidPid;
1468 : :
1469 : : /*
1470 : : * If syncing_slots is true, it indicates that the process errored out
1471 : : * without resetting the flag. So, we need to clean up shared memory and
1472 : : * reset the flag here.
1473 : : */
1474 [ + - ]: 6 : if (syncing_slots)
1475 : : {
1476 : 6 : SlotSyncCtx->syncing = false;
1477 : 6 : syncing_slots = false;
1478 : : }
1479 : :
1480 : 6 : SpinLockRelease(&SlotSyncCtx->mutex);
1481 : 6 : }
1482 : :
1483 : : /*
1484 : : * Sleep for long enough that we believe it's likely that the slots on primary
1485 : : * get updated.
1486 : : *
1487 : : * If there is no slot activity the wait time between sync-cycles will double
1488 : : * (to a maximum of 30s). If there is some slot activity the wait time between
1489 : : * sync-cycles is reset to the minimum (200ms).
1490 : : */
1491 : : static void
1492 : 28 : wait_for_slot_activity(bool some_slot_updated)
1493 : : {
1494 : : int rc;
1495 : :
1496 [ + + ]: 28 : if (!some_slot_updated)
1497 : : {
1498 : : /*
1499 : : * No slots were updated, so double the sleep time, but not beyond the
1500 : : * maximum allowable value.
1501 : : */
1502 : 15 : sleep_ms = Min(sleep_ms * 2, MAX_SLOTSYNC_WORKER_NAPTIME_MS);
1503 : : }
1504 : : else
1505 : : {
1506 : : /*
1507 : : * Some slots were updated since the last sleep, so reset the sleep
1508 : : * time.
1509 : : */
1510 : 13 : sleep_ms = MIN_SLOTSYNC_WORKER_NAPTIME_MS;
1511 : : }
1512 : :
1513 : 28 : rc = WaitLatch(MyLatch,
1514 : : WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
1515 : : sleep_ms,
1516 : : WAIT_EVENT_REPLICATION_SLOTSYNC_MAIN);
1517 : :
1518 [ + + ]: 28 : if (rc & WL_LATCH_SET)
1519 : 4 : ResetLatch(MyLatch);
1520 : 28 : }
1521 : :
1522 : : /*
1523 : : * Emit an error if a concurrent sync call is in progress.
1524 : : * Otherwise, advertise that a sync is in progress.
1525 : : */
1526 : : static void
1527 : 16 : check_and_set_sync_info(pid_t sync_process_pid)
1528 : : {
1529 : 16 : SpinLockAcquire(&SlotSyncCtx->mutex);
1530 : :
1531 : : /*
1532 : : * Exit immediately if promotion has been triggered. This guards against
1533 : : * a new worker (or a call to pg_sync_replication_slots()) that starts
1534 : : * after the old worker was stopped by ShutDownSlotSync().
1535 : : */
1536 [ - + ]: 16 : if (SlotSyncCtx->stopSignaled)
1537 : : {
1538 : 0 : SpinLockRelease(&SlotSyncCtx->mutex);
1539 : :
1540 [ # # ]: 0 : if (AmLogicalSlotSyncWorkerProcess())
1541 : : {
1542 [ # # ]: 0 : ereport(DEBUG1,
1543 : : errmsg("replication slot synchronization worker will not start because promotion was triggered"));
1544 : :
1545 : 0 : proc_exit(0);
1546 : : }
1547 : : else
1548 : : {
1549 : : /*
1550 : : * For the backend executing SQL function
1551 : : * pg_sync_replication_slots().
1552 : : */
1553 [ # # ]: 0 : ereport(ERROR,
1554 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1555 : : errmsg("replication slot synchronization will not start because promotion was triggered"));
1556 : : }
1557 : : }
1558 : :
1559 [ - + ]: 16 : if (SlotSyncCtx->syncing)
1560 : : {
1561 : 0 : SpinLockRelease(&SlotSyncCtx->mutex);
1562 [ # # ]: 0 : ereport(ERROR,
1563 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1564 : : errmsg("cannot synchronize replication slots concurrently"));
1565 : : }
1566 : :
1567 : : /* The pid must not be already assigned in SlotSyncCtx */
1568 : : Assert(SlotSyncCtx->pid == InvalidPid);
1569 : :
1570 : 16 : SlotSyncCtx->syncing = true;
1571 : :
1572 : : /*
1573 : : * Advertise the required PID so that the startup process can kill the
1574 : : * slot sync process on promotion.
1575 : : */
1576 : 16 : SlotSyncCtx->pid = sync_process_pid;
1577 : :
1578 : 16 : SpinLockRelease(&SlotSyncCtx->mutex);
1579 : :
1580 : 16 : syncing_slots = true;
1581 : 16 : }
1582 : :
1583 : : /*
1584 : : * Reset syncing flag.
1585 : : */
1586 : : static void
1587 : 10 : reset_syncing_flag(void)
1588 : : {
1589 : 10 : SpinLockAcquire(&SlotSyncCtx->mutex);
1590 : 10 : SlotSyncCtx->syncing = false;
1591 : 10 : SlotSyncCtx->pid = InvalidPid;
1592 : 10 : SpinLockRelease(&SlotSyncCtx->mutex);
1593 : :
1594 : 10 : syncing_slots = false;
1595 : 10 : }
1596 : :
1597 : : /*
1598 : : * The main loop of our worker process.
1599 : : *
1600 : : * It connects to the primary server, fetches logical failover slots
1601 : : * information periodically in order to create and sync the slots.
1602 : : *
1603 : : * Note: If any changes are made here, check if the corresponding SQL
1604 : : * function logic in SyncReplicationSlots() also needs to be changed.
1605 : : */
1606 : : void
1607 : 6 : ReplSlotSyncWorkerMain(const void *startup_data, size_t startup_data_len)
1608 : : {
1609 : 6 : WalReceiverConn *wrconn = NULL;
1610 : : char *dbname;
1611 : : char *err;
1612 : : sigjmp_buf local_sigjmp_buf;
1613 : : StringInfoData app_name;
1614 : :
1615 : : Assert(startup_data_len == 0);
1616 : :
1617 : : /* Release postmaster's working memory context */
1618 [ + - ]: 6 : if (PostmasterContext)
1619 : : {
1620 : 6 : MemoryContextDelete(PostmasterContext);
1621 : 6 : PostmasterContext = NULL;
1622 : : }
1623 : :
1624 : 6 : init_ps_display(NULL);
1625 : :
1626 : : Assert(GetProcessingMode() == InitProcessing);
1627 : :
1628 : : /*
1629 : : * Create a per-backend PGPROC struct in shared memory. We must do this
1630 : : * before we access any shared memory.
1631 : : */
1632 : 6 : InitProcess();
1633 : :
1634 : : /*
1635 : : * Early initialization.
1636 : : */
1637 : 6 : BaseInit();
1638 : :
1639 : : Assert(SlotSyncCtx != NULL);
1640 : :
1641 : : /*
1642 : : * If an exception is encountered, processing resumes here.
1643 : : *
1644 : : * We just need to clean up, report the error, and go away.
1645 : : *
1646 : : * If we do not have this handling here, then since this worker process
1647 : : * operates at the bottom of the exception stack, ERRORs turn into FATALs.
1648 : : * Therefore, we create our own exception handler to catch ERRORs.
1649 : : */
1650 [ + + ]: 6 : if (sigsetjmp(local_sigjmp_buf, 1) != 0)
1651 : : {
1652 : : /* since not using PG_TRY, must reset error stack by hand */
1653 : 2 : error_context_stack = NULL;
1654 : :
1655 : : /* Prevents interrupts while cleaning up */
1656 : 2 : HOLD_INTERRUPTS();
1657 : :
1658 : : /* Report the error to the server log */
1659 : 2 : EmitErrorReport();
1660 : :
1661 : : /*
1662 : : * We can now go away. Note that because we called InitProcess, a
1663 : : * callback was registered to do ProcKill, which will clean up
1664 : : * necessary state.
1665 : : */
1666 : 2 : proc_exit(0);
1667 : : }
1668 : :
1669 : : /* We can now handle ereport(ERROR) */
1670 : 6 : PG_exception_stack = &local_sigjmp_buf;
1671 : :
1672 : : /* Setup signal handling */
1673 : 6 : pqsignal(SIGHUP, SignalHandlerForConfigReload);
1674 : 6 : pqsignal(SIGINT, StatementCancelHandler);
1675 : 6 : pqsignal(SIGTERM, die);
1676 : 6 : pqsignal(SIGFPE, FloatExceptionHandler);
1677 : 6 : pqsignal(SIGUSR1, procsignal_sigusr1_handler);
1678 : 6 : pqsignal(SIGUSR2, PG_SIG_IGN);
1679 : 6 : pqsignal(SIGPIPE, PG_SIG_IGN);
1680 : 6 : pqsignal(SIGCHLD, PG_SIG_DFL);
1681 : :
1682 : 6 : check_and_set_sync_info(MyProcPid);
1683 : :
1684 [ + - ]: 6 : ereport(LOG, errmsg("slot sync worker started"));
1685 : :
1686 : : /* Register it as soon as SlotSyncCtx->pid is initialized. */
1687 : 6 : before_shmem_exit(slotsync_worker_onexit, (Datum) 0);
1688 : :
1689 : : /*
1690 : : * Establishes SIGALRM handler and initialize timeout module. It is needed
1691 : : * by InitPostgres to register different timeouts.
1692 : : */
1693 : 6 : InitializeTimeouts();
1694 : :
1695 : : /* Load the libpq-specific functions */
1696 : 6 : load_file("libpqwalreceiver", false);
1697 : :
1698 : : /*
1699 : : * Unblock signals (they were blocked when the postmaster forked us)
1700 : : */
1701 : 6 : sigprocmask(SIG_SETMASK, &UnBlockSig, NULL);
1702 : :
1703 : : /*
1704 : : * Set always-secure search path, so malicious users can't redirect user
1705 : : * code (e.g. operators).
1706 : : *
1707 : : * It's not strictly necessary since we won't be scanning or writing to
1708 : : * any user table locally, but it's good to retain it here for added
1709 : : * precaution.
1710 : : */
1711 : 6 : SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
1712 : :
1713 : 6 : dbname = CheckAndGetDbnameFromConninfo();
1714 : :
1715 : : /*
1716 : : * Connect to the database specified by the user in primary_conninfo. We
1717 : : * need a database connection for walrcv_exec to work which we use to
1718 : : * fetch slot information from the remote node. See comments atop
1719 : : * libpqrcv_exec.
1720 : : *
1721 : : * We do not specify a specific user here since the slot sync worker will
1722 : : * operate as a superuser. This is safe because the slot sync worker does
1723 : : * not interact with user tables, eliminating the risk of executing
1724 : : * arbitrary code within triggers.
1725 : : */
1726 : 6 : InitPostgres(dbname, InvalidOid, NULL, InvalidOid, 0, NULL);
1727 : :
1728 : 6 : SetProcessingMode(NormalProcessing);
1729 : :
1730 : 6 : initStringInfo(&app_name);
1731 [ + - ]: 6 : if (cluster_name[0])
1732 : 6 : appendStringInfo(&app_name, "%s_%s", cluster_name, "slotsync worker");
1733 : : else
1734 : 0 : appendStringInfoString(&app_name, "slotsync worker");
1735 : :
1736 : : /*
1737 : : * Establish the connection to the primary server for slot
1738 : : * synchronization.
1739 : : */
1740 : 6 : wrconn = walrcv_connect(PrimaryConnInfo, false, false, false,
1741 : : app_name.data, &err);
1742 : :
1743 [ - + ]: 6 : if (!wrconn)
1744 [ # # ]: 0 : ereport(ERROR,
1745 : : errcode(ERRCODE_CONNECTION_FAILURE),
1746 : : errmsg("synchronization worker \"%s\" could not connect to the primary server: %s",
1747 : : app_name.data, err));
1748 : :
1749 : 6 : pfree(app_name.data);
1750 : :
1751 : : /*
1752 : : * Register the disconnection callback.
1753 : : *
1754 : : * XXX: This can be combined with previous cleanup registration of
1755 : : * slotsync_worker_onexit() but that will need the connection to be made
1756 : : * global and we want to avoid introducing global for this purpose.
1757 : : */
1758 : 6 : before_shmem_exit(slotsync_worker_disconnect, PointerGetDatum(wrconn));
1759 : :
1760 : : /*
1761 : : * Using the specified primary server connection, check that we are not a
1762 : : * cascading standby and slot configured in 'primary_slot_name' exists on
1763 : : * the primary server.
1764 : : */
1765 : 6 : validate_remote_info(wrconn);
1766 : :
1767 : : /* Main loop to synchronize slots */
1768 : : for (;;)
1769 : 25 : {
1770 : 31 : bool some_slot_updated = false;
1771 : 31 : bool started_tx = false;
1772 : : List *remote_slots;
1773 : :
1774 [ + + ]: 31 : CHECK_FOR_INTERRUPTS();
1775 : :
1776 [ + + ]: 28 : if (ConfigReloadPending)
1777 : 1 : slotsync_reread_config();
1778 : :
1779 : : /*
1780 : : * The syscache access in fetch_remote_slots() needs a transaction
1781 : : * env.
1782 : : */
1783 [ + - ]: 27 : if (!IsTransactionState())
1784 : : {
1785 : 27 : StartTransactionCommand();
1786 : 27 : started_tx = true;
1787 : : }
1788 : :
1789 : 27 : remote_slots = fetch_remote_slots(wrconn, NIL);
1790 : 25 : some_slot_updated = synchronize_slots(wrconn, remote_slots, NULL);
1791 : 25 : list_free_deep(remote_slots);
1792 : :
1793 [ + - ]: 25 : if (started_tx)
1794 : 25 : CommitTransactionCommand();
1795 : :
1796 : 25 : wait_for_slot_activity(some_slot_updated);
1797 : : }
1798 : :
1799 : : /*
1800 : : * The slot sync worker can't get here because it will only stop when it
1801 : : * receives a stop request from the startup process, or when there is an
1802 : : * error.
1803 : : */
1804 : : Assert(false);
1805 : : }
1806 : :
1807 : : /*
1808 : : * Update the inactive_since property for synced slots.
1809 : : *
1810 : : * Note that this function is currently called when we shutdown the slot
1811 : : * sync machinery.
1812 : : */
1813 : : static void
1814 : 1028 : update_synced_slots_inactive_since(void)
1815 : : {
1816 : 1028 : TimestampTz now = 0;
1817 : :
1818 : : /*
1819 : : * We need to update inactive_since only when we are promoting standby to
1820 : : * correctly interpret the inactive_since if the standby gets promoted
1821 : : * without a restart. We don't want the slots to appear inactive for a
1822 : : * long time after promotion if they haven't been synchronized recently.
1823 : : * Whoever acquires the slot, i.e., makes the slot active, will reset it.
1824 : : */
1825 [ + + ]: 1028 : if (!StandbyMode)
1826 : 969 : return;
1827 : :
1828 : : /* The slot sync worker or the SQL function mustn't be running by now */
1829 : : Assert((SlotSyncCtx->pid == InvalidPid) && !SlotSyncCtx->syncing);
1830 : :
1831 : 59 : LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
1832 : :
1833 [ + + ]: 927 : for (int i = 0; i < max_replication_slots + max_repack_replication_slots; i++)
1834 : : {
1835 : 868 : ReplicationSlot *s = &ReplicationSlotCtl->replication_slots[i];
1836 : :
1837 : : /* Check if it is a synchronized slot */
1838 [ + + + + ]: 868 : if (s->in_use && s->data.synced)
1839 : : {
1840 : : Assert(SlotIsLogical(s));
1841 : :
1842 : : /* The slot must not be acquired by any process */
1843 : : Assert(s->active_proc == INVALID_PROC_NUMBER);
1844 : :
1845 : : /* Use the same inactive_since time for all the slots. */
1846 [ + + ]: 3 : if (now == 0)
1847 : 2 : now = GetCurrentTimestamp();
1848 : :
1849 : 3 : ReplicationSlotSetInactiveSince(s, now, true);
1850 : : }
1851 : : }
1852 : :
1853 : 59 : LWLockRelease(ReplicationSlotControlLock);
1854 : : }
1855 : :
1856 : : /*
1857 : : * Shut down slot synchronization.
1858 : : *
1859 : : * This function sets stopSignaled=true and wakes up the slot sync process
1860 : : * (either worker or backend running the SQL function pg_sync_replication_slots())
1861 : : * so that worker can exit or the SQL function pg_sync_replication_slots() can
1862 : : * finish. It also waits till the slot sync worker has exited or
1863 : : * pg_sync_replication_slots() has finished.
1864 : : */
1865 : : void
1866 : 1028 : ShutDownSlotSync(void)
1867 : : {
1868 : : pid_t sync_process_pid;
1869 : :
1870 : 1028 : SpinLockAcquire(&SlotSyncCtx->mutex);
1871 : :
1872 : 1028 : SlotSyncCtx->stopSignaled = true;
1873 : :
1874 : : /*
1875 : : * Return if neither the slot sync worker is running nor the function
1876 : : * pg_sync_replication_slots() is executing.
1877 : : */
1878 [ + + ]: 1028 : if (!SlotSyncCtx->syncing)
1879 : : {
1880 : 1027 : SpinLockRelease(&SlotSyncCtx->mutex);
1881 : 1027 : update_synced_slots_inactive_since();
1882 : 1027 : return;
1883 : : }
1884 : :
1885 : 1 : sync_process_pid = SlotSyncCtx->pid;
1886 : :
1887 : 1 : SpinLockRelease(&SlotSyncCtx->mutex);
1888 : :
1889 : : /*
1890 : : * Signal process doing slotsync, if any, asking it to stop.
1891 : : */
1892 [ + - ]: 1 : if (sync_process_pid != InvalidPid)
1893 : 1 : SendProcSignal(sync_process_pid, PROCSIG_SLOTSYNC_MESSAGE,
1894 : : INVALID_PROC_NUMBER);
1895 : :
1896 : : /* Wait for slot sync to end */
1897 : : for (;;)
1898 : 0 : {
1899 : : int rc;
1900 : :
1901 : : /* Wait a bit, we don't expect to have to wait long */
1902 : 1 : rc = WaitLatch(MyLatch,
1903 : : WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
1904 : : 10L, WAIT_EVENT_REPLICATION_SLOTSYNC_SHUTDOWN);
1905 : :
1906 [ - + ]: 1 : if (rc & WL_LATCH_SET)
1907 : : {
1908 : 0 : ResetLatch(MyLatch);
1909 [ # # ]: 0 : CHECK_FOR_INTERRUPTS();
1910 : : }
1911 : :
1912 : 1 : SpinLockAcquire(&SlotSyncCtx->mutex);
1913 : :
1914 : : /* Ensure that no process is syncing the slots. */
1915 [ + - ]: 1 : if (!SlotSyncCtx->syncing)
1916 : 1 : break;
1917 : :
1918 : 0 : SpinLockRelease(&SlotSyncCtx->mutex);
1919 : : }
1920 : :
1921 : 1 : SpinLockRelease(&SlotSyncCtx->mutex);
1922 : :
1923 : 1 : update_synced_slots_inactive_since();
1924 : : }
1925 : :
1926 : : /*
1927 : : * SlotSyncWorkerCanRestart
1928 : : *
1929 : : * Return true, indicating worker is allowed to restart, if enough time has
1930 : : * passed since it was last launched to reach SLOTSYNC_RESTART_INTERVAL_SEC.
1931 : : * Otherwise return false.
1932 : : *
1933 : : * This is a safety valve to protect against continuous respawn attempts if the
1934 : : * worker is dying immediately at launch. Note that since we will retry to
1935 : : * launch the worker from the postmaster main loop, we will get another
1936 : : * chance later.
1937 : : */
1938 : : bool
1939 : 17 : SlotSyncWorkerCanRestart(void)
1940 : : {
1941 : 17 : time_t curtime = time(NULL);
1942 : :
1943 : : /*
1944 : : * If first time through, or time somehow went backwards, always update
1945 : : * last_start_time to match the current clock and allow worker start.
1946 : : * Otherwise allow it only once enough time has elapsed.
1947 : : */
1948 [ + + ]: 17 : if (SlotSyncCtx->last_start_time == 0 ||
1949 [ + - ]: 11 : curtime < SlotSyncCtx->last_start_time ||
1950 [ - + ]: 11 : curtime - SlotSyncCtx->last_start_time >= SLOTSYNC_RESTART_INTERVAL_SEC)
1951 : : {
1952 : 6 : SlotSyncCtx->last_start_time = curtime;
1953 : 6 : return true;
1954 : : }
1955 : 11 : return false;
1956 : : }
1957 : :
1958 : : /*
1959 : : * Is current process syncing replication slots?
1960 : : *
1961 : : * Could be either backend executing SQL function or slot sync worker.
1962 : : */
1963 : : bool
1964 : 31 : IsSyncingReplicationSlots(void)
1965 : : {
1966 : 31 : return syncing_slots;
1967 : : }
1968 : :
1969 : : /*
1970 : : * Register shared memory space needed for slot synchronization.
1971 : : */
1972 : : static void
1973 : 1267 : SlotSyncShmemRequest(void *arg)
1974 : : {
1975 : 1267 : ShmemRequestStruct(.name = "Slot Sync Data",
1976 : : .size = sizeof(SlotSyncCtxStruct),
1977 : : .ptr = (void **) &SlotSyncCtx,
1978 : : );
1979 : 1267 : }
1980 : :
1981 : : /*
1982 : : * Initialize shared memory for slot synchronization.
1983 : : */
1984 : : static void
1985 : 1264 : SlotSyncShmemInit(void *arg)
1986 : : {
1987 : 1264 : memset(SlotSyncCtx, 0, sizeof(SlotSyncCtxStruct));
1988 : 1264 : SlotSyncCtx->pid = InvalidPid;
1989 : 1264 : SpinLockInit(&SlotSyncCtx->mutex);
1990 : 1264 : }
1991 : :
1992 : : /*
1993 : : * Error cleanup callback for slot sync SQL function.
1994 : : */
1995 : : static void
1996 : 1 : slotsync_failure_callback(int code, Datum arg)
1997 : : {
1998 : 1 : WalReceiverConn *wrconn = (WalReceiverConn *) DatumGetPointer(arg);
1999 : :
2000 : : /*
2001 : : * We need to do slots cleanup here just like WalSndErrorCleanup() does.
2002 : : *
2003 : : * The startup process during promotion invokes ShutDownSlotSync() which
2004 : : * waits for slot sync to finish and it does that by checking the
2005 : : * 'syncing' flag. Thus the SQL function must be done with slots' release
2006 : : * and cleanup to avoid any dangling temporary slots or active slots
2007 : : * before it marks itself as finished syncing.
2008 : : */
2009 : :
2010 : : /* Make sure active replication slots are released */
2011 [ - + ]: 1 : if (MyReplicationSlot != NULL)
2012 : 0 : ReplicationSlotRelease();
2013 : :
2014 : : /* Also cleanup the synced temporary slots. */
2015 : 1 : ReplicationSlotCleanup(true);
2016 : :
2017 : : /*
2018 : : * The set syncing_slots indicates that the process errored out without
2019 : : * resetting the flag. So, we need to clean up shared memory and reset the
2020 : : * flag here.
2021 : : */
2022 [ + - ]: 1 : if (syncing_slots)
2023 : 1 : reset_syncing_flag();
2024 : :
2025 : 1 : walrcv_disconnect(wrconn);
2026 : 1 : }
2027 : :
2028 : : /*
2029 : : * Helper function to extract slot names from a list of remote slots
2030 : : */
2031 : : static List *
2032 : 2 : extract_slot_names(List *remote_slots)
2033 : : {
2034 : 2 : List *slot_names = NIL;
2035 : :
2036 [ + - + + : 6 : foreach_ptr(RemoteSlot, remote_slot, remote_slots)
+ + ]
2037 : : {
2038 : : char *slot_name;
2039 : :
2040 : 2 : slot_name = pstrdup(remote_slot->name);
2041 : 2 : slot_names = lappend(slot_names, slot_name);
2042 : : }
2043 : :
2044 : 2 : return slot_names;
2045 : : }
2046 : :
2047 : : /*
2048 : : * Synchronize the failover enabled replication slots using the specified
2049 : : * primary server connection.
2050 : : *
2051 : : * Repeatedly fetches and updates replication slot information from the
2052 : : * primary until all slots are at least "sync ready".
2053 : : *
2054 : : * Exits early if promotion is triggered or certain critical
2055 : : * configuration parameters have changed.
2056 : : */
2057 : : void
2058 : 10 : SyncReplicationSlots(WalReceiverConn *wrconn)
2059 : : {
2060 [ + + ]: 10 : PG_ENSURE_ERROR_CLEANUP(slotsync_failure_callback, PointerGetDatum(wrconn));
2061 : : {
2062 : 10 : List *remote_slots = NIL;
2063 : 10 : List *slot_names = NIL; /* List of slot names to track */
2064 : : MemoryContext sync_retry_ctx;
2065 : :
2066 : 10 : check_and_set_sync_info(MyProcPid);
2067 : :
2068 : 10 : validate_remote_info(wrconn);
2069 : :
2070 : : /*
2071 : : * Setup and use a per-sync-cycle memory context, which is reset every
2072 : : * time we loop below. This avoids having to retail freeing the memory
2073 : : * used in each sync cycle.
2074 : : */
2075 : 9 : sync_retry_ctx = AllocSetContextCreate(CurrentMemoryContext,
2076 : : "slot sync retry context",
2077 : : ALLOCSET_DEFAULT_SIZES);
2078 : :
2079 : : /* Retry until all the slots are sync-ready */
2080 : : for (;;)
2081 : 3 : {
2082 : 12 : bool slot_persistence_pending = false;
2083 : 12 : bool some_slot_updated = false;
2084 : : MemoryContext oldctx;
2085 : :
2086 : : /* Check for interrupts and config changes */
2087 [ - + ]: 12 : CHECK_FOR_INTERRUPTS();
2088 : :
2089 [ - + ]: 12 : if (ConfigReloadPending)
2090 : 0 : slotsync_reread_config();
2091 : :
2092 : : /* We must be in a valid transaction state */
2093 : : Assert(IsTransactionState());
2094 : :
2095 : 12 : MemoryContextReset(sync_retry_ctx);
2096 : 12 : oldctx = MemoryContextSwitchTo(sync_retry_ctx);
2097 : :
2098 : : /*
2099 : : * Fetch remote slot info for the given slot_names. If slot_names
2100 : : * is NIL, fetch all failover-enabled slots. Note that we reuse
2101 : : * slot_names from the first iteration; re-fetching all failover
2102 : : * slots each time could cause an endless loop. Instead of
2103 : : * reprocessing only the pending slots in each iteration, it's
2104 : : * better to process all the slots received in the first
2105 : : * iteration. This ensures that by the time we're done, all slots
2106 : : * reflect the latest values.
2107 : : */
2108 : 12 : remote_slots = fetch_remote_slots(wrconn, slot_names);
2109 : :
2110 : : /* Attempt to synchronize slots */
2111 : 12 : some_slot_updated = synchronize_slots(wrconn, remote_slots,
2112 : : &slot_persistence_pending);
2113 : :
2114 : : /*
2115 : : * slot_names must survive later sync_retry_ctx resets, so copy it
2116 : : * in the outer context.
2117 : : */
2118 : 12 : MemoryContextSwitchTo(oldctx);
2119 : :
2120 : : /*
2121 : : * If slot_persistence_pending is true, extract slot names for
2122 : : * future iterations (only needed if we haven't done it yet)
2123 : : */
2124 [ + + + + ]: 12 : if (slot_names == NIL && slot_persistence_pending)
2125 : 2 : slot_names = extract_slot_names(remote_slots);
2126 : :
2127 : : /* Done if all slots are persisted i.e are sync-ready */
2128 [ + + ]: 12 : if (!slot_persistence_pending)
2129 : 9 : break;
2130 : :
2131 : : /* wait before retrying again */
2132 : 3 : wait_for_slot_activity(some_slot_updated);
2133 : : }
2134 : :
2135 : 9 : MemoryContextDelete(sync_retry_ctx);
2136 : :
2137 [ + + ]: 9 : if (slot_names)
2138 : 2 : list_free_deep(slot_names);
2139 : :
2140 : : /* Cleanup the synced temporary slots */
2141 : 9 : ReplicationSlotCleanup(true);
2142 : :
2143 : : /* We are done with sync, so reset sync flag */
2144 : 9 : reset_syncing_flag();
2145 : : }
2146 [ - + ]: 10 : PG_END_ENSURE_ERROR_CLEANUP(slotsync_failure_callback, PointerGetDatum(wrconn));
2147 : 9 : }
|