PostgreSQL Source Code git master
Loading...
Searching...
No Matches
slotsync.c
Go to the documentation of this file.
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 * The slot sync worker waits for some time before the next synchronization,
38 * with the duration varying based on whether any slots were updated during
39 * the last cycle. Refer to the comments above wait_for_slot_activity() for
40 * more details.
41 *
42 * If the SQL function pg_sync_replication_slots() is used to sync the slots,
43 * and if the slots are not ready to be synced and are marked as RS_TEMPORARY
44 * because of any of the reasons mentioned above, then the SQL function also
45 * waits and retries until the slots are marked as RS_PERSISTENT (which means
46 * sync-ready). Refer to the comments in SyncReplicationSlots() for more
47 * details.
48 *
49 * Any standby synchronized slots will be dropped if they no longer need
50 * to be synchronized. See comment atop drop_local_obsolete_slots() for more
51 * details.
52 *---------------------------------------------------------------------------
53 */
54
55#include "postgres.h"
56
57#include <time.h>
58
60#include "access/xlogrecovery.h"
61#include "catalog/pg_database.h"
62#include "libpq/pqsignal.h"
63#include "pgstat.h"
65#include "replication/logical.h"
68#include "storage/ipc.h"
69#include "storage/lmgr.h"
70#include "storage/proc.h"
71#include "storage/procarray.h"
72#include "tcop/tcopprot.h"
73#include "utils/builtins.h"
74#include "utils/memutils.h"
75#include "utils/pg_lsn.h"
76#include "utils/ps_status.h"
77#include "utils/timeout.h"
78
79/*
80 * Struct for sharing information to control slot synchronization.
81 *
82 * The 'pid' is either the slot sync worker's pid or the backend's pid running
83 * the SQL function pg_sync_replication_slots(). When the startup process sets
84 * 'stopSignaled' during promotion, it uses this 'pid' to wake up the currently
85 * synchronizing process so that the process can immediately stop its
86 * synchronizing work on seeing 'stopSignaled' set.
87 * Setting 'stopSignaled' is also used to handle the race condition when the
88 * postmaster has not noticed the promotion yet and thus may end up restarting
89 * the slot sync worker. If 'stopSignaled' is set, the worker will exit in such a
90 * case. The SQL function pg_sync_replication_slots() will also error out if
91 * this flag is set. Note that we don't need to reset this variable as after
92 * promotion the slot sync worker won't be restarted because the pmState
93 * changes to PM_RUN from PM_HOT_STANDBY and we don't support demoting
94 * primary without restarting the server. See LaunchMissingBackgroundProcesses.
95 *
96 * The 'syncing' flag is needed to prevent concurrent slot syncs to avoid slot
97 * overwrites.
98 *
99 * The 'last_start_time' is needed by postmaster to start the slot sync worker
100 * once per SLOTSYNC_RESTART_INTERVAL_SEC. In cases where an immediate restart
101 * is expected (e.g., slot sync GUCs change), slot sync worker will reset
102 * last_start_time before exiting, so that postmaster can start the worker
103 * without waiting for SLOTSYNC_RESTART_INTERVAL_SEC.
104 */
113
115
116/* GUC variable */
118
119/*
120 * The sleep time (ms) between slot-sync cycles varies dynamically
121 * (within a MIN/MAX range) according to slot activity. See
122 * wait_for_slot_activity() for details.
123 */
124#define MIN_SLOTSYNC_WORKER_NAPTIME_MS 200
125#define MAX_SLOTSYNC_WORKER_NAPTIME_MS 30000 /* 30s */
126
128
129/* The restart interval for slot sync work used by postmaster */
130#define SLOTSYNC_RESTART_INTERVAL_SEC 10
131
132/*
133 * Flag to tell if we are syncing replication slots. Unlike the 'syncing' flag
134 * in SlotSyncCtxStruct, this flag is true only if the current process is
135 * performing slot synchronization.
136 */
137static bool syncing_slots = false;
138
139/*
140 * Structure to hold information fetched from the primary server about a logical
141 * replication slot.
142 */
158
159static void slotsync_failure_callback(int code, Datum arg);
160static void update_synced_slots_inactive_since(void);
161
162/*
163 * Update slot sync skip stats. This function requires the caller to acquire
164 * the slot.
165 */
166static void
168{
169 ReplicationSlot *slot;
170
172
173 slot = MyReplicationSlot;
174
175 /*
176 * Update the slot sync related stats in pg_stat_replication_slots when a
177 * slot sync is skipped
178 */
181
182 /* Update the slot sync skip reason */
184 {
185 SpinLockAcquire(&slot->mutex);
187 SpinLockRelease(&slot->mutex);
188 }
189}
190
191/*
192 * If necessary, update the local synced slot's metadata based on the data
193 * from the remote slot.
194 *
195 * If no update was needed (the data of the remote slot is the same as the
196 * local slot) return false, otherwise true.
197 *
198 * *found_consistent_snapshot will be true iff the remote slot's LSN or xmin is
199 * modified, and decoding from the corresponding LSN's can reach a
200 * consistent snapshot.
201 *
202 * *remote_slot_precedes will be true if the remote slot's LSN or xmin
203 * precedes locally reserved position.
204 */
205static bool
209{
211 bool updated_xmin_or_lsn = false;
212 bool updated_config = false;
214
216
219
221 *remote_slot_precedes = false;
222
223 /*
224 * Don't overwrite if we already have a newer catalog_xmin and
225 * restart_lsn.
226 */
227 if (remote_slot->restart_lsn < slot->data.restart_lsn ||
229 slot->data.catalog_xmin))
230 {
231 /* Update slot sync skip stats */
233
234 /*
235 * This can happen in following situations:
236 *
237 * If the slot is temporary, it means either the initial WAL location
238 * reserved for the local slot is ahead of the remote slot's
239 * restart_lsn or the initial xmin_horizon computed for the local slot
240 * is ahead of the remote slot.
241 *
242 * If the slot is persistent, both restart_lsn and catalog_xmin of the
243 * synced slot could still be ahead of the remote slot. Since we use
244 * slot advance functionality to keep snapbuild/slot updated, it is
245 * possible that the restart_lsn and catalog_xmin are advanced to a
246 * later position than it has on the primary. This can happen when
247 * slot advancing machinery finds running xacts record after reaching
248 * the consistent state at a later point than the primary where it
249 * serializes the snapshot and updates the restart_lsn.
250 *
251 * We LOG the message if the slot is temporary as it can help the user
252 * to understand why the slot is not sync-ready. In the case of a
253 * persistent slot, it would be a more common case and won't directly
254 * impact the users, so we used DEBUG1 level to log the message.
255 */
257 errmsg("could not synchronize replication slot \"%s\"",
258 remote_slot->name),
259 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.",
260 LSN_FORMAT_ARGS(remote_slot->restart_lsn),
261 remote_slot->catalog_xmin,
263 slot->data.catalog_xmin));
264
266 *remote_slot_precedes = true;
267
268 /*
269 * Skip updating the configuration. This is required to avoid syncing
270 * two_phase_at without syncing confirmed_lsn. Otherwise, the prepared
271 * transaction between old confirmed_lsn and two_phase_at will
272 * unexpectedly get decoded and sent to the downstream after
273 * promotion. See comments in ReorderBufferFinishPrepared.
274 */
275 return false;
276 }
277
278 /*
279 * Attempt to sync LSNs and xmins only if remote slot is ahead of local
280 * slot.
281 */
282 if (remote_slot->confirmed_lsn > slot->data.confirmed_flush ||
283 remote_slot->restart_lsn > slot->data.restart_lsn ||
284 TransactionIdFollows(remote_slot->catalog_xmin,
285 slot->data.catalog_xmin))
286 {
287 /*
288 * We can't directly copy the remote slot's LSN or xmin unless there
289 * exists a consistent snapshot at that point. Otherwise, after
290 * promotion, the slots may not reach a consistent point before the
291 * confirmed_flush_lsn which can lead to a data loss. To avoid data
292 * loss, we let slot machinery advance the slot which ensures that
293 * snapbuilder/slot statuses are updated properly.
294 */
295 if (SnapBuildSnapshotExists(remote_slot->restart_lsn))
296 {
297 /*
298 * Update the slot info directly if there is a serialized snapshot
299 * at the restart_lsn, as the slot can quickly reach consistency
300 * at restart_lsn by restoring the snapshot.
301 */
302 SpinLockAcquire(&slot->mutex);
303 slot->data.restart_lsn = remote_slot->restart_lsn;
304 slot->data.confirmed_flush = remote_slot->confirmed_lsn;
305 slot->data.catalog_xmin = remote_slot->catalog_xmin;
306 SpinLockRelease(&slot->mutex);
307
310 }
311 else
312 {
315
316 /* Sanity check */
317 if (slot->data.confirmed_flush != remote_slot->confirmed_lsn)
319 errmsg_internal("synchronized confirmed_flush for slot \"%s\" differs from remote slot",
320 remote_slot->name),
321 errdetail_internal("Remote slot has LSN %X/%08X but local slot has LSN %X/%08X.",
322 LSN_FORMAT_ARGS(remote_slot->confirmed_lsn),
324
325 /*
326 * If we can't reach a consistent snapshot, the slot won't be
327 * persisted. See update_and_persist_local_synced_slot().
328 */
331 }
332
333 updated_xmin_or_lsn = true;
334 }
335
336 /* Update slot sync skip stats */
338
339 if (remote_dbid != slot->data.database ||
340 remote_slot->two_phase != slot->data.two_phase ||
341 remote_slot->failover != slot->data.failover ||
342 strcmp(remote_slot->plugin, NameStr(slot->data.plugin)) != 0 ||
343 remote_slot->two_phase_at != slot->data.two_phase_at)
344 {
346
347 /* Avoid expensive operations while holding a spinlock. */
349
350 SpinLockAcquire(&slot->mutex);
351 slot->data.plugin = plugin_name;
352 slot->data.database = remote_dbid;
353 slot->data.two_phase = remote_slot->two_phase;
354 slot->data.two_phase_at = remote_slot->two_phase_at;
355 slot->data.failover = remote_slot->failover;
356 SpinLockRelease(&slot->mutex);
357
358 updated_config = true;
359
360 /*
361 * Ensure that there is no risk of sending prepared transactions
362 * unexpectedly after the promotion.
363 */
365 }
366
367 /*
368 * We have to write the changed xmin to disk *before* we change the
369 * in-memory value, otherwise after a crash we wouldn't know that some
370 * catalog tuples might have been removed already.
371 */
373 {
376 }
377
378 /*
379 * Now the new xmin is safely on disk, we can let the global value
380 * advance. We do not take ProcArrayLock or similar since we only advance
381 * xmin here and there's not much harm done by a concurrent computation
382 * missing that.
383 */
385 {
386 SpinLockAcquire(&slot->mutex);
387 slot->effective_catalog_xmin = remote_slot->catalog_xmin;
388 SpinLockRelease(&slot->mutex);
389
392 }
393
395}
396
397/*
398 * Get the list of local logical slots that are synchronized from the
399 * primary server.
400 */
401static List *
403{
405
407
408 for (int i = 0; i < max_replication_slots; i++)
409 {
411
412 /* Check if it is a synchronized slot */
413 if (s->in_use && s->data.synced)
414 {
417 }
418 }
419
421
422 return local_slots;
423}
424
425/*
426 * Helper function to check if local_slot is required to be retained.
427 *
428 * Return false either if local_slot does not exist in the remote_slots list
429 * or is invalidated while the corresponding remote slot is still valid,
430 * otherwise true.
431 */
432static bool
434{
435 bool remote_exists = false;
436 bool locally_invalidated = false;
437
439 {
440 if (strcmp(remote_slot->name, NameStr(local_slot->data.name)) == 0)
441 {
442 remote_exists = true;
443
444 /*
445 * If remote slot is not invalidated but local slot is marked as
446 * invalidated, then set locally_invalidated flag.
447 */
450 (remote_slot->invalidated == RS_INVAL_NONE) &&
451 (local_slot->data.invalidated != RS_INVAL_NONE);
453
454 break;
455 }
456 }
457
459}
460
461/*
462 * Drop local obsolete slots.
463 *
464 * Drop the local slots that no longer need to be synced i.e. these either do
465 * not exist on the primary or are no longer enabled for failover.
466 *
467 * Additionally, drop any slots that are valid on the primary but got
468 * invalidated on the standby. This situation may occur due to the following
469 * reasons:
470 * - The 'max_slot_wal_keep_size' on the standby is insufficient to retain WAL
471 * records from the restart_lsn of the slot.
472 * - 'primary_slot_name' is temporarily reset to null and the physical slot is
473 * removed.
474 * These dropped slots will get recreated in next sync-cycle and it is okay to
475 * drop and recreate such slots as long as these are not consumable on the
476 * standby (which is the case currently).
477 *
478 * Note: Change of 'wal_level' on the primary server to a level lower than
479 * logical may also result in slot invalidation and removal on the standby.
480 * This is because such 'wal_level' change is only possible if the logical
481 * slots are removed on the primary server, so it's expected to see the
482 * slots being invalidated and removed on the standby too (and re-created
483 * if they are re-created on the primary server).
484 */
485static void
487{
489
491 {
492 /* Drop the local slot if it is not required to be retained. */
494 {
495 bool synced_slot;
496
497 /*
498 * Use shared lock to prevent a conflict with
499 * ReplicationSlotsDropDBSlots(), trying to drop the same slot
500 * during a drop-database operation.
501 */
503 0, AccessShareLock);
504
505 /*
506 * In the small window between getting the slot to drop and
507 * locking the database, there is a possibility of a parallel
508 * database drop by the startup process and the creation of a new
509 * slot by the user. This new user-created slot may end up using
510 * the same shared memory as that of 'local_slot'. Thus check if
511 * local_slot is still the synced one before performing actual
512 * drop.
513 */
515 synced_slot = local_slot->in_use && local_slot->data.synced;
517
518 if (synced_slot)
519 {
520 ReplicationSlotAcquire(NameStr(local_slot->data.name), true, false);
522 }
523
525 0, AccessShareLock);
526
527 ereport(LOG,
528 errmsg("dropped replication slot \"%s\" of database with OID %u",
529 NameStr(local_slot->data.name),
530 local_slot->data.database));
531 }
532 }
533}
534
535/*
536 * Reserve WAL for the currently active local slot using the specified WAL
537 * location (restart_lsn).
538 *
539 * If the given WAL location has been removed or is at risk of removal,
540 * reserve WAL using the oldest segment that is non-removable.
541 */
542static void
544{
547 XLogSegNo segno;
549
550 Assert(slot != NULL);
552
553 /*
554 * Acquire an exclusive lock to prevent the checkpoint process from
555 * concurrently calculating the minimum slot LSN (see
556 * CheckPointReplicationSlots), ensuring that if WAL reservation occurs
557 * first, the checkpoint must wait for the restart_lsn update before
558 * calculating the minimum LSN.
559 *
560 * Note: Unlike ReplicationSlotReserveWal(), this lock does not protect a
561 * newly synced slot from being invalidated if a concurrent checkpoint has
562 * invoked CheckPointReplicationSlots() before the WAL reservation here.
563 * This can happen because the initial restart_lsn received from the
564 * remote server can precede the redo pointer. Therefore, when selecting
565 * the initial restart_lsn, we consider using the redo pointer or the
566 * minimum slot LSN (if those values are greater than the remote
567 * restart_lsn) instead of relying solely on the remote value.
568 */
570
571 /*
572 * Determine the minimum non-removable LSN by comparing the redo pointer
573 * with the minimum slot LSN.
574 *
575 * The minimum slot LSN is considered because the redo pointer advances at
576 * every checkpoint, even when replication slots are present on the
577 * standby. In such scenarios, the redo pointer can exceed the remote
578 * restart_lsn, while WALs preceding the remote restart_lsn remain
579 * protected by a local replication slot.
580 */
583
586
587 /*
588 * If the minimum safe LSN is greater than the given restart_lsn, use it
589 * as the initial restart_lsn for the newly synced slot. Otherwise, use
590 * the given remote restart_lsn.
591 */
592 SpinLockAcquire(&slot->mutex);
593 slot->data.restart_lsn = Max(restart_lsn, min_safe_lsn);
594 SpinLockRelease(&slot->mutex);
595
597
599 if (XLogGetLastRemovedSegno() >= segno)
600 elog(ERROR, "WAL required by replication slot %s has been removed concurrently",
601 NameStr(slot->data.name));
602
604}
605
606/*
607 * If the remote restart_lsn and catalog_xmin have caught up with the
608 * local ones, then update the LSNs and persist the local synced slot for
609 * future synchronization; otherwise, do nothing.
610 *
611 * *slot_persistence_pending is set to true if any of the slots fail to
612 * persist.
613 *
614 * Return true if the slot is marked as RS_PERSISTENT (sync-ready), otherwise
615 * false.
616 */
617static bool
620{
622 bool found_consistent_snapshot = false;
623 bool remote_slot_precedes = false;
624
625 /* Slotsync skip stats are handled in function update_local_synced_slot() */
629
630 /*
631 * Check if the primary server has caught up. Refer to the comment atop
632 * the file for details on this check.
633 */
635 {
636 /*
637 * The remote slot didn't catch up to locally reserved position.
638 *
639 * We do not drop the slot because the restart_lsn can be ahead of the
640 * current location when recreating the slot in the next cycle. It may
641 * take more time to create such a slot. Therefore, we keep this slot
642 * and attempt the synchronization in the next cycle.
643 *
644 * We also update the slot_persistence_pending parameter, so the SQL
645 * function can retry.
646 */
649
650 return false;
651 }
652
653 /*
654 * Don't persist the slot if it cannot reach the consistent point from the
655 * restart_lsn. See comments atop this file.
656 */
658 {
659 ereport(LOG,
660 errmsg("could not synchronize replication slot \"%s\"", remote_slot->name),
661 errdetail("Synchronization could lead to data loss, because the standby could not build a consistent snapshot to decode WALs at LSN %X/%08X.",
663
664 /* Set this, so that SQL function can retry */
667
668 return false;
669 }
670
672
673 ereport(LOG,
674 errmsg("newly created replication slot \"%s\" is sync-ready now",
675 remote_slot->name));
676
677 return true;
678}
679
680/*
681 * Synchronize a single slot to the given position.
682 *
683 * This creates a new slot if there is no existing one and updates the
684 * metadata of the slot as per the data received from the primary server.
685 *
686 * The slot is created as a temporary slot and stays in the same state until the
687 * remote_slot catches up with locally reserved position and local slot is
688 * updated. The slot is then persisted and is considered as sync-ready for
689 * periodic syncs.
690 *
691 * *slot_persistence_pending is set to true if any of the slots fail to
692 * persist.
693 *
694 * Returns TRUE if the local slot is updated.
695 */
696static bool
699{
700 ReplicationSlot *slot;
702 bool slot_updated = false;
703
704 /* Search for the named slot */
705 if ((slot = SearchNamedReplicationSlot(remote_slot->name, true)))
706 {
707 bool synced;
708
709 SpinLockAcquire(&slot->mutex);
710 synced = slot->data.synced;
711 SpinLockRelease(&slot->mutex);
712
713 /* User-created slot with the same name exists, raise ERROR. */
714 if (!synced)
717 errmsg("exiting from slot synchronization because same"
718 " name slot \"%s\" already exists on the standby",
719 remote_slot->name));
720
721 /*
722 * The slot has been synchronized before.
723 *
724 * It is important to acquire the slot here before checking
725 * invalidation. If we don't acquire the slot first, there could be a
726 * race condition that the local slot could be invalidated just after
727 * checking the 'invalidated' flag here and we could end up
728 * overwriting 'invalidated' flag to remote_slot's value. See
729 * InvalidatePossiblyObsoleteSlot() where it invalidates slot directly
730 * if the slot is not acquired by other processes.
731 *
732 * XXX: If it ever turns out that slot acquire/release is costly for
733 * cases when none of the slot properties is changed then we can do a
734 * pre-check to ensure that at least one of the slot properties is
735 * changed before acquiring the slot.
736 */
737 ReplicationSlotAcquire(remote_slot->name, true, false);
738
739 Assert(slot == MyReplicationSlot);
740
741 /*
742 * Copy the invalidation cause from remote only if local slot is not
743 * invalidated locally, we don't want to overwrite existing one.
744 */
745 if (slot->data.invalidated == RS_INVAL_NONE &&
746 remote_slot->invalidated != RS_INVAL_NONE)
747 {
748 SpinLockAcquire(&slot->mutex);
749 slot->data.invalidated = remote_slot->invalidated;
750 SpinLockRelease(&slot->mutex);
751
752 /* Make sure the invalidated state persists across server restart */
755
756 slot_updated = true;
757 }
758
759 /* Skip the sync of an invalidated slot */
760 if (slot->data.invalidated != RS_INVAL_NONE)
761 {
763
765 return slot_updated;
766 }
767
768 /*
769 * Make sure that concerned WAL is received and flushed before syncing
770 * slot to target lsn received from the primary server.
771 *
772 * Report statistics only after the slot has been acquired, ensuring
773 * it cannot be dropped during the reporting process.
774 */
775 if (remote_slot->confirmed_lsn > latestFlushPtr)
776 {
778
779 /*
780 * Can get here only if GUC 'synchronized_standby_slots' on the
781 * primary server was not configured correctly.
782 */
785 errmsg("skipping slot synchronization because the received slot sync"
786 " LSN %X/%08X for slot \"%s\" is ahead of the standby position %X/%08X",
787 LSN_FORMAT_ARGS(remote_slot->confirmed_lsn),
788 remote_slot->name,
790
792
793 return slot_updated;
794 }
795
796 /* Slot not ready yet, let's attempt to make it sync-ready now. */
797 if (slot->data.persistency == RS_TEMPORARY)
798 {
802 }
803
804 /* Slot ready for sync, so sync it. */
805 else
806 {
807 /*
808 * Sanity check: As long as the invalidations are handled
809 * appropriately as above, this should never happen.
810 *
811 * We don't need to check restart_lsn here. See the comments in
812 * update_local_synced_slot() for details.
813 */
814 if (remote_slot->confirmed_lsn < slot->data.confirmed_flush)
816 errmsg_internal("cannot synchronize local slot \"%s\"",
817 remote_slot->name),
818 errdetail_internal("Local slot's start streaming location LSN(%X/%08X) is ahead of remote slot's LSN(%X/%08X).",
820 LSN_FORMAT_ARGS(remote_slot->confirmed_lsn)));
821
823 NULL, NULL);
824 }
825 }
826 /* Otherwise create the slot first. */
827 else
828 {
831
832 /* Skip creating the local slot if remote_slot is invalidated already */
833 if (remote_slot->invalidated != RS_INVAL_NONE)
834 return false;
835
836 /*
837 * We create temporary slots instead of ephemeral slots here because
838 * we want the slots to survive after releasing them. This is done to
839 * avoid dropping and re-creating the slots in each synchronization
840 * cycle if the restart_lsn or catalog_xmin of the remote slot has not
841 * caught up.
842 */
844 remote_slot->two_phase,
845 remote_slot->failover,
846 true);
847
848 /* For shorter lines. */
849 slot = MyReplicationSlot;
850
851 /* Avoid expensive operations while holding a spinlock. */
853
854 SpinLockAcquire(&slot->mutex);
855 slot->data.database = remote_dbid;
856 slot->data.plugin = plugin_name;
857 SpinLockRelease(&slot->mutex);
858
860
864 SpinLockAcquire(&slot->mutex);
867 SpinLockRelease(&slot->mutex);
871
872 /*
873 * Make sure that concerned WAL is received and flushed before syncing
874 * slot to target lsn received from the primary server.
875 *
876 * Report statistics only after the slot has been acquired, ensuring
877 * it cannot be dropped during the reporting process.
878 */
879 if (remote_slot->confirmed_lsn > latestFlushPtr)
880 {
882
883 /*
884 * Can get here only if GUC 'synchronized_standby_slots' on the
885 * primary server was not configured correctly.
886 */
889 errmsg("skipping slot synchronization because the received slot sync"
890 " LSN %X/%08X for slot \"%s\" is ahead of the standby position %X/%08X",
891 LSN_FORMAT_ARGS(remote_slot->confirmed_lsn),
892 remote_slot->name,
894
896
897 return false;
898 }
899
902
903 slot_updated = true;
904 }
905
907
908 return slot_updated;
909}
910
911/*
912 * Fetch remote slots.
913 *
914 * If slot_names is NIL, fetches all failover logical slots from the
915 * primary server, otherwise fetches only the ones with names in slot_names.
916 *
917 * Returns a list of remote slot information structures, or NIL if none
918 * are found.
919 */
920static List *
922{
923#define SLOTSYNC_COLUMN_COUNT 10
926
927 WalRcvExecResult *res;
928 TupleTableSlot *tupslot;
930 StringInfoData query;
931
932 initStringInfo(&query);
934 "SELECT slot_name, plugin, confirmed_flush_lsn,"
935 " restart_lsn, catalog_xmin, two_phase,"
936 " two_phase_at, failover,"
937 " database, invalidation_reason"
938 " FROM pg_catalog.pg_replication_slots"
939 " WHERE failover and NOT temporary");
940
941 if (slot_names != NIL)
942 {
943 bool first_slot = true;
944
945 /*
946 * Construct the query to fetch only the specified slots
947 */
948 appendStringInfoString(&query, " AND slot_name IN (");
949
950 foreach_ptr(char, slot_name, slot_names)
951 {
952 if (!first_slot)
953 appendStringInfoString(&query, ", ");
954
955 appendStringInfo(&query, "%s", quote_literal_cstr(slot_name));
956 first_slot = false;
957 }
958 appendStringInfoChar(&query, ')');
959 }
960
961 /* Execute the query */
963 pfree(query.data);
964 if (res->status != WALRCV_OK_TUPLES)
966 errmsg("could not fetch failover logical slots info from the primary server: %s",
967 res->err));
968
970 while (tuplestore_gettupleslot(res->tuplestore, true, false, tupslot))
971 {
972 bool isnull;
974 Datum d;
975 int col = 0;
976
978 &isnull));
979 Assert(!isnull);
980
981 remote_slot->plugin = TextDatumGetCString(slot_getattr(tupslot, ++col,
982 &isnull));
983 Assert(!isnull);
984
985 /*
986 * It is possible to get null values for LSN and Xmin if slot is
987 * invalidated on the primary server, so handle accordingly.
988 */
989 d = slot_getattr(tupslot, ++col, &isnull);
990 remote_slot->confirmed_lsn = isnull ? InvalidXLogRecPtr :
991 DatumGetLSN(d);
992
993 d = slot_getattr(tupslot, ++col, &isnull);
994 remote_slot->restart_lsn = isnull ? InvalidXLogRecPtr : DatumGetLSN(d);
995
996 d = slot_getattr(tupslot, ++col, &isnull);
997 remote_slot->catalog_xmin = isnull ? InvalidTransactionId :
999
1000 remote_slot->two_phase = DatumGetBool(slot_getattr(tupslot, ++col,
1001 &isnull));
1002 Assert(!isnull);
1003
1004 d = slot_getattr(tupslot, ++col, &isnull);
1005 remote_slot->two_phase_at = isnull ? InvalidXLogRecPtr : DatumGetLSN(d);
1006
1007 remote_slot->failover = DatumGetBool(slot_getattr(tupslot, ++col,
1008 &isnull));
1009 Assert(!isnull);
1010
1011 remote_slot->database = TextDatumGetCString(slot_getattr(tupslot,
1012 ++col, &isnull));
1013 Assert(!isnull);
1014
1015 d = slot_getattr(tupslot, ++col, &isnull);
1016 remote_slot->invalidated = isnull ? RS_INVAL_NONE :
1018
1019 /* Sanity check */
1021
1022 /*
1023 * If restart_lsn, confirmed_lsn or catalog_xmin is invalid but the
1024 * slot is valid, that means we have fetched the remote_slot in its
1025 * RS_EPHEMERAL state. In such a case, don't sync it; we can always
1026 * sync it in the next sync cycle when the remote_slot is persisted
1027 * and has valid lsn(s) and xmin values.
1028 *
1029 * XXX: In future, if we plan to expose 'slot->data.persistency' in
1030 * pg_replication_slots view, then we can avoid fetching RS_EPHEMERAL
1031 * slots in the first place.
1032 */
1033 if ((!XLogRecPtrIsValid(remote_slot->restart_lsn) ||
1034 !XLogRecPtrIsValid(remote_slot->confirmed_lsn) ||
1035 !TransactionIdIsValid(remote_slot->catalog_xmin)) &&
1036 remote_slot->invalidated == RS_INVAL_NONE)
1038 else
1039 /* Create list of remote slots */
1041
1042 ExecClearTuple(tupslot);
1043 }
1044
1046
1047 return remote_slot_list;
1048}
1049
1050/*
1051 * Synchronize slots.
1052 *
1053 * This function takes a list of remote slots and synchronizes them locally. It
1054 * creates the slots if not present on the standby and updates existing ones.
1055 *
1056 * If slot_persistence_pending is not NULL, it will be set to true if one or
1057 * more slots could not be persisted. This allows callers such as
1058 * SyncReplicationSlots() to retry those slots.
1059 *
1060 * Returns TRUE if any of the slots gets updated in this sync-cycle.
1061 */
1062static bool
1065{
1066 bool some_slot_updated = false;
1067
1068 /* Drop local slots that no longer need to be synced. */
1070
1071 /* Now sync the slots locally */
1073 {
1074 Oid remote_dbid = get_database_oid(remote_slot->database, false);
1075
1076 /*
1077 * Use shared lock to prevent a conflict with
1078 * ReplicationSlotsDropDBSlots(), trying to drop the same slot during
1079 * a drop-database operation.
1080 */
1082
1085
1087 }
1088
1089 return some_slot_updated;
1090}
1091
1092/*
1093 * Checks the remote server info.
1094 *
1095 * We ensure that the 'primary_slot_name' exists on the remote server and the
1096 * remote server is not a standby node.
1097 */
1098static void
1100{
1101#define PRIMARY_INFO_OUTPUT_COL_COUNT 2
1102 WalRcvExecResult *res;
1104 StringInfoData cmd;
1105 bool isnull;
1106 TupleTableSlot *tupslot;
1107 bool remote_in_recovery;
1108 bool primary_slot_valid;
1109 bool started_tx = false;
1110
1111 initStringInfo(&cmd);
1112 appendStringInfo(&cmd,
1113 "SELECT pg_is_in_recovery(), count(*) = 1"
1114 " FROM pg_catalog.pg_replication_slots"
1115 " WHERE slot_type='physical' AND slot_name=%s",
1117
1118 /* The syscache access in walrcv_exec() needs a transaction env. */
1119 if (!IsTransactionState())
1120 {
1122 started_tx = true;
1123 }
1124
1126 pfree(cmd.data);
1127
1128 if (res->status != WALRCV_OK_TUPLES)
1129 ereport(ERROR,
1130 errmsg("could not fetch primary slot name \"%s\" info from the primary server: %s",
1131 PrimarySlotName, res->err),
1132 errhint("Check if \"primary_slot_name\" is configured correctly."));
1133
1135 if (!tuplestore_gettupleslot(res->tuplestore, true, false, tupslot))
1136 elog(ERROR,
1137 "failed to fetch tuple for the primary server slot specified by \"primary_slot_name\"");
1138
1139 remote_in_recovery = DatumGetBool(slot_getattr(tupslot, 1, &isnull));
1140 Assert(!isnull);
1141
1142 /*
1143 * Slot sync is currently not supported on a cascading standby. This is
1144 * because if we allow it, the primary server needs to wait for all the
1145 * cascading standbys, otherwise, logical subscribers can still be ahead
1146 * of one of the cascading standbys which we plan to promote. Thus, to
1147 * avoid this additional complexity, we restrict it for the time being.
1148 */
1150 ereport(ERROR,
1152 errmsg("cannot synchronize replication slots from a standby server"));
1153
1154 primary_slot_valid = DatumGetBool(slot_getattr(tupslot, 2, &isnull));
1155 Assert(!isnull);
1156
1157 if (!primary_slot_valid)
1158 ereport(ERROR,
1160 /* translator: second %s is a GUC variable name */
1161 errmsg("replication slot \"%s\" specified by \"%s\" does not exist on primary server",
1162 PrimarySlotName, "primary_slot_name"));
1163
1164 ExecClearTuple(tupslot);
1166
1167 if (started_tx)
1169}
1170
1171/*
1172 * Checks if dbname is specified in 'primary_conninfo'.
1173 *
1174 * Error out if not specified otherwise return it.
1175 */
1176char *
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}
1198
1199/*
1200 * Return true if all necessary GUCs for slot synchronization are set
1201 * appropriately, otherwise, return false.
1202 */
1203bool
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}
1265
1266/*
1267 * Re-read the config file for slot synchronization.
1268 *
1269 * Exit or throw error if relevant GUCs have changed depending on whether
1270 * called from slot sync worker or from the SQL function pg_sync_replication_slots()
1271 */
1272static void
1274{
1279 bool conninfo_changed;
1282 bool parameter_changed = false;
1283
1286
1287 ConfigReloadPending = false;
1289
1294
1296 {
1298 {
1299 ereport(LOG,
1300 /* translator: %s is a GUC variable name */
1301 errmsg("replication slot synchronization worker will stop because \"%s\" is disabled",
1302 "sync_replication_slots"));
1303
1304 proc_exit(0);
1305 }
1306
1307 parameter_changed = true;
1308 }
1309 else
1310 {
1311 if (conninfo_changed ||
1314 {
1315
1317 {
1318 ereport(LOG,
1319 errmsg("replication slot synchronization worker will restart because of a parameter change"));
1320
1321 /*
1322 * Reset the last-start time for this worker so that the
1323 * postmaster can restart it without waiting for
1324 * SLOTSYNC_RESTART_INTERVAL_SEC.
1325 */
1327
1328 proc_exit(0);
1329 }
1330
1331 parameter_changed = true;
1332 }
1333 }
1334
1335 /*
1336 * If we have reached here with a parameter change, we must be running in
1337 * SQL function, emit error in such a case.
1338 */
1340 {
1342 ereport(ERROR,
1344 errmsg("replication slot synchronization will stop because of a parameter change"));
1345 }
1346
1347}
1348
1349/*
1350 * Interrupt handler for process performing slot synchronization.
1351 */
1352static void
1354{
1356
1358 {
1360 {
1361 ereport(LOG,
1362 errmsg("replication slot synchronization worker will stop because promotion is triggered"));
1363
1364 proc_exit(0);
1365 }
1366 else
1367 {
1368 /*
1369 * For the backend executing SQL function
1370 * pg_sync_replication_slots().
1371 */
1372 ereport(ERROR,
1374 errmsg("replication slot synchronization will stop because promotion is triggered"));
1375 }
1376 }
1377
1380}
1381
1382/*
1383 * Connection cleanup function for slotsync worker.
1384 *
1385 * Called on slotsync worker exit.
1386 */
1387static void
1394
1395/*
1396 * Cleanup function for slotsync worker.
1397 *
1398 * Called on slotsync worker exit.
1399 */
1400static void
1402{
1403 /*
1404 * We need to do slots cleanup here just like WalSndErrorCleanup() does.
1405 *
1406 * The startup process during promotion invokes ShutDownSlotSync() which
1407 * waits for slot sync to finish and it does that by checking the
1408 * 'syncing' flag. Thus the slot sync worker must be done with slots'
1409 * release and cleanup to avoid any dangling temporary slots or active
1410 * slots before it marks itself as finished syncing.
1411 */
1412
1413 /* Make sure active replication slots are released */
1414 if (MyReplicationSlot != NULL)
1416
1417 /* Also cleanup the temporary slots. */
1419
1421
1423
1424 /*
1425 * If syncing_slots is true, it indicates that the process errored out
1426 * without resetting the flag. So, we need to clean up shared memory and
1427 * reset the flag here.
1428 */
1429 if (syncing_slots)
1430 {
1431 SlotSyncCtx->syncing = false;
1432 syncing_slots = false;
1433 }
1434
1436}
1437
1438/*
1439 * Sleep for long enough that we believe it's likely that the slots on primary
1440 * get updated.
1441 *
1442 * If there is no slot activity the wait time between sync-cycles will double
1443 * (to a maximum of 30s). If there is some slot activity the wait time between
1444 * sync-cycles is reset to the minimum (200ms).
1445 */
1446static void
1448{
1449 int rc;
1450
1451 if (!some_slot_updated)
1452 {
1453 /*
1454 * No slots were updated, so double the sleep time, but not beyond the
1455 * maximum allowable value.
1456 */
1458 }
1459 else
1460 {
1461 /*
1462 * Some slots were updated since the last sleep, so reset the sleep
1463 * time.
1464 */
1466 }
1467
1468 rc = WaitLatch(MyLatch,
1470 sleep_ms,
1472
1473 if (rc & WL_LATCH_SET)
1475}
1476
1477/*
1478 * Emit an error if a concurrent sync call is in progress.
1479 * Otherwise, advertise that a sync is in progress.
1480 */
1481static void
1483{
1485
1486 if (SlotSyncCtx->syncing)
1487 {
1489 ereport(ERROR,
1491 errmsg("cannot synchronize replication slots concurrently"));
1492 }
1493
1494 /* The pid must not be already assigned in SlotSyncCtx */
1496
1497 SlotSyncCtx->syncing = true;
1498
1499 /*
1500 * Advertise the required PID so that the startup process can kill the
1501 * slot sync process on promotion.
1502 */
1504
1506
1507 syncing_slots = true;
1508}
1509
1510/*
1511 * Reset syncing flag.
1512 */
1513static void
1523
1524/*
1525 * The main loop of our worker process.
1526 *
1527 * It connects to the primary server, fetches logical failover slots
1528 * information periodically in order to create and sync the slots.
1529 *
1530 * Note: If any changes are made here, check if the corresponding SQL
1531 * function logic in SyncReplicationSlots() also needs to be changed.
1532 */
1533void
1535{
1537 char *dbname;
1538 char *err;
1541
1543
1545
1547
1548 /*
1549 * Create a per-backend PGPROC struct in shared memory. We must do this
1550 * before we access any shared memory.
1551 */
1552 InitProcess();
1553
1554 /*
1555 * Early initialization.
1556 */
1557 BaseInit();
1558
1560
1561 /*
1562 * If an exception is encountered, processing resumes here.
1563 *
1564 * We just need to clean up, report the error, and go away.
1565 *
1566 * If we do not have this handling here, then since this worker process
1567 * operates at the bottom of the exception stack, ERRORs turn into FATALs.
1568 * Therefore, we create our own exception handler to catch ERRORs.
1569 */
1570 if (sigsetjmp(local_sigjmp_buf, 1) != 0)
1571 {
1572 /* since not using PG_TRY, must reset error stack by hand */
1574
1575 /* Prevents interrupts while cleaning up */
1577
1578 /* Report the error to the server log */
1580
1581 /*
1582 * We can now go away. Note that because we called InitProcess, a
1583 * callback was registered to do ProcKill, which will clean up
1584 * necessary state.
1585 */
1586 proc_exit(0);
1587 }
1588
1589 /* We can now handle ereport(ERROR) */
1591
1592 /* Setup signal handling */
1601
1603
1604 ereport(LOG, errmsg("slot sync worker started"));
1605
1606 /* Register it as soon as SlotSyncCtx->pid is initialized. */
1608
1609 /*
1610 * Establishes SIGALRM handler and initialize timeout module. It is needed
1611 * by InitPostgres to register different timeouts.
1612 */
1614
1615 /* Load the libpq-specific functions */
1616 load_file("libpqwalreceiver", false);
1617
1618 /*
1619 * Unblock signals (they were blocked when the postmaster forked us)
1620 */
1622
1623 /*
1624 * Set always-secure search path, so malicious users can't redirect user
1625 * code (e.g. operators).
1626 *
1627 * It's not strictly necessary since we won't be scanning or writing to
1628 * any user table locally, but it's good to retain it here for added
1629 * precaution.
1630 */
1631 SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
1632
1634
1635 /*
1636 * Connect to the database specified by the user in primary_conninfo. We
1637 * need a database connection for walrcv_exec to work which we use to
1638 * fetch slot information from the remote node. See comments atop
1639 * libpqrcv_exec.
1640 *
1641 * We do not specify a specific user here since the slot sync worker will
1642 * operate as a superuser. This is safe because the slot sync worker does
1643 * not interact with user tables, eliminating the risk of executing
1644 * arbitrary code within triggers.
1645 */
1647
1649
1651 if (cluster_name[0])
1652 appendStringInfo(&app_name, "%s_%s", cluster_name, "slotsync worker");
1653 else
1654 appendStringInfoString(&app_name, "slotsync worker");
1655
1656 /*
1657 * Establish the connection to the primary server for slot
1658 * synchronization.
1659 */
1660 wrconn = walrcv_connect(PrimaryConnInfo, false, false, false,
1661 app_name.data, &err);
1662
1663 if (!wrconn)
1664 ereport(ERROR,
1666 errmsg("synchronization worker \"%s\" could not connect to the primary server: %s",
1667 app_name.data, err));
1668
1669 pfree(app_name.data);
1670
1671 /*
1672 * Register the disconnection callback.
1673 *
1674 * XXX: This can be combined with previous cleanup registration of
1675 * slotsync_worker_onexit() but that will need the connection to be made
1676 * global and we want to avoid introducing global for this purpose.
1677 */
1679
1680 /*
1681 * Using the specified primary server connection, check that we are not a
1682 * cascading standby and slot configured in 'primary_slot_name' exists on
1683 * the primary server.
1684 */
1686
1687 /* Main loop to synchronize slots */
1688 for (;;)
1689 {
1690 bool some_slot_updated = false;
1691 bool started_tx = false;
1693
1695
1696 /*
1697 * The syscache access in fetch_remote_slots() needs a transaction
1698 * env.
1699 */
1700 if (!IsTransactionState())
1701 {
1703 started_tx = true;
1704 }
1705
1709
1710 if (started_tx)
1712
1714 }
1715
1716 /*
1717 * The slot sync worker can't get here because it will only stop when it
1718 * receives a stop request from the startup process, or when there is an
1719 * error.
1720 */
1721 Assert(false);
1722}
1723
1724/*
1725 * Update the inactive_since property for synced slots.
1726 *
1727 * Note that this function is currently called when we shutdown the slot
1728 * sync machinery.
1729 */
1730static void
1732{
1733 TimestampTz now = 0;
1734
1735 /*
1736 * We need to update inactive_since only when we are promoting standby to
1737 * correctly interpret the inactive_since if the standby gets promoted
1738 * without a restart. We don't want the slots to appear inactive for a
1739 * long time after promotion if they haven't been synchronized recently.
1740 * Whoever acquires the slot, i.e., makes the slot active, will reset it.
1741 */
1742 if (!StandbyMode)
1743 return;
1744
1745 /* The slot sync worker or the SQL function mustn't be running by now */
1747
1749
1750 for (int i = 0; i < max_replication_slots; i++)
1751 {
1753
1754 /* Check if it is a synchronized slot */
1755 if (s->in_use && s->data.synced)
1756 {
1758
1759 /* The slot must not be acquired by any process */
1760 Assert(s->active_pid == 0);
1761
1762 /* Use the same inactive_since time for all the slots. */
1763 if (now == 0)
1765
1767 }
1768 }
1769
1771}
1772
1773/*
1774 * Shut down slot synchronization.
1775 *
1776 * This function sets stopSignaled=true and wakes up the slot sync process
1777 * (either worker or backend running the SQL function pg_sync_replication_slots())
1778 * so that worker can exit or the SQL function pg_sync_replication_slots() can
1779 * finish. It also waits till the slot sync worker has exited or
1780 * pg_sync_replication_slots() has finished.
1781 */
1782void
1784{
1786
1788
1789 SlotSyncCtx->stopSignaled = true;
1790
1791 /*
1792 * Return if neither the slot sync worker is running nor the function
1793 * pg_sync_replication_slots() is executing.
1794 */
1795 if (!SlotSyncCtx->syncing)
1796 {
1799 return;
1800 }
1801
1803
1805
1806 /*
1807 * Signal process doing slotsync, if any. The process will stop upon
1808 * detecting that the stopSignaled flag is set to true.
1809 */
1812
1813 /* Wait for slot sync to end */
1814 for (;;)
1815 {
1816 int rc;
1817
1818 /* Wait a bit, we don't expect to have to wait long */
1819 rc = WaitLatch(MyLatch,
1822
1823 if (rc & WL_LATCH_SET)
1824 {
1827 }
1828
1830
1831 /* Ensure that no process is syncing the slots. */
1832 if (!SlotSyncCtx->syncing)
1833 break;
1834
1836 }
1837
1839
1841}
1842
1843/*
1844 * SlotSyncWorkerCanRestart
1845 *
1846 * Return true, indicating worker is allowed to restart, if enough time has
1847 * passed since it was last launched to reach SLOTSYNC_RESTART_INTERVAL_SEC.
1848 * Otherwise return false.
1849 *
1850 * This is a safety valve to protect against continuous respawn attempts if the
1851 * worker is dying immediately at launch. Note that since we will retry to
1852 * launch the worker from the postmaster main loop, we will get another
1853 * chance later.
1854 */
1855bool
1857{
1858 time_t curtime = time(NULL);
1859
1860 /*
1861 * If first time through, or time somehow went backwards, always update
1862 * last_start_time to match the current clock and allow worker start.
1863 * Otherwise allow it only once enough time has elapsed.
1864 */
1865 if (SlotSyncCtx->last_start_time == 0 ||
1866 curtime < SlotSyncCtx->last_start_time ||
1868 {
1870 return true;
1871 }
1872 return false;
1873}
1874
1875/*
1876 * Is current process syncing replication slots?
1877 *
1878 * Could be either backend executing SQL function or slot sync worker.
1879 */
1880bool
1882{
1883 return syncing_slots;
1884}
1885
1886/*
1887 * Amount of shared memory required for slot synchronization.
1888 */
1889Size
1891{
1892 return sizeof(SlotSyncCtxStruct);
1893}
1894
1895/*
1896 * Allocate and initialize the shared memory of slot synchronization.
1897 */
1898void
1900{
1901 Size size = SlotSyncShmemSize();
1902 bool found;
1903
1905 ShmemInitStruct("Slot Sync Data", size, &found);
1906
1907 if (!found)
1908 {
1909 memset(SlotSyncCtx, 0, size);
1912 }
1913}
1914
1915/*
1916 * Error cleanup callback for slot sync SQL function.
1917 */
1918static void
1920{
1922
1923 /*
1924 * We need to do slots cleanup here just like WalSndErrorCleanup() does.
1925 *
1926 * The startup process during promotion invokes ShutDownSlotSync() which
1927 * waits for slot sync to finish and it does that by checking the
1928 * 'syncing' flag. Thus the SQL function must be done with slots' release
1929 * and cleanup to avoid any dangling temporary slots or active slots
1930 * before it marks itself as finished syncing.
1931 */
1932
1933 /* Make sure active replication slots are released */
1934 if (MyReplicationSlot != NULL)
1936
1937 /* Also cleanup the synced temporary slots. */
1939
1940 /*
1941 * The set syncing_slots indicates that the process errored out without
1942 * resetting the flag. So, we need to clean up shared memory and reset the
1943 * flag here.
1944 */
1945 if (syncing_slots)
1947
1949}
1950
1951/*
1952 * Helper function to extract slot names from a list of remote slots
1953 */
1954static List *
1956{
1957 List *slot_names = NIL;
1958
1960 {
1961 char *slot_name;
1962
1963 slot_name = pstrdup(remote_slot->name);
1964 slot_names = lappend(slot_names, slot_name);
1965 }
1966
1967 return slot_names;
1968}
1969
1970/*
1971 * Synchronize the failover enabled replication slots using the specified
1972 * primary server connection.
1973 *
1974 * Repeatedly fetches and updates replication slot information from the
1975 * primary until all slots are at least "sync ready".
1976 *
1977 * Exits early if promotion is triggered or certain critical
1978 * configuration parameters have changed.
1979 */
1980void
1982{
1984 {
1986 List *slot_names = NIL; /* List of slot names to track */
1987
1989
1990 /* Check for interrupts and config changes */
1992
1994
1995 /* Retry until all the slots are sync-ready */
1996 for (;;)
1997 {
1998 bool slot_persistence_pending = false;
1999 bool some_slot_updated = false;
2000
2001 /* Check for interrupts and config changes */
2003
2004 /* We must be in a valid transaction state */
2006
2007 /*
2008 * Fetch remote slot info for the given slot_names. If slot_names
2009 * is NIL, fetch all failover-enabled slots. Note that we reuse
2010 * slot_names from the first iteration; re-fetching all failover
2011 * slots each time could cause an endless loop. Instead of
2012 * reprocessing only the pending slots in each iteration, it's
2013 * better to process all the slots received in the first
2014 * iteration. This ensures that by the time we're done, all slots
2015 * reflect the latest values.
2016 */
2017 remote_slots = fetch_remote_slots(wrconn, slot_names);
2018
2019 /* Attempt to synchronize slots */
2022
2023 /*
2024 * If slot_persistence_pending is true, extract slot names for
2025 * future iterations (only needed if we haven't done it yet)
2026 */
2027 if (slot_names == NIL && slot_persistence_pending)
2028 slot_names = extract_slot_names(remote_slots);
2029
2030 /* Free the current remote_slots list */
2032
2033 /* Done if all slots are persisted i.e are sync-ready */
2035 break;
2036
2037 /* wait before retrying again */
2039 }
2040
2041 if (slot_names)
2042 list_free_deep(slot_names);
2043
2044 /* Cleanup the synced temporary slots */
2046
2047 /* We are done with sync, so reset sync flag */
2049 }
2051}
sigset_t UnBlockSig
Definition pqsignal.c:22
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1645
Datum now(PG_FUNCTION_ARGS)
Definition timestamp.c:1609
#define TextDatumGetCString(d)
Definition builtins.h:98
#define NameStr(name)
Definition c.h:765
#define Min(x, y)
Definition c.h:997
#define Max(x, y)
Definition c.h:991
#define Assert(condition)
Definition c.h:873
uint32 TransactionId
Definition c.h:666
size_t Size
Definition c.h:619
int64 TimestampTz
Definition timestamp.h:39
Oid get_database_oid(const char *dbname, bool missing_ok)
void load_file(const char *filename, bool restricted)
Definition dfmgr.c:149
int errmsg_internal(const char *fmt,...)
Definition elog.c:1170
void EmitErrorReport(void)
Definition elog.c:1704
int errdetail_internal(const char *fmt,...)
Definition elog.c:1243
int errdetail(const char *fmt,...)
Definition elog.c:1216
ErrorContextCallback * error_context_stack
Definition elog.c:95
int errhint(const char *fmt,...)
Definition elog.c:1330
int errcode(int sqlerrcode)
Definition elog.c:863
int errmsg(const char *fmt,...)
Definition elog.c:1080
sigjmp_buf * PG_exception_stack
Definition elog.c:97
#define LOG
Definition elog.h:31
#define DEBUG1
Definition elog.h:30
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define ereport(elevel,...)
Definition elog.h:150
void err(int eval, const char *fmt,...)
Definition err.c:43
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
const TupleTableSlotOps TTSOpsMinimalTuple
Definition execTuples.c:86
#define palloc0_object(type)
Definition fe_memutils.h:75
int MyProcPid
Definition globals.c:47
struct Latch * MyLatch
Definition globals.c:63
void ProcessConfigFile(GucContext context)
Definition guc-file.l:120
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
@ PGC_SIGHUP
Definition guc.h:75
char * cluster_name
Definition guc_tables.c:564
volatile sig_atomic_t ConfigReloadPending
Definition interrupt.c:27
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
#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
int i
Definition isn.c:77
void ResetLatch(Latch *latch)
Definition latch.c:374
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition latch.c:172
List * lappend(List *list, void *datum)
Definition list.c:339
void list_free_deep(List *list)
Definition list.c:1560
void LockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition lmgr.c:1088
void UnlockSharedObject(Oid classid, Oid objid, uint16 objsubid, LOCKMODE lockmode)
Definition lmgr.c:1148
#define AccessShareLock
Definition lockdefs.h:36
XLogRecPtr LogicalSlotAdvanceAndCheckSnapState(XLogRecPtr moveto, bool *found_consistent_snapshot)
Definition logical.c:2094
bool IsLogicalDecodingEnabled(void)
Definition logicalctl.c:204
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition lwlock.c:1176
void LWLockRelease(LWLock *lock)
Definition lwlock.c:1793
@ LW_SHARED
Definition lwlock.h:113
@ LW_EXCLUSIVE
Definition lwlock.h:112
char * pstrdup(const char *in)
Definition mcxt.c:1781
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 CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:123
#define AmLogicalSlotSyncWorkerProcess()
Definition miscadmin.h:386
#define HOLD_INTERRUPTS()
Definition miscadmin.h:134
#define SetProcessingMode(mode)
Definition miscadmin.h:483
#define InvalidPid
Definition miscadmin.h:32
void namestrcpy(Name name, const char *str)
Definition name.c:233
void * arg
#define NIL
Definition pg_list.h:68
#define foreach_ptr(type, var, lst)
Definition pg_list.h:469
static XLogRecPtr DatumGetLSN(Datum X)
Definition pg_lsn.h:25
#define die(msg)
void pgstat_report_replslotsync(ReplicationSlot *slot)
#define pqsignal
Definition port.h:547
void FloatExceptionHandler(SIGNAL_ARGS)
Definition postgres.c:3058
void StatementCancelHandler(SIGNAL_ARGS)
Definition postgres.c:3041
static bool DatumGetBool(Datum X)
Definition postgres.h:100
static Datum PointerGetDatum(const void *X)
Definition postgres.h:352
uint64_t Datum
Definition postgres.h:70
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:342
static TransactionId DatumGetTransactionId(Datum X)
Definition postgres.h:292
#define InvalidOid
unsigned int Oid
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
static int fb(int x)
TransactionId GetOldestSafeDecodingTransactionId(bool catalogOnly)
Definition procarray.c:2904
void procsignal_sigusr1_handler(SIGNAL_ARGS)
Definition procsignal.c:677
void init_ps_display(const char *fixed_part)
Definition ps_status.c:285
char * quote_literal_cstr(const char *rawstr)
Definition quote.c:101
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition shmem.c:378
void ReplicationSlotAcquire(const char *name, bool nowait, bool error_if_invalid)
Definition slot.c:620
void ReplicationSlotCreate(const char *name, bool db_specific, ReplicationSlotPersistency persistency, bool two_phase, bool failover, bool synced)
Definition slot.c:378
void ReplicationSlotDropAcquired(void)
Definition slot.c:1031
void ReplicationSlotMarkDirty(void)
Definition slot.c:1173
ReplicationSlotInvalidationCause GetSlotInvalidationCause(const char *cause_name)
Definition slot.c:2906
void ReplicationSlotsComputeRequiredXmin(bool already_locked)
Definition slot.c:1215
void ReplicationSlotPersist(void)
Definition slot.c:1190
ReplicationSlot * MyReplicationSlot
Definition slot.c:148
void ReplicationSlotSave(void)
Definition slot.c:1155
ReplicationSlot * SearchNamedReplicationSlot(const char *name, bool need_lock)
Definition slot.c:540
void ReplicationSlotRelease(void)
Definition slot.c:758
int max_replication_slots
Definition slot.c:151
ReplicationSlotCtlData * ReplicationSlotCtl
Definition slot.c:145
void ReplicationSlotsComputeRequiredLSN(void)
Definition slot.c:1297
void ReplicationSlotCleanup(bool synced_only)
Definition slot.c:857
@ RS_TEMPORARY
Definition slot.h:47
ReplicationSlotInvalidationCause
Definition slot.h:59
@ RS_INVAL_NONE
Definition slot.h:60
#define SlotIsLogical(slot)
Definition slot.h:285
static void ReplicationSlotSetInactiveSince(ReplicationSlot *s, TimestampTz ts, bool acquire_lock)
Definition slot.h:303
SlotSyncSkipReason
Definition slot.h:81
@ SS_SKIP_WAL_NOT_FLUSHED
Definition slot.h:83
@ SS_SKIP_NO_CONSISTENT_SNAPSHOT
Definition slot.h:87
@ SS_SKIP_NONE
Definition slot.h:82
@ SS_SKIP_INVALID
Definition slot.h:89
@ SS_SKIP_WAL_OR_ROWS_REMOVED
Definition slot.h:85
static List * get_local_synced_slots(void)
Definition slotsync.c:402
#define MIN_SLOTSYNC_WORKER_NAPTIME_MS
Definition slotsync.c:124
#define PRIMARY_INFO_OUTPUT_COL_COUNT
static void slotsync_worker_disconnect(int code, Datum arg)
Definition slotsync.c:1388
void SyncReplicationSlots(WalReceiverConn *wrconn)
Definition slotsync.c:1981
static bool local_sync_slot_required(ReplicationSlot *local_slot, List *remote_slots)
Definition slotsync.c:433
static void drop_local_obsolete_slots(List *remote_slot_list)
Definition slotsync.c:486
static void reserve_wal_for_local_slot(XLogRecPtr restart_lsn)
Definition slotsync.c:543
static void update_slotsync_skip_stats(SlotSyncSkipReason skip_reason)
Definition slotsync.c:167
void ShutDownSlotSync(void)
Definition slotsync.c:1783
bool sync_replication_slots
Definition slotsync.c:117
static bool synchronize_one_slot(RemoteSlot *remote_slot, Oid remote_dbid, bool *slot_persistence_pending)
Definition slotsync.c:697
static SlotSyncCtxStruct * SlotSyncCtx
Definition slotsync.c:114
static void slotsync_failure_callback(int code, Datum arg)
Definition slotsync.c:1919
#define SLOTSYNC_COLUMN_COUNT
static List * extract_slot_names(List *remote_slots)
Definition slotsync.c:1955
static long sleep_ms
Definition slotsync.c:127
#define SLOTSYNC_RESTART_INTERVAL_SEC
Definition slotsync.c:130
char * CheckAndGetDbnameFromConninfo(void)
Definition slotsync.c:1177
static bool syncing_slots
Definition slotsync.c:137
static void ProcessSlotSyncInterrupts(void)
Definition slotsync.c:1353
#define MAX_SLOTSYNC_WORKER_NAPTIME_MS
Definition slotsync.c:125
static bool update_and_persist_local_synced_slot(RemoteSlot *remote_slot, Oid remote_dbid, bool *slot_persistence_pending)
Definition slotsync.c:618
bool SlotSyncWorkerCanRestart(void)
Definition slotsync.c:1856
static void wait_for_slot_activity(bool some_slot_updated)
Definition slotsync.c:1447
static void slotsync_reread_config(void)
Definition slotsync.c:1273
static void reset_syncing_flag(void)
Definition slotsync.c:1514
void SlotSyncShmemInit(void)
Definition slotsync.c:1899
static bool update_local_synced_slot(RemoteSlot *remote_slot, Oid remote_dbid, bool *found_consistent_snapshot, bool *remote_slot_precedes)
Definition slotsync.c:206
static void slotsync_worker_onexit(int code, Datum arg)
Definition slotsync.c:1401
static void update_synced_slots_inactive_since(void)
Definition slotsync.c:1731
bool ValidateSlotSyncParams(int elevel)
Definition slotsync.c:1204
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
bool IsSyncingReplicationSlots(void)
Definition slotsync.c:1881
void ReplSlotSyncWorkerMain(const void *startup_data, size_t startup_data_len)
Definition slotsync.c:1534
static List * fetch_remote_slots(WalReceiverConn *wrconn, List *slot_names)
Definition slotsync.c:921
Size SlotSyncShmemSize(void)
Definition slotsync.c:1890
static bool synchronize_slots(WalReceiverConn *wrconn, List *remote_slot_list, bool *slot_persistence_pending)
Definition slotsync.c:1063
bool SnapBuildSnapshotExists(XLogRecPtr lsn)
Definition snapbuild.c:2057
#define SpinLockInit(lock)
Definition spin.h:57
#define SpinLockRelease(lock)
Definition spin.h:61
#define SpinLockAcquire(lock)
Definition spin.h:59
void InitProcess(void)
Definition proc.c:395
char * dbname
Definition streamutil.c:49
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition stringinfo.c:145
void appendStringInfoString(StringInfo str, const char *s)
Definition stringinfo.c:230
void appendStringInfoChar(StringInfo str, char ch)
Definition stringinfo.c:242
void initStringInfo(StringInfo str)
Definition stringinfo.c:97
Definition pg_list.h:54
bool two_phase
Definition slotsync.c:148
char * plugin
Definition slotsync.c:146
char * name
Definition slotsync.c:145
char * database
Definition slotsync.c:147
bool failover
Definition slotsync.c:149
ReplicationSlotInvalidationCause invalidated
Definition slotsync.c:156
XLogRecPtr confirmed_lsn
Definition slotsync.c:151
XLogRecPtr restart_lsn
Definition slotsync.c:150
XLogRecPtr two_phase_at
Definition slotsync.c:152
TransactionId catalog_xmin
Definition slotsync.c:153
ReplicationSlot replication_slots[1]
Definition slot.h:296
TransactionId catalog_xmin
Definition slot.h:122
ReplicationSlotPersistency persistency
Definition slot.h:106
ReplicationSlotInvalidationCause invalidated
Definition slot.h:128
TransactionId effective_catalog_xmin
Definition slot.h:207
slock_t mutex
Definition slot.h:183
pid_t active_pid
Definition slot.h:189
SlotSyncSkipReason slotsync_skip_reason
Definition slot.h:281
bool in_use
Definition slot.h:186
ReplicationSlotPersistentData data
Definition slot.h:210
time_t last_start_time
Definition slotsync.c:110
Tuplestorestate * tuplestore
TupleDesc tupledesc
WalRcvExecStatus status
Definition c.h:760
void InitializeTimeouts(void)
Definition timeout.c:470
static bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition transam.h:297
#define InvalidTransactionId
Definition transam.h:31
#define TransactionIdIsValid(xid)
Definition transam.h:41
static bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition transam.h:263
bool tuplestore_gettupleslot(Tuplestorestate *state, bool forward, bool copy, TupleTableSlot *slot)
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition tuptable.h:398
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition tuptable.h:457
#define WL_TIMEOUT
#define WL_EXIT_ON_PM_DEATH
#define WL_LATCH_SET
static WalReceiverConn * wrconn
Definition walreceiver.c:94
bool hot_standby_feedback
Definition walreceiver.c:91
#define walrcv_connect(conninfo, replication, logical, must_use_password, appname, err)
@ WALRCV_OK_TUPLES
static void walrcv_clear_result(WalRcvExecResult *walres)
#define walrcv_get_dbname_from_conninfo(conninfo)
#define walrcv_exec(conn, exec, nRetTypes, retTypes)
#define walrcv_disconnect(conn)
XLogRecPtr GetStandbyFlushRecPtr(TimeLineID *tli)
Definition walsender.c:3648
#define SIGCHLD
Definition win32_port.h:168
#define SIGHUP
Definition win32_port.h:158
#define SIGPIPE
Definition win32_port.h:163
#define kill(pid, sig)
Definition win32_port.h:490
#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
XLogSegNo XLogGetLastRemovedSegno(void)
Definition xlog.c:3795
XLogRecPtr GetRedoRecPtr(void)
Definition xlog.c:6563
XLogRecPtr XLogGetReplicationSlotMinimumLSN(void)
Definition xlog.c:2682
int wal_segment_size
Definition xlog.c:146
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)
#define XLogRecPtrIsValid(r)
Definition xlogdefs.h:29
#define LSN_FORMAT_ARGS(lsn)
Definition xlogdefs.h:47
uint64 XLogRecPtr
Definition xlogdefs.h:21
#define InvalidXLogRecPtr
Definition xlogdefs.h:28
uint64 XLogSegNo
Definition xlogdefs.h:52
char * PrimarySlotName
bool StandbyMode
char * PrimaryConnInfo