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 "miscadmin.h"
#include "replication/decode.h"
#include "replication/logical.h"
#include "replication/slot.h"
#include "replication/slotsync.h"
#include "utils/builtins.h"
#include "utils/guc.h"
#include "utils/inval.h"
#include "utils/pg_lsn.h"
#include "utils/resowner.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 601 of file slotfuncs.c.

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

126 {
127  LogicalDecodingContext *ctx = NULL;
128 
130 
131  /*
132  * Acquire a logical decoding slot, this will check for conflicting names.
133  * Initially create persistent slot as ephemeral - that allows us to
134  * nicely handle errors during initialization because it'll get dropped if
135  * this transaction fails. We'll make it persistent at the end. Temporary
136  * slots can be created as temporary from beginning as they get dropped on
137  * error as well.
138  */
140  temporary ? RS_TEMPORARY : RS_EPHEMERAL, two_phase,
141  failover, false);
142 
143  /*
144  * Create logical decoding context to find start point or, if we don't
145  * need it, to 1) bump slot's restart_lsn and xmin 2) check plugin sanity.
146  *
147  * Note: when !find_startpoint this is still important, because it's at
148  * this point that the output plugin is validated.
149  */
151  false, /* just catalogs is OK */
152  restart_lsn,
153  XL_ROUTINE(.page_read = read_local_xlog_page,
154  .segment_open = wal_segment_open,
155  .segment_close = wal_segment_close),
156  NULL, NULL, NULL);
157 
158  /*
159  * If caller needs us to determine the decoding start point, do so now.
160  * This might take a while.
161  */
162  if (find_startpoint)
164 
165  /* don't need the decoding context anymore */
166  FreeDecodingContext(ctx);
167 }
void FreeDecodingContext(LogicalDecodingContext *ctx)
Definition: logical.c:693
void DecodingContextFindStartpoint(LogicalDecodingContext *ctx)
Definition: logical.c:649
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:329
#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:36
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 40 of file slotfuncs.c.

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

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 832 of file slotfuncs.c.

833 {
834  return copy_replication_slot(fcinfo, true);
835 }
static Datum copy_replication_slot(FunctionCallInfo fcinfo, bool logical_slot)
Definition: slotfuncs.c:601

References copy_replication_slot().

◆ pg_copy_logical_replication_slot_b()

Datum pg_copy_logical_replication_slot_b ( PG_FUNCTION_ARGS  )

Definition at line 838 of file slotfuncs.c.

839 {
840  return copy_replication_slot(fcinfo, true);
841 }

References copy_replication_slot().

◆ pg_copy_logical_replication_slot_c()

Datum pg_copy_logical_replication_slot_c ( PG_FUNCTION_ARGS  )

Definition at line 844 of file slotfuncs.c.

845 {
846  return copy_replication_slot(fcinfo, true);
847 }

References copy_replication_slot().

◆ pg_copy_physical_replication_slot_a()

Datum pg_copy_physical_replication_slot_a ( PG_FUNCTION_ARGS  )

Definition at line 850 of file slotfuncs.c.

851 {
852  return copy_replication_slot(fcinfo, false);
853 }

References copy_replication_slot().

◆ pg_copy_physical_replication_slot_b()

Datum pg_copy_physical_replication_slot_b ( PG_FUNCTION_ARGS  )

Definition at line 856 of file slotfuncs.c.

857 {
858  return copy_replication_slot(fcinfo, false);
859 }

References copy_replication_slot().

◆ pg_create_logical_replication_slot()

Datum pg_create_logical_replication_slot ( PG_FUNCTION_ARGS  )

Definition at line 173 of file slotfuncs.c.

174 {
175  Name name = PG_GETARG_NAME(0);
177  bool temporary = PG_GETARG_BOOL(2);
178  bool two_phase = PG_GETARG_BOOL(3);
179  bool failover = PG_GETARG_BOOL(4);
180  Datum result;
181  TupleDesc tupdesc;
182  HeapTuple tuple;
183  Datum values[2];
184  bool nulls[2];
185 
186  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
187  elog(ERROR, "return type must be a row type");
188 
190 
192 
194  NameStr(*plugin),
195  temporary,
196  two_phase,
197  failover,
199  true);
200 
203 
204  memset(nulls, 0, sizeof(nulls));
205 
206  tuple = heap_form_tuple(tupdesc, values, nulls);
207  result = HeapTupleGetDatum(tuple);
208 
209  /* ok, slot is now fully created, mark it as persistent if needed */
210  if (!temporary)
213 
214  PG_RETURN_DATUM(result);
215 }
#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 69 of file slotfuncs.c.

70 {
72  bool immediately_reserve = PG_GETARG_BOOL(1);
73  bool temporary = PG_GETARG_BOOL(2);
74  Datum values[2];
75  bool nulls[2];
76  TupleDesc tupdesc;
77  HeapTuple tuple;
78  Datum result;
79 
80  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
81  elog(ERROR, "return type must be a row type");
82 
84 
86 
88  immediately_reserve,
89  temporary,
91 
93  nulls[0] = false;
94 
95  if (immediately_reserve)
96  {
98  nulls[1] = false;
99  }
100  else
101  nulls[1] = true;
102 
103  tuple = heap_form_tuple(tupdesc, values, nulls);
104  result = HeapTupleGetDatum(tuple);
105 
107 
108  PG_RETURN_DATUM(result);
109 }

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 222 of file slotfuncs.c.

223 {
224  Name name = PG_GETARG_NAME(0);
225 
227 
229 
231 
232  PG_RETURN_VOID();
233 }
#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 240 of file slotfuncs.c.

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

500 {
501  return LogicalSlotAdvanceAndCheckSnapState(moveto, NULL);
502 }
XLogRecPtr LogicalSlotAdvanceAndCheckSnapState(XLogRecPtr moveto, bool *found_consistent_snapshot)
Definition: logical.c:2060

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 463 of file slotfuncs.c.

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

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 508 of file slotfuncs.c.

509 {
510  Name slotname = PG_GETARG_NAME(0);
511  XLogRecPtr moveto = PG_GETARG_LSN(1);
512  XLogRecPtr endlsn;
513  XLogRecPtr minlsn;
514  TupleDesc tupdesc;
515  Datum values[2];
516  bool nulls[2];
517  HeapTuple tuple;
518  Datum result;
519 
521 
523 
524  if (XLogRecPtrIsInvalid(moveto))
525  ereport(ERROR,
526  (errmsg("invalid target WAL LSN")));
527 
528  /* Build a tuple descriptor for our result type */
529  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
530  elog(ERROR, "return type must be a row type");
531 
532  /*
533  * We can't move slot past what's been flushed/replayed so clamp the
534  * target position accordingly.
535  */
536  if (!RecoveryInProgress())
537  moveto = Min(moveto, GetFlushRecPtr(NULL));
538  else
539  moveto = Min(moveto, GetXLogReplayRecPtr(NULL));
540 
541  /* Acquire the slot so we "own" it */
542  ReplicationSlotAcquire(NameStr(*slotname), true);
543 
544  /* A slot whose restart_lsn has never been reserved cannot be advanced */
546  ereport(ERROR,
547  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
548  errmsg("replication slot \"%s\" cannot be advanced",
549  NameStr(*slotname)),
550  errdetail("This slot has never previously reserved WAL, or it has been invalidated.")));
551 
552  /*
553  * Check if the slot is not moving backwards. Physical slots rely simply
554  * on restart_lsn as a minimum point, while logical slots have confirmed
555  * consumption up to confirmed_flush, meaning that in both cases data
556  * older than that is not available anymore.
557  */
560  else
562 
563  if (moveto < minlsn)
564  ereport(ERROR,
565  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
566  errmsg("cannot advance replication slot to %X/%X, minimum is %X/%X",
567  LSN_FORMAT_ARGS(moveto), LSN_FORMAT_ARGS(minlsn))));
568 
569  /* Do the actual slot update, depending on the slot type */
571  endlsn = pg_logical_replication_slot_advance(moveto);
572  else
573  endlsn = pg_physical_replication_slot_advance(moveto);
574 
576  nulls[0] = false;
577 
578  /*
579  * Recompute the minimum LSN and xmin across all slots to adjust with the
580  * advancing potentially done.
581  */
584 
586 
587  /* Return the reached position. */
588  values[1] = LSNGetDatum(endlsn);
589  nulls[1] = false;
590 
591  tuple = heap_form_tuple(tupdesc, values, nulls);
592  result = HeapTupleGetDatum(tuple);
593 
594  PG_RETURN_DATUM(result);
595 }
#define Min(x, y)
Definition: c.h:1004
#define OidIsValid(objectId)
Definition: c.h:775
#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:499
static XLogRecPtr pg_physical_replication_slot_advance(XLogRecPtr moveto)
Definition: slotfuncs.c:463
bool RecoveryInProgress(void)
Definition: xlog.c:6290
XLogRecPtr GetFlushRecPtr(TimeLineID *insertTLI)
Definition: xlog.c:6455
#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 866 of file slotfuncs.c.

867 {
869  char *err;
870  StringInfoData app_name;
871 
873 
874  if (!RecoveryInProgress())
875  ereport(ERROR,
876  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
877  errmsg("replication slots can only be synchronized to a standby server"));
878 
880 
881  /* Load the libpq-specific functions */
882  load_file("libpqwalreceiver", false);
883 
885 
886  initStringInfo(&app_name);
887  if (cluster_name[0])
888  appendStringInfo(&app_name, "%s_slotsync", cluster_name);
889  else
890  appendStringInfoString(&app_name, "slotsync");
891 
892  /* Connect to the primary server. */
893  wrconn = walrcv_connect(PrimaryConnInfo, false, false, false,
894  app_name.data, &err);
895  pfree(app_name.data);
896 
897  if (!wrconn)
898  ereport(ERROR,
899  errcode(ERRCODE_CONNECTION_FAILURE),
900  errmsg("could not connect to the primary server: %s", err));
901 
903 
905 
906  PG_RETURN_VOID();
907 }
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:144
void err(int eval, const char *fmt,...)
Definition: err.c:43
char * cluster_name
Definition: guc_tables.c:539
void pfree(void *pointer)
Definition: mcxt.c:1520
void SyncReplicationSlots(WalReceiverConn *wrconn)
Definition: slotsync.c:1725
char * CheckAndGetDbnameFromConninfo(void)
Definition: slotsync.c:1013
bool ValidateSlotSyncParams(int elevel)
Definition: slotsync.c:1039
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:97
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:182
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
static WalReceiverConn * wrconn
Definition: walreceiver.c:92
#define walrcv_connect(conninfo, replication, logical, must_use_password, appname, err)
Definition: walreceiver.h:432
#define walrcv_disconnect(conn)
Definition: walreceiver.h:464
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.