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