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