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