Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : * logicalctl.c
3 : : * Functionality to control logical decoding status online.
4 : : *
5 : : * This module enables dynamic control of logical decoding availability.
6 : : * Logical decoding becomes active under two conditions: when the wal_level
7 : : * parameter is set to 'logical', or when at least one valid logical replication
8 : : * slot exists with wal_level set to 'replica'. The system disables logical
9 : : * decoding when neither condition is met. Therefore, the dynamic control
10 : : * of logical decoding availability is required only when wal_level is set
11 : : * to 'replica'. Logical decoding is always enabled when wal_level='logical'
12 : : * and always disabled when wal_level='minimal'.
13 : : *
14 : : * The core concept of dynamically enabling and disabling logical decoding
15 : : * is to separately control two aspects: writing information required for
16 : : * logical decoding to WAL records, and using logical decoding itself. During
17 : : * activation, we first enable logical WAL writing while keeping logical
18 : : * decoding disabled. This change is reflected in the read-only
19 : : * effective_wal_level GUC parameter. Once we ensure that all processes have
20 : : * updated to the latest effective_wal_level value, we then enable logical
21 : : * decoding. Deactivation follows a similar careful, multi-step process
22 : : * in reverse order.
23 : : *
24 : : * While activation occurs synchronously right after creating the first
25 : : * logical slot, deactivation happens asynchronously through the checkpointer
26 : : * process. This design avoids a race condition at the end of recovery; see
27 : : * the comments in UpdateLogicalDecodingStatusEndOfRecovery() for details.
28 : : * Asynchronous deactivation also avoids excessive toggling of the logical
29 : : * decoding status in workloads that repeatedly create and drop a single
30 : : * logical slot. On the other hand, this lazy approach can delay changes
31 : : * to effective_wal_level and the disabling of logical decoding, especially
32 : : * when the checkpointer is busy with other tasks. We chose this lazy approach
33 : : * in all deactivation paths to keep the implementation simple, even though
34 : : * laziness is strictly required only for end-of-recovery cases. Future work
35 : : * might address this limitation either by using a dedicated worker instead
36 : : * of the checkpointer, or by implementing synchronous waiting during slot
37 : : * drops if workloads are significantly affected by the lazy deactivation
38 : : * of logical decoding.
39 : : *
40 : : * Standby servers use the primary server's effective_wal_level and logical
41 : : * decoding status. Unlike normal activation and deactivation, these
42 : : * are updated simultaneously without status change coordination, solely by
43 : : * replaying XLOG_LOGICAL_DECODING_STATUS_CHANGE records. The local wal_level
44 : : * setting has no effect during this time. Upon promotion, we update the
45 : : * logical decoding status based on local conditions: the wal_level value and
46 : : * the presence of logical slots.
47 : : *
48 : : * In the future, we could extend support to include automatic transitions
49 : : * of effective_wal_level between 'minimal' and 'logical' WAL levels. However,
50 : : * this enhancement would require additional coordination mechanisms and
51 : : * careful implementation of operations such as terminating walsenders and
52 : : * archiver processes while carefully considering the sequence of operations
53 : : * to ensure system stability during these transitions.
54 : : *
55 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
56 : : * Portions Copyright (c) 1994, Regents of the University of California
57 : : *
58 : : * IDENTIFICATION
59 : : * src/backend/replication/logical/logicalctl.c
60 : : *
61 : : *-------------------------------------------------------------------------
62 : : */
63 : :
64 : : #include "postgres.h"
65 : :
66 : : #include "access/xloginsert.h"
67 : : #include "access/xlogrecovery.h"
68 : : #include "catalog/pg_control.h"
69 : : #include "miscadmin.h"
70 : : #include "replication/slot.h"
71 : : #include "storage/ipc.h"
72 : : #include "storage/lmgr.h"
73 : : #include "storage/proc.h"
74 : : #include "storage/procarray.h"
75 : : #include "storage/procsignal.h"
76 : : #include "storage/subsystems.h"
77 : : #include "utils/injection_point.h"
78 : :
79 : : /*
80 : : * Struct for controlling the logical decoding status.
81 : : *
82 : : * This struct is protected by LogicalDecodingControlLock.
83 : : */
84 : : typedef struct LogicalDecodingCtlData
85 : : {
86 : : /*
87 : : * This is the authoritative value used by all processes to determine
88 : : * whether to write additional information required by logical decoding to
89 : : * WAL. Since this information could be checked frequently, each process
90 : : * caches this value in XLogLogicalInfo for better performance.
91 : : */
92 : : bool xlog_logical_info;
93 : :
94 : : /* True if logical decoding is available in the system */
95 : : bool logical_decoding_enabled;
96 : :
97 : : /* True if logical decoding might need to be disabled */
98 : : bool pending_disable;
99 : :
100 : : /*
101 : : * End LSN of the last XLOG_LOGICAL_DECODING_STATUS_CHANGE record that
102 : : * enabled logical decoding during recovery (either replayed or written at
103 : : * the end of recovery), or InvalidXLogRecPtr if none has occurred since
104 : : * the server started. Checking it with logical_decoding_enabled tells
105 : : * from which point on WAL was written with logical decoding enabled; see
106 : : * GetLogicalDecodingEnabledLSN() and
107 : : * StandbyLogicalDecodingEnabledSince().
108 : : *
109 : : * WAL records that disable logical decoding are deliberately not tracked
110 : : * here. logical_decoding_enabled is false while decoding is off, which is
111 : : * all the check needs.
112 : : *
113 : : * This is maintained only during recovery and is not persisted, so it
114 : : * says nothing about a status change replayed in an earlier server run.
115 : : */
116 : : XLogRecPtr last_enable_lsn;
117 : : } LogicalDecodingCtlData;
118 : :
119 : : static LogicalDecodingCtlData *LogicalDecodingCtl = NULL;
120 : :
121 : : static void LogicalDecodingCtlShmemRequest(void *arg);
122 : : static void LogicalDecodingCtlShmemInit(void *arg);
123 : :
124 : : const ShmemCallbacks LogicalDecodingCtlShmemCallbacks = {
125 : : .request_fn = LogicalDecodingCtlShmemRequest,
126 : : .init_fn = LogicalDecodingCtlShmemInit,
127 : : };
128 : :
129 : : /*
130 : : * A process-local cache of LogicalDecodingCtl->xlog_logical_info. This is
131 : : * initialized at process startup, and updated when processing the process
132 : : * barrier signal in ProcessBarrierUpdateXLogLogicalInfo(). If the process
133 : : * is in an XID-assigned transaction, the cache update is delayed until the
134 : : * transaction ends. See the comments for XLogLogicalInfoUpdatePending for details.
135 : : */
136 : : bool XLogLogicalInfo = false;
137 : :
138 : : /*
139 : : * When receiving the PROCSIGNAL_BARRIER_UPDATE_XLOG_LOGICAL_INFO signal, if
140 : : * an XID is assigned to the current transaction, the process sets this flag and
141 : : * delays the XLogLogicalInfo update until the transaction ends. This ensures
142 : : * that the XLogLogicalInfo value (typically accessed via XLogLogicalInfoActive)
143 : : * remains consistent throughout the transaction.
144 : : */
145 : : static bool XLogLogicalInfoUpdatePending = false;
146 : :
147 : : static void update_xlog_logical_info(void);
148 : : static void abort_logical_decoding_activation(int code, Datum arg);
149 : : static XLogRecPtr write_logical_decoding_status_update_record(bool status);
150 : :
151 : : static void
236 heikki.linnakangas@i 152 :CBC 1329 : LogicalDecodingCtlShmemRequest(void *arg)
153 : : {
154 : 1329 : ShmemRequestStruct(.name = "Logical decoding control",
155 : : .size = sizeof(LogicalDecodingCtlData),
156 : : .ptr = (void **) &LogicalDecodingCtl,
157 : : );
340 msawada@postgresql.o 158 : 1329 : }
159 : :
160 : : static void
52 161 : 1325 : LogicalDecodingCtlShmemInit(void *arg)
162 : : {
163 : 1325 : LogicalDecodingCtl->xlog_logical_info = false;
164 : 1325 : LogicalDecodingCtl->logical_decoding_enabled = false;
165 : 1325 : LogicalDecodingCtl->pending_disable = false;
4 166 : 1325 : LogicalDecodingCtl->last_enable_lsn = InvalidXLogRecPtr;
52 167 : 1325 : }
168 : :
169 : : /*
170 : : * Initialize the logical decoding status in shmem at server startup. This
171 : : * must be called ONCE during postmaster or standalone-backend startup.
172 : : */
173 : : void
340 174 : 1143 : StartupLogicalDecodingStatus(bool last_status)
175 : : {
176 : : /* Logical decoding is always disabled when 'minimal' WAL level */
177 [ + + ]: 1143 : if (wal_level == WAL_LEVEL_MINIMAL)
178 : 399 : return;
179 : :
180 : : /*
181 : : * Set the initial logical decoding status based on the last status. If
182 : : * logical decoding was enabled before the last shutdown, it remains
183 : : * enabled as we might have set wal_level='logical' or have at least one
184 : : * logical slot.
185 : : */
186 : 744 : LogicalDecodingCtl->xlog_logical_info = last_status;
187 : 744 : LogicalDecodingCtl->logical_decoding_enabled = last_status;
188 : : }
189 : :
190 : : /*
191 : : * Update the XLogLogicalInfo cache.
192 : : */
193 : : static inline void
194 : 27455 : update_xlog_logical_info(void)
195 : : {
196 : 27455 : XLogLogicalInfo = IsXLogLogicalInfoEnabled();
197 : 27455 : }
198 : :
199 : : /*
200 : : * Initialize XLogLogicalInfo backend-private cache. This routine is called
201 : : * during process initialization.
202 : : */
203 : : void
204 : 25028 : InitializeProcessXLogLogicalInfo(void)
205 : : {
206 : 25028 : update_xlog_logical_info();
207 : 25028 : }
208 : :
209 : : /*
210 : : * This routine is called when we are told to update XLogLogicalInfo
211 : : * by a ProcSignalBarrier.
212 : : */
213 : : bool
214 : 2427 : ProcessBarrierUpdateXLogLogicalInfo(void)
215 : : {
216 [ + + ]: 2427 : if (GetTopTransactionIdIfAny() != InvalidTransactionId)
217 : : {
218 : : /* Delay updating XLogLogicalInfo until the transaction end */
219 : 8 : XLogLogicalInfoUpdatePending = true;
220 : : }
221 : : else
222 : 2419 : update_xlog_logical_info();
223 : :
224 : 2427 : return true;
225 : : }
226 : :
227 : : /*
228 : : * Check the shared memory state and return true if logical decoding is
229 : : * enabled on the system.
230 : : */
231 : : bool
232 : 21958 : IsLogicalDecodingEnabled(void)
233 : : {
234 : : bool enabled;
235 : :
236 : 21958 : LWLockAcquire(LogicalDecodingControlLock, LW_SHARED);
237 : 21958 : enabled = LogicalDecodingCtl->logical_decoding_enabled;
238 : 21958 : LWLockRelease(LogicalDecodingControlLock);
239 : :
240 : 21958 : return enabled;
241 : : }
242 : :
243 : : /*
244 : : * Return the end LSN of the last XLOG_LOGICAL_DECODING_STATUS_CHANGE record
245 : : * that enabled logical decoding during recovery, or InvalidXLogRecPtr if
246 : : * none has occurred since the server started.
247 : : *
248 : : * last_enable_lsn is maintained only during recovery, so this is
249 : : * intended for callers that have checked RecoveryInProgress(). Unlike
250 : : * StandbyLogicalDecodingEnabledSince(), we do not assert RecoveryInProgress()
251 : : * here because recovery may end concurrently right after the caller's check.
252 : : */
253 : : XLogRecPtr
4 254 : 29 : GetLogicalDecodingEnabledLSN(void)
255 : : {
256 : : XLogRecPtr lsn;
257 : :
258 : 29 : LWLockAcquire(LogicalDecodingControlLock, LW_SHARED);
259 : 29 : lsn = LogicalDecodingCtl->last_enable_lsn;
260 : 29 : LWLockRelease(LogicalDecodingControlLock);
261 : :
262 : 29 : return lsn;
263 : : }
264 : :
265 : : /*
266 : : * Return true if logical decoding has been enabled continuously from the given
267 : : * LSN up to the current replay position, that is, if the WAL in that range
268 : : * was written with logical decoding enabled.
269 : : *
270 : : * The given LSN must have been replayed already; nothing can be said about
271 : : * WAL this server has not replayed yet. The caller is responsible for checking
272 : : * that.
273 : : */
274 : : bool
52 275 : 11 : StandbyLogicalDecodingEnabledSince(XLogRecPtr lsn)
276 : : {
277 : : bool result;
278 : :
279 [ - + ]: 11 : Assert(RecoveryInProgress());
280 [ - + ]: 11 : Assert(lsn <= GetXLogReplayRecPtr(NULL));
281 : :
282 : 11 : LWLockAcquire(LogicalDecodingControlLock, LW_SHARED);
283 [ + + ]: 21 : result = LogicalDecodingCtl->logical_decoding_enabled &&
4 284 [ + + ]: 10 : lsn >= LogicalDecodingCtl->last_enable_lsn;
52 285 : 11 : LWLockRelease(LogicalDecodingControlLock);
286 : :
287 : 11 : return result;
288 : : }
289 : :
290 : : /*
291 : : * Returns true if logical WAL logging is enabled based on the shared memory
292 : : * status.
293 : : */
294 : : bool
340 295 : 27500 : IsXLogLogicalInfoEnabled(void)
296 : : {
297 : : bool xlog_logical_info;
298 : :
299 : 27500 : LWLockAcquire(LogicalDecodingControlLock, LW_SHARED);
300 : 27500 : xlog_logical_info = LogicalDecodingCtl->xlog_logical_info;
301 : 27500 : LWLockRelease(LogicalDecodingControlLock);
302 : :
303 : 27500 : return xlog_logical_info;
304 : : }
305 : :
306 : : /*
307 : : * Apply a pending XLogLogicalInfo update at end of the top-level transaction.
308 : : *
309 : : * This is called from CommitTransaction(), PrepareTransaction(), and
310 : : * CleanupTransaction(), which are the only places where the top-level XID is
311 : : * reset, so the next transaction always starts with the latest value.
312 : : */
313 : : void
314 : 442637 : AtEOXact_LogicalCtl(void)
315 : : {
316 : : /* Update the local cache if there is a pending update */
317 [ + + ]: 442637 : if (XLogLogicalInfoUpdatePending)
318 : : {
319 : 8 : update_xlog_logical_info();
320 : 8 : XLogLogicalInfoUpdatePending = false;
321 : : }
322 : 442637 : }
323 : :
324 : : /*
325 : : * Writes an XLOG_LOGICAL_DECODING_STATUS_CHANGE WAL record with the given
326 : : * status, and returns the end LSN of the inserted record.
327 : : */
328 : : static XLogRecPtr
329 : 124 : write_logical_decoding_status_update_record(bool status)
330 : : {
331 : : XLogRecPtr recptr;
332 : :
333 : 124 : XLogBeginInsert();
334 : 124 : XLogRegisterData(&status, sizeof(bool));
335 : 124 : recptr = XLogInsert(RM_XLOG_ID, XLOG_LOGICAL_DECODING_STATUS_CHANGE);
336 : 124 : XLogFlush(recptr);
337 : :
4 338 : 124 : return recptr;
339 : : }
340 : :
341 : : /*
342 : : * A PG_ENSURE_ERROR_CLEANUP callback for activating logical decoding.
343 : : *
344 : : * Rather than directly reverting xlog_logical_info here, we request
345 : : * that the checkpointer handle it via the normal disable path. This
346 : : * avoids race conditions when multiple backends attempt concurrent
347 : : * activation: the checkpointer will reset xlog_logical_info when
348 : : * no valid logical slots exist.
349 : : */
350 : : static void
340 351 : 2 : abort_logical_decoding_activation(int code, Datum arg)
352 : : {
353 [ + - ]: 2 : elog(DEBUG1, "aborting logical decoding activation process");
172 354 : 2 : RequestDisableLogicalDecoding();
340 355 : 2 : }
356 : :
357 : : /*
358 : : * Enable logical decoding if disabled.
359 : : *
360 : : * If this function is called during recovery, it just checks that logical
361 : : * decoding is still enabled, since the logical decoding status cannot be
362 : : * changed during this time. The logical decoding status depends on the
363 : : * status on the primary.
364 : : *
365 : : * Note that there is no interlock between logical decoding activation
366 : : * and slot creation. To ensure enabling logical decoding, the caller
367 : : * needs to call this function after creating a logical slot before
368 : : * initializing the logical decoding context.
369 : : */
370 : : void
371 : 563 : EnsureLogicalDecodingEnabled(void)
372 : : {
373 [ - + ]: 563 : Assert(MyReplicationSlot);
374 [ - + ]: 563 : Assert(wal_level >= WAL_LEVEL_REPLICA);
375 : :
376 : : /* Logical decoding is always enabled */
377 [ + + ]: 563 : if (wal_level >= WAL_LEVEL_LOGICAL)
378 : 528 : return;
379 : :
380 [ + + ]: 35 : if (RecoveryInProgress())
381 : : {
382 : : /*
383 : : * The caller has already checked that logical decoding is enabled via
384 : : * CheckLogicalDecodingRequirements(), but the status could have been
385 : : * disabled concurrently before we created our slot: either by
386 : : * replaying an XLOG_LOGICAL_DECODING_STATUS_CHANGE record, or by
387 : : * UpdateLogicalDecodingStatusEndOfRecovery() upon promotion. We
388 : : * cannot enable logical decoding during recovery, so raise an error.
389 : : *
390 : : * Our slot has already been created, so its in_use flag is set and
391 : : * the slot scans performed by a deactivation can see it. It
392 : : * guarantees that this check doesn't miss a concurrent deactivation:
393 : : * UpdateLogicalDecodingStatusEndOfRecovery() won't disable logical
394 : : * decoding since CheckLogicalSlotExists() finds our valid slot, and
395 : : * replaying a status change record after this check invalidates our
396 : : * slot, so this slot creation fails afterwards anyway (by a recovery
397 : : * conflict or the requirement re-check in
398 : : * CreateInitDecodingContext()). Hence, this check only needs to catch
399 : : * deactivations that completed before our slot's in_use flag was set.
400 : : */
121 401 [ + + ]: 4 : if (!IsLogicalDecodingEnabled())
402 [ + - ]: 1 : ereport(ERROR,
403 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
404 : : errmsg("logical decoding on standby requires \"effective_wal_level\" >= \"logical\" on the primary"),
405 : : errdetail("Logical decoding was concurrently disabled during the logical replication slot creation.")));
406 : :
340 407 : 3 : return;
408 : : }
409 : :
410 : : /*
411 : : * Ensure to abort the activation process in cases where there is an
412 : : * interruption during the wait.
413 : : */
414 [ + + ]: 31 : PG_ENSURE_ERROR_CLEANUP(abort_logical_decoding_activation, (Datum) 0);
415 : : {
52 416 : 31 : EnableLogicalDecoding(InvalidXLogRecPtr);
417 : : }
340 418 [ - + ]: 31 : PG_END_ENSURE_ERROR_CLEANUP(abort_logical_decoding_activation, (Datum) 0);
419 : : }
420 : :
421 : : /*
422 : : * A workhorse function to enable logical decoding.
423 : : *
424 : : * lsn is the end LSN of the XLOG_LOGICAL_DECODING_STATUS_CHANGE record
425 : : * being replayed, and is InvalidXLogRecPtr when not called from redo.
426 : : */
427 : : void
52 428 : 56 : EnableLogicalDecoding(XLogRecPtr lsn)
429 : : {
430 : : bool in_recovery;
431 : :
340 432 : 56 : LWLockAcquire(LogicalDecodingControlLock, LW_EXCLUSIVE);
433 : :
434 : : /*
435 : : * Remember where logical decoding was enabled. This has to happen before
436 : : * the early return below, because replay can reach here with the status
437 : : * already on. For example, CreateCheckPoint() fixes the redo point before
438 : : * it records logicalDecodingEnabled, so a checkpoint can claim logical
439 : : * decoding is enabled while the record that enabled it still follows the
440 : : * redo point.
441 : : */
52 442 [ - + ]: 56 : Assert(RecoveryInProgress() == XLogRecPtrIsValid(lsn));
443 [ + + ]: 56 : if (XLogRecPtrIsValid(lsn))
4 444 : 25 : LogicalDecodingCtl->last_enable_lsn = lsn;
445 : :
446 : : /* Return if it is already enabled */
340 447 [ + + ]: 56 : if (LogicalDecodingCtl->logical_decoding_enabled)
448 : : {
449 : 5 : LogicalDecodingCtl->pending_disable = false;
450 : 5 : LWLockRelease(LogicalDecodingControlLock);
451 : 5 : return;
452 : : }
453 : :
454 : : /*
455 : : * Set logical info WAL logging in shmem. All processes starting after
456 : : * this point will include the information required by logical decoding in
457 : : * WAL records.
458 : : */
459 : 51 : LogicalDecodingCtl->xlog_logical_info = true;
460 : :
461 : 51 : LWLockRelease(LogicalDecodingControlLock);
462 : :
463 : : /*
464 : : * Tell all running processes to reflect the xlog_logical_info update, and
465 : : * wait. This ensures that all running processes have enabled logical
466 : : * information WAL logging.
467 : : */
468 : 51 : WaitForProcSignalBarrier(
469 : : EmitProcSignalBarrier(PROCSIGNAL_BARRIER_UPDATE_XLOG_LOGICAL_INFO));
470 : :
471 : 51 : INJECTION_POINT("logical-decoding-activation", NULL);
472 : :
473 : 49 : in_recovery = RecoveryInProgress();
474 : :
475 : : /*
476 : : * There could be some transactions that might have started with the old
477 : : * status, but we don't need to wait for these transactions to complete as
478 : : * long as they have valid XIDs. These transactions will appear in the
479 : : * xl_running_xacts record and therefore the snapshot builder will not try
480 : : * to decode the transaction during the logical decoding initialization.
481 : : *
482 : : * There is a theoretical case where a transaction decides whether to
483 : : * include logical-info in WAL records before getting an XID. In this
484 : : * case, the transaction won't appear in xl_running_xacts.
485 : : *
486 : : * For operations that do not require an XID assignment, the process
487 : : * starts including logical-info immediately upon receiving the signal
488 : : * (barrier). If such an operation checks the effective_wal_level multiple
489 : : * times within a single execution, the resulting WAL records might be
490 : : * inconsistent (i.e., logical-info is included in some records but not in
491 : : * others). However, this is harmless because logical decoding generally
492 : : * ignores WAL records that are not associated with an assigned XID.
493 : : *
494 : : * One might think we need to wait for all running transactions, including
495 : : * those without XIDs and read-only transactions, to finish before
496 : : * enabling logical decoding. However, such a requirement would force the
497 : : * slot creation to wait for a potentially very long time due to
498 : : * long-running read queries, which is practically unacceptable.
499 : : */
500 : :
172 501 : 49 : LWLockAcquire(LogicalDecodingControlLock, LW_EXCLUSIVE);
502 : :
503 : : /*
504 : : * Re-check whether logical decoding got enabled while we waited for the
505 : : * barrier above.
506 : : */
124 507 [ + + ]: 49 : if (LogicalDecodingCtl->logical_decoding_enabled)
508 : : {
509 : 1 : LogicalDecodingCtl->pending_disable = false;
510 : 1 : LWLockRelease(LogicalDecodingControlLock);
511 : 1 : return;
512 : : }
513 : :
340 514 : 48 : START_CRIT_SECTION();
515 : :
516 : : /*
517 : : * We enable logical decoding first, followed by writing the WAL record.
518 : : * This sequence ensures logical decoding becomes available on the primary
519 : : * first.
520 : : */
521 : 48 : LogicalDecodingCtl->logical_decoding_enabled = true;
522 : :
523 [ + + ]: 48 : if (!in_recovery)
524 : 23 : write_logical_decoding_status_update_record(true);
525 : :
526 : 48 : LogicalDecodingCtl->pending_disable = false;
527 : :
528 [ - + ]: 48 : END_CRIT_SECTION();
529 : :
172 530 : 48 : LWLockRelease(LogicalDecodingControlLock);
531 : :
532 : : /*
533 : : * We log the activation message after releasing the slot lock. This is
534 : : * safe because the activation is performed while holding a logical slot,
535 : : * meaning, a concurrent deactivation cannot interleave its log message
536 : : * ahead of ours.
537 : : */
340 538 [ + + ]: 48 : if (!in_recovery)
539 [ + - ]: 23 : ereport(LOG,
540 : : errmsg("logical decoding is enabled upon creating a new logical replication slot"));
541 : : }
542 : :
543 : : /*
544 : : * Initiate a request for disabling logical decoding.
545 : : *
546 : : * Note that this function does not verify whether logical slots exist. The
547 : : * checkpointer will verify if logical decoding should actually be disabled.
548 : : *
549 : : * This may be called during recovery, for example when a standby invalidates
550 : : * its last valid logical slot. That is safe because the queued request is only
551 : : * acted upon outside recovery. See the RecoveryInProgress() check in
552 : : * DisableLogicalDecodingIfNecessary().
553 : : */
554 : : void
555 : 490 : RequestDisableLogicalDecoding(void)
556 : : {
557 [ + + ]: 490 : if (wal_level != WAL_LEVEL_REPLICA)
558 : 453 : return;
559 : :
560 : : /*
561 : : * It's possible that we might not actually need to disable logical
562 : : * decoding if someone creates a new logical slot concurrently. We set the
563 : : * flag anyway and the checkpointer will check it and disable logical
564 : : * decoding if necessary.
565 : : */
566 : 37 : LWLockAcquire(LogicalDecodingControlLock, LW_EXCLUSIVE);
567 : 37 : LogicalDecodingCtl->pending_disable = true;
568 : 37 : LWLockRelease(LogicalDecodingControlLock);
569 : :
570 : 37 : WakeupCheckpointer();
571 : :
572 [ + + ]: 37 : elog(DEBUG1, "requested disabling logical decoding");
573 : : }
574 : :
575 : : /*
576 : : * Disable logical decoding if necessary.
577 : : *
578 : : * This function disables logical decoding upon a request initiated by
579 : : * RequestDisableLogicalDecoding(). Otherwise, it performs no action.
580 : : */
581 : : void
582 : 6260 : DisableLogicalDecodingIfNecessary(void)
583 : : {
584 : : bool pending_disable;
585 : :
586 [ + + ]: 6260 : if (wal_level != WAL_LEVEL_REPLICA)
587 : 1397 : return;
588 : :
589 : : /*
590 : : * Sanity check as we cannot disable logical decoding while holding a
591 : : * logical slot.
592 : : */
593 [ - + ]: 4863 : Assert(!MyReplicationSlot);
594 : :
595 : : /*
596 : : * During recovery the logical decoding status follows the primary via WAL
597 : : * replay, so we must not disable it here. A pending_disable request
598 : : * queued during recovery, for example by a local slot invalidation, is
599 : : * intentionally left for the end-of-recovery transition or the
600 : : * post-promotion checkpointer to act on. See
601 : : * UpdateLogicalDecodingStatusEndOfRecovery().
602 : : */
603 [ + + ]: 4863 : if (RecoveryInProgress())
604 : 1956 : return;
605 : :
606 : 2907 : LWLockAcquire(LogicalDecodingControlLock, LW_SHARED);
607 : 2907 : pending_disable = LogicalDecodingCtl->pending_disable;
608 : 2907 : LWLockRelease(LogicalDecodingControlLock);
609 : :
610 : : /* Quick return if no pending disable request */
611 [ + + ]: 2907 : if (!pending_disable)
612 : 2873 : return;
613 : :
614 : 34 : DisableLogicalDecoding();
615 : : }
616 : :
617 : : /*
618 : : * A workhorse function to disable logical decoding.
619 : : */
620 : : void
621 : 60 : DisableLogicalDecoding(void)
622 : : {
623 : 60 : bool in_recovery = RecoveryInProgress();
624 : : bool was_enabled;
625 : :
626 : 60 : LWLockAcquire(LogicalDecodingControlLock, LW_EXCLUSIVE);
627 : :
628 : : /*
629 : : * Check if we can disable logical decoding.
630 : : *
631 : : * Nothing to do if both flags are already off, or if valid slots exist
632 : : * (skip the slot check during recovery because the existing slots will be
633 : : * invalidated after disabling logical decoding.)
634 : : */
172 635 [ + + ]: 60 : if ((!LogicalDecodingCtl->logical_decoding_enabled &&
636 [ + + ]: 4 : !LogicalDecodingCtl->xlog_logical_info) ||
340 637 [ + + + + ]: 57 : (!in_recovery && CheckLogicalSlotExists()))
638 : : {
639 : 9 : LogicalDecodingCtl->pending_disable = false;
640 : 9 : LWLockRelease(LogicalDecodingControlLock);
641 : 9 : return;
642 : : }
643 : :
644 : : /*
645 : : * Remember if logical decoding was enabled. An interrupted activation can
646 : : * leave xlog_logical_info=true while logical_decoding_enabled remains
647 : : * false.
648 : : */
172 649 : 51 : was_enabled = LogicalDecodingCtl->logical_decoding_enabled;
650 : :
340 651 : 51 : START_CRIT_SECTION();
652 : :
653 : : /*
654 : : * We need to disable logical decoding first and then disable logical
655 : : * information WAL logging in order to ensure that no logical decoding
656 : : * processes WAL records with insufficient information.
657 : : */
658 : 51 : LogicalDecodingCtl->logical_decoding_enabled = false;
659 : :
660 : : /* Write the WAL to disable logical decoding on standbys too */
172 661 [ + + + + ]: 51 : if (!in_recovery && was_enabled)
340 662 : 24 : write_logical_decoding_status_update_record(false);
663 : :
664 : : /* Now disable logical information WAL logging */
665 : 51 : LogicalDecodingCtl->xlog_logical_info = false;
666 : 51 : LogicalDecodingCtl->pending_disable = false;
667 : :
668 [ - + ]: 51 : END_CRIT_SECTION();
669 : :
670 : : /*
671 : : * Logging under the lock guarantees our "is disabled" message appears in
672 : : * the server log before its eventual "is enabled", making server log
673 : : * diagnostics easy.
674 : : */
172 675 [ + + + + ]: 51 : if (!in_recovery && was_enabled)
340 676 [ + - ]: 24 : ereport(LOG,
677 : : errmsg("logical decoding is disabled because there are no valid logical replication slots"));
678 : :
679 : 51 : LWLockRelease(LogicalDecodingControlLock);
680 : :
681 : : /*
682 : : * Tell all running processes to reflect the xlog_logical_info update.
683 : : * Unlike when enabling logical decoding, we don't need to wait for all
684 : : * processes to complete it in this case. We already disabled logical
685 : : * decoding and it's always safe to write logical information to WAL
686 : : * records, even when not strictly required. Therefore, we don't need to
687 : : * wait for all running transactions to finish either.
688 : : */
689 : 51 : EmitProcSignalBarrier(PROCSIGNAL_BARRIER_UPDATE_XLOG_LOGICAL_INFO);
690 : : }
691 : :
692 : : /*
693 : : * Update the logical decoding status at end of recovery, synchronizing
694 : : * process-local WAL logging state when necessary. This function must
695 : : * be called before accepting writes.
696 : : */
697 : : void
698 : 1070 : UpdateLogicalDecodingStatusEndOfRecovery(void)
699 : : {
700 : 1070 : bool new_status = false;
701 : :
702 [ - + ]: 1070 : Assert(RecoveryInProgress());
703 : :
704 : 1070 : LWLockAcquire(LogicalDecodingControlLock, LW_EXCLUSIVE);
705 : :
706 : : /*
707 : : * With 'minimal' WAL level, no logical replication slot can exist (see
708 : : * RestoreSlotFromDisk()), so the new status is always false. However,
709 : : * logical decoding could have been enabled during recovery by replaying
710 : : * an XLOG_LOGICAL_DECODING_STATUS_CHANGE record from WAL generated with a
711 : : * higher wal_level, e.g. if the server crashed right after the last
712 : : * logical slot was dropped and then restarted with wal_level='minimal'.
713 : : * The code below disables logical decoding in that case.
714 : : */
715 [ + + + + ]: 1070 : if (wal_level == WAL_LEVEL_LOGICAL || CheckLogicalSlotExists())
716 : 144 : new_status = true;
717 : :
718 : : /*
719 : : * When recovery ends, we need to either enable or disable logical
720 : : * decoding based on the wal_level setting and the presence of logical
721 : : * slots. We need to note that concurrent slot creation and deletion could
722 : : * happen but WAL writes are still not permitted until recovery fully
723 : : * completes. Here's how we handle concurrent toggling of logical
724 : : * decoding:
725 : : *
726 : : * For 'enable' case, if there's a concurrent disable request before
727 : : * recovery fully completes, the checkpointer will handle it after
728 : : * recovery is done. This means there might be a brief period after
729 : : * recovery where logical decoding remains enabled even with no logical
730 : : * replication slots present. This temporary state is not new - it can
731 : : * already occur due to the checkpointer's asynchronous deactivation
732 : : * process.
733 : : *
734 : : * For 'disable' case, a backend concurrently creating a logical slot on a
735 : : * standby could have passed its CheckLogicalDecodingRequirements() check
736 : : * when creating its slot only after our slot check above. Such a backend
737 : : * rechecks the status after creating the slot in
738 : : * EnsureLogicalDecodingEnabled() and raises an error if logical decoding
739 : : * has been disabled meanwhile, so it cannot end up with a logical slot
740 : : * while logical decoding remains disabled. (If recovery has already ended
741 : : * by the time of the recheck, the backend instead enables logical
742 : : * decoding by itself, which is fine after promotion.)
743 : : */
744 [ + + ]: 1070 : if (new_status != LogicalDecodingCtl->logical_decoding_enabled)
745 : : {
746 : : XLogRecPtr recptr;
747 : :
748 : : /*
749 : : * Update both the logical decoding status and logical WAL logging
750 : : * status. Unlike toggling these status during non-recovery, we don't
751 : : * need to worry about the operation order as WAL writes are still not
752 : : * permitted.
753 : : */
754 : 77 : LogicalDecodingCtl->xlog_logical_info = new_status;
755 : 77 : LogicalDecodingCtl->logical_decoding_enabled = new_status;
756 : :
757 [ + + ]: 77 : elog(DEBUG1,
758 : : "update logical decoding status to %d at the end of recovery",
759 : : new_status);
760 : :
761 : : /*
762 : : * Now that we updated the logical decoding status, clear the pending
763 : : * disable flag. It's possible that a concurrent process drops the
764 : : * last logical slot and initiates the pending disable again. The
765 : : * checkpointer process will check it.
766 : : */
767 : 77 : LogicalDecodingCtl->pending_disable = false;
768 : :
769 : : /*
770 : : * Write the WAL record and update last_enable_lsn before releasing
771 : : * LogicalDecodingControlLock so that concurrent slot creation before
772 : : * recovery completes sees the new LSN.
773 : : */
4 774 : 77 : recptr = write_logical_decoding_status_update_record(new_status);
775 [ + + ]: 77 : if (new_status)
776 : 74 : LogicalDecodingCtl->last_enable_lsn = recptr;
777 : : }
778 : :
779 : 1070 : LWLockRelease(LogicalDecodingControlLock);
780 : :
781 : : /*
782 : : * With wal_level = logical, XLogLogicalInfoActive() is always true, so no
783 : : * barrier is needed.
784 : : *
785 : : * Otherwise, notify all processes to refresh XLogLogicalInfo. Wait only
786 : : * if new_status is true, even if the shared status is unchanged, since
787 : : * recovery may have left stale caches. Writes are not yet allowed, so we
788 : : * need not wait for running transactions to finish.
789 : : *
790 : : * If new_status is false, stale caches only cause extra logical
791 : : * information in WAL, which is safe (see DisableLogicalDecoding()).
792 : : */
42 fujii@postgresql.org 793 [ + + + + ]: 1070 : if (IsUnderPostmaster && wal_level != WAL_LEVEL_LOGICAL)
794 : : {
795 : : uint64 generation;
796 : :
797 : 800 : generation = EmitProcSignalBarrier(PROCSIGNAL_BARRIER_UPDATE_XLOG_LOGICAL_INFO);
798 [ + + ]: 800 : if (new_status)
799 : 5 : WaitForProcSignalBarrier(generation);
800 : : }
801 : :
340 msawada@postgresql.o 802 : 1070 : INJECTION_POINT("startup-logical-decoding-status-change-end-of-recovery", NULL);
803 : 1070 : }
|