PostgreSQL Source Code  git master
snapbuild.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  *
3  * snapbuild.c
4  *
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
7  * WAL.
8  *
9  * NOTES:
10  *
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.
15  *
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.
28  *
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 it's 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 module, in contrast to HS, doesn't have to
38  * care about suboverflowed subtransactions and similar.
39  *
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  * (cf. combocid.c). Since combo CIDs 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.
49  *
50  * To facilitate all this we need our own visibility routine, as the normal
51  * ones are optimized for different usecases.
52  *
53  * To replace the normal catalog snapshots with decoding ones use the
54  * SetupHistoricSnapshot() and TeardownHistoricSnapshot() functions.
55  *
56  *
57  *
58  * The snapbuild machinery is starting up in several stages, as illustrated
59  * by the following graph describing the SnapBuild->state transitions:
60  *
61  * +-------------------------+
62  * +----| START |-------------+
63  * | +-------------------------+ |
64  * | | |
65  * | | |
66  * | running_xacts #1 |
67  * | | |
68  * | | |
69  * | v |
70  * | +-------------------------+ v
71  * | | BUILDING_SNAPSHOT |------------>|
72  * | +-------------------------+ |
73  * | | |
74  * | | |
75  * | running_xacts #2, xacts from #1 finished |
76  * | | |
77  * | | |
78  * | v |
79  * | +-------------------------+ v
80  * | | FULL_SNAPSHOT |------------>|
81  * | +-------------------------+ |
82  * | | |
83  * running_xacts | saved snapshot
84  * with zero xacts | at running_xacts's lsn
85  * | | |
86  * | running_xacts with xacts from #2 finished |
87  * | | |
88  * | v |
89  * | +-------------------------+ |
90  * +--->|SNAPBUILD_CONSISTENT |<------------+
91  * +-------------------------+
92  *
93  * Initially the machinery is in the START stage. When an xl_running_xacts
94  * record is read that is sufficiently new (above the safe xmin horizon),
95  * there's a state transition. If there were no running xacts when the
96  * running_xacts record was generated, we'll directly go into CONSISTENT
97  * state, otherwise we'll switch to the BUILDING_SNAPSHOT state. Having a full
98  * snapshot means that all transactions that start henceforth can be decoded
99  * in their entirety, but transactions that started previously can't. In
100  * FULL_SNAPSHOT we'll switch into CONSISTENT once all those previously
101  * running transactions have committed or aborted.
102  *
103  * Only transactions that commit after CONSISTENT state has been reached will
104  * be replayed, even though they might have started while still in
105  * FULL_SNAPSHOT. That ensures that we'll reach a point where no previous
106  * changes has been exported, but all the following ones will be. That point
107  * is a convenient point to initialize replication from, which is why we
108  * export a snapshot at that point, which *can* be used to read normal data.
109  *
110  * Copyright (c) 2012-2021, PostgreSQL Global Development Group
111  *
112  * IDENTIFICATION
113  * src/backend/replication/snapbuild.c
114  *
115  *-------------------------------------------------------------------------
116  */
117 
118 #include "postgres.h"
119 
120 #include <sys/stat.h>
121 #include <unistd.h>
122 
123 #include "access/heapam_xlog.h"
124 #include "access/transam.h"
125 #include "access/xact.h"
126 #include "miscadmin.h"
127 #include "pgstat.h"
128 #include "replication/logical.h"
130 #include "replication/snapbuild.h"
131 #include "storage/block.h" /* debugging output */
132 #include "storage/fd.h"
133 #include "storage/lmgr.h"
134 #include "storage/proc.h"
135 #include "storage/procarray.h"
136 #include "storage/standby.h"
137 #include "utils/builtins.h"
138 #include "utils/memutils.h"
139 #include "utils/snapmgr.h"
140 #include "utils/snapshot.h"
141 
142 /*
143  * This struct contains the current state of the snapshot building
144  * machinery. Besides a forward declaration in the header, it is not exposed
145  * to the public, so we can easily change its contents.
146  */
147 struct SnapBuild
148 {
149  /* how far are we along building our first full snapshot */
151 
152  /* private memory context used to allocate memory for this module. */
154 
155  /* all transactions < than this have committed/aborted */
157 
158  /* all transactions >= than this are uncommitted */
160 
161  /*
162  * Don't replay commits from an LSN < this LSN. This can be set externally
163  * but it will also be advanced (never retreat) from within snapbuild.c.
164  */
166 
167  /*
168  * LSN at which two-phase decoding was enabled or LSN at which we found a
169  * consistent point at the time of slot creation.
170  *
171  * The prepared transactions, that were skipped because previously
172  * two-phase was not enabled or are not covered by initial snapshot, need
173  * to be sent later along with commit prepared and they must be before
174  * this point.
175  */
177 
178  /*
179  * Don't start decoding WAL until the "xl_running_xacts" information
180  * indicates there are no running xids with an xid smaller than this.
181  */
183 
184  /* Indicates if we are building full snapshot or just catalog one. */
186 
187  /*
188  * Snapshot that's valid to see the catalog state seen at this moment.
189  */
191 
192  /*
193  * LSN of the last location we are sure a snapshot has been serialized to.
194  */
196 
197  /*
198  * The reorderbuffer we need to update with usable snapshots et al.
199  */
201 
202  /*
203  * TransactionId at which the next phase of initial snapshot building will
204  * happen. InvalidTransactionId if not known (i.e. SNAPBUILD_START), or
205  * when no next phase necessary (SNAPBUILD_CONSISTENT).
206  */
208 
209  /*
210  * Array of transactions which could have catalog changes that committed
211  * between xmin and xmax.
212  */
213  struct
214  {
215  /* number of committed transactions */
216  size_t xcnt;
217 
218  /* available space for committed transactions */
219  size_t xcnt_space;
220 
221  /*
222  * Until we reach a CONSISTENT state, we record commits of all
223  * transactions, not just the catalog changing ones. Record when that
224  * changes so we know we cannot export a snapshot safely anymore.
225  */
227 
228  /*
229  * Array of committed transactions that have modified the catalog.
230  *
231  * As this array is frequently modified we do *not* keep it in
232  * xidComparator order. Instead we sort the array when building &
233  * distributing a snapshot.
234  *
235  * TODO: It's unclear whether that reasoning has much merit. Every
236  * time we add something here after becoming consistent will also
237  * require distributing a snapshot. Storing them sorted would
238  * potentially also make it easier to purge (but more complicated wrt
239  * wraparound?). Should be improved if sorting while building the
240  * snapshot shows up in profiles.
241  */
243  } committed;
244 };
245 
246 /*
247  * Starting a transaction -- which we need to do while exporting a snapshot --
248  * removes knowledge about the previously used resowner, so we save it here.
249  */
251 static bool ExportInProgress = false;
252 
253 /* ->committed manipulation */
254 static void SnapBuildPurgeCommittedTxn(SnapBuild *builder);
255 
256 /* snapshot building/manipulation/distribution functions */
257 static Snapshot SnapBuildBuildSnapshot(SnapBuild *builder);
258 
259 static void SnapBuildFreeSnapshot(Snapshot snap);
260 
261 static void SnapBuildSnapIncRefcount(Snapshot snap);
262 
264 
265 /* xlog reading helper functions for SnapBuildProcessRunningXacts */
266 static bool SnapBuildFindSnapshot(SnapBuild *builder, XLogRecPtr lsn, xl_running_xacts *running);
267 static void SnapBuildWaitSnapshot(xl_running_xacts *running, TransactionId cutoff);
268 
269 /* serialization functions */
270 static void SnapBuildSerialize(SnapBuild *builder, XLogRecPtr lsn);
271 static bool SnapBuildRestore(SnapBuild *builder, XLogRecPtr lsn);
272 
273 /*
274  * Allocate a new snapshot builder.
275  *
276  * xmin_horizon is the xid >= which we can be sure no catalog rows have been
277  * removed, start_lsn is the LSN >= we want to replay commits.
278  */
279 SnapBuild *
281  TransactionId xmin_horizon,
282  XLogRecPtr start_lsn,
283  bool need_full_snapshot,
285 {
287  MemoryContext oldcontext;
288  SnapBuild *builder;
289 
290  /* allocate memory in own context, to have better accountability */
292  "snapshot builder context",
294  oldcontext = MemoryContextSwitchTo(context);
295 
296  builder = palloc0(sizeof(SnapBuild));
297 
298  builder->state = SNAPBUILD_START;
299  builder->context = context;
300  builder->reorder = reorder;
301  /* Other struct members initialized by zeroing via palloc0 above */
302 
303  builder->committed.xcnt = 0;
304  builder->committed.xcnt_space = 128; /* arbitrary number */
305  builder->committed.xip =
306  palloc0(builder->committed.xcnt_space * sizeof(TransactionId));
307  builder->committed.includes_all_transactions = true;
308 
309  builder->initial_xmin_horizon = xmin_horizon;
310  builder->start_decoding_at = start_lsn;
311  builder->building_full_snapshot = need_full_snapshot;
312  builder->two_phase_at = two_phase_at;
313 
314  MemoryContextSwitchTo(oldcontext);
315 
316  return builder;
317 }
318 
319 /*
320  * Free a snapshot builder.
321  */
322 void
324 {
325  MemoryContext context = builder->context;
326 
327  /* free snapshot explicitly, that contains some error checking */
328  if (builder->snapshot != NULL)
329  {
331  builder->snapshot = NULL;
332  }
333 
334  /* other resources are deallocated via memory context reset */
335  MemoryContextDelete(context);
336 }
337 
338 /*
339  * Free an unreferenced snapshot that has previously been built by us.
340  */
341 static void
343 {
344  /* make sure we don't get passed an external snapshot */
346 
347  /* make sure nobody modified our snapshot */
348  Assert(snap->curcid == FirstCommandId);
349  Assert(!snap->suboverflowed);
350  Assert(!snap->takenDuringRecovery);
351  Assert(snap->regd_count == 0);
352 
353  /* slightly more likely, so it's checked even without c-asserts */
354  if (snap->copied)
355  elog(ERROR, "cannot free a copied snapshot");
356 
357  if (snap->active_count)
358  elog(ERROR, "cannot free an active snapshot");
359 
360  pfree(snap);
361 }
362 
363 /*
364  * In which state of snapshot building are we?
365  */
368 {
369  return builder->state;
370 }
371 
372 /*
373  * Return the LSN at which the two-phase decoding was first enabled.
374  */
377 {
378  return builder->two_phase_at;
379 }
380 
381 /*
382  * Set the LSN at which two-phase decoding is enabled.
383  */
384 void
386 {
387  builder->two_phase_at = ptr;
388 }
389 
390 /*
391  * Should the contents of transaction ending at 'ptr' be decoded?
392  */
393 bool
395 {
396  return ptr < builder->start_decoding_at;
397 }
398 
399 /*
400  * Increase refcount of a snapshot.
401  *
402  * This is used when handing out a snapshot to some external resource or when
403  * adding a Snapshot as builder->snapshot.
404  */
405 static void
407 {
408  snap->active_count++;
409 }
410 
411 /*
412  * Decrease refcount of a snapshot and free if the refcount reaches zero.
413  *
414  * Externally visible, so that external resources that have been handed an
415  * IncRef'ed Snapshot can adjust its refcount easily.
416  */
417 void
419 {
420  /* make sure we don't get passed an external snapshot */
422 
423  /* make sure nobody modified our snapshot */
424  Assert(snap->curcid == FirstCommandId);
425  Assert(!snap->suboverflowed);
426  Assert(!snap->takenDuringRecovery);
427 
428  Assert(snap->regd_count == 0);
429 
430  Assert(snap->active_count > 0);
431 
432  /* slightly more likely, so it's checked even without casserts */
433  if (snap->copied)
434  elog(ERROR, "cannot free a copied snapshot");
435 
436  snap->active_count--;
437  if (snap->active_count == 0)
438  SnapBuildFreeSnapshot(snap);
439 }
440 
441 /*
442  * Build a new snapshot, based on currently committed catalog-modifying
443  * transactions.
444  *
445  * In-progress transactions with catalog access are *not* allowed to modify
446  * these snapshots; they have to copy them and fill in appropriate ->curcid
447  * and ->subxip/subxcnt values.
448  */
449 static Snapshot
451 {
453  Size ssize;
454 
455  Assert(builder->state >= SNAPBUILD_FULL_SNAPSHOT);
456 
457  ssize = sizeof(SnapshotData)
458  + sizeof(TransactionId) * builder->committed.xcnt
459  + sizeof(TransactionId) * 1 /* toplevel xid */ ;
460 
461  snapshot = MemoryContextAllocZero(builder->context, ssize);
462 
464 
465  /*
466  * We misuse the original meaning of SnapshotData's xip and subxip fields
467  * to make the more fitting for our needs.
468  *
469  * In the 'xip' array we store transactions that have to be treated as
470  * committed. Since we will only ever look at tuples from transactions
471  * that have modified the catalog it's more efficient to store those few
472  * that exist between xmin and xmax (frequently there are none).
473  *
474  * Snapshots that are used in transactions that have modified the catalog
475  * also use the 'subxip' array to store their toplevel xid and all the
476  * subtransaction xids so we can recognize when we need to treat rows as
477  * visible that are not in xip but still need to be visible. Subxip only
478  * gets filled when the transaction is copied into the context of a
479  * catalog modifying transaction since we otherwise share a snapshot
480  * between transactions. As long as a txn hasn't modified the catalog it
481  * doesn't need to treat any uncommitted rows as visible, so there is no
482  * need for those xids.
483  *
484  * Both arrays are qsort'ed so that we can use bsearch() on them.
485  */
486  Assert(TransactionIdIsNormal(builder->xmin));
487  Assert(TransactionIdIsNormal(builder->xmax));
488 
489  snapshot->xmin = builder->xmin;
490  snapshot->xmax = builder->xmax;
491 
492  /* store all transactions to be treated as committed by this snapshot */
493  snapshot->xip =
494  (TransactionId *) ((char *) snapshot + sizeof(SnapshotData));
495  snapshot->xcnt = builder->committed.xcnt;
496  memcpy(snapshot->xip,
497  builder->committed.xip,
498  builder->committed.xcnt * sizeof(TransactionId));
499 
500  /* sort so we can bsearch() */
501  qsort(snapshot->xip, snapshot->xcnt, sizeof(TransactionId), xidComparator);
502 
503  /*
504  * Initially, subxip is empty, i.e. it's a snapshot to be used by
505  * transactions that don't modify the catalog. Will be filled by
506  * ReorderBufferCopySnap() if necessary.
507  */
508  snapshot->subxcnt = 0;
509  snapshot->subxip = NULL;
510 
511  snapshot->suboverflowed = false;
512  snapshot->takenDuringRecovery = false;
513  snapshot->copied = false;
514  snapshot->curcid = FirstCommandId;
515  snapshot->active_count = 0;
516  snapshot->regd_count = 0;
517  snapshot->snapXactCompletionCount = 0;
518 
519  return snapshot;
520 }
521 
522 /*
523  * Build the initial slot snapshot and convert it to a normal snapshot that
524  * is understood by HeapTupleSatisfiesMVCC.
525  *
526  * The snapshot will be usable directly in current transaction or exported
527  * for loading in different transaction.
528  */
529 Snapshot
531 {
532  Snapshot snap;
533  TransactionId xid;
534  TransactionId *newxip;
535  int newxcnt = 0;
536 
539 
540  if (builder->state != SNAPBUILD_CONSISTENT)
541  elog(ERROR, "cannot build an initial slot snapshot before reaching a consistent state");
542 
543  if (!builder->committed.includes_all_transactions)
544  elog(ERROR, "cannot build an initial slot snapshot, not all transactions are monitored anymore");
545 
546  /* so we don't overwrite the existing value */
548  elog(ERROR, "cannot build an initial slot snapshot when MyProc->xmin already is valid");
549 
550  snap = SnapBuildBuildSnapshot(builder);
551 
552  /*
553  * We know that snap->xmin is alive, enforced by the logical xmin
554  * mechanism. Due to that we can do this without locks, we're only
555  * changing our own value.
556  */
557 #ifdef USE_ASSERT_CHECKING
558  {
559  TransactionId safeXid;
560 
561  LWLockAcquire(ProcArrayLock, LW_SHARED);
562  safeXid = GetOldestSafeDecodingTransactionId(false);
563  LWLockRelease(ProcArrayLock);
564 
565  Assert(TransactionIdPrecedesOrEquals(safeXid, snap->xmin));
566  }
567 #endif
568 
569  MyProc->xmin = snap->xmin;
570 
571  /* allocate in transaction context */
572  newxip = (TransactionId *)
574 
575  /*
576  * snapbuild.c builds transactions in an "inverted" manner, which means it
577  * stores committed transactions in ->xip, not ones in progress. Build a
578  * classical snapshot by marking all non-committed transactions as
579  * in-progress. This can be expensive.
580  */
581  for (xid = snap->xmin; NormalTransactionIdPrecedes(xid, snap->xmax);)
582  {
583  void *test;
584 
585  /*
586  * Check whether transaction committed using the decoding snapshot
587  * meaning of ->xip.
588  */
589  test = bsearch(&xid, snap->xip, snap->xcnt,
590  sizeof(TransactionId), xidComparator);
591 
592  if (test == NULL)
593  {
594  if (newxcnt >= GetMaxSnapshotXidCount())
595  ereport(ERROR,
596  (errcode(ERRCODE_T_R_SERIALIZATION_FAILURE),
597  errmsg("initial slot snapshot too large")));
598 
599  newxip[newxcnt++] = xid;
600  }
601 
603  }
604 
605  /* adjust remaining snapshot fields as needed */
607  snap->xcnt = newxcnt;
608  snap->xip = newxip;
609 
610  return snap;
611 }
612 
613 /*
614  * Export a snapshot so it can be set in another session with SET TRANSACTION
615  * SNAPSHOT.
616  *
617  * For that we need to start a transaction in the current backend as the
618  * importing side checks whether the source transaction is still open to make
619  * sure the xmin horizon hasn't advanced since then.
620  */
621 const char *
623 {
624  Snapshot snap;
625  char *snapname;
626 
628  elog(ERROR, "cannot export a snapshot from within a transaction");
629 
630  if (SavedResourceOwnerDuringExport)
631  elog(ERROR, "can only export one snapshot at a time");
632 
633  SavedResourceOwnerDuringExport = CurrentResourceOwner;
634  ExportInProgress = true;
635 
637 
638  /* There doesn't seem to a nice API to set these */
640  XactReadOnly = true;
641 
642  snap = SnapBuildInitialSnapshot(builder);
643 
644  /*
645  * now that we've built a plain snapshot, make it active and use the
646  * normal mechanisms for exporting it
647  */
648  snapname = ExportSnapshot(snap);
649 
650  ereport(LOG,
651  (errmsg_plural("exported logical decoding snapshot: \"%s\" with %u transaction ID",
652  "exported logical decoding snapshot: \"%s\" with %u transaction IDs",
653  snap->xcnt,
654  snapname, snap->xcnt)));
655  return snapname;
656 }
657 
658 /*
659  * Ensure there is a snapshot and if not build one for current transaction.
660  */
661 Snapshot
663 {
664  Assert(builder->state == SNAPBUILD_CONSISTENT);
665 
666  /* only build a new snapshot if we don't have a prebuilt one */
667  if (builder->snapshot == NULL)
668  {
669  builder->snapshot = SnapBuildBuildSnapshot(builder);
670  /* increase refcount for the snapshot builder */
672  }
673 
674  return builder->snapshot;
675 }
676 
677 /*
678  * Reset a previously SnapBuildExportSnapshot()'ed snapshot if there is
679  * any. Aborts the previously started transaction and resets the resource
680  * owner back to its original value.
681  */
682 void
684 {
685  /* nothing exported, that is the usual case */
686  if (!ExportInProgress)
687  return;
688 
689  if (!IsTransactionState())
690  elog(ERROR, "clearing exported snapshot in wrong transaction state");
691 
692  /* make sure nothing could have ever happened */
694 
696  SavedResourceOwnerDuringExport = NULL;
697  ExportInProgress = false;
698 }
699 
700 /*
701  * Handle the effects of a single heap change, appropriate to the current state
702  * of the snapshot builder and returns whether changes made at (xid, lsn) can
703  * be decoded.
704  */
705 bool
707 {
708  /*
709  * We can't handle data in transactions if we haven't built a snapshot
710  * yet, so don't store them.
711  */
712  if (builder->state < SNAPBUILD_FULL_SNAPSHOT)
713  return false;
714 
715  /*
716  * No point in keeping track of changes in transactions that we don't have
717  * enough information about to decode. This means that they started before
718  * we got into the SNAPBUILD_FULL_SNAPSHOT state.
719  */
720  if (builder->state < SNAPBUILD_CONSISTENT &&
721  TransactionIdPrecedes(xid, builder->next_phase_at))
722  return false;
723 
724  /*
725  * If the reorderbuffer doesn't yet have a snapshot, add one now, it will
726  * be needed to decode the change we're currently processing.
727  */
728  if (!ReorderBufferXidHasBaseSnapshot(builder->reorder, xid))
729  {
730  /* only build a new snapshot if we don't have a prebuilt one */
731  if (builder->snapshot == NULL)
732  {
733  builder->snapshot = SnapBuildBuildSnapshot(builder);
734  /* increase refcount for the snapshot builder */
736  }
737 
738  /*
739  * Increase refcount for the transaction we're handing the snapshot
740  * out to.
741  */
743  ReorderBufferSetBaseSnapshot(builder->reorder, xid, lsn,
744  builder->snapshot);
745  }
746 
747  return true;
748 }
749 
750 /*
751  * Do CommandId/combo CID handling after reading an xl_heap_new_cid record.
752  * This implies that a transaction has done some form of write to system
753  * catalogs.
754  */
755 void
757  XLogRecPtr lsn, xl_heap_new_cid *xlrec)
758 {
759  CommandId cid;
760 
761  /*
762  * we only log new_cid's if a catalog tuple was modified, so mark the
763  * transaction as containing catalog modifications
764  */
765  ReorderBufferXidSetCatalogChanges(builder->reorder, xid, lsn);
766 
767  ReorderBufferAddNewTupleCids(builder->reorder, xlrec->top_xid, lsn,
768  xlrec->target_node, xlrec->target_tid,
769  xlrec->cmin, xlrec->cmax,
770  xlrec->combocid);
771 
772  /* figure out new command id */
773  if (xlrec->cmin != InvalidCommandId &&
774  xlrec->cmax != InvalidCommandId)
775  cid = Max(xlrec->cmin, xlrec->cmax);
776  else if (xlrec->cmax != InvalidCommandId)
777  cid = xlrec->cmax;
778  else if (xlrec->cmin != InvalidCommandId)
779  cid = xlrec->cmin;
780  else
781  {
782  cid = InvalidCommandId; /* silence compiler */
783  elog(ERROR, "xl_heap_new_cid record without a valid CommandId");
784  }
785 
786  ReorderBufferAddNewCommandId(builder->reorder, xid, lsn, cid + 1);
787 }
788 
789 /*
790  * Add a new Snapshot to all transactions we're decoding that currently are
791  * in-progress so they can see new catalog contents made by the transaction
792  * that just committed. This is necessary because those in-progress
793  * transactions will use the new catalog's contents from here on (at the very
794  * least everything they do needs to be compatible with newer catalog
795  * contents).
796  */
797 static void
799 {
800  dlist_iter txn_i;
801  ReorderBufferTXN *txn;
802 
803  /*
804  * Iterate through all toplevel transactions. This can include
805  * subtransactions which we just don't yet know to be that, but that's
806  * fine, they will just get an unnecessary snapshot queued.
807  */
808  dlist_foreach(txn_i, &builder->reorder->toplevel_by_lsn)
809  {
810  txn = dlist_container(ReorderBufferTXN, node, txn_i.cur);
811 
813 
814  /*
815  * If we don't have a base snapshot yet, there are no changes in this
816  * transaction which in turn implies we don't yet need a snapshot at
817  * all. We'll add a snapshot when the first change gets queued.
818  *
819  * NB: This works correctly even for subtransactions because
820  * ReorderBufferAssignChild() takes care to transfer the base snapshot
821  * to the top-level transaction, and while iterating the changequeue
822  * we'll get the change from the subtxn.
823  */
824  if (!ReorderBufferXidHasBaseSnapshot(builder->reorder, txn->xid))
825  continue;
826 
827  /*
828  * We don't need to add snapshot to prepared transactions as they
829  * should not see the new catalog contents.
830  */
831  if (rbtxn_prepared(txn) || rbtxn_skip_prepared(txn))
832  continue;
833 
834  elog(DEBUG2, "adding a new snapshot to %u at %X/%X",
835  txn->xid, LSN_FORMAT_ARGS(lsn));
836 
837  /*
838  * increase the snapshot's refcount for the transaction we are handing
839  * it out to
840  */
842  ReorderBufferAddSnapshot(builder->reorder, txn->xid, lsn,
843  builder->snapshot);
844  }
845 }
846 
847 /*
848  * Keep track of a new catalog changing transaction that has committed.
849  */
850 static void
852 {
854 
855  if (builder->committed.xcnt == builder->committed.xcnt_space)
856  {
857  builder->committed.xcnt_space = builder->committed.xcnt_space * 2 + 1;
858 
859  elog(DEBUG1, "increasing space for committed transactions to %u",
860  (uint32) builder->committed.xcnt_space);
861 
862  builder->committed.xip = repalloc(builder->committed.xip,
863  builder->committed.xcnt_space * sizeof(TransactionId));
864  }
865 
866  /*
867  * TODO: It might make sense to keep the array sorted here instead of
868  * doing it every time we build a new snapshot. On the other hand this
869  * gets called repeatedly when a transaction with subtransactions commits.
870  */
871  builder->committed.xip[builder->committed.xcnt++] = xid;
872 }
873 
874 /*
875  * Remove knowledge about transactions we treat as committed that are smaller
876  * than ->xmin. Those won't ever get checked via the ->committed array but via
877  * the clog machinery, so we don't need to waste memory on them.
878  */
879 static void
881 {
882  int off;
883  TransactionId *workspace;
884  int surviving_xids = 0;
885 
886  /* not ready yet */
887  if (!TransactionIdIsNormal(builder->xmin))
888  return;
889 
890  /* TODO: Neater algorithm than just copying and iterating? */
891  workspace =
892  MemoryContextAlloc(builder->context,
893  builder->committed.xcnt * sizeof(TransactionId));
894 
895  /* copy xids that still are interesting to workspace */
896  for (off = 0; off < builder->committed.xcnt; off++)
897  {
898  if (NormalTransactionIdPrecedes(builder->committed.xip[off],
899  builder->xmin))
900  ; /* remove */
901  else
902  workspace[surviving_xids++] = builder->committed.xip[off];
903  }
904 
905  /* copy workspace back to persistent state */
906  memcpy(builder->committed.xip, workspace,
907  surviving_xids * sizeof(TransactionId));
908 
909  elog(DEBUG3, "purged committed transactions from %u to %u, xmin: %u, xmax: %u",
910  (uint32) builder->committed.xcnt, (uint32) surviving_xids,
911  builder->xmin, builder->xmax);
912  builder->committed.xcnt = surviving_xids;
913 
914  pfree(workspace);
915 }
916 
917 /*
918  * Handle everything that needs to be done when a transaction commits
919  */
920 void
922  int nsubxacts, TransactionId *subxacts)
923 {
924  int nxact;
925 
926  bool needs_snapshot = false;
927  bool needs_timetravel = false;
928  bool sub_needs_timetravel = false;
929 
930  TransactionId xmax = xid;
931 
932  /*
933  * Transactions preceding BUILDING_SNAPSHOT will neither be decoded, nor
934  * will they be part of a snapshot. So we don't need to record anything.
935  */
936  if (builder->state == SNAPBUILD_START ||
937  (builder->state == SNAPBUILD_BUILDING_SNAPSHOT &&
938  TransactionIdPrecedes(xid, builder->next_phase_at)))
939  {
940  /* ensure that only commits after this are getting replayed */
941  if (builder->start_decoding_at <= lsn)
942  builder->start_decoding_at = lsn + 1;
943  return;
944  }
945 
946  if (builder->state < SNAPBUILD_CONSISTENT)
947  {
948  /* ensure that only commits after this are getting replayed */
949  if (builder->start_decoding_at <= lsn)
950  builder->start_decoding_at = lsn + 1;
951 
952  /*
953  * If building an exportable snapshot, force xid to be tracked, even
954  * if the transaction didn't modify the catalog.
955  */
956  if (builder->building_full_snapshot)
957  {
958  needs_timetravel = true;
959  }
960  }
961 
962  for (nxact = 0; nxact < nsubxacts; nxact++)
963  {
964  TransactionId subxid = subxacts[nxact];
965 
966  /*
967  * Add subtransaction to base snapshot if catalog modifying, we don't
968  * distinguish to toplevel transactions there.
969  */
970  if (ReorderBufferXidHasCatalogChanges(builder->reorder, subxid))
971  {
972  sub_needs_timetravel = true;
973  needs_snapshot = true;
974 
975  elog(DEBUG1, "found subtransaction %u:%u with catalog changes",
976  xid, subxid);
977 
978  SnapBuildAddCommittedTxn(builder, subxid);
979 
980  if (NormalTransactionIdFollows(subxid, xmax))
981  xmax = subxid;
982  }
983 
984  /*
985  * If we're forcing timetravel we also need visibility information
986  * about subtransaction, so keep track of subtransaction's state, even
987  * if not catalog modifying. Don't need to distribute a snapshot in
988  * that case.
989  */
990  else if (needs_timetravel)
991  {
992  SnapBuildAddCommittedTxn(builder, subxid);
993  if (NormalTransactionIdFollows(subxid, xmax))
994  xmax = subxid;
995  }
996  }
997 
998  /* if top-level modified catalog, it'll need a snapshot */
999  if (ReorderBufferXidHasCatalogChanges(builder->reorder, xid))
1000  {
1001  elog(DEBUG2, "found top level transaction %u, with catalog changes",
1002  xid);
1003  needs_snapshot = true;
1004  needs_timetravel = true;
1005  SnapBuildAddCommittedTxn(builder, xid);
1006  }
1007  else if (sub_needs_timetravel)
1008  {
1009  /* track toplevel txn as well, subxact alone isn't meaningful */
1010  SnapBuildAddCommittedTxn(builder, xid);
1011  }
1012  else if (needs_timetravel)
1013  {
1014  elog(DEBUG2, "forced transaction %u to do timetravel", xid);
1015 
1016  SnapBuildAddCommittedTxn(builder, xid);
1017  }
1018 
1019  if (!needs_timetravel)
1020  {
1021  /* record that we cannot export a general snapshot anymore */
1022  builder->committed.includes_all_transactions = false;
1023  }
1024 
1025  Assert(!needs_snapshot || needs_timetravel);
1026 
1027  /*
1028  * Adjust xmax of the snapshot builder, we only do that for committed,
1029  * catalog modifying, transactions, everything else isn't interesting for
1030  * us since we'll never look at the respective rows.
1031  */
1032  if (needs_timetravel &&
1033  (!TransactionIdIsValid(builder->xmax) ||
1034  TransactionIdFollowsOrEquals(xmax, builder->xmax)))
1035  {
1036  builder->xmax = xmax;
1037  TransactionIdAdvance(builder->xmax);
1038  }
1039 
1040  /* if there's any reason to build a historic snapshot, do so now */
1041  if (needs_snapshot)
1042  {
1043  /*
1044  * If we haven't built a complete snapshot yet there's no need to hand
1045  * it out, it wouldn't (and couldn't) be used anyway.
1046  */
1047  if (builder->state < SNAPBUILD_FULL_SNAPSHOT)
1048  return;
1049 
1050  /*
1051  * Decrease the snapshot builder's refcount of the old snapshot, note
1052  * that it still will be used if it has been handed out to the
1053  * reorderbuffer earlier.
1054  */
1055  if (builder->snapshot)
1057 
1058  builder->snapshot = SnapBuildBuildSnapshot(builder);
1059 
1060  /* we might need to execute invalidations, add snapshot */
1061  if (!ReorderBufferXidHasBaseSnapshot(builder->reorder, xid))
1062  {
1064  ReorderBufferSetBaseSnapshot(builder->reorder, xid, lsn,
1065  builder->snapshot);
1066  }
1067 
1068  /* refcount of the snapshot builder for the new snapshot */
1070 
1071  /* add a new catalog snapshot to all currently running transactions */
1073  }
1074 }
1075 
1076 
1077 /* -----------------------------------
1078  * Snapshot building functions dealing with xlog records
1079  * -----------------------------------
1080  */
1081 
1082 /*
1083  * Process a running xacts record, and use its information to first build a
1084  * historic snapshot and later to release resources that aren't needed
1085  * anymore.
1086  */
1087 void
1089 {
1090  ReorderBufferTXN *txn;
1092 
1093  /*
1094  * If we're not consistent yet, inspect the record to see whether it
1095  * allows to get closer to being consistent. If we are consistent, dump
1096  * our snapshot so others or we, after a restart, can use it.
1097  */
1098  if (builder->state < SNAPBUILD_CONSISTENT)
1099  {
1100  /* returns false if there's no point in performing cleanup just yet */
1101  if (!SnapBuildFindSnapshot(builder, lsn, running))
1102  return;
1103  }
1104  else
1105  SnapBuildSerialize(builder, lsn);
1106 
1107  /*
1108  * Update range of interesting xids based on the running xacts
1109  * information. We don't increase ->xmax using it, because once we are in
1110  * a consistent state we can do that ourselves and much more efficiently
1111  * so, because we only need to do it for catalog transactions since we
1112  * only ever look at those.
1113  *
1114  * NB: We only increase xmax when a catalog modifying transaction commits
1115  * (see SnapBuildCommitTxn). Because of this, xmax can be lower than
1116  * xmin, which looks odd but is correct and actually more efficient, since
1117  * we hit fast paths in heapam_visibility.c.
1118  */
1119  builder->xmin = running->oldestRunningXid;
1120 
1121  /* Remove transactions we don't need to keep track off anymore */
1122  SnapBuildPurgeCommittedTxn(builder);
1123 
1124  /*
1125  * Advance the xmin limit for the current replication slot, to allow
1126  * vacuum to clean up the tuples this slot has been protecting.
1127  *
1128  * The reorderbuffer might have an xmin among the currently running
1129  * snapshots; use it if so. If not, we need only consider the snapshots
1130  * we'll produce later, which can't be less than the oldest running xid in
1131  * the record we're reading now.
1132  */
1133  xmin = ReorderBufferGetOldestXmin(builder->reorder);
1134  if (xmin == InvalidTransactionId)
1135  xmin = running->oldestRunningXid;
1136  elog(DEBUG3, "xmin: %u, xmax: %u, oldest running: %u, oldest xmin: %u",
1137  builder->xmin, builder->xmax, running->oldestRunningXid, xmin);
1138  LogicalIncreaseXminForSlot(lsn, xmin);
1139 
1140  /*
1141  * Also tell the slot where we can restart decoding from. We don't want to
1142  * do that after every commit because changing that implies an fsync of
1143  * the logical slot's state file, so we only do it every time we see a
1144  * running xacts record.
1145  *
1146  * Do so by looking for the oldest in progress transaction (determined by
1147  * the first LSN of any of its relevant records). Every transaction
1148  * remembers the last location we stored the snapshot to disk before its
1149  * beginning. That point is where we can restart from.
1150  */
1151 
1152  /*
1153  * Can't know about a serialized snapshot's location if we're not
1154  * consistent.
1155  */
1156  if (builder->state < SNAPBUILD_CONSISTENT)
1157  return;
1158 
1159  txn = ReorderBufferGetOldestTXN(builder->reorder);
1160 
1161  /*
1162  * oldest ongoing txn might have started when we didn't yet serialize
1163  * anything because we hadn't reached a consistent state yet.
1164  */
1165  if (txn != NULL && txn->restart_decoding_lsn != InvalidXLogRecPtr)
1167 
1168  /*
1169  * No in-progress transaction, can reuse the last serialized snapshot if
1170  * we have one.
1171  */
1172  else if (txn == NULL &&
1176  builder->last_serialized_snapshot);
1177 }
1178 
1179 
1180 /*
1181  * Build the start of a snapshot that's capable of decoding the catalog.
1182  *
1183  * Helper function for SnapBuildProcessRunningXacts() while we're not yet
1184  * consistent.
1185  *
1186  * Returns true if there is a point in performing internal maintenance/cleanup
1187  * using the xl_running_xacts record.
1188  */
1189 static bool
1191 {
1192  /* ---
1193  * Build catalog decoding snapshot incrementally using information about
1194  * the currently running transactions. There are several ways to do that:
1195  *
1196  * a) There were no running transactions when the xl_running_xacts record
1197  * was inserted, jump to CONSISTENT immediately. We might find such a
1198  * state while waiting on c)'s sub-states.
1199  *
1200  * b) This (in a previous run) or another decoding slot serialized a
1201  * snapshot to disk that we can use. Can't use this method for the
1202  * initial snapshot when slot is being created and needs full snapshot
1203  * for export or direct use, as that snapshot will only contain catalog
1204  * modifying transactions.
1205  *
1206  * c) First incrementally build a snapshot for catalog tuples
1207  * (BUILDING_SNAPSHOT), that requires all, already in-progress,
1208  * transactions to finish. Every transaction starting after that
1209  * (FULL_SNAPSHOT state), has enough information to be decoded. But
1210  * for older running transactions no viable snapshot exists yet, so
1211  * CONSISTENT will only be reached once all of those have finished.
1212  * ---
1213  */
1214 
1215  /*
1216  * xl_running_xact record is older than what we can use, we might not have
1217  * all necessary catalog rows anymore.
1218  */
1221  builder->initial_xmin_horizon))
1222  {
1223  ereport(DEBUG1,
1224  (errmsg_internal("skipping snapshot at %X/%X while building logical decoding snapshot, xmin horizon too low",
1225  LSN_FORMAT_ARGS(lsn)),
1226  errdetail_internal("initial xmin horizon of %u vs the snapshot's %u",
1227  builder->initial_xmin_horizon, running->oldestRunningXid)));
1228 
1229 
1230  SnapBuildWaitSnapshot(running, builder->initial_xmin_horizon);
1231 
1232  return true;
1233  }
1234 
1235  /*
1236  * a) No transaction were running, we can jump to consistent.
1237  *
1238  * This is not affected by races around xl_running_xacts, because we can
1239  * miss transaction commits, but currently not transactions starting.
1240  *
1241  * NB: We might have already started to incrementally assemble a snapshot,
1242  * so we need to be careful to deal with that.
1243  */
1244  if (running->oldestRunningXid == running->nextXid)
1245  {
1246  if (builder->start_decoding_at == InvalidXLogRecPtr ||
1247  builder->start_decoding_at <= lsn)
1248  /* can decode everything after this */
1249  builder->start_decoding_at = lsn + 1;
1250 
1251  /* As no transactions were running xmin/xmax can be trivially set. */
1252  builder->xmin = running->nextXid; /* < are finished */
1253  builder->xmax = running->nextXid; /* >= are running */
1254 
1255  /* so we can safely use the faster comparisons */
1256  Assert(TransactionIdIsNormal(builder->xmin));
1257  Assert(TransactionIdIsNormal(builder->xmax));
1258 
1259  builder->state = SNAPBUILD_CONSISTENT;
1261 
1262  ereport(LOG,
1263  (errmsg("logical decoding found consistent point at %X/%X",
1264  LSN_FORMAT_ARGS(lsn)),
1265  errdetail("There are no running transactions.")));
1266 
1267  return false;
1268  }
1269  /* b) valid on disk state and not building full snapshot */
1270  else if (!builder->building_full_snapshot &&
1271  SnapBuildRestore(builder, lsn))
1272  {
1273  /* there won't be any state to cleanup */
1274  return false;
1275  }
1276 
1277  /*
1278  * c) transition from START to BUILDING_SNAPSHOT.
1279  *
1280  * In START state, and a xl_running_xacts record with running xacts is
1281  * encountered. In that case, switch to BUILDING_SNAPSHOT state, and
1282  * record xl_running_xacts->nextXid. Once all running xacts have finished
1283  * (i.e. they're all >= nextXid), we have a complete catalog snapshot. It
1284  * might look that we could use xl_running_xact's ->xids information to
1285  * get there quicker, but that is problematic because transactions marked
1286  * as running, might already have inserted their commit record - it's
1287  * infeasible to change that with locking.
1288  */
1289  else if (builder->state == SNAPBUILD_START)
1290  {
1292  builder->next_phase_at = running->nextXid;
1293 
1294  /*
1295  * Start with an xmin/xmax that's correct for future, when all the
1296  * currently running transactions have finished. We'll update both
1297  * while waiting for the pending transactions to finish.
1298  */
1299  builder->xmin = running->nextXid; /* < are finished */
1300  builder->xmax = running->nextXid; /* >= are running */
1301 
1302  /* so we can safely use the faster comparisons */
1303  Assert(TransactionIdIsNormal(builder->xmin));
1304  Assert(TransactionIdIsNormal(builder->xmax));
1305 
1306  ereport(LOG,
1307  (errmsg("logical decoding found initial starting point at %X/%X",
1308  LSN_FORMAT_ARGS(lsn)),
1309  errdetail("Waiting for transactions (approximately %d) older than %u to end.",
1310  running->xcnt, running->nextXid)));
1311 
1312  SnapBuildWaitSnapshot(running, running->nextXid);
1313  }
1314 
1315  /*
1316  * c) transition from BUILDING_SNAPSHOT to FULL_SNAPSHOT.
1317  *
1318  * In BUILDING_SNAPSHOT state, and this xl_running_xacts' oldestRunningXid
1319  * is >= than nextXid from when we switched to BUILDING_SNAPSHOT. This
1320  * means all transactions starting afterwards have enough information to
1321  * be decoded. Switch to FULL_SNAPSHOT.
1322  */
1323  else if (builder->state == SNAPBUILD_BUILDING_SNAPSHOT &&
1325  running->oldestRunningXid))
1326  {
1327  builder->state = SNAPBUILD_FULL_SNAPSHOT;
1328  builder->next_phase_at = running->nextXid;
1329 
1330  ereport(LOG,
1331  (errmsg("logical decoding found initial consistent point at %X/%X",
1332  LSN_FORMAT_ARGS(lsn)),
1333  errdetail("Waiting for transactions (approximately %d) older than %u to end.",
1334  running->xcnt, running->nextXid)));
1335 
1336  SnapBuildWaitSnapshot(running, running->nextXid);
1337  }
1338 
1339  /*
1340  * c) transition from FULL_SNAPSHOT to CONSISTENT.
1341  *
1342  * In FULL_SNAPSHOT state (see d) ), and this xl_running_xacts'
1343  * oldestRunningXid is >= than nextXid from when we switched to
1344  * FULL_SNAPSHOT. This means all transactions that are currently in
1345  * progress have a catalog snapshot, and all their changes have been
1346  * collected. Switch to CONSISTENT.
1347  */
1348  else if (builder->state == SNAPBUILD_FULL_SNAPSHOT &&
1350  running->oldestRunningXid))
1351  {
1352  builder->state = SNAPBUILD_CONSISTENT;
1354 
1355  ereport(LOG,
1356  (errmsg("logical decoding found consistent point at %X/%X",
1357  LSN_FORMAT_ARGS(lsn)),
1358  errdetail("There are no old transactions anymore.")));
1359  }
1360 
1361  /*
1362  * We already started to track running xacts and need to wait for all
1363  * in-progress ones to finish. We fall through to the normal processing of
1364  * records so incremental cleanup can be performed.
1365  */
1366  return true;
1367 
1368 }
1369 
1370 /* ---
1371  * Iterate through xids in record, wait for all older than the cutoff to
1372  * finish. Then, if possible, log a new xl_running_xacts record.
1373  *
1374  * This isn't required for the correctness of decoding, but to:
1375  * a) allow isolationtester to notice that we're currently waiting for
1376  * something.
1377  * b) log a new xl_running_xacts record where it'd be helpful, without having
1378  * to wait for bgwriter or checkpointer.
1379  * ---
1380  */
1381 static void
1383 {
1384  int off;
1385 
1386  for (off = 0; off < running->xcnt; off++)
1387  {
1388  TransactionId xid = running->xids[off];
1389 
1390  /*
1391  * Upper layers should prevent that we ever need to wait on ourselves.
1392  * Check anyway, since failing to do so would either result in an
1393  * endless wait or an Assert() failure.
1394  */
1396  elog(ERROR, "waiting for ourselves");
1397 
1398  if (TransactionIdFollows(xid, cutoff))
1399  continue;
1400 
1401  XactLockTableWait(xid, NULL, NULL, XLTW_None);
1402  }
1403 
1404  /*
1405  * All transactions we needed to finish finished - try to ensure there is
1406  * another xl_running_xacts record in a timely manner, without having to
1407  * wait for bgwriter or checkpointer to log one. During recovery we can't
1408  * enforce that, so we'll have to wait.
1409  */
1410  if (!RecoveryInProgress())
1411  {
1413  }
1414 }
1415 
1416 /* -----------------------------------
1417  * Snapshot serialization support
1418  * -----------------------------------
1419  */
1420 
1421 /*
1422  * We store current state of struct SnapBuild on disk in the following manner:
1423  *
1424  * struct SnapBuildOnDisk;
1425  * TransactionId * running.xcnt_space;
1426  * TransactionId * committed.xcnt; (*not xcnt_space*)
1427  *
1428  */
1429 typedef struct SnapBuildOnDisk
1430 {
1431  /* first part of this struct needs to be version independent */
1432 
1433  /* data not covered by checksum */
1436 
1437  /* data covered by checksum */
1438 
1439  /* version, in case we want to support pg_upgrade */
1441  /* how large is the on disk data, excluding the constant sized part */
1443 
1444  /* version dependent part */
1446 
1447  /* variable amount of TransactionIds follows */
1448 } SnapBuildOnDisk;
1449 
1450 #define SnapBuildOnDiskConstantSize \
1451  offsetof(SnapBuildOnDisk, builder)
1452 #define SnapBuildOnDiskNotChecksummedSize \
1453  offsetof(SnapBuildOnDisk, version)
1454 
1455 #define SNAPBUILD_MAGIC 0x51A1E001
1456 #define SNAPBUILD_VERSION 4
1457 
1458 /*
1459  * Store/Load a snapshot from disk, depending on the snapshot builder's state.
1460  *
1461  * Supposed to be used by external (i.e. not snapbuild.c) code that just read
1462  * a record that's a potential location for a serialized snapshot.
1463  */
1464 void
1466 {
1467  if (builder->state < SNAPBUILD_CONSISTENT)
1468  SnapBuildRestore(builder, lsn);
1469  else
1470  SnapBuildSerialize(builder, lsn);
1471 }
1472 
1473 /*
1474  * Serialize the snapshot 'builder' at the location 'lsn' if it hasn't already
1475  * been done by another decoding process.
1476  */
1477 static void
1479 {
1480  Size needed_length;
1481  SnapBuildOnDisk *ondisk = NULL;
1482  char *ondisk_c;
1483  int fd;
1484  char tmppath[MAXPGPATH];
1485  char path[MAXPGPATH];
1486  int ret;
1487  struct stat stat_buf;
1488  Size sz;
1489 
1490  Assert(lsn != InvalidXLogRecPtr);
1492  builder->last_serialized_snapshot <= lsn);
1493 
1494  /*
1495  * no point in serializing if we cannot continue to work immediately after
1496  * restoring the snapshot
1497  */
1498  if (builder->state < SNAPBUILD_CONSISTENT)
1499  return;
1500 
1501  /* consistent snapshots have no next phase */
1503 
1504  /*
1505  * We identify snapshots by the LSN they are valid for. We don't need to
1506  * include timelines in the name as each LSN maps to exactly one timeline
1507  * unless the user used pg_resetwal or similar. If a user did so, there's
1508  * no hope continuing to decode anyway.
1509  */
1510  sprintf(path, "pg_logical/snapshots/%X-%X.snap",
1511  LSN_FORMAT_ARGS(lsn));
1512 
1513  /*
1514  * first check whether some other backend already has written the snapshot
1515  * for this LSN. It's perfectly fine if there's none, so we accept ENOENT
1516  * as a valid state. Everything else is an unexpected error.
1517  */
1518  ret = stat(path, &stat_buf);
1519 
1520  if (ret != 0 && errno != ENOENT)
1521  ereport(ERROR,
1523  errmsg("could not stat file \"%s\": %m", path)));
1524 
1525  else if (ret == 0)
1526  {
1527  /*
1528  * somebody else has already serialized to this point, don't overwrite
1529  * but remember location, so we don't need to read old data again.
1530  *
1531  * To be sure it has been synced to disk after the rename() from the
1532  * tempfile filename to the real filename, we just repeat the fsync.
1533  * That ought to be cheap because in most scenarios it should already
1534  * be safely on disk.
1535  */
1536  fsync_fname(path, false);
1537  fsync_fname("pg_logical/snapshots", true);
1538 
1539  builder->last_serialized_snapshot = lsn;
1540  goto out;
1541  }
1542 
1543  /*
1544  * there is an obvious race condition here between the time we stat(2) the
1545  * file and us writing the file. But we rename the file into place
1546  * atomically and all files created need to contain the same data anyway,
1547  * so this is perfectly fine, although a bit of a resource waste. Locking
1548  * seems like pointless complication.
1549  */
1550  elog(DEBUG1, "serializing snapshot to %s", path);
1551 
1552  /* to make sure only we will write to this tempfile, include pid */
1553  sprintf(tmppath, "pg_logical/snapshots/%X-%X.snap.%d.tmp",
1554  LSN_FORMAT_ARGS(lsn), MyProcPid);
1555 
1556  /*
1557  * Unlink temporary file if it already exists, needs to have been before a
1558  * crash/error since we won't enter this function twice from within a
1559  * single decoding slot/backend and the temporary file contains the pid of
1560  * the current process.
1561  */
1562  if (unlink(tmppath) != 0 && errno != ENOENT)
1563  ereport(ERROR,
1565  errmsg("could not remove file \"%s\": %m", tmppath)));
1566 
1567  needed_length = sizeof(SnapBuildOnDisk) +
1568  sizeof(TransactionId) * builder->committed.xcnt;
1569 
1570  ondisk_c = MemoryContextAllocZero(builder->context, needed_length);
1571  ondisk = (SnapBuildOnDisk *) ondisk_c;
1572  ondisk->magic = SNAPBUILD_MAGIC;
1573  ondisk->version = SNAPBUILD_VERSION;
1574  ondisk->length = needed_length;
1575  INIT_CRC32C(ondisk->checksum);
1576  COMP_CRC32C(ondisk->checksum,
1577  ((char *) ondisk) + SnapBuildOnDiskNotChecksummedSize,
1579  ondisk_c += sizeof(SnapBuildOnDisk);
1580 
1581  memcpy(&ondisk->builder, builder, sizeof(SnapBuild));
1582  /* NULL-ify memory-only data */
1583  ondisk->builder.context = NULL;
1584  ondisk->builder.snapshot = NULL;
1585  ondisk->builder.reorder = NULL;
1586  ondisk->builder.committed.xip = NULL;
1587 
1588  COMP_CRC32C(ondisk->checksum,
1589  &ondisk->builder,
1590  sizeof(SnapBuild));
1591 
1592  /* copy committed xacts */
1593  sz = sizeof(TransactionId) * builder->committed.xcnt;
1594  memcpy(ondisk_c, builder->committed.xip, sz);
1595  COMP_CRC32C(ondisk->checksum, ondisk_c, sz);
1596  ondisk_c += sz;
1597 
1598  FIN_CRC32C(ondisk->checksum);
1599 
1600  /* we have valid data now, open tempfile and write it there */
1601  fd = OpenTransientFile(tmppath,
1602  O_CREAT | O_EXCL | O_WRONLY | PG_BINARY);
1603  if (fd < 0)
1604  ereport(ERROR,
1606  errmsg("could not open file \"%s\": %m", tmppath)));
1607 
1608  errno = 0;
1610  if ((write(fd, ondisk, needed_length)) != needed_length)
1611  {
1612  int save_errno = errno;
1613 
1614  CloseTransientFile(fd);
1615 
1616  /* if write didn't set errno, assume problem is no disk space */
1617  errno = save_errno ? save_errno : ENOSPC;
1618  ereport(ERROR,
1620  errmsg("could not write to file \"%s\": %m", tmppath)));
1621  }
1623 
1624  /*
1625  * fsync the file before renaming so that even if we crash after this we
1626  * have either a fully valid file or nothing.
1627  *
1628  * It's safe to just ERROR on fsync() here because we'll retry the whole
1629  * operation including the writes.
1630  *
1631  * TODO: Do the fsync() via checkpoints/restartpoints, doing it here has
1632  * some noticeable overhead since it's performed synchronously during
1633  * decoding?
1634  */
1636  if (pg_fsync(fd) != 0)
1637  {
1638  int save_errno = errno;
1639 
1640  CloseTransientFile(fd);
1641  errno = save_errno;
1642  ereport(ERROR,
1644  errmsg("could not fsync file \"%s\": %m", tmppath)));
1645  }
1647 
1648  if (CloseTransientFile(fd) != 0)
1649  ereport(ERROR,
1651  errmsg("could not close file \"%s\": %m", tmppath)));
1652 
1653  fsync_fname("pg_logical/snapshots", true);
1654 
1655  /*
1656  * We may overwrite the work from some other backend, but that's ok, our
1657  * snapshot is valid as well, we'll just have done some superfluous work.
1658  */
1659  if (rename(tmppath, path) != 0)
1660  {
1661  ereport(ERROR,
1663  errmsg("could not rename file \"%s\" to \"%s\": %m",
1664  tmppath, path)));
1665  }
1666 
1667  /* make sure we persist */
1668  fsync_fname(path, false);
1669  fsync_fname("pg_logical/snapshots", true);
1670 
1671  /*
1672  * Now there's no way we can loose the dumped state anymore, remember this
1673  * as a serialization point.
1674  */
1675  builder->last_serialized_snapshot = lsn;
1676 
1677 out:
1679  builder->last_serialized_snapshot);
1680  /* be tidy */
1681  if (ondisk)
1682  pfree(ondisk);
1683 }
1684 
1685 /*
1686  * Restore a snapshot into 'builder' if previously one has been stored at the
1687  * location indicated by 'lsn'. Returns true if successful, false otherwise.
1688  */
1689 static bool
1691 {
1692  SnapBuildOnDisk ondisk;
1693  int fd;
1694  char path[MAXPGPATH];
1695  Size sz;
1696  int readBytes;
1697  pg_crc32c checksum;
1698 
1699  /* no point in loading a snapshot if we're already there */
1700  if (builder->state == SNAPBUILD_CONSISTENT)
1701  return false;
1702 
1703  sprintf(path, "pg_logical/snapshots/%X-%X.snap",
1704  LSN_FORMAT_ARGS(lsn));
1705 
1706  fd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
1707 
1708  if (fd < 0 && errno == ENOENT)
1709  return false;
1710  else if (fd < 0)
1711  ereport(ERROR,
1713  errmsg("could not open file \"%s\": %m", path)));
1714 
1715  /* ----
1716  * Make sure the snapshot had been stored safely to disk, that's normally
1717  * cheap.
1718  * Note that we do not need PANIC here, nobody will be able to use the
1719  * slot without fsyncing, and saving it won't succeed without an fsync()
1720  * either...
1721  * ----
1722  */
1723  fsync_fname(path, false);
1724  fsync_fname("pg_logical/snapshots", true);
1725 
1726 
1727  /* read statically sized portion of snapshot */
1729  readBytes = read(fd, &ondisk, SnapBuildOnDiskConstantSize);
1731  if (readBytes != SnapBuildOnDiskConstantSize)
1732  {
1733  int save_errno = errno;
1734 
1735  CloseTransientFile(fd);
1736 
1737  if (readBytes < 0)
1738  {
1739  errno = save_errno;
1740  ereport(ERROR,
1742  errmsg("could not read file \"%s\": %m", path)));
1743  }
1744  else
1745  ereport(ERROR,
1747  errmsg("could not read file \"%s\": read %d of %zu",
1748  path, readBytes,
1750  }
1751 
1752  if (ondisk.magic != SNAPBUILD_MAGIC)
1753  ereport(ERROR,
1755  errmsg("snapbuild state file \"%s\" has wrong magic number: %u instead of %u",
1756  path, ondisk.magic, SNAPBUILD_MAGIC)));
1757 
1758  if (ondisk.version != SNAPBUILD_VERSION)
1759  ereport(ERROR,
1761  errmsg("snapbuild state file \"%s\" has unsupported version: %u instead of %u",
1762  path, ondisk.version, SNAPBUILD_VERSION)));
1763 
1764  INIT_CRC32C(checksum);
1765  COMP_CRC32C(checksum,
1766  ((char *) &ondisk) + SnapBuildOnDiskNotChecksummedSize,
1768 
1769  /* read SnapBuild */
1771  readBytes = read(fd, &ondisk.builder, sizeof(SnapBuild));
1773  if (readBytes != sizeof(SnapBuild))
1774  {
1775  int save_errno = errno;
1776 
1777  CloseTransientFile(fd);
1778 
1779  if (readBytes < 0)
1780  {
1781  errno = save_errno;
1782  ereport(ERROR,
1784  errmsg("could not read file \"%s\": %m", path)));
1785  }
1786  else
1787  ereport(ERROR,
1789  errmsg("could not read file \"%s\": read %d of %zu",
1790  path, readBytes, sizeof(SnapBuild))));
1791  }
1792  COMP_CRC32C(checksum, &ondisk.builder, sizeof(SnapBuild));
1793 
1794  /* restore committed xacts information */
1795  sz = sizeof(TransactionId) * ondisk.builder.committed.xcnt;
1796  ondisk.builder.committed.xip = MemoryContextAllocZero(builder->context, sz);
1798  readBytes = read(fd, ondisk.builder.committed.xip, sz);
1800  if (readBytes != sz)
1801  {
1802  int save_errno = errno;
1803 
1804  CloseTransientFile(fd);
1805 
1806  if (readBytes < 0)
1807  {
1808  errno = save_errno;
1809  ereport(ERROR,
1811  errmsg("could not read file \"%s\": %m", path)));
1812  }
1813  else
1814  ereport(ERROR,
1816  errmsg("could not read file \"%s\": read %d of %zu",
1817  path, readBytes, sz)));
1818  }
1819  COMP_CRC32C(checksum, ondisk.builder.committed.xip, sz);
1820 
1821  if (CloseTransientFile(fd) != 0)
1822  ereport(ERROR,
1824  errmsg("could not close file \"%s\": %m", path)));
1825 
1826  FIN_CRC32C(checksum);
1827 
1828  /* verify checksum of what we've read */
1829  if (!EQ_CRC32C(checksum, ondisk.checksum))
1830  ereport(ERROR,
1832  errmsg("checksum mismatch for snapbuild state file \"%s\": is %u, should be %u",
1833  path, checksum, ondisk.checksum)));
1834 
1835  /*
1836  * ok, we now have a sensible snapshot here, figure out if it has more
1837  * information than we have.
1838  */
1839 
1840  /*
1841  * We are only interested in consistent snapshots for now, comparing
1842  * whether one incomplete snapshot is more "advanced" seems to be
1843  * unnecessarily complex.
1844  */
1845  if (ondisk.builder.state < SNAPBUILD_CONSISTENT)
1846  goto snapshot_not_interesting;
1847 
1848  /*
1849  * Don't use a snapshot that requires an xmin that we cannot guarantee to
1850  * be available.
1851  */
1852  if (TransactionIdPrecedes(ondisk.builder.xmin, builder->initial_xmin_horizon))
1853  goto snapshot_not_interesting;
1854 
1855  /* consistent snapshots have no next phase */
1856  Assert(ondisk.builder.next_phase_at == InvalidTransactionId);
1857 
1858  /* ok, we think the snapshot is sensible, copy over everything important */
1859  builder->xmin = ondisk.builder.xmin;
1860  builder->xmax = ondisk.builder.xmax;
1861  builder->state = ondisk.builder.state;
1862 
1863  builder->committed.xcnt = ondisk.builder.committed.xcnt;
1864  /* We only allocated/stored xcnt, not xcnt_space xids ! */
1865  /* don't overwrite preallocated xip, if we don't have anything here */
1866  if (builder->committed.xcnt > 0)
1867  {
1868  pfree(builder->committed.xip);
1869  builder->committed.xcnt_space = ondisk.builder.committed.xcnt;
1870  builder->committed.xip = ondisk.builder.committed.xip;
1871  }
1872  ondisk.builder.committed.xip = NULL;
1873 
1874  /* our snapshot is not interesting anymore, build a new one */
1875  if (builder->snapshot != NULL)
1876  {
1878  }
1879  builder->snapshot = SnapBuildBuildSnapshot(builder);
1881 
1882  ReorderBufferSetRestartPoint(builder->reorder, lsn);
1883 
1884  Assert(builder->state == SNAPBUILD_CONSISTENT);
1885 
1886  ereport(LOG,
1887  (errmsg("logical decoding found consistent point at %X/%X",
1888  LSN_FORMAT_ARGS(lsn)),
1889  errdetail("Logical decoding will begin using saved snapshot.")));
1890  return true;
1891 
1892 snapshot_not_interesting:
1893  if (ondisk.builder.committed.xip != NULL)
1894  pfree(ondisk.builder.committed.xip);
1895  return false;
1896 }
1897 
1898 /*
1899  * Remove all serialized snapshots that are not required anymore because no
1900  * slot can need them. This doesn't actually have to run during a checkpoint,
1901  * but it's a convenient point to schedule this.
1902  *
1903  * NB: We run this during checkpoints even if logical decoding is disabled so
1904  * we cleanup old slots at some point after it got disabled.
1905  */
1906 void
1908 {
1909  XLogRecPtr cutoff;
1910  XLogRecPtr redo;
1911  DIR *snap_dir;
1912  struct dirent *snap_de;
1913  char path[MAXPGPATH + 21];
1914 
1915  /*
1916  * We start off with a minimum of the last redo pointer. No new
1917  * replication slot will start before that, so that's a safe upper bound
1918  * for removal.
1919  */
1920  redo = GetRedoRecPtr();
1921 
1922  /* now check for the restart ptrs from existing slots */
1924 
1925  /* don't start earlier than the restart lsn */
1926  if (redo < cutoff)
1927  cutoff = redo;
1928 
1929  snap_dir = AllocateDir("pg_logical/snapshots");
1930  while ((snap_de = ReadDir(snap_dir, "pg_logical/snapshots")) != NULL)
1931  {
1932  uint32 hi;
1933  uint32 lo;
1934  XLogRecPtr lsn;
1935  struct stat statbuf;
1936 
1937  if (strcmp(snap_de->d_name, ".") == 0 ||
1938  strcmp(snap_de->d_name, "..") == 0)
1939  continue;
1940 
1941  snprintf(path, sizeof(path), "pg_logical/snapshots/%s", snap_de->d_name);
1942 
1943  if (lstat(path, &statbuf) == 0 && !S_ISREG(statbuf.st_mode))
1944  {
1945  elog(DEBUG1, "only regular files expected: %s", path);
1946  continue;
1947  }
1948 
1949  /*
1950  * temporary filenames from SnapBuildSerialize() include the LSN and
1951  * everything but are postfixed by .$pid.tmp. We can just remove them
1952  * the same as other files because there can be none that are
1953  * currently being written that are older than cutoff.
1954  *
1955  * We just log a message if a file doesn't fit the pattern, it's
1956  * probably some editors lock/state file or similar...
1957  */
1958  if (sscanf(snap_de->d_name, "%X-%X.snap", &hi, &lo) != 2)
1959  {
1960  ereport(LOG,
1961  (errmsg("could not parse file name \"%s\"", path)));
1962  continue;
1963  }
1964 
1965  lsn = ((uint64) hi) << 32 | lo;
1966 
1967  /* check whether we still need it */
1968  if (lsn < cutoff || cutoff == InvalidXLogRecPtr)
1969  {
1970  elog(DEBUG1, "removing snapbuild snapshot %s", path);
1971 
1972  /*
1973  * It's not particularly harmful, though strange, if we can't
1974  * remove the file here. Don't prevent the checkpoint from
1975  * completing, that'd be a cure worse than the disease.
1976  */
1977  if (unlink(path) < 0)
1978  {
1979  ereport(LOG,
1981  errmsg("could not remove file \"%s\": %m",
1982  path)));
1983  continue;
1984  }
1985  }
1986  }
1987  FreeDir(snap_dir);
1988 }
#define TransactionIdAdvance(dest)
Definition: transam.h:91
static bool SnapBuildRestore(SnapBuild *builder, XLogRecPtr lsn)
Definition: snapbuild.c:1690
bool ReorderBufferXidHasBaseSnapshot(ReorderBuffer *rb, TransactionId xid)
#define INIT_CRC32C(crc)
Definition: pg_crc32c.h:41
uint32 CommandId
Definition: c.h:601
void AbortCurrentTransaction(void)
Definition: xact.c:3220
uint64 snapXactCompletionCount
Definition: snapshot.h:216
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
TransactionId GetOldestSafeDecodingTransactionId(bool catalogOnly)
Definition: procarray.c:2947
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#define AllocSetContextCreate
Definition: memutils.h:173
#define rbtxn_prepared(txn)
#define DEBUG1
Definition: elog.h:25
int MyProcPid
Definition: globals.c:43
static void SnapBuildAddCommittedTxn(SnapBuild *builder, TransactionId xid)
Definition: snapbuild.c:851
#define SNAPBUILD_VERSION
Definition: snapbuild.c:1456
static void pgstat_report_wait_end(void)
Definition: wait_event.h:278
static void test(void)
bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition: transam.c:334
uint32 TransactionId
Definition: c.h:587
bool copied
Definition: snapshot.h:185
TransactionId next_phase_at
Definition: snapbuild.c:207
static void SnapBuildWaitSnapshot(xl_running_xacts *running, TransactionId cutoff)
Definition: snapbuild.c:1382
bool SnapBuildXactNeedsSkip(SnapBuild *builder, XLogRecPtr ptr)
Definition: snapbuild.c:394
#define SNAPBUILD_MAGIC
Definition: snapbuild.c:1455
void SnapBuildCommitTxn(SnapBuild *builder, XLogRecPtr lsn, TransactionId xid, int nsubxacts, TransactionId *subxacts)
Definition: snapbuild.c:921
#define DEBUG3
Definition: elog.h:23
SnapBuildState SnapBuildCurrentState(SnapBuild *builder)
Definition: snapbuild.c:367
bool TransactionIdIsCurrentTransactionId(TransactionId xid)
Definition: xact.c:869
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1019
#define write(a, b, c)
Definition: win32.h:14
PGPROC * MyProc
Definition: proc.c:68
CommandId combocid
Definition: heapam_xlog.h:370
pg_crc32c checksum
Definition: snapbuild.c:1435
Snapshot snapshot
Definition: snapbuild.c:190
#define dlist_foreach(iter, lhead)
Definition: ilist.h:526
uint32 pg_crc32c
Definition: pg_crc32c.h:38
void LogicalIncreaseRestartDecodingForSlot(XLogRecPtr current_lsn, XLogRecPtr restart_lsn)
Definition: logical.c:1632
ResourceOwner CurrentResourceOwner
Definition: resowner.c:146
XLogRecPtr current_restart_decoding_lsn
#define XACT_REPEATABLE_READ
Definition: xact.h:38
bool building_full_snapshot
Definition: snapbuild.c:185
void fsync_fname(const char *fname, bool isdir)
Definition: fd.c:671
void ReorderBufferSetBaseSnapshot(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, Snapshot snap)
bool TransactionIdFollowsOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:349
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
int errcode(int sqlerrcode)
Definition: elog.c:698
CommandId cmax
Definition: heapam_xlog.h:369
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4711
size_t xcnt_space
Definition: snapbuild.c:219
ItemPointerData target_tid
Definition: heapam_xlog.h:376
char * ExportSnapshot(Snapshot snapshot)
Definition: snapmgr.c:1106
bool suboverflowed
Definition: snapshot.h:182
void ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, RelFileNode node, ItemPointerData tid, CommandId cmin, CommandId cmax, CommandId combocid)
static bool SnapBuildFindSnapshot(SnapBuild *builder, XLogRecPtr lsn, xl_running_xacts *running)
Definition: snapbuild.c:1190
size_t xcnt
Definition: snapbuild.c:216
#define LOG
Definition: elog.h:26
bool RecoveryInProgress(void)
Definition: xlog.c:8220
Definition: dirent.h:9
uint32 regd_count
Definition: snapshot.h:205
static int fd(const char *x, int i)
Definition: preproc-init.c:105
#define PG_BINARY
Definition: c.h:1271
static ResourceOwner SavedResourceOwnerDuringExport
Definition: snapbuild.c:250
#define FirstCommandId
Definition: c.h:603
int errdetail_internal(const char *fmt,...)
Definition: elog.c:1069
bool SnapBuildProcessChange(SnapBuild *builder, TransactionId xid, XLogRecPtr lsn)
Definition: snapbuild.c:706
void ReorderBufferSetRestartPoint(ReorderBuffer *rb, XLogRecPtr ptr)
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
TransactionId xids[FLEXIBLE_ARRAY_MEMBER]
Definition: standbydefs.h:56
#define sprintf
Definition: port.h:218
const char * SnapBuildExportSnapshot(SnapBuild *builder)
Definition: snapbuild.c:622
SnapBuildState state
Definition: snapbuild.c:150
static void SnapBuildSerialize(SnapBuild *builder, XLogRecPtr lsn)
Definition: snapbuild.c:1478
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
#define dlist_container(type, membername, ptr)
Definition: ilist.h:496
void pfree(void *pointer)
Definition: mcxt.c:1169
XLogRecPtr LogStandbySnapshot(void)
Definition: standby.c:1220
bool TransactionIdPrecedesOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:319
Definition: dirent.c:25
#define ERROR
Definition: elog.h:46
Definition: lmgr.h:26
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2509
bool FirstSnapshotSet
Definition: snapmgr.c:149
#define MAXPGPATH
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
static void SnapBuildDistributeNewCatalogSnapshot(SnapBuild *builder, XLogRecPtr lsn)
Definition: snapbuild.c:798
static bool ExportInProgress
Definition: snapbuild.c:251
TransactionId xmin
Definition: proc.h:138
#define DEBUG2
Definition: elog.h:24
SnapBuild builder
Definition: snapbuild.c:1445
ReorderBuffer * reorder
Definition: snapbuild.c:200
TransactionId initial_xmin_horizon
Definition: snapbuild.c:182
TransactionId * xip
Definition: snapbuild.c:242
void SnapBuildProcessNewCid(SnapBuild *builder, TransactionId xid, XLogRecPtr lsn, xl_heap_new_cid *xlrec)
Definition: snapbuild.c:756
static void SnapBuildFreeSnapshot(Snapshot snap)
Definition: snapbuild.c:342
int errdetail(const char *fmt,...)
Definition: elog.c:1042
static Snapshot SnapBuildBuildSnapshot(SnapBuild *builder)
Definition: snapbuild.c:450
int errcode_for_file_access(void)
Definition: elog.c:721
XLogRecPtr ReplicationSlotsComputeLogicalRestartLSN(void)
Definition: slot.c:860
struct SnapshotData SnapshotData
bool includes_all_transactions
Definition: snapbuild.c:226
#define InvalidTransactionId
Definition: transam.h:31
void CheckPointSnapBuild(void)
Definition: snapbuild.c:1907
SnapshotType snapshot_type
Definition: snapshot.h:144
bool ReorderBufferXidHasCatalogChanges(ReorderBuffer *rb, TransactionId xid)
unsigned int uint32
Definition: c.h:441
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2720
void SnapBuildProcessRunningXacts(SnapBuild *builder, XLogRecPtr lsn, xl_running_xacts *running)
Definition: snapbuild.c:1088
TransactionId xmax
Definition: snapshot.h:158
TransactionId xmin
Definition: snapshot.h:157
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
SnapBuildState
Definition: snapbuild.h:18
#define EQ_CRC32C(c1, c2)
Definition: pg_crc32c.h:42
XLogRecPtr two_phase_at
Definition: snapbuild.c:176
XLogRecPtr last_serialized_snapshot
Definition: snapbuild.c:195
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:300
TransactionId * xip
Definition: snapshot.h:168
static void pgstat_report_wait_start(uint32 wait_event_info)
Definition: wait_event.h:262
#define S_ISREG(m)
Definition: win32_port.h:319
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:47
int CloseTransientFile(int fd)
Definition: fd.c:2686
TransactionId xmax
Definition: snapbuild.c:159
RelFileNode target_node
Definition: heapam_xlog.h:375
void SnapBuildSetTwoPhaseAt(SnapBuild *builder, XLogRecPtr ptr)
Definition: snapbuild.c:385
TransactionId ReorderBufferGetOldestXmin(ReorderBuffer *rb)
void * palloc0(Size size)
Definition: mcxt.c:1093
#define InvalidCommandId
Definition: c.h:604
unsigned short st_mode
Definition: win32_port.h:260
dlist_head toplevel_by_lsn
TransactionId xid
dlist_node * cur
Definition: ilist.h:161
void * MemoryContextAllocZero(MemoryContext context, Size size)
Definition: mcxt.c:906
void ReorderBufferAddSnapshot(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, Snapshot snap)
CommandId curcid
Definition: snapshot.h:187
#define SnapBuildOnDiskConstantSize
Definition: snapbuild.c:1450
#define ereport(elevel,...)
Definition: elog.h:157
int GetMaxSnapshotXidCount(void)
Definition: procarray.c:2069
bool XactReadOnly
Definition: xact.c:78
void FreeSnapshotBuilder(SnapBuild *builder)
Definition: snapbuild.c:323
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
#define Max(x, y)
Definition: c.h:980
void XactLockTableWait(TransactionId xid, Relation rel, ItemPointer ctid, XLTW_Oper oper)
Definition: lmgr.c:640
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:804
ReorderBufferTXN * ReorderBufferGetOldestTXN(ReorderBuffer *rb)
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2786
void LogicalIncreaseXminForSlot(XLogRecPtr current_lsn, TransactionId xmin)
Definition: logical.c:1564
void StartTransactionCommand(void)
Definition: xact.c:2848
#define SnapBuildOnDiskNotChecksummedSize
Definition: snapbuild.c:1452
bool takenDuringRecovery
Definition: snapshot.h:184
SnapBuild * AllocateSnapshotBuilder(ReorderBuffer *reorder, TransactionId xmin_horizon, XLogRecPtr start_lsn, bool need_full_snapshot, XLogRecPtr two_phase_at)
Definition: snapbuild.c:280
#define NormalTransactionIdFollows(id1, id2)
Definition: transam.h:152
size_t Size
Definition: c.h:540
int XactIsoLevel
Definition: xact.c:75
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
bool IsTransactionState(void)
Definition: xact.c:371
MemoryContext context
Definition: snapbuild.c:153
XLogRecPtr GetRedoRecPtr(void)
Definition: xlog.c:8512
TransactionId nextXid
Definition: standbydefs.h:52
#define NormalTransactionIdPrecedes(id1, id2)
Definition: transam.h:147
void * repalloc(void *pointer, Size size)
Definition: mcxt.c:1182
#define rbtxn_skip_prepared(txn)
void SnapBuildSnapDecRefcount(Snapshot snap)
Definition: snapbuild.c:418
#define lstat(path, sb)
Definition: win32_port.h:276
struct SnapBuild::@16 committed
XLogRecPtr SnapBuildGetTwoPhaseAt(SnapBuild *builder)
Definition: snapbuild.c:376
Snapshot SnapBuildInitialSnapshot(SnapBuild *builder)
Definition: snapbuild.c:530
uint32 xcnt
Definition: snapshot.h:169
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
TransactionId xmin
Definition: snapbuild.c:156
void * MemoryContextAlloc(MemoryContext context, Size size)
Definition: mcxt.c:863
#define elog(elevel,...)
Definition: elog.h:232
void SnapBuildSerializationPoint(SnapBuild *builder, XLogRecPtr lsn)
Definition: snapbuild.c:1465
XLogRecPtr restart_decoding_lsn
TransactionId oldestRunningXid
Definition: standbydefs.h:53
CommandId cmin
Definition: heapam_xlog.h:368
int pg_fsync(int fd)
Definition: fd.c:357
void ReorderBufferXidSetCatalogChanges(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
char d_name[MAX_PATH]
Definition: dirent.h:15
struct SnapBuildOnDisk SnapBuildOnDisk
#define qsort(a, b, c, d)
Definition: port.h:504
#define TransactionIdIsValid(xid)
Definition: transam.h:41
#define TransactionIdIsNormal(xid)
Definition: transam.h:42
#define COMP_CRC32C(crc, data, len)
Definition: pg_crc32c.h:89
static void SnapBuildSnapIncRefcount(Snapshot snap)
Definition: snapbuild.c:406
#define snprintf
Definition: port.h:216
#define FIN_CRC32C(crc)
Definition: pg_crc32c.h:94
XLogRecPtr start_decoding_at
Definition: snapbuild.c:165
static void SnapBuildPurgeCommittedTxn(SnapBuild *builder)
Definition: snapbuild.c:880
#define read(a, b, c)
Definition: win32.h:13
int FreeDir(DIR *dir)
Definition: fd.c:2838
#define stat
Definition: win32_port.h:275
void SnapBuildClearExportedSnapshot(void)
Definition: snapbuild.c:683
TransactionId * subxip
Definition: snapshot.h:180
uint32 active_count
Definition: snapshot.h:204
int xidComparator(const void *arg1, const void *arg2)
Definition: xid.c:136
int32 subxcnt
Definition: snapshot.h:181
TransactionId top_xid
Definition: heapam_xlog.h:367
void ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, CommandId cid)
Snapshot SnapBuildGetOrBuildSnapshot(SnapBuild *builder, TransactionId xid)
Definition: snapbuild.c:662