PostgreSQL Source Code git master
slotfuncs.c
Go to the documentation of this file.
1/*-------------------------------------------------------------------------
2 *
3 * slotfuncs.c
4 * Support functions for replication slots
5 *
6 * Copyright (c) 2012-2026, PostgreSQL Global Development Group
7 *
8 * IDENTIFICATION
9 * src/backend/replication/slotfuncs.c
10 *
11 *-------------------------------------------------------------------------
12 */
13#include "postgres.h"
14
15#include "access/htup_details.h"
17#include "access/xlogrecovery.h"
18#include "access/xlogutils.h"
19#include "funcapi.h"
20#include "replication/logical.h"
21#include "replication/slot.h"
23#include "utils/builtins.h"
24#include "utils/guc.h"
25#include "utils/pg_lsn.h"
26
27/*
28 * Map SlotSyncSkipReason enum values to human-readable names.
29 */
30static const char *SlotSyncSkipReasonNames[] = {
31 [SS_SKIP_NONE] = "none",
32 [SS_SKIP_WAL_NOT_FLUSHED] = "wal_not_flushed",
33 [SS_SKIP_WAL_OR_ROWS_REMOVED] = "wal_or_rows_removed",
34 [SS_SKIP_NO_CONSISTENT_SNAPSHOT] = "no_consistent_snapshot",
35 [SS_SKIP_INVALID] = "slot_invalidated"
36};
37
38/*
39 * Helper function for creating a new physical replication slot with
40 * given arguments. Note that this function doesn't release the created
41 * slot.
42 *
43 * If restart_lsn is a valid value, we use it without WAL reservation
44 * routine. So the caller must guarantee that WAL is available.
45 */
46static void
47create_physical_replication_slot(char *name, bool immediately_reserve,
48 bool temporary, XLogRecPtr restart_lsn)
49{
51
52 /* acquire replication slot, this will check for conflicting names */
54 temporary ? RS_TEMPORARY : RS_PERSISTENT, false,
55 false, false);
56
57 if (immediately_reserve)
58 {
59 /* Reserve WAL as the user asked for it */
60 if (!XLogRecPtrIsValid(restart_lsn))
62 else
63 MyReplicationSlot->data.restart_lsn = restart_lsn;
64
65 /* Write this slot to disk */
68 }
69}
70
71/*
72 * SQL function for creating a new physical (streaming replication)
73 * replication slot.
74 */
77{
79 bool immediately_reserve = PG_GETARG_BOOL(1);
80 bool temporary = PG_GETARG_BOOL(2);
81 Datum values[2];
82 bool nulls[2];
83 TupleDesc tupdesc;
84 HeapTuple tuple;
85 Datum result;
86
87 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
88 elog(ERROR, "return type must be a row type");
89
91
93
95 immediately_reserve,
96 temporary,
98
100 nulls[0] = false;
101
102 if (immediately_reserve)
103 {
105 nulls[1] = false;
106 }
107 else
108 nulls[1] = true;
109
110 tuple = heap_form_tuple(tupdesc, values, nulls);
111 result = HeapTupleGetDatum(tuple);
112
114
115 PG_RETURN_DATUM(result);
116}
117
118
119/*
120 * Helper function for creating a new logical replication slot with
121 * given arguments. Note that this function doesn't release the created
122 * slot.
123 *
124 * When find_startpoint is false, the slot's confirmed_flush is not set; it's
125 * caller's responsibility to ensure it's set to something sensible.
126 */
127static void
129 bool temporary, bool two_phase,
130 bool failover,
131 XLogRecPtr restart_lsn,
132 bool find_startpoint)
133{
134 LogicalDecodingContext *ctx = NULL;
135
137
138 /*
139 * Acquire a logical decoding slot, this will check for conflicting names.
140 * Initially create persistent slot as ephemeral - that allows us to
141 * nicely handle errors during initialization because it'll get dropped if
142 * this transaction fails. We'll make it persistent at the end. Temporary
143 * slots can be created as temporary from beginning as they get dropped on
144 * error as well.
145 */
147 temporary ? RS_TEMPORARY : RS_EPHEMERAL, two_phase,
148 failover, false);
149
150 /*
151 * Ensure the logical decoding is enabled before initializing the logical
152 * decoding context.
153 */
156
157 /*
158 * Create logical decoding context to find start point or, if we don't
159 * need it, to 1) bump slot's restart_lsn and xmin 2) check plugin sanity.
160 *
161 * Note: when !find_startpoint this is still important, because it's at
162 * this point that the output plugin is validated.
163 */
165 false, /* just catalogs is OK */
166 restart_lsn,
167 XL_ROUTINE(.page_read = read_local_xlog_page,
168 .segment_open = wal_segment_open,
169 .segment_close = wal_segment_close),
170 NULL, NULL, NULL);
171
172 /*
173 * If caller needs us to determine the decoding start point, do so now.
174 * This might take a while.
175 */
176 if (find_startpoint)
178
179 /* don't need the decoding context anymore */
181}
182
183/*
184 * SQL function for creating a new logical replication slot.
185 */
186Datum
188{
191 bool temporary = PG_GETARG_BOOL(2);
192 bool two_phase = PG_GETARG_BOOL(3);
193 bool failover = PG_GETARG_BOOL(4);
194 Datum result;
195 TupleDesc tupdesc;
196 HeapTuple tuple;
197 Datum values[2];
198 bool nulls[2];
199
200 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
201 elog(ERROR, "return type must be a row type");
202
204
206
208 NameStr(*plugin),
209 temporary,
210 two_phase,
211 failover,
213 true);
214
217
218 memset(nulls, 0, sizeof(nulls));
219
220 tuple = heap_form_tuple(tupdesc, values, nulls);
221 result = HeapTupleGetDatum(tuple);
222
223 /* ok, slot is now fully created, mark it as persistent if needed */
224 if (!temporary)
227
228 PG_RETURN_DATUM(result);
229}
230
231
232/*
233 * SQL function for dropping a replication slot.
234 */
235Datum
237{
239
241
243
245
247}
248
249/*
250 * pg_get_replication_slots - SQL SRF showing all replication slots
251 * that currently exist on the database cluster.
252 */
253Datum
255{
256#define PG_GET_REPLICATION_SLOTS_COLS 21
257 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
258 XLogRecPtr currlsn;
259 int slotno;
260
261 /*
262 * We don't require any special permission to see this function's data
263 * because nothing should be sensitive. The most critical being the slot
264 * name, which shouldn't contain anything particularly sensitive.
265 */
266
267 InitMaterializedSRF(fcinfo, 0);
268
269 currlsn = GetXLogWriteRecPtr();
270
271 LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
272 for (slotno = 0; slotno < max_replication_slots; slotno++)
273 {
275 ReplicationSlot slot_contents;
278 WALAvailability walstate;
279 int i;
281
282 if (!slot->in_use)
283 continue;
284
285 /* Copy slot contents while holding spinlock, then examine at leisure */
286 SpinLockAcquire(&slot->mutex);
287 slot_contents = *slot;
288 SpinLockRelease(&slot->mutex);
289
290 memset(values, 0, sizeof(values));
291 memset(nulls, 0, sizeof(nulls));
292
293 i = 0;
294 values[i++] = NameGetDatum(&slot_contents.data.name);
295
296 if (slot_contents.data.database == InvalidOid)
297 nulls[i++] = true;
298 else
299 values[i++] = NameGetDatum(&slot_contents.data.plugin);
300
301 if (slot_contents.data.database == InvalidOid)
302 values[i++] = CStringGetTextDatum("physical");
303 else
304 values[i++] = CStringGetTextDatum("logical");
305
306 if (slot_contents.data.database == InvalidOid)
307 nulls[i++] = true;
308 else
309 values[i++] = ObjectIdGetDatum(slot_contents.data.database);
310
311 values[i++] = BoolGetDatum(slot_contents.data.persistency == RS_TEMPORARY);
312 values[i++] = BoolGetDatum(slot_contents.active_pid != 0);
313
314 if (slot_contents.active_pid != 0)
315 values[i++] = Int32GetDatum(slot_contents.active_pid);
316 else
317 nulls[i++] = true;
318
319 if (slot_contents.data.xmin != InvalidTransactionId)
320 values[i++] = TransactionIdGetDatum(slot_contents.data.xmin);
321 else
322 nulls[i++] = true;
323
324 if (slot_contents.data.catalog_xmin != InvalidTransactionId)
325 values[i++] = TransactionIdGetDatum(slot_contents.data.catalog_xmin);
326 else
327 nulls[i++] = true;
328
329 if (XLogRecPtrIsValid(slot_contents.data.restart_lsn))
330 values[i++] = LSNGetDatum(slot_contents.data.restart_lsn);
331 else
332 nulls[i++] = true;
333
334 if (XLogRecPtrIsValid(slot_contents.data.confirmed_flush))
335 values[i++] = LSNGetDatum(slot_contents.data.confirmed_flush);
336 else
337 nulls[i++] = true;
338
339 /*
340 * If the slot has not been invalidated, test availability from
341 * restart_lsn.
342 */
343 if (slot_contents.data.invalidated != RS_INVAL_NONE)
344 walstate = WALAVAIL_REMOVED;
345 else
346 walstate = GetWALAvailability(slot_contents.data.restart_lsn);
347
348 switch (walstate)
349 {
351 nulls[i++] = true;
352 break;
353
355 values[i++] = CStringGetTextDatum("reserved");
356 break;
357
359 values[i++] = CStringGetTextDatum("extended");
360 break;
361
363 values[i++] = CStringGetTextDatum("unreserved");
364 break;
365
366 case WALAVAIL_REMOVED:
367
368 /*
369 * If we read the restart_lsn long enough ago, maybe that file
370 * has been removed by now. However, the walsender could have
371 * moved forward enough that it jumped to another file after
372 * we looked. If checkpointer signalled the process to
373 * termination, then it's definitely lost; but if a process is
374 * still alive, then "unreserved" seems more appropriate.
375 *
376 * If we do change it, save the state for safe_wal_size below.
377 */
378 if (XLogRecPtrIsValid(slot_contents.data.restart_lsn))
379 {
380 int pid;
381
382 SpinLockAcquire(&slot->mutex);
383 pid = slot->active_pid;
384 slot_contents.data.restart_lsn = slot->data.restart_lsn;
385 SpinLockRelease(&slot->mutex);
386 if (pid != 0)
387 {
388 values[i++] = CStringGetTextDatum("unreserved");
389 walstate = WALAVAIL_UNRESERVED;
390 break;
391 }
392 }
393 values[i++] = CStringGetTextDatum("lost");
394 break;
395 }
396
397 /*
398 * safe_wal_size is only computed for slots that have not been lost,
399 * and only if there's a configured maximum size.
400 */
401 if (walstate == WALAVAIL_REMOVED || max_slot_wal_keep_size_mb < 0)
402 nulls[i++] = true;
403 else
404 {
405 XLogSegNo targetSeg;
406 uint64 slotKeepSegs;
407 uint64 keepSegs;
408 XLogSegNo failSeg;
409 XLogRecPtr failLSN;
410
411 XLByteToSeg(slot_contents.data.restart_lsn, targetSeg, wal_segment_size);
412
413 /* determine how many segments can be kept by slots */
415 /* ditto for wal_keep_size */
417
418 /* if currpos reaches failLSN, we lose our segment */
419 failSeg = targetSeg + Max(slotKeepSegs, keepSegs) + 1;
420 XLogSegNoOffsetToRecPtr(failSeg, 0, wal_segment_size, failLSN);
421
422 values[i++] = Int64GetDatum(failLSN - currlsn);
423 }
424
425 values[i++] = BoolGetDatum(slot_contents.data.two_phase);
426
427 if (slot_contents.data.two_phase &&
428 XLogRecPtrIsValid(slot_contents.data.two_phase_at))
429 values[i++] = LSNGetDatum(slot_contents.data.two_phase_at);
430 else
431 nulls[i++] = true;
432
433 if (slot_contents.inactive_since > 0)
434 values[i++] = TimestampTzGetDatum(slot_contents.inactive_since);
435 else
436 nulls[i++] = true;
437
438 cause = slot_contents.data.invalidated;
439
440 if (SlotIsPhysical(&slot_contents))
441 nulls[i++] = true;
442 else
443 {
444 /*
445 * rows_removed and wal_level_insufficient are the only two
446 * reasons for the logical slot's conflict with recovery.
447 */
448 if (cause == RS_INVAL_HORIZON ||
449 cause == RS_INVAL_WAL_LEVEL)
450 values[i++] = BoolGetDatum(true);
451 else
452 values[i++] = BoolGetDatum(false);
453 }
454
455 if (cause == RS_INVAL_NONE)
456 nulls[i++] = true;
457 else
459
460 values[i++] = BoolGetDatum(slot_contents.data.failover);
461
462 values[i++] = BoolGetDatum(slot_contents.data.synced);
463
464 if (slot_contents.slotsync_skip_reason == SS_SKIP_NONE)
465 nulls[i++] = true;
466 else
468
470
471 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
472 values, nulls);
473 }
474
475 LWLockRelease(ReplicationSlotControlLock);
476
477 return (Datum) 0;
478}
479
480/*
481 * Helper function for advancing our physical replication slot forward.
482 *
483 * The LSN position to move to is compared simply to the slot's restart_lsn,
484 * knowing that any position older than that would be removed by successive
485 * checkpoints.
486 */
487static XLogRecPtr
489{
491 XLogRecPtr retlsn = startlsn;
492
493 Assert(XLogRecPtrIsValid(moveto));
494
495 if (startlsn < moveto)
496 {
500 retlsn = moveto;
501
502 /*
503 * Dirty the slot so as it is written out at the next checkpoint. Note
504 * that the LSN position advanced may still be lost in the event of a
505 * crash, but this makes the data consistent after a clean shutdown.
506 */
508
509 /*
510 * Wake up logical walsenders holding logical failover slots after
511 * updating the restart_lsn of the physical slot.
512 */
514 }
515
516 return retlsn;
517}
518
519/*
520 * Advance our logical replication slot forward. See
521 * LogicalSlotAdvanceAndCheckSnapState for details.
522 */
523static XLogRecPtr
525{
526 return LogicalSlotAdvanceAndCheckSnapState(moveto, NULL);
527}
528
529/*
530 * SQL function for moving the position in a replication slot.
531 */
532Datum
534{
535 Name slotname = PG_GETARG_NAME(0);
536 XLogRecPtr moveto = PG_GETARG_LSN(1);
537 XLogRecPtr endlsn;
538 XLogRecPtr minlsn;
539 TupleDesc tupdesc;
540 Datum values[2];
541 bool nulls[2];
542 HeapTuple tuple;
543 Datum result;
544
546
548
549 if (!XLogRecPtrIsValid(moveto))
551 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
552 errmsg("invalid target WAL LSN")));
553
554 /* Build a tuple descriptor for our result type */
555 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
556 elog(ERROR, "return type must be a row type");
557
558 /*
559 * We can't move slot past what's been flushed/replayed so clamp the
560 * target position accordingly.
561 */
562 if (!RecoveryInProgress())
563 moveto = Min(moveto, GetFlushRecPtr(NULL));
564 else
565 moveto = Min(moveto, GetXLogReplayRecPtr(NULL));
566
567 /* Acquire the slot so we "own" it */
568 ReplicationSlotAcquire(NameStr(*slotname), true, true);
569
570 /* A slot whose restart_lsn has never been reserved cannot be advanced */
573 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
574 errmsg("replication slot \"%s\" cannot be advanced",
575 NameStr(*slotname)),
576 errdetail("This slot has never previously reserved WAL, or it has been invalidated.")));
577
578 /*
579 * Check if the slot is not moving backwards. Physical slots rely simply
580 * on restart_lsn as a minimum point, while logical slots have confirmed
581 * consumption up to confirmed_flush, meaning that in both cases data
582 * older than that is not available anymore.
583 */
586 else
588
589 if (moveto < minlsn)
591 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
592 errmsg("cannot advance replication slot to %X/%08X, minimum is %X/%08X",
593 LSN_FORMAT_ARGS(moveto), LSN_FORMAT_ARGS(minlsn))));
594
595 /* Do the actual slot update, depending on the slot type */
598 else
600
602 nulls[0] = false;
603
604 /*
605 * Recompute the minimum LSN and xmin across all slots to adjust with the
606 * advancing potentially done.
607 */
610
612
613 /* Return the reached position. */
614 values[1] = LSNGetDatum(endlsn);
615 nulls[1] = false;
616
617 tuple = heap_form_tuple(tupdesc, values, nulls);
618 result = HeapTupleGetDatum(tuple);
619
620 PG_RETURN_DATUM(result);
621}
622
623/*
624 * Helper function of copying a replication slot.
625 */
626static Datum
627copy_replication_slot(FunctionCallInfo fcinfo, bool logical_slot)
628{
629 Name src_name = PG_GETARG_NAME(0);
630 Name dst_name = PG_GETARG_NAME(1);
631 ReplicationSlot *src = NULL;
632 ReplicationSlot first_slot_contents;
633 ReplicationSlot second_slot_contents;
634 XLogRecPtr src_restart_lsn;
635 bool src_islogical;
636 bool temporary;
637 char *plugin;
638 Datum values[2];
639 bool nulls[2];
640 Datum result;
641 TupleDesc tupdesc;
642 HeapTuple tuple;
643
644 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
645 elog(ERROR, "return type must be a row type");
646
648
649 if (logical_slot)
651 else
653
654 LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
655
656 /*
657 * We need to prevent the source slot's reserved WAL from being removed,
658 * but we don't want to lock that slot for very long, and it can advance
659 * in the meantime. So obtain the source slot's data, and create a new
660 * slot using its restart_lsn. Afterwards we lock the source slot again
661 * and verify that the data we copied (name, type) has not changed
662 * incompatibly. No inconvenient WAL removal can occur once the new slot
663 * is created -- but since WAL removal could have occurred before we
664 * managed to create the new slot, we advance the new slot's restart_lsn
665 * to the source slot's updated restart_lsn the second time we lock it.
666 */
667 for (int i = 0; i < max_replication_slots; i++)
668 {
670
671 if (s->in_use && strcmp(NameStr(s->data.name), NameStr(*src_name)) == 0)
672 {
673 /* Copy the slot contents while holding spinlock */
675 first_slot_contents = *s;
677 src = s;
678 break;
679 }
680 }
681
682 LWLockRelease(ReplicationSlotControlLock);
683
684 if (src == NULL)
686 (errcode(ERRCODE_UNDEFINED_OBJECT),
687 errmsg("replication slot \"%s\" does not exist", NameStr(*src_name))));
688
689 src_islogical = SlotIsLogical(&first_slot_contents);
690 src_restart_lsn = first_slot_contents.data.restart_lsn;
691 temporary = (first_slot_contents.data.persistency == RS_TEMPORARY);
692 plugin = logical_slot ? NameStr(first_slot_contents.data.plugin) : NULL;
693
694 /* Check type of replication slot */
695 if (src_islogical != logical_slot)
697 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
698 src_islogical ?
699 errmsg("cannot copy physical replication slot \"%s\" as a logical replication slot",
700 NameStr(*src_name)) :
701 errmsg("cannot copy logical replication slot \"%s\" as a physical replication slot",
702 NameStr(*src_name))));
703
704 /* Copying non-reserved slot doesn't make sense */
705 if (!XLogRecPtrIsValid(src_restart_lsn))
707 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
708 errmsg("cannot copy a replication slot that doesn't reserve WAL")));
709
710 /* Cannot copy an invalidated replication slot */
711 if (first_slot_contents.data.invalidated != RS_INVAL_NONE)
713 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
714 errmsg("cannot copy invalidated replication slot \"%s\"",
715 NameStr(*src_name)));
716
717 /* Overwrite params from optional arguments */
718 if (PG_NARGS() >= 3)
719 temporary = PG_GETARG_BOOL(2);
720 if (PG_NARGS() >= 4)
721 {
722 Assert(logical_slot);
724 }
725
726 /* Create new slot and acquire it */
727 if (logical_slot)
728 {
729 /*
730 * We must not try to read WAL, since we haven't reserved it yet --
731 * hence pass find_startpoint false. confirmed_flush will be set
732 * below, by copying from the source slot.
733 *
734 * We don't copy the failover option to prevent potential issues with
735 * slot synchronization. For instance, if a slot was synchronized to
736 * the standby, then dropped on the primary, and immediately recreated
737 * by copying from another existing slot with much earlier restart_lsn
738 * and confirmed_flush_lsn, the slot synchronization would only
739 * observe the LSN of the same slot moving backward. As slot
740 * synchronization does not copy the restart_lsn and
741 * confirmed_flush_lsn backward (see update_local_synced_slot() for
742 * details), if a failover happens before the primary's slot catches
743 * up, logical replication cannot continue using the synchronized slot
744 * on the promoted standby because the slot retains the restart_lsn
745 * and confirmed_flush_lsn that are much later than expected.
746 */
748 plugin,
749 temporary,
750 false,
751 false,
752 src_restart_lsn,
753 false);
754 }
755 else
757 true,
758 temporary,
759 src_restart_lsn);
760
761 /*
762 * Update the destination slot to current values of the source slot;
763 * recheck that the source slot is still the one we saw previously.
764 */
765 {
766 TransactionId copy_effective_xmin;
767 TransactionId copy_effective_catalog_xmin;
768 TransactionId copy_xmin;
769 TransactionId copy_catalog_xmin;
770 XLogRecPtr copy_restart_lsn;
771 XLogRecPtr copy_confirmed_flush;
772 bool copy_islogical;
773 char *copy_name;
774
775 /* Copy data of source slot again */
776 SpinLockAcquire(&src->mutex);
777 second_slot_contents = *src;
778 SpinLockRelease(&src->mutex);
779
780 copy_effective_xmin = second_slot_contents.effective_xmin;
781 copy_effective_catalog_xmin = second_slot_contents.effective_catalog_xmin;
782
783 copy_xmin = second_slot_contents.data.xmin;
784 copy_catalog_xmin = second_slot_contents.data.catalog_xmin;
785 copy_restart_lsn = second_slot_contents.data.restart_lsn;
786 copy_confirmed_flush = second_slot_contents.data.confirmed_flush;
787
788 /* for existence check */
789 copy_name = NameStr(second_slot_contents.data.name);
790 copy_islogical = SlotIsLogical(&second_slot_contents);
791
792 /*
793 * Check if the source slot still exists and is valid. We regard it as
794 * invalid if the type of replication slot or name has been changed,
795 * or the restart_lsn either is invalid or has gone backward. (The
796 * restart_lsn could go backwards if the source slot is dropped and
797 * copied from an older slot during installation.)
798 *
799 * Since erroring out will release and drop the destination slot we
800 * don't need to release it here.
801 */
802 if (copy_restart_lsn < src_restart_lsn ||
803 src_islogical != copy_islogical ||
804 strcmp(copy_name, NameStr(*src_name)) != 0)
806 (errmsg("could not copy replication slot \"%s\"",
807 NameStr(*src_name)),
808 errdetail("The source replication slot was modified incompatibly during the copy operation.")));
809
810 /* The source slot must have a consistent snapshot */
811 if (src_islogical && !XLogRecPtrIsValid(copy_confirmed_flush))
813 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
814 errmsg("cannot copy unfinished logical replication slot \"%s\"",
815 NameStr(*src_name)),
816 errhint("Retry when the source replication slot's confirmed_flush_lsn is valid.")));
817
818 /*
819 * Copying an invalid slot doesn't make sense. Note that the source
820 * slot can become invalid after we create the new slot and copy the
821 * data of source slot. This is possible because the operations in
822 * InvalidateObsoleteReplicationSlots() are not serialized with this
823 * function. Even though we can't detect such a case here, the copied
824 * slot will become invalid in the next checkpoint cycle.
825 */
826 if (second_slot_contents.data.invalidated != RS_INVAL_NONE)
828 errmsg("cannot copy replication slot \"%s\"",
829 NameStr(*src_name)),
830 errdetail("The source replication slot was invalidated during the copy operation."));
831
832 /* Install copied values again */
834 MyReplicationSlot->effective_xmin = copy_effective_xmin;
835 MyReplicationSlot->effective_catalog_xmin = copy_effective_catalog_xmin;
836
837 MyReplicationSlot->data.xmin = copy_xmin;
838 MyReplicationSlot->data.catalog_xmin = copy_catalog_xmin;
839 MyReplicationSlot->data.restart_lsn = copy_restart_lsn;
840 MyReplicationSlot->data.confirmed_flush = copy_confirmed_flush;
842
847
848#ifdef USE_ASSERT_CHECKING
849 /* Check that the restart_lsn is available */
850 {
851 XLogSegNo segno;
852
853 XLByteToSeg(copy_restart_lsn, segno, wal_segment_size);
855 }
856#endif
857 }
858
859 /* target slot fully created, mark as persistent if needed */
860 if (logical_slot && !temporary)
862
863 /* All done. Set up the return values */
864 values[0] = NameGetDatum(dst_name);
865 nulls[0] = false;
867 {
869 nulls[1] = false;
870 }
871 else
872 nulls[1] = true;
873
874 tuple = heap_form_tuple(tupdesc, values, nulls);
875 result = HeapTupleGetDatum(tuple);
876
878
879 PG_RETURN_DATUM(result);
880}
881
882/* The wrappers below are all to appease opr_sanity */
883Datum
885{
886 return copy_replication_slot(fcinfo, true);
887}
888
889Datum
891{
892 return copy_replication_slot(fcinfo, true);
893}
894
895Datum
897{
898 return copy_replication_slot(fcinfo, true);
899}
900
901Datum
903{
904 return copy_replication_slot(fcinfo, false);
905}
906
907Datum
909{
910 return copy_replication_slot(fcinfo, false);
911}
912
913/*
914 * Synchronize failover enabled replication slots to a standby server
915 * from the primary server.
916 */
917Datum
919{
921 char *err;
922 StringInfoData app_name;
923
925
926 if (!RecoveryInProgress())
928 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
929 errmsg("replication slots can only be synchronized to a standby server"));
930
932
933 /* Load the libpq-specific functions */
934 load_file("libpqwalreceiver", false);
935
937
938 initStringInfo(&app_name);
939 if (cluster_name[0])
940 appendStringInfo(&app_name, "%s_slotsync", cluster_name);
941 else
942 appendStringInfoString(&app_name, "slotsync");
943
944 /* Connect to the primary server. */
945 wrconn = walrcv_connect(PrimaryConnInfo, false, false, false,
946 app_name.data, &err);
947
948 if (!wrconn)
950 errcode(ERRCODE_CONNECTION_FAILURE),
951 errmsg("synchronization worker \"%s\" could not connect to the primary server: %s",
952 app_name.data, err));
953
954 pfree(app_name.data);
955
957
959
961}
static Datum values[MAXATTR]
Definition: bootstrap.c:155
#define CStringGetTextDatum(s)
Definition: builtins.h:97
#define NameStr(name)
Definition: c.h:771
#define Min(x, y)
Definition: c.h:1003
#define Max(x, y)
Definition: c.h:997
uint64_t uint64
Definition: c.h:553
uint32 TransactionId
Definition: c.h:672
#define OidIsValid(objectId)
Definition: c.h:794
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:149
int errdetail(const char *fmt,...)
Definition: elog.c:1216
int errhint(const char *fmt,...)
Definition: elog.c:1330
int errcode(int sqlerrcode)
Definition: elog.c:863
int errmsg(const char *fmt,...)
Definition: elog.c:1080
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
#define ereport(elevel,...)
Definition: elog.h:150
void err(int eval, const char *fmt,...)
Definition: err.c:43
#define PG_RETURN_VOID()
Definition: fmgr.h:350
#define PG_NARGS()
Definition: fmgr.h:203
#define PG_GETARG_NAME(n)
Definition: fmgr.h:279
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:354
#define PG_FUNCTION_ARGS
Definition: fmgr.h:193
void InitMaterializedSRF(FunctionCallInfo fcinfo, bits32 flags)
Definition: funcapi.c:76
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:276
@ TYPEFUNC_COMPOSITE
Definition: funcapi.h:149
static Datum HeapTupleGetDatum(const HeapTupleData *tuple)
Definition: funcapi.h:230
char * cluster_name
Definition: guc_tables.c:555
Assert(PointerIsAligned(start, uint64))
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition: heaptuple.c:1117
int i
Definition: isn.c:77
XLogRecPtr LogicalSlotAdvanceAndCheckSnapState(XLogRecPtr moveto, bool *found_consistent_snapshot)
Definition: logical.c:2076
void FreeDecodingContext(LogicalDecodingContext *ctx)
Definition: logical.c:668
void DecodingContextFindStartpoint(LogicalDecodingContext *ctx)
Definition: logical.c:624
LogicalDecodingContext * CreateInitDecodingContext(const char *plugin, List *output_plugin_options, bool need_full_snapshot, XLogRecPtr restart_lsn, XLogReaderRoutine *xl_routine, LogicalOutputPluginWriterPrepareWrite prepare_write, LogicalOutputPluginWriterWrite do_write, LogicalOutputPluginWriterUpdateProgress update_progress)
Definition: logical.c:321
void CheckLogicalDecodingRequirements(void)
Definition: logical.c:111
bool IsLogicalDecodingEnabled(void)
Definition: logicalctl.c:204
void EnsureLogicalDecodingEnabled(void)
Definition: logicalctl.c:305
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1178
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1898
@ LW_SHARED
Definition: lwlock.h:113
void pfree(void *pointer)
Definition: mcxt.c:1616
#define NIL
Definition: pg_list.h:68
#define PG_GETARG_LSN(n)
Definition: pg_lsn.h:36
static Datum LSNGetDatum(XLogRecPtr X)
Definition: pg_lsn.h:31
static bool two_phase
static bool failover
static const char * plugin
static Datum Int64GetDatum(int64 X)
Definition: postgres.h:423
static Datum TransactionIdGetDatum(TransactionId X)
Definition: postgres.h:302
static Datum BoolGetDatum(bool X)
Definition: postgres.h:112
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:262
static Datum NameGetDatum(const NameData *X)
Definition: postgres.h:403
uint64_t Datum
Definition: postgres.h:70
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:222
#define InvalidOid
Definition: postgres_ext.h:37
void ReplicationSlotAcquire(const char *name, bool nowait, bool error_if_invalid)
Definition: slot.c:620
void ReplicationSlotCreate(const char *name, bool db_specific, ReplicationSlotPersistency persistency, bool two_phase, bool failover, bool synced)
Definition: slot.c:378
void ReplicationSlotMarkDirty(void)
Definition: slot.c:1173
void ReplicationSlotReserveWal(void)
Definition: slot.c:1693
void ReplicationSlotsComputeRequiredXmin(bool already_locked)
Definition: slot.c:1215
void ReplicationSlotPersist(void)
Definition: slot.c:1190
ReplicationSlot * MyReplicationSlot
Definition: slot.c:148
void ReplicationSlotDrop(const char *name, bool nowait)
Definition: slot.c:909
void ReplicationSlotSave(void)
Definition: slot.c:1155
void CheckSlotPermissions(void)
Definition: slot.c:1676
void ReplicationSlotRelease(void)
Definition: slot.c:758
int max_replication_slots
Definition: slot.c:151
ReplicationSlotCtlData * ReplicationSlotCtl
Definition: slot.c:145
void ReplicationSlotsComputeRequiredLSN(void)
Definition: slot.c:1297
void CheckSlotRequirements(void)
Definition: slot.c:1654
const char * GetSlotInvalidationCauseName(ReplicationSlotInvalidationCause cause)
Definition: slot.c:2926
@ RS_PERSISTENT
Definition: slot.h:45
@ RS_EPHEMERAL
Definition: slot.h:46
@ RS_TEMPORARY
Definition: slot.h:47
#define SlotIsPhysical(slot)
Definition: slot.h:284
ReplicationSlotInvalidationCause
Definition: slot.h:59
@ RS_INVAL_HORIZON
Definition: slot.h:64
@ RS_INVAL_WAL_LEVEL
Definition: slot.h:66
@ RS_INVAL_NONE
Definition: slot.h:60
#define SlotIsLogical(slot)
Definition: slot.h:285
@ SS_SKIP_WAL_NOT_FLUSHED
Definition: slot.h:83
@ SS_SKIP_NO_CONSISTENT_SNAPSHOT
Definition: slot.h:87
@ SS_SKIP_NONE
Definition: slot.h:82
@ SS_SKIP_INVALID
Definition: slot.h:89
@ SS_SKIP_WAL_OR_ROWS_REMOVED
Definition: slot.h:85
Datum pg_get_replication_slots(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:254
Datum pg_copy_physical_replication_slot_a(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:902
static void create_logical_replication_slot(char *name, char *plugin, bool temporary, bool two_phase, bool failover, XLogRecPtr restart_lsn, bool find_startpoint)
Definition: slotfuncs.c:128
Datum pg_create_logical_replication_slot(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:187
#define PG_GET_REPLICATION_SLOTS_COLS
static Datum copy_replication_slot(FunctionCallInfo fcinfo, bool logical_slot)
Definition: slotfuncs.c:627
Datum pg_copy_logical_replication_slot_c(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:896
Datum pg_create_physical_replication_slot(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:76
Datum pg_copy_logical_replication_slot_a(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:884
Datum pg_copy_physical_replication_slot_b(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:908
static const char * SlotSyncSkipReasonNames[]
Definition: slotfuncs.c:30
Datum pg_sync_replication_slots(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:918
Datum pg_copy_logical_replication_slot_b(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:890
static XLogRecPtr pg_logical_replication_slot_advance(XLogRecPtr moveto)
Definition: slotfuncs.c:524
static XLogRecPtr pg_physical_replication_slot_advance(XLogRecPtr moveto)
Definition: slotfuncs.c:488
Datum pg_replication_slot_advance(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:533
static void create_physical_replication_slot(char *name, bool immediately_reserve, bool temporary, XLogRecPtr restart_lsn)
Definition: slotfuncs.c:47
Datum pg_drop_replication_slot(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:236
void SyncReplicationSlots(WalReceiverConn *wrconn)
Definition: slotsync.c:1982
char * CheckAndGetDbnameFromConninfo(void)
Definition: slotsync.c:1176
bool ValidateSlotSyncParams(int elevel)
Definition: slotsync.c:1203
#define SpinLockRelease(lock)
Definition: spin.h:61
#define SpinLockAcquire(lock)
Definition: spin.h:59
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:145
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:230
void initStringInfo(StringInfo str)
Definition: stringinfo.c:97
ReplicationSlot replication_slots[1]
Definition: slot.h:296
TransactionId xmin
Definition: slot.h:114
TransactionId catalog_xmin
Definition: slot.h:122
XLogRecPtr confirmed_flush
Definition: slot.h:136
ReplicationSlotPersistency persistency
Definition: slot.h:106
ReplicationSlotInvalidationCause invalidated
Definition: slot.h:128
TransactionId effective_catalog_xmin
Definition: slot.h:207
slock_t mutex
Definition: slot.h:183
pid_t active_pid
Definition: slot.h:189
SlotSyncSkipReason slotsync_skip_reason
Definition: slot.h:281
bool in_use
Definition: slot.h:186
TransactionId effective_xmin
Definition: slot.h:206
ReplicationSlotPersistentData data
Definition: slot.h:210
TimestampTz inactive_since
Definition: slot.h:242
TupleDesc setDesc
Definition: execnodes.h:364
Tuplestorestate * setResult
Definition: execnodes.h:363
Definition: c.h:766
#define InvalidTransactionId
Definition: transam.h:31
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, const Datum *values, const bool *isnull)
Definition: tuplestore.c:784
static Datum TimestampTzGetDatum(TimestampTz X)
Definition: timestamp.h:52
const char * name
static WalReceiverConn * wrconn
Definition: walreceiver.c:94
#define walrcv_connect(conninfo, replication, logical, must_use_password, appname, err)
Definition: walreceiver.h:435
#define walrcv_disconnect(conn)
Definition: walreceiver.h:467
void PhysicalWakeupLogicalWalSnd(void)
Definition: walsender.c:1739
bool RecoveryInProgress(void)
Definition: xlog.c:6461
XLogSegNo XLogGetLastRemovedSegno(void)
Definition: xlog.c:3796
int wal_keep_size_mb
Definition: xlog.c:119
int wal_segment_size
Definition: xlog.c:146
WALAvailability GetWALAvailability(XLogRecPtr targetLSN)
Definition: xlog.c:8000
int max_slot_wal_keep_size_mb
Definition: xlog.c:138
XLogRecPtr GetFlushRecPtr(TimeLineID *insertTLI)
Definition: xlog.c:6626
XLogRecPtr GetXLogWriteRecPtr(void)
Definition: xlog.c:9612
WALAvailability
Definition: xlog.h:199
@ WALAVAIL_REMOVED
Definition: xlog.h:205
@ WALAVAIL_RESERVED
Definition: xlog.h:201
@ WALAVAIL_UNRESERVED
Definition: xlog.h:204
@ WALAVAIL_EXTENDED
Definition: xlog.h:202
@ WALAVAIL_INVALID_LSN
Definition: xlog.h:200
#define XLogSegNoOffsetToRecPtr(segno, offset, wal_segsz_bytes, dest)
#define XLogMBVarToSegs(mbvar, wal_segsz_bytes)
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)
#define XLogRecPtrIsValid(r)
Definition: xlogdefs.h:29
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:47
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
uint64 XLogSegNo
Definition: xlogdefs.h:52
#define XL_ROUTINE(...)
Definition: xlogreader.h:117
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
char * PrimaryConnInfo
Definition: xlogrecovery.c:99
void wal_segment_close(XLogReaderState *state)
Definition: xlogutils.c:831
void wal_segment_open(XLogReaderState *state, XLogSegNo nextSegNo, TimeLineID *tli_p)
Definition: xlogutils.c:806
int read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *cur_page)
Definition: xlogutils.c:845