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-2019, 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  * restart_lsn -- if given as invalid, it's this routine's responsibility to
212  * mark WAL as reserved by setting a convenient restart_lsn for the slot.
213  * Otherwise, we set for decoding to start from the given LSN without
214  * marking WAL reserved beforehand. In that scenario, it's up to the
215  * caller to guarantee that WAL remains available.
216  * read_page, prepare_write, do_write, update_progress --
217  * callbacks that perform the use-case dependent, actual, work.
218  *
219  * Needs to be called while in a memory context that's at least as long lived
220  * as the decoding context because further memory contexts will be created
221  * inside it.
222  *
223  * Returns an initialized decoding context after calling the output plugin's
224  * startup function.
225  */
228  List *output_plugin_options,
229  bool need_full_snapshot,
230  XLogRecPtr restart_lsn,
231  XLogPageReadCB read_page,
235 {
236  TransactionId xmin_horizon = InvalidTransactionId;
237  ReplicationSlot *slot;
239  MemoryContext old_context;
240 
241  /* shorter lines... */
242  slot = MyReplicationSlot;
243 
244  /* first some sanity checks that are unlikely to be violated */
245  if (slot == NULL)
246  elog(ERROR, "cannot perform logical decoding without an acquired slot");
247 
248  if (plugin == NULL)
249  elog(ERROR, "cannot initialize logical decoding without a specified plugin");
250 
251  /* Make sure the passed slot is suitable. These are user facing errors. */
252  if (SlotIsPhysical(slot))
253  ereport(ERROR,
254  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
255  errmsg("cannot use physical replication slot for logical decoding")));
256 
257  if (slot->data.database != MyDatabaseId)
258  ereport(ERROR,
259  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
260  errmsg("replication slot \"%s\" was not created in this database",
261  NameStr(slot->data.name))));
262 
263  if (IsTransactionState() &&
265  ereport(ERROR,
266  (errcode(ERRCODE_ACTIVE_SQL_TRANSACTION),
267  errmsg("cannot create logical replication slot in transaction that has performed writes")));
268 
269  /* register output plugin name with slot */
270  SpinLockAcquire(&slot->mutex);
271  StrNCpy(NameStr(slot->data.plugin), plugin, NAMEDATALEN);
272  SpinLockRelease(&slot->mutex);
273 
274  if (XLogRecPtrIsInvalid(restart_lsn))
276  else
277  {
278  SpinLockAcquire(&slot->mutex);
279  slot->data.restart_lsn = restart_lsn;
280  SpinLockRelease(&slot->mutex);
281  }
282 
283  /* ----
284  * This is a bit tricky: We need to determine a safe xmin horizon to start
285  * decoding from, to avoid starting from a running xacts record referring
286  * to xids whose rows have been vacuumed or pruned
287  * already. GetOldestSafeDecodingTransactionId() returns such a value, but
288  * without further interlock its return value might immediately be out of
289  * date.
290  *
291  * So we have to acquire the ProcArrayLock to prevent computation of new
292  * xmin horizons by other backends, get the safe decoding xid, and inform
293  * the slot machinery about the new limit. Once that's done the
294  * ProcArrayLock can be released as the slot machinery now is
295  * protecting against vacuum.
296  *
297  * Note that, temporarily, the data, not just the catalog, xmin has to be
298  * reserved if a data snapshot is to be exported. Otherwise the initial
299  * data snapshot created here is not guaranteed to be valid. After that
300  * the data xmin doesn't need to be managed anymore and the global xmin
301  * should be recomputed. As we are fine with losing the pegged data xmin
302  * after crash - no chance a snapshot would get exported anymore - we can
303  * get away with just setting the slot's
304  * effective_xmin. ReplicationSlotRelease will reset it again.
305  *
306  * ----
307  */
308  LWLockAcquire(ProcArrayLock, LW_EXCLUSIVE);
309 
310  xmin_horizon = GetOldestSafeDecodingTransactionId(!need_full_snapshot);
311 
312  SpinLockAcquire(&slot->mutex);
313  slot->effective_catalog_xmin = xmin_horizon;
314  slot->data.catalog_xmin = xmin_horizon;
315  if (need_full_snapshot)
316  slot->effective_xmin = xmin_horizon;
317  SpinLockRelease(&slot->mutex);
318 
320 
321  LWLockRelease(ProcArrayLock);
322 
325 
326  ctx = StartupDecodingContext(NIL, restart_lsn, xmin_horizon,
327  need_full_snapshot, false,
328  read_page, prepare_write, do_write,
329  update_progress);
330 
331  /* call output plugin initialization callback */
332  old_context = MemoryContextSwitchTo(ctx->context);
333  if (ctx->callbacks.startup_cb != NULL)
334  startup_cb_wrapper(ctx, &ctx->options, true);
335  MemoryContextSwitchTo(old_context);
336 
338 
339  return ctx;
340 }
341 
342 /*
343  * Create a new decoding context, for a logical slot that has previously been
344  * used already.
345  *
346  * start_lsn
347  * The LSN at which to start decoding. If InvalidXLogRecPtr, restart
348  * from the slot's confirmed_flush; otherwise, start from the specified
349  * location (but move it forwards to confirmed_flush if it's older than
350  * that, see below).
351  *
352  * output_plugin_options
353  * options passed to the output plugin.
354  *
355  * fast_forward
356  * bypass the generation of logical changes.
357  *
358  * read_page, prepare_write, do_write, update_progress
359  * callbacks that have to be filled to perform the use-case dependent,
360  * actual work.
361  *
362  * Needs to be called while in a memory context that's at least as long lived
363  * as the decoding context because further memory contexts will be created
364  * inside it.
365  *
366  * Returns an initialized decoding context after calling the output plugin's
367  * startup function.
368  */
371  List *output_plugin_options,
372  bool fast_forward,
373  XLogPageReadCB read_page,
377 {
379  ReplicationSlot *slot;
380  MemoryContext old_context;
381 
382  /* shorter lines... */
383  slot = MyReplicationSlot;
384 
385  /* first some sanity checks that are unlikely to be violated */
386  if (slot == NULL)
387  elog(ERROR, "cannot perform logical decoding without an acquired slot");
388 
389  /* make sure the passed slot is suitable, these are user facing errors */
390  if (SlotIsPhysical(slot))
391  ereport(ERROR,
392  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
393  (errmsg("cannot use physical replication slot for logical decoding"))));
394 
395  if (slot->data.database != MyDatabaseId)
396  ereport(ERROR,
397  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
398  (errmsg("replication slot \"%s\" was not created in this database",
399  NameStr(slot->data.name)))));
400 
401  if (start_lsn == InvalidXLogRecPtr)
402  {
403  /* continue from last position */
404  start_lsn = slot->data.confirmed_flush;
405  }
406  else if (start_lsn < slot->data.confirmed_flush)
407  {
408  /*
409  * It might seem like we should error out in this case, but it's
410  * pretty common for a client to acknowledge a LSN it doesn't have to
411  * do anything for, and thus didn't store persistently, because the
412  * xlog records didn't result in anything relevant for logical
413  * decoding. Clients have to be able to do that to support synchronous
414  * replication.
415  */
416  elog(DEBUG1, "cannot stream from %X/%X, minimum is %X/%X, forwarding",
417  (uint32) (start_lsn >> 32), (uint32) start_lsn,
418  (uint32) (slot->data.confirmed_flush >> 32),
419  (uint32) slot->data.confirmed_flush);
420 
421  start_lsn = slot->data.confirmed_flush;
422  }
423 
424  ctx = StartupDecodingContext(output_plugin_options,
425  start_lsn, InvalidTransactionId, false,
426  fast_forward, read_page, prepare_write,
427  do_write, update_progress);
428 
429  /* call output plugin initialization callback */
430  old_context = MemoryContextSwitchTo(ctx->context);
431  if (ctx->callbacks.startup_cb != NULL)
432  startup_cb_wrapper(ctx, &ctx->options, false);
433  MemoryContextSwitchTo(old_context);
434 
436 
437  ereport(LOG,
438  (errmsg("starting logical decoding for slot \"%s\"",
439  NameStr(slot->data.name)),
440  errdetail("Streaming transactions committing after %X/%X, reading WAL from %X/%X.",
441  (uint32) (slot->data.confirmed_flush >> 32),
442  (uint32) slot->data.confirmed_flush,
443  (uint32) (slot->data.restart_lsn >> 32),
444  (uint32) slot->data.restart_lsn)));
445 
446  return ctx;
447 }
448 
449 /*
450  * Returns true if a consistent initial decoding snapshot has been built.
451  */
452 bool
454 {
456 }
457 
458 /*
459  * Read from the decoding slot, until it is ready to start extracting changes.
460  */
461 void
463 {
465  ReplicationSlot *slot = ctx->slot;
466 
467  /* Initialize from where to start reading WAL. */
468  startptr = slot->data.restart_lsn;
469 
470  elog(DEBUG1, "searching for logical decoding starting point, starting at %X/%X",
471  (uint32) (slot->data.restart_lsn >> 32),
472  (uint32) slot->data.restart_lsn);
473 
474  /* Wait for a consistent starting point */
475  for (;;)
476  {
477  XLogRecord *record;
478  char *err = NULL;
479 
480  /* the read_page callback waits for new WAL */
481  record = XLogReadRecord(ctx->reader, startptr, &err);
482  if (err)
483  elog(ERROR, "%s", err);
484  if (!record)
485  elog(ERROR, "no record found"); /* shouldn't happen */
486 
487  startptr = InvalidXLogRecPtr;
488 
490 
491  /* only continue till we found a consistent spot */
492  if (DecodingContextReady(ctx))
493  break;
494 
496  }
497 
498  SpinLockAcquire(&slot->mutex);
499  slot->data.confirmed_flush = ctx->reader->EndRecPtr;
500  SpinLockRelease(&slot->mutex);
501 }
502 
503 /*
504  * Free a previously allocated decoding context, invoking the shutdown
505  * callback if necessary.
506  */
507 void
509 {
510  if (ctx->callbacks.shutdown_cb != NULL)
511  shutdown_cb_wrapper(ctx);
512 
515  XLogReaderFree(ctx->reader);
517 }
518 
519 /*
520  * Prepare a write using the context's output routine.
521  */
522 void
524 {
525  if (!ctx->accept_writes)
526  elog(ERROR, "writes are only accepted in commit, begin and change callbacks");
527 
528  ctx->prepare_write(ctx, ctx->write_location, ctx->write_xid, last_write);
529  ctx->prepared_write = true;
530 }
531 
532 /*
533  * Perform a write using the context's output routine.
534  */
535 void
537 {
538  if (!ctx->prepared_write)
539  elog(ERROR, "OutputPluginPrepareWrite needs to be called before OutputPluginWrite");
540 
541  ctx->write(ctx, ctx->write_location, ctx->write_xid, last_write);
542  ctx->prepared_write = false;
543 }
544 
545 /*
546  * Update progress tracking (if supported).
547  */
548 void
550 {
551  if (!ctx->update_progress)
552  return;
553 
554  ctx->update_progress(ctx, ctx->write_location, ctx->write_xid);
555 }
556 
557 /*
558  * Load the output plugin, lookup its output plugin init function, and check
559  * that it provides the required callbacks.
560  */
561 static void
563 {
564  LogicalOutputPluginInit plugin_init;
565 
566  plugin_init = (LogicalOutputPluginInit)
567  load_external_function(plugin, "_PG_output_plugin_init", false, NULL);
568 
569  if (plugin_init == NULL)
570  elog(ERROR, "output plugins have to declare the _PG_output_plugin_init symbol");
571 
572  /* ask the output plugin to fill the callback struct */
573  plugin_init(callbacks);
574 
575  if (callbacks->begin_cb == NULL)
576  elog(ERROR, "output plugins have to register a begin callback");
577  if (callbacks->change_cb == NULL)
578  elog(ERROR, "output plugins have to register a change callback");
579  if (callbacks->commit_cb == NULL)
580  elog(ERROR, "output plugins have to register a commit callback");
581 }
582 
583 static void
585 {
587 
588  /* not all callbacks have an associated LSN */
589  if (state->report_location != InvalidXLogRecPtr)
590  errcontext("slot \"%s\", output plugin \"%s\", in the %s callback, associated LSN %X/%X",
591  NameStr(state->ctx->slot->data.name),
592  NameStr(state->ctx->slot->data.plugin),
593  state->callback_name,
594  (uint32) (state->report_location >> 32),
595  (uint32) state->report_location);
596  else
597  errcontext("slot \"%s\", output plugin \"%s\", in the %s callback",
598  NameStr(state->ctx->slot->data.name),
599  NameStr(state->ctx->slot->data.plugin),
600  state->callback_name);
601 }
602 
603 static void
605 {
607  ErrorContextCallback errcallback;
608 
609  Assert(!ctx->fast_forward);
610 
611  /* Push callback + info on the error context stack */
612  state.ctx = ctx;
613  state.callback_name = "startup";
616  errcallback.arg = (void *) &state;
617  errcallback.previous = error_context_stack;
618  error_context_stack = &errcallback;
619 
620  /* set output state */
621  ctx->accept_writes = false;
622 
623  /* do the actual work: call callback */
624  ctx->callbacks.startup_cb(ctx, opt, is_init);
625 
626  /* Pop the error context stack */
627  error_context_stack = errcallback.previous;
628 }
629 
630 static void
632 {
634  ErrorContextCallback errcallback;
635 
636  Assert(!ctx->fast_forward);
637 
638  /* Push callback + info on the error context stack */
639  state.ctx = ctx;
640  state.callback_name = "shutdown";
643  errcallback.arg = (void *) &state;
644  errcallback.previous = error_context_stack;
645  error_context_stack = &errcallback;
646 
647  /* set output state */
648  ctx->accept_writes = false;
649 
650  /* do the actual work: call callback */
651  ctx->callbacks.shutdown_cb(ctx);
652 
653  /* Pop the error context stack */
654  error_context_stack = errcallback.previous;
655 }
656 
657 
658 /*
659  * Callbacks for ReorderBuffer which add in some more information and then call
660  * output_plugin.h plugins.
661  */
662 static void
664 {
667  ErrorContextCallback errcallback;
668 
669  Assert(!ctx->fast_forward);
670 
671  /* Push callback + info on the error context stack */
672  state.ctx = ctx;
673  state.callback_name = "begin";
674  state.report_location = txn->first_lsn;
676  errcallback.arg = (void *) &state;
677  errcallback.previous = error_context_stack;
678  error_context_stack = &errcallback;
679 
680  /* set output state */
681  ctx->accept_writes = true;
682  ctx->write_xid = txn->xid;
683  ctx->write_location = txn->first_lsn;
684 
685  /* do the actual work: call callback */
686  ctx->callbacks.begin_cb(ctx, txn);
687 
688  /* Pop the error context stack */
689  error_context_stack = errcallback.previous;
690 }
691 
692 static void
694  XLogRecPtr commit_lsn)
695 {
698  ErrorContextCallback errcallback;
699 
700  Assert(!ctx->fast_forward);
701 
702  /* Push callback + info on the error context stack */
703  state.ctx = ctx;
704  state.callback_name = "commit";
705  state.report_location = txn->final_lsn; /* beginning of commit record */
707  errcallback.arg = (void *) &state;
708  errcallback.previous = error_context_stack;
709  error_context_stack = &errcallback;
710 
711  /* set output state */
712  ctx->accept_writes = true;
713  ctx->write_xid = txn->xid;
714  ctx->write_location = txn->end_lsn; /* points to the end of the record */
715 
716  /* do the actual work: call callback */
717  ctx->callbacks.commit_cb(ctx, txn, commit_lsn);
718 
719  /* Pop the error context stack */
720  error_context_stack = errcallback.previous;
721 }
722 
723 static void
725  Relation relation, ReorderBufferChange *change)
726 {
729  ErrorContextCallback errcallback;
730 
731  Assert(!ctx->fast_forward);
732 
733  /* Push callback + info on the error context stack */
734  state.ctx = ctx;
735  state.callback_name = "change";
736  state.report_location = change->lsn;
738  errcallback.arg = (void *) &state;
739  errcallback.previous = error_context_stack;
740  error_context_stack = &errcallback;
741 
742  /* set output state */
743  ctx->accept_writes = true;
744  ctx->write_xid = txn->xid;
745 
746  /*
747  * report this change's lsn so replies from clients can give an up2date
748  * answer. This won't ever be enough (and shouldn't be!) to confirm
749  * receipt of this transaction, but it might allow another transaction's
750  * commit to be confirmed with one message.
751  */
752  ctx->write_location = change->lsn;
753 
754  ctx->callbacks.change_cb(ctx, txn, relation, change);
755 
756  /* Pop the error context stack */
757  error_context_stack = errcallback.previous;
758 }
759 
760 static void
762  int nrelations, Relation relations[], ReorderBufferChange *change)
763 {
766  ErrorContextCallback errcallback;
767 
768  Assert(!ctx->fast_forward);
769 
770  if (!ctx->callbacks.truncate_cb)
771  return;
772 
773  /* Push callback + info on the error context stack */
774  state.ctx = ctx;
775  state.callback_name = "truncate";
776  state.report_location = change->lsn;
778  errcallback.arg = (void *) &state;
779  errcallback.previous = error_context_stack;
780  error_context_stack = &errcallback;
781 
782  /* set output state */
783  ctx->accept_writes = true;
784  ctx->write_xid = txn->xid;
785 
786  /*
787  * report this change's lsn so replies from clients can give an up2date
788  * answer. This won't ever be enough (and shouldn't be!) to confirm
789  * receipt of this transaction, but it might allow another transaction's
790  * commit to be confirmed with one message.
791  */
792  ctx->write_location = change->lsn;
793 
794  ctx->callbacks.truncate_cb(ctx, txn, nrelations, relations, change);
795 
796  /* Pop the error context stack */
797  error_context_stack = errcallback.previous;
798 }
799 
800 bool
802 {
804  ErrorContextCallback errcallback;
805  bool ret;
806 
807  Assert(!ctx->fast_forward);
808 
809  /* Push callback + info on the error context stack */
810  state.ctx = ctx;
811  state.callback_name = "filter_by_origin";
814  errcallback.arg = (void *) &state;
815  errcallback.previous = error_context_stack;
816  error_context_stack = &errcallback;
817 
818  /* set output state */
819  ctx->accept_writes = false;
820 
821  /* do the actual work: call callback */
822  ret = ctx->callbacks.filter_by_origin_cb(ctx, origin_id);
823 
824  /* Pop the error context stack */
825  error_context_stack = errcallback.previous;
826 
827  return ret;
828 }
829 
830 static void
832  XLogRecPtr message_lsn, bool transactional,
833  const char *prefix, Size message_size, const char *message)
834 {
837  ErrorContextCallback errcallback;
838 
839  Assert(!ctx->fast_forward);
840 
841  if (ctx->callbacks.message_cb == NULL)
842  return;
843 
844  /* Push callback + info on the error context stack */
845  state.ctx = ctx;
846  state.callback_name = "message";
847  state.report_location = message_lsn;
849  errcallback.arg = (void *) &state;
850  errcallback.previous = error_context_stack;
851  error_context_stack = &errcallback;
852 
853  /* set output state */
854  ctx->accept_writes = true;
855  ctx->write_xid = txn != NULL ? txn->xid : InvalidTransactionId;
856  ctx->write_location = message_lsn;
857 
858  /* do the actual work: call callback */
859  ctx->callbacks.message_cb(ctx, txn, message_lsn, transactional, prefix,
860  message_size, message);
861 
862  /* Pop the error context stack */
863  error_context_stack = errcallback.previous;
864 }
865 
866 /*
867  * Set the required catalog xmin horizon for historic snapshots in the current
868  * replication slot.
869  *
870  * Note that in the most cases, we won't be able to immediately use the xmin
871  * to increase the xmin horizon: we need to wait till the client has confirmed
872  * receiving current_lsn with LogicalConfirmReceivedLocation().
873  */
874 void
876 {
877  bool updated_xmin = false;
878  ReplicationSlot *slot;
879 
880  slot = MyReplicationSlot;
881 
882  Assert(slot != NULL);
883 
884  SpinLockAcquire(&slot->mutex);
885 
886  /*
887  * don't overwrite if we already have a newer xmin. This can happen if we
888  * restart decoding in a slot.
889  */
891  {
892  }
893 
894  /*
895  * If the client has already confirmed up to this lsn, we directly can
896  * mark this as accepted. This can happen if we restart decoding in a
897  * slot.
898  */
899  else if (current_lsn <= slot->data.confirmed_flush)
900  {
901  slot->candidate_catalog_xmin = xmin;
902  slot->candidate_xmin_lsn = current_lsn;
903 
904  /* our candidate can directly be used */
905  updated_xmin = true;
906  }
907 
908  /*
909  * Only increase if the previous values have been applied, otherwise we
910  * might never end up updating if the receiver acks too slowly.
911  */
912  else if (slot->candidate_xmin_lsn == InvalidXLogRecPtr)
913  {
914  slot->candidate_catalog_xmin = xmin;
915  slot->candidate_xmin_lsn = current_lsn;
916  }
917  SpinLockRelease(&slot->mutex);
918 
919  /* candidate already valid with the current flush position, apply */
920  if (updated_xmin)
922 }
923 
924 /*
925  * Mark the minimal LSN (restart_lsn) we need to read to replay all
926  * transactions that have not yet committed at current_lsn.
927  *
928  * Just like LogicalIncreaseXminForSlot this only takes effect when the
929  * client has confirmed to have received current_lsn.
930  */
931 void
933 {
934  bool updated_lsn = false;
935  ReplicationSlot *slot;
936 
937  slot = MyReplicationSlot;
938 
939  Assert(slot != NULL);
940  Assert(restart_lsn != InvalidXLogRecPtr);
941  Assert(current_lsn != InvalidXLogRecPtr);
942 
943  SpinLockAcquire(&slot->mutex);
944 
945  /* don't overwrite if have a newer restart lsn */
946  if (restart_lsn <= slot->data.restart_lsn)
947  {
948  }
949 
950  /*
951  * We might have already flushed far enough to directly accept this lsn,
952  * in this case there is no need to check for existing candidate LSNs
953  */
954  else if (current_lsn <= slot->data.confirmed_flush)
955  {
956  slot->candidate_restart_valid = current_lsn;
957  slot->candidate_restart_lsn = restart_lsn;
958 
959  /* our candidate can directly be used */
960  updated_lsn = true;
961  }
962 
963  /*
964  * Only increase if the previous values have been applied, otherwise we
965  * might never end up updating if the receiver acks too slowly. A missed
966  * value here will just cause some extra effort after reconnecting.
967  */
969  {
970  slot->candidate_restart_valid = current_lsn;
971  slot->candidate_restart_lsn = restart_lsn;
972 
973  elog(DEBUG1, "got new restart lsn %X/%X at %X/%X",
974  (uint32) (restart_lsn >> 32), (uint32) restart_lsn,
975  (uint32) (current_lsn >> 32), (uint32) current_lsn);
976  }
977  else
978  {
979  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",
980  (uint32) (restart_lsn >> 32), (uint32) restart_lsn,
981  (uint32) (current_lsn >> 32), (uint32) current_lsn,
982  (uint32) (slot->candidate_restart_lsn >> 32),
984  (uint32) (slot->candidate_restart_valid >> 32),
986  (uint32) (slot->data.confirmed_flush >> 32),
987  (uint32) slot->data.confirmed_flush
988  );
989  }
990  SpinLockRelease(&slot->mutex);
991 
992  /* candidates are already valid with the current flush position, apply */
993  if (updated_lsn)
995 }
996 
997 /*
998  * Handle a consumer's confirmation having received all changes up to lsn.
999  */
1000 void
1002 {
1003  Assert(lsn != InvalidXLogRecPtr);
1004 
1005  /* Do an unlocked check for candidate_lsn first. */
1008  {
1009  bool updated_xmin = false;
1010  bool updated_restart = false;
1011 
1013 
1015 
1016  /* if we're past the location required for bumping xmin, do so */
1019  {
1020  /*
1021  * We have to write the changed xmin to disk *before* we change
1022  * the in-memory value, otherwise after a crash we wouldn't know
1023  * that some catalog tuples might have been removed already.
1024  *
1025  * Ensure that by first writing to ->xmin and only update
1026  * ->effective_xmin once the new state is synced to disk. After a
1027  * crash ->effective_xmin is set to ->xmin.
1028  */
1031  {
1035  updated_xmin = true;
1036  }
1037  }
1038 
1041  {
1043 
1047  updated_restart = true;
1048  }
1049 
1051 
1052  /* first write new xmin to disk, so we know what's up after a crash */
1053  if (updated_xmin || updated_restart)
1054  {
1057  elog(DEBUG1, "updated xmin: %u restart: %u", updated_xmin, updated_restart);
1058  }
1059 
1060  /*
1061  * Now the new xmin is safely on disk, we can let the global value
1062  * advance. We do not take ProcArrayLock or similar since we only
1063  * advance xmin here and there's not much harm done by a concurrent
1064  * computation missing that.
1065  */
1066  if (updated_xmin)
1067  {
1071 
1074  }
1075  }
1076  else
1077  {
1081  }
1082 }
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:2177
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:724
struct ReorderBuffer * reorder
Definition: logical.h:42
#define PROC_IN_LOGICAL_DECODING
Definition: proc.h:57
int wal_segment_size
Definition: xlog.c:112
uint32 TransactionId
Definition: c.h:514
SnapBuildState SnapBuildCurrentState(SnapBuild *builder)
Definition: snapbuild.c:395
static void LoadOutputPlugin(OutputPluginCallbacks *callbacks, char *plugin)
Definition: logical.c:562
bool DecodingContextReady(LogicalDecodingContext *ctx)
Definition: logical.c:453
struct LogicalErrorCallbackState LogicalErrorCallbackState
static void commit_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn, XLogRecPtr commit_lsn)
Definition: logical.c:693
OutputPluginOptions options
Definition: logical.h:53
void LogicalIncreaseRestartDecodingForSlot(XLogRecPtr current_lsn, XLogRecPtr restart_lsn)
Definition: logical.c:932
int wal_level
Definition: xlog.c:103
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:608
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:7935
void(* callback)(void *arg)
Definition: elog.h:256
struct ErrorContextCallback * previous
Definition: elog.h:255
#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
XLogRecord * XLogReadRecord(XLogReaderState *state, XLogRecPtr RecPtr, char **errormsg)
Definition: xlogreader.c:238
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:132
uint8 vacuumFlags
Definition: proc.h:233
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
ErrorContextCallback * error_context_stack
Definition: elog.c:91
#define NAMEDATALEN
#define SpinLockAcquire(lock)
Definition: spin.h:62
void ReplicationSlotReserveWal(void)
Definition: slot.c:997
void DecodingContextFindStartpoint(LogicalDecodingContext *ctx)
Definition: logical.c:462
void ReplicationSlotsComputeRequiredLSN(void)
Definition: slot.c:748
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:604
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:631
XLogRecPtr candidate_restart_valid
Definition: slot.h:149
int errdetail(const char *fmt,...)
Definition: elog.c:955
TransactionId catalog_xmin
Definition: slot.h:69
#define InvalidTransactionId
Definition: transam.h:31
LogicalOutputPluginWriterUpdateProgress update_progress
Definition: logical.h:65
unsigned int uint32
Definition: c.h:359
XLogRecPtr final_lsn
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
bool filter_by_origin_cb_wrapper(LogicalDecodingContext *ctx, RepOriginId origin_id)
Definition: logical.c:801
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 ereport(elevel, rest)
Definition: elog.h:141
#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:227
void OutputPluginUpdateProgress(struct LogicalDecodingContext *ctx)
Definition: logical.c:549
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:370
TransactionId xid
Oid MyDatabaseId
Definition: globals.c:85
#define InvalidOid
Definition: postgres_ext.h:36
void FreeSnapshotBuilder(SnapBuild *builder)
Definition: snapbuild.c:351
static void begin_cb_wrapper(ReorderBuffer *cache, ReorderBufferTXN *txn)
Definition: logical.c:663
void OutputPluginPrepareWrite(struct LogicalDecodingContext *ctx, bool last_write)
Definition: logical.c:523
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:739
#define StrNCpy(dst, src, len)
Definition: c.h:935
Definition: regguts.h:298
void FreeDecodingContext(LogicalDecodingContext *ctx)
Definition: logical.c:508
XLogRecPtr restart_lsn
Definition: slot.h:72
void LogicalIncreaseXminForSlot(XLogRecPtr current_lsn, TransactionId xmin)
Definition: logical.c:875
XLogRecPtr end_lsn
size_t Size
Definition: c.h:467
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:1122
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:1001
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:761
int errmsg(const char *fmt,...)
Definition: elog.c:822
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:536
LogicalOutputPluginWriterWrite write
Definition: logical.h:64
#define elog(elevel,...)
Definition: elog.h:228
StringInfo out
Definition: logical.h:70
#define errcontext
Definition: elog.h:183
#define NameStr(name)
Definition: c.h:616
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:831
int(* XLogPageReadCB)(XLogReaderState *xlogreader, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *readBuf)
Definition: xlogreader.h:52
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:584
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
static XLogRecPtr startptr
Definition: basebackup.c:117