LCOV - code coverage report
Current view: top level - src/backend/replication - slotfuncs.c (source / functions) Hit Total Coverage
Test: PostgreSQL 13beta1 Lines: 288 306 94.1 %
Date: 2020-06-03 09:06:53 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-2020, 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/xlogutils.h"
      18             : #include "funcapi.h"
      19             : #include "miscadmin.h"
      20             : #include "replication/decode.h"
      21             : #include "replication/logical.h"
      22             : #include "replication/slot.h"
      23             : #include "utils/builtins.h"
      24             : #include "utils/inval.h"
      25             : #include "utils/pg_lsn.h"
      26             : #include "utils/resowner.h"
      27             : 
      28             : static void
      29         358 : check_permissions(void)
      30             : {
      31         358 :     if (!superuser() && !has_rolreplication(GetUserId()))
      32           6 :         ereport(ERROR,
      33             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
      34             :                  errmsg("must be superuser or replication role to use replication slots")));
      35         352 : }
      36             : 
      37             : /*
      38             :  * Helper function for creating a new physical replication slot with
      39             :  * given arguments. Note that this function doesn't release the created
      40             :  * slot.
      41             :  *
      42             :  * If restart_lsn is a valid value, we use it without WAL reservation
      43             :  * routine. So the caller must guarantee that WAL is available.
      44             :  */
      45             : static void
      46          32 : create_physical_replication_slot(char *name, bool immediately_reserve,
      47             :                                  bool temporary, XLogRecPtr restart_lsn)
      48             : {
      49             :     Assert(!MyReplicationSlot);
      50             : 
      51             :     /* acquire replication slot, this will check for conflicting names */
      52          32 :     ReplicationSlotCreate(name, false,
      53             :                           temporary ? RS_TEMPORARY : RS_PERSISTENT);
      54             : 
      55          32 :     if (immediately_reserve)
      56             :     {
      57             :         /* Reserve WAL as the user asked for it */
      58          14 :         if (XLogRecPtrIsInvalid(restart_lsn))
      59           6 :             ReplicationSlotReserveWal();
      60             :         else
      61           8 :             MyReplicationSlot->data.restart_lsn = restart_lsn;
      62             : 
      63             :         /* Write this slot to disk */
      64          14 :         ReplicationSlotMarkDirty();
      65          14 :         ReplicationSlotSave();
      66             :     }
      67          32 : }
      68             : 
      69             : /*
      70             :  * SQL function for creating a new physical (streaming replication)
      71             :  * replication slot.
      72             :  */
      73             : Datum
      74          24 : pg_create_physical_replication_slot(PG_FUNCTION_ARGS)
      75             : {
      76          24 :     Name        name = PG_GETARG_NAME(0);
      77          24 :     bool        immediately_reserve = PG_GETARG_BOOL(1);
      78          24 :     bool        temporary = PG_GETARG_BOOL(2);
      79             :     Datum       values[2];
      80             :     bool        nulls[2];
      81             :     TupleDesc   tupdesc;
      82             :     HeapTuple   tuple;
      83             :     Datum       result;
      84             : 
      85          24 :     if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
      86           0 :         elog(ERROR, "return type must be a row type");
      87             : 
      88          24 :     check_permissions();
      89             : 
      90          24 :     CheckSlotRequirements();
      91             : 
      92          24 :     create_physical_replication_slot(NameStr(*name),
      93             :                                      immediately_reserve,
      94             :                                      temporary,
      95             :                                      InvalidXLogRecPtr);
      96             : 
      97          24 :     values[0] = NameGetDatum(&MyReplicationSlot->data.name);
      98          24 :     nulls[0] = false;
      99             : 
     100          24 :     if (immediately_reserve)
     101             :     {
     102           6 :         values[1] = LSNGetDatum(MyReplicationSlot->data.restart_lsn);
     103           6 :         nulls[1] = false;
     104             :     }
     105             :     else
     106          18 :         nulls[1] = true;
     107             : 
     108          24 :     tuple = heap_form_tuple(tupdesc, values, nulls);
     109          24 :     result = HeapTupleGetDatum(tuple);
     110             : 
     111          24 :     ReplicationSlotRelease();
     112             : 
     113          24 :     PG_RETURN_DATUM(result);
     114             : }
     115             : 
     116             : 
     117             : /*
     118             :  * Helper function for creating a new logical replication slot with
     119             :  * given arguments. Note that this function doesn't release the created
     120             :  * slot.
     121             :  *
     122             :  * When find_startpoint is false, the slot's confirmed_flush is not set; it's
     123             :  * caller's responsibility to ensure it's set to something sensible.
     124             :  */
     125             : static void
     126         160 : create_logical_replication_slot(char *name, char *plugin,
     127             :                                 bool temporary, XLogRecPtr restart_lsn,
     128             :                                 bool find_startpoint)
     129             : {
     130         160 :     LogicalDecodingContext *ctx = NULL;
     131             : 
     132             :     Assert(!MyReplicationSlot);
     133             : 
     134             :     /*
     135             :      * Acquire a logical decoding slot, this will check for conflicting names.
     136             :      * Initially create persistent slot as ephemeral - that allows us to
     137             :      * nicely handle errors during initialization because it'll get dropped if
     138             :      * this transaction fails. We'll make it persistent at the end. Temporary
     139             :      * slots can be created as temporary from beginning as they get dropped on
     140             :      * error as well.
     141             :      */
     142         160 :     ReplicationSlotCreate(name, true,
     143             :                           temporary ? RS_TEMPORARY : RS_EPHEMERAL);
     144             : 
     145             :     /*
     146             :      * Create logical decoding context to find start point or, if we don't
     147             :      * need it, to 1) bump slot's restart_lsn and xmin 2) check plugin sanity.
     148             :      *
     149             :      * Note: when !find_startpoint this is still important, because it's at
     150             :      * this point that the output plugin is validated.
     151             :      */
     152         152 :     ctx = CreateInitDecodingContext(plugin, NIL,
     153             :                                     false,  /* just catalogs is OK */
     154             :                                     restart_lsn,
     155         152 :                                     XL_ROUTINE(.page_read = read_local_xlog_page,
     156             :                                                .segment_open = wal_segment_open,
     157             :                                                .segment_close = wal_segment_close),
     158             :                                     NULL, NULL, NULL);
     159             : 
     160             :     /*
     161             :      * If caller needs us to determine the decoding start point, do so now.
     162             :      * This might take a while.
     163             :      */
     164         146 :     if (find_startpoint)
     165         134 :         DecodingContextFindStartpoint(ctx);
     166             : 
     167             :     /* don't need the decoding context anymore */
     168         146 :     FreeDecodingContext(ctx);
     169         146 : }
     170             : 
     171             : /*
     172             :  * SQL function for creating a new logical replication slot.
     173             :  */
     174             : Datum
     175         148 : pg_create_logical_replication_slot(PG_FUNCTION_ARGS)
     176             : {
     177         148 :     Name        name = PG_GETARG_NAME(0);
     178         148 :     Name        plugin = PG_GETARG_NAME(1);
     179         148 :     bool        temporary = PG_GETARG_BOOL(2);
     180             :     Datum       result;
     181             :     TupleDesc   tupdesc;
     182             :     HeapTuple   tuple;
     183             :     Datum       values[2];
     184             :     bool        nulls[2];
     185             : 
     186         148 :     if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
     187           0 :         elog(ERROR, "return type must be a row type");
     188             : 
     189         148 :     check_permissions();
     190             : 
     191         146 :     CheckLogicalDecodingRequirements();
     192             : 
     193         292 :     create_logical_replication_slot(NameStr(*name),
     194         146 :                                     NameStr(*plugin),
     195             :                                     temporary,
     196             :                                     InvalidXLogRecPtr,
     197             :                                     true);
     198             : 
     199         134 :     values[0] = NameGetDatum(&MyReplicationSlot->data.name);
     200         134 :     values[1] = LSNGetDatum(MyReplicationSlot->data.confirmed_flush);
     201             : 
     202         134 :     memset(nulls, 0, sizeof(nulls));
     203             : 
     204         134 :     tuple = heap_form_tuple(tupdesc, values, nulls);
     205         134 :     result = HeapTupleGetDatum(tuple);
     206             : 
     207             :     /* ok, slot is now fully created, mark it as persistent if needed */
     208         134 :     if (!temporary)
     209         124 :         ReplicationSlotPersist();
     210         134 :     ReplicationSlotRelease();
     211             : 
     212         134 :     PG_RETURN_DATUM(result);
     213             : }
     214             : 
     215             : 
     216             : /*
     217             :  * SQL function for dropping a replication slot.
     218             :  */
     219             : Datum
     220         146 : pg_drop_replication_slot(PG_FUNCTION_ARGS)
     221             : {
     222         146 :     Name        name = PG_GETARG_NAME(0);
     223             : 
     224         146 :     check_permissions();
     225             : 
     226         142 :     CheckSlotRequirements();
     227             : 
     228         142 :     ReplicationSlotDrop(NameStr(*name), true);
     229             : 
     230         132 :     PG_RETURN_VOID();
     231             : }
     232             : 
     233             : /*
     234             :  * pg_get_replication_slots - SQL SRF showing active replication slots.
     235             :  */
     236             : Datum
     237         122 : pg_get_replication_slots(PG_FUNCTION_ARGS)
     238             : {
     239             : #define PG_GET_REPLICATION_SLOTS_COLS 13
     240         122 :     ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
     241             :     TupleDesc   tupdesc;
     242             :     Tuplestorestate *tupstore;
     243             :     MemoryContext per_query_ctx;
     244             :     MemoryContext oldcontext;
     245             :     int         slotno;
     246             : 
     247             :     /* check to see if caller supports us returning a tuplestore */
     248         122 :     if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
     249           0 :         ereport(ERROR,
     250             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     251             :                  errmsg("set-valued function called in context that cannot accept a set")));
     252         122 :     if (!(rsinfo->allowedModes & SFRM_Materialize))
     253           0 :         ereport(ERROR,
     254             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     255             :                  errmsg("materialize mode required, but it is not allowed in this context")));
     256             : 
     257             :     /* Build a tuple descriptor for our result type */
     258         122 :     if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
     259           0 :         elog(ERROR, "return type must be a row type");
     260             : 
     261             :     /*
     262             :      * We don't require any special permission to see this function's data
     263             :      * because nothing should be sensitive. The most critical being the slot
     264             :      * name, which shouldn't contain anything particularly sensitive.
     265             :      */
     266             : 
     267         122 :     per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
     268         122 :     oldcontext = MemoryContextSwitchTo(per_query_ctx);
     269             : 
     270         122 :     tupstore = tuplestore_begin_heap(true, false, work_mem);
     271         122 :     rsinfo->returnMode = SFRM_Materialize;
     272         122 :     rsinfo->setResult = tupstore;
     273         122 :     rsinfo->setDesc = tupdesc;
     274             : 
     275         122 :     MemoryContextSwitchTo(oldcontext);
     276             : 
     277         122 :     LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
     278         692 :     for (slotno = 0; slotno < max_replication_slots; slotno++)
     279             :     {
     280         570 :         ReplicationSlot *slot = &ReplicationSlotCtl->replication_slots[slotno];
     281             :         Datum       values[PG_GET_REPLICATION_SLOTS_COLS];
     282             :         bool        nulls[PG_GET_REPLICATION_SLOTS_COLS];
     283             : 
     284             :         ReplicationSlotPersistency persistency;
     285             :         TransactionId xmin;
     286             :         TransactionId catalog_xmin;
     287             :         XLogRecPtr  restart_lsn;
     288             :         XLogRecPtr  confirmed_flush_lsn;
     289             :         pid_t       active_pid;
     290             :         Oid         database;
     291             :         NameData    slot_name;
     292             :         NameData    plugin;
     293             :         WALAvailability walstate;
     294             :         XLogSegNo   last_removed_seg;
     295             :         int         i;
     296             : 
     297         570 :         if (!slot->in_use)
     298         392 :             continue;
     299             : 
     300         178 :         SpinLockAcquire(&slot->mutex);
     301             : 
     302         178 :         xmin = slot->data.xmin;
     303         178 :         catalog_xmin = slot->data.catalog_xmin;
     304         178 :         database = slot->data.database;
     305         178 :         restart_lsn = slot->data.restart_lsn;
     306         178 :         confirmed_flush_lsn = slot->data.confirmed_flush;
     307         178 :         namecpy(&slot_name, &slot->data.name);
     308         178 :         namecpy(&plugin, &slot->data.plugin);
     309         178 :         active_pid = slot->active_pid;
     310         178 :         persistency = slot->data.persistency;
     311             : 
     312         178 :         SpinLockRelease(&slot->mutex);
     313             : 
     314         178 :         memset(nulls, 0, sizeof(nulls));
     315             : 
     316         178 :         i = 0;
     317         178 :         values[i++] = NameGetDatum(&slot_name);
     318             : 
     319         178 :         if (database == InvalidOid)
     320          98 :             nulls[i++] = true;
     321             :         else
     322          80 :             values[i++] = NameGetDatum(&plugin);
     323             : 
     324         178 :         if (database == InvalidOid)
     325          98 :             values[i++] = CStringGetTextDatum("physical");
     326             :         else
     327          80 :             values[i++] = CStringGetTextDatum("logical");
     328             : 
     329         178 :         if (database == InvalidOid)
     330          98 :             nulls[i++] = true;
     331             :         else
     332          80 :             values[i++] = database;
     333             : 
     334         178 :         values[i++] = BoolGetDatum(persistency == RS_TEMPORARY);
     335         178 :         values[i++] = BoolGetDatum(active_pid != 0);
     336             : 
     337         178 :         if (active_pid != 0)
     338          68 :             values[i++] = Int32GetDatum(active_pid);
     339             :         else
     340         110 :             nulls[i++] = true;
     341             : 
     342         178 :         if (xmin != InvalidTransactionId)
     343          24 :             values[i++] = TransactionIdGetDatum(xmin);
     344             :         else
     345         154 :             nulls[i++] = true;
     346             : 
     347         178 :         if (catalog_xmin != InvalidTransactionId)
     348          86 :             values[i++] = TransactionIdGetDatum(catalog_xmin);
     349             :         else
     350          92 :             nulls[i++] = true;
     351             : 
     352         178 :         if (restart_lsn != InvalidXLogRecPtr)
     353         168 :             values[i++] = LSNGetDatum(restart_lsn);
     354             :         else
     355          10 :             nulls[i++] = true;
     356             : 
     357         178 :         if (confirmed_flush_lsn != InvalidXLogRecPtr)
     358          80 :             values[i++] = LSNGetDatum(confirmed_flush_lsn);
     359             :         else
     360          98 :             nulls[i++] = true;
     361             : 
     362         178 :         walstate = GetWALAvailability(restart_lsn);
     363             : 
     364         178 :         switch (walstate)
     365             :         {
     366          10 :             case WALAVAIL_INVALID_LSN:
     367          10 :                 nulls[i++] = true;
     368          10 :                 break;
     369             : 
     370         164 :             case WALAVAIL_NORMAL:
     371         164 :                 values[i++] = CStringGetTextDatum("normal");
     372         164 :                 break;
     373             : 
     374           2 :             case WALAVAIL_RESERVED:
     375           2 :                 values[i++] = CStringGetTextDatum("reserved");
     376           2 :                 break;
     377             : 
     378           2 :             case WALAVAIL_REMOVED:
     379           2 :                 values[i++] = CStringGetTextDatum("lost");
     380           2 :                 break;
     381             :         }
     382             : 
     383         178 :         if (max_slot_wal_keep_size_mb >= 0 &&
     384          14 :             (walstate == WALAVAIL_NORMAL || walstate == WALAVAIL_RESERVED) &&
     385           8 :             ((last_removed_seg = XLogGetLastRemovedSegno()) != 0))
     386           8 :         {
     387             :             XLogRecPtr  min_safe_lsn;
     388             : 
     389           8 :             XLogSegNoOffsetToRecPtr(last_removed_seg + 1, 0,
     390             :                                     wal_segment_size, min_safe_lsn);
     391           8 :             values[i++] = Int64GetDatum(min_safe_lsn);
     392             :         }
     393             :         else
     394         170 :             nulls[i++] = true;
     395             : 
     396         178 :         tuplestore_putvalues(tupstore, tupdesc, values, nulls);
     397             :     }
     398         122 :     LWLockRelease(ReplicationSlotControlLock);
     399             : 
     400             :     tuplestore_donestoring(tupstore);
     401             : 
     402         122 :     return (Datum) 0;
     403             : }
     404             : 
     405             : /*
     406             :  * Helper function for advancing our physical replication slot forward.
     407             :  *
     408             :  * The LSN position to move to is compared simply to the slot's restart_lsn,
     409             :  * knowing that any position older than that would be removed by successive
     410             :  * checkpoints.
     411             :  */
     412             : static XLogRecPtr
     413           2 : pg_physical_replication_slot_advance(XLogRecPtr moveto)
     414             : {
     415           2 :     XLogRecPtr  startlsn = MyReplicationSlot->data.restart_lsn;
     416           2 :     XLogRecPtr  retlsn = startlsn;
     417             : 
     418             :     Assert(moveto != InvalidXLogRecPtr);
     419             : 
     420           2 :     if (startlsn < moveto)
     421             :     {
     422           2 :         SpinLockAcquire(&MyReplicationSlot->mutex);
     423           2 :         MyReplicationSlot->data.restart_lsn = moveto;
     424           2 :         SpinLockRelease(&MyReplicationSlot->mutex);
     425           2 :         retlsn = moveto;
     426             : 
     427             :         /*
     428             :          * Dirty the slot so as it is written out at the next checkpoint. Note
     429             :          * that the LSN position advanced may still be lost in the event of a
     430             :          * crash, but this makes the data consistent after a clean shutdown.
     431             :          */
     432           2 :         ReplicationSlotMarkDirty();
     433             :     }
     434             : 
     435           2 :     return retlsn;
     436             : }
     437             : 
     438             : /*
     439             :  * Helper function for advancing our logical replication slot forward.
     440             :  *
     441             :  * The slot's restart_lsn is used as start point for reading records, while
     442             :  * confirmed_flush is used as base point for the decoding context.
     443             :  *
     444             :  * We cannot just do LogicalConfirmReceivedLocation to update confirmed_flush,
     445             :  * because we need to digest WAL to advance restart_lsn allowing to recycle
     446             :  * WAL and removal of old catalog tuples.  As decoding is done in fast_forward
     447             :  * mode, no changes are generated anyway.
     448             :  */
     449             : static XLogRecPtr
     450           6 : pg_logical_replication_slot_advance(XLogRecPtr moveto)
     451             : {
     452             :     LogicalDecodingContext *ctx;
     453           6 :     ResourceOwner old_resowner = CurrentResourceOwner;
     454             :     XLogRecPtr  retlsn;
     455             : 
     456             :     Assert(moveto != InvalidXLogRecPtr);
     457             : 
     458           6 :     PG_TRY();
     459             :     {
     460             :         /*
     461             :          * Create our decoding context in fast_forward mode, passing start_lsn
     462             :          * as InvalidXLogRecPtr, so that we start processing from my slot's
     463             :          * confirmed_flush.
     464             :          */
     465          12 :         ctx = CreateDecodingContext(InvalidXLogRecPtr,
     466             :                                     NIL,
     467             :                                     true,   /* fast_forward */
     468           6 :                                     XL_ROUTINE(.page_read = read_local_xlog_page,
     469             :                                                .segment_open = wal_segment_open,
     470             :                                                .segment_close = wal_segment_close),
     471             :                                     NULL, NULL, NULL);
     472             : 
     473             :         /*
     474             :          * Start reading at the slot's restart_lsn, which we know to point to
     475             :          * a valid record.
     476             :          */
     477           6 :         XLogBeginRead(ctx->reader, MyReplicationSlot->data.restart_lsn);
     478             : 
     479             :         /* Initialize our return value in case we don't do anything */
     480           6 :         retlsn = MyReplicationSlot->data.confirmed_flush;
     481             : 
     482             :         /* invalidate non-timetravel entries */
     483           6 :         InvalidateSystemCaches();
     484             : 
     485             :         /* Decode at least one record, until we run out of records */
     486         182 :         while (ctx->reader->EndRecPtr < moveto)
     487             :         {
     488         182 :             char       *errm = NULL;
     489             :             XLogRecord *record;
     490             : 
     491             :             /*
     492             :              * Read records.  No changes are generated in fast_forward mode,
     493             :              * but snapbuilder/slot statuses are updated properly.
     494             :              */
     495         182 :             record = XLogReadRecord(ctx->reader, &errm);
     496         182 :             if (errm)
     497           0 :                 elog(ERROR, "%s", errm);
     498             : 
     499             :             /*
     500             :              * Process the record.  Storage-level changes are ignored in
     501             :              * fast_forward mode, but other modules (such as snapbuilder)
     502             :              * might still have critical updates to do.
     503             :              */
     504         182 :             if (record)
     505         182 :                 LogicalDecodingProcessRecord(ctx, ctx->reader);
     506             : 
     507             :             /* Stop once the requested target has been reached */
     508         182 :             if (moveto <= ctx->reader->EndRecPtr)
     509           6 :                 break;
     510             : 
     511         176 :             CHECK_FOR_INTERRUPTS();
     512             :         }
     513             : 
     514             :         /*
     515             :          * Logical decoding could have clobbered CurrentResourceOwner during
     516             :          * transaction management, so restore the executor's value.  (This is
     517             :          * a kluge, but it's not worth cleaning up right now.)
     518             :          */
     519           6 :         CurrentResourceOwner = old_resowner;
     520             : 
     521           6 :         if (ctx->reader->EndRecPtr != InvalidXLogRecPtr)
     522             :         {
     523           6 :             LogicalConfirmReceivedLocation(moveto);
     524             : 
     525             :             /*
     526             :              * If only the confirmed_flush LSN has changed the slot won't get
     527             :              * marked as dirty by the above. Callers on the walsender
     528             :              * interface are expected to keep track of their own progress and
     529             :              * don't need it written out. But SQL-interface users cannot
     530             :              * specify their own start positions and it's harder for them to
     531             :              * keep track of their progress, so we should make more of an
     532             :              * effort to save it for them.
     533             :              *
     534             :              * Dirty the slot so it is written out at the next checkpoint. The
     535             :              * LSN position advanced to may still be lost on a crash but this
     536             :              * makes the data consistent after a clean shutdown.
     537             :              */
     538           6 :             ReplicationSlotMarkDirty();
     539             :         }
     540             : 
     541           6 :         retlsn = MyReplicationSlot->data.confirmed_flush;
     542             : 
     543             :         /* free context, call shutdown callback */
     544           6 :         FreeDecodingContext(ctx);
     545             : 
     546           6 :         InvalidateSystemCaches();
     547             :     }
     548           0 :     PG_CATCH();
     549             :     {
     550             :         /* clear all timetravel entries */
     551           0 :         InvalidateSystemCaches();
     552             : 
     553           0 :         PG_RE_THROW();
     554             :     }
     555           6 :     PG_END_TRY();
     556             : 
     557           6 :     return retlsn;
     558             : }
     559             : 
     560             : /*
     561             :  * SQL function for moving the position in a replication slot.
     562             :  */
     563             : Datum
     564          12 : pg_replication_slot_advance(PG_FUNCTION_ARGS)
     565             : {
     566          12 :     Name        slotname = PG_GETARG_NAME(0);
     567          12 :     XLogRecPtr  moveto = PG_GETARG_LSN(1);
     568             :     XLogRecPtr  endlsn;
     569             :     XLogRecPtr  minlsn;
     570             :     TupleDesc   tupdesc;
     571             :     Datum       values[2];
     572             :     bool        nulls[2];
     573             :     HeapTuple   tuple;
     574             :     Datum       result;
     575             : 
     576             :     Assert(!MyReplicationSlot);
     577             : 
     578          12 :     check_permissions();
     579             : 
     580          12 :     if (XLogRecPtrIsInvalid(moveto))
     581           2 :         ereport(ERROR,
     582             :                 (errmsg("invalid target WAL LSN")));
     583             : 
     584             :     /* Build a tuple descriptor for our result type */
     585          10 :     if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
     586           0 :         elog(ERROR, "return type must be a row type");
     587             : 
     588             :     /*
     589             :      * We can't move slot past what's been flushed/replayed so clamp the
     590             :      * target position accordingly.
     591             :      */
     592          10 :     if (!RecoveryInProgress())
     593          10 :         moveto = Min(moveto, GetFlushRecPtr());
     594             :     else
     595           0 :         moveto = Min(moveto, GetXLogReplayRecPtr(&ThisTimeLineID));
     596             : 
     597             :     /* Acquire the slot so we "own" it */
     598          10 :     (void) ReplicationSlotAcquire(NameStr(*slotname), SAB_Error);
     599             : 
     600             :     /* A slot whose restart_lsn has never been reserved cannot be advanced */
     601          10 :     if (XLogRecPtrIsInvalid(MyReplicationSlot->data.restart_lsn))
     602           2 :         ereport(ERROR,
     603             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     604             :                  errmsg("replication slot \"%s\" cannot be advanced",
     605             :                         NameStr(*slotname)),
     606             :                  errdetail("This slot has never previously reserved WAL, or has been invalidated.")));
     607             : 
     608             :     /*
     609             :      * Check if the slot is not moving backwards.  Physical slots rely simply
     610             :      * on restart_lsn as a minimum point, while logical slots have confirmed
     611             :      * consumption up to confirmed_flush, meaning that in both cases data
     612             :      * older than that is not available anymore.
     613             :      */
     614           8 :     if (OidIsValid(MyReplicationSlot->data.database))
     615           6 :         minlsn = MyReplicationSlot->data.confirmed_flush;
     616             :     else
     617           2 :         minlsn = MyReplicationSlot->data.restart_lsn;
     618             : 
     619           8 :     if (moveto < minlsn)
     620           0 :         ereport(ERROR,
     621             :                 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     622             :                  errmsg("cannot advance replication slot to %X/%X, minimum is %X/%X",
     623             :                         (uint32) (moveto >> 32), (uint32) moveto,
     624             :                         (uint32) (minlsn >> 32), (uint32) minlsn)));
     625             : 
     626             :     /* Do the actual slot update, depending on the slot type */
     627           8 :     if (OidIsValid(MyReplicationSlot->data.database))
     628           6 :         endlsn = pg_logical_replication_slot_advance(moveto);
     629             :     else
     630           2 :         endlsn = pg_physical_replication_slot_advance(moveto);
     631             : 
     632           8 :     values[0] = NameGetDatum(&MyReplicationSlot->data.name);
     633           8 :     nulls[0] = false;
     634             : 
     635           8 :     ReplicationSlotRelease();
     636             : 
     637             :     /* Return the reached position. */
     638           8 :     values[1] = LSNGetDatum(endlsn);
     639           8 :     nulls[1] = false;
     640             : 
     641           8 :     tuple = heap_form_tuple(tupdesc, values, nulls);
     642           8 :     result = HeapTupleGetDatum(tuple);
     643             : 
     644           8 :     PG_RETURN_DATUM(result);
     645             : }
     646             : 
     647             : /*
     648             :  * Helper function of copying a replication slot.
     649             :  */
     650             : static Datum
     651          28 : copy_replication_slot(FunctionCallInfo fcinfo, bool logical_slot)
     652             : {
     653          28 :     Name        src_name = PG_GETARG_NAME(0);
     654          28 :     Name        dst_name = PG_GETARG_NAME(1);
     655          28 :     ReplicationSlot *src = NULL;
     656             :     XLogRecPtr  src_restart_lsn;
     657             :     bool        src_islogical;
     658             :     bool        temporary;
     659             :     char       *plugin;
     660             :     Datum       values[2];
     661             :     bool        nulls[2];
     662             :     Datum       result;
     663             :     TupleDesc   tupdesc;
     664             :     HeapTuple   tuple;
     665             : 
     666          28 :     if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
     667           0 :         elog(ERROR, "return type must be a row type");
     668             : 
     669          28 :     check_permissions();
     670             : 
     671          28 :     if (logical_slot)
     672          16 :         CheckLogicalDecodingRequirements();
     673             :     else
     674          12 :         CheckSlotRequirements();
     675             : 
     676          28 :     LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
     677             : 
     678             :     /*
     679             :      * We need to prevent the source slot's reserved WAL from being removed,
     680             :      * but we don't want to lock that slot for very long, and it can advance
     681             :      * in the meantime.  So obtain the source slot's data, and create a new
     682             :      * slot using its restart_lsn.  Afterwards we lock the source slot again
     683             :      * and verify that the data we copied (name, type) has not changed
     684             :      * incompatibly.  No inconvenient WAL removal can occur once the new slot
     685             :      * is created -- but since WAL removal could have occurred before we
     686             :      * managed to create the new slot, we advance the new slot's restart_lsn
     687             :      * to the source slot's updated restart_lsn the second time we lock it.
     688             :      */
     689          30 :     for (int i = 0; i < max_replication_slots; i++)
     690             :     {
     691          30 :         ReplicationSlot *s = &ReplicationSlotCtl->replication_slots[i];
     692             : 
     693          30 :         if (s->in_use && strcmp(NameStr(s->data.name), NameStr(*src_name)) == 0)
     694             :         {
     695          28 :             SpinLockAcquire(&s->mutex);
     696          28 :             src_islogical = SlotIsLogical(s);
     697          28 :             src_restart_lsn = s->data.restart_lsn;
     698          28 :             temporary = s->data.persistency == RS_TEMPORARY;
     699          28 :             plugin = logical_slot ? pstrdup(NameStr(s->data.plugin)) : NULL;
     700          28 :             SpinLockRelease(&s->mutex);
     701             : 
     702          28 :             src = s;
     703          28 :             break;
     704             :         }
     705             :     }
     706             : 
     707          28 :     LWLockRelease(ReplicationSlotControlLock);
     708             : 
     709          28 :     if (src == NULL)
     710           0 :         ereport(ERROR,
     711             :                 (errcode(ERRCODE_UNDEFINED_OBJECT),
     712             :                  errmsg("replication slot \"%s\" does not exist", NameStr(*src_name))));
     713             : 
     714             :     /* Check type of replication slot */
     715          28 :     if (src_islogical != logical_slot)
     716           4 :         ereport(ERROR,
     717             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     718             :                  src_islogical ?
     719             :                  errmsg("cannot copy physical replication slot \"%s\" as a logical replication slot",
     720             :                         NameStr(*src_name)) :
     721             :                  errmsg("cannot copy logical replication slot \"%s\" as a physical replication slot",
     722             :                         NameStr(*src_name))));
     723             : 
     724             :     /* Copying non-reserved slot doesn't make sense */
     725          24 :     if (XLogRecPtrIsInvalid(src_restart_lsn))
     726             :     {
     727             :         Assert(!logical_slot);
     728           2 :         ereport(ERROR,
     729             :                 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     730             :                  errmsg("cannot copy a replication slot that doesn't reserve WAL")));
     731             :     }
     732             : 
     733             :     /* Overwrite params from optional arguments */
     734          22 :     if (PG_NARGS() >= 3)
     735          12 :         temporary = PG_GETARG_BOOL(2);
     736          22 :     if (PG_NARGS() >= 4)
     737             :     {
     738             :         Assert(logical_slot);
     739           8 :         plugin = NameStr(*(PG_GETARG_NAME(3)));
     740             :     }
     741             : 
     742             :     /* Create new slot and acquire it */
     743          22 :     if (logical_slot)
     744             :     {
     745             :         /*
     746             :          * We must not try to read WAL, since we haven't reserved it yet --
     747             :          * hence pass find_startpoint false.  confirmed_flush will be set
     748             :          * below, by copying from the source slot.
     749             :          */
     750          14 :         create_logical_replication_slot(NameStr(*dst_name),
     751             :                                         plugin,
     752             :                                         temporary,
     753             :                                         src_restart_lsn,
     754             :                                         false);
     755             :     }
     756             :     else
     757           8 :         create_physical_replication_slot(NameStr(*dst_name),
     758             :                                          true,
     759             :                                          temporary,
     760             :                                          src_restart_lsn);
     761             : 
     762             :     /*
     763             :      * Update the destination slot to current values of the source slot;
     764             :      * recheck that the source slot is still the one we saw previously.
     765             :      */
     766             :     {
     767             :         TransactionId copy_effective_xmin;
     768             :         TransactionId copy_effective_catalog_xmin;
     769             :         TransactionId copy_xmin;
     770             :         TransactionId copy_catalog_xmin;
     771             :         XLogRecPtr  copy_restart_lsn;
     772             :         XLogRecPtr  copy_confirmed_flush;
     773             :         bool        copy_islogical;
     774             :         char       *copy_name;
     775             : 
     776             :         /* Copy data of source slot again */
     777          20 :         SpinLockAcquire(&src->mutex);
     778          20 :         copy_effective_xmin = src->effective_xmin;
     779          20 :         copy_effective_catalog_xmin = src->effective_catalog_xmin;
     780             : 
     781          20 :         copy_xmin = src->data.xmin;
     782          20 :         copy_catalog_xmin = src->data.catalog_xmin;
     783          20 :         copy_restart_lsn = src->data.restart_lsn;
     784          20 :         copy_confirmed_flush = src->data.confirmed_flush;
     785             : 
     786             :         /* for existence check */
     787          20 :         copy_name = pstrdup(NameStr(src->data.name));
     788          20 :         copy_islogical = SlotIsLogical(src);
     789          20 :         SpinLockRelease(&src->mutex);
     790             : 
     791             :         /*
     792             :          * Check if the source slot still exists and is valid. We regard it as
     793             :          * invalid if the type of replication slot or name has been changed,
     794             :          * or the restart_lsn either is invalid or has gone backward. (The
     795             :          * restart_lsn could go backwards if the source slot is dropped and
     796             :          * copied from an older slot during installation.)
     797             :          *
     798             :          * Since erroring out will release and drop the destination slot we
     799             :          * don't need to release it here.
     800             :          */
     801          20 :         if (copy_restart_lsn < src_restart_lsn ||
     802          20 :             src_islogical != copy_islogical ||
     803          20 :             strcmp(copy_name, NameStr(*src_name)) != 0)
     804           0 :             ereport(ERROR,
     805             :                     (errmsg("could not copy replication slot \"%s\"",
     806             :                             NameStr(*src_name)),
     807             :                      errdetail("The source replication slot was modified incompatibly during the copy operation.")));
     808             : 
     809             :         /* The source slot must have a consistent snapshot */
     810          20 :         if (src_islogical && XLogRecPtrIsInvalid(copy_confirmed_flush))
     811           0 :             ereport(ERROR,
     812             :                     (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
     813             :                      errmsg("cannot copy unfinished logical replication slot \"%s\"",
     814             :                             NameStr(*src_name)),
     815             :                      errhint("Retry when the source replication slot's confirmed_flush_lsn is valid.")));
     816             : 
     817             :         /* Install copied values again */
     818          20 :         SpinLockAcquire(&MyReplicationSlot->mutex);
     819          20 :         MyReplicationSlot->effective_xmin = copy_effective_xmin;
     820          20 :         MyReplicationSlot->effective_catalog_xmin = copy_effective_catalog_xmin;
     821             : 
     822          20 :         MyReplicationSlot->data.xmin = copy_xmin;
     823          20 :         MyReplicationSlot->data.catalog_xmin = copy_catalog_xmin;
     824          20 :         MyReplicationSlot->data.restart_lsn = copy_restart_lsn;
     825          20 :         MyReplicationSlot->data.confirmed_flush = copy_confirmed_flush;
     826          20 :         SpinLockRelease(&MyReplicationSlot->mutex);
     827             : 
     828          20 :         ReplicationSlotMarkDirty();
     829          20 :         ReplicationSlotsComputeRequiredXmin(false);
     830          20 :         ReplicationSlotsComputeRequiredLSN();
     831          20 :         ReplicationSlotSave();
     832             : 
     833             : #ifdef USE_ASSERT_CHECKING
     834             :         /* Check that the restart_lsn is available */
     835             :         {
     836             :             XLogSegNo   segno;
     837             : 
     838             :             XLByteToSeg(copy_restart_lsn, segno, wal_segment_size);
     839             :             Assert(XLogGetLastRemovedSegno() < segno);
     840             :         }
     841             : #endif
     842             :     }
     843             : 
     844             :     /* target slot fully created, mark as persistent if needed */
     845          20 :     if (logical_slot && !temporary)
     846           6 :         ReplicationSlotPersist();
     847             : 
     848             :     /* All done.  Set up the return values */
     849          20 :     values[0] = NameGetDatum(dst_name);
     850          20 :     nulls[0] = false;
     851          20 :     if (!XLogRecPtrIsInvalid(MyReplicationSlot->data.confirmed_flush))
     852             :     {
     853          12 :         values[1] = LSNGetDatum(MyReplicationSlot->data.confirmed_flush);
     854          12 :         nulls[1] = false;
     855             :     }
     856             :     else
     857           8 :         nulls[1] = true;
     858             : 
     859          20 :     tuple = heap_form_tuple(tupdesc, values, nulls);
     860          20 :     result = HeapTupleGetDatum(tuple);
     861             : 
     862          20 :     ReplicationSlotRelease();
     863             : 
     864          20 :     PG_RETURN_DATUM(result);
     865             : }
     866             : 
     867             : /* The wrappers below are all to appease opr_sanity */
     868             : Datum
     869           8 : pg_copy_logical_replication_slot_a(PG_FUNCTION_ARGS)
     870             : {
     871           8 :     return copy_replication_slot(fcinfo, true);
     872             : }
     873             : 
     874             : Datum
     875           0 : pg_copy_logical_replication_slot_b(PG_FUNCTION_ARGS)
     876             : {
     877           0 :     return copy_replication_slot(fcinfo, true);
     878             : }
     879             : 
     880             : Datum
     881           8 : pg_copy_logical_replication_slot_c(PG_FUNCTION_ARGS)
     882             : {
     883           8 :     return copy_replication_slot(fcinfo, true);
     884             : }
     885             : 
     886             : Datum
     887           4 : pg_copy_physical_replication_slot_a(PG_FUNCTION_ARGS)
     888             : {
     889           4 :     return copy_replication_slot(fcinfo, false);
     890             : }
     891             : 
     892             : Datum
     893           8 : pg_copy_physical_replication_slot_b(PG_FUNCTION_ARGS)
     894             : {
     895           8 :     return copy_replication_slot(fcinfo, false);
     896             : }

Generated by: LCOV version 1.13