PostgreSQL Source Code  git master
snapbuild.h File Reference
#include "access/xlogdefs.h"
#include "utils/snapmgr.h"
Include dependency graph for snapbuild.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Typedefs

typedef struct SnapBuild SnapBuild
 

Enumerations

enum  SnapBuildState { SNAPBUILD_START = -1 , SNAPBUILD_BUILDING_SNAPSHOT = 0 , SNAPBUILD_FULL_SNAPSHOT = 1 , SNAPBUILD_CONSISTENT = 2 }
 

Functions

void CheckPointSnapBuild (void)
 
SnapBuildAllocateSnapshotBuilder (struct ReorderBuffer *reorder, TransactionId xmin_horizon, XLogRecPtr start_lsn, bool need_full_snapshot, XLogRecPtr two_phase_at)
 
void FreeSnapshotBuilder (SnapBuild *builder)
 
void SnapBuildSnapDecRefcount (Snapshot snap)
 
Snapshot SnapBuildInitialSnapshot (SnapBuild *builder)
 
const char * SnapBuildExportSnapshot (SnapBuild *builder)
 
void SnapBuildClearExportedSnapshot (void)
 
void SnapBuildResetExportedSnapshotState (void)
 
SnapBuildState SnapBuildCurrentState (SnapBuild *builder)
 
Snapshot SnapBuildGetOrBuildSnapshot (SnapBuild *builder)
 
bool SnapBuildXactNeedsSkip (SnapBuild *builder, XLogRecPtr ptr)
 
XLogRecPtr SnapBuildGetTwoPhaseAt (SnapBuild *builder)
 
void SnapBuildSetTwoPhaseAt (SnapBuild *builder, XLogRecPtr ptr)
 
void SnapBuildCommitTxn (SnapBuild *builder, XLogRecPtr lsn, TransactionId xid, int nsubxacts, TransactionId *subxacts, uint32 xinfo)
 
bool SnapBuildProcessChange (SnapBuild *builder, TransactionId xid, XLogRecPtr lsn)
 
void SnapBuildProcessNewCid (SnapBuild *builder, TransactionId xid, XLogRecPtr lsn, struct xl_heap_new_cid *xlrec)
 
void SnapBuildProcessRunningXacts (SnapBuild *builder, XLogRecPtr lsn, struct xl_running_xacts *running)
 
void SnapBuildSerializationPoint (SnapBuild *builder, XLogRecPtr lsn)
 

Typedef Documentation

◆ SnapBuild

typedef struct SnapBuild SnapBuild

Definition at line 1 of file snapbuild.h.

Enumeration Type Documentation

◆ SnapBuildState

Enumerator
SNAPBUILD_START 
SNAPBUILD_BUILDING_SNAPSHOT 
SNAPBUILD_FULL_SNAPSHOT 
SNAPBUILD_CONSISTENT 

Definition at line 18 of file snapbuild.h.

19 {
20  /*
21  * Initial state, we can't do much yet.
22  */
23  SNAPBUILD_START = -1,
24 
25  /*
26  * Collecting committed transactions, to build the initial catalog
27  * snapshot.
28  */
30 
31  /*
32  * We have collected enough information to decode tuples in transactions
33  * that started after this.
34  *
35  * Once we reached this we start to collect changes. We cannot apply them
36  * yet, because they might be based on transactions that were still
37  * running when FULL_SNAPSHOT was reached.
38  */
40 
41  /*
42  * Found a point after SNAPBUILD_FULL_SNAPSHOT where all transactions that
43  * were running at that point finished. Till we reach that we hold off
44  * calling any commit callbacks.
45  */
SnapBuildState
Definition: snapbuild.h:19
@ SNAPBUILD_START
Definition: snapbuild.h:23
@ SNAPBUILD_BUILDING_SNAPSHOT
Definition: snapbuild.h:29
@ SNAPBUILD_FULL_SNAPSHOT
Definition: snapbuild.h:39
@ SNAPBUILD_CONSISTENT
Definition: snapbuild.h:46

Function Documentation

◆ AllocateSnapshotBuilder()

SnapBuild* AllocateSnapshotBuilder ( struct ReorderBuffer reorder,
TransactionId  xmin_horizon,
XLogRecPtr  start_lsn,
bool  need_full_snapshot,
XLogRecPtr  two_phase_at 
)

Definition at line 312 of file snapbuild.c.

317 {
318  MemoryContext context;
319  MemoryContext oldcontext;
320  SnapBuild *builder;
321 
322  /* allocate memory in own context, to have better accountability */
324  "snapshot builder context",
326  oldcontext = MemoryContextSwitchTo(context);
327 
328  builder = palloc0(sizeof(SnapBuild));
329 
330  builder->state = SNAPBUILD_START;
331  builder->context = context;
332  builder->reorder = reorder;
333  /* Other struct members initialized by zeroing via palloc0 above */
334 
335  builder->committed.xcnt = 0;
336  builder->committed.xcnt_space = 128; /* arbitrary number */
337  builder->committed.xip =
338  palloc0(builder->committed.xcnt_space * sizeof(TransactionId));
339  builder->committed.includes_all_transactions = true;
340 
341  builder->catchange.xcnt = 0;
342  builder->catchange.xip = NULL;
343 
344  builder->initial_xmin_horizon = xmin_horizon;
345  builder->start_decoding_at = start_lsn;
346  builder->building_full_snapshot = need_full_snapshot;
347  builder->two_phase_at = two_phase_at;
348 
349  MemoryContextSwitchTo(oldcontext);
350 
351  return builder;
352 }
uint32 TransactionId
Definition: c.h:636
void * palloc0(Size size)
Definition: mcxt.c:1241
MemoryContext CurrentMemoryContext
Definition: mcxt.c:135
#define AllocSetContextCreate
Definition: memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:153
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:138
XLogRecPtr start_decoding_at
Definition: snapbuild.c:166
SnapBuildState state
Definition: snapbuild.c:151
TransactionId initial_xmin_horizon
Definition: snapbuild.c:183
struct SnapBuild::@16 committed
TransactionId * xip
Definition: snapbuild.c:243
XLogRecPtr two_phase_at
Definition: snapbuild.c:177
bool building_full_snapshot
Definition: snapbuild.c:186
struct SnapBuild::@17 catchange
size_t xcnt
Definition: snapbuild.c:217
size_t xcnt_space
Definition: snapbuild.c:220
bool includes_all_transactions
Definition: snapbuild.c:227
MemoryContext context
Definition: snapbuild.c:154
ReorderBuffer * reorder
Definition: snapbuild.c:201

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, SnapBuild::building_full_snapshot, SnapBuild::catchange, SnapBuild::committed, SnapBuild::context, CurrentMemoryContext, SnapBuild::includes_all_transactions, SnapBuild::initial_xmin_horizon, MemoryContextSwitchTo(), palloc0(), SnapBuild::reorder, SNAPBUILD_START, SnapBuild::start_decoding_at, SnapBuild::state, SnapBuild::two_phase_at, SnapBuild::xcnt, SnapBuild::xcnt_space, and SnapBuild::xip.

Referenced by StartupDecodingContext().

◆ CheckPointSnapBuild()

void CheckPointSnapBuild ( void  )

Definition at line 2046 of file snapbuild.c.

2047 {
2048  XLogRecPtr cutoff;
2049  XLogRecPtr redo;
2050  DIR *snap_dir;
2051  struct dirent *snap_de;
2052  char path[MAXPGPATH + 21];
2053 
2054  /*
2055  * We start off with a minimum of the last redo pointer. No new
2056  * replication slot will start before that, so that's a safe upper bound
2057  * for removal.
2058  */
2059  redo = GetRedoRecPtr();
2060 
2061  /* now check for the restart ptrs from existing slots */
2063 
2064  /* don't start earlier than the restart lsn */
2065  if (redo < cutoff)
2066  cutoff = redo;
2067 
2068  snap_dir = AllocateDir("pg_logical/snapshots");
2069  while ((snap_de = ReadDir(snap_dir, "pg_logical/snapshots")) != NULL)
2070  {
2071  uint32 hi;
2072  uint32 lo;
2073  XLogRecPtr lsn;
2074  PGFileType de_type;
2075 
2076  if (strcmp(snap_de->d_name, ".") == 0 ||
2077  strcmp(snap_de->d_name, "..") == 0)
2078  continue;
2079 
2080  snprintf(path, sizeof(path), "pg_logical/snapshots/%s", snap_de->d_name);
2081  de_type = get_dirent_type(path, snap_de, false, DEBUG1);
2082 
2083  if (de_type != PGFILETYPE_ERROR && de_type != PGFILETYPE_REG)
2084  {
2085  elog(DEBUG1, "only regular files expected: %s", path);
2086  continue;
2087  }
2088 
2089  /*
2090  * temporary filenames from SnapBuildSerialize() include the LSN and
2091  * everything but are postfixed by .$pid.tmp. We can just remove them
2092  * the same as other files because there can be none that are
2093  * currently being written that are older than cutoff.
2094  *
2095  * We just log a message if a file doesn't fit the pattern, it's
2096  * probably some editors lock/state file or similar...
2097  */
2098  if (sscanf(snap_de->d_name, "%X-%X.snap", &hi, &lo) != 2)
2099  {
2100  ereport(LOG,
2101  (errmsg("could not parse file name \"%s\"", path)));
2102  continue;
2103  }
2104 
2105  lsn = ((uint64) hi) << 32 | lo;
2106 
2107  /* check whether we still need it */
2108  if (lsn < cutoff || cutoff == InvalidXLogRecPtr)
2109  {
2110  elog(DEBUG1, "removing snapbuild snapshot %s", path);
2111 
2112  /*
2113  * It's not particularly harmful, though strange, if we can't
2114  * remove the file here. Don't prevent the checkpoint from
2115  * completing, that'd be a cure worse than the disease.
2116  */
2117  if (unlink(path) < 0)
2118  {
2119  ereport(LOG,
2121  errmsg("could not remove file \"%s\": %m",
2122  path)));
2123  continue;
2124  }
2125  }
2126  }
2127  FreeDir(snap_dir);
2128 }
unsigned int uint32
Definition: c.h:490
int errcode_for_file_access(void)
Definition: elog.c:881
int errmsg(const char *fmt,...)
Definition: elog.c:1069
#define LOG
Definition: elog.h:31
#define DEBUG1
Definition: elog.h:30
#define ereport(elevel,...)
Definition: elog.h:149
struct dirent * ReadDir(DIR *dir, const char *dirname)
Definition: fd.c:2710
int FreeDir(DIR *dir)
Definition: fd.c:2762
DIR * AllocateDir(const char *dirname)
Definition: fd.c:2644
PGFileType get_dirent_type(const char *path, const struct dirent *de, bool look_through_symlinks, int elevel)
Definition: file_utils.c:406
PGFileType
Definition: file_utils.h:19
@ PGFILETYPE_REG
Definition: file_utils.h:22
@ PGFILETYPE_ERROR
Definition: file_utils.h:20
#define MAXPGPATH
#define snprintf
Definition: port.h:238
XLogRecPtr ReplicationSlotsComputeLogicalRestartLSN(void)
Definition: slot.c:935
Definition: dirent.c:26
Definition: dirent.h:10
char d_name[MAX_PATH]
Definition: dirent.h:15
XLogRecPtr GetRedoRecPtr(void)
Definition: xlog.c:6011
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28

References AllocateDir(), dirent::d_name, DEBUG1, elog(), ereport, errcode_for_file_access(), errmsg(), FreeDir(), get_dirent_type(), GetRedoRecPtr(), InvalidXLogRecPtr, LOG, MAXPGPATH, PGFILETYPE_ERROR, PGFILETYPE_REG, ReadDir(), ReplicationSlotsComputeLogicalRestartLSN(), and snprintf.

Referenced by CheckPointGuts().

◆ FreeSnapshotBuilder()

void FreeSnapshotBuilder ( SnapBuild builder)

Definition at line 358 of file snapbuild.c.

359 {
360  MemoryContext context = builder->context;
361 
362  /* free snapshot explicitly, that contains some error checking */
363  if (builder->snapshot != NULL)
364  {
366  builder->snapshot = NULL;
367  }
368 
369  /* other resources are deallocated via memory context reset */
370  MemoryContextDelete(context);
371 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:387
void SnapBuildSnapDecRefcount(Snapshot snap)
Definition: snapbuild.c:453
Snapshot snapshot
Definition: snapbuild.c:191

References SnapBuild::context, MemoryContextDelete(), SnapBuildSnapDecRefcount(), and SnapBuild::snapshot.

Referenced by FreeDecodingContext().

◆ SnapBuildClearExportedSnapshot()

void SnapBuildClearExportedSnapshot ( void  )

Definition at line 725 of file snapbuild.c.

726 {
727  ResourceOwner tmpResOwner;
728 
729  /* nothing exported, that is the usual case */
730  if (!ExportInProgress)
731  return;
732 
733  if (!IsTransactionState())
734  elog(ERROR, "clearing exported snapshot in wrong transaction state");
735 
736  /*
737  * AbortCurrentTransaction() takes care of resetting the snapshot state,
738  * so remember SavedResourceOwnerDuringExport.
739  */
740  tmpResOwner = SavedResourceOwnerDuringExport;
741 
742  /* make sure nothing could have ever happened */
744 
745  CurrentResourceOwner = tmpResOwner;
746 }
#define ERROR
Definition: elog.h:39
ResourceOwner CurrentResourceOwner
Definition: resowner.c:146
static ResourceOwner SavedResourceOwnerDuringExport
Definition: snapbuild.c:278
static bool ExportInProgress
Definition: snapbuild.c:279
bool IsTransactionState(void)
Definition: xact.c:378
void AbortCurrentTransaction(void)
Definition: xact.c:3312

References AbortCurrentTransaction(), CurrentResourceOwner, elog(), ERROR, ExportInProgress, IsTransactionState(), and SavedResourceOwnerDuringExport.

Referenced by exec_replication_command().

◆ SnapBuildCommitTxn()

void SnapBuildCommitTxn ( SnapBuild builder,
XLogRecPtr  lsn,
TransactionId  xid,
int  nsubxacts,
TransactionId subxacts,
uint32  xinfo 
)

Definition at line 1020 of file snapbuild.c.

1022 {
1023  int nxact;
1024 
1025  bool needs_snapshot = false;
1026  bool needs_timetravel = false;
1027  bool sub_needs_timetravel = false;
1028 
1029  TransactionId xmax = xid;
1030 
1031  /*
1032  * Transactions preceding BUILDING_SNAPSHOT will neither be decoded, nor
1033  * will they be part of a snapshot. So we don't need to record anything.
1034  */
1035  if (builder->state == SNAPBUILD_START ||
1036  (builder->state == SNAPBUILD_BUILDING_SNAPSHOT &&
1037  TransactionIdPrecedes(xid, builder->next_phase_at)))
1038  {
1039  /* ensure that only commits after this are getting replayed */
1040  if (builder->start_decoding_at <= lsn)
1041  builder->start_decoding_at = lsn + 1;
1042  return;
1043  }
1044 
1045  if (builder->state < SNAPBUILD_CONSISTENT)
1046  {
1047  /* ensure that only commits after this are getting replayed */
1048  if (builder->start_decoding_at <= lsn)
1049  builder->start_decoding_at = lsn + 1;
1050 
1051  /*
1052  * If building an exportable snapshot, force xid to be tracked, even
1053  * if the transaction didn't modify the catalog.
1054  */
1055  if (builder->building_full_snapshot)
1056  {
1057  needs_timetravel = true;
1058  }
1059  }
1060 
1061  for (nxact = 0; nxact < nsubxacts; nxact++)
1062  {
1063  TransactionId subxid = subxacts[nxact];
1064 
1065  /*
1066  * Add subtransaction to base snapshot if catalog modifying, we don't
1067  * distinguish to toplevel transactions there.
1068  */
1069  if (SnapBuildXidHasCatalogChanges(builder, subxid, xinfo))
1070  {
1071  sub_needs_timetravel = true;
1072  needs_snapshot = true;
1073 
1074  elog(DEBUG1, "found subtransaction %u:%u with catalog changes",
1075  xid, subxid);
1076 
1077  SnapBuildAddCommittedTxn(builder, subxid);
1078 
1079  if (NormalTransactionIdFollows(subxid, xmax))
1080  xmax = subxid;
1081  }
1082 
1083  /*
1084  * If we're forcing timetravel we also need visibility information
1085  * about subtransaction, so keep track of subtransaction's state, even
1086  * if not catalog modifying. Don't need to distribute a snapshot in
1087  * that case.
1088  */
1089  else if (needs_timetravel)
1090  {
1091  SnapBuildAddCommittedTxn(builder, subxid);
1092  if (NormalTransactionIdFollows(subxid, xmax))
1093  xmax = subxid;
1094  }
1095  }
1096 
1097  /* if top-level modified catalog, it'll need a snapshot */
1098  if (SnapBuildXidHasCatalogChanges(builder, xid, xinfo))
1099  {
1100  elog(DEBUG2, "found top level transaction %u, with catalog changes",
1101  xid);
1102  needs_snapshot = true;
1103  needs_timetravel = true;
1104  SnapBuildAddCommittedTxn(builder, xid);
1105  }
1106  else if (sub_needs_timetravel)
1107  {
1108  /* track toplevel txn as well, subxact alone isn't meaningful */
1109  elog(DEBUG2, "forced transaction %u to do timetravel due to one of its subtransactions",
1110  xid);
1111  needs_timetravel = true;
1112  SnapBuildAddCommittedTxn(builder, xid);
1113  }
1114  else if (needs_timetravel)
1115  {
1116  elog(DEBUG2, "forced transaction %u to do timetravel", xid);
1117 
1118  SnapBuildAddCommittedTxn(builder, xid);
1119  }
1120 
1121  if (!needs_timetravel)
1122  {
1123  /* record that we cannot export a general snapshot anymore */
1124  builder->committed.includes_all_transactions = false;
1125  }
1126 
1127  Assert(!needs_snapshot || needs_timetravel);
1128 
1129  /*
1130  * Adjust xmax of the snapshot builder, we only do that for committed,
1131  * catalog modifying, transactions, everything else isn't interesting for
1132  * us since we'll never look at the respective rows.
1133  */
1134  if (needs_timetravel &&
1135  (!TransactionIdIsValid(builder->xmax) ||
1136  TransactionIdFollowsOrEquals(xmax, builder->xmax)))
1137  {
1138  builder->xmax = xmax;
1139  TransactionIdAdvance(builder->xmax);
1140  }
1141 
1142  /* if there's any reason to build a historic snapshot, do so now */
1143  if (needs_snapshot)
1144  {
1145  /*
1146  * If we haven't built a complete snapshot yet there's no need to hand
1147  * it out, it wouldn't (and couldn't) be used anyway.
1148  */
1149  if (builder->state < SNAPBUILD_FULL_SNAPSHOT)
1150  return;
1151 
1152  /*
1153  * Decrease the snapshot builder's refcount of the old snapshot, note
1154  * that it still will be used if it has been handed out to the
1155  * reorderbuffer earlier.
1156  */
1157  if (builder->snapshot)
1159 
1160  builder->snapshot = SnapBuildBuildSnapshot(builder);
1161 
1162  /* we might need to execute invalidations, add snapshot */
1163  if (!ReorderBufferXidHasBaseSnapshot(builder->reorder, xid))
1164  {
1166  ReorderBufferSetBaseSnapshot(builder->reorder, xid, lsn,
1167  builder->snapshot);
1168  }
1169 
1170  /* refcount of the snapshot builder for the new snapshot */
1172 
1173  /* add a new catalog snapshot to all currently running transactions */
1175  }
1176 }
#define DEBUG2
Definition: elog.h:29
Assert(fmt[strlen(fmt) - 1] !='\n')
void ReorderBufferSetBaseSnapshot(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, Snapshot snap)
bool ReorderBufferXidHasBaseSnapshot(ReorderBuffer *rb, TransactionId xid)
static void SnapBuildSnapIncRefcount(Snapshot snap)
Definition: snapbuild.c:441
static void SnapBuildAddCommittedTxn(SnapBuild *builder, TransactionId xid)
Definition: snapbuild.c:909
static bool SnapBuildXidHasCatalogChanges(SnapBuild *builder, TransactionId xid, uint32 xinfo)
Definition: snapbuild.c:1183
static Snapshot SnapBuildBuildSnapshot(SnapBuild *builder)
Definition: snapbuild.c:485
static void SnapBuildDistributeNewCatalogSnapshot(SnapBuild *builder, XLogRecPtr lsn)
Definition: snapbuild.c:856
TransactionId xmax
Definition: snapbuild.c:160
TransactionId next_phase_at
Definition: snapbuild.c:208
bool TransactionIdPrecedes(TransactionId id1, TransactionId id2)
Definition: transam.c:280
bool TransactionIdFollowsOrEquals(TransactionId id1, TransactionId id2)
Definition: transam.c:329
#define NormalTransactionIdFollows(id1, id2)
Definition: transam.h:152
#define TransactionIdIsValid(xid)
Definition: transam.h:41
#define TransactionIdAdvance(dest)
Definition: transam.h:91

References Assert(), SnapBuild::building_full_snapshot, SnapBuild::committed, DEBUG1, DEBUG2, elog(), SnapBuild::includes_all_transactions, SnapBuild::next_phase_at, NormalTransactionIdFollows, SnapBuild::reorder, ReorderBufferSetBaseSnapshot(), ReorderBufferXidHasBaseSnapshot(), SNAPBUILD_BUILDING_SNAPSHOT, SNAPBUILD_CONSISTENT, SNAPBUILD_FULL_SNAPSHOT, SNAPBUILD_START, SnapBuildAddCommittedTxn(), SnapBuildBuildSnapshot(), SnapBuildDistributeNewCatalogSnapshot(), SnapBuildSnapDecRefcount(), SnapBuildSnapIncRefcount(), SnapBuildXidHasCatalogChanges(), SnapBuild::snapshot, SnapBuild::start_decoding_at, SnapBuild::state, TransactionIdAdvance, TransactionIdFollowsOrEquals(), TransactionIdIsValid, TransactionIdPrecedes(), and SnapBuild::xmax.

Referenced by DecodeCommit().

◆ SnapBuildCurrentState()

SnapBuildState SnapBuildCurrentState ( SnapBuild builder)

Definition at line 402 of file snapbuild.c.

403 {
404  return builder->state;
405 }

References SnapBuild::state.

Referenced by DecodePrepare(), DecodingContextReady(), heap2_decode(), heap_decode(), logicalmsg_decode(), ReorderBufferCanStartStreaming(), and xact_decode().

◆ SnapBuildExportSnapshot()

const char* SnapBuildExportSnapshot ( SnapBuild builder)

Definition at line 664 of file snapbuild.c.

665 {
666  Snapshot snap;
667  char *snapname;
668 
670  elog(ERROR, "cannot export a snapshot from within a transaction");
671 
673  elog(ERROR, "can only export one snapshot at a time");
674 
676  ExportInProgress = true;
677 
679 
680  /* There doesn't seem to a nice API to set these */
682  XactReadOnly = true;
683 
684  snap = SnapBuildInitialSnapshot(builder);
685 
686  /*
687  * now that we've built a plain snapshot, make it active and use the
688  * normal mechanisms for exporting it
689  */
690  snapname = ExportSnapshot(snap);
691 
692  ereport(LOG,
693  (errmsg_plural("exported logical decoding snapshot: \"%s\" with %u transaction ID",
694  "exported logical decoding snapshot: \"%s\" with %u transaction IDs",
695  snap->xcnt,
696  snapname, snap->xcnt)));
697  return snapname;
698 }
int errmsg_plural(const char *fmt_singular, const char *fmt_plural, unsigned long n,...)
Definition: elog.c:1179
Snapshot SnapBuildInitialSnapshot(SnapBuild *builder)
Definition: snapbuild.c:565
char * ExportSnapshot(Snapshot snapshot)
Definition: snapmgr.c:1125
uint32 xcnt
Definition: snapshot.h:169
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4841
bool XactReadOnly
Definition: xact.c:82
void StartTransactionCommand(void)
Definition: xact.c:2944
int XactIsoLevel
Definition: xact.c:79
#define XACT_REPEATABLE_READ
Definition: xact.h:38

References CurrentResourceOwner, elog(), ereport, errmsg_plural(), ERROR, ExportInProgress, ExportSnapshot(), IsTransactionOrTransactionBlock(), LOG, SavedResourceOwnerDuringExport, SnapBuildInitialSnapshot(), StartTransactionCommand(), XACT_REPEATABLE_READ, XactIsoLevel, XactReadOnly, and SnapshotData::xcnt.

Referenced by CreateReplicationSlot().

◆ SnapBuildGetOrBuildSnapshot()

Snapshot SnapBuildGetOrBuildSnapshot ( SnapBuild builder)

Definition at line 704 of file snapbuild.c.

705 {
706  Assert(builder->state == SNAPBUILD_CONSISTENT);
707 
708  /* only build a new snapshot if we don't have a prebuilt one */
709  if (builder->snapshot == NULL)
710  {
711  builder->snapshot = SnapBuildBuildSnapshot(builder);
712  /* increase refcount for the snapshot builder */
714  }
715 
716  return builder->snapshot;
717 }

References Assert(), SNAPBUILD_CONSISTENT, SnapBuildBuildSnapshot(), SnapBuildSnapIncRefcount(), SnapBuild::snapshot, and SnapBuild::state.

Referenced by logicalmsg_decode().

◆ SnapBuildGetTwoPhaseAt()

XLogRecPtr SnapBuildGetTwoPhaseAt ( SnapBuild builder)

Definition at line 411 of file snapbuild.c.

412 {
413  return builder->two_phase_at;
414 }

References SnapBuild::two_phase_at.

Referenced by DecodeCommit().

◆ SnapBuildInitialSnapshot()

Snapshot SnapBuildInitialSnapshot ( SnapBuild builder)

Definition at line 565 of file snapbuild.c.

566 {
567  Snapshot snap;
568  TransactionId xid;
569  TransactionId safeXid;
570  TransactionId *newxip;
571  int newxcnt = 0;
572 
574  Assert(builder->building_full_snapshot);
575 
576  /* don't allow older snapshots */
577  InvalidateCatalogSnapshot(); /* about to overwrite MyProc->xmin */
579  elog(ERROR, "cannot build an initial slot snapshot when snapshots exist");
581 
582  if (builder->state != SNAPBUILD_CONSISTENT)
583  elog(ERROR, "cannot build an initial slot snapshot before reaching a consistent state");
584 
585  if (!builder->committed.includes_all_transactions)
586  elog(ERROR, "cannot build an initial slot snapshot, not all transactions are monitored anymore");
587 
588  /* so we don't overwrite the existing value */
590  elog(ERROR, "cannot build an initial slot snapshot when MyProc->xmin already is valid");
591 
592  snap = SnapBuildBuildSnapshot(builder);
593 
594  /*
595  * We know that snap->xmin is alive, enforced by the logical xmin
596  * mechanism. Due to that we can do this without locks, we're only
597  * changing our own value.
598  *
599  * Building an initial snapshot is expensive and an unenforced xmin
600  * horizon would have bad consequences, therefore always double-check that
601  * the horizon is enforced.
602  */
603  LWLockAcquire(ProcArrayLock, LW_SHARED);
604  safeXid = GetOldestSafeDecodingTransactionId(false);
605  LWLockRelease(ProcArrayLock);
606 
607  if (TransactionIdFollows(safeXid, snap->xmin))
608  elog(ERROR, "cannot build an initial slot snapshot as oldest safe xid %u follows snapshot's xmin %u",
609  safeXid, snap->xmin);
610 
611  MyProc->xmin = snap->xmin;
612 
613  /* allocate in transaction context */
614  newxip = (TransactionId *)
616 
617  /*
618  * snapbuild.c builds transactions in an "inverted" manner, which means it
619  * stores committed transactions in ->xip, not ones in progress. Build a
620  * classical snapshot by marking all non-committed transactions as
621  * in-progress. This can be expensive.
622  */
623  for (xid = snap->xmin; NormalTransactionIdPrecedes(xid, snap->xmax);)
624  {
625  void *test;
626 
627  /*
628  * Check whether transaction committed using the decoding snapshot
629  * meaning of ->xip.
630  */
631  test = bsearch(&xid, snap->xip, snap->xcnt,
632  sizeof(TransactionId), xidComparator);
633 
634  if (test == NULL)
635  {
636  if (newxcnt >= GetMaxSnapshotXidCount())
637  ereport(ERROR,
639  errmsg("initial slot snapshot too large")));
640 
641  newxip[newxcnt++] = xid;
642  }
643 
645  }
646 
647  /* adjust remaining snapshot fields as needed */
649  snap->xcnt = newxcnt;
650  snap->xip = newxip;
651 
652  return snap;
653 }
int errcode(int sqlerrcode)
Definition: elog.c:858
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1195
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
@ LW_SHARED
Definition: lwlock.h:116
void * palloc(Size size)
Definition: mcxt.c:1210
#define ERRCODE_T_R_SERIALIZATION_FAILURE
Definition: pgbench.c:76
static void test(void)
TransactionId GetOldestSafeDecodingTransactionId(bool catalogOnly)
Definition: procarray.c:2992
int GetMaxSnapshotXidCount(void)
Definition: procarray.c:2098
bool HistoricSnapshotActive(void)
Definition: snapmgr.c:2103
bool HaveRegisteredOrActiveSnapshot(void)
Definition: snapmgr.c:1641
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:457
@ SNAPSHOT_MVCC
Definition: snapshot.h:50
PGPROC * MyProc
Definition: proc.c:66
TransactionId xmin
Definition: proc.h:178
TransactionId xmin
Definition: snapshot.h:157
TransactionId xmax
Definition: snapshot.h:158
SnapshotType snapshot_type
Definition: snapshot.h:144
TransactionId * xip
Definition: snapshot.h:168
bool TransactionIdFollows(TransactionId id1, TransactionId id2)
Definition: transam.c:314
#define NormalTransactionIdPrecedes(id1, id2)
Definition: transam.h:147
int xidComparator(const void *arg1, const void *arg2)
Definition: xid.c:138

References Assert(), SnapBuild::building_full_snapshot, SnapBuild::committed, elog(), ereport, errcode(), ERRCODE_T_R_SERIALIZATION_FAILURE, errmsg(), ERROR, GetMaxSnapshotXidCount(), GetOldestSafeDecodingTransactionId(), HaveRegisteredOrActiveSnapshot(), HistoricSnapshotActive(), SnapBuild::includes_all_transactions, InvalidateCatalogSnapshot(), LW_SHARED, LWLockAcquire(), LWLockRelease(), MyProc, NormalTransactionIdPrecedes, palloc(), SNAPBUILD_CONSISTENT, SnapBuildBuildSnapshot(), SNAPSHOT_MVCC, SnapshotData::snapshot_type, SnapBuild::state, test(), TransactionIdAdvance, TransactionIdFollows(), TransactionIdIsValid, XACT_REPEATABLE_READ, XactIsoLevel, SnapshotData::xcnt, xidComparator(), SnapshotData::xip, SnapshotData::xmax, PGPROC::xmin, and SnapshotData::xmin.

Referenced by CreateReplicationSlot(), and SnapBuildExportSnapshot().

◆ SnapBuildProcessChange()

bool SnapBuildProcessChange ( SnapBuild builder,
TransactionId  xid,
XLogRecPtr  lsn 
)

Definition at line 764 of file snapbuild.c.

765 {
766  /*
767  * We can't handle data in transactions if we haven't built a snapshot
768  * yet, so don't store them.
769  */
770  if (builder->state < SNAPBUILD_FULL_SNAPSHOT)
771  return false;
772 
773  /*
774  * No point in keeping track of changes in transactions that we don't have
775  * enough information about to decode. This means that they started before
776  * we got into the SNAPBUILD_FULL_SNAPSHOT state.
777  */
778  if (builder->state < SNAPBUILD_CONSISTENT &&
779  TransactionIdPrecedes(xid, builder->next_phase_at))
780  return false;
781 
782  /*
783  * If the reorderbuffer doesn't yet have a snapshot, add one now, it will
784  * be needed to decode the change we're currently processing.
785  */
786  if (!ReorderBufferXidHasBaseSnapshot(builder->reorder, xid))
787  {
788  /* only build a new snapshot if we don't have a prebuilt one */
789  if (builder->snapshot == NULL)
790  {
791  builder->snapshot = SnapBuildBuildSnapshot(builder);
792  /* increase refcount for the snapshot builder */
794  }
795 
796  /*
797  * Increase refcount for the transaction we're handing the snapshot
798  * out to.
799  */
801  ReorderBufferSetBaseSnapshot(builder->reorder, xid, lsn,
802  builder->snapshot);
803  }
804 
805  return true;
806 }

References SnapBuild::next_phase_at, SnapBuild::reorder, ReorderBufferSetBaseSnapshot(), ReorderBufferXidHasBaseSnapshot(), SNAPBUILD_CONSISTENT, SNAPBUILD_FULL_SNAPSHOT, SnapBuildBuildSnapshot(), SnapBuildSnapIncRefcount(), SnapBuild::snapshot, SnapBuild::state, and TransactionIdPrecedes().

Referenced by heap2_decode(), heap_decode(), and logicalmsg_decode().

◆ SnapBuildProcessNewCid()

void SnapBuildProcessNewCid ( SnapBuild builder,
TransactionId  xid,
XLogRecPtr  lsn,
struct xl_heap_new_cid xlrec 
)

Definition at line 814 of file snapbuild.c.

816 {
817  CommandId cid;
818 
819  /*
820  * we only log new_cid's if a catalog tuple was modified, so mark the
821  * transaction as containing catalog modifications
822  */
823  ReorderBufferXidSetCatalogChanges(builder->reorder, xid, lsn);
824 
825  ReorderBufferAddNewTupleCids(builder->reorder, xlrec->top_xid, lsn,
826  xlrec->target_locator, xlrec->target_tid,
827  xlrec->cmin, xlrec->cmax,
828  xlrec->combocid);
829 
830  /* figure out new command id */
831  if (xlrec->cmin != InvalidCommandId &&
832  xlrec->cmax != InvalidCommandId)
833  cid = Max(xlrec->cmin, xlrec->cmax);
834  else if (xlrec->cmax != InvalidCommandId)
835  cid = xlrec->cmax;
836  else if (xlrec->cmin != InvalidCommandId)
837  cid = xlrec->cmin;
838  else
839  {
840  cid = InvalidCommandId; /* silence compiler */
841  elog(ERROR, "xl_heap_new_cid record without a valid CommandId");
842  }
843 
844  ReorderBufferAddNewCommandId(builder->reorder, xid, lsn, cid + 1);
845 }
#define InvalidCommandId
Definition: c.h:653
#define Max(x, y)
Definition: c.h:982
uint32 CommandId
Definition: c.h:650
void ReorderBufferXidSetCatalogChanges(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn)
void ReorderBufferAddNewCommandId(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, CommandId cid)
void ReorderBufferAddNewTupleCids(ReorderBuffer *rb, TransactionId xid, XLogRecPtr lsn, RelFileLocator locator, ItemPointerData tid, CommandId cmin, CommandId cmax, CommandId combocid)
CommandId cmin
Definition: heapam_xlog.h:376
CommandId combocid
Definition: heapam_xlog.h:378
ItemPointerData target_tid
Definition: heapam_xlog.h:384
TransactionId top_xid
Definition: heapam_xlog.h:375
CommandId cmax
Definition: heapam_xlog.h:377
RelFileLocator target_locator
Definition: heapam_xlog.h:383

References xl_heap_new_cid::cmax, xl_heap_new_cid::cmin, xl_heap_new_cid::combocid, elog(), ERROR, InvalidCommandId, Max, SnapBuild::reorder, ReorderBufferAddNewCommandId(), ReorderBufferAddNewTupleCids(), ReorderBufferXidSetCatalogChanges(), xl_heap_new_cid::target_locator, xl_heap_new_cid::target_tid, and xl_heap_new_cid::top_xid.

Referenced by heap2_decode().

◆ SnapBuildProcessRunningXacts()

void SnapBuildProcessRunningXacts ( SnapBuild builder,
XLogRecPtr  lsn,
struct xl_running_xacts running 
)

Definition at line 1213 of file snapbuild.c.

1214 {
1215  ReorderBufferTXN *txn;
1216  TransactionId xmin;
1217 
1218  /*
1219  * If we're not consistent yet, inspect the record to see whether it
1220  * allows to get closer to being consistent. If we are consistent, dump
1221  * our snapshot so others or we, after a restart, can use it.
1222  */
1223  if (builder->state < SNAPBUILD_CONSISTENT)
1224  {
1225  /* returns false if there's no point in performing cleanup just yet */
1226  if (!SnapBuildFindSnapshot(builder, lsn, running))
1227  return;
1228  }
1229  else
1230  SnapBuildSerialize(builder, lsn);
1231 
1232  /*
1233  * Update range of interesting xids based on the running xacts
1234  * information. We don't increase ->xmax using it, because once we are in
1235  * a consistent state we can do that ourselves and much more efficiently
1236  * so, because we only need to do it for catalog transactions since we
1237  * only ever look at those.
1238  *
1239  * NB: We only increase xmax when a catalog modifying transaction commits
1240  * (see SnapBuildCommitTxn). Because of this, xmax can be lower than
1241  * xmin, which looks odd but is correct and actually more efficient, since
1242  * we hit fast paths in heapam_visibility.c.
1243  */
1244  builder->xmin = running->oldestRunningXid;
1245 
1246  /* Remove transactions we don't need to keep track off anymore */
1247  SnapBuildPurgeOlderTxn(builder);
1248 
1249  /*
1250  * Advance the xmin limit for the current replication slot, to allow
1251  * vacuum to clean up the tuples this slot has been protecting.
1252  *
1253  * The reorderbuffer might have an xmin among the currently running
1254  * snapshots; use it if so. If not, we need only consider the snapshots
1255  * we'll produce later, which can't be less than the oldest running xid in
1256  * the record we're reading now.
1257  */
1258  xmin = ReorderBufferGetOldestXmin(builder->reorder);
1259  if (xmin == InvalidTransactionId)
1260  xmin = running->oldestRunningXid;
1261  elog(DEBUG3, "xmin: %u, xmax: %u, oldest running: %u, oldest xmin: %u",
1262  builder->xmin, builder->xmax, running->oldestRunningXid, xmin);
1263  LogicalIncreaseXminForSlot(lsn, xmin);
1264 
1265  /*
1266  * Also tell the slot where we can restart decoding from. We don't want to
1267  * do that after every commit because changing that implies an fsync of
1268  * the logical slot's state file, so we only do it every time we see a
1269  * running xacts record.
1270  *
1271  * Do so by looking for the oldest in progress transaction (determined by
1272  * the first LSN of any of its relevant records). Every transaction
1273  * remembers the last location we stored the snapshot to disk before its
1274  * beginning. That point is where we can restart from.
1275  */
1276 
1277  /*
1278  * Can't know about a serialized snapshot's location if we're not
1279  * consistent.
1280  */
1281  if (builder->state < SNAPBUILD_CONSISTENT)
1282  return;
1283 
1284  txn = ReorderBufferGetOldestTXN(builder->reorder);
1285 
1286  /*
1287  * oldest ongoing txn might have started when we didn't yet serialize
1288  * anything because we hadn't reached a consistent state yet.
1289  */
1290  if (txn != NULL && txn->restart_decoding_lsn != InvalidXLogRecPtr)
1292 
1293  /*
1294  * No in-progress transaction, can reuse the last serialized snapshot if
1295  * we have one.
1296  */
1297  else if (txn == NULL &&
1301  builder->last_serialized_snapshot);
1302 }
#define DEBUG3
Definition: elog.h:28
void LogicalIncreaseRestartDecodingForSlot(XLogRecPtr current_lsn, XLogRecPtr restart_lsn)
Definition: logical.c:1714
void LogicalIncreaseXminForSlot(XLogRecPtr current_lsn, TransactionId xmin)
Definition: logical.c:1646
TransactionId ReorderBufferGetOldestXmin(ReorderBuffer *rb)
ReorderBufferTXN * ReorderBufferGetOldestTXN(ReorderBuffer *rb)
static void SnapBuildSerialize(SnapBuild *builder, XLogRecPtr lsn)
Definition: snapbuild.c:1601
static bool SnapBuildFindSnapshot(SnapBuild *builder, XLogRecPtr lsn, xl_running_xacts *running)
Definition: snapbuild.c:1315
static void SnapBuildPurgeOlderTxn(SnapBuild *builder)
Definition: snapbuild.c:943
XLogRecPtr restart_decoding_lsn
XLogRecPtr current_restart_decoding_lsn
TransactionId xmin
Definition: snapbuild.c:157
XLogRecPtr last_serialized_snapshot
Definition: snapbuild.c:196
TransactionId oldestRunningXid
Definition: standbydefs.h:53
#define InvalidTransactionId
Definition: transam.h:31

References ReorderBuffer::current_restart_decoding_lsn, DEBUG3, elog(), InvalidTransactionId, InvalidXLogRecPtr, SnapBuild::last_serialized_snapshot, LogicalIncreaseRestartDecodingForSlot(), LogicalIncreaseXminForSlot(), xl_running_xacts::oldestRunningXid, SnapBuild::reorder, ReorderBufferGetOldestTXN(), ReorderBufferGetOldestXmin(), ReorderBufferTXN::restart_decoding_lsn, SNAPBUILD_CONSISTENT, SnapBuildFindSnapshot(), SnapBuildPurgeOlderTxn(), SnapBuildSerialize(), SnapBuild::state, SnapBuild::xmax, and SnapBuild::xmin.

Referenced by standby_decode().

◆ SnapBuildResetExportedSnapshotState()

void SnapBuildResetExportedSnapshotState ( void  )

Definition at line 752 of file snapbuild.c.

753 {
755  ExportInProgress = false;
756 }

References ExportInProgress, and SavedResourceOwnerDuringExport.

Referenced by AbortTransaction().

◆ SnapBuildSerializationPoint()

void SnapBuildSerializationPoint ( SnapBuild builder,
XLogRecPtr  lsn 
)

Definition at line 1588 of file snapbuild.c.

1589 {
1590  if (builder->state < SNAPBUILD_CONSISTENT)
1591  SnapBuildRestore(builder, lsn);
1592  else
1593  SnapBuildSerialize(builder, lsn);
1594 }
static bool SnapBuildRestore(SnapBuild *builder, XLogRecPtr lsn)
Definition: snapbuild.c:1841

References SNAPBUILD_CONSISTENT, SnapBuildRestore(), SnapBuildSerialize(), and SnapBuild::state.

Referenced by xlog_decode().

◆ SnapBuildSetTwoPhaseAt()

void SnapBuildSetTwoPhaseAt ( SnapBuild builder,
XLogRecPtr  ptr 
)

Definition at line 420 of file snapbuild.c.

421 {
422  builder->two_phase_at = ptr;
423 }

References SnapBuild::two_phase_at.

Referenced by CreateDecodingContext().

◆ SnapBuildSnapDecRefcount()

void SnapBuildSnapDecRefcount ( Snapshot  snap)

Definition at line 453 of file snapbuild.c.

454 {
455  /* make sure we don't get passed an external snapshot */
457 
458  /* make sure nobody modified our snapshot */
459  Assert(snap->curcid == FirstCommandId);
460  Assert(!snap->suboverflowed);
461  Assert(!snap->takenDuringRecovery);
462 
463  Assert(snap->regd_count == 0);
464 
465  Assert(snap->active_count > 0);
466 
467  /* slightly more likely, so it's checked even without casserts */
468  if (snap->copied)
469  elog(ERROR, "cannot free a copied snapshot");
470 
471  snap->active_count--;
472  if (snap->active_count == 0)
473  SnapBuildFreeSnapshot(snap);
474 }
#define FirstCommandId
Definition: c.h:652
static void SnapBuildFreeSnapshot(Snapshot snap)
Definition: snapbuild.c:377
@ SNAPSHOT_HISTORIC_MVCC
Definition: snapshot.h:109
bool copied
Definition: snapshot.h:185
uint32 regd_count
Definition: snapshot.h:205
uint32 active_count
Definition: snapshot.h:204
CommandId curcid
Definition: snapshot.h:187
bool suboverflowed
Definition: snapshot.h:182
bool takenDuringRecovery
Definition: snapshot.h:184

References SnapshotData::active_count, Assert(), SnapshotData::copied, SnapshotData::curcid, elog(), ERROR, FirstCommandId, SnapshotData::regd_count, SnapBuildFreeSnapshot(), SNAPSHOT_HISTORIC_MVCC, SnapshotData::snapshot_type, SnapshotData::suboverflowed, and SnapshotData::takenDuringRecovery.

Referenced by FreeSnapshotBuilder(), ReorderBufferCleanupTXN(), ReorderBufferFreeSnap(), ReorderBufferTransferSnapToParent(), SnapBuildCommitTxn(), and SnapBuildRestore().

◆ SnapBuildXactNeedsSkip()

bool SnapBuildXactNeedsSkip ( SnapBuild builder,
XLogRecPtr  ptr 
)

Definition at line 429 of file snapbuild.c.

430 {
431  return ptr < builder->start_decoding_at;
432 }

References SnapBuild::start_decoding_at.

Referenced by AssertTXNLsnOrder(), DecodeTXNNeedSkip(), logicalmsg_decode(), and ReorderBufferCanStartStreaming().