Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : * logical.c
3 : : * PostgreSQL logical decoding coordination
4 : : *
5 : : * Copyright (c) 2012-2026, PostgreSQL Global Development Group
6 : : *
7 : : * IDENTIFICATION
8 : : * src/backend/replication/logical/logical.c
9 : : *
10 : : * NOTES
11 : : * This file coordinates interaction between the various modules that
12 : : * together provide logical decoding, primarily by providing so
13 : : * called LogicalDecodingContexts. The goal is to encapsulate most of the
14 : : * internal complexity for consumers of logical decoding, so they can
15 : : * create and consume a changestream with a low amount of code. Builtin
16 : : * consumers are the walsender and SQL SRF interface, but it's possible to
17 : : * add further ones without changing core code, e.g. to consume changes in
18 : : * a bgworker.
19 : : *
20 : : * The idea is that a consumer provides three callbacks, one to read WAL,
21 : : * one to prepare a data write, and a final one for actually writing since
22 : : * their implementation depends on the type of consumer. Check
23 : : * logicalfuncs.c for an example implementation of a fairly simple consumer
24 : : * and an implementation of a WAL reading callback that's suitable for
25 : : * simple consumers.
26 : : *-------------------------------------------------------------------------
27 : : */
28 : :
29 : : #include "postgres.h"
30 : :
31 : : #include "access/xact.h"
32 : : #include "access/xlog_internal.h"
33 : : #include "access/xlogutils.h"
34 : : #include "commands/repack.h"
35 : : #include "fmgr.h"
36 : : #include "miscadmin.h"
37 : : #include "pgstat.h"
38 : : #include "replication/decode.h"
39 : : #include "replication/logical.h"
40 : : #include "replication/reorderbuffer.h"
41 : : #include "replication/slotsync.h"
42 : : #include "replication/snapbuild.h"
43 : : #include "storage/proc.h"
44 : : #include "storage/procarray.h"
45 : : #include "utils/builtins.h"
46 : : #include "utils/guc.h"
47 : : #include "utils/guc_hooks.h"
48 : : #include "utils/injection_point.h"
49 : : #include "utils/inval.h"
50 : : #include "utils/memutils.h"
51 : : #include "utils/varlena.h"
52 : :
53 : : /* data for errcontext callback */
54 : : typedef struct LogicalErrorCallbackState
55 : : {
56 : : LogicalDecodingContext *ctx;
57 : : const char *callback_name;
58 : : XLogRecPtr report_location;
59 : : } LogicalErrorCallbackState;
60 : :
61 : : /* GUC variables */
62 : : char *output_plugin_libraries_string;
63 : :
64 : : /* wrappers around output plugin callbacks */
65 : : static void output_plugin_error_callback(void *arg);
66 : : static void startup_cb_wrapper(LogicalDecodingContext *ctx, OutputPluginOptions *opt,
67 : : bool is_init);
68 : : static void shutdown_cb_wrapper(LogicalDecodingContext *ctx);
69 : : static void begin_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn);
70 : : static void commit_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
71 : : XLogRecPtr commit_lsn);
72 : : static void begin_prepare_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn);
73 : : static void prepare_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
74 : : XLogRecPtr prepare_lsn);
75 : : static void commit_prepared_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
76 : : XLogRecPtr commit_lsn);
77 : : static void rollback_prepared_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
78 : : XLogRecPtr prepare_end_lsn, TimestampTz prepare_time);
79 : : static void change_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
80 : : Relation relation, ReorderBufferChange *change);
81 : : static void truncate_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
82 : : int nrelations, Relation relations[], ReorderBufferChange *change);
83 : : static void message_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
84 : : TransactionId xid, XLogRecPtr message_lsn, bool transactional,
85 : : const char *prefix, Size message_size, const char *message);
86 : :
87 : : /* streaming callbacks */
88 : : static void stream_start_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
89 : : XLogRecPtr first_lsn);
90 : : static void stream_stop_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
91 : : XLogRecPtr last_lsn);
92 : : static void stream_abort_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
93 : : XLogRecPtr abort_lsn);
94 : : static void stream_prepare_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
95 : : XLogRecPtr prepare_lsn);
96 : : static void stream_commit_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
97 : : XLogRecPtr commit_lsn);
98 : : static void stream_change_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
99 : : Relation relation, ReorderBufferChange *change);
100 : : static void stream_message_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
101 : : TransactionId xid, XLogRecPtr message_lsn, bool transactional,
102 : : const char *prefix, Size message_size, const char *message);
103 : : static void stream_truncate_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
104 : : int nrelations, Relation relations[], ReorderBufferChange *change);
105 : :
106 : : /* callback to update txn's progress */
107 : : static void update_progress_txn_cb_wrapper(ReorderBuffer *cache,
108 : : ReorderBufferTXN *txn,
109 : : XLogRecPtr lsn);
110 : :
111 : : static void LoadOutputPlugin(OutputPluginCallbacks *callbacks, const char *plugin);
112 : :
113 : : /* check_hook: validate new output_plugin_libraries value */
114 : : bool
115 : 1419 : check_output_plugin_libraries(char **newval, void **extra, GucSource source)
116 : : {
117 : : char *copy;
118 : : List *components;
119 : 1419 : bool ok = true;
120 : :
121 : 1419 : copy = guc_strdup(LOG, *newval);
122 [ - + ]: 1419 : if (!copy)
123 : 0 : return false;
124 : :
125 : : /*
126 : : * XXX SplitGUCList won't respect guc_malloc requirements, but this is
127 : : * consistent with other check_hook implementations...
128 : : */
129 [ + + ]: 1419 : if (!SplitGUCList(copy, ',', &components))
130 : : {
131 : 4 : GUC_check_errdetail("List syntax is invalid.");
132 : 4 : ok = false;
133 : : }
134 : :
135 : : /*
136 : : * Like with related GUC_LIST_QUOTE variables, we check only syntax here
137 : : * and not the existence of the plugins themselves.
138 : : */
139 : :
140 : 1419 : list_free(components);
141 : 1419 : guc_free(copy);
142 : :
143 : 1419 : return ok;
144 : : }
145 : :
146 : : /*
147 : : * Make sure the current settings & environment are capable of doing logical
148 : : * decoding.
149 : : */
150 : : void
151 : 1951 : CheckLogicalDecodingRequirements(bool repack)
152 : : {
153 : 1951 : CheckSlotRequirements(repack);
154 : :
155 : : /*
156 : : * NB: Adding a new requirement likely means that RestoreSlotFromDisk()
157 : : * needs the same check.
158 : : */
159 : :
160 [ + + ]: 1951 : if (MyDatabaseId == InvalidOid)
161 [ + - ]: 1 : ereport(ERROR,
162 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
163 : : errmsg("logical decoding requires a database connection")));
164 : :
165 : : /* CheckSlotRequirements() has already checked if wal_level >= 'replica' */
166 : : Assert(wal_level >= WAL_LEVEL_REPLICA);
167 : :
168 : : /* Check if logical decoding is available on standby */
169 [ + + + + ]: 1950 : if (RecoveryInProgress() && !IsLogicalDecodingEnabled())
170 [ + - ]: 2 : ereport(ERROR,
171 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
172 : : errmsg("logical decoding on standby requires \"effective_wal_level\" >= \"logical\" on the primary"),
173 : : errhint("Set \"wal_level\" >= \"logical\" or create at least one logical slot when \"wal_level\" = \"replica\".")));
174 : 1948 : }
175 : :
176 : : /*
177 : : * Helper function for CreateInitDecodingContext() and
178 : : * CreateDecodingContext() performing common tasks.
179 : : */
180 : : static LogicalDecodingContext *
181 : 1383 : StartupDecodingContext(List *output_plugin_options,
182 : : XLogRecPtr start_lsn,
183 : : TransactionId xmin_horizon,
184 : : bool need_full_snapshot,
185 : : bool fast_forward,
186 : : bool in_create,
187 : : bool for_repack,
188 : : XLogReaderRoutine *xl_routine,
189 : : LogicalOutputPluginWriterPrepareWrite prepare_write,
190 : : LogicalOutputPluginWriterWrite do_write,
191 : : LogicalOutputPluginWriterUpdateProgress update_progress)
192 : : {
193 : : ReplicationSlot *slot;
194 : : MemoryContext context,
195 : : old_context;
196 : : LogicalDecodingContext *ctx;
197 : :
198 : : /* shorter lines... */
199 : 1383 : slot = MyReplicationSlot;
200 : :
201 : 1383 : context = AllocSetContextCreate(CurrentMemoryContext,
202 : : "Logical decoding context",
203 : : ALLOCSET_DEFAULT_SIZES);
204 : 1383 : old_context = MemoryContextSwitchTo(context);
205 : 1383 : ctx = palloc0_object(LogicalDecodingContext);
206 : :
207 : 1383 : ctx->context = context;
208 : :
209 : : /*
210 : : * (re-)load output plugins, so we detect a bad (removed) output plugin
211 : : * now.
212 : : */
213 [ + + ]: 1383 : if (!fast_forward)
214 : : {
215 : : /*
216 : : * Before loading this library, make sure it's been blessed for
217 : : * logical decoding.
218 : : */
219 : 1356 : const char *plugin = NameStr(slot->data.plugin);
220 : 1356 : bool plugin_allowed = false;
221 : :
222 [ + + ]: 1356 : if (strcmp(plugin, "pgrepack") == 0)
223 : : {
224 : : /*
225 : : * REPACK is a special case -- print a more helpful error message
226 : : * here if we're not being called in the correct context.
227 : : */
228 [ + + - + ]: 15 : if (!for_repack || !AmRepackWorker())
229 [ + - ]: 1 : ereport(ERROR,
230 : : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
231 : : errmsg("unsupported use of logical decoding plugin \"%s\"",
232 : : "pgrepack"),
233 : : errdetail("This plugin can only be used by %s.",
234 : : "REPACK (CONCURRENTLY)"));
235 : :
236 : 14 : plugin_allowed = true;
237 : : }
238 [ + - ]: 1341 : else if (output_plugin_libraries_string &&
239 [ + - ]: 1341 : output_plugin_libraries_string[0])
240 : : {
241 : : /* Check this plugin against output_plugin_libraries. */
242 : : char *rawstring;
243 : 1341 : List *elemlist = NIL;
244 : :
245 : : /* Need a modifiable copy */
246 : 1341 : rawstring = pstrdup(output_plugin_libraries_string);
247 : :
248 : : /* The check_hook should have already handled syntax errors. */
249 [ - + ]: 1341 : if (!SplitGUCList(rawstring, ',', &elemlist))
250 [ # # ]: 0 : elog(ERROR, "internal error: invalid output_plugin_libraries syntax after check_hook");
251 : :
252 [ + - + + : 3087 : foreach_ptr(char, allowed, elemlist)
+ + ]
253 : : {
254 [ + + ]: 1743 : if (strcmp(allowed, plugin) == 0)
255 : : {
256 : 1338 : plugin_allowed = true;
257 : 1338 : break;
258 : : }
259 : : }
260 : :
261 : 1341 : list_free(elemlist);
262 : 1341 : pfree(rawstring);
263 : : }
264 : :
265 [ + + ]: 1355 : if (!plugin_allowed)
266 : : {
267 : : /*
268 : : * Use the same error message as check_restricted_library_name(),
269 : : * but provide additional context for the DBA in the logs. (The
270 : : * HINT will be sent to the client, but that's not a secret.)
271 : : */
272 [ + - ]: 3 : ereport(ERROR,
273 : : errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
274 : : errmsg("library \"%s\" may not be used as an output plugin",
275 : : plugin),
276 : : /*- translator: The second %s is the value of the output_plugin_libraries GUC, which may contain whitespace, commas, and double-quotes (") */
277 : : errdetail_log("The configuration parameter \"%s\" (currently '%s') does not name this library as a trusted output plugin.",
278 : : "output_plugin_libraries",
279 : : output_plugin_libraries_string),
280 : : errhint("If it is safe for all REPLICATION users to use this library as an output plugin, add it to \"%s\" and reload the server configuration.",
281 : : "output_plugin_libraries"));
282 : : }
283 : :
284 : 1352 : LoadOutputPlugin(&ctx->callbacks, plugin);
285 : : }
286 : :
287 : : /*
288 : : * Now that the slot's xmin has been set, we can announce ourselves as a
289 : : * logical decoding backend which doesn't need to be checked individually
290 : : * when computing the xmin horizon because the xmin is enforced via
291 : : * replication slots.
292 : : *
293 : : * We can only do so if we're outside of a transaction (i.e. the case when
294 : : * streaming changes via walsender), otherwise an already setup
295 : : * snapshot/xid would end up being ignored. That's not a particularly
296 : : * bothersome restriction since the SQL interface can't be used for
297 : : * streaming anyway.
298 : : */
299 [ + + ]: 1378 : if (!IsTransactionOrTransactionBlock())
300 : : {
301 : 715 : LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
302 : 715 : MyProc->statusFlags |= PROC_IN_LOGICAL_DECODING;
303 : 715 : ProcGlobal->statusFlags[MyProc->pgxactoff] = MyProc->statusFlags;
304 : 715 : LWLockRelease(ProcArrayLock);
305 : : }
306 : :
307 : 1378 : ctx->slot = slot;
308 : :
309 : 1378 : ctx->reader = XLogReaderAllocate(wal_segment_size, NULL, xl_routine, ctx);
310 [ - + ]: 1378 : if (!ctx->reader)
311 [ # # ]: 0 : ereport(ERROR,
312 : : (errcode(ERRCODE_OUT_OF_MEMORY),
313 : : errmsg("out of memory"),
314 : : errdetail("Failed while allocating a WAL reading processor.")));
315 : :
316 : 1378 : ctx->reorder = ReorderBufferAllocate();
317 : 1378 : ctx->snapshot_builder =
318 : 1378 : AllocateSnapshotBuilder(ctx->reorder, xmin_horizon, start_lsn,
319 : : need_full_snapshot, in_create, slot->data.two_phase_at);
320 : :
321 : 1378 : ctx->reorder->private_data = ctx;
322 : :
323 : : /* wrap output plugin callbacks, so we can add error context information */
324 : 1378 : ctx->reorder->begin = begin_cb_wrapper;
325 : 1378 : ctx->reorder->apply_change = change_cb_wrapper;
326 : 1378 : ctx->reorder->apply_truncate = truncate_cb_wrapper;
327 : 1378 : ctx->reorder->commit = commit_cb_wrapper;
328 : 1378 : ctx->reorder->message = message_cb_wrapper;
329 : :
330 : : /*
331 : : * To support streaming, we require start/stop/abort/commit/change
332 : : * callbacks. The message and truncate callbacks are optional, similar to
333 : : * regular output plugins. We however enable streaming when at least one
334 : : * of the methods is enabled so that we can easily identify missing
335 : : * methods.
336 : : *
337 : : * We decide it here, but only check it later in the wrappers.
338 : : */
339 : 2797 : ctx->streaming = (ctx->callbacks.stream_start_cb != NULL) ||
340 [ + - ]: 41 : (ctx->callbacks.stream_stop_cb != NULL) ||
341 [ + - ]: 41 : (ctx->callbacks.stream_abort_cb != NULL) ||
342 [ + - ]: 41 : (ctx->callbacks.stream_commit_cb != NULL) ||
343 [ + - ]: 41 : (ctx->callbacks.stream_change_cb != NULL) ||
344 [ + + + - ]: 1460 : (ctx->callbacks.stream_message_cb != NULL) ||
345 [ - + ]: 41 : (ctx->callbacks.stream_truncate_cb != NULL);
346 : :
347 : : /*
348 : : * streaming callbacks
349 : : *
350 : : * stream_message and stream_truncate callbacks are optional, so we do not
351 : : * fail with ERROR when missing, but the wrappers simply do nothing. We
352 : : * must set the ReorderBuffer callbacks to something, otherwise the calls
353 : : * from there will crash (we don't want to move the checks there).
354 : : */
355 : 1378 : ctx->reorder->stream_start = stream_start_cb_wrapper;
356 : 1378 : ctx->reorder->stream_stop = stream_stop_cb_wrapper;
357 : 1378 : ctx->reorder->stream_abort = stream_abort_cb_wrapper;
358 : 1378 : ctx->reorder->stream_prepare = stream_prepare_cb_wrapper;
359 : 1378 : ctx->reorder->stream_commit = stream_commit_cb_wrapper;
360 : 1378 : ctx->reorder->stream_change = stream_change_cb_wrapper;
361 : 1378 : ctx->reorder->stream_message = stream_message_cb_wrapper;
362 : 1378 : ctx->reorder->stream_truncate = stream_truncate_cb_wrapper;
363 : :
364 : :
365 : : /*
366 : : * To support two-phase logical decoding, we require
367 : : * begin_prepare/prepare/commit-prepare/abort-prepare callbacks. The
368 : : * filter_prepare callback is optional. We however enable two-phase
369 : : * logical decoding when at least one of the methods is enabled so that we
370 : : * can easily identify missing methods.
371 : : *
372 : : * We decide it here, but only check it later in the wrappers.
373 : : */
374 : 2797 : ctx->twophase = (ctx->callbacks.begin_prepare_cb != NULL) ||
375 [ + - ]: 41 : (ctx->callbacks.prepare_cb != NULL) ||
376 [ + - ]: 41 : (ctx->callbacks.commit_prepared_cb != NULL) ||
377 [ + - ]: 41 : (ctx->callbacks.rollback_prepared_cb != NULL) ||
378 [ + + + - ]: 1460 : (ctx->callbacks.stream_prepare_cb != NULL) ||
379 [ - + ]: 41 : (ctx->callbacks.filter_prepare_cb != NULL);
380 : :
381 : : /*
382 : : * Callback to support decoding at prepare time.
383 : : */
384 : 1378 : ctx->reorder->begin_prepare = begin_prepare_cb_wrapper;
385 : 1378 : ctx->reorder->prepare = prepare_cb_wrapper;
386 : 1378 : ctx->reorder->commit_prepared = commit_prepared_cb_wrapper;
387 : 1378 : ctx->reorder->rollback_prepared = rollback_prepared_cb_wrapper;
388 : :
389 : : /*
390 : : * Callback to support updating progress during sending data of a
391 : : * transaction (and its subtransactions) to the output plugin.
392 : : */
393 : 1378 : ctx->reorder->update_progress_txn = update_progress_txn_cb_wrapper;
394 : :
395 : 1378 : ctx->out = makeStringInfo();
396 : 1378 : ctx->prepare_write = prepare_write;
397 : 1378 : ctx->write = do_write;
398 : 1378 : ctx->update_progress = update_progress;
399 : :
400 : 1378 : ctx->output_plugin_options = output_plugin_options;
401 : :
402 : 1378 : ctx->fast_forward = fast_forward;
403 : :
404 : 1378 : MemoryContextSwitchTo(old_context);
405 : :
406 : 1378 : return ctx;
407 : : }
408 : :
409 : : /*
410 : : * Create a new decoding context, for a new logical slot.
411 : : *
412 : : * plugin -- contains the name of the output plugin
413 : : * output_plugin_options -- contains options passed to the output plugin
414 : : * need_full_snapshot -- if true, must obtain a snapshot able to read all
415 : : * tables; if false, one that can read only catalogs is acceptable.
416 : : * for_repack -- if true, we're going to be decoding for REPACK.
417 : : * restart_lsn -- if given as invalid, it's this routine's responsibility to
418 : : * mark WAL as reserved by setting a convenient restart_lsn for the slot.
419 : : * Otherwise, we set for decoding to start from the given LSN without
420 : : * marking WAL reserved beforehand. In that scenario, it's up to the
421 : : * caller to guarantee that WAL remains available.
422 : : * xl_routine -- XLogReaderRoutine for underlying XLogReader
423 : : * prepare_write, do_write, update_progress --
424 : : * callbacks that perform the use-case dependent, actual, work.
425 : : *
426 : : * Needs to be called while in a memory context that's at least as long lived
427 : : * as the decoding context because further memory contexts will be created
428 : : * inside it.
429 : : *
430 : : * Returns an initialized decoding context after calling the output plugin's
431 : : * startup function.
432 : : */
433 : : LogicalDecodingContext *
434 : 567 : CreateInitDecodingContext(const char *plugin,
435 : : List *output_plugin_options,
436 : : bool need_full_snapshot,
437 : : bool for_repack,
438 : : XLogRecPtr restart_lsn,
439 : : XLogReaderRoutine *xl_routine,
440 : : LogicalOutputPluginWriterPrepareWrite prepare_write,
441 : : LogicalOutputPluginWriterWrite do_write,
442 : : LogicalOutputPluginWriterUpdateProgress update_progress)
443 : : {
444 : 567 : TransactionId xmin_horizon = InvalidTransactionId;
445 : : ReplicationSlot *slot;
446 : : NameData plugin_name;
447 : : LogicalDecodingContext *ctx;
448 : : MemoryContext old_context;
449 : :
450 : : /*
451 : : * On a standby, this check is also required while creating the slot.
452 : : * Check the comments in the function.
453 : : */
454 : 567 : CheckLogicalDecodingRequirements(for_repack);
455 : :
456 : : /* shorter lines... */
457 : 567 : slot = MyReplicationSlot;
458 : :
459 : : /* first some sanity checks that are unlikely to be violated */
460 [ - + ]: 567 : if (slot == NULL)
461 [ # # ]: 0 : elog(ERROR, "cannot perform logical decoding without an acquired slot");
462 : :
463 [ - + ]: 567 : if (plugin == NULL)
464 [ # # ]: 0 : elog(ERROR, "cannot initialize logical decoding without a specified plugin");
465 : :
466 : : /* Make sure the passed slot is suitable. These are user facing errors. */
467 [ - + ]: 567 : if (SlotIsPhysical(slot))
468 [ # # ]: 0 : ereport(ERROR,
469 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
470 : : errmsg("cannot use physical replication slot for logical decoding")));
471 : :
472 [ - + ]: 567 : if (slot->data.database != MyDatabaseId)
473 [ # # ]: 0 : ereport(ERROR,
474 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
475 : : errmsg("replication slot \"%s\" was not created in this database",
476 : : NameStr(slot->data.name))));
477 : :
478 [ + + + + ]: 972 : if (IsTransactionState() &&
479 : 405 : GetTopTransactionIdIfAny() != InvalidTransactionId)
480 [ + - ]: 2 : ereport(ERROR,
481 : : (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
482 : : errmsg("cannot create logical replication slot in transaction that has performed writes")));
483 : :
484 : : /*
485 : : * Register output plugin name with slot. We need the mutex to avoid
486 : : * concurrent reading of a partially copied string. But we don't want any
487 : : * complicated code while holding a spinlock, so do namestrcpy() outside.
488 : : */
489 : 565 : namestrcpy(&plugin_name, plugin);
490 : 565 : SpinLockAcquire(&slot->mutex);
491 : 565 : slot->data.plugin = plugin_name;
492 : 565 : SpinLockRelease(&slot->mutex);
493 : :
494 [ + + ]: 565 : if (!XLogRecPtrIsValid(restart_lsn))
495 : 557 : ReplicationSlotReserveWal();
496 : : else
497 : : {
498 : 8 : SpinLockAcquire(&slot->mutex);
499 : 8 : slot->data.restart_lsn = restart_lsn;
500 : 8 : SpinLockRelease(&slot->mutex);
501 : : }
502 : :
503 : : /* ----
504 : : * This is a bit tricky: We need to determine a safe xmin horizon to start
505 : : * decoding from, to avoid starting from a running xacts record referring
506 : : * to xids whose rows have been vacuumed or pruned
507 : : * already. GetOldestSafeDecodingTransactionId() returns such a value, but
508 : : * without further interlock its return value might immediately be out of
509 : : * date.
510 : : *
511 : : * So we have to acquire both the ReplicationSlotControlLock and the
512 : : * ProcArrayLock to prevent concurrent computation and update of new xmin
513 : : * horizons by other backends, get the safe decoding xid, and inform the
514 : : * slot machinery about the new limit. Once that's done both locks can be
515 : : * released as the slot machinery now is protecting against vacuum.
516 : : *
517 : : * Note that, temporarily, the data, not just the catalog, xmin has to be
518 : : * reserved if a data snapshot is to be exported. Otherwise the initial
519 : : * data snapshot created here is not guaranteed to be valid. After that
520 : : * the data xmin doesn't need to be managed anymore and the global xmin
521 : : * should be recomputed. As we are fine with losing the pegged data xmin
522 : : * after crash - no chance a snapshot would get exported anymore - we can
523 : : * get away with just setting the slot's
524 : : * effective_xmin. ReplicationSlotRelease will reset it again.
525 : : *
526 : : * ----
527 : : */
528 : 565 : LWLockAcquire(ReplicationSlotControlLock, LW_EXCLUSIVE);
529 : 565 : LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
530 : :
531 : 565 : xmin_horizon = GetOldestSafeDecodingTransactionId(!need_full_snapshot);
532 : :
533 : 565 : SpinLockAcquire(&slot->mutex);
534 : 565 : slot->effective_catalog_xmin = xmin_horizon;
535 : 565 : slot->data.catalog_xmin = xmin_horizon;
536 [ + + ]: 565 : if (need_full_snapshot)
537 : 241 : slot->effective_xmin = xmin_horizon;
538 : 565 : SpinLockRelease(&slot->mutex);
539 : :
540 : 565 : ReplicationSlotsComputeRequiredXmin(true);
541 : :
542 : 565 : LWLockRelease(ProcArrayLock);
543 : 565 : LWLockRelease(ReplicationSlotControlLock);
544 : :
545 : 565 : ReplicationSlotMarkDirty();
546 : 565 : ReplicationSlotSave();
547 : :
548 : 565 : ctx = StartupDecodingContext(NIL, restart_lsn, xmin_horizon,
549 : : need_full_snapshot, false, true, for_repack,
550 : : xl_routine, prepare_write, do_write,
551 : : update_progress);
552 : :
553 : : /* call output plugin initialization callback */
554 : 560 : old_context = MemoryContextSwitchTo(ctx->context);
555 [ + - ]: 560 : if (ctx->callbacks.startup_cb != NULL)
556 : 560 : startup_cb_wrapper(ctx, &ctx->options, true);
557 : 560 : MemoryContextSwitchTo(old_context);
558 : :
559 : : /*
560 : : * We allow decoding of prepared transactions when the two_phase is
561 : : * enabled at the time of slot creation, or when the two_phase option is
562 : : * given at the streaming start, provided the plugin supports all the
563 : : * callbacks for two-phase.
564 : : */
565 : 560 : ctx->twophase &= slot->data.two_phase;
566 : :
567 : 560 : ctx->reorder->output_rewrites = ctx->options.receive_rewrites;
568 : :
569 : 560 : return ctx;
570 : : }
571 : :
572 : : /*
573 : : * Create a new decoding context, for a logical slot that has previously been
574 : : * used already.
575 : : *
576 : : * start_lsn
577 : : * The LSN at which to start decoding. If InvalidXLogRecPtr, restart
578 : : * from the slot's confirmed_flush; otherwise, start from the specified
579 : : * location (but move it forwards to confirmed_flush if it's older than
580 : : * that, see below).
581 : : *
582 : : * output_plugin_options
583 : : * options passed to the output plugin.
584 : : *
585 : : * fast_forward
586 : : * bypass the generation of logical changes.
587 : : *
588 : : * xl_routine
589 : : * XLogReaderRoutine used by underlying xlogreader
590 : : *
591 : : * prepare_write, do_write, update_progress
592 : : * callbacks that have to be filled to perform the use-case dependent,
593 : : * actual work.
594 : : *
595 : : * Needs to be called while in a memory context that's at least as long lived
596 : : * as the decoding context because further memory contexts will be created
597 : : * inside it.
598 : : *
599 : : * Returns an initialized decoding context after calling the output plugin's
600 : : * startup function.
601 : : */
602 : : LogicalDecodingContext *
603 : 823 : CreateDecodingContext(XLogRecPtr start_lsn,
604 : : List *output_plugin_options,
605 : : bool fast_forward,
606 : : XLogReaderRoutine *xl_routine,
607 : : LogicalOutputPluginWriterPrepareWrite prepare_write,
608 : : LogicalOutputPluginWriterWrite do_write,
609 : : LogicalOutputPluginWriterUpdateProgress update_progress)
610 : : {
611 : : LogicalDecodingContext *ctx;
612 : : ReplicationSlot *slot;
613 : : MemoryContext old_context;
614 : :
615 : : /* shorter lines... */
616 : 823 : slot = MyReplicationSlot;
617 : :
618 : : /* first some sanity checks that are unlikely to be violated */
619 [ - + ]: 823 : if (slot == NULL)
620 [ # # ]: 0 : elog(ERROR, "cannot perform logical decoding without an acquired slot");
621 : :
622 : : /* make sure the passed slot is suitable, these are user facing errors */
623 [ + + ]: 823 : if (SlotIsPhysical(slot))
624 [ + - ]: 1 : ereport(ERROR,
625 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
626 : : errmsg("cannot use physical replication slot for logical decoding")));
627 : :
628 : : /*
629 : : * We need to access the system tables during decoding to build the
630 : : * logical changes unless we are in fast_forward mode where no changes are
631 : : * generated.
632 : : */
633 [ + + + + ]: 822 : if (slot->data.database != MyDatabaseId && !fast_forward)
634 [ + - ]: 3 : ereport(ERROR,
635 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
636 : : errmsg("replication slot \"%s\" was not created in this database",
637 : : NameStr(slot->data.name))));
638 : :
639 : : /*
640 : : * The slots being synced from the primary can't be used for decoding as
641 : : * they are used after failover. However, we do allow advancing the LSNs
642 : : * during the synchronization of slots. See update_local_synced_slot.
643 : : */
644 [ + + + + : 819 : if (RecoveryInProgress() && slot->data.synced && !IsSyncingReplicationSlots())
+ + ]
645 [ + - ]: 1 : ereport(ERROR,
646 : : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
647 : : errmsg("cannot use replication slot \"%s\" for logical decoding",
648 : : NameStr(slot->data.name)),
649 : : errdetail("This replication slot is being synchronized from the primary server."),
650 : : errhint("Specify another replication slot."));
651 : :
652 : : /* slot must be valid to allow decoding */
653 : : Assert(slot->data.invalidated == RS_INVAL_NONE);
654 : : Assert(XLogRecPtrIsValid(slot->data.restart_lsn));
655 : :
656 [ + + ]: 818 : if (!XLogRecPtrIsValid(start_lsn))
657 : : {
658 : : /* continue from last position */
659 : 431 : start_lsn = slot->data.confirmed_flush;
660 : : }
661 [ + + ]: 387 : else if (start_lsn < slot->data.confirmed_flush)
662 : : {
663 : : /*
664 : : * It might seem like we should error out in this case, but it's
665 : : * pretty common for a client to acknowledge a LSN it doesn't have to
666 : : * do anything for, and thus didn't store persistently, because the
667 : : * xlog records didn't result in anything relevant for logical
668 : : * decoding. Clients have to be able to do that to support synchronous
669 : : * replication.
670 : : *
671 : : * Starting at a different LSN than requested might not catch certain
672 : : * kinds of client errors; so the client may wish to check that
673 : : * confirmed_flush_lsn matches its expectations.
674 : : */
675 [ + - ]: 45 : elog(LOG, "%X/%08X has been already streamed, forwarding to %X/%08X",
676 : : LSN_FORMAT_ARGS(start_lsn),
677 : : LSN_FORMAT_ARGS(slot->data.confirmed_flush));
678 : :
679 : 45 : start_lsn = slot->data.confirmed_flush;
680 : : }
681 : :
682 : 818 : ctx = StartupDecodingContext(output_plugin_options,
683 : : start_lsn, InvalidTransactionId, false,
684 : : fast_forward, false, false,
685 : : xl_routine, prepare_write,
686 : : do_write, update_progress);
687 : :
688 : : /* call output plugin initialization callback */
689 : 818 : old_context = MemoryContextSwitchTo(ctx->context);
690 [ + + ]: 818 : if (ctx->callbacks.startup_cb != NULL)
691 : 791 : startup_cb_wrapper(ctx, &ctx->options, false);
692 : 812 : MemoryContextSwitchTo(old_context);
693 : :
694 : : /*
695 : : * We allow decoding of prepared transactions when the two_phase is
696 : : * enabled at the time of slot creation, or when the two_phase option is
697 : : * given at the streaming start, provided the plugin supports all the
698 : : * callbacks for two-phase.
699 : : */
700 [ + + + + ]: 812 : ctx->twophase &= (slot->data.two_phase || ctx->twophase_opt_given);
701 : :
702 : : /* Mark slot to allow two_phase decoding if not already marked */
703 [ + + + + ]: 812 : if (ctx->twophase && !slot->data.two_phase)
704 : : {
705 : 9 : SpinLockAcquire(&slot->mutex);
706 : 9 : slot->data.two_phase = true;
707 : 9 : slot->data.two_phase_at = start_lsn;
708 : 9 : SpinLockRelease(&slot->mutex);
709 : 9 : ReplicationSlotMarkDirty();
710 : 9 : ReplicationSlotSave();
711 : 9 : SnapBuildSetTwoPhaseAt(ctx->snapshot_builder, start_lsn);
712 : : }
713 : :
714 : 812 : ctx->reorder->output_rewrites = ctx->options.receive_rewrites;
715 : :
716 [ + + + + ]: 812 : ereport(LogicalDecodingLogLevel(),
717 : : (errmsg("starting logical decoding for slot \"%s\"",
718 : : NameStr(slot->data.name)),
719 : : errdetail("Streaming transactions committing after %X/%08X, reading WAL from %X/%08X.",
720 : : LSN_FORMAT_ARGS(slot->data.confirmed_flush),
721 : : LSN_FORMAT_ARGS(slot->data.restart_lsn))));
722 : :
723 : 812 : return ctx;
724 : : }
725 : :
726 : : /*
727 : : * Returns true if a consistent initial decoding snapshot has been built.
728 : : */
729 : : bool
730 : 636 : DecodingContextReady(LogicalDecodingContext *ctx)
731 : : {
732 : 636 : return SnapBuildCurrentState(ctx->snapshot_builder) == SNAPBUILD_CONSISTENT;
733 : : }
734 : :
735 : : /*
736 : : * Read from the decoding slot, until it is ready to start extracting changes.
737 : : */
738 : : void
739 : 552 : DecodingContextFindStartpoint(LogicalDecodingContext *ctx)
740 : : {
741 : 552 : ReplicationSlot *slot = ctx->slot;
742 : :
743 : : /* Initialize from where to start reading WAL. */
744 : 552 : XLogBeginRead(ctx->reader, slot->data.restart_lsn);
745 : :
746 [ + + ]: 552 : elog(DEBUG1, "searching for logical decoding starting point, starting at %X/%08X",
747 : : LSN_FORMAT_ARGS(slot->data.restart_lsn));
748 : :
749 : : /* Wait for a consistent starting point */
750 : : for (;;)
751 : 75 : {
752 : : XLogRecord *record;
753 : 627 : char *err = NULL;
754 : :
755 : : /* the read_page callback waits for new WAL */
756 : 627 : record = XLogReadRecord(ctx->reader, &err);
757 [ - + ]: 627 : if (err)
758 [ # # ]: 0 : elog(ERROR, "could not find logical decoding starting point: %s", err);
759 [ - + ]: 627 : if (!record)
760 [ # # ]: 0 : elog(ERROR, "could not find logical decoding starting point");
761 : :
762 : 627 : LogicalDecodingProcessRecord(ctx, ctx->reader);
763 : :
764 : : /* only continue till we found a consistent spot */
765 [ + + ]: 625 : if (DecodingContextReady(ctx))
766 : 550 : break;
767 : :
768 [ - + ]: 75 : CHECK_FOR_INTERRUPTS();
769 : : }
770 : :
771 : 550 : SpinLockAcquire(&slot->mutex);
772 : 550 : slot->data.confirmed_flush = ctx->reader->EndRecPtr;
773 [ + + ]: 550 : if (slot->data.two_phase)
774 : 9 : slot->data.two_phase_at = ctx->reader->EndRecPtr;
775 : 550 : SpinLockRelease(&slot->mutex);
776 : 550 : }
777 : :
778 : : /*
779 : : * Free a previously allocated decoding context, invoking the shutdown
780 : : * callback if necessary.
781 : : */
782 : : void
783 : 1035 : FreeDecodingContext(LogicalDecodingContext *ctx)
784 : : {
785 [ + + ]: 1035 : if (ctx->callbacks.shutdown_cb != NULL)
786 : 1008 : shutdown_cb_wrapper(ctx);
787 : :
788 : 1035 : ReorderBufferFree(ctx->reorder);
789 : 1035 : FreeSnapshotBuilder(ctx->snapshot_builder);
790 : 1035 : XLogReaderFree(ctx->reader);
791 : 1035 : MemoryContextDelete(ctx->context);
792 : 1035 : }
793 : :
794 : : /*
795 : : * Prepare a write using the context's output routine.
796 : : */
797 : : void
798 : 362015 : OutputPluginPrepareWrite(struct LogicalDecodingContext *ctx, bool last_write)
799 : : {
800 [ - + ]: 362015 : if (!ctx->accept_writes)
801 [ # # ]: 0 : elog(ERROR, "writes are only accepted in commit, begin and change callbacks");
802 : :
803 : 362015 : ctx->prepare_write(ctx, ctx->write_location, ctx->write_xid, last_write);
804 : 362015 : ctx->prepared_write = true;
805 : 362015 : }
806 : :
807 : : /*
808 : : * Perform a write using the context's output routine.
809 : : */
810 : : void
811 : 362013 : OutputPluginWrite(struct LogicalDecodingContext *ctx, bool last_write)
812 : : {
813 [ - + ]: 362013 : if (!ctx->prepared_write)
814 [ # # ]: 0 : elog(ERROR, "OutputPluginPrepareWrite needs to be called before OutputPluginWrite");
815 : :
816 : 362013 : ctx->write(ctx, ctx->write_location, ctx->write_xid, last_write);
817 : 361992 : ctx->prepared_write = false;
818 : 361992 : }
819 : :
820 : : /*
821 : : * Update progress tracking (if supported).
822 : : */
823 : : void
824 : 5860 : OutputPluginUpdateProgress(struct LogicalDecodingContext *ctx,
825 : : bool skipped_xact)
826 : : {
827 [ + + ]: 5860 : if (!ctx->update_progress)
828 : 1600 : return;
829 : :
830 : 4260 : ctx->update_progress(ctx, ctx->write_location, ctx->write_xid,
831 : : skipped_xact);
832 : : }
833 : :
834 : : /*
835 : : * Load the output plugin, lookup its output plugin init function, and check
836 : : * that it provides the required callbacks. The caller must have checked that
837 : : * the current user has the necessary privileges to load the given plugin;
838 : : * standard LOAD restrictions are not applied here.
839 : : */
840 : : static void
841 : 1352 : LoadOutputPlugin(OutputPluginCallbacks *callbacks, const char *plugin)
842 : : {
843 : : LogicalOutputPluginInit plugin_init;
844 : :
845 : 1351 : plugin_init = (LogicalOutputPluginInit)
846 : 1352 : load_external_function(plugin, "_PG_output_plugin_init", false, NULL);
847 : :
848 [ - + ]: 1351 : if (plugin_init == NULL)
849 [ # # ]: 0 : elog(ERROR, "output plugins have to declare the _PG_output_plugin_init symbol");
850 : :
851 : : /* ask the output plugin to fill the callback struct */
852 : 1351 : plugin_init(callbacks);
853 : :
854 [ - + ]: 1351 : if (callbacks->begin_cb == NULL)
855 [ # # ]: 0 : elog(ERROR, "output plugins have to register a begin callback");
856 [ - + ]: 1351 : if (callbacks->change_cb == NULL)
857 [ # # ]: 0 : elog(ERROR, "output plugins have to register a change callback");
858 [ - + ]: 1351 : if (callbacks->commit_cb == NULL)
859 [ # # ]: 0 : elog(ERROR, "output plugins have to register a commit callback");
860 : 1351 : }
861 : :
862 : : static void
863 : 1324 : output_plugin_error_callback(void *arg)
864 : : {
865 : 1324 : LogicalErrorCallbackState *state = (LogicalErrorCallbackState *) arg;
866 : :
867 : : /* not all callbacks have an associated LSN */
868 [ + + ]: 1324 : if (XLogRecPtrIsValid(state->report_location))
869 : 1318 : errcontext("slot \"%s\", output plugin \"%s\", in the %s callback, associated LSN %X/%08X",
870 : 1318 : NameStr(state->ctx->slot->data.name),
871 : 1318 : NameStr(state->ctx->slot->data.plugin),
872 : : state->callback_name,
873 : 1318 : LSN_FORMAT_ARGS(state->report_location));
874 : : else
875 : 6 : errcontext("slot \"%s\", output plugin \"%s\", in the %s callback",
876 : 6 : NameStr(state->ctx->slot->data.name),
877 : 6 : NameStr(state->ctx->slot->data.plugin),
878 : : state->callback_name);
879 : 1324 : }
880 : :
881 : : static void
882 : 1351 : startup_cb_wrapper(LogicalDecodingContext *ctx, OutputPluginOptions *opt, bool is_init)
883 : : {
884 : : LogicalErrorCallbackState state;
885 : : ErrorContextCallback errcallback;
886 : :
887 : : Assert(!ctx->fast_forward);
888 : :
889 : : /* Push callback + info on the error context stack */
890 : 1351 : state.ctx = ctx;
891 : 1351 : state.callback_name = "startup";
892 : 1351 : state.report_location = InvalidXLogRecPtr;
893 : 1351 : errcallback.callback = output_plugin_error_callback;
894 : 1351 : errcallback.arg = &state;
895 : 1351 : errcallback.previous = error_context_stack;
896 : 1351 : error_context_stack = &errcallback;
897 : :
898 : : /* set output state */
899 : 1351 : ctx->accept_writes = false;
900 : 1351 : ctx->end_xact = false;
901 : :
902 : : /* do the actual work: call callback */
903 : 1351 : ctx->callbacks.startup_cb(ctx, opt, is_init);
904 : :
905 : : /* Pop the error context stack */
906 : 1345 : error_context_stack = errcallback.previous;
907 : 1345 : }
908 : :
909 : : static void
910 : 1008 : shutdown_cb_wrapper(LogicalDecodingContext *ctx)
911 : : {
912 : : LogicalErrorCallbackState state;
913 : : ErrorContextCallback errcallback;
914 : :
915 : : Assert(!ctx->fast_forward);
916 : :
917 : : /* Push callback + info on the error context stack */
918 : 1008 : state.ctx = ctx;
919 : 1008 : state.callback_name = "shutdown";
920 : 1008 : state.report_location = InvalidXLogRecPtr;
921 : 1008 : errcallback.callback = output_plugin_error_callback;
922 : 1008 : errcallback.arg = &state;
923 : 1008 : errcallback.previous = error_context_stack;
924 : 1008 : error_context_stack = &errcallback;
925 : :
926 : : /* set output state */
927 : 1008 : ctx->accept_writes = false;
928 : 1008 : ctx->end_xact = false;
929 : :
930 : : /* do the actual work: call callback */
931 : 1008 : ctx->callbacks.shutdown_cb(ctx);
932 : :
933 : : /* Pop the error context stack */
934 : 1008 : error_context_stack = errcallback.previous;
935 : 1008 : }
936 : :
937 : :
938 : : /*
939 : : * Callbacks for ReorderBuffer which add in some more information and then call
940 : : * output_plugin.h plugins.
941 : : */
942 : : static void
943 : 2851 : begin_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn)
944 : : {
945 : 2851 : LogicalDecodingContext *ctx = cache->private_data;
946 : : LogicalErrorCallbackState state;
947 : : ErrorContextCallback errcallback;
948 : :
949 : : Assert(!ctx->fast_forward);
950 : :
951 : : /* Push callback + info on the error context stack */
952 : 2851 : state.ctx = ctx;
953 : 2851 : state.callback_name = "begin";
954 : 2851 : state.report_location = txn->first_lsn;
955 : 2851 : errcallback.callback = output_plugin_error_callback;
956 : 2851 : errcallback.arg = &state;
957 : 2851 : errcallback.previous = error_context_stack;
958 : 2851 : error_context_stack = &errcallback;
959 : :
960 : : /* set output state */
961 : 2851 : ctx->accept_writes = true;
962 : 2851 : ctx->write_xid = txn->xid;
963 : 2851 : ctx->write_location = txn->first_lsn;
964 : 2851 : ctx->end_xact = false;
965 : :
966 : : /* do the actual work: call callback */
967 : 2851 : ctx->callbacks.begin_cb(ctx, txn);
968 : :
969 : : /* Pop the error context stack */
970 : 2851 : error_context_stack = errcallback.previous;
971 : 2851 : }
972 : :
973 : : static void
974 : 2844 : commit_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
975 : : XLogRecPtr commit_lsn)
976 : : {
977 : 2844 : LogicalDecodingContext *ctx = cache->private_data;
978 : : LogicalErrorCallbackState state;
979 : : ErrorContextCallback errcallback;
980 : :
981 : : Assert(!ctx->fast_forward);
982 : :
983 : : /* Push callback + info on the error context stack */
984 : 2844 : state.ctx = ctx;
985 : 2844 : state.callback_name = "commit";
986 : 2844 : state.report_location = txn->final_lsn; /* beginning of commit record */
987 : 2844 : errcallback.callback = output_plugin_error_callback;
988 : 2844 : errcallback.arg = &state;
989 : 2844 : errcallback.previous = error_context_stack;
990 : 2844 : error_context_stack = &errcallback;
991 : :
992 : : /* set output state */
993 : 2844 : ctx->accept_writes = true;
994 : 2844 : ctx->write_xid = txn->xid;
995 : 2844 : ctx->write_location = txn->end_lsn; /* points to the end of the record */
996 : 2844 : ctx->end_xact = true;
997 : :
998 : : /* do the actual work: call callback */
999 : 2844 : ctx->callbacks.commit_cb(ctx, txn, commit_lsn);
1000 : :
1001 : : /* Pop the error context stack */
1002 : 2825 : error_context_stack = errcallback.previous;
1003 : 2825 : }
1004 : :
1005 : : /*
1006 : : * The functionality of begin_prepare is quite similar to begin with the
1007 : : * exception that this will have gid (global transaction id) information which
1008 : : * can be used by plugin. Now, we thought about extending the existing begin
1009 : : * but that would break the replication protocol and additionally this looks
1010 : : * cleaner.
1011 : : */
1012 : : static void
1013 : 31 : begin_prepare_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn)
1014 : : {
1015 : 31 : LogicalDecodingContext *ctx = cache->private_data;
1016 : : LogicalErrorCallbackState state;
1017 : : ErrorContextCallback errcallback;
1018 : :
1019 : : Assert(!ctx->fast_forward);
1020 : :
1021 : : /* We're only supposed to call this when two-phase commits are supported */
1022 : : Assert(ctx->twophase);
1023 : :
1024 : : /* Push callback + info on the error context stack */
1025 : 31 : state.ctx = ctx;
1026 : 31 : state.callback_name = "begin_prepare";
1027 : 31 : state.report_location = txn->first_lsn;
1028 : 31 : errcallback.callback = output_plugin_error_callback;
1029 : 31 : errcallback.arg = &state;
1030 : 31 : errcallback.previous = error_context_stack;
1031 : 31 : error_context_stack = &errcallback;
1032 : :
1033 : : /* set output state */
1034 : 31 : ctx->accept_writes = true;
1035 : 31 : ctx->write_xid = txn->xid;
1036 : 31 : ctx->write_location = txn->first_lsn;
1037 : 31 : ctx->end_xact = false;
1038 : :
1039 : : /*
1040 : : * If the plugin supports two-phase commits then begin prepare callback is
1041 : : * mandatory
1042 : : */
1043 [ - + ]: 31 : if (ctx->callbacks.begin_prepare_cb == NULL)
1044 [ # # ]: 0 : ereport(ERROR,
1045 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1046 : : errmsg("logical replication at prepare time requires a %s callback",
1047 : : "begin_prepare_cb")));
1048 : :
1049 : : /* do the actual work: call callback */
1050 : 31 : ctx->callbacks.begin_prepare_cb(ctx, txn);
1051 : :
1052 : : /* Pop the error context stack */
1053 : 31 : error_context_stack = errcallback.previous;
1054 : 31 : }
1055 : :
1056 : : static void
1057 : 31 : prepare_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
1058 : : XLogRecPtr prepare_lsn)
1059 : : {
1060 : 31 : LogicalDecodingContext *ctx = cache->private_data;
1061 : : LogicalErrorCallbackState state;
1062 : : ErrorContextCallback errcallback;
1063 : :
1064 : : Assert(!ctx->fast_forward);
1065 : :
1066 : : /* We're only supposed to call this when two-phase commits are supported */
1067 : : Assert(ctx->twophase);
1068 : :
1069 : : /* Push callback + info on the error context stack */
1070 : 31 : state.ctx = ctx;
1071 : 31 : state.callback_name = "prepare";
1072 : 31 : state.report_location = txn->final_lsn; /* beginning of prepare record */
1073 : 31 : errcallback.callback = output_plugin_error_callback;
1074 : 31 : errcallback.arg = &state;
1075 : 31 : errcallback.previous = error_context_stack;
1076 : 31 : error_context_stack = &errcallback;
1077 : :
1078 : : /* set output state */
1079 : 31 : ctx->accept_writes = true;
1080 : 31 : ctx->write_xid = txn->xid;
1081 : 31 : ctx->write_location = txn->end_lsn; /* points to the end of the record */
1082 : 31 : ctx->end_xact = true;
1083 : :
1084 : : /*
1085 : : * If the plugin supports two-phase commits then prepare callback is
1086 : : * mandatory
1087 : : */
1088 [ - + ]: 31 : if (ctx->callbacks.prepare_cb == NULL)
1089 [ # # ]: 0 : ereport(ERROR,
1090 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1091 : : errmsg("logical replication at prepare time requires a %s callback",
1092 : : "prepare_cb")));
1093 : :
1094 : : /* do the actual work: call callback */
1095 : 31 : ctx->callbacks.prepare_cb(ctx, txn, prepare_lsn);
1096 : :
1097 : : /* Pop the error context stack */
1098 : 31 : error_context_stack = errcallback.previous;
1099 : 31 : }
1100 : :
1101 : : static void
1102 : 35 : commit_prepared_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
1103 : : XLogRecPtr commit_lsn)
1104 : : {
1105 : 35 : LogicalDecodingContext *ctx = cache->private_data;
1106 : : LogicalErrorCallbackState state;
1107 : : ErrorContextCallback errcallback;
1108 : :
1109 : : Assert(!ctx->fast_forward);
1110 : :
1111 : : /* We're only supposed to call this when two-phase commits are supported */
1112 : : Assert(ctx->twophase);
1113 : :
1114 : : /* Push callback + info on the error context stack */
1115 : 35 : state.ctx = ctx;
1116 : 35 : state.callback_name = "commit_prepared";
1117 : 35 : state.report_location = txn->final_lsn; /* beginning of commit record */
1118 : 35 : errcallback.callback = output_plugin_error_callback;
1119 : 35 : errcallback.arg = &state;
1120 : 35 : errcallback.previous = error_context_stack;
1121 : 35 : error_context_stack = &errcallback;
1122 : :
1123 : : /* set output state */
1124 : 35 : ctx->accept_writes = true;
1125 : 35 : ctx->write_xid = txn->xid;
1126 : 35 : ctx->write_location = txn->end_lsn; /* points to the end of the record */
1127 : 35 : ctx->end_xact = true;
1128 : :
1129 : : /*
1130 : : * If the plugin support two-phase commits then commit prepared callback
1131 : : * is mandatory
1132 : : */
1133 [ - + ]: 35 : if (ctx->callbacks.commit_prepared_cb == NULL)
1134 [ # # ]: 0 : ereport(ERROR,
1135 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1136 : : errmsg("logical replication at prepare time requires a %s callback",
1137 : : "commit_prepared_cb")));
1138 : :
1139 : : /* do the actual work: call callback */
1140 : 35 : ctx->callbacks.commit_prepared_cb(ctx, txn, commit_lsn);
1141 : :
1142 : : /* Pop the error context stack */
1143 : 35 : error_context_stack = errcallback.previous;
1144 : 35 : }
1145 : :
1146 : : static void
1147 : 11 : rollback_prepared_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
1148 : : XLogRecPtr prepare_end_lsn,
1149 : : TimestampTz prepare_time)
1150 : : {
1151 : 11 : LogicalDecodingContext *ctx = cache->private_data;
1152 : : LogicalErrorCallbackState state;
1153 : : ErrorContextCallback errcallback;
1154 : :
1155 : : Assert(!ctx->fast_forward);
1156 : :
1157 : : /* We're only supposed to call this when two-phase commits are supported */
1158 : : Assert(ctx->twophase);
1159 : :
1160 : : /* Push callback + info on the error context stack */
1161 : 11 : state.ctx = ctx;
1162 : 11 : state.callback_name = "rollback_prepared";
1163 : 11 : state.report_location = txn->final_lsn; /* beginning of commit record */
1164 : 11 : errcallback.callback = output_plugin_error_callback;
1165 : 11 : errcallback.arg = &state;
1166 : 11 : errcallback.previous = error_context_stack;
1167 : 11 : error_context_stack = &errcallback;
1168 : :
1169 : : /* set output state */
1170 : 11 : ctx->accept_writes = true;
1171 : 11 : ctx->write_xid = txn->xid;
1172 : 11 : ctx->write_location = txn->end_lsn; /* points to the end of the record */
1173 : 11 : ctx->end_xact = true;
1174 : :
1175 : : /*
1176 : : * If the plugin support two-phase commits then rollback prepared callback
1177 : : * is mandatory
1178 : : */
1179 [ - + ]: 11 : if (ctx->callbacks.rollback_prepared_cb == NULL)
1180 [ # # ]: 0 : ereport(ERROR,
1181 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1182 : : errmsg("logical replication at prepare time requires a %s callback",
1183 : : "rollback_prepared_cb")));
1184 : :
1185 : : /* do the actual work: call callback */
1186 : 11 : ctx->callbacks.rollback_prepared_cb(ctx, txn, prepare_end_lsn,
1187 : : prepare_time);
1188 : :
1189 : : /* Pop the error context stack */
1190 : 11 : error_context_stack = errcallback.previous;
1191 : 11 : }
1192 : :
1193 : : static void
1194 : 179602 : change_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
1195 : : Relation relation, ReorderBufferChange *change)
1196 : : {
1197 : 179602 : LogicalDecodingContext *ctx = cache->private_data;
1198 : : LogicalErrorCallbackState state;
1199 : : ErrorContextCallback errcallback;
1200 : :
1201 : : Assert(!ctx->fast_forward);
1202 : :
1203 : : /* Push callback + info on the error context stack */
1204 : 179602 : state.ctx = ctx;
1205 : 179602 : state.callback_name = "change";
1206 : 179602 : state.report_location = change->lsn;
1207 : 179602 : errcallback.callback = output_plugin_error_callback;
1208 : 179602 : errcallback.arg = &state;
1209 : 179602 : errcallback.previous = error_context_stack;
1210 : 179602 : error_context_stack = &errcallback;
1211 : :
1212 : : /* set output state */
1213 : 179602 : ctx->accept_writes = true;
1214 : 179602 : ctx->write_xid = txn->xid;
1215 : :
1216 : : /*
1217 : : * Report this change's lsn so replies from clients can give an up-to-date
1218 : : * answer. This won't ever be enough (and shouldn't be!) to confirm
1219 : : * receipt of this transaction, but it might allow another transaction's
1220 : : * commit to be confirmed with one message.
1221 : : */
1222 : 179602 : ctx->write_location = change->lsn;
1223 : :
1224 : 179602 : ctx->end_xact = false;
1225 : :
1226 : 179602 : ctx->callbacks.change_cb(ctx, txn, relation, change);
1227 : :
1228 : : /* Pop the error context stack */
1229 : 179595 : error_context_stack = errcallback.previous;
1230 : 179595 : }
1231 : :
1232 : : static void
1233 : 26 : truncate_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
1234 : : int nrelations, Relation relations[], ReorderBufferChange *change)
1235 : : {
1236 : 26 : LogicalDecodingContext *ctx = cache->private_data;
1237 : : LogicalErrorCallbackState state;
1238 : : ErrorContextCallback errcallback;
1239 : :
1240 : : Assert(!ctx->fast_forward);
1241 : :
1242 [ - + ]: 26 : if (!ctx->callbacks.truncate_cb)
1243 : 0 : return;
1244 : :
1245 : : /* Push callback + info on the error context stack */
1246 : 26 : state.ctx = ctx;
1247 : 26 : state.callback_name = "truncate";
1248 : 26 : state.report_location = change->lsn;
1249 : 26 : errcallback.callback = output_plugin_error_callback;
1250 : 26 : errcallback.arg = &state;
1251 : 26 : errcallback.previous = error_context_stack;
1252 : 26 : error_context_stack = &errcallback;
1253 : :
1254 : : /* set output state */
1255 : 26 : ctx->accept_writes = true;
1256 : 26 : ctx->write_xid = txn->xid;
1257 : :
1258 : : /*
1259 : : * Report this change's lsn so replies from clients can give an up-to-date
1260 : : * answer. This won't ever be enough (and shouldn't be!) to confirm
1261 : : * receipt of this transaction, but it might allow another transaction's
1262 : : * commit to be confirmed with one message.
1263 : : */
1264 : 26 : ctx->write_location = change->lsn;
1265 : :
1266 : 26 : ctx->end_xact = false;
1267 : :
1268 : 26 : ctx->callbacks.truncate_cb(ctx, txn, nrelations, relations, change);
1269 : :
1270 : : /* Pop the error context stack */
1271 : 26 : error_context_stack = errcallback.previous;
1272 : : }
1273 : :
1274 : : bool
1275 : 170 : filter_prepare_cb_wrapper(LogicalDecodingContext *ctx, TransactionId xid,
1276 : : const char *gid)
1277 : : {
1278 : : LogicalErrorCallbackState state;
1279 : : ErrorContextCallback errcallback;
1280 : : bool ret;
1281 : :
1282 : : Assert(!ctx->fast_forward);
1283 : :
1284 : : /* Push callback + info on the error context stack */
1285 : 170 : state.ctx = ctx;
1286 : 170 : state.callback_name = "filter_prepare";
1287 : 170 : state.report_location = InvalidXLogRecPtr;
1288 : 170 : errcallback.callback = output_plugin_error_callback;
1289 : 170 : errcallback.arg = &state;
1290 : 170 : errcallback.previous = error_context_stack;
1291 : 170 : error_context_stack = &errcallback;
1292 : :
1293 : : /* set output state */
1294 : 170 : ctx->accept_writes = false;
1295 : 170 : ctx->end_xact = false;
1296 : :
1297 : : /* do the actual work: call callback */
1298 : 170 : ret = ctx->callbacks.filter_prepare_cb(ctx, xid, gid);
1299 : :
1300 : : /* Pop the error context stack */
1301 : 170 : error_context_stack = errcallback.previous;
1302 : :
1303 : 170 : return ret;
1304 : : }
1305 : :
1306 : : bool
1307 : 1622125 : filter_by_origin_cb_wrapper(LogicalDecodingContext *ctx, ReplOriginId origin_id)
1308 : : {
1309 : : LogicalErrorCallbackState state;
1310 : : ErrorContextCallback errcallback;
1311 : : bool ret;
1312 : :
1313 : : Assert(!ctx->fast_forward);
1314 : :
1315 : : /* Push callback + info on the error context stack */
1316 : 1622125 : state.ctx = ctx;
1317 : 1622125 : state.callback_name = "filter_by_origin";
1318 : 1622125 : state.report_location = InvalidXLogRecPtr;
1319 : 1622125 : errcallback.callback = output_plugin_error_callback;
1320 : 1622125 : errcallback.arg = &state;
1321 : 1622125 : errcallback.previous = error_context_stack;
1322 : 1622125 : error_context_stack = &errcallback;
1323 : :
1324 : : /* set output state */
1325 : 1622125 : ctx->accept_writes = false;
1326 : 1622125 : ctx->end_xact = false;
1327 : :
1328 : : /* do the actual work: call callback */
1329 : 1622125 : ret = ctx->callbacks.filter_by_origin_cb(ctx, origin_id);
1330 : :
1331 : : /* Pop the error context stack */
1332 : 1622125 : error_context_stack = errcallback.previous;
1333 : :
1334 : 1622125 : return ret;
1335 : : }
1336 : :
1337 : : bool
1338 : 336 : filter_by_rlocator_cb_wrapper(LogicalDecodingContext *ctx,
1339 : : RelFileLocator rlocator)
1340 : : {
1341 : : LogicalErrorCallbackState state;
1342 : : ErrorContextCallback errcallback;
1343 : : bool ret;
1344 : :
1345 : : Assert(!ctx->fast_forward);
1346 : :
1347 : : /* Push callback + info on the error context stack */
1348 : 336 : state.ctx = ctx;
1349 : 336 : state.callback_name = "filter_by_rlocator";
1350 : 336 : state.report_location = InvalidXLogRecPtr;
1351 : 336 : errcallback.callback = output_plugin_error_callback;
1352 : 336 : errcallback.arg = &state;
1353 : 336 : errcallback.previous = error_context_stack;
1354 : 336 : error_context_stack = &errcallback;
1355 : :
1356 : : /* set output state */
1357 : 336 : ctx->accept_writes = false;
1358 : 336 : ctx->end_xact = false;
1359 : :
1360 : : /* do the actual work: call callback */
1361 : 336 : ret = ctx->callbacks.filter_by_rlocator_cb(ctx, rlocator);
1362 : :
1363 : : /* Pop the error context stack */
1364 : 336 : error_context_stack = errcallback.previous;
1365 : :
1366 : 336 : return ret;
1367 : : }
1368 : :
1369 : : static void
1370 : 18 : message_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
1371 : : TransactionId xid, XLogRecPtr message_lsn, bool transactional,
1372 : : const char *prefix, Size message_size, const char *message)
1373 : : {
1374 : 18 : LogicalDecodingContext *ctx = cache->private_data;
1375 : : LogicalErrorCallbackState state;
1376 : : ErrorContextCallback errcallback;
1377 : :
1378 : : Assert(!ctx->fast_forward);
1379 : :
1380 [ - + ]: 18 : if (ctx->callbacks.message_cb == NULL)
1381 : 0 : return;
1382 : :
1383 : : /* Push callback + info on the error context stack */
1384 : 18 : state.ctx = ctx;
1385 : 18 : state.callback_name = "message";
1386 : 18 : state.report_location = message_lsn;
1387 : 18 : errcallback.callback = output_plugin_error_callback;
1388 : 18 : errcallback.arg = &state;
1389 : 18 : errcallback.previous = error_context_stack;
1390 : 18 : error_context_stack = &errcallback;
1391 : :
1392 : : /* set output state */
1393 : 18 : ctx->accept_writes = true;
1394 [ + + ]: 18 : ctx->write_xid = txn != NULL ? txn->xid : InvalidTransactionId;
1395 : 18 : ctx->write_location = message_lsn;
1396 : 18 : ctx->end_xact = false;
1397 : :
1398 : : /* do the actual work: call callback */
1399 : 18 : ctx->callbacks.message_cb(ctx, txn, xid, message_lsn, transactional, prefix,
1400 : : message_size, message);
1401 : :
1402 : : /* Pop the error context stack */
1403 : 18 : error_context_stack = errcallback.previous;
1404 : : }
1405 : :
1406 : : static void
1407 : 689 : stream_start_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
1408 : : XLogRecPtr first_lsn)
1409 : : {
1410 : 689 : LogicalDecodingContext *ctx = cache->private_data;
1411 : : LogicalErrorCallbackState state;
1412 : : ErrorContextCallback errcallback;
1413 : :
1414 : : Assert(!ctx->fast_forward);
1415 : :
1416 : : /* We're only supposed to call this when streaming is supported. */
1417 : : Assert(ctx->streaming);
1418 : :
1419 : : /* Push callback + info on the error context stack */
1420 : 689 : state.ctx = ctx;
1421 : 689 : state.callback_name = "stream_start";
1422 : 689 : state.report_location = first_lsn;
1423 : 689 : errcallback.callback = output_plugin_error_callback;
1424 : 689 : errcallback.arg = &state;
1425 : 689 : errcallback.previous = error_context_stack;
1426 : 689 : error_context_stack = &errcallback;
1427 : :
1428 : : /* set output state */
1429 : 689 : ctx->accept_writes = true;
1430 : 689 : ctx->write_xid = txn->xid;
1431 : :
1432 : : /*
1433 : : * Report this message's lsn so replies from clients can give an
1434 : : * up-to-date answer. This won't ever be enough (and shouldn't be!) to
1435 : : * confirm receipt of this transaction, but it might allow another
1436 : : * transaction's commit to be confirmed with one message.
1437 : : */
1438 : 689 : ctx->write_location = first_lsn;
1439 : :
1440 : 689 : ctx->end_xact = false;
1441 : :
1442 : : /* in streaming mode, stream_start_cb is required */
1443 [ - + ]: 689 : if (ctx->callbacks.stream_start_cb == NULL)
1444 [ # # ]: 0 : ereport(ERROR,
1445 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1446 : : errmsg("logical streaming requires a %s callback",
1447 : : "stream_start_cb")));
1448 : :
1449 : 689 : ctx->callbacks.stream_start_cb(ctx, txn);
1450 : :
1451 : : /* Pop the error context stack */
1452 : 689 : error_context_stack = errcallback.previous;
1453 : 689 : }
1454 : :
1455 : : static void
1456 : 689 : stream_stop_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
1457 : : XLogRecPtr last_lsn)
1458 : : {
1459 : 689 : LogicalDecodingContext *ctx = cache->private_data;
1460 : : LogicalErrorCallbackState state;
1461 : : ErrorContextCallback errcallback;
1462 : :
1463 : : Assert(!ctx->fast_forward);
1464 : :
1465 : : /* We're only supposed to call this when streaming is supported. */
1466 : : Assert(ctx->streaming);
1467 : :
1468 : : /* Push callback + info on the error context stack */
1469 : 689 : state.ctx = ctx;
1470 : 689 : state.callback_name = "stream_stop";
1471 : 689 : state.report_location = last_lsn;
1472 : 689 : errcallback.callback = output_plugin_error_callback;
1473 : 689 : errcallback.arg = &state;
1474 : 689 : errcallback.previous = error_context_stack;
1475 : 689 : error_context_stack = &errcallback;
1476 : :
1477 : : /* set output state */
1478 : 689 : ctx->accept_writes = true;
1479 : 689 : ctx->write_xid = txn->xid;
1480 : :
1481 : : /*
1482 : : * Report this message's lsn so replies from clients can give an
1483 : : * up-to-date answer. This won't ever be enough (and shouldn't be!) to
1484 : : * confirm receipt of this transaction, but it might allow another
1485 : : * transaction's commit to be confirmed with one message.
1486 : : */
1487 : 689 : ctx->write_location = last_lsn;
1488 : :
1489 : 689 : ctx->end_xact = false;
1490 : :
1491 : : /* in streaming mode, stream_stop_cb is required */
1492 [ - + ]: 689 : if (ctx->callbacks.stream_stop_cb == NULL)
1493 [ # # ]: 0 : ereport(ERROR,
1494 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1495 : : errmsg("logical streaming requires a %s callback",
1496 : : "stream_stop_cb")));
1497 : :
1498 : 689 : ctx->callbacks.stream_stop_cb(ctx, txn);
1499 : :
1500 : : /* Pop the error context stack */
1501 : 689 : error_context_stack = errcallback.previous;
1502 : 689 : }
1503 : :
1504 : : static void
1505 : 31 : stream_abort_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
1506 : : XLogRecPtr abort_lsn)
1507 : : {
1508 : 31 : LogicalDecodingContext *ctx = cache->private_data;
1509 : : LogicalErrorCallbackState state;
1510 : : ErrorContextCallback errcallback;
1511 : :
1512 : : Assert(!ctx->fast_forward);
1513 : :
1514 : : /* We're only supposed to call this when streaming is supported. */
1515 : : Assert(ctx->streaming);
1516 : :
1517 : : /* Push callback + info on the error context stack */
1518 : 31 : state.ctx = ctx;
1519 : 31 : state.callback_name = "stream_abort";
1520 : 31 : state.report_location = abort_lsn;
1521 : 31 : errcallback.callback = output_plugin_error_callback;
1522 : 31 : errcallback.arg = &state;
1523 : 31 : errcallback.previous = error_context_stack;
1524 : 31 : error_context_stack = &errcallback;
1525 : :
1526 : : /* set output state */
1527 : 31 : ctx->accept_writes = true;
1528 : 31 : ctx->write_xid = txn->xid;
1529 : 31 : ctx->write_location = abort_lsn;
1530 : 31 : ctx->end_xact = true;
1531 : :
1532 : : /* in streaming mode, stream_abort_cb is required */
1533 [ - + ]: 31 : if (ctx->callbacks.stream_abort_cb == NULL)
1534 [ # # ]: 0 : ereport(ERROR,
1535 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1536 : : errmsg("logical streaming requires a %s callback",
1537 : : "stream_abort_cb")));
1538 : :
1539 : 31 : ctx->callbacks.stream_abort_cb(ctx, txn, abort_lsn);
1540 : :
1541 : : /* Pop the error context stack */
1542 : 31 : error_context_stack = errcallback.previous;
1543 : 31 : }
1544 : :
1545 : : static void
1546 : 17 : stream_prepare_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
1547 : : XLogRecPtr prepare_lsn)
1548 : : {
1549 : 17 : LogicalDecodingContext *ctx = cache->private_data;
1550 : : LogicalErrorCallbackState state;
1551 : : ErrorContextCallback errcallback;
1552 : :
1553 : : Assert(!ctx->fast_forward);
1554 : :
1555 : : /*
1556 : : * We're only supposed to call this when streaming and two-phase commits
1557 : : * are supported.
1558 : : */
1559 : : Assert(ctx->streaming);
1560 : : Assert(ctx->twophase);
1561 : :
1562 : : /* Push callback + info on the error context stack */
1563 : 17 : state.ctx = ctx;
1564 : 17 : state.callback_name = "stream_prepare";
1565 : 17 : state.report_location = txn->final_lsn;
1566 : 17 : errcallback.callback = output_plugin_error_callback;
1567 : 17 : errcallback.arg = &state;
1568 : 17 : errcallback.previous = error_context_stack;
1569 : 17 : error_context_stack = &errcallback;
1570 : :
1571 : : /* set output state */
1572 : 17 : ctx->accept_writes = true;
1573 : 17 : ctx->write_xid = txn->xid;
1574 : 17 : ctx->write_location = txn->end_lsn;
1575 : 17 : ctx->end_xact = true;
1576 : :
1577 : : /* in streaming mode with two-phase commits, stream_prepare_cb is required */
1578 [ - + ]: 17 : if (ctx->callbacks.stream_prepare_cb == NULL)
1579 [ # # ]: 0 : ereport(ERROR,
1580 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1581 : : errmsg("logical streaming at prepare time requires a %s callback",
1582 : : "stream_prepare_cb")));
1583 : :
1584 : 17 : ctx->callbacks.stream_prepare_cb(ctx, txn, prepare_lsn);
1585 : :
1586 : : /* Pop the error context stack */
1587 : 17 : error_context_stack = errcallback.previous;
1588 : 17 : }
1589 : :
1590 : : static void
1591 : 52 : stream_commit_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
1592 : : XLogRecPtr commit_lsn)
1593 : : {
1594 : 52 : LogicalDecodingContext *ctx = cache->private_data;
1595 : : LogicalErrorCallbackState state;
1596 : : ErrorContextCallback errcallback;
1597 : :
1598 : : Assert(!ctx->fast_forward);
1599 : :
1600 : : /* We're only supposed to call this when streaming is supported. */
1601 : : Assert(ctx->streaming);
1602 : :
1603 : : /* Push callback + info on the error context stack */
1604 : 52 : state.ctx = ctx;
1605 : 52 : state.callback_name = "stream_commit";
1606 : 52 : state.report_location = txn->final_lsn;
1607 : 52 : errcallback.callback = output_plugin_error_callback;
1608 : 52 : errcallback.arg = &state;
1609 : 52 : errcallback.previous = error_context_stack;
1610 : 52 : error_context_stack = &errcallback;
1611 : :
1612 : : /* set output state */
1613 : 52 : ctx->accept_writes = true;
1614 : 52 : ctx->write_xid = txn->xid;
1615 : 52 : ctx->write_location = txn->end_lsn;
1616 : 52 : ctx->end_xact = true;
1617 : :
1618 : : /* in streaming mode, stream_commit_cb is required */
1619 [ - + ]: 52 : if (ctx->callbacks.stream_commit_cb == NULL)
1620 [ # # ]: 0 : ereport(ERROR,
1621 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1622 : : errmsg("logical streaming requires a %s callback",
1623 : : "stream_commit_cb")));
1624 : :
1625 : 52 : ctx->callbacks.stream_commit_cb(ctx, txn, commit_lsn);
1626 : :
1627 : : /* Pop the error context stack */
1628 : 52 : error_context_stack = errcallback.previous;
1629 : 52 : }
1630 : :
1631 : : static void
1632 : 180636 : stream_change_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
1633 : : Relation relation, ReorderBufferChange *change)
1634 : : {
1635 : 180636 : LogicalDecodingContext *ctx = cache->private_data;
1636 : : LogicalErrorCallbackState state;
1637 : : ErrorContextCallback errcallback;
1638 : :
1639 : : Assert(!ctx->fast_forward);
1640 : :
1641 : : /* We're only supposed to call this when streaming is supported. */
1642 : : Assert(ctx->streaming);
1643 : :
1644 : : /* Push callback + info on the error context stack */
1645 : 180636 : state.ctx = ctx;
1646 : 180636 : state.callback_name = "stream_change";
1647 : 180636 : state.report_location = change->lsn;
1648 : 180636 : errcallback.callback = output_plugin_error_callback;
1649 : 180636 : errcallback.arg = &state;
1650 : 180636 : errcallback.previous = error_context_stack;
1651 : 180636 : error_context_stack = &errcallback;
1652 : :
1653 : : /* set output state */
1654 : 180636 : ctx->accept_writes = true;
1655 : 180636 : ctx->write_xid = txn->xid;
1656 : :
1657 : : /*
1658 : : * Report this change's lsn so replies from clients can give an up-to-date
1659 : : * answer. This won't ever be enough (and shouldn't be!) to confirm
1660 : : * receipt of this transaction, but it might allow another transaction's
1661 : : * commit to be confirmed with one message.
1662 : : */
1663 : 180636 : ctx->write_location = change->lsn;
1664 : :
1665 : 180636 : ctx->end_xact = false;
1666 : :
1667 : : /* in streaming mode, stream_change_cb is required */
1668 [ - + ]: 180636 : if (ctx->callbacks.stream_change_cb == NULL)
1669 [ # # ]: 0 : ereport(ERROR,
1670 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1671 : : errmsg("logical streaming requires a %s callback",
1672 : : "stream_change_cb")));
1673 : :
1674 : 180636 : ctx->callbacks.stream_change_cb(ctx, txn, relation, change);
1675 : :
1676 : : /* Pop the error context stack */
1677 : 180636 : error_context_stack = errcallback.previous;
1678 : 180636 : }
1679 : :
1680 : : static void
1681 : 4 : stream_message_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
1682 : : TransactionId xid, XLogRecPtr message_lsn, bool transactional,
1683 : : const char *prefix, Size message_size, const char *message)
1684 : : {
1685 : 4 : LogicalDecodingContext *ctx = cache->private_data;
1686 : : LogicalErrorCallbackState state;
1687 : : ErrorContextCallback errcallback;
1688 : :
1689 : : Assert(!ctx->fast_forward);
1690 : :
1691 : : /* We're only supposed to call this when streaming is supported. */
1692 : : Assert(ctx->streaming);
1693 : :
1694 : : /* this callback is optional */
1695 [ - + ]: 4 : if (ctx->callbacks.stream_message_cb == NULL)
1696 : 0 : return;
1697 : :
1698 : : /* Push callback + info on the error context stack */
1699 : 4 : state.ctx = ctx;
1700 : 4 : state.callback_name = "stream_message";
1701 : 4 : state.report_location = message_lsn;
1702 : 4 : errcallback.callback = output_plugin_error_callback;
1703 : 4 : errcallback.arg = &state;
1704 : 4 : errcallback.previous = error_context_stack;
1705 : 4 : error_context_stack = &errcallback;
1706 : :
1707 : : /* set output state */
1708 : 4 : ctx->accept_writes = true;
1709 [ + - ]: 4 : ctx->write_xid = txn != NULL ? txn->xid : InvalidTransactionId;
1710 : 4 : ctx->write_location = message_lsn;
1711 : 4 : ctx->end_xact = false;
1712 : :
1713 : : /* do the actual work: call callback */
1714 : 4 : ctx->callbacks.stream_message_cb(ctx, txn, xid, message_lsn, transactional, prefix,
1715 : : message_size, message);
1716 : :
1717 : : /* Pop the error context stack */
1718 : 4 : error_context_stack = errcallback.previous;
1719 : : }
1720 : :
1721 : : static void
1722 : 0 : stream_truncate_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
1723 : : int nrelations, Relation relations[],
1724 : : ReorderBufferChange *change)
1725 : : {
1726 : 0 : LogicalDecodingContext *ctx = cache->private_data;
1727 : : LogicalErrorCallbackState state;
1728 : : ErrorContextCallback errcallback;
1729 : :
1730 : : Assert(!ctx->fast_forward);
1731 : :
1732 : : /* We're only supposed to call this when streaming is supported. */
1733 : : Assert(ctx->streaming);
1734 : :
1735 : : /* this callback is optional */
1736 [ # # ]: 0 : if (!ctx->callbacks.stream_truncate_cb)
1737 : 0 : return;
1738 : :
1739 : : /* Push callback + info on the error context stack */
1740 : 0 : state.ctx = ctx;
1741 : 0 : state.callback_name = "stream_truncate";
1742 : 0 : state.report_location = change->lsn;
1743 : 0 : errcallback.callback = output_plugin_error_callback;
1744 : 0 : errcallback.arg = &state;
1745 : 0 : errcallback.previous = error_context_stack;
1746 : 0 : error_context_stack = &errcallback;
1747 : :
1748 : : /* set output state */
1749 : 0 : ctx->accept_writes = true;
1750 : 0 : ctx->write_xid = txn->xid;
1751 : :
1752 : : /*
1753 : : * Report this change's lsn so replies from clients can give an up-to-date
1754 : : * answer. This won't ever be enough (and shouldn't be!) to confirm
1755 : : * receipt of this transaction, but it might allow another transaction's
1756 : : * commit to be confirmed with one message.
1757 : : */
1758 : 0 : ctx->write_location = change->lsn;
1759 : :
1760 : 0 : ctx->end_xact = false;
1761 : :
1762 : 0 : ctx->callbacks.stream_truncate_cb(ctx, txn, nrelations, relations, change);
1763 : :
1764 : : /* Pop the error context stack */
1765 : 0 : error_context_stack = errcallback.previous;
1766 : : }
1767 : :
1768 : : static void
1769 : 3387 : update_progress_txn_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
1770 : : XLogRecPtr lsn)
1771 : : {
1772 : 3387 : LogicalDecodingContext *ctx = cache->private_data;
1773 : : LogicalErrorCallbackState state;
1774 : : ErrorContextCallback errcallback;
1775 : :
1776 : : Assert(!ctx->fast_forward);
1777 : :
1778 : : /* Push callback + info on the error context stack */
1779 : 3387 : state.ctx = ctx;
1780 : 3387 : state.callback_name = "update_progress_txn";
1781 : 3387 : state.report_location = lsn;
1782 : 3387 : errcallback.callback = output_plugin_error_callback;
1783 : 3387 : errcallback.arg = &state;
1784 : 3387 : errcallback.previous = error_context_stack;
1785 : 3387 : error_context_stack = &errcallback;
1786 : :
1787 : : /* set output state */
1788 : 3387 : ctx->accept_writes = false;
1789 : 3387 : ctx->write_xid = txn->xid;
1790 : :
1791 : : /*
1792 : : * Report this change's lsn so replies from clients can give an up-to-date
1793 : : * answer. This won't ever be enough (and shouldn't be!) to confirm
1794 : : * receipt of this transaction, but it might allow another transaction's
1795 : : * commit to be confirmed with one message.
1796 : : */
1797 : 3387 : ctx->write_location = lsn;
1798 : :
1799 : 3387 : ctx->end_xact = false;
1800 : :
1801 : 3387 : OutputPluginUpdateProgress(ctx, false);
1802 : :
1803 : : /* Pop the error context stack */
1804 : 3387 : error_context_stack = errcallback.previous;
1805 : 3387 : }
1806 : :
1807 : : /*
1808 : : * Set the required catalog xmin horizon for historic snapshots in the current
1809 : : * replication slot.
1810 : : *
1811 : : * Note that in the most cases, we won't be able to immediately use the xmin
1812 : : * to increase the xmin horizon: we need to wait till the client has confirmed
1813 : : * receiving current_lsn with LogicalConfirmReceivedLocation().
1814 : : */
1815 : : void
1816 : 695 : LogicalIncreaseXminForSlot(XLogRecPtr current_lsn, TransactionId xmin)
1817 : : {
1818 : 695 : bool updated_xmin = false;
1819 : : ReplicationSlot *slot;
1820 : 695 : bool got_new_xmin = false;
1821 : :
1822 : 695 : slot = MyReplicationSlot;
1823 : :
1824 : : Assert(slot != NULL);
1825 : :
1826 : 695 : SpinLockAcquire(&slot->mutex);
1827 : :
1828 : : /*
1829 : : * don't overwrite if we already have a newer xmin. This can happen if we
1830 : : * restart decoding in a slot.
1831 : : */
1832 [ + + ]: 695 : if (TransactionIdPrecedesOrEquals(xmin, slot->data.catalog_xmin))
1833 : : {
1834 : : }
1835 : :
1836 : : /*
1837 : : * If the client has already confirmed up to this lsn, we directly can
1838 : : * mark this as accepted. This can happen if we restart decoding in a
1839 : : * slot.
1840 : : */
1841 [ + + ]: 316 : else if (current_lsn <= slot->data.confirmed_flush)
1842 : : {
1843 : 78 : slot->candidate_catalog_xmin = xmin;
1844 : 78 : slot->candidate_xmin_lsn = current_lsn;
1845 : :
1846 : : /* our candidate can directly be used */
1847 : 78 : updated_xmin = true;
1848 : : }
1849 : :
1850 : : /*
1851 : : * Only increase if the previous values have been applied, otherwise we
1852 : : * might never end up updating if the receiver acks too slowly.
1853 : : */
1854 [ + + ]: 238 : else if (!XLogRecPtrIsValid(slot->candidate_xmin_lsn))
1855 : : {
1856 : 31 : slot->candidate_catalog_xmin = xmin;
1857 : 31 : slot->candidate_xmin_lsn = current_lsn;
1858 : :
1859 : : /*
1860 : : * Log new xmin at an appropriate log level after releasing the
1861 : : * spinlock.
1862 : : */
1863 : 31 : got_new_xmin = true;
1864 : : }
1865 : 695 : SpinLockRelease(&slot->mutex);
1866 : :
1867 [ + + ]: 695 : if (got_new_xmin)
1868 [ + + ]: 31 : elog(DEBUG1, "got new catalog xmin %u at %X/%08X", xmin,
1869 : : LSN_FORMAT_ARGS(current_lsn));
1870 : :
1871 : : /* candidate already valid with the current flush position, apply */
1872 [ + + ]: 695 : if (updated_xmin)
1873 : 78 : LogicalConfirmReceivedLocation(slot->data.confirmed_flush);
1874 : 695 : }
1875 : :
1876 : : /*
1877 : : * Mark the minimal LSN (restart_lsn) we need to read to replay all
1878 : : * transactions that have not yet committed at current_lsn.
1879 : : *
1880 : : * Just like LogicalIncreaseXminForSlot this only takes effect when the
1881 : : * client has confirmed to have received current_lsn.
1882 : : */
1883 : : void
1884 : 627 : LogicalIncreaseRestartDecodingForSlot(XLogRecPtr current_lsn, XLogRecPtr restart_lsn)
1885 : : {
1886 : 627 : bool updated_lsn = false;
1887 : : ReplicationSlot *slot;
1888 : :
1889 : 627 : slot = MyReplicationSlot;
1890 : :
1891 : : Assert(slot != NULL);
1892 : : Assert(XLogRecPtrIsValid(restart_lsn));
1893 : : Assert(XLogRecPtrIsValid(current_lsn));
1894 : :
1895 : 627 : SpinLockAcquire(&slot->mutex);
1896 : :
1897 : : /* don't overwrite if have a newer restart lsn */
1898 [ + + ]: 627 : if (restart_lsn <= slot->data.restart_lsn)
1899 : : {
1900 : 11 : SpinLockRelease(&slot->mutex);
1901 : : }
1902 : :
1903 : : /*
1904 : : * We might have already flushed far enough to directly accept this lsn,
1905 : : * in this case there is no need to check for existing candidate LSNs
1906 : : */
1907 [ + + ]: 616 : else if (current_lsn <= slot->data.confirmed_flush)
1908 : : {
1909 : 350 : slot->candidate_restart_valid = current_lsn;
1910 : 350 : slot->candidate_restart_lsn = restart_lsn;
1911 : 350 : SpinLockRelease(&slot->mutex);
1912 : :
1913 : : /* our candidate can directly be used */
1914 : 350 : updated_lsn = true;
1915 : : }
1916 : :
1917 : : /*
1918 : : * Only increase if the previous values have been applied, otherwise we
1919 : : * might never end up updating if the receiver acks too slowly. A missed
1920 : : * value here will just cause some extra effort after reconnecting.
1921 : : */
1922 [ + + ]: 266 : else if (!XLogRecPtrIsValid(slot->candidate_restart_valid))
1923 : : {
1924 : 50 : slot->candidate_restart_valid = current_lsn;
1925 : 50 : slot->candidate_restart_lsn = restart_lsn;
1926 : 50 : SpinLockRelease(&slot->mutex);
1927 : :
1928 [ + + ]: 50 : elog(DEBUG1, "got new restart lsn %X/%08X at %X/%08X",
1929 : : LSN_FORMAT_ARGS(restart_lsn),
1930 : : LSN_FORMAT_ARGS(current_lsn));
1931 : : }
1932 : : else
1933 : : {
1934 : : XLogRecPtr candidate_restart_lsn;
1935 : : XLogRecPtr candidate_restart_valid;
1936 : : XLogRecPtr confirmed_flush;
1937 : :
1938 : 216 : candidate_restart_lsn = slot->candidate_restart_lsn;
1939 : 216 : candidate_restart_valid = slot->candidate_restart_valid;
1940 : 216 : confirmed_flush = slot->data.confirmed_flush;
1941 : 216 : SpinLockRelease(&slot->mutex);
1942 : :
1943 [ + + ]: 216 : elog(DEBUG1, "failed to increase restart lsn: proposed %X/%08X, after %X/%08X, current candidate %X/%08X, current after %X/%08X, flushed up to %X/%08X",
1944 : : LSN_FORMAT_ARGS(restart_lsn),
1945 : : LSN_FORMAT_ARGS(current_lsn),
1946 : : LSN_FORMAT_ARGS(candidate_restart_lsn),
1947 : : LSN_FORMAT_ARGS(candidate_restart_valid),
1948 : : LSN_FORMAT_ARGS(confirmed_flush));
1949 : : }
1950 : :
1951 : : /* candidates are already valid with the current flush position, apply */
1952 [ + + ]: 627 : if (updated_lsn)
1953 : 350 : LogicalConfirmReceivedLocation(slot->data.confirmed_flush);
1954 : 627 : }
1955 : :
1956 : : /*
1957 : : * Handle a consumer's confirmation having received all changes up to lsn.
1958 : : */
1959 : : void
1960 : 17746 : LogicalConfirmReceivedLocation(XLogRecPtr lsn)
1961 : : {
1962 : : Assert(XLogRecPtrIsValid(lsn));
1963 : :
1964 : : /* Do an unlocked check for candidate_lsn first. */
1965 [ + + ]: 17746 : if (XLogRecPtrIsValid(MyReplicationSlot->candidate_xmin_lsn) ||
1966 [ + + ]: 17570 : XLogRecPtrIsValid(MyReplicationSlot->candidate_restart_valid))
1967 : 548 : {
1968 : 548 : bool updated_xmin = false;
1969 : 548 : bool updated_restart = false;
1970 : : XLogRecPtr restart_lsn pg_attribute_unused();
1971 : :
1972 : 548 : SpinLockAcquire(&MyReplicationSlot->mutex);
1973 : :
1974 : : /* remember the old restart lsn */
1975 : 548 : restart_lsn = MyReplicationSlot->data.restart_lsn;
1976 : :
1977 : : /*
1978 : : * Prevent moving the confirmed_flush backwards, as this could lead to
1979 : : * data duplication issues caused by replicating already replicated
1980 : : * changes.
1981 : : *
1982 : : * This can happen when a client acknowledges an LSN it doesn't have
1983 : : * to do anything for, and thus didn't store persistently. After a
1984 : : * restart, the client can send the prior LSN that it stored
1985 : : * persistently as an acknowledgement, but we need to ignore such an
1986 : : * LSN. See similar case handling in CreateDecodingContext.
1987 : : */
1988 [ + + ]: 548 : if (lsn > MyReplicationSlot->data.confirmed_flush)
1989 : 42 : MyReplicationSlot->data.confirmed_flush = lsn;
1990 : :
1991 : : /* if we're past the location required for bumping xmin, do so */
1992 [ + + ]: 548 : if (XLogRecPtrIsValid(MyReplicationSlot->candidate_xmin_lsn) &&
1993 [ + + ]: 176 : MyReplicationSlot->candidate_xmin_lsn <= lsn)
1994 : : {
1995 : : /*
1996 : : * We have to write the changed xmin to disk *before* we change
1997 : : * the in-memory value, otherwise after a crash we wouldn't know
1998 : : * that some catalog tuples might have been removed already.
1999 : : *
2000 : : * Ensure that by first writing to ->xmin and only update
2001 : : * ->effective_xmin once the new state is synced to disk. After a
2002 : : * crash ->effective_xmin is set to ->xmin.
2003 : : */
2004 [ + - ]: 99 : if (TransactionIdIsValid(MyReplicationSlot->candidate_catalog_xmin) &&
2005 [ + - ]: 99 : MyReplicationSlot->data.catalog_xmin != MyReplicationSlot->candidate_catalog_xmin)
2006 : : {
2007 : 99 : MyReplicationSlot->data.catalog_xmin = MyReplicationSlot->candidate_catalog_xmin;
2008 : 99 : MyReplicationSlot->candidate_catalog_xmin = InvalidTransactionId;
2009 : 99 : MyReplicationSlot->candidate_xmin_lsn = InvalidXLogRecPtr;
2010 : 99 : updated_xmin = true;
2011 : : }
2012 : : }
2013 : :
2014 [ + + ]: 548 : if (XLogRecPtrIsValid(MyReplicationSlot->candidate_restart_valid) &&
2015 [ + + ]: 470 : MyReplicationSlot->candidate_restart_valid <= lsn)
2016 : : {
2017 : : Assert(XLogRecPtrIsValid(MyReplicationSlot->candidate_restart_lsn));
2018 : :
2019 : 391 : MyReplicationSlot->data.restart_lsn = MyReplicationSlot->candidate_restart_lsn;
2020 : 391 : MyReplicationSlot->candidate_restart_lsn = InvalidXLogRecPtr;
2021 : 391 : MyReplicationSlot->candidate_restart_valid = InvalidXLogRecPtr;
2022 : 391 : updated_restart = true;
2023 : : }
2024 : :
2025 : 548 : SpinLockRelease(&MyReplicationSlot->mutex);
2026 : :
2027 : : /* first write new xmin to disk, so we know what's up after a crash */
2028 [ + + + + ]: 548 : if (updated_xmin || updated_restart)
2029 : : {
2030 : : #ifdef USE_INJECTION_POINTS
2031 : : XLogSegNo seg1,
2032 : : seg2;
2033 : :
2034 : 469 : XLByteToSeg(restart_lsn, seg1, wal_segment_size);
2035 : 469 : XLByteToSeg(MyReplicationSlot->data.restart_lsn, seg2, wal_segment_size);
2036 : :
2037 : : /* trigger injection point, but only if segment changes */
2038 [ + + ]: 469 : if (seg1 != seg2)
2039 : 17 : INJECTION_POINT("logical-replication-slot-advance-segment", NULL);
2040 : : #endif
2041 : :
2042 : 469 : ReplicationSlotMarkDirty();
2043 : 469 : ReplicationSlotSave();
2044 [ + + ]: 469 : elog(DEBUG1, "updated xmin: %u restart: %u", updated_xmin, updated_restart);
2045 : : }
2046 : :
2047 : : /*
2048 : : * Now the new xmin is safely on disk, we can let the global value
2049 : : * advance. We do not take ProcArrayLock or similar since we only
2050 : : * advance xmin here and there's not much harm done by a concurrent
2051 : : * computation missing that.
2052 : : */
2053 [ + + ]: 548 : if (updated_xmin)
2054 : : {
2055 : 99 : SpinLockAcquire(&MyReplicationSlot->mutex);
2056 : 99 : MyReplicationSlot->effective_catalog_xmin = MyReplicationSlot->data.catalog_xmin;
2057 : 99 : SpinLockRelease(&MyReplicationSlot->mutex);
2058 : :
2059 : 99 : ReplicationSlotsComputeRequiredXmin(false);
2060 : : }
2061 : :
2062 : : /*
2063 : : * Now that the new restart_lsn is safely on disk, recompute the
2064 : : * global WAL retention requirement.
2065 : : */
2066 [ + + ]: 548 : if (updated_restart)
2067 : 391 : ReplicationSlotsComputeRequiredLSN();
2068 : : }
2069 : : else
2070 : : {
2071 : 17198 : SpinLockAcquire(&MyReplicationSlot->mutex);
2072 : :
2073 : : /*
2074 : : * Prevent moving the confirmed_flush backwards. See comments above
2075 : : * for the details.
2076 : : */
2077 [ + + ]: 17198 : if (lsn > MyReplicationSlot->data.confirmed_flush)
2078 : 16311 : MyReplicationSlot->data.confirmed_flush = lsn;
2079 : :
2080 : 17198 : SpinLockRelease(&MyReplicationSlot->mutex);
2081 : : }
2082 : 17746 : }
2083 : :
2084 : : /*
2085 : : * Clear logical streaming state during (sub)transaction abort.
2086 : : */
2087 : : void
2088 : 43479 : ResetLogicalStreamingState(void)
2089 : : {
2090 : 43479 : CheckXidAlive = InvalidTransactionId;
2091 : 43479 : bsysscan = false;
2092 : 43479 : }
2093 : :
2094 : : /*
2095 : : * Report stats for a slot.
2096 : : */
2097 : : void
2098 : 8351 : UpdateDecodingStats(LogicalDecodingContext *ctx)
2099 : : {
2100 : 8351 : ReorderBuffer *rb = ctx->reorder;
2101 : : PgStat_StatReplSlotEntry repSlotStat;
2102 : :
2103 : : /* Nothing to do if we don't have any replication stats to be sent. */
2104 [ + + + + : 8351 : if (rb->spillBytes <= 0 && rb->streamBytes <= 0 && rb->totalBytes <= 0 &&
+ + ]
2105 [ + + ]: 647 : rb->memExceededCount <= 0)
2106 : 635 : return;
2107 : :
2108 [ + + ]: 7716 : elog(DEBUG2, "UpdateDecodingStats: updating stats %p %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64 " %" PRId64,
2109 : : rb,
2110 : : rb->spillTxns,
2111 : : rb->spillCount,
2112 : : rb->spillBytes,
2113 : : rb->streamTxns,
2114 : : rb->streamCount,
2115 : : rb->streamBytes,
2116 : : rb->memExceededCount,
2117 : : rb->totalTxns,
2118 : : rb->totalBytes);
2119 : :
2120 : 7716 : repSlotStat.spill_txns = rb->spillTxns;
2121 : 7716 : repSlotStat.spill_count = rb->spillCount;
2122 : 7716 : repSlotStat.spill_bytes = rb->spillBytes;
2123 : 7716 : repSlotStat.stream_txns = rb->streamTxns;
2124 : 7716 : repSlotStat.stream_count = rb->streamCount;
2125 : 7716 : repSlotStat.stream_bytes = rb->streamBytes;
2126 : 7716 : repSlotStat.mem_exceeded_count = rb->memExceededCount;
2127 : 7716 : repSlotStat.total_txns = rb->totalTxns;
2128 : 7716 : repSlotStat.total_bytes = rb->totalBytes;
2129 : :
2130 : 7716 : pgstat_report_replslot(ctx->slot, &repSlotStat);
2131 : :
2132 : 7716 : rb->spillTxns = 0;
2133 : 7716 : rb->spillCount = 0;
2134 : 7716 : rb->spillBytes = 0;
2135 : 7716 : rb->streamTxns = 0;
2136 : 7716 : rb->streamCount = 0;
2137 : 7716 : rb->streamBytes = 0;
2138 : 7716 : rb->memExceededCount = 0;
2139 : 7716 : rb->totalTxns = 0;
2140 : 7716 : rb->totalBytes = 0;
2141 : : }
2142 : :
2143 : : /*
2144 : : * Read up to the end of WAL starting from the decoding slot's restart_lsn
2145 : : * to end_of_wal in order to check if any meaningful/decodable WAL records
2146 : : * are encountered. scan_cutoff_lsn is the LSN, where we can terminate the
2147 : : * WAL scan early if we find a decodable WAL record after this LSN.
2148 : : *
2149 : : * Returns the last LSN decodable WAL record's LSN if found, otherwise
2150 : : * returns InvalidXLogRecPtr.
2151 : : */
2152 : : XLogRecPtr
2153 : 4 : LogicalReplicationSlotCheckPendingWal(XLogRecPtr end_of_wal,
2154 : : XLogRecPtr scan_cutoff_lsn)
2155 : : {
2156 : 4 : XLogRecPtr last_pending_wal = InvalidXLogRecPtr;
2157 : :
2158 : : Assert(MyReplicationSlot);
2159 : : Assert(end_of_wal >= scan_cutoff_lsn);
2160 : :
2161 [ + - ]: 4 : PG_TRY();
2162 : : {
2163 : : LogicalDecodingContext *ctx;
2164 : :
2165 : : /*
2166 : : * Create our decoding context in fast_forward mode, passing start_lsn
2167 : : * as InvalidXLogRecPtr, so that we start processing from the slot's
2168 : : * confirmed_flush.
2169 : : */
2170 : 8 : ctx = CreateDecodingContext(InvalidXLogRecPtr,
2171 : : NIL,
2172 : : true, /* fast_forward */
2173 : 4 : XL_ROUTINE(.page_read = read_local_xlog_page,
2174 : : .segment_open = wal_segment_open,
2175 : : .segment_close = wal_segment_close),
2176 : : NULL, NULL, NULL);
2177 : :
2178 : : /*
2179 : : * Start reading at the slot's restart_lsn, which we know points to a
2180 : : * valid record.
2181 : : */
2182 : 4 : XLogBeginRead(ctx->reader, MyReplicationSlot->data.restart_lsn);
2183 : :
2184 : : /* Invalidate non-timetravel entries */
2185 : 4 : InvalidateSystemCaches();
2186 : :
2187 [ + + ]: 88 : while (ctx->reader->EndRecPtr < end_of_wal)
2188 : : {
2189 : : XLogRecord *record;
2190 : 84 : char *errm = NULL;
2191 : :
2192 : 84 : record = XLogReadRecord(ctx->reader, &errm);
2193 : :
2194 [ - + ]: 84 : if (errm)
2195 [ # # ]: 0 : elog(ERROR, "could not find record for logical decoding: %s", errm);
2196 : :
2197 [ + - ]: 84 : if (record != NULL)
2198 : 84 : LogicalDecodingProcessRecord(ctx, ctx->reader);
2199 : :
2200 [ + + ]: 84 : if (ctx->processing_required)
2201 : : {
2202 : 2 : last_pending_wal = ctx->reader->ReadRecPtr;
2203 : :
2204 : : /*
2205 : : * If we find a decodable WAL after the scan_cutoff_lsn point,
2206 : : * we can terminate the scan early.
2207 : : */
2208 [ - + ]: 2 : if (last_pending_wal >= scan_cutoff_lsn)
2209 : 0 : break;
2210 : :
2211 : : /* Reset the flag and continue checking */
2212 : 2 : ctx->processing_required = false;
2213 : : }
2214 : :
2215 [ - + ]: 84 : CHECK_FOR_INTERRUPTS();
2216 : : }
2217 : :
2218 : : /* Clean up */
2219 : 4 : FreeDecodingContext(ctx);
2220 : 4 : InvalidateSystemCaches();
2221 : : }
2222 : 0 : PG_CATCH();
2223 : : {
2224 : : /* clear all timetravel entries */
2225 : 0 : InvalidateSystemCaches();
2226 : :
2227 : 0 : PG_RE_THROW();
2228 : : }
2229 [ - + ]: 4 : PG_END_TRY();
2230 : :
2231 : 4 : return last_pending_wal;
2232 : : }
2233 : :
2234 : : /*
2235 : : * Helper function for advancing our logical replication slot forward.
2236 : : *
2237 : : * The slot's restart_lsn is used as start point for reading records, while
2238 : : * confirmed_flush is used as base point for the decoding context.
2239 : : *
2240 : : * We cannot just do LogicalConfirmReceivedLocation to update confirmed_flush,
2241 : : * because we need to digest WAL to advance restart_lsn allowing to recycle
2242 : : * WAL and removal of old catalog tuples. As decoding is done in fast_forward
2243 : : * mode, no changes are generated anyway.
2244 : : *
2245 : : * *found_consistent_snapshot will be true if the initial decoding snapshot has
2246 : : * been built; Otherwise, it will be false.
2247 : : */
2248 : : XLogRecPtr
2249 : 23 : LogicalSlotAdvanceAndCheckSnapState(XLogRecPtr moveto,
2250 : : bool *found_consistent_snapshot)
2251 : : {
2252 : : LogicalDecodingContext *ctx;
2253 : : XLogRecPtr retlsn;
2254 : :
2255 : : Assert(XLogRecPtrIsValid(moveto));
2256 : :
2257 [ + + ]: 23 : if (found_consistent_snapshot)
2258 : 11 : *found_consistent_snapshot = false;
2259 : :
2260 [ + - ]: 23 : PG_TRY();
2261 : : {
2262 : : /*
2263 : : * Create our decoding context in fast_forward mode, passing start_lsn
2264 : : * as InvalidXLogRecPtr, so that we start processing from my slot's
2265 : : * confirmed_flush.
2266 : : */
2267 : 46 : ctx = CreateDecodingContext(InvalidXLogRecPtr,
2268 : : NIL,
2269 : : true, /* fast_forward */
2270 : 23 : XL_ROUTINE(.page_read = read_local_xlog_page,
2271 : : .segment_open = wal_segment_open,
2272 : : .segment_close = wal_segment_close),
2273 : : NULL, NULL, NULL);
2274 : :
2275 : : /*
2276 : : * Wait for specified streaming replication standby servers (if any)
2277 : : * to confirm receipt of WAL up to moveto lsn.
2278 : : */
2279 : 23 : WaitForStandbyConfirmation(moveto);
2280 : :
2281 : : /*
2282 : : * Start reading at the slot's restart_lsn, which we know to point to
2283 : : * a valid record.
2284 : : */
2285 : 23 : XLogBeginRead(ctx->reader, MyReplicationSlot->data.restart_lsn);
2286 : :
2287 : : /* invalidate non-timetravel entries */
2288 : 23 : InvalidateSystemCaches();
2289 : :
2290 : : /* Decode records until we reach the requested target */
2291 [ + + ]: 3075 : while (ctx->reader->EndRecPtr < moveto)
2292 : : {
2293 : 3052 : char *errm = NULL;
2294 : : XLogRecord *record;
2295 : :
2296 : : /*
2297 : : * Read records. No changes are generated in fast_forward mode,
2298 : : * but snapbuilder/slot statuses are updated properly.
2299 : : */
2300 : 3052 : record = XLogReadRecord(ctx->reader, &errm);
2301 [ - + ]: 3052 : if (errm)
2302 [ # # ]: 0 : elog(ERROR, "could not find record while advancing replication slot: %s",
2303 : : errm);
2304 : :
2305 : : /*
2306 : : * Process the record. Storage-level changes are ignored in
2307 : : * fast_forward mode, but other modules (such as snapbuilder)
2308 : : * might still have critical updates to do.
2309 : : */
2310 [ + - ]: 3052 : if (record)
2311 : 3052 : LogicalDecodingProcessRecord(ctx, ctx->reader);
2312 : :
2313 [ - + ]: 3052 : CHECK_FOR_INTERRUPTS();
2314 : : }
2315 : :
2316 [ + + + - ]: 23 : if (found_consistent_snapshot && DecodingContextReady(ctx))
2317 : 11 : *found_consistent_snapshot = true;
2318 : :
2319 [ + - ]: 23 : if (XLogRecPtrIsValid(ctx->reader->EndRecPtr))
2320 : : {
2321 : 23 : LogicalConfirmReceivedLocation(moveto);
2322 : :
2323 : : /*
2324 : : * If only the confirmed_flush LSN has changed the slot won't get
2325 : : * marked as dirty by the above. Callers on the walsender
2326 : : * interface are expected to keep track of their own progress and
2327 : : * don't need it written out. But SQL-interface users cannot
2328 : : * specify their own start positions and it's harder for them to
2329 : : * keep track of their progress, so we should make more of an
2330 : : * effort to save it for them.
2331 : : *
2332 : : * Dirty the slot so it is written out at the next checkpoint. The
2333 : : * LSN position advanced to may still be lost on a crash but this
2334 : : * makes the data consistent after a clean shutdown.
2335 : : */
2336 : 23 : ReplicationSlotMarkDirty();
2337 : : }
2338 : :
2339 : 23 : retlsn = MyReplicationSlot->data.confirmed_flush;
2340 : :
2341 : : /* free context, call shutdown callback */
2342 : 23 : FreeDecodingContext(ctx);
2343 : :
2344 : 23 : InvalidateSystemCaches();
2345 : : }
2346 : 0 : PG_CATCH();
2347 : : {
2348 : : /* clear all timetravel entries */
2349 : 0 : InvalidateSystemCaches();
2350 : :
2351 : 0 : PG_RE_THROW();
2352 : : }
2353 [ - + ]: 23 : PG_END_TRY();
2354 : :
2355 : 23 : return retlsn;
2356 : : }
|