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