PostgreSQL Source Code  git master
logical.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  * logical.c
3  * PostgreSQL logical decoding coordination
4  *
5  * Copyright (c) 2012-2020, 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 "fmgr.h"
34 #include "miscadmin.h"
35 #include "replication/decode.h"
36 #include "replication/logical.h"
37 #include "replication/origin.h"
39 #include "replication/snapbuild.h"
40 #include "storage/proc.h"
41 #include "storage/procarray.h"
42 #include "utils/memutils.h"
43 
44 /* data for errcontext callback */
46 {
48  const char *callback_name;
51 
52 /* wrappers around output plugin callbacks */
53 static void output_plugin_error_callback(void *arg);
55  bool is_init);
57 static void begin_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn);
58 static void commit_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
59  XLogRecPtr commit_lsn);
60 static void change_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
61  Relation relation, ReorderBufferChange *change);
62 static void truncate_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
63  int nrelations, Relation relations[], ReorderBufferChange *change);
64 static void message_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn,
65  XLogRecPtr message_lsn, bool transactional,
66  const char *prefix, Size message_size, const char *message);
67 
68 static void LoadOutputPlugin(OutputPluginCallbacks *callbacks, char *plugin);
69 
70 /*
71  * Make sure the current settings & environment are capable of doing logical
72  * decoding.
73  */
74 void
76 {
78 
79  /*
80  * NB: Adding a new requirement likely means that RestoreSlotFromDisk()
81  * needs the same check.
82  */
83 
85  ereport(ERROR,
86  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
87  errmsg("logical decoding requires wal_level >= logical")));
88 
89  if (MyDatabaseId == InvalidOid)
90  ereport(ERROR,
91  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
92  errmsg("logical decoding requires a database connection")));
93 
94  /* ----
95  * TODO: We got to change that someday soon...
96  *
97  * There's basically three things missing to allow this:
98  * 1) We need to be able to correctly and quickly identify the timeline a
99  * LSN belongs to
100  * 2) We need to force hot_standby_feedback to be enabled at all times so
101  * the primary cannot remove rows we need.
102  * 3) support dropping replication slots referring to a database, in
103  * dbase_redo. There can't be any active ones due to HS recovery
104  * conflicts, so that should be relatively easy.
105  * ----
106  */
107  if (RecoveryInProgress())
108  ereport(ERROR,
109  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
110  errmsg("logical decoding cannot be used while in recovery")));
111 }
112 
113 /*
114  * Helper function for CreateInitDecodingContext() and
115  * CreateDecodingContext() performing common tasks.
116  */
117 static LogicalDecodingContext *
118 StartupDecodingContext(List *output_plugin_options,
119  XLogRecPtr start_lsn,
120  TransactionId xmin_horizon,
121  bool need_full_snapshot,
122  bool fast_forward,
123  XLogPageReadCB read_page,
127 {
128  ReplicationSlot *slot;
129  MemoryContext context,
130  old_context;
132 
133  /* shorter lines... */
134  slot = MyReplicationSlot;
135 
137  "Logical decoding context",
139  old_context = MemoryContextSwitchTo(context);
140  ctx = palloc0(sizeof(LogicalDecodingContext));
141 
142  ctx->context = context;
143 
144  /*
145  * (re-)load output plugins, so we detect a bad (removed) output plugin
146  * now.
147  */
148  if (!fast_forward)
150 
151  /*
152  * Now that the slot's xmin has been set, we can announce ourselves as a
153  * logical decoding backend which doesn't need to be checked individually
154  * when computing the xmin horizon because the xmin is enforced via
155  * replication slots.
156  *
157  * We can only do so if we're outside of a transaction (i.e. the case when
158  * streaming changes via walsender), otherwise an already setup
159  * snapshot/xid would end up being ignored. That's not a particularly
160  * bothersome restriction since the SQL interface can't be used for
161  * streaming anyway.
162  */
164  {
165  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
167  LWLockRelease(ProcArrayLock);
168  }
169 
170  ctx->slot = slot;
171 
172  ctx->reader = XLogReaderAllocate(wal_segment_size, NULL, read_page, ctx);
173  if (!ctx->reader)
174  ereport(ERROR,
175  (errcode(ERRCODE_OUT_OF_MEMORY),
176  errmsg("out of memory")));
177 
179  ctx->snapshot_builder =
180  AllocateSnapshotBuilder(ctx->reorder, xmin_horizon, start_lsn,
181  need_full_snapshot);
182 
183  ctx->reorder->private_data = ctx;
184 
185  /* wrap output plugin callbacks, so we can add error context information */
191 
192  ctx->out = makeStringInfo();
193  ctx->prepare_write = prepare_write;
194  ctx->write = do_write;
195  ctx->update_progress = update_progress;
196 
197  ctx->output_plugin_options = output_plugin_options;
198 
199  ctx->fast_forward = fast_forward;
200 
201  MemoryContextSwitchTo(old_context);
202 
203  return ctx;
204 }
205 
206 /*
207  * Create a new decoding context, for a new logical slot.
208  *
209  * plugin -- contains the name of the output plugin
210  * output_plugin_options -- contains options passed to the output plugin
211  * need_full_snapshot -- if true, must obtain a snapshot able to read all
212  * tables; if false, one that can read only catalogs is acceptable.
213  * restart_lsn -- if given as invalid, it's this routine's responsibility to
214  * mark WAL as reserved by setting a convenient restart_lsn for the slot.
215  * Otherwise, we set for decoding to start from the given LSN without
216  * marking WAL reserved beforehand. In that scenario, it's up to the
217  * caller to guarantee that WAL remains available.
218  * read_page, prepare_write, do_write, update_progress --
219  * callbacks that perform the use-case dependent, actual, work.
220  *
221  * Needs to be called while in a memory context that's at least as long lived
222  * as the decoding context because further memory contexts will be created
223  * inside it.
224  *
225  * Returns an initialized decoding context after calling the output plugin's
226  * startup function.
227  */
230  List *output_plugin_options,
231  bool need_full_snapshot,
232  XLogRecPtr restart_lsn,
233  XLogPageReadCB read_page,
237 {
238  TransactionId xmin_horizon = InvalidTransactionId;
239  ReplicationSlot *slot;
241  MemoryContext old_context;
242 
243  /* shorter lines... */
244  slot = MyReplicationSlot;
245 
246  /* first some sanity checks that are unlikely to be violated */
247  if (slot == NULL)
248  elog(ERROR, "cannot perform logical decoding without an acquired slot");
249 
250  if (plugin == NULL)
251  elog(ERROR, "cannot initialize logical decoding without a specified plugin");
252 
253  /* Make sure the passed slot is suitable. These are user facing errors. */
254  if (SlotIsPhysical(slot))
255  ereport(ERROR,
256  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
257  errmsg("cannot use physical replication slot for logical decoding")));
258 
259  if (slot->data.database != MyDatabaseId)
260  ereport(ERROR,
261  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
262  errmsg("replication slot \"%s\" was not created in this database",
263  NameStr(slot->data.name))));
264 
265  if (IsTransactionState() &&
267  ereport(ERROR,
268  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
269  errmsg("cannot create logical replication slot in transaction that has performed writes")));
270 
271  /* register output plugin name with slot */
272  SpinLockAcquire(&slot->mutex);
273  StrNCpy(NameStr(slot->data.plugin), plugin, NAMEDATALEN);
274  SpinLockRelease(&slot->mutex);
275 
276  if (XLogRecPtrIsInvalid(restart_lsn))
278  else
279  {
280  SpinLockAcquire(&slot->mutex);
281  slot->data.restart_lsn = restart_lsn;
282  SpinLockRelease(&slot->mutex);
283  }
284 
285  /* ----
286  * This is a bit tricky: We need to determine a safe xmin horizon to start
287  * decoding from, to avoid starting from a running xacts record referring
288  * to xids whose rows have been vacuumed or pruned
289  * already. GetOldestSafeDecodingTransactionId() returns such a value, but
290  * without further interlock its return value might immediately be out of
291  * date.
292  *
293  * So we have to acquire the ProcArrayLock to prevent computation of new
294  * xmin horizons by other backends, get the safe decoding xid, and inform
295  * the slot machinery about the new limit. Once that's done the
296  * ProcArrayLock can be released as the slot machinery now is
297  * protecting against vacuum.
298  *
299  * Note that, temporarily, the data, not just the catalog, xmin has to be
300  * reserved if a data snapshot is to be exported. Otherwise the initial
301  * data snapshot created here is not guaranteed to be valid. After that
302  * the data xmin doesn't need to be managed anymore and the global xmin
303  * should be recomputed. As we are fine with losing the pegged data xmin
304  * after crash - no chance a snapshot would get exported anymore - we can
305  * get away with just setting the slot's
306  * effective_xmin. ReplicationSlotRelease will reset it again.
307  *
308  * ----
309  */
310  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
311 
312  xmin_horizon = GetOldestSafeDecodingTransactionId(!need_full_snapshot);
313 
314  SpinLockAcquire(&slot->mutex);
315  slot->effective_catalog_xmin = xmin_horizon;
316  slot->data.catalog_xmin = xmin_horizon;
317  if (need_full_snapshot)
318  slot->effective_xmin = xmin_horizon;
319  SpinLockRelease(&slot->mutex);
320 
322 
323  LWLockRelease(ProcArrayLock);
324 
327 
328  ctx = StartupDecodingContext(NIL, restart_lsn, xmin_horizon,
329  need_full_snapshot, false,
330  read_page, prepare_write, do_write,
331  update_progress);
332 
333  /* call output plugin initialization callback */
334  old_context = MemoryContextSwitchTo(ctx->context);
335  if (ctx->callbacks.startup_cb != NULL)
336  startup_cb_wrapper(ctx, &ctx->options, true);
337  MemoryContextSwitchTo(old_context);
338 
340 
341  return ctx;
342 }
343 
344 /*
345  * Create a new decoding context, for a logical slot that has previously been
346  * used already.
347  *
348  * start_lsn
349  * The LSN at which to start decoding. If InvalidXLogRecPtr, restart
350  * from the slot's confirmed_flush; otherwise, start from the specified
351  * location (but move it forwards to confirmed_flush if it's older than
352  * that, see below).
353  *
354  * output_plugin_options
355  * options passed to the output plugin.
356  *
357  * fast_forward
358  * bypass the generation of logical changes.
359  *
360  * read_page, prepare_write, do_write, update_progress
361  * callbacks that have to be filled to perform the use-case dependent,
362  * actual work.
363  *
364  * Needs to be called while in a memory context that's at least as long lived
365  * as the decoding context because further memory contexts will be created
366  * inside it.
367  *
368  * Returns an initialized decoding context after calling the output plugin's
369  * startup function.
370  */
373  List *output_plugin_options,
374  bool fast_forward,
375  XLogPageReadCB read_page,
379 {
381  ReplicationSlot *slot;
382  MemoryContext old_context;
383 
384  /* shorter lines... */
385  slot = MyReplicationSlot;
386 
387  /* first some sanity checks that are unlikely to be violated */
388  if (slot == NULL)
389  elog(ERROR, "cannot perform logical decoding without an acquired slot");
390 
391  /* make sure the passed slot is suitable, these are user facing errors */
392  if (SlotIsPhysical(slot))
393  ereport(ERROR,
394  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
395  errmsg("cannot use physical replication slot for logical decoding")));
396 
397  if (slot->data.database != MyDatabaseId)
398  ereport(ERROR,
399  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
400  errmsg("replication slot \"%s\" was not created in this database",
401  NameStr(slot->data.name))));
402 
403  if (start_lsn == InvalidXLogRecPtr)
404  {
405  /* continue from last position */
406  start_lsn = slot->data.confirmed_flush;
407  }
408  else if (start_lsn < slot->data.confirmed_flush)
409  {
410  /*
411  * It might seem like we should error out in this case, but it's
412  * pretty common for a client to acknowledge a LSN it doesn't have to
413  * do anything for, and thus didn't store persistently, because the
414  * xlog records didn't result in anything relevant for logical
415  * decoding. Clients have to be able to do that to support synchronous
416  * replication.
417  */
418  elog(DEBUG1, "cannot stream from %X/%X, minimum is %X/%X, forwarding",
419  (uint32) (start_lsn >> 32), (uint32) start_lsn,
420  (uint32) (slot->data.confirmed_flush >> 32),
421  (uint32) slot->data.confirmed_flush);
422 
423  start_lsn = slot->data.confirmed_flush;
424  }
425 
426  ctx = StartupDecodingContext(output_plugin_options,
427  start_lsn, InvalidTransactionId, false,
428  fast_forward, read_page, prepare_write,
429  do_write, update_progress);
430 
431  /* call output plugin initialization callback */
432  old_context = MemoryContextSwitchTo(ctx->context);
433  if (ctx->callbacks.startup_cb != NULL)
434  startup_cb_wrapper(ctx, &ctx->options, false);
435  MemoryContextSwitchTo(old_context);
436 
438 
439  ereport(LOG,
440  (errmsg("starting logical decoding for slot \"%s\"",
441  NameStr(slot->data.name)),
442  errdetail("Streaming transactions committing after %X/%X, reading WAL from %X/%X.",
443  (uint32) (slot->data.confirmed_flush >> 32),
444  (uint32) slot->data.confirmed_flush,
445  (uint32) (slot->data.restart_lsn >> 32),
446  (uint32) slot->data.restart_lsn)));
447 
448  return ctx;
449 }
450 
451 /*
452  * Returns true if a consistent initial decoding snapshot has been built.
453  */
454 bool
456 {
458 }
459 
460 /*
461  * Read from the decoding slot, until it is ready to start extracting changes.
462  */
463 void
465 {
466  ReplicationSlot *slot = ctx->slot;
467 
468  /* Initialize from where to start reading WAL. */
469  XLogBeginRead(ctx->reader, slot->data.restart_lsn);
470 
471  elog(DEBUG1, "searching for logical decoding starting point, starting at %X/%X",
472  (uint32) (slot->data.restart_lsn >> 32),
473  (uint32) slot->data.restart_lsn);
474 
475  /* Wait for a consistent starting point */
476  for (;;)
477  {
478  XLogRecord *record;
479  char *err = NULL;
480 
481  /* the read_page callback waits for new WAL */
482  record = XLogReadRecord(ctx->reader, &err);
483  if (err)
484  elog(ERROR, "%s", err);
485  if (!record)
486  elog(ERROR, "no record found"); /* shouldn't happen */
487 
489 
490  /* only continue till we found a consistent spot */
491  if (DecodingContextReady(ctx))
492  break;
493 
495  }
496 
497  SpinLockAcquire(&slot->mutex);
498  slot->data.confirmed_flush = ctx->reader->EndRecPtr;
499  SpinLockRelease(&slot->mutex);
500 }
501 
502 /*
503  * Free a previously allocated decoding context, invoking the shutdown
504  * callback if necessary.
505  */
506 void
508 {
509  if (ctx->callbacks.shutdown_cb != NULL)
510  shutdown_cb_wrapper(ctx);
511 
514  XLogReaderFree(ctx->reader);
516 }
517 
518 /*
519  * Prepare a write using the context's output routine.
520  */
521 void
523 {
524  if (!ctx->accept_writes)
525  elog(ERROR, "writes are only accepted in commit, begin and change callbacks");
526 
527  ctx->prepare_write(ctx, ctx->write_location, ctx->write_xid, last_write);
528  ctx->prepared_write = true;
529 }
530 
531 /*
532  * Perform a write using the context's output routine.
533  */
534 void
536 {
537  if (!ctx->prepared_write)
538  elog(ERROR, "OutputPluginPrepareWrite needs to be called before OutputPluginWrite");
539 
540  ctx->write(ctx, ctx->write_location, ctx->write_xid, last_write);
541  ctx->prepared_write = false;
542 }
543 
544 /*
545  * Update progress tracking (if supported).
546  */
547 void
549 {
550  if (!ctx->update_progress)
551  return;
552 
553  ctx->update_progress(ctx, ctx->write_location, ctx->write_xid);
554 }
555 
556 /*
557  * Load the output plugin, lookup its output plugin init function, and check
558  * that it provides the required callbacks.
559  */
560 static void
562 {
563  LogicalOutputPluginInit plugin_init;
564 
565  plugin_init = (LogicalOutputPluginInit)
566  load_external_function(plugin, "_PG_output_plugin_init", false, NULL);
567 
568  if (plugin_init == NULL)
569  elog(ERROR, "output plugins have to declare the _PG_output_plugin_init symbol");
570 
571  /* ask the output plugin to fill the callback struct */
572  plugin_init(callbacks);
573 
574  if (callbacks->begin_cb == NULL)
575  elog(ERROR, "output plugins have to register a begin callback");
576  if (callbacks->change_cb == NULL)
577  elog(ERROR, "output plugins have to register a change callback");
578  if (callbacks->commit_cb == NULL)
579  elog(ERROR, "output plugins have to register a commit callback");
580 }
581 
582 static void
584 {
586 
587  /* not all callbacks have an associated LSN */
588  if (state->report_location != InvalidXLogRecPtr)
589  errcontext("slot \"%s\", output plugin \"%s\", in the %s callback, associated LSN %X/%X",
590  NameStr(state->ctx->slot->data.name),
591  NameStr(state->ctx->slot->data.plugin),
592  state->callback_name,
593  (uint32) (state->report_location >> 32),
594  (uint32) state->report_location);
595  else
596  errcontext("slot \"%s\", output plugin \"%s\", in the %s callback",
597  NameStr(state->ctx->slot->data.name),
598  NameStr(state->ctx->slot->data.plugin),
599  state->callback_name);
600 }
601 
602 static void
604 {
606  ErrorContextCallback errcallback;
607 
608  Assert(!ctx->fast_forward);
609 
610  /* Push callback + info on the error context stack */
611  state.ctx = ctx;
612  state.callback_name = "startup";
615  errcallback.arg = (void *) &state;
616  errcallback.previous = error_context_stack;
617  error_context_stack = &errcallback;
618 
619  /* set output state */
620  ctx->accept_writes = false;
621 
622  /* do the actual work: call callback */
623  ctx->callbacks.startup_cb(ctx, opt, is_init);
624 
625  /* Pop the error context stack */
626  error_context_stack = errcallback.previous;
627 }
628 
629 static void
631 {
633  ErrorContextCallback errcallback;
634 
635  Assert(!ctx->fast_forward);
636 
637  /* Push callback + info on the error context stack */
638  state.ctx = ctx;
639  state.callback_name = "shutdown";
642  errcallback.arg = (void *) &state;
643  errcallback.previous = error_context_stack;
644  error_context_stack = &errcallback;
645 
646  /* set output state */
647  ctx->accept_writes = false;
648 
649  /* do the actual work: call callback */
650  ctx->callbacks.shutdown_cb(ctx);
651 
652  /* Pop the error context stack */
653  error_context_stack = errcallback.previous;
654 }
655 
656 
657 /*
658  * Callbacks for ReorderBuffer which add in some more information and then call
659  * output_plugin.h plugins.
660  */
661 static void
663 {
666  ErrorContextCallback errcallback;
667 
668  Assert(!ctx->fast_forward);
669 
670  /* Push callback + info on the error context stack */
671  state.ctx = ctx;
672  state.callback_name = "begin";
673  state.report_location = txn->first_lsn;
675  errcallback.arg = (void *) &state;
676  errcallback.previous = error_context_stack;
677  error_context_stack = &errcallback;
678 
679  /* set output state */
680  ctx->accept_writes = true;
681  ctx->write_xid = txn->xid;
682  ctx->write_location = txn->first_lsn;
683 
684  /* do the actual work: call callback */
685  ctx->callbacks.begin_cb(ctx, txn);
686 
687  /* Pop the error context stack */
688  error_context_stack = errcallback.previous;
689 }
690 
691 static void
693  XLogRecPtr commit_lsn)
694 {
697  ErrorContextCallback errcallback;
698 
699  Assert(!ctx->fast_forward);
700 
701  /* Push callback + info on the error context stack */
702  state.ctx = ctx;
703  state.callback_name = "commit";
704  state.report_location = txn->final_lsn; /* beginning of commit record */
706  errcallback.arg = (void *) &state;
707  errcallback.previous = error_context_stack;
708  error_context_stack = &errcallback;
709 
710  /* set output state */
711  ctx->accept_writes = true;
712  ctx->write_xid = txn->xid;
713  ctx->write_location = txn->end_lsn; /* points to the end of the record */
714 
715  /* do the actual work: call callback */
716  ctx->callbacks.commit_cb(ctx, txn, commit_lsn);
717 
718  /* Pop the error context stack */
719  error_context_stack = errcallback.previous;
720 }
721 
722 static void
724  Relation relation, ReorderBufferChange *change)
725 {
728  ErrorContextCallback errcallback;
729 
730  Assert(!ctx->fast_forward);
731 
732  /* Push callback + info on the error context stack */
733  state.ctx = ctx;
734  state.callback_name = "change";
735  state.report_location = change->lsn;
737  errcallback.arg = (void *) &state;
738  errcallback.previous = error_context_stack;
739  error_context_stack = &errcallback;
740 
741  /* set output state */
742  ctx->accept_writes = true;
743  ctx->write_xid = txn->xid;
744 
745  /*
746  * report this change's lsn so replies from clients can give an up2date
747  * answer. This won't ever be enough (and shouldn't be!) to confirm
748  * receipt of this transaction, but it might allow another transaction's
749  * commit to be confirmed with one message.
750  */
751  ctx->write_location = change->lsn;
752 
753  ctx->callbacks.change_cb(ctx, txn, relation, change);
754 
755  /* Pop the error context stack */
756  error_context_stack = errcallback.previous;
757 }
758 
759 static void
761  int nrelations, Relation relations[], ReorderBufferChange *change)
762 {
765  ErrorContextCallback errcallback;
766 
767  Assert(!ctx->fast_forward);
768 
769  if (!ctx->callbacks.truncate_cb)
770  return;
771 
772  /* Push callback + info on the error context stack */
773  state.ctx = ctx;
774  state.callback_name = "truncate";
775  state.report_location = change->lsn;
777  errcallback.arg = (void *) &state;
778  errcallback.previous = error_context_stack;
779  error_context_stack = &errcallback;
780 
781  /* set output state */
782  ctx->accept_writes = true;
783  ctx->write_xid = txn->xid;
784 
785  /*
786  * report this change's lsn so replies from clients can give an up2date
787  * answer. This won't ever be enough (and shouldn't be!) to confirm
788  * receipt of this transaction, but it might allow another transaction's
789  * commit to be confirmed with one message.
790  */
791  ctx->write_location = change->lsn;
792 
793  ctx->callbacks.truncate_cb(ctx, txn, nrelations, relations, change);
794 
795  /* Pop the error context stack */
796  error_context_stack = errcallback.previous;
797 }
798 
799 bool
801 {
803  ErrorContextCallback errcallback;
804  bool ret;
805 
806  Assert(!ctx->fast_forward);
807 
808  /* Push callback + info on the error context stack */
809  state.ctx = ctx;
810  state.callback_name = "filter_by_origin";
813  errcallback.arg = (void *) &state;
814  errcallback.previous = error_context_stack;
815  error_context_stack = &errcallback;
816 
817  /* set output state */
818  ctx->accept_writes = false;
819 
820  /* do the actual work: call callback */
821  ret = ctx->callbacks.filter_by_origin_cb(ctx, origin_id);
822 
823  /* Pop the error context stack */
824  error_context_stack = errcallback.previous;
825 
826  return ret;
827 }
828 
829 static void
831  XLogRecPtr message_lsn, bool transactional,
832  const char *prefix, Size message_size, const char *message)
833 {
836  ErrorContextCallback errcallback;
837 
838  Assert(!ctx->fast_forward);
839 
840  if (ctx->callbacks.message_cb == NULL)
841  return;
842 
843  /* Push callback + info on the error context stack */
844  state.ctx = ctx;
845  state.callback_name = "message";
846  state.report_location = message_lsn;
848  errcallback.arg = (void *) &state;
849  errcallback.previous = error_context_stack;
850  error_context_stack = &errcallback;
851 
852  /* set output state */
853  ctx->accept_writes = true;
854  ctx->write_xid = txn != NULL ? txn->xid : InvalidTransactionId;
855  ctx->write_location = message_lsn;
856 
857  /* do the actual work: call callback */
858  ctx->callbacks.message_cb(ctx, txn, message_lsn, transactional, prefix,
859  message_size, message);
860 
861  /* Pop the error context stack */
862  error_context_stack = errcallback.previous;
863 }
864 
865 /*
866  * Set the required catalog xmin horizon for historic snapshots in the current
867  * replication slot.
868  *
869  * Note that in the most cases, we won't be able to immediately use the xmin
870  * to increase the xmin horizon: we need to wait till the client has confirmed
871  * receiving current_lsn with LogicalConfirmReceivedLocation().
872  */
873 void
875 {
876  bool updated_xmin = false;
877  ReplicationSlot *slot;
878 
879  slot = MyReplicationSlot;
880 
881  Assert(slot != NULL);
882 
883  SpinLockAcquire(&slot->mutex);
884 
885  /*
886  * don't overwrite if we already have a newer xmin. This can happen if we
887  * restart decoding in a slot.
888  */
890  {
891  }
892 
893  /*
894  * If the client has already confirmed up to this lsn, we directly can
895  * mark this as accepted. This can happen if we restart decoding in a
896  * slot.
897  */
898  else if (current_lsn <= slot->data.confirmed_flush)
899  {
900  slot->candidate_catalog_xmin = xmin;
901  slot->candidate_xmin_lsn = current_lsn;
902 
903  /* our candidate can directly be used */
904  updated_xmin = true;
905  }
906 
907  /*
908  * Only increase if the previous values have been applied, otherwise we
909  * might never end up updating if the receiver acks too slowly.
910  */
911  else if (slot->candidate_xmin_lsn == InvalidXLogRecPtr)
912  {
913  slot->candidate_catalog_xmin = xmin;
914  slot->candidate_xmin_lsn = current_lsn;
915  }
916  SpinLockRelease(&slot->mutex);
917 
918  /* candidate already valid with the current flush position, apply */
919  if (updated_xmin)
921 }
922 
923 /*
924  * Mark the minimal LSN (restart_lsn) we need to read to replay all
925  * transactions that have not yet committed at current_lsn.
926  *
927  * Just like LogicalIncreaseXminForSlot this only takes effect when the
928  * client has confirmed to have received current_lsn.
929  */
930 void
932 {
933  bool updated_lsn = false;
934  ReplicationSlot *slot;
935 
936  slot = MyReplicationSlot;
937 
938  Assert(slot != NULL);
939  Assert(restart_lsn != InvalidXLogRecPtr);
940  Assert(current_lsn != InvalidXLogRecPtr);
941 
942  SpinLockAcquire(&slot->mutex);
943 
944  /* don't overwrite if have a newer restart lsn */
945  if (restart_lsn <= slot->data.restart_lsn)
946  {
947  }
948 
949  /*
950  * We might have already flushed far enough to directly accept this lsn,
951  * in this case there is no need to check for existing candidate LSNs
952  */
953  else if (current_lsn <= slot->data.confirmed_flush)
954  {
955  slot->candidate_restart_valid = current_lsn;
956  slot->candidate_restart_lsn = restart_lsn;
957 
958  /* our candidate can directly be used */
959  updated_lsn = true;
960  }
961 
962  /*
963  * Only increase if the previous values have been applied, otherwise we
964  * might never end up updating if the receiver acks too slowly. A missed
965  * value here will just cause some extra effort after reconnecting.
966  */
968  {
969  slot->candidate_restart_valid = current_lsn;
970  slot->candidate_restart_lsn = restart_lsn;
971 
972  elog(DEBUG1, "got new restart lsn %X/%X at %X/%X",
973  (uint32) (restart_lsn >> 32), (uint32) restart_lsn,
974  (uint32) (current_lsn >> 32), (uint32) current_lsn);
975  }
976  else
977  {
978  elog(DEBUG1, "failed to increase restart lsn: proposed %X/%X, after %X/%X, current candidate %X/%X, current after %X/%X, flushed up to %X/%X",
979  (uint32) (restart_lsn >> 32), (uint32) restart_lsn,
980  (uint32) (current_lsn >> 32), (uint32) current_lsn,
981  (uint32) (slot->candidate_restart_lsn >> 32),
983  (uint32) (slot->candidate_restart_valid >> 32),
985  (uint32) (slot->data.confirmed_flush >> 32),
986  (uint32) slot->data.confirmed_flush
987  );
988  }
989  SpinLockRelease(&slot->mutex);
990 
991  /* candidates are already valid with the current flush position, apply */
992  if (updated_lsn)
994 }
995 
996 /*
997  * Handle a consumer's confirmation having received all changes up to lsn.
998  */
999 void
1001 {
1002  Assert(lsn != InvalidXLogRecPtr);
1003 
1004  /* Do an unlocked check for candidate_lsn first. */
1007  {
1008  bool updated_xmin = false;
1009  bool updated_restart = false;
1010 
1012 
1014 
1015  /* if we're past the location required for bumping xmin, do so */
1018  {
1019  /*
1020  * We have to write the changed xmin to disk *before* we change
1021  * the in-memory value, otherwise after a crash we wouldn't know
1022  * that some catalog tuples might have been removed already.
1023  *
1024  * Ensure that by first writing to ->xmin and only update
1025  * ->effective_xmin once the new state is synced to disk. After a
1026  * crash ->effective_xmin is set to ->xmin.
1027  */
1030  {
1034  updated_xmin = true;
1035  }
1036  }
1037 
1040  {
1042 
1046  updated_restart = true;
1047  }
1048 
1050 
1051  /* first write new xmin to disk, so we know what's up after a crash */
1052  if (updated_xmin || updated_restart)
1053  {
1056  elog(DEBUG1, "updated xmin: %u restart: %u", updated_xmin, updated_restart);
1057  }
1058 
1059  /*
1060  * Now the new xmin is safely on disk, we can let the global value
1061  * advance. We do not take ProcArrayLock or similar since we only
1062  * advance xmin here and there's not much harm done by a concurrent
1063  * computation missing that.
1064  */
1065  if (updated_xmin)
1066  {
1070 
1073  }
1074  }
1075  else
1076  {
1080  }
1081 }
XLogRecPtr first_lsn
LogicalDecodeTruncateCB truncate_cb
#define NIL
Definition: pg_list.h:65
TransactionId write_xid
Definition: logical.h:88
static const char * plugin
void CheckSlotRequirements(void)
Definition: slot.c:972
TransactionId candidate_catalog_xmin
Definition: slot.h:147
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
TransactionId GetOldestSafeDecodingTransactionId(bool catalogOnly)
Definition: procarray.c:2178
ReorderBufferApplyChangeCB apply_change
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:170
void * private_data
#define DEBUG1
Definition: elog.h:25
static void change_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn, Relation relation, ReorderBufferChange *change)
Definition: logical.c:723
struct ReorderBuffer * reorder
Definition: logical.h:42
#define PROC_IN_LOGICAL_DECODING
Definition: proc.h:57
int wal_segment_size
Definition: xlog.c:114
uint32 TransactionId
Definition: c.h:513
SnapBuildState SnapBuildCurrentState(SnapBuild *builder)
Definition: snapbuild.c:395
static void LoadOutputPlugin(OutputPluginCallbacks *callbacks, char *plugin)
Definition: logical.c:561
bool DecodingContextReady(LogicalDecodingContext *ctx)
Definition: logical.c:455
struct LogicalErrorCallbackState LogicalErrorCallbackState
static void commit_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn, XLogRecPtr commit_lsn)
Definition: logical.c:692
OutputPluginOptions options
Definition: logical.h:53
void LogicalIncreaseRestartDecodingForSlot(XLogRecPtr current_lsn, XLogRecPtr restart_lsn)
Definition: logical.c:931
int wal_level
Definition: xlog.c:105
StringInfo makeStringInfo(void)
Definition: stringinfo.c:41
LogicalDecodeMessageCB message_cb
OutputPluginCallbacks callbacks
Definition: logical.h:52
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void ReorderBufferFree(ReorderBuffer *rb)
uint16 RepOriginId
Definition: xlogdefs.h:58
int errcode(int sqlerrcode)
Definition: elog.c:610
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4653
MemoryContext context
Definition: logical.h:35
void ReplicationSlotSave(void)
Definition: slot.c:645
List * output_plugin_options
Definition: logical.h:58
ReorderBufferCommitCB commit
ReplicationSlotPersistentData data
Definition: slot.h:132
#define LOG
Definition: elog.h:26
bool RecoveryInProgress(void)
Definition: xlog.c:8060
void(* callback)(void *arg)
Definition: elog.h:229
struct ErrorContextCallback * previous
Definition: elog.h:228
#define SlotIsPhysical(slot)
Definition: slot.h:153
LogicalOutputPluginWriterWrite LogicalOutputPluginWriterPrepareWrite
Definition: logical.h:25
void(* LogicalOutputPluginWriterUpdateProgress)(struct LogicalDecodingContext *lr, XLogRecPtr Ptr, TransactionId xid)
Definition: logical.h:27
const char * callback_name
Definition: logical.c:48
XLogRecPtr confirmed_flush
Definition: slot.h:80
PGXACT * MyPgXact
Definition: proc.c:68
XLogRecPtr write_location
Definition: logical.h:87
XLogRecPtr EndRecPtr
Definition: xlogreader.h:135
uint8 vacuumFlags
Definition: proc.h:233
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1727
ErrorContextCallback * error_context_stack
Definition: elog.c:92
#define NAMEDATALEN
#define SpinLockAcquire(lock)
Definition: spin.h:62
void ReplicationSlotReserveWal(void)
Definition: slot.c:997
void DecodingContextFindStartpoint(LogicalDecodingContext *ctx)
Definition: logical.c:464
void ReplicationSlotsComputeRequiredLSN(void)
Definition: slot.c:748
XLogRecord * XLogReadRecord(XLogReaderState *state, char **errormsg)
Definition: xlogreader.c:261
bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:319
#define ERROR
Definition: elog.h:43
void LogicalDecodingProcessRecord(LogicalDecodingContext *ctx, XLogReaderState *record)
Definition: decode.c:94
static void startup_cb_wrapper(LogicalDecodingContext *ctx, OutputPluginOptions *opt, bool is_init)
Definition: logical.c:603
LogicalOutputPluginWriterPrepareWrite prepare_write
Definition: logical.h:63
LogicalDecodeCommitCB commit_cb
TransactionId effective_xmin
Definition: slot.h:128
void(* LogicalOutputPluginInit)(struct OutputPluginCallbacks *cb)
Definition: output_plugin.h:36
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:192
static void shutdown_cb_wrapper(LogicalDecodingContext *ctx)
Definition: logical.c:630
XLogRecPtr candidate_restart_valid
Definition: slot.h:149
int errdetail(const char *fmt,...)
Definition: elog.c:957
TransactionId catalog_xmin
Definition: slot.h:69
#define InvalidTransactionId
Definition: transam.h:31
void XLogBeginRead(XLogReaderState *state, XLogRecPtr RecPtr)
Definition: xlogreader.c:233
LogicalOutputPluginWriterUpdateProgress update_progress
Definition: logical.h:65
unsigned int uint32
Definition: c.h:367
XLogRecPtr final_lsn
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
bool filter_by_origin_cb_wrapper(LogicalDecodingContext *ctx, RepOriginId origin_id)
Definition: logical.c:800
TransactionId GetTopTransactionIdIfAny(void)
Definition: xact.c:409
ReorderBufferMessageCB message
PGFunction load_external_function(const char *filename, const char *funcname, bool signalNotFound, void **filehandle)
Definition: dfmgr.c:107
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
void XLogReaderFree(XLogReaderState *state)
Definition: xlogreader.c:135
#define SpinLockRelease(lock)
Definition: spin.h:64
LogicalDecodingContext * CreateInitDecodingContext(char *plugin, List *output_plugin_options, bool need_full_snapshot, XLogRecPtr restart_lsn, XLogPageReadCB read_page, LogicalOutputPluginWriterPrepareWrite prepare_write, LogicalOutputPluginWriterWrite do_write, LogicalOutputPluginWriterUpdateProgress update_progress)
Definition: logical.c:229
void OutputPluginUpdateProgress(struct LogicalDecodingContext *ctx)
Definition: logical.c:548
void * palloc0(Size size)
Definition: mcxt.c:980
LogicalDecodeChangeCB change_cb
TransactionId effective_catalog_xmin
Definition: slot.h:129
LogicalDecodingContext * CreateDecodingContext(XLogRecPtr start_lsn, List *output_plugin_options, bool fast_forward, XLogPageReadCB read_page, LogicalOutputPluginWriterPrepareWrite prepare_write, LogicalOutputPluginWriterWrite do_write, LogicalOutputPluginWriterUpdateProgress update_progress)
Definition: logical.c:372
TransactionId xid
Oid MyDatabaseId
Definition: globals.c:85
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:144
void FreeSnapshotBuilder(SnapBuild *builder)
Definition: snapbuild.c:351
static void begin_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn)
Definition: logical.c:662
void OutputPluginPrepareWrite(struct LogicalDecodingContext *ctx, bool last_write)
Definition: logical.c:522
struct SnapBuild * snapshot_builder
Definition: logical.h:43
ReplicationSlot * MyReplicationSlot
Definition: slot.c:96
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:738
#define StrNCpy(dst, src, len)
Definition: c.h:944
Definition: regguts.h:298
void FreeDecodingContext(LogicalDecodingContext *ctx)
Definition: logical.c:507
XLogRecPtr restart_lsn
Definition: slot.h:72
void LogicalIncreaseXminForSlot(XLogRecPtr current_lsn, TransactionId xmin)
Definition: logical.c:874
XLogRecPtr end_lsn
size_t Size
Definition: c.h:466
static LogicalDecodingContext * StartupDecodingContext(List *output_plugin_options, XLogRecPtr start_lsn, TransactionId xmin_horizon, bool need_full_snapshot, bool fast_forward, XLogPageReadCB read_page, LogicalOutputPluginWriterPrepareWrite prepare_write, LogicalOutputPluginWriterWrite do_write, LogicalOutputPluginWriterUpdateProgress update_progress)
Definition: logical.c:118
LogicalDecodeShutdownCB shutdown_cb
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1123
bool IsTransactionState(void)
Definition: xact.c:355
ReorderBuffer * ReorderBufferAllocate(void)
void(* LogicalOutputPluginWriterWrite)(struct LogicalDecodingContext *lr, XLogRecPtr Ptr, TransactionId xid, bool last_write)
Definition: logical.h:19
void LogicalConfirmReceivedLocation(XLogRecPtr lsn)
Definition: logical.c:1000
LogicalDecodeStartupCB startup_cb
XLogRecPtr candidate_xmin_lsn
Definition: slot.h:148
XLogReaderState * XLogReaderAllocate(int wal_segment_size, const char *waldir, XLogPageReadCB pagereadfunc, void *private_data)
Definition: xlogreader.c:73
XLogRecPtr report_location
Definition: logical.c:49
static void truncate_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn, int nrelations, Relation relations[], ReorderBufferChange *change)
Definition: logical.c:760
int errmsg(const char *fmt,...)
Definition: elog.c:824
XLogReaderState * reader
Definition: logical.h:41
ReplicationSlot * slot
Definition: logical.h:38
ReorderBufferApplyTruncateCB apply_truncate
void OutputPluginWrite(struct LogicalDecodingContext *ctx, bool last_write)
Definition: logical.c:535
LogicalOutputPluginWriterWrite write
Definition: logical.h:64
#define elog(elevel,...)
Definition: elog.h:214
StringInfo out
Definition: logical.h:70
#define errcontext
Definition: elog.h:185
#define NameStr(name)
Definition: c.h:615
void * arg
LogicalDecodeBeginCB begin_cb
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
static void message_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn, XLogRecPtr message_lsn, bool transactional, const char *prefix, Size message_size, const char *message)
Definition: logical.c:830
int(* XLogPageReadCB)(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *readBuf)
Definition: xlogreader.h:54
slock_t mutex
Definition: slot.h:105
#define TransactionIdIsValid(xid)
Definition: transam.h:41
LogicalDecodingContext * ctx
Definition: logical.c:47
ReorderBufferBeginCB begin
static void output_plugin_error_callback(void *arg)
Definition: logical.c:583
LogicalDecodeFilterByOriginCB filter_by_origin_cb
Definition: pg_list.h:50
void CheckLogicalDecodingRequirements(void)
Definition: logical.c:75
SnapBuild * AllocateSnapshotBuilder(ReorderBuffer *reorder, TransactionId xmin_horizon, XLogRecPtr start_lsn, bool need_full_snapshot)
Definition: snapbuild.c:310
void ReplicationSlotsComputeRequiredXmin(bool already_locked)
Definition: slot.c:702
XLogRecPtr candidate_restart_lsn
Definition: slot.h:150
void ReplicationSlotMarkDirty(void)
Definition: slot.c:663