1 /*-------------------------------------------------------------------------
5 * Infrastructure for building historic catalog snapshots based on contents
6 * of the WAL, for the purpose of decoding heapam.c style values in the
11 * We build snapshots which can *only* be used to read catalog contents and we
12 * do so by reading and interpreting the WAL stream. The aim is to build a
13 * snapshot that behaves the same as a freshly taken MVCC snapshot would have
14 * at the time the XLogRecord was generated.
16 * To build the snapshots we reuse the infrastructure built for Hot
17 * Standby. The in-memory snapshots we build look different than HS' because
18 * we have different needs. To successfully decode data from the WAL we only
19 * need to access catalog tables and (sys|rel|cat)cache, not the actual user
20 * tables since the data we decode is wholly contained in the WAL
21 * records. Also, our snapshots need to be different in comparison to normal
22 * MVCC ones because in contrast to those we cannot fully rely on the clog and
23 * pg_subtrans for information about committed transactions because they might
24 * commit in the future from the POV of the WAL entry we're currently
25 * decoding. This definition has the advantage that we only need to prevent
26 * removal of catalog rows, while normal table's rows can still be
27 * removed. This is achieved by using the replication slot mechanism.
29 * As the percentage of transactions modifying the catalog normally is fairly
30 * small in comparisons to ones only manipulating user data, we keep track of
31 * the committed catalog modifying ones inside (xmin, xmax) instead of keeping
32 * track of all running transactions like its done in a normal snapshot. Note
33 * that we're generally only looking at transactions that have acquired an
34 * xid. That is we keep a list of transactions between snapshot->(xmin, xmax)
35 * that we consider committed, everything else is considered aborted/in
36 * progress. That also allows us not to care about subtransactions before they
37 * have committed which means this modules, in contrast to HS, doesn't have to
38 * care about suboverflowed subtransactions and similar.
40 * One complexity of doing this is that to e.g. handle mixed DDL/DML
41 * transactions we need Snapshots that see intermediate versions of the
42 * catalog in a transaction. During normal operation this is achieved by using
43 * CommandIds/cmin/cmax. The problem with that however is that for space
44 * efficiency reasons only one value of that is stored
45 * (c.f. combocid.c). Since ComboCids are only available in memory we log
46 * additional information which allows us to get the original (cmin, cmax)
47 * pair during visibility checks. Check the reorderbuffer.c's comment above
48 * ResolveCminCmaxDuringDecoding() for details.
50 * To facilitate all this we need our own visibility routine, as the normal
51 * ones are optimized for different usecases.
53 * To replace the normal catalog snapshots with decoding ones use the
54 * SetupHistoricSnapshot() and TeardownHistoricSnapshot() functions.
58 * The snapbuild machinery is starting up in several stages, as illustrated
59 * by the following graph:
60 * +-------------------------+
61 * +----|SNAPBUILD_START |-------------+
62 * | +-------------------------+ |
65 * | running_xacts with running xacts |
69 * | +-------------------------+ v
70 * | |SNAPBUILD_FULL_SNAPSHOT |------------>|
71 * | +-------------------------+ |
72 * running_xacts | saved snapshot
73 * with zero xacts | at running_xacts's lsn
75 * | all running toplevel TXNs finished |
78 * | +-------------------------+ |
79 * +--->|SNAPBUILD_CONSISTENT |<------------+
80 * +-------------------------+
82 * Initially the machinery is in the START stage. When a xl_running_xacts
83 * record is read that is sufficiently new (above the safe xmin horizon),
84 * there's a state transation. If there were no running xacts when the
85 * runnign_xacts record was generated, we'll directly go into CONSISTENT
86 * state, otherwise we'll switch to the FULL_SNAPSHOT state. Having a full
87 * snapshot means that all transactions that start henceforth can be decoded
88 * in their entirety, but transactions that started previously can't. In
89 * FULL_SNAPSHOT we'll switch into CONSISTENT once all those previously
90 * running transactions have committed or aborted.
92 * Only transactions that commit after CONSISTENT state has been reached will
93 * be replayed, even though they might have started while still in
94 * FULL_SNAPSHOT. That ensures that we'll reach a point where no previous
95 * changes has been exported, but all the following ones will be. That point
96 * is a convenient point to initialize replication from, which is why we
97 * export a snapshot at that point, which *can* be used to read normal data.
99 * Copyright (c) 2012-2014, PostgreSQL Global Development Group
102 * src/backend/replication/snapbuild.c
104 *-------------------------------------------------------------------------
107 #include "postgres.h"
109 #include <sys/stat.h>
110 #include <sys/types.h>
113 #include "miscadmin.h"
115 #include "access/heapam_xlog.h"
116 #include "access/transam.h"
117 #include "access/xact.h"
119 #include "replication/logical.h"
120 #include "replication/reorderbuffer.h"
121 #include "replication/snapbuild.h"
123 #include "utils/builtins.h"
124 #include "utils/memutils.h"
125 #include "utils/snapshot.h"
126 #include "utils/snapmgr.h"
127 #include "utils/tqual.h"
129 #include "storage/block.h" /* debugging output */
130 #include "storage/fd.h"
131 #include "storage/lmgr.h"
132 #include "storage/proc.h"
133 #include "storage/procarray.h"
134 #include "storage/standby.h"
137 * This struct contains the current state of the snapshot building
138 * machinery. Besides a forward declaration in the header, it is not exposed
139 * to the public, so we can easily change it's contents.
143 /* how far are we along building our first full snapshot */
144 SnapBuildState state;
146 /* private memory context used to allocate memory for this module. */
147 MemoryContext context;
149 /* all transactions < than this have committed/aborted */
152 /* all transactions >= than this are uncommitted */
156 * Don't replay commits from an LSN <= this LSN. This can be set
157 * externally but it will also be advanced (never retreat) from within
160 XLogRecPtr transactions_after;
163 * Don't start decoding WAL until the "xl_running_xacts" information
164 * indicates there are no running xids with a xid smaller than this.
166 TransactionId initial_xmin_horizon;
169 * Snapshot that's valid to see the catalog state seen at this moment.
174 * LSN of the last location we are sure a snapshot has been serialized to.
176 XLogRecPtr last_serialized_snapshot;
179 * The reorderbuffer we need to update with usable snapshots et al.
181 ReorderBuffer *reorder;
184 * Information about initially running transactions
186 * When we start building a snapshot there already may be transactions in
187 * progress. Those are stored in running.xip. We don't have enough
188 * information about those to decode their contents, so until they are
189 * finished (xcnt=0) we cannot switch to a CONSISTENT state.
194 * As long as running.xcnt all XIDs < running.xmin and > running.xmax
195 * have to be checked whether they still are running.
200 size_t xcnt; /* number of used xip entries */
201 size_t xcnt_space; /* allocated size of xip */
202 TransactionId *xip; /* running xacts array, xidComparator-sorted */
206 * Array of transactions which could have catalog changes that committed
207 * between xmin and xmax.
211 /* number of committed transactions */
214 /* available space for committed transactions */
218 * Until we reach a CONSISTENT state, we record commits of all
219 * transactions, not just the catalog changing ones. Record when that
220 * changes so we know we cannot export a snapshot safely anymore.
222 bool includes_all_transactions;
225 * Array of committed transactions that have modified the catalog.
227 * As this array is frequently modified we do *not* keep it in
228 * xidComparator order. Instead we sort the array when building &
229 * distributing a snapshot.
231 * TODO: It's unclear whether that reasoning has much merit. Every
232 * time we add something here after becoming consistent will also
233 * require distributing a snapshot. Storing them sorted would
234 * potentially also make it easier to purge (but more complicated wrt
235 * wraparound?). Should be improved if sorting while building the
236 * snapshot shows up in profiles.
243 * Starting a transaction -- which we need to do while exporting a snapshot --
244 * removes knowledge about the previously used resowner, so we save it here.
246 ResourceOwner SavedResourceOwnerDuringExport = NULL;
247 bool ExportInProgress = false;
249 /* transaction state manipulation functions */
250 static void SnapBuildEndTxn(SnapBuild *builder, XLogRecPtr lsn, TransactionId xid);
252 /* ->running manipulation */
253 static bool SnapBuildTxnIsRunning(SnapBuild *builder, TransactionId xid);
255 /* ->committed manipulation */
256 static void SnapBuildPurgeCommittedTxn(SnapBuild *builder);
258 /* snapshot building/manipulation/distribution functions */
259 static Snapshot SnapBuildBuildSnapshot(SnapBuild *builder, TransactionId xid);
261 static void SnapBuildFreeSnapshot(Snapshot snap);
263 static void SnapBuildSnapIncRefcount(Snapshot snap);
265 static void SnapBuildDistributeNewCatalogSnapshot(SnapBuild *builder, XLogRecPtr lsn);
267 /* xlog reading helper functions for SnapBuildProcessRecord */
268 static bool SnapBuildFindSnapshot(SnapBuild *builder, XLogRecPtr lsn, xl_running_xacts *running);
270 /* serialization functions */
271 static void SnapBuildSerialize(SnapBuild *builder, XLogRecPtr lsn);
272 static bool SnapBuildRestore(SnapBuild *builder, XLogRecPtr lsn);
276 * Allocate a new snapshot builder.
278 * xmin_horizon is the xid >=which we can be sure no catalog rows have been
279 * removed, start_lsn is the LSN >= we want to replay commits.
282 AllocateSnapshotBuilder(ReorderBuffer *reorder,
283 TransactionId xmin_horizon,
284 XLogRecPtr start_lsn)
286 MemoryContext context;
287 MemoryContext oldcontext;
290 /* allocate memory in own context, to have better accountability */
291 context = AllocSetContextCreate(CurrentMemoryContext,
292 "snapshot builder context",
293 ALLOCSET_DEFAULT_MINSIZE,
294 ALLOCSET_DEFAULT_INITSIZE,
295 ALLOCSET_DEFAULT_MAXSIZE);
296 oldcontext = MemoryContextSwitchTo(context);
298 builder = palloc0(sizeof(SnapBuild));
300 builder->state = SNAPBUILD_START;
301 builder->context = context;
302 builder->reorder = reorder;
303 /* Other struct members initialized by zeroing via palloc0 above */
305 builder->committed.xcnt = 0;
306 builder->committed.xcnt_space = 128; /* arbitrary number */
307 builder->committed.xip =
308 palloc0(builder->committed.xcnt_space * sizeof(TransactionId));
309 builder->committed.includes_all_transactions = true;
310 builder->committed.xip =
311 palloc0(builder->committed.xcnt_space * sizeof(TransactionId));
312 builder->initial_xmin_horizon = xmin_horizon;
313 builder->transactions_after = start_lsn;
315 MemoryContextSwitchTo(oldcontext);
321 * Free a snapshot builder.
324 FreeSnapshotBuilder(SnapBuild *builder)
326 MemoryContext context = builder->context;
328 /* free snapshot explicitly, that contains some error checking */
329 if (builder->snapshot != NULL)
331 SnapBuildSnapDecRefcount(builder->snapshot);
332 builder->snapshot = NULL;
335 /* other resources are deallocated via memory context reset */
336 MemoryContextDelete(context);
340 * Free an unreferenced snapshot that has previously been built by us.
343 SnapBuildFreeSnapshot(Snapshot snap)
345 /* make sure we don't get passed an external snapshot */
346 Assert(snap->satisfies == HeapTupleSatisfiesHistoricMVCC);
348 /* make sure nobody modified our snapshot */
349 Assert(snap->curcid == FirstCommandId);
350 Assert(!snap->suboverflowed);
351 Assert(!snap->takenDuringRecovery);
352 Assert(snap->regd_count == 1);
354 /* slightly more likely, so it's checked even without c-asserts */
356 elog(ERROR, "cannot free a copied snapshot");
358 if (snap->active_count)
359 elog(ERROR, "cannot free an active snapshot");
365 * In which state of snapshot building are we?
368 SnapBuildCurrentState(SnapBuild *builder)
370 return builder->state;
374 * Should the contents of transaction ending at 'ptr' be decoded?
377 SnapBuildXactNeedsSkip(SnapBuild *builder, XLogRecPtr ptr)
379 return ptr <= builder->transactions_after;
383 * Increase refcount of a snapshot.
385 * This is used when handing out a snapshot to some external resource or when
386 * adding a Snapshot as builder->snapshot.
389 SnapBuildSnapIncRefcount(Snapshot snap)
391 snap->active_count++;
395 * Decrease refcount of a snapshot and free if the refcount reaches zero.
397 * Externally visible, so that external resources that have been handed an
398 * IncRef'ed Snapshot can adjust its refcount easily.
401 SnapBuildSnapDecRefcount(Snapshot snap)
403 /* make sure we don't get passed an external snapshot */
404 Assert(snap->satisfies == HeapTupleSatisfiesHistoricMVCC);
406 /* make sure nobody modified our snapshot */
407 Assert(snap->curcid == FirstCommandId);
408 Assert(!snap->suboverflowed);
409 Assert(!snap->takenDuringRecovery);
411 Assert(snap->regd_count == 1);
413 Assert(snap->active_count);
415 /* slightly more likely, so its checked even without casserts */
417 elog(ERROR, "cannot free a copied snapshot");
419 snap->active_count--;
420 if (!snap->active_count)
421 SnapBuildFreeSnapshot(snap);
425 * Build a new snapshot, based on currently committed catalog-modifying
428 * In-progress transactions with catalog access are *not* allowed to modify
429 * these snapshots; they have to copy them and fill in appropriate ->curcid
430 * and ->subxip/subxcnt values.
433 SnapBuildBuildSnapshot(SnapBuild *builder, TransactionId xid)
438 Assert(builder->state >= SNAPBUILD_FULL_SNAPSHOT);
440 ssize = sizeof(SnapshotData)
441 + sizeof(TransactionId) * builder->committed.xcnt
442 + sizeof(TransactionId) * 1 /* toplevel xid */ ;
444 snapshot = MemoryContextAllocZero(builder->context, ssize);
446 snapshot->satisfies = HeapTupleSatisfiesHistoricMVCC;
449 * We misuse the original meaning of SnapshotData's xip and subxip fields
450 * to make the more fitting for our needs.
452 * In the 'xip' array we store transactions that have to be treated as
453 * committed. Since we will only ever look at tuples from transactions
454 * that have modified the catalog its more efficient to store those few
455 * that exist between xmin and xmax (frequently there are none).
457 * Snapshots that are used in transactions that have modified the catalog
458 * also use the 'subxip' array to store their toplevel xid and all the
459 * subtransaction xids so we can recognize when we need to treat rows as
460 * visible that are not in xip but still need to be visible. Subxip only
461 * gets filled when the transaction is copied into the context of a
462 * catalog modifying transaction since we otherwise share a snapshot
463 * between transactions. As long as a txn hasn't modified the catalog it
464 * doesn't need to treat any uncommitted rows as visible, so there is no
465 * need for those xids.
467 * Both arrays are qsort'ed so that we can use bsearch() on them.
469 Assert(TransactionIdIsNormal(builder->xmin));
470 Assert(TransactionIdIsNormal(builder->xmax));
472 snapshot->xmin = builder->xmin;
473 snapshot->xmax = builder->xmax;
475 /* store all transactions to be treated as committed by this snapshot */
477 (TransactionId *) ((char *) snapshot + sizeof(SnapshotData));
478 snapshot->xcnt = builder->committed.xcnt;
479 memcpy(snapshot->xip,
480 builder->committed.xip,
481 builder->committed.xcnt * sizeof(TransactionId));
483 /* sort so we can bsearch() */
484 qsort(snapshot->xip, snapshot->xcnt, sizeof(TransactionId), xidComparator);
487 * Initially, subxip is empty, i.e. it's a snapshot to be used by
488 * transactions that don't modify the catalog. Will be filled by
489 * ReorderBufferCopySnap() if necessary.
491 snapshot->subxcnt = 0;
492 snapshot->subxip = NULL;
494 snapshot->suboverflowed = false;
495 snapshot->takenDuringRecovery = false;
496 snapshot->copied = false;
497 snapshot->curcid = FirstCommandId;
498 snapshot->active_count = 0;
499 snapshot->regd_count = 1; /* mark as registered so nobody frees it */
505 * Export a snapshot so it can be set in another session with SET TRANSACTION
508 * For that we need to start a transaction in the current backend as the
509 * importing side checks whether the source transaction is still open to make
510 * sure the xmin horizon hasn't advanced since then.
512 * After that we convert a locally built snapshot into the normal variant
513 * understood by HeapTupleSatisfiesMVCC et al.
516 SnapBuildExportSnapshot(SnapBuild *builder)
521 TransactionId *newxip;
524 if (builder->state != SNAPBUILD_CONSISTENT)
525 elog(ERROR, "cannot export a snapshot before reaching a consistent state");
527 if (!builder->committed.includes_all_transactions)
528 elog(ERROR, "cannot export a snapshot, not all transactions are monitored anymore");
530 /* so we don't overwrite the existing value */
531 if (TransactionIdIsValid(MyPgXact->xmin))
532 elog(ERROR, "cannot export a snapshot when MyPgXact->xmin already is valid");
534 if (IsTransactionOrTransactionBlock())
535 elog(ERROR, "cannot export a snapshot from within a transaction");
537 if (SavedResourceOwnerDuringExport)
538 elog(ERROR, "can only export one snapshot at a time");
540 SavedResourceOwnerDuringExport = CurrentResourceOwner;
541 ExportInProgress = true;
543 StartTransactionCommand();
545 Assert(!FirstSnapshotSet);
547 /* There doesn't seem to a nice API to set these */
548 XactIsoLevel = XACT_REPEATABLE_READ;
551 snap = SnapBuildBuildSnapshot(builder, GetTopTransactionId());
554 * We know that snap->xmin is alive, enforced by the logical xmin
555 * mechanism. Due to that we can do this without locks, we're only
556 * changing our own value.
558 MyPgXact->xmin = snap->xmin;
560 /* allocate in transaction context */
561 newxip = (TransactionId *)
562 palloc(sizeof(TransactionId) * GetMaxSnapshotXidCount());
565 * snapbuild.c builds transactions in an "inverted" manner, which means it
566 * stores committed transactions in ->xip, not ones in progress. Build a
567 * classical snapshot by marking all non-committed transactions as
568 * in-progress. This can be expensive.
570 for (xid = snap->xmin; NormalTransactionIdPrecedes(xid, snap->xmax);)
575 * Check whether transaction committed using the decoding snapshot
578 test = bsearch(&xid, snap->xip, snap->xcnt,
579 sizeof(TransactionId), xidComparator);
583 if (newxcnt >= GetMaxSnapshotXidCount())
584 elog(ERROR, "snapshot too large");
586 newxip[newxcnt++] = xid;
589 TransactionIdAdvance(xid);
592 snap->xcnt = newxcnt;
596 * now that we've built a plain snapshot, use the normal mechanisms for
599 snapname = ExportSnapshot(snap);
602 (errmsg("exported logical decoding snapshot: \"%s\" with %u xids",
603 snapname, snap->xcnt)));
608 * Reset a previously SnapBuildExportSnapshot()'ed snapshot if there is
609 * any. Aborts the previously started transaction and resets the resource
610 * owner back to it's original value.
613 SnapBuildClearExportedSnapshot()
615 /* nothing exported, thats the usual case */
616 if (!ExportInProgress)
619 if (!IsTransactionState())
620 elog(ERROR, "clearing exported snapshot in wrong transaction state");
622 /* make sure nothing could have ever happened */
623 AbortCurrentTransaction();
625 CurrentResourceOwner = SavedResourceOwnerDuringExport;
626 SavedResourceOwnerDuringExport = NULL;
627 ExportInProgress = false;
631 * Handle the effects of a single heap change, appropriate to the current state
632 * of the snapshot builder and returns whether changes made at (xid, lsn) can
636 SnapBuildProcessChange(SnapBuild *builder, TransactionId xid, XLogRecPtr lsn)
641 * We can't handle data in transactions if we haven't built a snapshot
642 * yet, so don't store them.
644 if (builder->state < SNAPBUILD_FULL_SNAPSHOT)
648 * No point in keeping track of changes in transactions that we don't have
649 * enough information about to decode. This means that they started before
650 * we got into the SNAPBUILD_FULL_SNAPSHOT state.
652 if (builder->state < SNAPBUILD_CONSISTENT &&
653 SnapBuildTxnIsRunning(builder, xid))
657 * If the reorderbuffer doesn't yet have a snapshot, add one now, it will
658 * be needed to decode the change we're currently processing.
660 is_old_tx = ReorderBufferIsXidKnown(builder->reorder, xid);
662 if (!is_old_tx || !ReorderBufferXidHasBaseSnapshot(builder->reorder, xid))
664 /* only build a new snapshot if we don't have a prebuilt one */
665 if (builder->snapshot == NULL)
667 builder->snapshot = SnapBuildBuildSnapshot(builder, xid);
668 /* inrease refcount for the snapshot builder */
669 SnapBuildSnapIncRefcount(builder->snapshot);
673 * Increase refcount for the transaction we're handing the snapshot
676 SnapBuildSnapIncRefcount(builder->snapshot);
677 ReorderBufferSetBaseSnapshot(builder->reorder, xid, lsn,
685 * Do CommandId/ComboCid handling after reading a xl_heap_new_cid record. This
686 * implies that a transaction has done some form of write to system catalogs.
689 SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid,
690 XLogRecPtr lsn, xl_heap_new_cid *xlrec)
695 * we only log new_cid's if a catalog tuple was modified, so mark
696 * the transaction as containing catalog modifications
698 ReorderBufferXidSetCatalogChanges(builder->reorder, xid,lsn);
700 ReorderBufferAddNewTupleCids(builder->reorder, xlrec->top_xid, lsn,
701 xlrec->target.node, xlrec->target.tid,
702 xlrec->cmin, xlrec->cmax,
705 /* figure out new command id */
706 if (xlrec->cmin != InvalidCommandId &&
707 xlrec->cmax != InvalidCommandId)
708 cid = Max(xlrec->cmin, xlrec->cmax);
709 else if (xlrec->cmax != InvalidCommandId)
711 else if (xlrec->cmin != InvalidCommandId)
715 cid = InvalidCommandId; /* silence compiler */
716 elog(ERROR, "xl_heap_new_cid record without a valid CommandId");
719 ReorderBufferAddNewCommandId(builder->reorder, xid, lsn, cid + 1);
723 * Check whether `xid` is currently 'running'.
725 * Running transactions in our parlance are transactions which we didn't
726 * observe from the start so we can't properly decode their contents. They
727 * only exist after we freshly started from an < CONSISTENT snapshot.
730 SnapBuildTxnIsRunning(SnapBuild *builder, TransactionId xid)
732 Assert(builder->state < SNAPBUILD_CONSISTENT);
733 Assert(TransactionIdIsNormal(builder->running.xmin));
734 Assert(TransactionIdIsNormal(builder->running.xmax));
736 if (builder->running.xcnt &&
737 NormalTransactionIdFollows(xid, builder->running.xmin) &&
738 NormalTransactionIdPrecedes(xid, builder->running.xmax))
740 TransactionId *search =
741 bsearch(&xid, builder->running.xip, builder->running.xcnt_space,
742 sizeof(TransactionId), xidComparator);
746 Assert(*search == xid);
755 * Add a new Snapshot to all transactions we're decoding that currently are
756 * in-progress so they can see new catalog contents made by the transaction
757 * that just committed. This is necessary because those in-progress
758 * transactions will use the new catalog's contents from here on (at the very
759 * least everything they do needs to be compatible with newer catalog
763 SnapBuildDistributeNewCatalogSnapshot(SnapBuild *builder, XLogRecPtr lsn)
766 ReorderBufferTXN *txn;
769 * Iterate through all toplevel transactions. This can include
770 * subtransactions which we just don't yet know to be that, but that's
771 * fine, they will just get an unneccesary snapshot queued.
773 dlist_foreach(txn_i, &builder->reorder->toplevel_by_lsn)
775 txn = dlist_container(ReorderBufferTXN, node, txn_i.cur);
777 Assert(TransactionIdIsValid(txn->xid));
780 * If we don't have a base snapshot yet, there are no changes in this
781 * transaction which in turn implies we don't yet need a snapshot at
782 * all. We'll add a snapshot when the first change gets queued.
784 * NB: This works correctly even for subtransactions because
785 * ReorderBufferCommitChild() takes care to pass the parent the base
786 * snapshot, and while iterating the changequeue we'll get the change
789 if (!ReorderBufferXidHasBaseSnapshot(builder->reorder, txn->xid))
792 elog(DEBUG2, "adding a new snapshot to %u at %X/%X",
793 txn->xid, (uint32) (lsn >> 32), (uint32) lsn);
796 * increase the snapshot's refcount for the transaction we are handing
799 SnapBuildSnapIncRefcount(builder->snapshot);
800 ReorderBufferAddSnapshot(builder->reorder, txn->xid, lsn,
806 * Keep track of a new catalog changing transaction that has committed.
809 SnapBuildAddCommittedTxn(SnapBuild *builder, TransactionId xid)
811 Assert(TransactionIdIsValid(xid));
813 if (builder->committed.xcnt == builder->committed.xcnt_space)
815 builder->committed.xcnt_space = builder->committed.xcnt_space * 2 + 1;
817 elog(DEBUG1, "increasing space for committed transactions to %u",
818 (uint32) builder->committed.xcnt_space);
820 builder->committed.xip = repalloc(builder->committed.xip,
821 builder->committed.xcnt_space * sizeof(TransactionId));
825 * TODO: It might make sense to keep the array sorted here instead of
826 * doing it every time we build a new snapshot. On the other hand this
827 * gets called repeatedly when a transaction with subtransactions commits.
829 builder->committed.xip[builder->committed.xcnt++] = xid;
833 * Remove knowledge about transactions we treat as committed that are smaller
834 * than ->xmin. Those won't ever get checked via the ->commited array but via
835 * the clog machinery, so we don't need to waste memory on them.
838 SnapBuildPurgeCommittedTxn(SnapBuild *builder)
841 TransactionId *workspace;
842 int surviving_xids = 0;
845 if (!TransactionIdIsNormal(builder->xmin))
848 /* TODO: Neater algorithm than just copying and iterating? */
850 MemoryContextAlloc(builder->context,
851 builder->committed.xcnt * sizeof(TransactionId));
853 /* copy xids that still are interesting to workspace */
854 for (off = 0; off < builder->committed.xcnt; off++)
856 if (NormalTransactionIdPrecedes(builder->committed.xip[off],
860 workspace[surviving_xids++] = builder->committed.xip[off];
863 /* copy workspace back to persistent state */
864 memcpy(builder->committed.xip, workspace,
865 surviving_xids * sizeof(TransactionId));
867 elog(DEBUG3, "purged committed transactions from %u to %u, xmin: %u, xmax: %u",
868 (uint32) builder->committed.xcnt, (uint32) surviving_xids,
869 builder->xmin, builder->xmax);
870 builder->committed.xcnt = surviving_xids;
876 * Common logic for SnapBuildAbortTxn and SnapBuildCommitTxn dealing with
877 * keeping track of the amount of running transactions.
880 SnapBuildEndTxn(SnapBuild *builder, XLogRecPtr lsn, TransactionId xid)
882 if (builder->state == SNAPBUILD_CONSISTENT)
886 * NB: This handles subtransactions correctly even if we started from
887 * suboverflowed xl_running_xacts because we only keep track of toplevel
888 * transactions. Since the latter are always are allocated before their
889 * subxids and since they end at the same time it's sufficient to deal
892 if (SnapBuildTxnIsRunning(builder, xid))
894 Assert(builder->running.xcnt > 0);
896 if (!--builder->running.xcnt)
899 * None of the originally running transaction is running anymore,
900 * so our incrementaly built snapshot now is consistent.
903 (errmsg("logical decoding found consistent point at %X/%X",
904 (uint32)(lsn >> 32), (uint32)lsn),
905 errdetail("xid %u finished, no running transactions anymore",
907 builder->state = SNAPBUILD_CONSISTENT;
913 * Abort a transaction, throw away all state we kept.
916 SnapBuildAbortTxn(SnapBuild *builder, XLogRecPtr lsn,
918 int nsubxacts, TransactionId *subxacts)
922 for (i = 0; i < nsubxacts; i++)
924 TransactionId subxid = subxacts[i];
926 SnapBuildEndTxn(builder, lsn, subxid);
929 SnapBuildEndTxn(builder, lsn, xid);
933 * Handle everything that needs to be done when a transaction commits
936 SnapBuildCommitTxn(SnapBuild *builder, XLogRecPtr lsn, TransactionId xid,
937 int nsubxacts, TransactionId *subxacts)
941 bool forced_timetravel = false;
942 bool sub_needs_timetravel = false;
943 bool top_needs_timetravel = false;
945 TransactionId xmax = xid;
948 * If we couldn't observe every change of a transaction because it was
949 * already running at the point we started to observe we have to assume it
950 * made catalog changes.
952 * This has the positive benefit that we afterwards have enough
953 * information to build an exportable snapshot that's usable by pg_dump et
956 if (builder->state < SNAPBUILD_CONSISTENT)
958 /* ensure that only commits after this are getting replayed */
959 if (builder->transactions_after < lsn)
960 builder->transactions_after = lsn;
963 * We could avoid treating !SnapBuildTxnIsRunning transactions as
964 * timetravel ones, but we want to be able to export a snapshot when
965 * we reached consistency.
967 forced_timetravel = true;
968 elog(DEBUG1, "forced to assume catalog changes for xid %u because it was running to early", xid);
971 for (nxact = 0; nxact < nsubxacts; nxact++)
973 TransactionId subxid = subxacts[nxact];
976 * make sure txn is not tracked in running txn's anymore, switch state
978 SnapBuildEndTxn(builder, lsn, subxid);
981 * If we're forcing timetravel we also need visibility information
982 * about subtransaction, so keep track of subtransaction's state.
984 if (forced_timetravel)
986 SnapBuildAddCommittedTxn(builder, subxid);
987 if (NormalTransactionIdFollows(subxid, xmax))
992 * Add subtransaction to base snapshot if it DDL, we don't distinguish
993 * to toplevel transactions there.
995 else if (ReorderBufferXidHasCatalogChanges(builder->reorder, subxid))
997 sub_needs_timetravel = true;
999 elog(DEBUG1, "found subtransaction %u:%u with catalog changes.",
1002 SnapBuildAddCommittedTxn(builder, subxid);
1004 if (NormalTransactionIdFollows(subxid, xmax))
1010 * Make sure toplevel txn is not tracked in running txn's anymore, switch
1011 * state to consistent if possible.
1013 SnapBuildEndTxn(builder, lsn, xid);
1015 if (forced_timetravel)
1017 elog(DEBUG2, "forced transaction %u to do timetravel.", xid);
1019 SnapBuildAddCommittedTxn(builder, xid);
1021 /* add toplevel transaction to base snapshot */
1022 else if (ReorderBufferXidHasCatalogChanges(builder->reorder, xid))
1024 elog(DEBUG2, "found top level transaction %u, with catalog changes!",
1027 top_needs_timetravel = true;
1028 SnapBuildAddCommittedTxn(builder, xid);
1030 else if (sub_needs_timetravel)
1032 /* mark toplevel txn as timetravel as well */
1033 SnapBuildAddCommittedTxn(builder, xid);
1036 /* if there's any reason to build a historic snapshot, to so now */
1037 if (forced_timetravel || top_needs_timetravel || sub_needs_timetravel)
1040 * Adjust xmax of the snapshot builder, we only do that for committed,
1041 * catalog modifying, transactions, everything else isn't interesting
1042 * for us since we'll never look at the respective rows.
1044 if (!TransactionIdIsValid(builder->xmax) ||
1045 TransactionIdFollowsOrEquals(xmax, builder->xmax))
1047 builder->xmax = xmax;
1048 TransactionIdAdvance(builder->xmax);
1052 * If we haven't built a complete snapshot yet there's no need to hand
1053 * it out, it wouldn't (and couldn't) be used anyway.
1055 if (builder->state < SNAPBUILD_FULL_SNAPSHOT)
1059 * Decrease the snapshot builder's refcount of the old snapshot, note
1060 * that it still will be used if it has been handed out to the
1061 * reorderbuffer earlier.
1063 if (builder->snapshot)
1064 SnapBuildSnapDecRefcount(builder->snapshot);
1066 builder->snapshot = SnapBuildBuildSnapshot(builder, xid);
1068 /* we might need to execute invalidations, add snapshot */
1069 if (!ReorderBufferXidHasBaseSnapshot(builder->reorder, xid))
1071 SnapBuildSnapIncRefcount(builder->snapshot);
1072 ReorderBufferSetBaseSnapshot(builder->reorder, xid, lsn,
1076 /* refcount of the snapshot builder for the new snapshot */
1077 SnapBuildSnapIncRefcount(builder->snapshot);
1079 /* add a new SnapshotNow to all currently running transactions */
1080 SnapBuildDistributeNewCatalogSnapshot(builder, lsn);
1084 /* record that we cannot export a general snapshot anymore */
1085 builder->committed.includes_all_transactions = false;
1090 /* -----------------------------------
1091 * Snapshot building functions dealing with xlog records
1092 * -----------------------------------
1096 * Process a running xacts record, and use it's information to first build a
1097 * historic snapshot and later to release resources that aren't needed
1101 SnapBuildProcessRunningXacts(SnapBuild *builder, XLogRecPtr lsn, xl_running_xacts *running)
1103 ReorderBufferTXN *txn;
1106 * If we're not consistent yet, inspect the record to see whether it
1107 * allows to get closer to being consistent. If we are consistent, dump
1108 * our snapshot so others or we, after a restart, can use it.
1110 if (builder->state < SNAPBUILD_CONSISTENT)
1112 /* returns false if there's no point in performing cleanup just yet */
1113 if (!SnapBuildFindSnapshot(builder, lsn, running))
1117 SnapBuildSerialize(builder, lsn);
1120 * Update range of interesting xids base don the running xacts
1121 * information. We don't increase ->xmax using it, because once we are in
1122 * a consistent state we can do that ourselves and much more efficiently
1123 * so, because we only need to do it for catalog transactions since we
1124 * only ever look at those.
1126 * NB: Because of that xmax can be lower than xmin, because we only
1127 * increase xmax when a catalog modifying transaction commits. While odd
1128 * looking, its correct and actually more efficient this way since we hit
1129 * fast paths in tqual.c.
1131 builder->xmin = running->oldestRunningXid;
1133 /* Remove transactions we don't need to keep track off anymore */
1134 SnapBuildPurgeCommittedTxn(builder);
1136 elog(DEBUG3, "xmin: %u, xmax: %u, oldestrunning: %u",
1137 builder->xmin, builder->xmax,
1138 running->oldestRunningXid);
1141 * Inrease shared memory limits, so vacuum can work on tuples we prevented
1142 * from being pruned till now.
1144 LogicalIncreaseXminForSlot(lsn, running->oldestRunningXid);
1147 * Also tell the slot where we can restart decoding from. We don't want to
1148 * do that after every commit because changing that implies an fsync of
1149 * the logical slot's state file, so we only do it every time we see a
1150 * running xacts record.
1152 * Do so by looking for the oldest in progress transaction (determined by
1153 * the first LSN of any of its relevant records). Every transaction
1154 * remembers the last location we stored the snapshot to disk before its
1155 * beginning. That point is where we can restart from.
1159 * Can't know about a serialized snapshot's location if we're not
1162 if (builder->state < SNAPBUILD_CONSISTENT)
1165 txn = ReorderBufferGetOldestTXN(builder->reorder);
1168 * oldest ongoing txn might have started when we didn't yet serialize
1169 * anything because we hadn't reached a consistent state yet.
1171 if (txn != NULL && txn->restart_decoding_lsn != InvalidXLogRecPtr)
1172 LogicalIncreaseRestartDecodingForSlot(lsn, txn->restart_decoding_lsn);
1174 * No in-progress transaction, can reuse the last serialized snapshot if
1177 else if (txn == NULL &&
1178 builder->reorder->current_restart_decoding_lsn != InvalidXLogRecPtr &&
1179 builder->last_serialized_snapshot != InvalidXLogRecPtr)
1180 LogicalIncreaseRestartDecodingForSlot(lsn,
1181 builder->last_serialized_snapshot);
1186 * Build the start of a snapshot that's capable of decoding the catalog.
1188 * Helper function for SnapBuildProcessRunningXacts() while we're not yet
1191 * Returns true if there is a point in performing internal maintenance/cleanup
1192 * using the xl_running_xacts record.
1195 SnapBuildFindSnapshot(SnapBuild *builder, XLogRecPtr lsn, xl_running_xacts *running)
1198 * Build catalog decoding snapshot incrementally using information about
1199 * the currently running transactions. There are several ways to do that:
1201 * a) There were no running transactions when the xl_running_xacts record
1202 * was inserted, jump to CONSISTENT immediately. We might find such a
1203 * state we were waiting for b) and c).
1205 * b) Wait for all toplevel transactions that were running to end. We
1206 * simply track the number of in-progress toplevel transactions and
1207 * lower it whenever one commits or aborts. When that number
1208 * (builder->running.xcnt) reaches zero, we can go from FULL_SNAPSHOT
1210 * NB: We need to search running.xip when seeing a transaction's end to
1211 * make sure it's a toplevel transaction and it's been one of the
1212 * intially running ones.
1213 * Interestingly, in contrast to HS, this allows us not to care about
1214 * subtransactions - and by extension suboverflowed xl_running_xacts -
1217 * c) This (in a previous run) or another decoding slot serialized a
1218 * snapshot to disk that we can use.
1223 * xl_running_xact record is older than what we can use, we might not have
1224 * all necessary catalog rows anymore.
1226 if (TransactionIdIsNormal(builder->initial_xmin_horizon) &&
1227 NormalTransactionIdPrecedes(running->oldestRunningXid,
1228 builder->initial_xmin_horizon))
1231 (errmsg("skipping snapshot at %X/%X while building logical decoding snapshot, xmin horizon too low",
1232 (uint32) (lsn >> 32), (uint32) lsn),
1233 errdetail("initial xmin horizon of %u vs the snapshot's %u",
1234 builder->initial_xmin_horizon, running->oldestRunningXid)));
1239 * a) No transaction were running, we can jump to consistent.
1241 * NB: We might have already started to incrementally assemble a snapshot,
1242 * so we need to be careful to deal with that.
1244 if (running->xcnt == 0)
1246 if (builder->transactions_after == InvalidXLogRecPtr ||
1247 builder->transactions_after < lsn)
1248 builder->transactions_after = lsn;
1250 builder->xmin = running->oldestRunningXid;
1251 builder->xmax = running->latestCompletedXid;
1252 TransactionIdAdvance(builder->xmax);
1254 Assert(TransactionIdIsNormal(builder->xmin));
1255 Assert(TransactionIdIsNormal(builder->xmax));
1257 /* no transactions running now */
1258 builder->running.xcnt = 0;
1259 builder->running.xmin = InvalidTransactionId;
1260 builder->running.xmax = InvalidTransactionId;
1262 builder->state = SNAPBUILD_CONSISTENT;
1265 (errmsg("logical decoding found consistent point at %X/%X",
1266 (uint32)(lsn >> 32), (uint32)lsn),
1267 errdetail("running xacts with xcnt == 0")));
1271 /* c) valid on disk state */
1272 else if (SnapBuildRestore(builder, lsn))
1274 /* there won't be any state to cleanup */
1278 * b) first encounter of a useable xl_running_xacts record. If we had
1279 * found one earlier we would either track running transactions
1280 * (i.e. builder->running.xcnt != 0) or be consistent (this function
1281 * wouldn't get called).
1283 else if (!builder->running.xcnt)
1288 * We only care about toplevel xids as those are the ones we
1289 * definitely see in the wal stream. As snapbuild.c tracks committed
1290 * instead of running transactions we don't need to know anything
1291 * about uncommitted subtransactions.
1293 builder->xmin = running->oldestRunningXid;
1294 builder->xmax = running->latestCompletedXid;
1295 TransactionIdAdvance(builder->xmax);
1297 /* so we can safely use the faster comparisons */
1298 Assert(TransactionIdIsNormal(builder->xmin));
1299 Assert(TransactionIdIsNormal(builder->xmax));
1301 builder->running.xcnt = running->xcnt;
1302 builder->running.xcnt_space = running->xcnt;
1303 builder->running.xip =
1304 MemoryContextAlloc(builder->context,
1305 builder->running.xcnt * sizeof(TransactionId));
1306 memcpy(builder->running.xip, running->xids,
1307 builder->running.xcnt * sizeof(TransactionId));
1309 /* sort so we can do a binary search */
1310 qsort(builder->running.xip, builder->running.xcnt,
1311 sizeof(TransactionId), xidComparator);
1313 builder->running.xmin = builder->running.xip[0];
1314 builder->running.xmax = builder->running.xip[running->xcnt - 1];
1316 /* makes comparisons cheaper later */
1317 TransactionIdRetreat(builder->running.xmin);
1318 TransactionIdAdvance(builder->running.xmax);
1320 builder->state = SNAPBUILD_FULL_SNAPSHOT;
1323 (errmsg("logical decoding found initial starting point at %X/%X",
1324 (uint32)(lsn >> 32), (uint32)lsn),
1325 errdetail("%u xacts need to finish", (uint32) builder->running.xcnt)));
1328 * Iterate through all xids, wait for them to finish.
1330 * This isn't required for the correctness of decoding, but to allow
1331 * isolationtester to notice that we're currently waiting for
1334 for(off = 0; off < builder->running.xcnt; off++)
1336 TransactionId xid = builder->running.xip[off];
1339 * Upper layers should prevent that we ever need to wait on
1340 * ourselves. Check anyway, since failing to do so would either
1341 * result in an endless wait or an Assert() failure.
1343 if (TransactionIdIsCurrentTransactionId(xid))
1344 elog(ERROR, "waiting for ourselves");
1346 XactLockTableWait(xid);
1349 /* nothing could have built up so far, so don't perform cleanup */
1354 * We already started to track running xacts and need to wait for all
1355 * in-progress ones to finish. We fall through to the normal processing of
1356 * records so incremental cleanup can be performed.
1362 /* -----------------------------------
1363 * Snapshot serialization support
1364 * -----------------------------------
1368 * We store current state of struct SnapBuild on disk in the following manner:
1370 * struct SnapBuildOnDisk;
1371 * TransactionId * running.xcnt_space;
1372 * TransactionId * committed.xcnt; (*not xcnt_space*)
1375 typedef struct SnapBuildOnDisk
1377 /* first part of this struct needs to be version independent */
1379 /* data not covered by checksum */
1383 /* data covered by checksum */
1385 /* version, in case we want to support pg_upgrade */
1387 /* how large is the on disk data, excluding the constant sized part */
1390 /* version dependent part */
1393 /* variable amount of TransactionIds follows */
1396 #define SnapBuildOnDiskConstantSize \
1397 offsetof(SnapBuildOnDisk, builder)
1398 #define SnapBuildOnDiskNotChecksummedSize \
1399 offsetof(SnapBuildOnDisk, version)
1401 #define SNAPBUILD_MAGIC 0x51A1E001
1402 #define SNAPBUILD_VERSION 1
1405 * Store/Load a snapshot from disk, depending on the snapshot builder's state.
1407 * Supposed to be used by external (i.e. not snapbuild.c) code that just reada
1408 * record that's a potential location for a serialized snapshot.
1411 SnapBuildSerializationPoint(SnapBuild *builder, XLogRecPtr lsn)
1413 if (builder->state < SNAPBUILD_CONSISTENT)
1414 SnapBuildRestore(builder, lsn);
1416 SnapBuildSerialize(builder, lsn);
1420 * Serialize the snapshot 'builder' at the location 'lsn' if it hasn't already
1421 * been done by another decoding process.
1424 SnapBuildSerialize(SnapBuild *builder, XLogRecPtr lsn)
1427 SnapBuildOnDisk *ondisk;
1430 char tmppath[MAXPGPATH];
1431 char path[MAXPGPATH];
1433 struct stat stat_buf;
1436 Assert(lsn != InvalidXLogRecPtr);
1437 Assert(builder->last_serialized_snapshot == InvalidXLogRecPtr ||
1438 builder->last_serialized_snapshot <= lsn);
1441 * no point in serializing if we cannot continue to work immediately after
1442 * restoring the snapshot
1444 if (builder->state < SNAPBUILD_CONSISTENT)
1448 * We identify snapshots by the LSN they are valid for. We don't need to
1449 * include timelines in the name as each LSN maps to exactly one timeline
1450 * unless the user used pg_resetxlog or similar. If a user did so, there's
1451 * no hope continuing to decode anyway.
1453 sprintf(path, "pg_llog/snapshots/%X-%X.snap",
1454 (uint32) (lsn >> 32), (uint32) lsn);
1457 * first check whether some other backend already has written the snapshot
1458 * for this LSN. It's perfectly fine if there's none, so we accept ENOENT
1459 * as a valid state. Everything else is an unexpected error.
1461 ret = stat(path, &stat_buf);
1463 if (ret != 0 && errno != ENOENT)
1465 (errmsg("could not stat file \"%s\": %m", path)));
1470 * somebody else has already serialized to this point, don't overwrite
1471 * but remember location, so we don't need to read old data again.
1473 * To be sure it has been synced to disk after the rename() from the
1474 * tempfile filename to the real filename, we just repeat the
1475 * fsync. That ought to be cheap because in most scenarios it should
1476 * already be safely on disk.
1478 fsync_fname(path, false);
1479 fsync_fname("pg_llog/snapshots", true);
1481 builder->last_serialized_snapshot = lsn;
1486 * there is an obvious race condition here between the time we stat(2) the
1487 * file and us writing the file. But we rename the file into place
1488 * atomically and all files created need to contain the same data anyway,
1489 * so this is perfectly fine, although a bit of a resource waste. Locking
1490 * seems like pointless complication.
1492 elog(DEBUG1, "serializing snapshot to %s", path);
1494 /* to make sure only we will write to this tempfile, include pid */
1495 sprintf(tmppath, "pg_llog/snapshots/%X-%X.snap.%u.tmp",
1496 (uint32) (lsn >> 32), (uint32) lsn, MyProcPid);
1499 * Unlink temporary file if it already exists, needs to have been before a
1500 * crash/error since we won't enter this function twice from within a
1501 * single decoding slot/backend and the temporary file contains the pid of
1502 * the current process.
1504 if (unlink(tmppath) != 0 && errno != ENOENT)
1506 (errcode_for_file_access(),
1507 errmsg("could not unlink file \"%s\": %m", path)));
1509 needed_length = sizeof(SnapBuildOnDisk) +
1510 sizeof(TransactionId) * builder->running.xcnt_space +
1511 sizeof(TransactionId) * builder->committed.xcnt;
1513 ondisk_c = MemoryContextAllocZero(builder->context, needed_length);
1514 ondisk = (SnapBuildOnDisk *) ondisk_c;
1515 ondisk->magic = SNAPBUILD_MAGIC;
1516 ondisk->version = SNAPBUILD_VERSION;
1517 ondisk->length = needed_length;
1518 INIT_CRC32(ondisk->checksum);
1519 COMP_CRC32(ondisk->checksum,
1520 ((char *) ondisk) + SnapBuildOnDiskNotChecksummedSize,
1521 SnapBuildOnDiskConstantSize - SnapBuildOnDiskNotChecksummedSize);
1522 ondisk_c += sizeof(SnapBuildOnDisk);
1524 memcpy(&ondisk->builder, builder, sizeof(SnapBuild));
1525 /* NULL-ify memory-only data */
1526 ondisk->builder.context = NULL;
1527 ondisk->builder.snapshot = NULL;
1528 ondisk->builder.reorder = NULL;
1529 ondisk->builder.running.xip = NULL;
1530 ondisk->builder.committed.xip = NULL;
1532 COMP_CRC32(ondisk->checksum,
1536 /* copy running xacts */
1537 sz = sizeof(TransactionId) * builder->running.xcnt_space;
1538 memcpy(ondisk_c, builder->running.xip, sz);
1539 COMP_CRC32(ondisk->checksum, ondisk_c, sz);
1542 /* copy committed xacts */
1543 sz = sizeof(TransactionId) * builder->committed.xcnt;
1544 memcpy(ondisk_c, builder->committed.xip, sz);
1545 COMP_CRC32(ondisk->checksum, ondisk_c, sz);
1548 /* we have valid data now, open tempfile and write it there */
1549 fd = OpenTransientFile(tmppath,
1550 O_CREAT | O_EXCL | O_WRONLY | PG_BINARY,
1554 (errmsg("could not open file \"%s\": %m", path)));
1556 if ((write(fd, ondisk, needed_length)) != needed_length)
1558 CloseTransientFile(fd);
1560 (errcode_for_file_access(),
1561 errmsg("could not write to file \"%s\": %m", tmppath)));
1565 * fsync the file before renaming so that even if we crash after this we
1566 * have either a fully valid file or nothing.
1568 * TODO: Do the fsync() via checkpoints/restartpoints, doing it here has
1569 * some noticeable overhead since it's performed synchronously during
1572 if (pg_fsync(fd) != 0)
1574 CloseTransientFile(fd);
1576 (errcode_for_file_access(),
1577 errmsg("could not fsync file \"%s\": %m", tmppath)));
1579 CloseTransientFile(fd);
1581 fsync_fname("pg_llog/snapshots", true);
1584 * We may overwrite the work from some other backend, but that's ok, our
1585 * snapshot is valid as well, we'll just have done some superflous work.
1587 if (rename(tmppath, path) != 0)
1590 (errcode_for_file_access(),
1591 errmsg("could not rename file \"%s\" to \"%s\": %m",
1595 /* make sure we persist */
1596 fsync_fname(path, false);
1597 fsync_fname("pg_llog/snapshots", true);
1600 * Now there's no way we can loose the dumped state anymore, remember
1601 * this as a serialization point.
1603 builder->last_serialized_snapshot = lsn;
1606 ReorderBufferSetRestartPoint(builder->reorder,
1607 builder->last_serialized_snapshot);
1611 * Restore a snapshot into 'builder' if previously one has been stored at the
1612 * location indicated by 'lsn'. Returns true if successful, false otherwise.
1615 SnapBuildRestore(SnapBuild *builder, XLogRecPtr lsn)
1617 SnapBuildOnDisk ondisk;
1619 char path[MAXPGPATH];
1624 /* no point in loading a snapshot if we're already there */
1625 if (builder->state == SNAPBUILD_CONSISTENT)
1628 sprintf(path, "pg_llog/snapshots/%X-%X.snap",
1629 (uint32) (lsn >> 32), (uint32) lsn);
1631 fd = OpenTransientFile(path, O_RDONLY | PG_BINARY, 0);
1633 if (fd < 0 && errno == ENOENT)
1637 (errcode_for_file_access(),
1638 errmsg("could not open file \"%s\": %m", path)));
1641 * Make sure the snapshot had been stored safely to disk, that's normally
1643 * Note that we do not need PANIC here, nobody will be able to use the
1644 * slot without fsyncing, and saving it won't suceed without an fsync()
1648 fsync_fname(path, false);
1649 fsync_fname("pg_llog/snapshots", true);
1652 /* read statically sized portion of snapshot */
1653 readBytes = read(fd, &ondisk, SnapBuildOnDiskConstantSize);
1654 if (readBytes != SnapBuildOnDiskConstantSize)
1656 CloseTransientFile(fd);
1658 (errcode_for_file_access(),
1659 errmsg("could not read file \"%s\", read %d of %d: %m",
1660 path, readBytes, (int) SnapBuildOnDiskConstantSize)));
1663 if (ondisk.magic != SNAPBUILD_MAGIC)
1665 (errmsg("snapbuild state file \"%s\" has wrong magic %u instead of %u",
1666 path, ondisk.magic, SNAPBUILD_MAGIC)));
1668 if (ondisk.version != SNAPBUILD_VERSION)
1670 (errmsg("snapbuild state file \"%s\" has unsupported version %u instead of %u",
1671 path, ondisk.version, SNAPBUILD_VERSION)));
1673 INIT_CRC32(checksum);
1674 COMP_CRC32(checksum,
1675 ((char *) &ondisk) + SnapBuildOnDiskNotChecksummedSize,
1676 SnapBuildOnDiskConstantSize - SnapBuildOnDiskNotChecksummedSize);
1678 /* read SnapBuild */
1679 readBytes = read(fd, &ondisk.builder, sizeof(SnapBuild));
1680 if (readBytes != sizeof(SnapBuild))
1682 CloseTransientFile(fd);
1684 (errcode_for_file_access(),
1685 errmsg("could not read file \"%s\", read %d of %d: %m",
1686 path, readBytes, (int) sizeof(SnapBuild))));
1688 COMP_CRC32(checksum, &ondisk.builder, sizeof(SnapBuild));
1690 /* restore running xacts information */
1691 sz = sizeof(TransactionId) * ondisk.builder.running.xcnt_space;
1692 ondisk.builder.running.xip = MemoryContextAlloc(builder->context, sz);
1693 readBytes = read(fd, ondisk.builder.running.xip, sz);
1694 if (readBytes != sz)
1696 CloseTransientFile(fd);
1698 (errcode_for_file_access(),
1699 errmsg("could not read file \"%s\", read %d of %d: %m",
1700 path, readBytes, (int) sz)));
1702 COMP_CRC32(checksum, ondisk.builder.running.xip, sz);
1704 /* restore committed xacts information */
1705 sz = sizeof(TransactionId) * ondisk.builder.committed.xcnt;
1706 ondisk.builder.committed.xip = MemoryContextAlloc(builder->context, sz);
1707 readBytes = read(fd, ondisk.builder.committed.xip, sz);
1708 if (readBytes != sz)
1710 CloseTransientFile(fd);
1712 (errcode_for_file_access(),
1713 errmsg("could not read file \"%s\", read %d of %d: %m",
1714 path, readBytes, (int) sz)));
1716 COMP_CRC32(checksum, ondisk.builder.committed.xip, sz);
1718 CloseTransientFile(fd);
1720 /* verify checksum of what we've read */
1721 if (!EQ_CRC32(checksum, ondisk.checksum))
1723 (errcode_for_file_access(),
1724 errmsg("snapbuild state file %s: checksum mismatch, is %u, should be %u",
1725 path, checksum, ondisk.checksum)));
1728 * ok, we now have a sensible snapshot here, figure out if it has more
1729 * information than we have.
1733 * We are only interested in consistent snapshots for now, comparing
1734 * whether one imcomplete snapshot is more "advanced" seems to be
1735 * unnecessarily complex.
1737 if (ondisk.builder.state < SNAPBUILD_CONSISTENT)
1738 goto snapshot_not_interesting;
1741 * Don't use a snapshot that requires an xmin that we cannot guarantee to
1744 if (TransactionIdPrecedes(ondisk.builder.xmin, builder->initial_xmin_horizon))
1745 goto snapshot_not_interesting;
1748 /* ok, we think the snapshot is sensible, copy over everything important */
1749 builder->xmin = ondisk.builder.xmin;
1750 builder->xmax = ondisk.builder.xmax;
1751 builder->state = ondisk.builder.state;
1753 builder->committed.xcnt = ondisk.builder.committed.xcnt;
1754 /* We only allocated/stored xcnt, not xcnt_space xids ! */
1755 /* don't overwrite preallocated xip, if we don't have anything here */
1756 if (builder->committed.xcnt > 0)
1758 pfree(builder->committed.xip);
1759 builder->committed.xcnt_space = ondisk.builder.committed.xcnt;
1760 builder->committed.xip = ondisk.builder.committed.xip;
1762 ondisk.builder.committed.xip = NULL;
1764 builder->running.xcnt = ondisk.builder.committed.xcnt;
1765 if (builder->running.xip)
1766 pfree(builder->running.xip);
1767 builder->running.xcnt_space = ondisk.builder.committed.xcnt_space;
1768 builder->running.xip = ondisk.builder.running.xip;
1770 /* our snapshot is not interesting anymore, build a new one */
1771 if (builder->snapshot != NULL)
1773 SnapBuildSnapDecRefcount(builder->snapshot);
1775 builder->snapshot = SnapBuildBuildSnapshot(builder, InvalidTransactionId);
1776 SnapBuildSnapIncRefcount(builder->snapshot);
1778 ReorderBufferSetRestartPoint(builder->reorder, lsn);
1780 Assert(builder->state == SNAPBUILD_CONSISTENT);
1783 (errmsg("logical decoding found consistent point at %X/%X",
1784 (uint32)(lsn >> 32), (uint32)lsn),
1785 errdetail("found initial snapshot in snapbuild file")));
1788 snapshot_not_interesting:
1789 if (ondisk.builder.running.xip != NULL)
1790 pfree(ondisk.builder.running.xip);
1791 if (ondisk.builder.committed.xip != NULL)
1792 pfree(ondisk.builder.committed.xip);
1797 * Remove all serialized snapshots that are not required anymore because no
1798 * slot can need them. This doesn't actually have to run during a checkpoint,
1799 * but it's a convenient point to schedule this.
1801 * NB: We run this during checkpoints even if logical decoding is disabled so
1802 * we cleanup old slots at some point after it got disabled.
1805 CheckPointSnapBuild(void)
1810 struct dirent *snap_de;
1811 char path[MAXPGPATH];
1814 * We start of with a minimum of the last redo pointer. No new replication
1815 * slot will start before that, so that's a safe upper bound for removal.
1817 redo = GetRedoRecPtr();
1819 /* now check for the restart ptrs from existing slots */
1820 cutoff = ReplicationSlotsComputeLogicalRestartLSN();
1822 /* don't start earlier than the restart lsn */
1826 snap_dir = AllocateDir("pg_llog/snapshots");
1827 while ((snap_de = ReadDir(snap_dir, "pg_llog/snapshots")) != NULL)
1832 struct stat statbuf;
1834 if (strcmp(snap_de->d_name, ".") == 0 ||
1835 strcmp(snap_de->d_name, "..") == 0)
1838 snprintf(path, MAXPGPATH, "pg_llog/snapshots/%s", snap_de->d_name);
1840 if (lstat(path, &statbuf) == 0 && !S_ISREG(statbuf.st_mode))
1842 elog(DEBUG1, "only regular files expected: %s", path);
1847 * temporary filenames from SnapBuildSerialize() include the LSN and
1848 * everything but are postfixed by .$pid.tmp. We can just remove them
1849 * the same as other files because there can be none that are currently
1850 * being written that are older than cutoff.
1852 * We just log a message if a file doesn't fit the pattern, it's
1853 * probably some editors lock/state file or similar...
1855 if (sscanf(snap_de->d_name, "%X-%X.snap", &hi, &lo) != 2)
1858 (errmsg("could not parse filename \"%s\"", path)));
1862 lsn = ((uint64) hi) << 32 | lo;
1864 /* check whether we still need it */
1865 if (lsn < cutoff || cutoff == InvalidXLogRecPtr)
1867 elog(DEBUG1, "removing snapbuild snapshot %s", path);
1870 * It's not particularly harmful, though strange, if we can't
1871 * remove the file here. Don't prevent the checkpoint from
1872 * completing, that'd be cure worse than the disease.
1874 if (unlink(path) < 0)
1877 (errcode_for_file_access(),
1878 errmsg("could not unlink file \"%s\": %m",