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 317 of file snapbuild.c.

322 {
323  MemoryContext context;
324  MemoryContext oldcontext;
325  SnapBuild *builder;
326 
327  /* allocate memory in own context, to have better accountability */
329  "snapshot builder context",
331  oldcontext = MemoryContextSwitchTo(context);
332 
333  builder = palloc0(sizeof(SnapBuild));
334 
335  builder->state = SNAPBUILD_START;
336  builder->context = context;
337  builder->reorder = reorder;
338  /* Other struct members initialized by zeroing via palloc0 above */
339 
340  builder->committed.xcnt = 0;
341  builder->committed.xcnt_space = 128; /* arbitrary number */
342  builder->committed.xip =
343  palloc0(builder->committed.xcnt_space * sizeof(TransactionId));
344  builder->committed.includes_all_transactions = true;
345 
346  builder->catchange.xcnt = 0;
347  builder->catchange.xip = NULL;
348 
349  builder->initial_xmin_horizon = xmin_horizon;
350  builder->start_decoding_at = start_lsn;
351  builder->building_full_snapshot = need_full_snapshot;
352  builder->two_phase_at = two_phase_at;
353 
354  MemoryContextSwitchTo(oldcontext);
355 
356  return builder;
357 }
uint32 TransactionId
Definition: c.h:641
void * palloc0(Size size)
Definition: mcxt.c:1257
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:171
SnapBuildState state
Definition: snapbuild.c:156
TransactionId initial_xmin_horizon
Definition: snapbuild.c:188
struct SnapBuild::@16 committed
TransactionId * xip
Definition: snapbuild.c:248
XLogRecPtr two_phase_at
Definition: snapbuild.c:182
bool building_full_snapshot
Definition: snapbuild.c:191
struct SnapBuild::@17 catchange
size_t xcnt
Definition: snapbuild.c:222
size_t xcnt_space
Definition: snapbuild.c:225
bool includes_all_transactions
Definition: snapbuild.c:232
MemoryContext context
Definition: snapbuild.c:159
ReorderBuffer * reorder
Definition: snapbuild.c:206

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 2055 of file snapbuild.c.

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

364 {
365  MemoryContext context = builder->context;
366 
367  /* free snapshot explicitly, that contains some error checking */
368  if (builder->snapshot != NULL)
369  {
371  builder->snapshot = NULL;
372  }
373 
374  /* other resources are deallocated via memory context reset */
375  MemoryContextDelete(context);
376 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:403
void SnapBuildSnapDecRefcount(Snapshot snap)
Definition: snapbuild.c:458
Snapshot snapshot
Definition: snapbuild.c:196

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

Referenced by FreeDecodingContext().

◆ SnapBuildClearExportedSnapshot()

void SnapBuildClearExportedSnapshot ( void  )

Definition at line 730 of file snapbuild.c.

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

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 1025 of file snapbuild.c.

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

408 {
409  return builder->state;
410 }

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 669 of file snapbuild.c.

670 {
671  Snapshot snap;
672  char *snapname;
673 
675  elog(ERROR, "cannot export a snapshot from within a transaction");
676 
678  elog(ERROR, "can only export one snapshot at a time");
679 
681  ExportInProgress = true;
682 
684 
685  /* There doesn't seem to a nice API to set these */
687  XactReadOnly = true;
688 
689  snap = SnapBuildInitialSnapshot(builder);
690 
691  /*
692  * now that we've built a plain snapshot, make it active and use the
693  * normal mechanisms for exporting it
694  */
695  snapname = ExportSnapshot(snap);
696 
697  ereport(LOG,
698  (errmsg_plural("exported logical decoding snapshot: \"%s\" with %u transaction ID",
699  "exported logical decoding snapshot: \"%s\" with %u transaction IDs",
700  snap->xcnt,
701  snapname, snap->xcnt)));
702  return snapname;
703 }
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:570
char * ExportSnapshot(Snapshot snapshot)
Definition: snapmgr.c:1071
uint32 xcnt
Definition: snapshot.h:169
bool IsTransactionOrTransactionBlock(void)
Definition: xact.c:4834
bool XactReadOnly
Definition: xact.c:82
void StartTransactionCommand(void)
Definition: xact.c:2937
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 709 of file snapbuild.c.

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

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

Referenced by logicalmsg_decode().

◆ SnapBuildGetTwoPhaseAt()

XLogRecPtr SnapBuildGetTwoPhaseAt ( SnapBuild builder)

Definition at line 416 of file snapbuild.c.

417 {
418  return builder->two_phase_at;
419 }

References SnapBuild::two_phase_at.

Referenced by DecodeCommit().

◆ SnapBuildInitialSnapshot()

Snapshot SnapBuildInitialSnapshot ( SnapBuild builder)

Definition at line 570 of file snapbuild.c.

571 {
572  Snapshot snap;
573  TransactionId xid;
574  TransactionId safeXid;
575  TransactionId *newxip;
576  int newxcnt = 0;
577 
579  Assert(builder->building_full_snapshot);
580 
581  /* don't allow older snapshots */
582  InvalidateCatalogSnapshot(); /* about to overwrite MyProc->xmin */
584  elog(ERROR, "cannot build an initial slot snapshot when snapshots exist");
586 
587  if (builder->state != SNAPBUILD_CONSISTENT)
588  elog(ERROR, "cannot build an initial slot snapshot before reaching a consistent state");
589 
590  if (!builder->committed.includes_all_transactions)
591  elog(ERROR, "cannot build an initial slot snapshot, not all transactions are monitored anymore");
592 
593  /* so we don't overwrite the existing value */
595  elog(ERROR, "cannot build an initial slot snapshot when MyProc->xmin already is valid");
596 
597  snap = SnapBuildBuildSnapshot(builder);
598 
599  /*
600  * We know that snap->xmin is alive, enforced by the logical xmin
601  * mechanism. Due to that we can do this without locks, we're only
602  * changing our own value.
603  *
604  * Building an initial snapshot is expensive and an unenforced xmin
605  * horizon would have bad consequences, therefore always double-check that
606  * the horizon is enforced.
607  */
608  LWLockAcquire(ProcArrayLock, LW_SHARED);
609  safeXid = GetOldestSafeDecodingTransactionId(false);
610  LWLockRelease(ProcArrayLock);
611 
612  if (TransactionIdFollows(safeXid, snap->xmin))
613  elog(ERROR, "cannot build an initial slot snapshot as oldest safe xid %u follows snapshot's xmin %u",
614  safeXid, snap->xmin);
615 
616  MyProc->xmin = snap->xmin;
617 
618  /* allocate in transaction context */
619  newxip = (TransactionId *)
621 
622  /*
623  * snapbuild.c builds transactions in an "inverted" manner, which means it
624  * stores committed transactions in ->xip, not ones in progress. Build a
625  * classical snapshot by marking all non-committed transactions as
626  * in-progress. This can be expensive.
627  */
628  for (xid = snap->xmin; NormalTransactionIdPrecedes(xid, snap->xmax);)
629  {
630  void *test;
631 
632  /*
633  * Check whether transaction committed using the decoding snapshot
634  * meaning of ->xip.
635  */
636  test = bsearch(&xid, snap->xip, snap->xcnt,
637  sizeof(TransactionId), xidComparator);
638 
639  if (test == NULL)
640  {
641  if (newxcnt >= GetMaxSnapshotXidCount())
642  ereport(ERROR,
644  errmsg("initial slot snapshot too large")));
645 
646  newxip[newxcnt++] = xid;
647  }
648 
650  }
651 
652  /* adjust remaining snapshot fields as needed */
654  snap->xcnt = newxcnt;
655  snap->xip = newxip;
656 
657  return snap;
658 }
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:1808
@ LW_SHARED
Definition: lwlock.h:117
void * palloc(Size size)
Definition: mcxt.c:1226
#define ERRCODE_T_R_SERIALIZATION_FAILURE
Definition: pgbench.c:76
static void test(void)
TransactionId GetOldestSafeDecodingTransactionId(bool catalogOnly)
Definition: procarray.c:2910
int GetMaxSnapshotXidCount(void)
Definition: procarray.c:2050
bool HistoricSnapshotActive(void)
Definition: snapmgr.c:1647
bool HaveRegisteredOrActiveSnapshot(void)
Definition: snapmgr.c:1599
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:403
@ 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 769 of file snapbuild.c.

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

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 819 of file snapbuild.c.

821 {
822  CommandId cid;
823 
824  /*
825  * we only log new_cid's if a catalog tuple was modified, so mark the
826  * transaction as containing catalog modifications
827  */
828  ReorderBufferXidSetCatalogChanges(builder->reorder, xid, lsn);
829 
830  ReorderBufferAddNewTupleCids(builder->reorder, xlrec->top_xid, lsn,
831  xlrec->target_locator, xlrec->target_tid,
832  xlrec->cmin, xlrec->cmax,
833  xlrec->combocid);
834 
835  /* figure out new command id */
836  if (xlrec->cmin != InvalidCommandId &&
837  xlrec->cmax != InvalidCommandId)
838  cid = Max(xlrec->cmin, xlrec->cmax);
839  else if (xlrec->cmax != InvalidCommandId)
840  cid = xlrec->cmax;
841  else if (xlrec->cmin != InvalidCommandId)
842  cid = xlrec->cmin;
843  else
844  {
845  cid = InvalidCommandId; /* silence compiler */
846  elog(ERROR, "xl_heap_new_cid record without a valid CommandId");
847  }
848 
849  ReorderBufferAddNewCommandId(builder->reorder, xid, lsn, cid + 1);
850 }
#define InvalidCommandId
Definition: c.h:658
#define Max(x, y)
Definition: c.h:987
uint32 CommandId
Definition: c.h:655
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:380
CommandId combocid
Definition: heapam_xlog.h:382
ItemPointerData target_tid
Definition: heapam_xlog.h:388
TransactionId top_xid
Definition: heapam_xlog.h:379
CommandId cmax
Definition: heapam_xlog.h:381
RelFileLocator target_locator
Definition: heapam_xlog.h:387

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 1218 of file snapbuild.c.

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

758 {
760  ExportInProgress = false;
761 }

References ExportInProgress, and SavedResourceOwnerDuringExport.

Referenced by AbortTransaction().

◆ SnapBuildSerializationPoint()

void SnapBuildSerializationPoint ( SnapBuild builder,
XLogRecPtr  lsn 
)

Definition at line 1593 of file snapbuild.c.

1594 {
1595  if (builder->state < SNAPBUILD_CONSISTENT)
1596  SnapBuildRestore(builder, lsn);
1597  else
1598  SnapBuildSerialize(builder, lsn);
1599 }
static bool SnapBuildRestore(SnapBuild *builder, XLogRecPtr lsn)
Definition: snapbuild.c:1846

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

Referenced by xlog_decode().

◆ SnapBuildSetTwoPhaseAt()

void SnapBuildSetTwoPhaseAt ( SnapBuild builder,
XLogRecPtr  ptr 
)

Definition at line 425 of file snapbuild.c.

426 {
427  builder->two_phase_at = ptr;
428 }

References SnapBuild::two_phase_at.

Referenced by CreateDecodingContext().

◆ SnapBuildSnapDecRefcount()

void SnapBuildSnapDecRefcount ( Snapshot  snap)

Definition at line 458 of file snapbuild.c.

459 {
460  /* make sure we don't get passed an external snapshot */
462 
463  /* make sure nobody modified our snapshot */
464  Assert(snap->curcid == FirstCommandId);
465  Assert(!snap->suboverflowed);
466  Assert(!snap->takenDuringRecovery);
467 
468  Assert(snap->regd_count == 0);
469 
470  Assert(snap->active_count > 0);
471 
472  /* slightly more likely, so it's checked even without casserts */
473  if (snap->copied)
474  elog(ERROR, "cannot free a copied snapshot");
475 
476  snap->active_count--;
477  if (snap->active_count == 0)
478  SnapBuildFreeSnapshot(snap);
479 }
#define FirstCommandId
Definition: c.h:657
static void SnapBuildFreeSnapshot(Snapshot snap)
Definition: snapbuild.c:382
@ 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 434 of file snapbuild.c.

435 {
436  return ptr < builder->start_decoding_at;
437 }

References SnapBuild::start_decoding_at.

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