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