PostgreSQL Source Code git master
slotfuncs.c File Reference
#include "postgres.h"
#include "access/htup_details.h"
#include "access/xlog_internal.h"
#include "access/xlogrecovery.h"
#include "access/xlogutils.h"
#include "funcapi.h"
#include "replication/logical.h"
#include "replication/slot.h"
#include "replication/slotsync.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/pg_lsn.h"
Include dependency graph for slotfuncs.c:

Go to the source code of this file.

Macros

#define PG_GET_REPLICATION_SLOTS_COLS   19
 

Functions

static void create_physical_replication_slot (char *name, bool immediately_reserve, bool temporary, XLogRecPtr restart_lsn)
 
Datum pg_create_physical_replication_slot (PG_FUNCTION_ARGS)
 
static void create_logical_replication_slot (char *name, char *plugin, bool temporary, bool two_phase, bool failover, XLogRecPtr restart_lsn, bool find_startpoint)
 
Datum pg_create_logical_replication_slot (PG_FUNCTION_ARGS)
 
Datum pg_drop_replication_slot (PG_FUNCTION_ARGS)
 
Datum pg_get_replication_slots (PG_FUNCTION_ARGS)
 
static XLogRecPtr pg_physical_replication_slot_advance (XLogRecPtr moveto)
 
static XLogRecPtr pg_logical_replication_slot_advance (XLogRecPtr moveto)
 
Datum pg_replication_slot_advance (PG_FUNCTION_ARGS)
 
static Datum copy_replication_slot (FunctionCallInfo fcinfo, bool logical_slot)
 
Datum pg_copy_logical_replication_slot_a (PG_FUNCTION_ARGS)
 
Datum pg_copy_logical_replication_slot_b (PG_FUNCTION_ARGS)
 
Datum pg_copy_logical_replication_slot_c (PG_FUNCTION_ARGS)
 
Datum pg_copy_physical_replication_slot_a (PG_FUNCTION_ARGS)
 
Datum pg_copy_physical_replication_slot_b (PG_FUNCTION_ARGS)
 
Datum pg_sync_replication_slots (PG_FUNCTION_ARGS)
 

Macro Definition Documentation

◆ PG_GET_REPLICATION_SLOTS_COLS

#define PG_GET_REPLICATION_SLOTS_COLS   19

Function Documentation

◆ copy_replication_slot()

static Datum copy_replication_slot ( FunctionCallInfo  fcinfo,
bool  logical_slot 
)
static

Definition at line 598 of file slotfuncs.c.

599{
600 Name src_name = PG_GETARG_NAME(0);
601 Name dst_name = PG_GETARG_NAME(1);
602 ReplicationSlot *src = NULL;
603 ReplicationSlot first_slot_contents;
604 ReplicationSlot second_slot_contents;
605 XLogRecPtr src_restart_lsn;
606 bool src_islogical;
607 bool temporary;
608 char *plugin;
609 Datum values[2];
610 bool nulls[2];
611 Datum result;
612 TupleDesc tupdesc;
613 HeapTuple tuple;
614
615 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
616 elog(ERROR, "return type must be a row type");
617
619
620 if (logical_slot)
622 else
624
625 LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
626
627 /*
628 * We need to prevent the source slot's reserved WAL from being removed,
629 * but we don't want to lock that slot for very long, and it can advance
630 * in the meantime. So obtain the source slot's data, and create a new
631 * slot using its restart_lsn. Afterwards we lock the source slot again
632 * and verify that the data we copied (name, type) has not changed
633 * incompatibly. No inconvenient WAL removal can occur once the new slot
634 * is created -- but since WAL removal could have occurred before we
635 * managed to create the new slot, we advance the new slot's restart_lsn
636 * to the source slot's updated restart_lsn the second time we lock it.
637 */
638 for (int i = 0; i < max_replication_slots; i++)
639 {
641
642 if (s->in_use && strcmp(NameStr(s->data.name), NameStr(*src_name)) == 0)
643 {
644 /* Copy the slot contents while holding spinlock */
646 first_slot_contents = *s;
648 src = s;
649 break;
650 }
651 }
652
653 LWLockRelease(ReplicationSlotControlLock);
654
655 if (src == NULL)
657 (errcode(ERRCODE_UNDEFINED_OBJECT),
658 errmsg("replication slot \"%s\" does not exist", NameStr(*src_name))));
659
660 src_islogical = SlotIsLogical(&first_slot_contents);
661 src_restart_lsn = first_slot_contents.data.restart_lsn;
662 temporary = (first_slot_contents.data.persistency == RS_TEMPORARY);
663 plugin = logical_slot ? NameStr(first_slot_contents.data.plugin) : NULL;
664
665 /* Check type of replication slot */
666 if (src_islogical != logical_slot)
668 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
669 src_islogical ?
670 errmsg("cannot copy physical replication slot \"%s\" as a logical replication slot",
671 NameStr(*src_name)) :
672 errmsg("cannot copy logical replication slot \"%s\" as a physical replication slot",
673 NameStr(*src_name))));
674
675 /* Copying non-reserved slot doesn't make sense */
676 if (XLogRecPtrIsInvalid(src_restart_lsn))
678 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
679 errmsg("cannot copy a replication slot that doesn't reserve WAL")));
680
681 /* Overwrite params from optional arguments */
682 if (PG_NARGS() >= 3)
683 temporary = PG_GETARG_BOOL(2);
684 if (PG_NARGS() >= 4)
685 {
686 Assert(logical_slot);
688 }
689
690 /* Create new slot and acquire it */
691 if (logical_slot)
692 {
693 /*
694 * We must not try to read WAL, since we haven't reserved it yet --
695 * hence pass find_startpoint false. confirmed_flush will be set
696 * below, by copying from the source slot.
697 *
698 * To avoid potential issues with the slot synchronization where the
699 * restart_lsn of a replication slot can go backward, we set the
700 * failover option to false here. This situation occurs when a slot
701 * on the primary server is dropped and immediately replaced with a
702 * new slot of the same name, created by copying from another existing
703 * slot. However, the slot synchronization will only observe the
704 * restart_lsn of the same slot going backward.
705 */
707 plugin,
708 temporary,
709 false,
710 false,
711 src_restart_lsn,
712 false);
713 }
714 else
716 true,
717 temporary,
718 src_restart_lsn);
719
720 /*
721 * Update the destination slot to current values of the source slot;
722 * recheck that the source slot is still the one we saw previously.
723 */
724 {
725 TransactionId copy_effective_xmin;
726 TransactionId copy_effective_catalog_xmin;
727 TransactionId copy_xmin;
728 TransactionId copy_catalog_xmin;
729 XLogRecPtr copy_restart_lsn;
730 XLogRecPtr copy_confirmed_flush;
731 bool copy_islogical;
732 char *copy_name;
733
734 /* Copy data of source slot again */
735 SpinLockAcquire(&src->mutex);
736 second_slot_contents = *src;
737 SpinLockRelease(&src->mutex);
738
739 copy_effective_xmin = second_slot_contents.effective_xmin;
740 copy_effective_catalog_xmin = second_slot_contents.effective_catalog_xmin;
741
742 copy_xmin = second_slot_contents.data.xmin;
743 copy_catalog_xmin = second_slot_contents.data.catalog_xmin;
744 copy_restart_lsn = second_slot_contents.data.restart_lsn;
745 copy_confirmed_flush = second_slot_contents.data.confirmed_flush;
746
747 /* for existence check */
748 copy_name = NameStr(second_slot_contents.data.name);
749 copy_islogical = SlotIsLogical(&second_slot_contents);
750
751 /*
752 * Check if the source slot still exists and is valid. We regard it as
753 * invalid if the type of replication slot or name has been changed,
754 * or the restart_lsn either is invalid or has gone backward. (The
755 * restart_lsn could go backwards if the source slot is dropped and
756 * copied from an older slot during installation.)
757 *
758 * Since erroring out will release and drop the destination slot we
759 * don't need to release it here.
760 */
761 if (copy_restart_lsn < src_restart_lsn ||
762 src_islogical != copy_islogical ||
763 strcmp(copy_name, NameStr(*src_name)) != 0)
765 (errmsg("could not copy replication slot \"%s\"",
766 NameStr(*src_name)),
767 errdetail("The source replication slot was modified incompatibly during the copy operation.")));
768
769 /* The source slot must have a consistent snapshot */
770 if (src_islogical && XLogRecPtrIsInvalid(copy_confirmed_flush))
772 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
773 errmsg("cannot copy unfinished logical replication slot \"%s\"",
774 NameStr(*src_name)),
775 errhint("Retry when the source replication slot's confirmed_flush_lsn is valid.")));
776
777 /* Install copied values again */
779 MyReplicationSlot->effective_xmin = copy_effective_xmin;
780 MyReplicationSlot->effective_catalog_xmin = copy_effective_catalog_xmin;
781
782 MyReplicationSlot->data.xmin = copy_xmin;
783 MyReplicationSlot->data.catalog_xmin = copy_catalog_xmin;
784 MyReplicationSlot->data.restart_lsn = copy_restart_lsn;
785 MyReplicationSlot->data.confirmed_flush = copy_confirmed_flush;
787
792
793#ifdef USE_ASSERT_CHECKING
794 /* Check that the restart_lsn is available */
795 {
796 XLogSegNo segno;
797
798 XLByteToSeg(copy_restart_lsn, segno, wal_segment_size);
800 }
801#endif
802 }
803
804 /* target slot fully created, mark as persistent if needed */
805 if (logical_slot && !temporary)
807
808 /* All done. Set up the return values */
809 values[0] = NameGetDatum(dst_name);
810 nulls[0] = false;
812 {
814 nulls[1] = false;
815 }
816 else
817 nulls[1] = true;
818
819 tuple = heap_form_tuple(tupdesc, values, nulls);
820 result = HeapTupleGetDatum(tuple);
821
823
824 PG_RETURN_DATUM(result);
825}
static Datum values[MAXATTR]
Definition: bootstrap.c:151
#define NameStr(name)
Definition: c.h:703
#define Assert(condition)
Definition: c.h:815
uint32 TransactionId
Definition: c.h:609
int errdetail(const char *fmt,...)
Definition: elog.c:1203
int errhint(const char *fmt,...)
Definition: elog.c:1317
int errcode(int sqlerrcode)
Definition: elog.c:853
int errmsg(const char *fmt,...)
Definition: elog.c:1070
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:225
#define ereport(elevel,...)
Definition: elog.h:149
#define PG_NARGS()
Definition: fmgr.h:203
#define PG_GETARG_NAME(n)
Definition: fmgr.h:278
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:353
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
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition: heaptuple.c:1117
int i
Definition: isn.c:72
void CheckLogicalDecodingRequirements(void)
Definition: logical.c:109
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1168
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1781
@ LW_SHARED
Definition: lwlock.h:115
static Datum LSNGetDatum(XLogRecPtr X)
Definition: pg_lsn.h:28
static const char * plugin
uintptr_t Datum
Definition: postgres.h:69
static Datum NameGetDatum(const NameData *X)
Definition: postgres.h:378
void ReplicationSlotMarkDirty(void)
Definition: slot.c:1038
void ReplicationSlotsComputeRequiredXmin(bool already_locked)
Definition: slot.c:1077
void ReplicationSlotPersist(void)
Definition: slot.c:1055
ReplicationSlot * MyReplicationSlot
Definition: slot.c:138
void ReplicationSlotSave(void)
Definition: slot.c:1020
void CheckSlotPermissions(void)
Definition: slot.c:1412
void ReplicationSlotRelease(void)
Definition: slot.c:652
int max_replication_slots
Definition: slot.c:141
ReplicationSlotCtlData * ReplicationSlotCtl
Definition: slot.c:135
void ReplicationSlotsComputeRequiredLSN(void)
Definition: slot.c:1133
void CheckSlotRequirements(void)
Definition: slot.c:1390
@ RS_TEMPORARY
Definition: slot.h:40
#define SlotIsLogical(slot)
Definition: slot.h:217
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:117
static void create_physical_replication_slot(char *name, bool immediately_reserve, bool temporary, XLogRecPtr restart_lsn)
Definition: slotfuncs.c:36
#define SpinLockRelease(lock)
Definition: spin.h:61
#define SpinLockAcquire(lock)
Definition: spin.h:59
ReplicationSlot replication_slots[1]
Definition: slot.h:228
TransactionId xmin
Definition: slot.h:85
TransactionId catalog_xmin
Definition: slot.h:93
XLogRecPtr restart_lsn
Definition: slot.h:96
XLogRecPtr confirmed_flush
Definition: slot.h:107
ReplicationSlotPersistency persistency
Definition: slot.h:77
TransactionId effective_catalog_xmin
Definition: slot.h:178
slock_t mutex
Definition: slot.h:154
bool in_use
Definition: slot.h:157
TransactionId effective_xmin
Definition: slot.h:177
ReplicationSlotPersistentData data
Definition: slot.h:181
Definition: c.h:698
XLogSegNo XLogGetLastRemovedSegno(void)
Definition: xlog.c:3758
int wal_segment_size
Definition: xlog.c:143
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
uint64 XLogRecPtr
Definition: xlogdefs.h:21
uint64 XLogSegNo
Definition: xlogdefs.h:48

References Assert, ReplicationSlotPersistentData::catalog_xmin, CheckLogicalDecodingRequirements(), CheckSlotPermissions(), CheckSlotRequirements(), ReplicationSlotPersistentData::confirmed_flush, create_logical_replication_slot(), create_physical_replication_slot(), ReplicationSlot::data, ReplicationSlot::effective_catalog_xmin, ReplicationSlot::effective_xmin, elog, ereport, errcode(), errdetail(), errhint(), errmsg(), ERROR, get_call_result_type(), heap_form_tuple(), HeapTupleGetDatum(), i, ReplicationSlot::in_use, LSNGetDatum(), LW_SHARED, LWLockAcquire(), LWLockRelease(), max_replication_slots, ReplicationSlot::mutex, MyReplicationSlot, ReplicationSlotPersistentData::name, NameGetDatum(), NameStr, ReplicationSlotPersistentData::persistency, PG_GETARG_BOOL, PG_GETARG_NAME, PG_NARGS, PG_RETURN_DATUM, plugin, ReplicationSlotPersistentData::plugin, ReplicationSlotCtlData::replication_slots, ReplicationSlotCtl, ReplicationSlotMarkDirty(), ReplicationSlotPersist(), ReplicationSlotRelease(), ReplicationSlotSave(), ReplicationSlotsComputeRequiredLSN(), ReplicationSlotsComputeRequiredXmin(), ReplicationSlotPersistentData::restart_lsn, RS_TEMPORARY, SlotIsLogical, SpinLockAcquire, SpinLockRelease, TYPEFUNC_COMPOSITE, values, wal_segment_size, XLByteToSeg, XLogGetLastRemovedSegno(), XLogRecPtrIsInvalid, and ReplicationSlotPersistentData::xmin.

Referenced by pg_copy_logical_replication_slot_a(), pg_copy_logical_replication_slot_b(), pg_copy_logical_replication_slot_c(), pg_copy_physical_replication_slot_a(), and pg_copy_physical_replication_slot_b().

◆ create_logical_replication_slot()

static void create_logical_replication_slot ( char *  name,
char *  plugin,
bool  temporary,
bool  two_phase,
bool  failover,
XLogRecPtr  restart_lsn,
bool  find_startpoint 
)
static

Definition at line 117 of file slotfuncs.c.

122{
123 LogicalDecodingContext *ctx = NULL;
124
126
127 /*
128 * Acquire a logical decoding slot, this will check for conflicting names.
129 * Initially create persistent slot as ephemeral - that allows us to
130 * nicely handle errors during initialization because it'll get dropped if
131 * this transaction fails. We'll make it persistent at the end. Temporary
132 * slots can be created as temporary from beginning as they get dropped on
133 * error as well.
134 */
136 temporary ? RS_TEMPORARY : RS_EPHEMERAL, two_phase,
137 failover, false);
138
139 /*
140 * Create logical decoding context to find start point or, if we don't
141 * need it, to 1) bump slot's restart_lsn and xmin 2) check plugin sanity.
142 *
143 * Note: when !find_startpoint this is still important, because it's at
144 * this point that the output plugin is validated.
145 */
147 false, /* just catalogs is OK */
148 restart_lsn,
149 XL_ROUTINE(.page_read = read_local_xlog_page,
150 .segment_open = wal_segment_open,
151 .segment_close = wal_segment_close),
152 NULL, NULL, NULL);
153
154 /*
155 * If caller needs us to determine the decoding start point, do so now.
156 * This might take a while.
157 */
158 if (find_startpoint)
160
161 /* don't need the decoding context anymore */
163}
void FreeDecodingContext(LogicalDecodingContext *ctx)
Definition: logical.c:694
void DecodingContextFindStartpoint(LogicalDecodingContext *ctx)
Definition: logical.c:650
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:330
#define NIL
Definition: pg_list.h:68
static bool two_phase
void ReplicationSlotCreate(const char *name, bool db_specific, ReplicationSlotPersistency persistency, bool two_phase, bool failover, bool synced)
Definition: slot.c:309
@ RS_EPHEMERAL
Definition: slot.h:39
const char * name
#define XL_ROUTINE(...)
Definition: xlogreader.h:117
void wal_segment_close(XLogReaderState *state)
Definition: xlogutils.c:842
void wal_segment_open(XLogReaderState *state, XLogSegNo nextSegNo, TimeLineID *tli_p)
Definition: xlogutils.c:817
int read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *cur_page)
Definition: xlogutils.c:861

References Assert, CreateInitDecodingContext(), DecodingContextFindStartpoint(), FreeDecodingContext(), MyReplicationSlot, name, NIL, plugin, read_local_xlog_page(), ReplicationSlotCreate(), RS_EPHEMERAL, RS_TEMPORARY, two_phase, wal_segment_close(), wal_segment_open(), and XL_ROUTINE.

Referenced by copy_replication_slot(), and pg_create_logical_replication_slot().

◆ create_physical_replication_slot()

static void create_physical_replication_slot ( char *  name,
bool  immediately_reserve,
bool  temporary,
XLogRecPtr  restart_lsn 
)
static

Definition at line 36 of file slotfuncs.c.

38{
40
41 /* acquire replication slot, this will check for conflicting names */
43 temporary ? RS_TEMPORARY : RS_PERSISTENT, false,
44 false, false);
45
46 if (immediately_reserve)
47 {
48 /* Reserve WAL as the user asked for it */
49 if (XLogRecPtrIsInvalid(restart_lsn))
51 else
52 MyReplicationSlot->data.restart_lsn = restart_lsn;
53
54 /* Write this slot to disk */
57 }
58}
void ReplicationSlotReserveWal(void)
Definition: slot.c:1429
@ RS_PERSISTENT
Definition: slot.h:38

References Assert, ReplicationSlot::data, MyReplicationSlot, name, ReplicationSlotCreate(), ReplicationSlotMarkDirty(), ReplicationSlotReserveWal(), ReplicationSlotSave(), ReplicationSlotPersistentData::restart_lsn, RS_PERSISTENT, RS_TEMPORARY, and XLogRecPtrIsInvalid.

Referenced by copy_replication_slot(), and pg_create_physical_replication_slot().

◆ pg_copy_logical_replication_slot_a()

Datum pg_copy_logical_replication_slot_a ( PG_FUNCTION_ARGS  )

Definition at line 829 of file slotfuncs.c.

830{
831 return copy_replication_slot(fcinfo, true);
832}
static Datum copy_replication_slot(FunctionCallInfo fcinfo, bool logical_slot)
Definition: slotfuncs.c:598

References copy_replication_slot().

◆ pg_copy_logical_replication_slot_b()

Datum pg_copy_logical_replication_slot_b ( PG_FUNCTION_ARGS  )

Definition at line 835 of file slotfuncs.c.

836{
837 return copy_replication_slot(fcinfo, true);
838}

References copy_replication_slot().

◆ pg_copy_logical_replication_slot_c()

Datum pg_copy_logical_replication_slot_c ( PG_FUNCTION_ARGS  )

Definition at line 841 of file slotfuncs.c.

842{
843 return copy_replication_slot(fcinfo, true);
844}

References copy_replication_slot().

◆ pg_copy_physical_replication_slot_a()

Datum pg_copy_physical_replication_slot_a ( PG_FUNCTION_ARGS  )

Definition at line 847 of file slotfuncs.c.

848{
849 return copy_replication_slot(fcinfo, false);
850}

References copy_replication_slot().

◆ pg_copy_physical_replication_slot_b()

Datum pg_copy_physical_replication_slot_b ( PG_FUNCTION_ARGS  )

Definition at line 853 of file slotfuncs.c.

854{
855 return copy_replication_slot(fcinfo, false);
856}

References copy_replication_slot().

◆ pg_create_logical_replication_slot()

Datum pg_create_logical_replication_slot ( PG_FUNCTION_ARGS  )

Definition at line 169 of file slotfuncs.c.

170{
173 bool temporary = PG_GETARG_BOOL(2);
174 bool two_phase = PG_GETARG_BOOL(3);
175 bool failover = PG_GETARG_BOOL(4);
176 Datum result;
177 TupleDesc tupdesc;
178 HeapTuple tuple;
179 Datum values[2];
180 bool nulls[2];
181
182 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
183 elog(ERROR, "return type must be a row type");
184
186
188
190 NameStr(*plugin),
191 temporary,
192 two_phase,
193 failover,
195 true);
196
199
200 memset(nulls, 0, sizeof(nulls));
201
202 tuple = heap_form_tuple(tupdesc, values, nulls);
203 result = HeapTupleGetDatum(tuple);
204
205 /* ok, slot is now fully created, mark it as persistent if needed */
206 if (!temporary)
209
210 PG_RETURN_DATUM(result);
211}
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28

References CheckLogicalDecodingRequirements(), CheckSlotPermissions(), ReplicationSlotPersistentData::confirmed_flush, create_logical_replication_slot(), ReplicationSlot::data, elog, ERROR, get_call_result_type(), heap_form_tuple(), HeapTupleGetDatum(), InvalidXLogRecPtr, LSNGetDatum(), MyReplicationSlot, name, ReplicationSlotPersistentData::name, NameGetDatum(), NameStr, PG_GETARG_BOOL, PG_GETARG_NAME, PG_RETURN_DATUM, plugin, ReplicationSlotPersist(), ReplicationSlotRelease(), two_phase, TYPEFUNC_COMPOSITE, and values.

◆ pg_create_physical_replication_slot()

Datum pg_create_physical_replication_slot ( PG_FUNCTION_ARGS  )

Definition at line 65 of file slotfuncs.c.

66{
68 bool immediately_reserve = PG_GETARG_BOOL(1);
69 bool temporary = PG_GETARG_BOOL(2);
70 Datum values[2];
71 bool nulls[2];
72 TupleDesc tupdesc;
73 HeapTuple tuple;
74 Datum result;
75
76 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
77 elog(ERROR, "return type must be a row type");
78
80
82
84 immediately_reserve,
85 temporary,
87
89 nulls[0] = false;
90
91 if (immediately_reserve)
92 {
94 nulls[1] = false;
95 }
96 else
97 nulls[1] = true;
98
99 tuple = heap_form_tuple(tupdesc, values, nulls);
100 result = HeapTupleGetDatum(tuple);
101
103
104 PG_RETURN_DATUM(result);
105}

References CheckSlotPermissions(), CheckSlotRequirements(), create_physical_replication_slot(), ReplicationSlot::data, elog, ERROR, get_call_result_type(), heap_form_tuple(), HeapTupleGetDatum(), InvalidXLogRecPtr, LSNGetDatum(), MyReplicationSlot, name, ReplicationSlotPersistentData::name, NameGetDatum(), NameStr, PG_GETARG_BOOL, PG_GETARG_NAME, PG_RETURN_DATUM, ReplicationSlotRelease(), ReplicationSlotPersistentData::restart_lsn, TYPEFUNC_COMPOSITE, and values.

◆ pg_drop_replication_slot()

Datum pg_drop_replication_slot ( PG_FUNCTION_ARGS  )

Definition at line 218 of file slotfuncs.c.

219{
221
223
225
227
229}
#define PG_RETURN_VOID()
Definition: fmgr.h:349
void ReplicationSlotDrop(const char *name, bool nowait)
Definition: slot.c:784

References CheckSlotPermissions(), CheckSlotRequirements(), name, NameStr, PG_GETARG_NAME, PG_RETURN_VOID, and ReplicationSlotDrop().

◆ pg_get_replication_slots()

Datum pg_get_replication_slots ( PG_FUNCTION_ARGS  )

Definition at line 236 of file slotfuncs.c.

237{
238#define PG_GET_REPLICATION_SLOTS_COLS 19
239 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
240 XLogRecPtr currlsn;
241 int slotno;
242
243 /*
244 * We don't require any special permission to see this function's data
245 * because nothing should be sensitive. The most critical being the slot
246 * name, which shouldn't contain anything particularly sensitive.
247 */
248
249 InitMaterializedSRF(fcinfo, 0);
250
251 currlsn = GetXLogWriteRecPtr();
252
253 LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
254 for (slotno = 0; slotno < max_replication_slots; slotno++)
255 {
257 ReplicationSlot slot_contents;
260 WALAvailability walstate;
261 int i;
263
264 if (!slot->in_use)
265 continue;
266
267 /* Copy slot contents while holding spinlock, then examine at leisure */
268 SpinLockAcquire(&slot->mutex);
269 slot_contents = *slot;
270 SpinLockRelease(&slot->mutex);
271
272 memset(values, 0, sizeof(values));
273 memset(nulls, 0, sizeof(nulls));
274
275 i = 0;
276 values[i++] = NameGetDatum(&slot_contents.data.name);
277
278 if (slot_contents.data.database == InvalidOid)
279 nulls[i++] = true;
280 else
281 values[i++] = NameGetDatum(&slot_contents.data.plugin);
282
283 if (slot_contents.data.database == InvalidOid)
284 values[i++] = CStringGetTextDatum("physical");
285 else
286 values[i++] = CStringGetTextDatum("logical");
287
288 if (slot_contents.data.database == InvalidOid)
289 nulls[i++] = true;
290 else
291 values[i++] = ObjectIdGetDatum(slot_contents.data.database);
292
293 values[i++] = BoolGetDatum(slot_contents.data.persistency == RS_TEMPORARY);
294 values[i++] = BoolGetDatum(slot_contents.active_pid != 0);
295
296 if (slot_contents.active_pid != 0)
297 values[i++] = Int32GetDatum(slot_contents.active_pid);
298 else
299 nulls[i++] = true;
300
301 if (slot_contents.data.xmin != InvalidTransactionId)
302 values[i++] = TransactionIdGetDatum(slot_contents.data.xmin);
303 else
304 nulls[i++] = true;
305
306 if (slot_contents.data.catalog_xmin != InvalidTransactionId)
307 values[i++] = TransactionIdGetDatum(slot_contents.data.catalog_xmin);
308 else
309 nulls[i++] = true;
310
311 if (slot_contents.data.restart_lsn != InvalidXLogRecPtr)
312 values[i++] = LSNGetDatum(slot_contents.data.restart_lsn);
313 else
314 nulls[i++] = true;
315
316 if (slot_contents.data.confirmed_flush != InvalidXLogRecPtr)
317 values[i++] = LSNGetDatum(slot_contents.data.confirmed_flush);
318 else
319 nulls[i++] = true;
320
321 /*
322 * If the slot has not been invalidated, test availability from
323 * restart_lsn.
324 */
325 if (slot_contents.data.invalidated != RS_INVAL_NONE)
326 walstate = WALAVAIL_REMOVED;
327 else
328 walstate = GetWALAvailability(slot_contents.data.restart_lsn);
329
330 switch (walstate)
331 {
333 nulls[i++] = true;
334 break;
335
337 values[i++] = CStringGetTextDatum("reserved");
338 break;
339
341 values[i++] = CStringGetTextDatum("extended");
342 break;
343
345 values[i++] = CStringGetTextDatum("unreserved");
346 break;
347
348 case WALAVAIL_REMOVED:
349
350 /*
351 * If we read the restart_lsn long enough ago, maybe that file
352 * has been removed by now. However, the walsender could have
353 * moved forward enough that it jumped to another file after
354 * we looked. If checkpointer signalled the process to
355 * termination, then it's definitely lost; but if a process is
356 * still alive, then "unreserved" seems more appropriate.
357 *
358 * If we do change it, save the state for safe_wal_size below.
359 */
360 if (!XLogRecPtrIsInvalid(slot_contents.data.restart_lsn))
361 {
362 int pid;
363
364 SpinLockAcquire(&slot->mutex);
365 pid = slot->active_pid;
366 slot_contents.data.restart_lsn = slot->data.restart_lsn;
367 SpinLockRelease(&slot->mutex);
368 if (pid != 0)
369 {
370 values[i++] = CStringGetTextDatum("unreserved");
371 walstate = WALAVAIL_UNRESERVED;
372 break;
373 }
374 }
375 values[i++] = CStringGetTextDatum("lost");
376 break;
377 }
378
379 /*
380 * safe_wal_size is only computed for slots that have not been lost,
381 * and only if there's a configured maximum size.
382 */
383 if (walstate == WALAVAIL_REMOVED || max_slot_wal_keep_size_mb < 0)
384 nulls[i++] = true;
385 else
386 {
387 XLogSegNo targetSeg;
388 uint64 slotKeepSegs;
389 uint64 keepSegs;
390 XLogSegNo failSeg;
391 XLogRecPtr failLSN;
392
393 XLByteToSeg(slot_contents.data.restart_lsn, targetSeg, wal_segment_size);
394
395 /* determine how many segments can be kept by slots */
397 /* ditto for wal_keep_size */
399
400 /* if currpos reaches failLSN, we lose our segment */
401 failSeg = targetSeg + Max(slotKeepSegs, keepSegs) + 1;
402 XLogSegNoOffsetToRecPtr(failSeg, 0, wal_segment_size, failLSN);
403
404 values[i++] = Int64GetDatum(failLSN - currlsn);
405 }
406
407 values[i++] = BoolGetDatum(slot_contents.data.two_phase);
408
409 if (slot_contents.inactive_since > 0)
410 values[i++] = TimestampTzGetDatum(slot_contents.inactive_since);
411 else
412 nulls[i++] = true;
413
414 cause = slot_contents.data.invalidated;
415
416 if (SlotIsPhysical(&slot_contents))
417 nulls[i++] = true;
418 else
419 {
420 /*
421 * rows_removed and wal_level_insufficient are the only two
422 * reasons for the logical slot's conflict with recovery.
423 */
424 if (cause == RS_INVAL_HORIZON ||
425 cause == RS_INVAL_WAL_LEVEL)
426 values[i++] = BoolGetDatum(true);
427 else
428 values[i++] = BoolGetDatum(false);
429 }
430
431 if (cause == RS_INVAL_NONE)
432 nulls[i++] = true;
433 else
435
436 values[i++] = BoolGetDatum(slot_contents.data.failover);
437
438 values[i++] = BoolGetDatum(slot_contents.data.synced);
439
441
442 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
443 values, nulls);
444 }
445
446 LWLockRelease(ReplicationSlotControlLock);
447
448 return (Datum) 0;
449}
#define CStringGetTextDatum(s)
Definition: builtins.h:97
#define Max(x, y)
Definition: c.h:955
uint64_t uint64
Definition: c.h:489
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1807
void InitMaterializedSRF(FunctionCallInfo fcinfo, bits32 flags)
Definition: funcapi.c:76
static Datum TransactionIdGetDatum(TransactionId X)
Definition: postgres.h:277
static Datum BoolGetDatum(bool X)
Definition: postgres.h:107
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:257
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:217
#define InvalidOid
Definition: postgres_ext.h:37
const char *const SlotInvalidationCauses[]
Definition: slot.c:105
#define SlotIsPhysical(slot)
Definition: slot.h:216
ReplicationSlotInvalidationCause
Definition: slot.h:51
@ RS_INVAL_HORIZON
Definition: slot.h:56
@ RS_INVAL_WAL_LEVEL
Definition: slot.h:58
@ RS_INVAL_NONE
Definition: slot.h:52
#define PG_GET_REPLICATION_SLOTS_COLS
ReplicationSlotInvalidationCause invalidated
Definition: slot.h:99
pid_t active_pid
Definition: slot.h:160
TimestampTz inactive_since
Definition: slot.h:213
TupleDesc setDesc
Definition: execnodes.h:358
Tuplestorestate * setResult
Definition: execnodes.h:357
#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
int wal_keep_size_mb
Definition: xlog.c:116
WALAvailability GetWALAvailability(XLogRecPtr targetLSN)
Definition: xlog.c:7869
int max_slot_wal_keep_size_mb
Definition: xlog.c:135
XLogRecPtr GetXLogWriteRecPtr(void)
Definition: xlog.c:9451
WALAvailability
Definition: xlog.h:188
@ WALAVAIL_REMOVED
Definition: xlog.h:194
@ WALAVAIL_RESERVED
Definition: xlog.h:190
@ WALAVAIL_UNRESERVED
Definition: xlog.h:193
@ WALAVAIL_EXTENDED
Definition: xlog.h:191
@ WALAVAIL_INVALID_LSN
Definition: xlog.h:189
#define XLogSegNoOffsetToRecPtr(segno, offset, wal_segsz_bytes, dest)
#define XLogMBVarToSegs(mbvar, wal_segsz_bytes)

References ReplicationSlot::active_pid, Assert, BoolGetDatum(), ReplicationSlotPersistentData::catalog_xmin, ReplicationSlotPersistentData::confirmed_flush, CStringGetTextDatum, ReplicationSlot::data, ReplicationSlotPersistentData::database, ReplicationSlotPersistentData::failover, GetWALAvailability(), GetXLogWriteRecPtr(), i, ReplicationSlot::in_use, ReplicationSlot::inactive_since, InitMaterializedSRF(), Int32GetDatum(), Int64GetDatum(), ReplicationSlotPersistentData::invalidated, InvalidOid, InvalidTransactionId, InvalidXLogRecPtr, LSNGetDatum(), LW_SHARED, LWLockAcquire(), LWLockRelease(), Max, max_replication_slots, max_slot_wal_keep_size_mb, ReplicationSlot::mutex, ReplicationSlotPersistentData::name, NameGetDatum(), ObjectIdGetDatum(), ReplicationSlotPersistentData::persistency, PG_GET_REPLICATION_SLOTS_COLS, ReplicationSlotPersistentData::plugin, ReplicationSlotCtlData::replication_slots, ReplicationSlotCtl, ReplicationSlotPersistentData::restart_lsn, RS_INVAL_HORIZON, RS_INVAL_NONE, RS_INVAL_WAL_LEVEL, RS_TEMPORARY, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SlotInvalidationCauses, SlotIsPhysical, SpinLockAcquire, SpinLockRelease, ReplicationSlotPersistentData::synced, TimestampTzGetDatum(), TransactionIdGetDatum(), tuplestore_putvalues(), ReplicationSlotPersistentData::two_phase, values, wal_keep_size_mb, wal_segment_size, WALAVAIL_EXTENDED, WALAVAIL_INVALID_LSN, WALAVAIL_REMOVED, WALAVAIL_RESERVED, WALAVAIL_UNRESERVED, XLByteToSeg, XLogMBVarToSegs, XLogRecPtrIsInvalid, XLogSegNoOffsetToRecPtr, and ReplicationSlotPersistentData::xmin.

◆ pg_logical_replication_slot_advance()

static XLogRecPtr pg_logical_replication_slot_advance ( XLogRecPtr  moveto)
static

Definition at line 495 of file slotfuncs.c.

496{
497 return LogicalSlotAdvanceAndCheckSnapState(moveto, NULL);
498}
XLogRecPtr LogicalSlotAdvanceAndCheckSnapState(XLogRecPtr moveto, bool *found_consistent_snapshot)
Definition: logical.c:2063

References LogicalSlotAdvanceAndCheckSnapState().

Referenced by pg_replication_slot_advance().

◆ pg_physical_replication_slot_advance()

static XLogRecPtr pg_physical_replication_slot_advance ( XLogRecPtr  moveto)
static

Definition at line 459 of file slotfuncs.c.

460{
462 XLogRecPtr retlsn = startlsn;
463
464 Assert(moveto != InvalidXLogRecPtr);
465
466 if (startlsn < moveto)
467 {
471 retlsn = moveto;
472
473 /*
474 * Dirty the slot so as it is written out at the next checkpoint. Note
475 * that the LSN position advanced may still be lost in the event of a
476 * crash, but this makes the data consistent after a clean shutdown.
477 */
479
480 /*
481 * Wake up logical walsenders holding logical failover slots after
482 * updating the restart_lsn of the physical slot.
483 */
485 }
486
487 return retlsn;
488}
void PhysicalWakeupLogicalWalSnd(void)
Definition: walsender.c:1708

References Assert, ReplicationSlot::data, InvalidXLogRecPtr, ReplicationSlot::mutex, MyReplicationSlot, PhysicalWakeupLogicalWalSnd(), ReplicationSlotMarkDirty(), ReplicationSlotPersistentData::restart_lsn, SpinLockAcquire, and SpinLockRelease.

Referenced by pg_replication_slot_advance().

◆ pg_replication_slot_advance()

Datum pg_replication_slot_advance ( PG_FUNCTION_ARGS  )

Definition at line 504 of file slotfuncs.c.

505{
506 Name slotname = PG_GETARG_NAME(0);
507 XLogRecPtr moveto = PG_GETARG_LSN(1);
508 XLogRecPtr endlsn;
509 XLogRecPtr minlsn;
510 TupleDesc tupdesc;
511 Datum values[2];
512 bool nulls[2];
513 HeapTuple tuple;
514 Datum result;
515
517
519
520 if (XLogRecPtrIsInvalid(moveto))
522 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
523 errmsg("invalid target WAL LSN")));
524
525 /* Build a tuple descriptor for our result type */
526 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
527 elog(ERROR, "return type must be a row type");
528
529 /*
530 * We can't move slot past what's been flushed/replayed so clamp the
531 * target position accordingly.
532 */
533 if (!RecoveryInProgress())
534 moveto = Min(moveto, GetFlushRecPtr(NULL));
535 else
536 moveto = Min(moveto, GetXLogReplayRecPtr(NULL));
537
538 /* Acquire the slot so we "own" it */
539 ReplicationSlotAcquire(NameStr(*slotname), true);
540
541 /* A slot whose restart_lsn has never been reserved cannot be advanced */
544 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
545 errmsg("replication slot \"%s\" cannot be advanced",
546 NameStr(*slotname)),
547 errdetail("This slot has never previously reserved WAL, or it has been invalidated.")));
548
549 /*
550 * Check if the slot is not moving backwards. Physical slots rely simply
551 * on restart_lsn as a minimum point, while logical slots have confirmed
552 * consumption up to confirmed_flush, meaning that in both cases data
553 * older than that is not available anymore.
554 */
557 else
559
560 if (moveto < minlsn)
562 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
563 errmsg("cannot advance replication slot to %X/%X, minimum is %X/%X",
564 LSN_FORMAT_ARGS(moveto), LSN_FORMAT_ARGS(minlsn))));
565
566 /* Do the actual slot update, depending on the slot type */
569 else
571
573 nulls[0] = false;
574
575 /*
576 * Recompute the minimum LSN and xmin across all slots to adjust with the
577 * advancing potentially done.
578 */
581
583
584 /* Return the reached position. */
585 values[1] = LSNGetDatum(endlsn);
586 nulls[1] = false;
587
588 tuple = heap_form_tuple(tupdesc, values, nulls);
589 result = HeapTupleGetDatum(tuple);
590
591 PG_RETURN_DATUM(result);
592}
#define Min(x, y)
Definition: c.h:961
#define OidIsValid(objectId)
Definition: c.h:732
#define PG_GETARG_LSN(n)
Definition: pg_lsn.h:33
void ReplicationSlotAcquire(const char *name, bool nowait)
Definition: slot.c:540
static XLogRecPtr pg_logical_replication_slot_advance(XLogRecPtr moveto)
Definition: slotfuncs.c:495
static XLogRecPtr pg_physical_replication_slot_advance(XLogRecPtr moveto)
Definition: slotfuncs.c:459
bool RecoveryInProgress(void)
Definition: xlog.c:6334
XLogRecPtr GetFlushRecPtr(TimeLineID *insertTLI)
Definition: xlog.c:6499
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)

References Assert, CheckSlotPermissions(), ReplicationSlotPersistentData::confirmed_flush, ReplicationSlot::data, ReplicationSlotPersistentData::database, elog, ereport, errcode(), errdetail(), errmsg(), ERROR, get_call_result_type(), GetFlushRecPtr(), GetXLogReplayRecPtr(), heap_form_tuple(), HeapTupleGetDatum(), LSN_FORMAT_ARGS, LSNGetDatum(), Min, MyReplicationSlot, ReplicationSlotPersistentData::name, NameGetDatum(), NameStr, OidIsValid, PG_GETARG_LSN, PG_GETARG_NAME, pg_logical_replication_slot_advance(), pg_physical_replication_slot_advance(), PG_RETURN_DATUM, RecoveryInProgress(), ReplicationSlotAcquire(), ReplicationSlotRelease(), ReplicationSlotsComputeRequiredLSN(), ReplicationSlotsComputeRequiredXmin(), ReplicationSlotPersistentData::restart_lsn, TYPEFUNC_COMPOSITE, values, and XLogRecPtrIsInvalid.

◆ pg_sync_replication_slots()

Datum pg_sync_replication_slots ( PG_FUNCTION_ARGS  )

Definition at line 863 of file slotfuncs.c.

864{
866 char *err;
867 StringInfoData app_name;
868
870
871 if (!RecoveryInProgress())
873 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
874 errmsg("replication slots can only be synchronized to a standby server"));
875
877
878 /* Load the libpq-specific functions */
879 load_file("libpqwalreceiver", false);
880
882
883 initStringInfo(&app_name);
884 if (cluster_name[0])
885 appendStringInfo(&app_name, "%s_slotsync", cluster_name);
886 else
887 appendStringInfoString(&app_name, "slotsync");
888
889 /* Connect to the primary server. */
890 wrconn = walrcv_connect(PrimaryConnInfo, false, false, false,
891 app_name.data, &err);
892 pfree(app_name.data);
893
894 if (!wrconn)
896 errcode(ERRCODE_CONNECTION_FAILURE),
897 errmsg("synchronization worker \"%s\" could not connect to the primary server: %s",
898 app_name.data, err));
899
901
903
905}
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:134
void err(int eval, const char *fmt,...)
Definition: err.c:43
char * cluster_name
Definition: guc_tables.c:537
void pfree(void *pointer)
Definition: mcxt.c:1521
void SyncReplicationSlots(WalReceiverConn *wrconn)
Definition: slotsync.c:1724
char * CheckAndGetDbnameFromConninfo(void)
Definition: slotsync.c:1010
bool ValidateSlotSyncParams(int elevel)
Definition: slotsync.c:1037
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
static WalReceiverConn * wrconn
Definition: walreceiver.c:92
#define walrcv_connect(conninfo, replication, logical, must_use_password, appname, err)
Definition: walreceiver.h:435
#define walrcv_disconnect(conn)
Definition: walreceiver.h:467
char * PrimaryConnInfo
Definition: xlogrecovery.c:96

References appendStringInfo(), appendStringInfoString(), CheckAndGetDbnameFromConninfo(), CheckSlotPermissions(), cluster_name, StringInfoData::data, ereport, err(), errcode(), errmsg(), ERROR, initStringInfo(), load_file(), pfree(), PG_RETURN_VOID, PrimaryConnInfo, RecoveryInProgress(), SyncReplicationSlots(), ValidateSlotSyncParams(), walrcv_connect, walrcv_disconnect, and wrconn.