LCOV - code coverage report
Current view: top level - src/backend/replication - slotfuncs.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 295 311 94.9 %
Date: 2024-11-21 08:14:44 Functions: 15 16 93.8 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * slotfuncs.c
       4             :  *     Support functions for replication slots
       5             :  *
       6             :  * Copyright (c) 2012-2024, 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"
      16             : #include "access/xlog_internal.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"
      22             : #include "replication/slotsync.h"
      23             : #include "utils/builtins.h"
      24             : #include "utils/guc.h"
      25             : #include "utils/pg_lsn.h"
      26             : 
      27             : /*
      28             :  * Helper function for creating a new physical replication slot with
      29             :  * given arguments. Note that this function doesn't release the created
      30             :  * slot.
      31             :  *
      32             :  * If restart_lsn is a valid value, we use it without WAL reservation
      33             :  * routine. So the caller must guarantee that WAL is available.
      34             :  */
      35             : static void
      36          72 : create_physical_replication_slot(char *name, bool immediately_reserve,
      37             :                                  bool temporary, XLogRecPtr restart_lsn)
      38             : {
      39             :     Assert(!MyReplicationSlot);
      40             : 
      41             :     /* acquire replication slot, this will check for conflicting names */
      42          72 :     ReplicationSlotCreate(name, false,
      43             :                           temporary ? RS_TEMPORARY : RS_PERSISTENT, false,
      44             :                           false, false);
      45             : 
      46          72 :     if (immediately_reserve)
      47             :     {
      48             :         /* Reserve WAL as the user asked for it */
      49          32 :         if (XLogRecPtrIsInvalid(restart_lsn))
      50          24 :             ReplicationSlotReserveWal();
      51             :         else
      52           8 :             MyReplicationSlot->data.restart_lsn = restart_lsn;
      53             : 
      54             :         /* Write this slot to disk */
      55          32 :         ReplicationSlotMarkDirty();
      56          32 :         ReplicationSlotSave();
      57             :     }
      58          72 : }
      59             : 
      60             : /*
      61             :  * SQL function for creating a new physical (streaming replication)
      62             :  * replication slot.
      63             :  */
      64             : Datum
      65          64 : pg_create_physical_replication_slot(PG_FUNCTION_ARGS)
      66             : {
      67          64 :     Name        name = PG_GETARG_NAME(0);
      68          64 :     bool        immediately_reserve = PG_GETARG_BOOL(1);
      69          64 :     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          64 :     if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
      77           0 :         elog(ERROR, "return type must be a row type");
      78             : 
      79          64 :     CheckSlotPermissions();
      80             : 
      81          64 :     CheckSlotRequirements();
      82             : 
      83          64 :     create_physical_replication_slot(NameStr(*name),
      84             :                                      immediately_reserve,
      85             :                                      temporary,
      86             :                                      InvalidXLogRecPtr);
      87             : 
      88          64 :     values[0] = NameGetDatum(&MyReplicationSlot->data.name);
      89          64 :     nulls[0] = false;
      90             : 
      91          64 :     if (immediately_reserve)
      92             :     {
      93          24 :         values[1] = LSNGetDatum(MyReplicationSlot->data.restart_lsn);
      94          24 :         nulls[1] = false;
      95             :     }
      96             :     else
      97          40 :         nulls[1] = true;
      98             : 
      99          64 :     tuple = heap_form_tuple(tupdesc, values, nulls);
     100          64 :     result = HeapTupleGetDatum(tuple);
     101             : 
     102          64 :     ReplicationSlotRelease();
     103             : 
     104          64 :     PG_RETURN_DATUM(result);
     105             : }
     106             : 
     107             : 
     108             : /*
     109             :  * Helper function for creating a new logical replication slot with
     110             :  * given arguments. Note that this function doesn't release the created
     111             :  * slot.
     112             :  *
     113             :  * When find_startpoint is false, the slot's confirmed_flush is not set; it's
     114             :  * caller's responsibility to ensure it's set to something sensible.
     115             :  */
     116             : static void
     117         242 : create_logical_replication_slot(char *name, char *plugin,
     118             :                                 bool temporary, bool two_phase,
     119             :                                 bool failover,
     120             :                                 XLogRecPtr restart_lsn,
     121             :                                 bool find_startpoint)
     122             : {
     123         242 :     LogicalDecodingContext *ctx = NULL;
     124             : 
     125             :     Assert(!MyReplicationSlot);
     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             :      */
     135         242 :     ReplicationSlotCreate(name, true,
     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             :      */
     146         232 :     ctx = CreateInitDecodingContext(plugin, NIL,
     147             :                                     false,  /* just catalogs is OK */
     148             :                                     restart_lsn,
     149         232 :                                     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         226 :     if (find_startpoint)
     159         214 :         DecodingContextFindStartpoint(ctx);
     160             : 
     161             :     /* don't need the decoding context anymore */
     162         222 :     FreeDecodingContext(ctx);
     163         222 : }
     164             : 
     165             : /*
     166             :  * SQL function for creating a new logical replication slot.
     167             :  */
     168             : Datum
     169         230 : pg_create_logical_replication_slot(PG_FUNCTION_ARGS)
     170             : {
     171         230 :     Name        name = PG_GETARG_NAME(0);
     172         230 :     Name        plugin = PG_GETARG_NAME(1);
     173         230 :     bool        temporary = PG_GETARG_BOOL(2);
     174         230 :     bool        two_phase = PG_GETARG_BOOL(3);
     175         230 :     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         230 :     if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
     183           0 :         elog(ERROR, "return type must be a row type");
     184             : 
     185         230 :     CheckSlotPermissions();
     186             : 
     187         228 :     CheckLogicalDecodingRequirements();
     188             : 
     189         228 :     create_logical_replication_slot(NameStr(*name),
     190         228 :                                     NameStr(*plugin),
     191             :                                     temporary,
     192             :                                     two_phase,
     193             :                                     failover,
     194             :                                     InvalidXLogRecPtr,
     195             :                                     true);
     196             : 
     197         210 :     values[0] = NameGetDatum(&MyReplicationSlot->data.name);
     198         210 :     values[1] = LSNGetDatum(MyReplicationSlot->data.confirmed_flush);
     199             : 
     200         210 :     memset(nulls, 0, sizeof(nulls));
     201             : 
     202         210 :     tuple = heap_form_tuple(tupdesc, values, nulls);
     203         210 :     result = HeapTupleGetDatum(tuple);
     204             : 
     205             :     /* ok, slot is now fully created, mark it as persistent if needed */
     206         210 :     if (!temporary)
     207         200 :         ReplicationSlotPersist();
     208         210 :     ReplicationSlotRelease();
     209             : 
     210         210 :     PG_RETURN_DATUM(result);
     211             : }
     212             : 
     213             : 
     214             : /*
     215             :  * SQL function for dropping a replication slot.
     216             :  */
     217             : Datum
     218         252 : pg_drop_replication_slot(PG_FUNCTION_ARGS)
     219             : {
     220         252 :     Name        name = PG_GETARG_NAME(0);
     221             : 
     222         252 :     CheckSlotPermissions();
     223             : 
     224         248 :     CheckSlotRequirements();
     225             : 
     226         248 :     ReplicationSlotDrop(NameStr(*name), true);
     227             : 
     228         236 :     PG_RETURN_VOID();
     229             : }
     230             : 
     231             : /*
     232             :  * pg_get_replication_slots - SQL SRF showing all replication slots
     233             :  * that currently exist on the database cluster.
     234             :  */
     235             : Datum
     236         540 : pg_get_replication_slots(PG_FUNCTION_ARGS)
     237             : {
     238             : #define PG_GET_REPLICATION_SLOTS_COLS 19
     239         540 :     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         540 :     InitMaterializedSRF(fcinfo, 0);
     250             : 
     251         540 :     currlsn = GetXLogWriteRecPtr();
     252             : 
     253         540 :     LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
     254        4396 :     for (slotno = 0; slotno < max_replication_slots; slotno++)
     255             :     {
     256        3856 :         ReplicationSlot *slot = &ReplicationSlotCtl->replication_slots[slotno];
     257             :         ReplicationSlot slot_contents;
     258             :         Datum       values[PG_GET_REPLICATION_SLOTS_COLS];
     259             :         bool        nulls[PG_GET_REPLICATION_SLOTS_COLS];
     260             :         WALAvailability walstate;
     261             :         int         i;
     262             :         ReplicationSlotInvalidationCause cause;
     263             : 
     264        3856 :         if (!slot->in_use)
     265        2946 :             continue;
     266             : 
     267             :         /* Copy slot contents while holding spinlock, then examine at leisure */
     268         910 :         SpinLockAcquire(&slot->mutex);
     269         910 :         slot_contents = *slot;
     270         910 :         SpinLockRelease(&slot->mutex);
     271             : 
     272         910 :         memset(values, 0, sizeof(values));
     273         910 :         memset(nulls, 0, sizeof(nulls));
     274             : 
     275         910 :         i = 0;
     276         910 :         values[i++] = NameGetDatum(&slot_contents.data.name);
     277             : 
     278         910 :         if (slot_contents.data.database == InvalidOid)
     279         260 :             nulls[i++] = true;
     280             :         else
     281         650 :             values[i++] = NameGetDatum(&slot_contents.data.plugin);
     282             : 
     283         910 :         if (slot_contents.data.database == InvalidOid)
     284         260 :             values[i++] = CStringGetTextDatum("physical");
     285             :         else
     286         650 :             values[i++] = CStringGetTextDatum("logical");
     287             : 
     288         910 :         if (slot_contents.data.database == InvalidOid)
     289         260 :             nulls[i++] = true;
     290             :         else
     291         650 :             values[i++] = ObjectIdGetDatum(slot_contents.data.database);
     292             : 
     293         910 :         values[i++] = BoolGetDatum(slot_contents.data.persistency == RS_TEMPORARY);
     294         910 :         values[i++] = BoolGetDatum(slot_contents.active_pid != 0);
     295             : 
     296         910 :         if (slot_contents.active_pid != 0)
     297         282 :             values[i++] = Int32GetDatum(slot_contents.active_pid);
     298             :         else
     299         628 :             nulls[i++] = true;
     300             : 
     301         910 :         if (slot_contents.data.xmin != InvalidTransactionId)
     302         122 :             values[i++] = TransactionIdGetDatum(slot_contents.data.xmin);
     303             :         else
     304         788 :             nulls[i++] = true;
     305             : 
     306         910 :         if (slot_contents.data.catalog_xmin != InvalidTransactionId)
     307         712 :             values[i++] = TransactionIdGetDatum(slot_contents.data.catalog_xmin);
     308             :         else
     309         198 :             nulls[i++] = true;
     310             : 
     311         910 :         if (slot_contents.data.restart_lsn != InvalidXLogRecPtr)
     312         876 :             values[i++] = LSNGetDatum(slot_contents.data.restart_lsn);
     313             :         else
     314          34 :             nulls[i++] = true;
     315             : 
     316         910 :         if (slot_contents.data.confirmed_flush != InvalidXLogRecPtr)
     317         604 :             values[i++] = LSNGetDatum(slot_contents.data.confirmed_flush);
     318             :         else
     319         306 :             nulls[i++] = true;
     320             : 
     321             :         /*
     322             :          * If the slot has not been invalidated, test availability from
     323             :          * restart_lsn.
     324             :          */
     325         910 :         if (slot_contents.data.invalidated != RS_INVAL_NONE)
     326          62 :             walstate = WALAVAIL_REMOVED;
     327             :         else
     328         848 :             walstate = GetWALAvailability(slot_contents.data.restart_lsn);
     329             : 
     330         910 :         switch (walstate)
     331             :         {
     332          28 :             case WALAVAIL_INVALID_LSN:
     333          28 :                 nulls[i++] = true;
     334          28 :                 break;
     335             : 
     336         814 :             case WALAVAIL_RESERVED:
     337         814 :                 values[i++] = CStringGetTextDatum("reserved");
     338         814 :                 break;
     339             : 
     340           4 :             case WALAVAIL_EXTENDED:
     341           4 :                 values[i++] = CStringGetTextDatum("extended");
     342           4 :                 break;
     343             : 
     344           2 :             case WALAVAIL_UNRESERVED:
     345           2 :                 values[i++] = CStringGetTextDatum("unreserved");
     346           2 :                 break;
     347             : 
     348          62 :             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          62 :                 if (!XLogRecPtrIsInvalid(slot_contents.data.restart_lsn))
     361             :                 {
     362             :                     int         pid;
     363             : 
     364          56 :                     SpinLockAcquire(&slot->mutex);
     365          56 :                     pid = slot->active_pid;
     366          56 :                     slot_contents.data.restart_lsn = slot->data.restart_lsn;
     367          56 :                     SpinLockRelease(&slot->mutex);
     368          56 :                     if (pid != 0)
     369             :                     {
     370           0 :                         values[i++] = CStringGetTextDatum("unreserved");
     371           0 :                         walstate = WALAVAIL_UNRESERVED;
     372           0 :                         break;
     373             :                     }
     374             :                 }
     375          62 :                 values[i++] = CStringGetTextDatum("lost");
     376          62 :                 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         910 :         if (walstate == WALAVAIL_REMOVED || max_slot_wal_keep_size_mb < 0)
     384         900 :             nulls[i++] = true;
     385             :         else
     386             :         {
     387             :             XLogSegNo   targetSeg;
     388             :             uint64      slotKeepSegs;
     389             :             uint64      keepSegs;
     390             :             XLogSegNo   failSeg;
     391             :             XLogRecPtr  failLSN;
     392             : 
     393          10 :             XLByteToSeg(slot_contents.data.restart_lsn, targetSeg, wal_segment_size);
     394             : 
     395             :             /* determine how many segments can be kept by slots */
     396          10 :             slotKeepSegs = XLogMBVarToSegs(max_slot_wal_keep_size_mb, wal_segment_size);
     397             :             /* ditto for wal_keep_size */
     398          10 :             keepSegs = XLogMBVarToSegs(wal_keep_size_mb, wal_segment_size);
     399             : 
     400             :             /* if currpos reaches failLSN, we lose our segment */
     401          10 :             failSeg = targetSeg + Max(slotKeepSegs, keepSegs) + 1;
     402          10 :             XLogSegNoOffsetToRecPtr(failSeg, 0, wal_segment_size, failLSN);
     403             : 
     404          10 :             values[i++] = Int64GetDatum(failLSN - currlsn);
     405             :         }
     406             : 
     407         910 :         values[i++] = BoolGetDatum(slot_contents.data.two_phase);
     408             : 
     409         910 :         if (slot_contents.inactive_since > 0)
     410         654 :             values[i++] = TimestampTzGetDatum(slot_contents.inactive_since);
     411             :         else
     412         256 :             nulls[i++] = true;
     413             : 
     414         910 :         cause = slot_contents.data.invalidated;
     415             : 
     416         910 :         if (SlotIsPhysical(&slot_contents))
     417         260 :             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         650 :             if (cause == RS_INVAL_HORIZON ||
     425             :                 cause == RS_INVAL_WAL_LEVEL)
     426          56 :                 values[i++] = BoolGetDatum(true);
     427             :             else
     428         594 :                 values[i++] = BoolGetDatum(false);
     429             :         }
     430             : 
     431         910 :         if (cause == RS_INVAL_NONE)
     432         848 :             nulls[i++] = true;
     433             :         else
     434          62 :             values[i++] = CStringGetTextDatum(SlotInvalidationCauses[cause]);
     435             : 
     436         910 :         values[i++] = BoolGetDatum(slot_contents.data.failover);
     437             : 
     438         910 :         values[i++] = BoolGetDatum(slot_contents.data.synced);
     439             : 
     440             :         Assert(i == PG_GET_REPLICATION_SLOTS_COLS);
     441             : 
     442         910 :         tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
     443             :                              values, nulls);
     444             :     }
     445             : 
     446         540 :     LWLockRelease(ReplicationSlotControlLock);
     447             : 
     448         540 :     return (Datum) 0;
     449             : }
     450             : 
     451             : /*
     452             :  * Helper function for advancing our physical replication slot forward.
     453             :  *
     454             :  * The LSN position to move to is compared simply to the slot's restart_lsn,
     455             :  * knowing that any position older than that would be removed by successive
     456             :  * checkpoints.
     457             :  */
     458             : static XLogRecPtr
     459           2 : pg_physical_replication_slot_advance(XLogRecPtr moveto)
     460             : {
     461           2 :     XLogRecPtr  startlsn = MyReplicationSlot->data.restart_lsn;
     462           2 :     XLogRecPtr  retlsn = startlsn;
     463             : 
     464             :     Assert(moveto != InvalidXLogRecPtr);
     465             : 
     466           2 :     if (startlsn < moveto)
     467             :     {
     468           2 :         SpinLockAcquire(&MyReplicationSlot->mutex);
     469           2 :         MyReplicationSlot->data.restart_lsn = moveto;
     470           2 :         SpinLockRelease(&MyReplicationSlot->mutex);
     471           2 :         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             :          */
     478           2 :         ReplicationSlotMarkDirty();
     479             : 
     480             :         /*
     481             :          * Wake up logical walsenders holding logical failover slots after
     482             :          * updating the restart_lsn of the physical slot.
     483             :          */
     484           2 :         PhysicalWakeupLogicalWalSnd();
     485             :     }
     486             : 
     487           2 :     return retlsn;
     488             : }
     489             : 
     490             : /*
     491             :  * Advance our logical replication slot forward. See
     492             :  * LogicalSlotAdvanceAndCheckSnapState for details.
     493             :  */
     494             : static XLogRecPtr
     495          10 : pg_logical_replication_slot_advance(XLogRecPtr moveto)
     496             : {
     497          10 :     return LogicalSlotAdvanceAndCheckSnapState(moveto, NULL);
     498             : }
     499             : 
     500             : /*
     501             :  * SQL function for moving the position in a replication slot.
     502             :  */
     503             : Datum
     504          16 : pg_replication_slot_advance(PG_FUNCTION_ARGS)
     505             : {
     506          16 :     Name        slotname = PG_GETARG_NAME(0);
     507          16 :     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             : 
     516             :     Assert(!MyReplicationSlot);
     517             : 
     518          16 :     CheckSlotPermissions();
     519             : 
     520          16 :     if (XLogRecPtrIsInvalid(moveto))
     521           2 :         ereport(ERROR,
     522             :                 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
     523             :                  errmsg("invalid target WAL LSN")));
     524             : 
     525             :     /* Build a tuple descriptor for our result type */
     526          14 :     if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
     527           0 :         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          14 :     if (!RecoveryInProgress())
     534          14 :         moveto = Min(moveto, GetFlushRecPtr(NULL));
     535             :     else
     536           0 :         moveto = Min(moveto, GetXLogReplayRecPtr(NULL));
     537             : 
     538             :     /* Acquire the slot so we "own" it */
     539          14 :     ReplicationSlotAcquire(NameStr(*slotname), true);
     540             : 
     541             :     /* A slot whose restart_lsn has never been reserved cannot be advanced */
     542          14 :     if (XLogRecPtrIsInvalid(MyReplicationSlot->data.restart_lsn))
     543           2 :         ereport(ERROR,
     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             :      */
     555          12 :     if (OidIsValid(MyReplicationSlot->data.database))
     556          10 :         minlsn = MyReplicationSlot->data.confirmed_flush;
     557             :     else
     558           2 :         minlsn = MyReplicationSlot->data.restart_lsn;
     559             : 
     560          12 :     if (moveto < minlsn)
     561           0 :         ereport(ERROR,
     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 */
     567          12 :     if (OidIsValid(MyReplicationSlot->data.database))
     568          10 :         endlsn = pg_logical_replication_slot_advance(moveto);
     569             :     else
     570           2 :         endlsn = pg_physical_replication_slot_advance(moveto);
     571             : 
     572          12 :     values[0] = NameGetDatum(&MyReplicationSlot->data.name);
     573          12 :     nulls[0] = false;
     574             : 
     575             :     /*
     576             :      * Recompute the minimum LSN and xmin across all slots to adjust with the
     577             :      * advancing potentially done.
     578             :      */
     579          12 :     ReplicationSlotsComputeRequiredXmin(false);
     580          12 :     ReplicationSlotsComputeRequiredLSN();
     581             : 
     582          12 :     ReplicationSlotRelease();
     583             : 
     584             :     /* Return the reached position. */
     585          12 :     values[1] = LSNGetDatum(endlsn);
     586          12 :     nulls[1] = false;
     587             : 
     588          12 :     tuple = heap_form_tuple(tupdesc, values, nulls);
     589          12 :     result = HeapTupleGetDatum(tuple);
     590             : 
     591          12 :     PG_RETURN_DATUM(result);
     592             : }
     593             : 
     594             : /*
     595             :  * Helper function of copying a replication slot.
     596             :  */
     597             : static Datum
     598          28 : copy_replication_slot(FunctionCallInfo fcinfo, bool logical_slot)
     599             : {
     600          28 :     Name        src_name = PG_GETARG_NAME(0);
     601          28 :     Name        dst_name = PG_GETARG_NAME(1);
     602          28 :     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          28 :     if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
     616           0 :         elog(ERROR, "return type must be a row type");
     617             : 
     618          28 :     CheckSlotPermissions();
     619             : 
     620          28 :     if (logical_slot)
     621          16 :         CheckLogicalDecodingRequirements();
     622             :     else
     623          12 :         CheckSlotRequirements();
     624             : 
     625          28 :     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          30 :     for (int i = 0; i < max_replication_slots; i++)
     639             :     {
     640          30 :         ReplicationSlot *s = &ReplicationSlotCtl->replication_slots[i];
     641             : 
     642          30 :         if (s->in_use && strcmp(NameStr(s->data.name), NameStr(*src_name)) == 0)
     643             :         {
     644             :             /* Copy the slot contents while holding spinlock */
     645          28 :             SpinLockAcquire(&s->mutex);
     646          28 :             first_slot_contents = *s;
     647          28 :             SpinLockRelease(&s->mutex);
     648          28 :             src = s;
     649          28 :             break;
     650             :         }
     651             :     }
     652             : 
     653          28 :     LWLockRelease(ReplicationSlotControlLock);
     654             : 
     655          28 :     if (src == NULL)
     656           0 :         ereport(ERROR,
     657             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
     658             :                  errmsg("replication slot \"%s\" does not exist", NameStr(*src_name))));
     659             : 
     660          28 :     src_islogical = SlotIsLogical(&first_slot_contents);
     661          28 :     src_restart_lsn = first_slot_contents.data.restart_lsn;
     662          28 :     temporary = (first_slot_contents.data.persistency == RS_TEMPORARY);
     663          28 :     plugin = logical_slot ? NameStr(first_slot_contents.data.plugin) : NULL;
     664             : 
     665             :     /* Check type of replication slot */
     666          28 :     if (src_islogical != logical_slot)
     667           4 :         ereport(ERROR,
     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          24 :     if (XLogRecPtrIsInvalid(src_restart_lsn))
     677           2 :         ereport(ERROR,
     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          22 :     if (PG_NARGS() >= 3)
     683          12 :         temporary = PG_GETARG_BOOL(2);
     684          22 :     if (PG_NARGS() >= 4)
     685             :     {
     686             :         Assert(logical_slot);
     687           8 :         plugin = NameStr(*(PG_GETARG_NAME(3)));
     688             :     }
     689             : 
     690             :     /* Create new slot and acquire it */
     691          22 :     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             :          */
     706          14 :         create_logical_replication_slot(NameStr(*dst_name),
     707             :                                         plugin,
     708             :                                         temporary,
     709             :                                         false,
     710             :                                         false,
     711             :                                         src_restart_lsn,
     712             :                                         false);
     713             :     }
     714             :     else
     715           8 :         create_physical_replication_slot(NameStr(*dst_name),
     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          20 :         SpinLockAcquire(&src->mutex);
     736          20 :         second_slot_contents = *src;
     737          20 :         SpinLockRelease(&src->mutex);
     738             : 
     739          20 :         copy_effective_xmin = second_slot_contents.effective_xmin;
     740          20 :         copy_effective_catalog_xmin = second_slot_contents.effective_catalog_xmin;
     741             : 
     742          20 :         copy_xmin = second_slot_contents.data.xmin;
     743          20 :         copy_catalog_xmin = second_slot_contents.data.catalog_xmin;
     744          20 :         copy_restart_lsn = second_slot_contents.data.restart_lsn;
     745          20 :         copy_confirmed_flush = second_slot_contents.data.confirmed_flush;
     746             : 
     747             :         /* for existence check */
     748          20 :         copy_name = NameStr(second_slot_contents.data.name);
     749          20 :         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          20 :         if (copy_restart_lsn < src_restart_lsn ||
     762          20 :             src_islogical != copy_islogical ||
     763          20 :             strcmp(copy_name, NameStr(*src_name)) != 0)
     764           0 :             ereport(ERROR,
     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          20 :         if (src_islogical && XLogRecPtrIsInvalid(copy_confirmed_flush))
     771           0 :             ereport(ERROR,
     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 */
     778          20 :         SpinLockAcquire(&MyReplicationSlot->mutex);
     779          20 :         MyReplicationSlot->effective_xmin = copy_effective_xmin;
     780          20 :         MyReplicationSlot->effective_catalog_xmin = copy_effective_catalog_xmin;
     781             : 
     782          20 :         MyReplicationSlot->data.xmin = copy_xmin;
     783          20 :         MyReplicationSlot->data.catalog_xmin = copy_catalog_xmin;
     784          20 :         MyReplicationSlot->data.restart_lsn = copy_restart_lsn;
     785          20 :         MyReplicationSlot->data.confirmed_flush = copy_confirmed_flush;
     786          20 :         SpinLockRelease(&MyReplicationSlot->mutex);
     787             : 
     788          20 :         ReplicationSlotMarkDirty();
     789          20 :         ReplicationSlotsComputeRequiredXmin(false);
     790          20 :         ReplicationSlotsComputeRequiredLSN();
     791          20 :         ReplicationSlotSave();
     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);
     799             :             Assert(XLogGetLastRemovedSegno() < segno);
     800             :         }
     801             : #endif
     802             :     }
     803             : 
     804             :     /* target slot fully created, mark as persistent if needed */
     805          20 :     if (logical_slot && !temporary)
     806           6 :         ReplicationSlotPersist();
     807             : 
     808             :     /* All done.  Set up the return values */
     809          20 :     values[0] = NameGetDatum(dst_name);
     810          20 :     nulls[0] = false;
     811          20 :     if (!XLogRecPtrIsInvalid(MyReplicationSlot->data.confirmed_flush))
     812             :     {
     813          12 :         values[1] = LSNGetDatum(MyReplicationSlot->data.confirmed_flush);
     814          12 :         nulls[1] = false;
     815             :     }
     816             :     else
     817           8 :         nulls[1] = true;
     818             : 
     819          20 :     tuple = heap_form_tuple(tupdesc, values, nulls);
     820          20 :     result = HeapTupleGetDatum(tuple);
     821             : 
     822          20 :     ReplicationSlotRelease();
     823             : 
     824          20 :     PG_RETURN_DATUM(result);
     825             : }
     826             : 
     827             : /* The wrappers below are all to appease opr_sanity */
     828             : Datum
     829           8 : pg_copy_logical_replication_slot_a(PG_FUNCTION_ARGS)
     830             : {
     831           8 :     return copy_replication_slot(fcinfo, true);
     832             : }
     833             : 
     834             : Datum
     835           0 : pg_copy_logical_replication_slot_b(PG_FUNCTION_ARGS)
     836             : {
     837           0 :     return copy_replication_slot(fcinfo, true);
     838             : }
     839             : 
     840             : Datum
     841           8 : pg_copy_logical_replication_slot_c(PG_FUNCTION_ARGS)
     842             : {
     843           8 :     return copy_replication_slot(fcinfo, true);
     844             : }
     845             : 
     846             : Datum
     847           4 : pg_copy_physical_replication_slot_a(PG_FUNCTION_ARGS)
     848             : {
     849           4 :     return copy_replication_slot(fcinfo, false);
     850             : }
     851             : 
     852             : Datum
     853           8 : pg_copy_physical_replication_slot_b(PG_FUNCTION_ARGS)
     854             : {
     855           8 :     return copy_replication_slot(fcinfo, false);
     856             : }
     857             : 
     858             : /*
     859             :  * Synchronize failover enabled replication slots to a standby server
     860             :  * from the primary server.
     861             :  */
     862             : Datum
     863          22 : pg_sync_replication_slots(PG_FUNCTION_ARGS)
     864             : {
     865             :     WalReceiverConn *wrconn;
     866             :     char       *err;
     867             :     StringInfoData app_name;
     868             : 
     869          22 :     CheckSlotPermissions();
     870             : 
     871          20 :     if (!RecoveryInProgress())
     872           2 :         ereport(ERROR,
     873             :                 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     874             :                 errmsg("replication slots can only be synchronized to a standby server"));
     875             : 
     876          18 :     ValidateSlotSyncParams(ERROR);
     877             : 
     878             :     /* Load the libpq-specific functions */
     879          18 :     load_file("libpqwalreceiver", false);
     880             : 
     881          18 :     (void) CheckAndGetDbnameFromConninfo();
     882             : 
     883          16 :     initStringInfo(&app_name);
     884          16 :     if (cluster_name[0])
     885          16 :         appendStringInfo(&app_name, "%s_slotsync", cluster_name);
     886             :     else
     887           0 :         appendStringInfoString(&app_name, "slotsync");
     888             : 
     889             :     /* Connect to the primary server. */
     890          16 :     wrconn = walrcv_connect(PrimaryConnInfo, false, false, false,
     891             :                             app_name.data, &err);
     892          16 :     pfree(app_name.data);
     893             : 
     894          16 :     if (!wrconn)
     895           0 :         ereport(ERROR,
     896             :                 errcode(ERRCODE_CONNECTION_FAILURE),
     897             :                 errmsg("synchronization worker \"%s\" could not connect to the primary server: %s",
     898             :                        app_name.data, err));
     899             : 
     900          16 :     SyncReplicationSlots(wrconn);
     901             : 
     902          14 :     walrcv_disconnect(wrconn);
     903             : 
     904          14 :     PG_RETURN_VOID();
     905             : }

Generated by: LCOV version 1.14