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

Generated by: LCOV version 1.14