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