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