PostgreSQL Source Code  git master
slotfuncs.c
Go to the documentation of this file.
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 create_physical_replication_slot(char *name, bool immediately_reserve,
41  bool temporary, XLogRecPtr restart_lsn)
42 {
44 
45  /* acquire replication slot, this will check for conflicting names */
47  temporary ? RS_TEMPORARY : RS_PERSISTENT, false,
48  false, false);
49 
50  if (immediately_reserve)
51  {
52  /* Reserve WAL as the user asked for it */
53  if (XLogRecPtrIsInvalid(restart_lsn))
55  else
56  MyReplicationSlot->data.restart_lsn = restart_lsn;
57 
58  /* Write this slot to disk */
61  }
62 }
63 
64 /*
65  * SQL function for creating a new physical (streaming replication)
66  * replication slot.
67  */
68 Datum
70 {
72  bool immediately_reserve = PG_GETARG_BOOL(1);
73  bool temporary = PG_GETARG_BOOL(2);
74  Datum values[2];
75  bool nulls[2];
76  TupleDesc tupdesc;
77  HeapTuple tuple;
78  Datum result;
79 
80  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
81  elog(ERROR, "return type must be a row type");
82 
84 
86 
88  immediately_reserve,
89  temporary,
91 
93  nulls[0] = false;
94 
95  if (immediately_reserve)
96  {
98  nulls[1] = false;
99  }
100  else
101  nulls[1] = true;
102 
103  tuple = heap_form_tuple(tupdesc, values, nulls);
104  result = HeapTupleGetDatum(tuple);
105 
107 
108  PG_RETURN_DATUM(result);
109 }
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
122  bool temporary, bool two_phase,
123  bool failover,
124  XLogRecPtr restart_lsn,
125  bool find_startpoint)
126 {
127  LogicalDecodingContext *ctx = NULL;
128 
130 
131  /*
132  * Acquire a logical decoding slot, this will check for conflicting names.
133  * Initially create persistent slot as ephemeral - that allows us to
134  * nicely handle errors during initialization because it'll get dropped if
135  * this transaction fails. We'll make it persistent at the end. Temporary
136  * slots can be created as temporary from beginning as they get dropped on
137  * error as well.
138  */
140  temporary ? RS_TEMPORARY : RS_EPHEMERAL, two_phase,
141  failover, false);
142 
143  /*
144  * Create logical decoding context to find start point or, if we don't
145  * need it, to 1) bump slot's restart_lsn and xmin 2) check plugin sanity.
146  *
147  * Note: when !find_startpoint this is still important, because it's at
148  * this point that the output plugin is validated.
149  */
151  false, /* just catalogs is OK */
152  restart_lsn,
153  XL_ROUTINE(.page_read = read_local_xlog_page,
154  .segment_open = wal_segment_open,
155  .segment_close = wal_segment_close),
156  NULL, NULL, NULL);
157 
158  /*
159  * If caller needs us to determine the decoding start point, do so now.
160  * This might take a while.
161  */
162  if (find_startpoint)
164 
165  /* don't need the decoding context anymore */
166  FreeDecodingContext(ctx);
167 }
168 
169 /*
170  * SQL function for creating a new logical replication slot.
171  */
172 Datum
174 {
175  Name name = PG_GETARG_NAME(0);
177  bool temporary = PG_GETARG_BOOL(2);
178  bool two_phase = PG_GETARG_BOOL(3);
179  bool failover = PG_GETARG_BOOL(4);
180  Datum result;
181  TupleDesc tupdesc;
182  HeapTuple tuple;
183  Datum values[2];
184  bool nulls[2];
185 
186  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
187  elog(ERROR, "return type must be a row type");
188 
190 
192 
194  NameStr(*plugin),
195  temporary,
196  two_phase,
197  failover,
199  true);
200 
203 
204  memset(nulls, 0, sizeof(nulls));
205 
206  tuple = heap_form_tuple(tupdesc, values, nulls);
207  result = HeapTupleGetDatum(tuple);
208 
209  /* ok, slot is now fully created, mark it as persistent if needed */
210  if (!temporary)
213 
214  PG_RETURN_DATUM(result);
215 }
216 
217 
218 /*
219  * SQL function for dropping a replication slot.
220  */
221 Datum
223 {
224  Name name = PG_GETARG_NAME(0);
225 
227 
229 
231 
232  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
241 {
242 #define PG_GET_REPLICATION_SLOTS_COLS 17
243  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
244  XLogRecPtr currlsn;
245  int slotno;
246 
247  /*
248  * We don't require any special permission to see this function's data
249  * because nothing should be sensitive. The most critical being the slot
250  * name, which shouldn't contain anything particularly sensitive.
251  */
252 
253  InitMaterializedSRF(fcinfo, 0);
254 
255  currlsn = GetXLogWriteRecPtr();
256 
257  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
258  for (slotno = 0; slotno < max_replication_slots; slotno++)
259  {
261  ReplicationSlot slot_contents;
263  bool nulls[PG_GET_REPLICATION_SLOTS_COLS];
264  WALAvailability walstate;
265  int i;
266 
267  if (!slot->in_use)
268  continue;
269 
270  /* Copy slot contents while holding spinlock, then examine at leisure */
271  SpinLockAcquire(&slot->mutex);
272  slot_contents = *slot;
273  SpinLockRelease(&slot->mutex);
274 
275  memset(values, 0, sizeof(values));
276  memset(nulls, 0, sizeof(nulls));
277 
278  i = 0;
279  values[i++] = NameGetDatum(&slot_contents.data.name);
280 
281  if (slot_contents.data.database == InvalidOid)
282  nulls[i++] = true;
283  else
284  values[i++] = NameGetDatum(&slot_contents.data.plugin);
285 
286  if (slot_contents.data.database == InvalidOid)
287  values[i++] = CStringGetTextDatum("physical");
288  else
289  values[i++] = CStringGetTextDatum("logical");
290 
291  if (slot_contents.data.database == InvalidOid)
292  nulls[i++] = true;
293  else
294  values[i++] = ObjectIdGetDatum(slot_contents.data.database);
295 
296  values[i++] = BoolGetDatum(slot_contents.data.persistency == RS_TEMPORARY);
297  values[i++] = BoolGetDatum(slot_contents.active_pid != 0);
298 
299  if (slot_contents.active_pid != 0)
300  values[i++] = Int32GetDatum(slot_contents.active_pid);
301  else
302  nulls[i++] = true;
303 
304  if (slot_contents.data.xmin != InvalidTransactionId)
305  values[i++] = TransactionIdGetDatum(slot_contents.data.xmin);
306  else
307  nulls[i++] = true;
308 
309  if (slot_contents.data.catalog_xmin != InvalidTransactionId)
310  values[i++] = TransactionIdGetDatum(slot_contents.data.catalog_xmin);
311  else
312  nulls[i++] = true;
313 
314  if (slot_contents.data.restart_lsn != InvalidXLogRecPtr)
315  values[i++] = LSNGetDatum(slot_contents.data.restart_lsn);
316  else
317  nulls[i++] = true;
318 
319  if (slot_contents.data.confirmed_flush != InvalidXLogRecPtr)
320  values[i++] = LSNGetDatum(slot_contents.data.confirmed_flush);
321  else
322  nulls[i++] = true;
323 
324  /*
325  * If the slot has not been invalidated, test availability from
326  * restart_lsn.
327  */
328  if (slot_contents.data.invalidated != RS_INVAL_NONE)
329  walstate = WALAVAIL_REMOVED;
330  else
331  walstate = GetWALAvailability(slot_contents.data.restart_lsn);
332 
333  switch (walstate)
334  {
336  nulls[i++] = true;
337  break;
338 
339  case WALAVAIL_RESERVED:
340  values[i++] = CStringGetTextDatum("reserved");
341  break;
342 
343  case WALAVAIL_EXTENDED:
344  values[i++] = CStringGetTextDatum("extended");
345  break;
346 
347  case WALAVAIL_UNRESERVED:
348  values[i++] = CStringGetTextDatum("unreserved");
349  break;
350 
351  case WALAVAIL_REMOVED:
352 
353  /*
354  * If we read the restart_lsn long enough ago, maybe that file
355  * has been removed by now. However, the walsender could have
356  * moved forward enough that it jumped to another file after
357  * we looked. If checkpointer signalled the process to
358  * termination, then it's definitely lost; but if a process is
359  * still alive, then "unreserved" seems more appropriate.
360  *
361  * If we do change it, save the state for safe_wal_size below.
362  */
363  if (!XLogRecPtrIsInvalid(slot_contents.data.restart_lsn))
364  {
365  int pid;
366 
367  SpinLockAcquire(&slot->mutex);
368  pid = slot->active_pid;
369  slot_contents.data.restart_lsn = slot->data.restart_lsn;
370  SpinLockRelease(&slot->mutex);
371  if (pid != 0)
372  {
373  values[i++] = CStringGetTextDatum("unreserved");
374  walstate = WALAVAIL_UNRESERVED;
375  break;
376  }
377  }
378  values[i++] = CStringGetTextDatum("lost");
379  break;
380  }
381 
382  /*
383  * safe_wal_size is only computed for slots that have not been lost,
384  * and only if there's a configured maximum size.
385  */
386  if (walstate == WALAVAIL_REMOVED || max_slot_wal_keep_size_mb < 0)
387  nulls[i++] = true;
388  else
389  {
390  XLogSegNo targetSeg;
391  uint64 slotKeepSegs;
392  uint64 keepSegs;
393  XLogSegNo failSeg;
394  XLogRecPtr failLSN;
395 
396  XLByteToSeg(slot_contents.data.restart_lsn, targetSeg, wal_segment_size);
397 
398  /* determine how many segments can be kept by slots */
400  /* ditto for wal_keep_size */
402 
403  /* if currpos reaches failLSN, we lose our segment */
404  failSeg = targetSeg + Max(slotKeepSegs, keepSegs) + 1;
405  XLogSegNoOffsetToRecPtr(failSeg, 0, wal_segment_size, failLSN);
406 
407  values[i++] = Int64GetDatum(failLSN - currlsn);
408  }
409 
410  values[i++] = BoolGetDatum(slot_contents.data.two_phase);
411 
412  if (slot_contents.data.database == InvalidOid)
413  nulls[i++] = true;
414  else
415  {
416  switch (slot_contents.data.invalidated)
417  {
418  case RS_INVAL_NONE:
419  nulls[i++] = true;
420  break;
421 
424  break;
425 
426  case RS_INVAL_HORIZON:
428  break;
429 
430  case RS_INVAL_WAL_LEVEL:
432  break;
433  }
434  }
435 
436  values[i++] = BoolGetDatum(slot_contents.data.failover);
437 
438  values[i++] = BoolGetDatum(slot_contents.data.synced);
439 
441 
442  tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
443  values, nulls);
444  }
445 
446  LWLockRelease(ReplicationSlotControlLock);
447 
448  return (Datum) 0;
449 }
450 
451 /*
452  * Helper function for advancing our physical replication slot forward.
453  *
454  * The LSN position to move to is compared simply to the slot's restart_lsn,
455  * knowing that any position older than that would be removed by successive
456  * checkpoints.
457  */
458 static XLogRecPtr
460 {
462  XLogRecPtr retlsn = startlsn;
463 
464  Assert(moveto != InvalidXLogRecPtr);
465 
466  if (startlsn < moveto)
467  {
471  retlsn = moveto;
472 
473  /*
474  * Dirty the slot so as it is written out at the next checkpoint. Note
475  * that the LSN position advanced may still be lost in the event of a
476  * crash, but this makes the data consistent after a clean shutdown.
477  */
479  }
480 
481  return retlsn;
482 }
483 
484 /*
485  * Helper function for advancing our logical replication slot forward.
486  *
487  * The slot's restart_lsn is used as start point for reading records, while
488  * confirmed_flush is used as base point for the decoding context.
489  *
490  * We cannot just do LogicalConfirmReceivedLocation to update confirmed_flush,
491  * because we need to digest WAL to advance restart_lsn allowing to recycle
492  * WAL and removal of old catalog tuples. As decoding is done in fast_forward
493  * mode, no changes are generated anyway.
494  */
495 static XLogRecPtr
497 {
499  ResourceOwner old_resowner = CurrentResourceOwner;
500  XLogRecPtr retlsn;
501 
502  Assert(moveto != InvalidXLogRecPtr);
503 
504  PG_TRY();
505  {
506  /*
507  * Create our decoding context in fast_forward mode, passing start_lsn
508  * as InvalidXLogRecPtr, so that we start processing from my slot's
509  * confirmed_flush.
510  */
512  NIL,
513  true, /* fast_forward */
514  XL_ROUTINE(.page_read = read_local_xlog_page,
515  .segment_open = wal_segment_open,
516  .segment_close = wal_segment_close),
517  NULL, NULL, NULL);
518 
519  /*
520  * Start reading at the slot's restart_lsn, which we know to point to
521  * a valid record.
522  */
524 
525  /* invalidate non-timetravel entries */
527 
528  /* Decode records until we reach the requested target */
529  while (ctx->reader->EndRecPtr < moveto)
530  {
531  char *errm = NULL;
532  XLogRecord *record;
533 
534  /*
535  * Read records. No changes are generated in fast_forward mode,
536  * but snapbuilder/slot statuses are updated properly.
537  */
538  record = XLogReadRecord(ctx->reader, &errm);
539  if (errm)
540  elog(ERROR, "could not find record while advancing replication slot: %s",
541  errm);
542 
543  /*
544  * Process the record. Storage-level changes are ignored in
545  * fast_forward mode, but other modules (such as snapbuilder)
546  * might still have critical updates to do.
547  */
548  if (record)
550 
552  }
553 
554  /*
555  * Logical decoding could have clobbered CurrentResourceOwner during
556  * transaction management, so restore the executor's value. (This is
557  * a kluge, but it's not worth cleaning up right now.)
558  */
559  CurrentResourceOwner = old_resowner;
560 
561  if (ctx->reader->EndRecPtr != InvalidXLogRecPtr)
562  {
564 
565  /*
566  * If only the confirmed_flush LSN has changed the slot won't get
567  * marked as dirty by the above. Callers on the walsender
568  * interface are expected to keep track of their own progress and
569  * don't need it written out. But SQL-interface users cannot
570  * specify their own start positions and it's harder for them to
571  * keep track of their progress, so we should make more of an
572  * effort to save it for them.
573  *
574  * Dirty the slot so it is written out at the next checkpoint. The
575  * LSN position advanced to may still be lost on a crash but this
576  * makes the data consistent after a clean shutdown.
577  */
579  }
580 
582 
583  /* free context, call shutdown callback */
584  FreeDecodingContext(ctx);
585 
587  }
588  PG_CATCH();
589  {
590  /* clear all timetravel entries */
592 
593  PG_RE_THROW();
594  }
595  PG_END_TRY();
596 
597  return retlsn;
598 }
599 
600 /*
601  * SQL function for moving the position in a replication slot.
602  */
603 Datum
605 {
606  Name slotname = PG_GETARG_NAME(0);
607  XLogRecPtr moveto = PG_GETARG_LSN(1);
608  XLogRecPtr endlsn;
609  XLogRecPtr minlsn;
610  TupleDesc tupdesc;
611  Datum values[2];
612  bool nulls[2];
613  HeapTuple tuple;
614  Datum result;
615 
617 
619 
620  if (XLogRecPtrIsInvalid(moveto))
621  ereport(ERROR,
622  (errmsg("invalid target WAL LSN")));
623 
624  /* Build a tuple descriptor for our result type */
625  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
626  elog(ERROR, "return type must be a row type");
627 
628  /*
629  * We can't move slot past what's been flushed/replayed so clamp the
630  * target position accordingly.
631  */
632  if (!RecoveryInProgress())
633  moveto = Min(moveto, GetFlushRecPtr(NULL));
634  else
635  moveto = Min(moveto, GetXLogReplayRecPtr(NULL));
636 
637  /* Acquire the slot so we "own" it */
638  ReplicationSlotAcquire(NameStr(*slotname), true);
639 
640  /* A slot whose restart_lsn has never been reserved cannot be advanced */
642  ereport(ERROR,
643  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
644  errmsg("replication slot \"%s\" cannot be advanced",
645  NameStr(*slotname)),
646  errdetail("This slot has never previously reserved WAL, or it has been invalidated.")));
647 
648  /*
649  * Check if the slot is not moving backwards. Physical slots rely simply
650  * on restart_lsn as a minimum point, while logical slots have confirmed
651  * consumption up to confirmed_flush, meaning that in both cases data
652  * older than that is not available anymore.
653  */
656  else
658 
659  if (moveto < minlsn)
660  ereport(ERROR,
661  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
662  errmsg("cannot advance replication slot to %X/%X, minimum is %X/%X",
663  LSN_FORMAT_ARGS(moveto), LSN_FORMAT_ARGS(minlsn))));
664 
665  /* Do the actual slot update, depending on the slot type */
667  endlsn = pg_logical_replication_slot_advance(moveto);
668  else
669  endlsn = pg_physical_replication_slot_advance(moveto);
670 
672  nulls[0] = false;
673 
674  /*
675  * Recompute the minimum LSN and xmin across all slots to adjust with the
676  * advancing potentially done.
677  */
680 
682 
683  /* Return the reached position. */
684  values[1] = LSNGetDatum(endlsn);
685  nulls[1] = false;
686 
687  tuple = heap_form_tuple(tupdesc, values, nulls);
688  result = HeapTupleGetDatum(tuple);
689 
690  PG_RETURN_DATUM(result);
691 }
692 
693 /*
694  * Helper function of copying a replication slot.
695  */
696 static Datum
697 copy_replication_slot(FunctionCallInfo fcinfo, bool logical_slot)
698 {
699  Name src_name = PG_GETARG_NAME(0);
700  Name dst_name = PG_GETARG_NAME(1);
701  ReplicationSlot *src = NULL;
702  ReplicationSlot first_slot_contents;
703  ReplicationSlot second_slot_contents;
704  XLogRecPtr src_restart_lsn;
705  bool src_islogical;
706  bool temporary;
707  char *plugin;
708  Datum values[2];
709  bool nulls[2];
710  Datum result;
711  TupleDesc tupdesc;
712  HeapTuple tuple;
713 
714  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
715  elog(ERROR, "return type must be a row type");
716 
718 
719  if (logical_slot)
721  else
723 
724  LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
725 
726  /*
727  * We need to prevent the source slot's reserved WAL from being removed,
728  * but we don't want to lock that slot for very long, and it can advance
729  * in the meantime. So obtain the source slot's data, and create a new
730  * slot using its restart_lsn. Afterwards we lock the source slot again
731  * and verify that the data we copied (name, type) has not changed
732  * incompatibly. No inconvenient WAL removal can occur once the new slot
733  * is created -- but since WAL removal could have occurred before we
734  * managed to create the new slot, we advance the new slot's restart_lsn
735  * to the source slot's updated restart_lsn the second time we lock it.
736  */
737  for (int i = 0; i < max_replication_slots; i++)
738  {
740 
741  if (s->in_use && strcmp(NameStr(s->data.name), NameStr(*src_name)) == 0)
742  {
743  /* Copy the slot contents while holding spinlock */
744  SpinLockAcquire(&s->mutex);
745  first_slot_contents = *s;
746  SpinLockRelease(&s->mutex);
747  src = s;
748  break;
749  }
750  }
751 
752  LWLockRelease(ReplicationSlotControlLock);
753 
754  if (src == NULL)
755  ereport(ERROR,
756  (errcode(ERRCODE_UNDEFINED_OBJECT),
757  errmsg("replication slot \"%s\" does not exist", NameStr(*src_name))));
758 
759  src_islogical = SlotIsLogical(&first_slot_contents);
760  src_restart_lsn = first_slot_contents.data.restart_lsn;
761  temporary = (first_slot_contents.data.persistency == RS_TEMPORARY);
762  plugin = logical_slot ? NameStr(first_slot_contents.data.plugin) : NULL;
763 
764  /* Check type of replication slot */
765  if (src_islogical != logical_slot)
766  ereport(ERROR,
767  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
768  src_islogical ?
769  errmsg("cannot copy physical replication slot \"%s\" as a logical replication slot",
770  NameStr(*src_name)) :
771  errmsg("cannot copy logical replication slot \"%s\" as a physical replication slot",
772  NameStr(*src_name))));
773 
774  /* Copying non-reserved slot doesn't make sense */
775  if (XLogRecPtrIsInvalid(src_restart_lsn))
776  ereport(ERROR,
777  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
778  errmsg("cannot copy a replication slot that doesn't reserve WAL")));
779 
780  /* Overwrite params from optional arguments */
781  if (PG_NARGS() >= 3)
782  temporary = PG_GETARG_BOOL(2);
783  if (PG_NARGS() >= 4)
784  {
785  Assert(logical_slot);
786  plugin = NameStr(*(PG_GETARG_NAME(3)));
787  }
788 
789  /* Create new slot and acquire it */
790  if (logical_slot)
791  {
792  /*
793  * We must not try to read WAL, since we haven't reserved it yet --
794  * hence pass find_startpoint false. confirmed_flush will be set
795  * below, by copying from the source slot.
796  *
797  * To avoid potential issues with the slot synchronization where the
798  * restart_lsn of a replication slot can go backward, we set the
799  * failover option to false here. This situation occurs when a slot
800  * on the primary server is dropped and immediately replaced with a
801  * new slot of the same name, created by copying from another existing
802  * slot. However, the slot synchronization will only observe the
803  * restart_lsn of the same slot going backward.
804  */
806  plugin,
807  temporary,
808  false,
809  false,
810  src_restart_lsn,
811  false);
812  }
813  else
815  true,
816  temporary,
817  src_restart_lsn);
818 
819  /*
820  * Update the destination slot to current values of the source slot;
821  * recheck that the source slot is still the one we saw previously.
822  */
823  {
824  TransactionId copy_effective_xmin;
825  TransactionId copy_effective_catalog_xmin;
826  TransactionId copy_xmin;
827  TransactionId copy_catalog_xmin;
828  XLogRecPtr copy_restart_lsn;
829  XLogRecPtr copy_confirmed_flush;
830  bool copy_islogical;
831  char *copy_name;
832 
833  /* Copy data of source slot again */
834  SpinLockAcquire(&src->mutex);
835  second_slot_contents = *src;
836  SpinLockRelease(&src->mutex);
837 
838  copy_effective_xmin = second_slot_contents.effective_xmin;
839  copy_effective_catalog_xmin = second_slot_contents.effective_catalog_xmin;
840 
841  copy_xmin = second_slot_contents.data.xmin;
842  copy_catalog_xmin = second_slot_contents.data.catalog_xmin;
843  copy_restart_lsn = second_slot_contents.data.restart_lsn;
844  copy_confirmed_flush = second_slot_contents.data.confirmed_flush;
845 
846  /* for existence check */
847  copy_name = NameStr(second_slot_contents.data.name);
848  copy_islogical = SlotIsLogical(&second_slot_contents);
849 
850  /*
851  * Check if the source slot still exists and is valid. We regard it as
852  * invalid if the type of replication slot or name has been changed,
853  * or the restart_lsn either is invalid or has gone backward. (The
854  * restart_lsn could go backwards if the source slot is dropped and
855  * copied from an older slot during installation.)
856  *
857  * Since erroring out will release and drop the destination slot we
858  * don't need to release it here.
859  */
860  if (copy_restart_lsn < src_restart_lsn ||
861  src_islogical != copy_islogical ||
862  strcmp(copy_name, NameStr(*src_name)) != 0)
863  ereport(ERROR,
864  (errmsg("could not copy replication slot \"%s\"",
865  NameStr(*src_name)),
866  errdetail("The source replication slot was modified incompatibly during the copy operation.")));
867 
868  /* The source slot must have a consistent snapshot */
869  if (src_islogical && XLogRecPtrIsInvalid(copy_confirmed_flush))
870  ereport(ERROR,
871  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
872  errmsg("cannot copy unfinished logical replication slot \"%s\"",
873  NameStr(*src_name)),
874  errhint("Retry when the source replication slot's confirmed_flush_lsn is valid.")));
875 
876  /* Install copied values again */
878  MyReplicationSlot->effective_xmin = copy_effective_xmin;
879  MyReplicationSlot->effective_catalog_xmin = copy_effective_catalog_xmin;
880 
881  MyReplicationSlot->data.xmin = copy_xmin;
882  MyReplicationSlot->data.catalog_xmin = copy_catalog_xmin;
883  MyReplicationSlot->data.restart_lsn = copy_restart_lsn;
884  MyReplicationSlot->data.confirmed_flush = copy_confirmed_flush;
886 
891 
892 #ifdef USE_ASSERT_CHECKING
893  /* Check that the restart_lsn is available */
894  {
895  XLogSegNo segno;
896 
897  XLByteToSeg(copy_restart_lsn, segno, wal_segment_size);
898  Assert(XLogGetLastRemovedSegno() < segno);
899  }
900 #endif
901  }
902 
903  /* target slot fully created, mark as persistent if needed */
904  if (logical_slot && !temporary)
906 
907  /* All done. Set up the return values */
908  values[0] = NameGetDatum(dst_name);
909  nulls[0] = false;
911  {
913  nulls[1] = false;
914  }
915  else
916  nulls[1] = true;
917 
918  tuple = heap_form_tuple(tupdesc, values, nulls);
919  result = HeapTupleGetDatum(tuple);
920 
922 
923  PG_RETURN_DATUM(result);
924 }
925 
926 /* The wrappers below are all to appease opr_sanity */
927 Datum
929 {
930  return copy_replication_slot(fcinfo, true);
931 }
932 
933 Datum
935 {
936  return copy_replication_slot(fcinfo, true);
937 }
938 
939 Datum
941 {
942  return copy_replication_slot(fcinfo, true);
943 }
944 
945 Datum
947 {
948  return copy_replication_slot(fcinfo, false);
949 }
950 
951 Datum
953 {
954  return copy_replication_slot(fcinfo, false);
955 }
956 
957 /*
958  * Synchronize failover enabled replication slots to a standby server
959  * from the primary server.
960  */
961 Datum
963 {
965  char *err;
966  StringInfoData app_name;
967 
969 
970  if (!RecoveryInProgress())
971  ereport(ERROR,
972  errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
973  errmsg("replication slots can only be synchronized to a standby server"));
974 
975  /* Load the libpq-specific functions */
976  load_file("libpqwalreceiver", false);
977 
979 
980  initStringInfo(&app_name);
981  if (cluster_name[0])
982  appendStringInfo(&app_name, "%s_slotsync", cluster_name);
983  else
984  appendStringInfoString(&app_name, "slotsync");
985 
986  /* Connect to the primary server. */
987  wrconn = walrcv_connect(PrimaryConnInfo, false, false, false,
988  app_name.data, &err);
989  pfree(app_name.data);
990 
991  if (!wrconn)
992  ereport(ERROR,
993  errcode(ERRCODE_CONNECTION_FAILURE),
994  errmsg("could not connect to the primary server: %s", err));
995 
997 
999 
1000  PG_RETURN_VOID();
1001 }
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define CStringGetTextDatum(s)
Definition: builtins.h:97
#define NameStr(name)
Definition: c.h:735
#define Min(x, y)
Definition: c.h:993
#define Max(x, y)
Definition: c.h:987
uint32 TransactionId
Definition: c.h:641
#define OidIsValid(objectId)
Definition: c.h:764
void LogicalDecodingProcessRecord(LogicalDecodingContext *ctx, XLogReaderState *record)
Definition: decode.c:91
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:144
int errdetail(const char *fmt,...)
Definition: elog.c:1208
int errhint(const char *fmt,...)
Definition: elog.c:1322
int errcode(int sqlerrcode)
Definition: elog.c:860
int errmsg(const char *fmt,...)
Definition: elog.c:1075
#define PG_RE_THROW()
Definition: elog.h:411
#define PG_TRY(...)
Definition: elog.h:370
#define PG_END_TRY(...)
Definition: elog.h:395
#define ERROR
Definition: elog.h:39
#define PG_CATCH(...)
Definition: elog.h:380
#define ereport(elevel,...)
Definition: elog.h:149
void err(int eval, const char *fmt,...)
Definition: err.c:43
Datum Int64GetDatum(int64 X)
Definition: fmgr.c:1807
#define PG_RETURN_VOID()
Definition: fmgr.h:349
#define PG_NARGS()
Definition: fmgr.h:203
#define PG_GETARG_NAME(n)
Definition: fmgr.h:278
#define PG_GETARG_BOOL(n)
Definition: fmgr.h:274
#define PG_RETURN_DATUM(x)
Definition: fmgr.h:353
#define PG_FUNCTION_ARGS
Definition: fmgr.h:193
void InitMaterializedSRF(FunctionCallInfo fcinfo, bits32 flags)
Definition: funcapi.c:76
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:276
@ TYPEFUNC_COMPOSITE
Definition: funcapi.h:149
static Datum HeapTupleGetDatum(const HeapTupleData *tuple)
Definition: funcapi.h:230
char * cluster_name
Definition: guc_tables.c:536
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition: heaptuple.c:1117
void InvalidateSystemCaches(void)
Definition: inval.c:793
int i
Definition: isn.c:73
Assert(fmt[strlen(fmt) - 1] !='\n')
void LogicalConfirmReceivedLocation(XLogRecPtr lsn)
Definition: logical.c:1829
void FreeDecodingContext(LogicalDecodingContext *ctx)
Definition: logical.c:688
void DecodingContextFindStartpoint(LogicalDecodingContext *ctx)
Definition: logical.c:644
void CheckLogicalDecodingRequirements(void)
Definition: logical.c:110
LogicalDecodingContext * CreateInitDecodingContext(const char *plugin, List *output_plugin_options, bool need_full_snapshot, XLogRecPtr restart_lsn, XLogReaderRoutine *xl_routine, LogicalOutputPluginWriterPrepareWrite prepare_write, LogicalOutputPluginWriterWrite do_write, LogicalOutputPluginWriterUpdateProgress update_progress)
Definition: logical.c:330
LogicalDecodingContext * CreateDecodingContext(XLogRecPtr start_lsn, List *output_plugin_options, bool fast_forward, XLogReaderRoutine *xl_routine, LogicalOutputPluginWriterPrepareWrite prepare_write, LogicalOutputPluginWriterWrite do_write, LogicalOutputPluginWriterUpdateProgress update_progress)
Definition: logical.c:496
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1168
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1781
@ LW_SHARED
Definition: lwlock.h:117
void pfree(void *pointer)
Definition: mcxt.c:1431
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:122
#define NIL
Definition: pg_list.h:68
#define PG_GETARG_LSN(n)
Definition: pg_lsn.h:33
static Datum LSNGetDatum(XLogRecPtr X)
Definition: pg_lsn.h:28
static bool two_phase
static const char * plugin
static Datum TransactionIdGetDatum(TransactionId X)
Definition: postgres.h:272
uintptr_t Datum
Definition: postgres.h:64
static Datum BoolGetDatum(bool X)
Definition: postgres.h:102
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:252
static Datum NameGetDatum(const NameData *X)
Definition: postgres.h:373
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:212
#define InvalidOid
Definition: postgres_ext.h:36
ResourceOwner CurrentResourceOwner
Definition: resowner.c:165
void ReplicationSlotCreate(const char *name, bool db_specific, ReplicationSlotPersistency persistency, bool two_phase, bool failover, bool synced)
Definition: slot.c:256
void ReplicationSlotMarkDirty(void)
Definition: slot.c:930
void ReplicationSlotReserveWal(void)
Definition: slot.c:1307
void ReplicationSlotAcquire(const char *name, bool nowait)
Definition: slot.c:486
void ReplicationSlotsComputeRequiredXmin(bool already_locked)
Definition: slot.c:969
void ReplicationSlotPersist(void)
Definition: slot.c:947
ReplicationSlot * MyReplicationSlot
Definition: slot.c:100
void ReplicationSlotDrop(const char *name, bool nowait)
Definition: slot.c:704
void ReplicationSlotSave(void)
Definition: slot.c:912
void CheckSlotPermissions(void)
Definition: slot.c:1290
void ReplicationSlotRelease(void)
Definition: slot.c:590
int max_replication_slots
Definition: slot.c:103
ReplicationSlotCtlData * ReplicationSlotCtl
Definition: slot.c:97
void ReplicationSlotsComputeRequiredLSN(void)
Definition: slot.c:1025
void CheckSlotRequirements(void)
Definition: slot.c:1268
@ RS_PERSISTENT
Definition: slot.h:35
@ RS_EPHEMERAL
Definition: slot.h:36
@ RS_TEMPORARY
Definition: slot.h:37
#define SLOT_INVAL_HORIZON_TEXT
Definition: slot.h:60
#define SLOT_INVAL_WAL_REMOVED_TEXT
Definition: slot.h:59
@ RS_INVAL_WAL_REMOVED
Definition: slot.h:48
@ RS_INVAL_HORIZON
Definition: slot.h:50
@ RS_INVAL_WAL_LEVEL
Definition: slot.h:52
@ RS_INVAL_NONE
Definition: slot.h:46
#define SlotIsLogical(slot)
Definition: slot.h:210
#define SLOT_INVAL_WAL_LEVEL_TEXT
Definition: slot.h:61
Datum pg_get_replication_slots(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:240
Datum pg_copy_physical_replication_slot_a(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:946
static void create_logical_replication_slot(char *name, char *plugin, bool temporary, bool two_phase, bool failover, XLogRecPtr restart_lsn, bool find_startpoint)
Definition: slotfuncs.c:121
Datum pg_create_logical_replication_slot(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:173
#define PG_GET_REPLICATION_SLOTS_COLS
static Datum copy_replication_slot(FunctionCallInfo fcinfo, bool logical_slot)
Definition: slotfuncs.c:697
Datum pg_copy_logical_replication_slot_c(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:940
Datum pg_create_physical_replication_slot(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:69
Datum pg_copy_logical_replication_slot_a(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:928
Datum pg_copy_physical_replication_slot_b(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:952
Datum pg_sync_replication_slots(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:962
Datum pg_copy_logical_replication_slot_b(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:934
static XLogRecPtr pg_logical_replication_slot_advance(XLogRecPtr moveto)
Definition: slotfuncs.c:496
static XLogRecPtr pg_physical_replication_slot_advance(XLogRecPtr moveto)
Definition: slotfuncs.c:459
Datum pg_replication_slot_advance(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:604
static void create_physical_replication_slot(char *name, bool immediately_reserve, bool temporary, XLogRecPtr restart_lsn)
Definition: slotfuncs.c:40
Datum pg_drop_replication_slot(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:222
void SyncReplicationSlots(WalReceiverConn *wrconn)
Definition: slotsync.c:911
void ValidateSlotSyncParams(void)
Definition: slotsync.c:781
#define SpinLockRelease(lock)
Definition: spin.h:64
#define SpinLockAcquire(lock)
Definition: spin.h:62
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:97
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:182
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
XLogReaderState * reader
Definition: logical.h:42
ReplicationSlot replication_slots[1]
Definition: slot.h:221
TransactionId xmin
Definition: slot.h:85
TransactionId catalog_xmin
Definition: slot.h:93
XLogRecPtr restart_lsn
Definition: slot.h:96
XLogRecPtr confirmed_flush
Definition: slot.h:107
ReplicationSlotPersistency persistency
Definition: slot.h:77
ReplicationSlotInvalidationCause invalidated
Definition: slot.h:99
TransactionId effective_catalog_xmin
Definition: slot.h:178
slock_t mutex
Definition: slot.h:154
pid_t active_pid
Definition: slot.h:160
bool in_use
Definition: slot.h:157
TransactionId effective_xmin
Definition: slot.h:177
ReplicationSlotPersistentData data
Definition: slot.h:181
TupleDesc setDesc
Definition: execnodes.h:340
Tuplestorestate * setResult
Definition: execnodes.h:339
XLogRecPtr EndRecPtr
Definition: xlogreader.h:207
Definition: c.h:730
#define InvalidTransactionId
Definition: transam.h:31
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, const Datum *values, const bool *isnull)
Definition: tuplestore.c:750
const char * name
static WalReceiverConn * wrconn
Definition: walreceiver.c:95
#define walrcv_connect(conninfo, replication, logical, must_use_password, appname, err)
Definition: walreceiver.h:432
#define walrcv_disconnect(conn)
Definition: walreceiver.h:464
bool RecoveryInProgress(void)
Definition: xlog.c:6211
XLogSegNo XLogGetLastRemovedSegno(void)
Definition: xlog.c:3693
int wal_keep_size_mb
Definition: xlog.c:120
int wal_segment_size
Definition: xlog.c:147
WALAvailability GetWALAvailability(XLogRecPtr targetLSN)
Definition: xlog.c:7709
int max_slot_wal_keep_size_mb
Definition: xlog.c:139
XLogRecPtr GetFlushRecPtr(TimeLineID *insertTLI)
Definition: xlog.c:6376
XLogRecPtr GetXLogWriteRecPtr(void)
Definition: xlog.c:9288
WALAvailability
Definition: xlog.h:185
@ WALAVAIL_REMOVED
Definition: xlog.h:191
@ WALAVAIL_RESERVED
Definition: xlog.h:187
@ WALAVAIL_UNRESERVED
Definition: xlog.h:190
@ WALAVAIL_EXTENDED
Definition: xlog.h:188
@ WALAVAIL_INVALID_LSN
Definition: xlog.h:186
#define XLogSegNoOffsetToRecPtr(segno, offset, wal_segsz_bytes, dest)
#define XLogMBVarToSegs(mbvar, wal_segsz_bytes)
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
uint64 XLogSegNo
Definition: xlogdefs.h:48
XLogRecord * XLogReadRecord(XLogReaderState *state, char **errormsg)
Definition: xlogreader.c:391
void XLogBeginRead(XLogReaderState *state, XLogRecPtr RecPtr)
Definition: xlogreader.c:233
#define XL_ROUTINE(...)
Definition: xlogreader.h:117
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
char * PrimaryConnInfo
Definition: xlogrecovery.c:96
void wal_segment_close(XLogReaderState *state)
Definition: xlogutils.c:845
void wal_segment_open(XLogReaderState *state, XLogSegNo nextSegNo, TimeLineID *tli_p)
Definition: xlogutils.c:820
int read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *cur_page)
Definition: xlogutils.c:864