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-2025, 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"
17#include "access/xlogrecovery.h"
18#include "access/xlogutils.h"
19#include "funcapi.h"
20#include "replication/logical.h"
21#include "replication/slot.h"
23#include "utils/builtins.h"
24#include "utils/guc.h"
25#include "utils/pg_lsn.h"
26
27/*
28 * Map SlotSyncSkipReason enum values to human-readable names.
29 */
30static const char *SlotSyncSkipReasonNames[] = {
31 [SS_SKIP_NONE] = "none",
32 [SS_SKIP_WAL_NOT_FLUSHED] = "wal_not_flushed",
33 [SS_SKIP_WAL_OR_ROWS_REMOVED] = "wal_or_rows_removed",
34 [SS_SKIP_NO_CONSISTENT_SNAPSHOT] = "no_consistent_snapshot",
35 [SS_SKIP_INVALID] = "slot_invalidated"
36};
37
38/*
39 * Helper function for creating a new physical replication slot with
40 * given arguments. Note that this function doesn't release the created
41 * slot.
42 *
43 * If restart_lsn is a valid value, we use it without WAL reservation
44 * routine. So the caller must guarantee that WAL is available.
45 */
46static void
47create_physical_replication_slot(char *name, bool immediately_reserve,
48 bool temporary, XLogRecPtr restart_lsn)
49{
51
52 /* acquire replication slot, this will check for conflicting names */
54 temporary ? RS_TEMPORARY : RS_PERSISTENT, false,
55 false, false);
56
57 if (immediately_reserve)
58 {
59 /* Reserve WAL as the user asked for it */
60 if (!XLogRecPtrIsValid(restart_lsn))
62 else
63 MyReplicationSlot->data.restart_lsn = restart_lsn;
64
65 /* Write this slot to disk */
68 }
69}
70
71/*
72 * SQL function for creating a new physical (streaming replication)
73 * replication slot.
74 */
77{
79 bool immediately_reserve = PG_GETARG_BOOL(1);
80 bool temporary = PG_GETARG_BOOL(2);
81 Datum values[2];
82 bool nulls[2];
83 TupleDesc tupdesc;
84 HeapTuple tuple;
85 Datum result;
86
87 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
88 elog(ERROR, "return type must be a row type");
89
91
93
95 immediately_reserve,
96 temporary,
98
100 nulls[0] = false;
101
102 if (immediately_reserve)
103 {
105 nulls[1] = false;
106 }
107 else
108 nulls[1] = true;
109
110 tuple = heap_form_tuple(tupdesc, values, nulls);
111 result = HeapTupleGetDatum(tuple);
112
114
115 PG_RETURN_DATUM(result);
116}
117
118
119/*
120 * Helper function for creating a new logical replication slot with
121 * given arguments. Note that this function doesn't release the created
122 * slot.
123 *
124 * When find_startpoint is false, the slot's confirmed_flush is not set; it's
125 * caller's responsibility to ensure it's set to something sensible.
126 */
127static void
129 bool temporary, bool two_phase,
130 bool failover,
131 XLogRecPtr restart_lsn,
132 bool find_startpoint)
133{
134 LogicalDecodingContext *ctx = NULL;
135
137
138 /*
139 * Acquire a logical decoding slot, this will check for conflicting names.
140 * Initially create persistent slot as ephemeral - that allows us to
141 * nicely handle errors during initialization because it'll get dropped if
142 * this transaction fails. We'll make it persistent at the end. Temporary
143 * slots can be created as temporary from beginning as they get dropped on
144 * error as well.
145 */
147 temporary ? RS_TEMPORARY : RS_EPHEMERAL, two_phase,
148 failover, false);
149
150 /*
151 * Create logical decoding context to find start point or, if we don't
152 * need it, to 1) bump slot's restart_lsn and xmin 2) check plugin sanity.
153 *
154 * Note: when !find_startpoint this is still important, because it's at
155 * this point that the output plugin is validated.
156 */
158 false, /* just catalogs is OK */
159 restart_lsn,
160 XL_ROUTINE(.page_read = read_local_xlog_page,
161 .segment_open = wal_segment_open,
162 .segment_close = wal_segment_close),
163 NULL, NULL, NULL);
164
165 /*
166 * If caller needs us to determine the decoding start point, do so now.
167 * This might take a while.
168 */
169 if (find_startpoint)
171
172 /* don't need the decoding context anymore */
174}
175
176/*
177 * SQL function for creating a new logical replication slot.
178 */
179Datum
181{
184 bool temporary = PG_GETARG_BOOL(2);
185 bool two_phase = PG_GETARG_BOOL(3);
186 bool failover = PG_GETARG_BOOL(4);
187 Datum result;
188 TupleDesc tupdesc;
189 HeapTuple tuple;
190 Datum values[2];
191 bool nulls[2];
192
193 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
194 elog(ERROR, "return type must be a row type");
195
197
199
201 NameStr(*plugin),
202 temporary,
203 two_phase,
204 failover,
206 true);
207
210
211 memset(nulls, 0, sizeof(nulls));
212
213 tuple = heap_form_tuple(tupdesc, values, nulls);
214 result = HeapTupleGetDatum(tuple);
215
216 /* ok, slot is now fully created, mark it as persistent if needed */
217 if (!temporary)
220
221 PG_RETURN_DATUM(result);
222}
223
224
225/*
226 * SQL function for dropping a replication slot.
227 */
228Datum
230{
232
234
236
238
240}
241
242/*
243 * pg_get_replication_slots - SQL SRF showing all replication slots
244 * that currently exist on the database cluster.
245 */
246Datum
248{
249#define PG_GET_REPLICATION_SLOTS_COLS 21
250 ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
251 XLogRecPtr currlsn;
252 int slotno;
253
254 /*
255 * We don't require any special permission to see this function's data
256 * because nothing should be sensitive. The most critical being the slot
257 * name, which shouldn't contain anything particularly sensitive.
258 */
259
260 InitMaterializedSRF(fcinfo, 0);
261
262 currlsn = GetXLogWriteRecPtr();
263
264 LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
265 for (slotno = 0; slotno < max_replication_slots; slotno++)
266 {
268 ReplicationSlot slot_contents;
271 WALAvailability walstate;
272 int i;
274
275 if (!slot->in_use)
276 continue;
277
278 /* Copy slot contents while holding spinlock, then examine at leisure */
279 SpinLockAcquire(&slot->mutex);
280 slot_contents = *slot;
281 SpinLockRelease(&slot->mutex);
282
283 memset(values, 0, sizeof(values));
284 memset(nulls, 0, sizeof(nulls));
285
286 i = 0;
287 values[i++] = NameGetDatum(&slot_contents.data.name);
288
289 if (slot_contents.data.database == InvalidOid)
290 nulls[i++] = true;
291 else
292 values[i++] = NameGetDatum(&slot_contents.data.plugin);
293
294 if (slot_contents.data.database == InvalidOid)
295 values[i++] = CStringGetTextDatum("physical");
296 else
297 values[i++] = CStringGetTextDatum("logical");
298
299 if (slot_contents.data.database == InvalidOid)
300 nulls[i++] = true;
301 else
302 values[i++] = ObjectIdGetDatum(slot_contents.data.database);
303
304 values[i++] = BoolGetDatum(slot_contents.data.persistency == RS_TEMPORARY);
305 values[i++] = BoolGetDatum(slot_contents.active_pid != 0);
306
307 if (slot_contents.active_pid != 0)
308 values[i++] = Int32GetDatum(slot_contents.active_pid);
309 else
310 nulls[i++] = true;
311
312 if (slot_contents.data.xmin != InvalidTransactionId)
313 values[i++] = TransactionIdGetDatum(slot_contents.data.xmin);
314 else
315 nulls[i++] = true;
316
317 if (slot_contents.data.catalog_xmin != InvalidTransactionId)
318 values[i++] = TransactionIdGetDatum(slot_contents.data.catalog_xmin);
319 else
320 nulls[i++] = true;
321
322 if (XLogRecPtrIsValid(slot_contents.data.restart_lsn))
323 values[i++] = LSNGetDatum(slot_contents.data.restart_lsn);
324 else
325 nulls[i++] = true;
326
327 if (XLogRecPtrIsValid(slot_contents.data.confirmed_flush))
328 values[i++] = LSNGetDatum(slot_contents.data.confirmed_flush);
329 else
330 nulls[i++] = true;
331
332 /*
333 * If the slot has not been invalidated, test availability from
334 * restart_lsn.
335 */
336 if (slot_contents.data.invalidated != RS_INVAL_NONE)
337 walstate = WALAVAIL_REMOVED;
338 else
339 walstate = GetWALAvailability(slot_contents.data.restart_lsn);
340
341 switch (walstate)
342 {
344 nulls[i++] = true;
345 break;
346
348 values[i++] = CStringGetTextDatum("reserved");
349 break;
350
352 values[i++] = CStringGetTextDatum("extended");
353 break;
354
356 values[i++] = CStringGetTextDatum("unreserved");
357 break;
358
359 case WALAVAIL_REMOVED:
360
361 /*
362 * If we read the restart_lsn long enough ago, maybe that file
363 * has been removed by now. However, the walsender could have
364 * moved forward enough that it jumped to another file after
365 * we looked. If checkpointer signalled the process to
366 * termination, then it's definitely lost; but if a process is
367 * still alive, then "unreserved" seems more appropriate.
368 *
369 * If we do change it, save the state for safe_wal_size below.
370 */
371 if (XLogRecPtrIsValid(slot_contents.data.restart_lsn))
372 {
373 int pid;
374
375 SpinLockAcquire(&slot->mutex);
376 pid = slot->active_pid;
377 slot_contents.data.restart_lsn = slot->data.restart_lsn;
378 SpinLockRelease(&slot->mutex);
379 if (pid != 0)
380 {
381 values[i++] = CStringGetTextDatum("unreserved");
382 walstate = WALAVAIL_UNRESERVED;
383 break;
384 }
385 }
386 values[i++] = CStringGetTextDatum("lost");
387 break;
388 }
389
390 /*
391 * safe_wal_size is only computed for slots that have not been lost,
392 * and only if there's a configured maximum size.
393 */
394 if (walstate == WALAVAIL_REMOVED || max_slot_wal_keep_size_mb < 0)
395 nulls[i++] = true;
396 else
397 {
398 XLogSegNo targetSeg;
399 uint64 slotKeepSegs;
400 uint64 keepSegs;
401 XLogSegNo failSeg;
402 XLogRecPtr failLSN;
403
404 XLByteToSeg(slot_contents.data.restart_lsn, targetSeg, wal_segment_size);
405
406 /* determine how many segments can be kept by slots */
408 /* ditto for wal_keep_size */
410
411 /* if currpos reaches failLSN, we lose our segment */
412 failSeg = targetSeg + Max(slotKeepSegs, keepSegs) + 1;
413 XLogSegNoOffsetToRecPtr(failSeg, 0, wal_segment_size, failLSN);
414
415 values[i++] = Int64GetDatum(failLSN - currlsn);
416 }
417
418 values[i++] = BoolGetDatum(slot_contents.data.two_phase);
419
420 if (slot_contents.data.two_phase &&
421 XLogRecPtrIsValid(slot_contents.data.two_phase_at))
422 values[i++] = LSNGetDatum(slot_contents.data.two_phase_at);
423 else
424 nulls[i++] = true;
425
426 if (slot_contents.inactive_since > 0)
427 values[i++] = TimestampTzGetDatum(slot_contents.inactive_since);
428 else
429 nulls[i++] = true;
430
431 cause = slot_contents.data.invalidated;
432
433 if (SlotIsPhysical(&slot_contents))
434 nulls[i++] = true;
435 else
436 {
437 /*
438 * rows_removed and wal_level_insufficient are the only two
439 * reasons for the logical slot's conflict with recovery.
440 */
441 if (cause == RS_INVAL_HORIZON ||
442 cause == RS_INVAL_WAL_LEVEL)
443 values[i++] = BoolGetDatum(true);
444 else
445 values[i++] = BoolGetDatum(false);
446 }
447
448 if (cause == RS_INVAL_NONE)
449 nulls[i++] = true;
450 else
452
453 values[i++] = BoolGetDatum(slot_contents.data.failover);
454
455 values[i++] = BoolGetDatum(slot_contents.data.synced);
456
457 if (slot_contents.slotsync_skip_reason == SS_SKIP_NONE)
458 nulls[i++] = true;
459 else
461
463
464 tuplestore_putvalues(rsinfo->setResult, rsinfo->setDesc,
465 values, nulls);
466 }
467
468 LWLockRelease(ReplicationSlotControlLock);
469
470 return (Datum) 0;
471}
472
473/*
474 * Helper function for advancing our physical replication slot forward.
475 *
476 * The LSN position to move to is compared simply to the slot's restart_lsn,
477 * knowing that any position older than that would be removed by successive
478 * checkpoints.
479 */
480static XLogRecPtr
482{
484 XLogRecPtr retlsn = startlsn;
485
486 Assert(XLogRecPtrIsValid(moveto));
487
488 if (startlsn < moveto)
489 {
493 retlsn = moveto;
494
495 /*
496 * Dirty the slot so as it is written out at the next checkpoint. Note
497 * that the LSN position advanced may still be lost in the event of a
498 * crash, but this makes the data consistent after a clean shutdown.
499 */
501
502 /*
503 * Wake up logical walsenders holding logical failover slots after
504 * updating the restart_lsn of the physical slot.
505 */
507 }
508
509 return retlsn;
510}
511
512/*
513 * Advance our logical replication slot forward. See
514 * LogicalSlotAdvanceAndCheckSnapState for details.
515 */
516static XLogRecPtr
518{
519 return LogicalSlotAdvanceAndCheckSnapState(moveto, NULL);
520}
521
522/*
523 * SQL function for moving the position in a replication slot.
524 */
525Datum
527{
528 Name slotname = PG_GETARG_NAME(0);
529 XLogRecPtr moveto = PG_GETARG_LSN(1);
530 XLogRecPtr endlsn;
531 XLogRecPtr minlsn;
532 TupleDesc tupdesc;
533 Datum values[2];
534 bool nulls[2];
535 HeapTuple tuple;
536 Datum result;
537
539
541
542 if (!XLogRecPtrIsValid(moveto))
544 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
545 errmsg("invalid target WAL LSN")));
546
547 /* Build a tuple descriptor for our result type */
548 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
549 elog(ERROR, "return type must be a row type");
550
551 /*
552 * We can't move slot past what's been flushed/replayed so clamp the
553 * target position accordingly.
554 */
555 if (!RecoveryInProgress())
556 moveto = Min(moveto, GetFlushRecPtr(NULL));
557 else
558 moveto = Min(moveto, GetXLogReplayRecPtr(NULL));
559
560 /* Acquire the slot so we "own" it */
561 ReplicationSlotAcquire(NameStr(*slotname), true, true);
562
563 /* A slot whose restart_lsn has never been reserved cannot be advanced */
566 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
567 errmsg("replication slot \"%s\" cannot be advanced",
568 NameStr(*slotname)),
569 errdetail("This slot has never previously reserved WAL, or it has been invalidated.")));
570
571 /*
572 * Check if the slot is not moving backwards. Physical slots rely simply
573 * on restart_lsn as a minimum point, while logical slots have confirmed
574 * consumption up to confirmed_flush, meaning that in both cases data
575 * older than that is not available anymore.
576 */
579 else
581
582 if (moveto < minlsn)
584 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
585 errmsg("cannot advance replication slot to %X/%08X, minimum is %X/%08X",
586 LSN_FORMAT_ARGS(moveto), LSN_FORMAT_ARGS(minlsn))));
587
588 /* Do the actual slot update, depending on the slot type */
591 else
593
595 nulls[0] = false;
596
597 /*
598 * Recompute the minimum LSN and xmin across all slots to adjust with the
599 * advancing potentially done.
600 */
603
605
606 /* Return the reached position. */
607 values[1] = LSNGetDatum(endlsn);
608 nulls[1] = false;
609
610 tuple = heap_form_tuple(tupdesc, values, nulls);
611 result = HeapTupleGetDatum(tuple);
612
613 PG_RETURN_DATUM(result);
614}
615
616/*
617 * Helper function of copying a replication slot.
618 */
619static Datum
620copy_replication_slot(FunctionCallInfo fcinfo, bool logical_slot)
621{
622 Name src_name = PG_GETARG_NAME(0);
623 Name dst_name = PG_GETARG_NAME(1);
624 ReplicationSlot *src = NULL;
625 ReplicationSlot first_slot_contents;
626 ReplicationSlot second_slot_contents;
627 XLogRecPtr src_restart_lsn;
628 bool src_islogical;
629 bool temporary;
630 char *plugin;
631 Datum values[2];
632 bool nulls[2];
633 Datum result;
634 TupleDesc tupdesc;
635 HeapTuple tuple;
636
637 if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
638 elog(ERROR, "return type must be a row type");
639
641
642 if (logical_slot)
644 else
646
647 LWLockAcquire(ReplicationSlotControlLock, LW_SHARED);
648
649 /*
650 * We need to prevent the source slot's reserved WAL from being removed,
651 * but we don't want to lock that slot for very long, and it can advance
652 * in the meantime. So obtain the source slot's data, and create a new
653 * slot using its restart_lsn. Afterwards we lock the source slot again
654 * and verify that the data we copied (name, type) has not changed
655 * incompatibly. No inconvenient WAL removal can occur once the new slot
656 * is created -- but since WAL removal could have occurred before we
657 * managed to create the new slot, we advance the new slot's restart_lsn
658 * to the source slot's updated restart_lsn the second time we lock it.
659 */
660 for (int i = 0; i < max_replication_slots; i++)
661 {
663
664 if (s->in_use && strcmp(NameStr(s->data.name), NameStr(*src_name)) == 0)
665 {
666 /* Copy the slot contents while holding spinlock */
668 first_slot_contents = *s;
670 src = s;
671 break;
672 }
673 }
674
675 LWLockRelease(ReplicationSlotControlLock);
676
677 if (src == NULL)
679 (errcode(ERRCODE_UNDEFINED_OBJECT),
680 errmsg("replication slot \"%s\" does not exist", NameStr(*src_name))));
681
682 src_islogical = SlotIsLogical(&first_slot_contents);
683 src_restart_lsn = first_slot_contents.data.restart_lsn;
684 temporary = (first_slot_contents.data.persistency == RS_TEMPORARY);
685 plugin = logical_slot ? NameStr(first_slot_contents.data.plugin) : NULL;
686
687 /* Check type of replication slot */
688 if (src_islogical != logical_slot)
690 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
691 src_islogical ?
692 errmsg("cannot copy physical replication slot \"%s\" as a logical replication slot",
693 NameStr(*src_name)) :
694 errmsg("cannot copy logical replication slot \"%s\" as a physical replication slot",
695 NameStr(*src_name))));
696
697 /* Copying non-reserved slot doesn't make sense */
698 if (!XLogRecPtrIsValid(src_restart_lsn))
700 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
701 errmsg("cannot copy a replication slot that doesn't reserve WAL")));
702
703 /* Cannot copy an invalidated replication slot */
704 if (first_slot_contents.data.invalidated != RS_INVAL_NONE)
706 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
707 errmsg("cannot copy invalidated replication slot \"%s\"",
708 NameStr(*src_name)));
709
710 /* Overwrite params from optional arguments */
711 if (PG_NARGS() >= 3)
712 temporary = PG_GETARG_BOOL(2);
713 if (PG_NARGS() >= 4)
714 {
715 Assert(logical_slot);
717 }
718
719 /* Create new slot and acquire it */
720 if (logical_slot)
721 {
722 /*
723 * We must not try to read WAL, since we haven't reserved it yet --
724 * hence pass find_startpoint false. confirmed_flush will be set
725 * below, by copying from the source slot.
726 *
727 * We don't copy the failover option to prevent potential issues with
728 * slot synchronization. For instance, if a slot was synchronized to
729 * the standby, then dropped on the primary, and immediately recreated
730 * by copying from another existing slot with much earlier restart_lsn
731 * and confirmed_flush_lsn, the slot synchronization would only
732 * observe the LSN of the same slot moving backward. As slot
733 * synchronization does not copy the restart_lsn and
734 * confirmed_flush_lsn backward (see update_local_synced_slot() for
735 * details), if a failover happens before the primary's slot catches
736 * up, logical replication cannot continue using the synchronized slot
737 * on the promoted standby because the slot retains the restart_lsn
738 * and confirmed_flush_lsn that are much later than expected.
739 */
741 plugin,
742 temporary,
743 false,
744 false,
745 src_restart_lsn,
746 false);
747 }
748 else
750 true,
751 temporary,
752 src_restart_lsn);
753
754 /*
755 * Update the destination slot to current values of the source slot;
756 * recheck that the source slot is still the one we saw previously.
757 */
758 {
759 TransactionId copy_effective_xmin;
760 TransactionId copy_effective_catalog_xmin;
761 TransactionId copy_xmin;
762 TransactionId copy_catalog_xmin;
763 XLogRecPtr copy_restart_lsn;
764 XLogRecPtr copy_confirmed_flush;
765 bool copy_islogical;
766 char *copy_name;
767
768 /* Copy data of source slot again */
769 SpinLockAcquire(&src->mutex);
770 second_slot_contents = *src;
771 SpinLockRelease(&src->mutex);
772
773 copy_effective_xmin = second_slot_contents.effective_xmin;
774 copy_effective_catalog_xmin = second_slot_contents.effective_catalog_xmin;
775
776 copy_xmin = second_slot_contents.data.xmin;
777 copy_catalog_xmin = second_slot_contents.data.catalog_xmin;
778 copy_restart_lsn = second_slot_contents.data.restart_lsn;
779 copy_confirmed_flush = second_slot_contents.data.confirmed_flush;
780
781 /* for existence check */
782 copy_name = NameStr(second_slot_contents.data.name);
783 copy_islogical = SlotIsLogical(&second_slot_contents);
784
785 /*
786 * Check if the source slot still exists and is valid. We regard it as
787 * invalid if the type of replication slot or name has been changed,
788 * or the restart_lsn either is invalid or has gone backward. (The
789 * restart_lsn could go backwards if the source slot is dropped and
790 * copied from an older slot during installation.)
791 *
792 * Since erroring out will release and drop the destination slot we
793 * don't need to release it here.
794 */
795 if (copy_restart_lsn < src_restart_lsn ||
796 src_islogical != copy_islogical ||
797 strcmp(copy_name, NameStr(*src_name)) != 0)
799 (errmsg("could not copy replication slot \"%s\"",
800 NameStr(*src_name)),
801 errdetail("The source replication slot was modified incompatibly during the copy operation.")));
802
803 /* The source slot must have a consistent snapshot */
804 if (src_islogical && !XLogRecPtrIsValid(copy_confirmed_flush))
806 (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
807 errmsg("cannot copy unfinished logical replication slot \"%s\"",
808 NameStr(*src_name)),
809 errhint("Retry when the source replication slot's confirmed_flush_lsn is valid.")));
810
811 /*
812 * Copying an invalid slot doesn't make sense. Note that the source
813 * slot can become invalid after we create the new slot and copy the
814 * data of source slot. This is possible because the operations in
815 * InvalidateObsoleteReplicationSlots() are not serialized with this
816 * function. Even though we can't detect such a case here, the copied
817 * slot will become invalid in the next checkpoint cycle.
818 */
819 if (second_slot_contents.data.invalidated != RS_INVAL_NONE)
821 errmsg("cannot copy replication slot \"%s\"",
822 NameStr(*src_name)),
823 errdetail("The source replication slot was invalidated during the copy operation."));
824
825 /* Install copied values again */
827 MyReplicationSlot->effective_xmin = copy_effective_xmin;
828 MyReplicationSlot->effective_catalog_xmin = copy_effective_catalog_xmin;
829
830 MyReplicationSlot->data.xmin = copy_xmin;
831 MyReplicationSlot->data.catalog_xmin = copy_catalog_xmin;
832 MyReplicationSlot->data.restart_lsn = copy_restart_lsn;
833 MyReplicationSlot->data.confirmed_flush = copy_confirmed_flush;
835
840
841#ifdef USE_ASSERT_CHECKING
842 /* Check that the restart_lsn is available */
843 {
844 XLogSegNo segno;
845
846 XLByteToSeg(copy_restart_lsn, segno, wal_segment_size);
848 }
849#endif
850 }
851
852 /* target slot fully created, mark as persistent if needed */
853 if (logical_slot && !temporary)
855
856 /* All done. Set up the return values */
857 values[0] = NameGetDatum(dst_name);
858 nulls[0] = false;
860 {
862 nulls[1] = false;
863 }
864 else
865 nulls[1] = true;
866
867 tuple = heap_form_tuple(tupdesc, values, nulls);
868 result = HeapTupleGetDatum(tuple);
869
871
872 PG_RETURN_DATUM(result);
873}
874
875/* The wrappers below are all to appease opr_sanity */
876Datum
878{
879 return copy_replication_slot(fcinfo, true);
880}
881
882Datum
884{
885 return copy_replication_slot(fcinfo, true);
886}
887
888Datum
890{
891 return copy_replication_slot(fcinfo, true);
892}
893
894Datum
896{
897 return copy_replication_slot(fcinfo, false);
898}
899
900Datum
902{
903 return copy_replication_slot(fcinfo, false);
904}
905
906/*
907 * Synchronize failover enabled replication slots to a standby server
908 * from the primary server.
909 */
910Datum
912{
914 char *err;
915 StringInfoData app_name;
916
918
919 if (!RecoveryInProgress())
921 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
922 errmsg("replication slots can only be synchronized to a standby server"));
923
925
926 /* Load the libpq-specific functions */
927 load_file("libpqwalreceiver", false);
928
930
931 initStringInfo(&app_name);
932 if (cluster_name[0])
933 appendStringInfo(&app_name, "%s_slotsync", cluster_name);
934 else
935 appendStringInfoString(&app_name, "slotsync");
936
937 /* Connect to the primary server. */
938 wrconn = walrcv_connect(PrimaryConnInfo, false, false, false,
939 app_name.data, &err);
940
941 if (!wrconn)
943 errcode(ERRCODE_CONNECTION_FAILURE),
944 errmsg("synchronization worker \"%s\" could not connect to the primary server: %s",
945 app_name.data, err));
946
947 pfree(app_name.data);
948
950
952
954}
static Datum values[MAXATTR]
Definition: bootstrap.c:153
#define CStringGetTextDatum(s)
Definition: builtins.h:97
#define NameStr(name)
Definition: c.h:756
#define Min(x, y)
Definition: c.h:1008
#define Max(x, y)
Definition: c.h:1002
uint64_t uint64
Definition: c.h:544
uint32 TransactionId
Definition: c.h:662
#define OidIsValid(objectId)
Definition: c.h:779
void load_file(const char *filename, bool restricted)
Definition: dfmgr.c:149
int errdetail(const char *fmt,...)
Definition: elog.c:1216
int errhint(const char *fmt,...)
Definition: elog.c:1330
int errcode(int sqlerrcode)
Definition: elog.c:863
int errmsg(const char *fmt,...)
Definition: elog.c:1080
#define ERROR
Definition: elog.h:39
#define elog(elevel,...)
Definition: elog.h:226
#define ereport(elevel,...)
Definition: elog.h:150
void err(int eval, const char *fmt,...)
Definition: err.c:43
#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:555
Assert(PointerIsAligned(start, uint64))
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, const Datum *values, const bool *isnull)
Definition: heaptuple.c:1117
int i
Definition: isn.c:77
XLogRecPtr LogicalSlotAdvanceAndCheckSnapState(XLogRecPtr moveto, bool *found_consistent_snapshot)
Definition: logical.c:2085
void FreeDecodingContext(LogicalDecodingContext *ctx)
Definition: logical.c:677
void DecodingContextFindStartpoint(LogicalDecodingContext *ctx)
Definition: logical.c:633
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:332
void CheckLogicalDecodingRequirements(void)
Definition: logical.c:111
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1174
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1894
@ LW_SHARED
Definition: lwlock.h:113
void pfree(void *pointer)
Definition: mcxt.c:1594
#define NIL
Definition: pg_list.h:68
#define PG_GETARG_LSN(n)
Definition: pg_lsn.h:36
static Datum LSNGetDatum(XLogRecPtr X)
Definition: pg_lsn.h:31
static bool two_phase
static bool failover
static const char * plugin
static Datum Int64GetDatum(int64 X)
Definition: postgres.h:403
static Datum TransactionIdGetDatum(TransactionId X)
Definition: postgres.h:282
static Datum BoolGetDatum(bool X)
Definition: postgres.h:112
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:262
static Datum NameGetDatum(const NameData *X)
Definition: postgres.h:383
uint64_t Datum
Definition: postgres.h:70
static Datum Int32GetDatum(int32 X)
Definition: postgres.h:222
#define InvalidOid
Definition: postgres_ext.h:37
void ReplicationSlotAcquire(const char *name, bool nowait, bool error_if_invalid)
Definition: slot.c:626
void ReplicationSlotCreate(const char *name, bool db_specific, ReplicationSlotPersistency persistency, bool two_phase, bool failover, bool synced)
Definition: slot.c:384
void ReplicationSlotMarkDirty(void)
Definition: slot.c:1139
void ReplicationSlotReserveWal(void)
Definition: slot.c:1572
void ReplicationSlotsComputeRequiredXmin(bool already_locked)
Definition: slot.c:1178
void ReplicationSlotPersist(void)
Definition: slot.c:1156
ReplicationSlot * MyReplicationSlot
Definition: slot.c:148
void ReplicationSlotDrop(const char *name, bool nowait)
Definition: slot.c:892
void ReplicationSlotSave(void)
Definition: slot.c:1121
void CheckSlotPermissions(void)
Definition: slot.c:1555
void ReplicationSlotRelease(void)
Definition: slot.c:764
int max_replication_slots
Definition: slot.c:151
ReplicationSlotCtlData * ReplicationSlotCtl
Definition: slot.c:145
void ReplicationSlotsComputeRequiredLSN(void)
Definition: slot.c:1234
void CheckSlotRequirements(void)
Definition: slot.c:1533
const char * GetSlotInvalidationCauseName(ReplicationSlotInvalidationCause cause)
Definition: slot.c:2745
@ RS_PERSISTENT
Definition: slot.h:45
@ RS_EPHEMERAL
Definition: slot.h:46
@ RS_TEMPORARY
Definition: slot.h:47
#define SlotIsPhysical(slot)
Definition: slot.h:284
ReplicationSlotInvalidationCause
Definition: slot.h:59
@ RS_INVAL_HORIZON
Definition: slot.h:64
@ RS_INVAL_WAL_LEVEL
Definition: slot.h:66
@ RS_INVAL_NONE
Definition: slot.h:60
#define SlotIsLogical(slot)
Definition: slot.h:285
@ SS_SKIP_WAL_NOT_FLUSHED
Definition: slot.h:83
@ SS_SKIP_NO_CONSISTENT_SNAPSHOT
Definition: slot.h:87
@ SS_SKIP_NONE
Definition: slot.h:82
@ SS_SKIP_INVALID
Definition: slot.h:89
@ SS_SKIP_WAL_OR_ROWS_REMOVED
Definition: slot.h:85
Datum pg_get_replication_slots(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:247
Datum pg_copy_physical_replication_slot_a(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:895
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:128
Datum pg_create_logical_replication_slot(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:180
#define PG_GET_REPLICATION_SLOTS_COLS
static Datum copy_replication_slot(FunctionCallInfo fcinfo, bool logical_slot)
Definition: slotfuncs.c:620
Datum pg_copy_logical_replication_slot_c(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:889
Datum pg_create_physical_replication_slot(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:76
Datum pg_copy_logical_replication_slot_a(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:877
Datum pg_copy_physical_replication_slot_b(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:901
static const char * SlotSyncSkipReasonNames[]
Definition: slotfuncs.c:30
Datum pg_sync_replication_slots(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:911
Datum pg_copy_logical_replication_slot_b(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:883
static XLogRecPtr pg_logical_replication_slot_advance(XLogRecPtr moveto)
Definition: slotfuncs.c:517
static XLogRecPtr pg_physical_replication_slot_advance(XLogRecPtr moveto)
Definition: slotfuncs.c:481
Datum pg_replication_slot_advance(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:526
static void create_physical_replication_slot(char *name, bool immediately_reserve, bool temporary, XLogRecPtr restart_lsn)
Definition: slotfuncs.c:47
Datum pg_drop_replication_slot(PG_FUNCTION_ARGS)
Definition: slotfuncs.c:229
void SyncReplicationSlots(WalReceiverConn *wrconn)
Definition: slotsync.c:1829
char * CheckAndGetDbnameFromConninfo(void)
Definition: slotsync.c:1110
bool ValidateSlotSyncParams(int elevel)
Definition: slotsync.c:1137
#define SpinLockRelease(lock)
Definition: spin.h:61
#define SpinLockAcquire(lock)
Definition: spin.h:59
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:145
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:230
void initStringInfo(StringInfo str)
Definition: stringinfo.c:97
ReplicationSlot replication_slots[1]
Definition: slot.h:296
TransactionId xmin
Definition: slot.h:114
TransactionId catalog_xmin
Definition: slot.h:122
XLogRecPtr confirmed_flush
Definition: slot.h:136
ReplicationSlotPersistency persistency
Definition: slot.h:106
ReplicationSlotInvalidationCause invalidated
Definition: slot.h:128
TransactionId effective_catalog_xmin
Definition: slot.h:207
slock_t mutex
Definition: slot.h:183
pid_t active_pid
Definition: slot.h:189
SlotSyncSkipReason slotsync_skip_reason
Definition: slot.h:281
bool in_use
Definition: slot.h:186
TransactionId effective_xmin
Definition: slot.h:206
ReplicationSlotPersistentData data
Definition: slot.h:210
TimestampTz inactive_since
Definition: slot.h:242
TupleDesc setDesc
Definition: execnodes.h:364
Tuplestorestate * setResult
Definition: execnodes.h:363
Definition: c.h:751
#define InvalidTransactionId
Definition: transam.h:31
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, const Datum *values, const bool *isnull)
Definition: tuplestore.c:784
static Datum TimestampTzGetDatum(TimestampTz X)
Definition: timestamp.h:52
const char * name
static WalReceiverConn * wrconn
Definition: walreceiver.c:93
#define walrcv_connect(conninfo, replication, logical, must_use_password, appname, err)
Definition: walreceiver.h:435
#define walrcv_disconnect(conn)
Definition: walreceiver.h:467
void PhysicalWakeupLogicalWalSnd(void)
Definition: walsender.c:1732
bool RecoveryInProgress(void)
Definition: xlog.c:6406
XLogSegNo XLogGetLastRemovedSegno(void)
Definition: xlog.c:3777
int wal_keep_size_mb
Definition: xlog.c:118
int wal_segment_size
Definition: xlog.c:145
WALAvailability GetWALAvailability(XLogRecPtr targetLSN)
Definition: xlog.c:7937
int max_slot_wal_keep_size_mb
Definition: xlog.c:137
XLogRecPtr GetFlushRecPtr(TimeLineID *insertTLI)
Definition: xlog.c:6571
XLogRecPtr GetXLogWriteRecPtr(void)
Definition: xlog.c:9515
WALAvailability
Definition: xlog.h:188
@ WALAVAIL_REMOVED
Definition: xlog.h:194
@ WALAVAIL_RESERVED
Definition: xlog.h:190
@ WALAVAIL_UNRESERVED
Definition: xlog.h:193
@ WALAVAIL_EXTENDED
Definition: xlog.h:191
@ WALAVAIL_INVALID_LSN
Definition: xlog.h:189
#define XLogSegNoOffsetToRecPtr(segno, offset, wal_segsz_bytes, dest)
#define XLogMBVarToSegs(mbvar, wal_segsz_bytes)
#define XLByteToSeg(xlrp, logSegNo, wal_segsz_bytes)
#define XLogRecPtrIsValid(r)
Definition: xlogdefs.h:29
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:47
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
uint64 XLogSegNo
Definition: xlogdefs.h:52
#define XL_ROUTINE(...)
Definition: xlogreader.h:117
XLogRecPtr GetXLogReplayRecPtr(TimeLineID *replayTLI)
char * PrimaryConnInfo
Definition: xlogrecovery.c:99
void wal_segment_close(XLogReaderState *state)
Definition: xlogutils.c:831
void wal_segment_open(XLogReaderState *state, XLogSegNo nextSegNo, TimeLineID *tli_p)
Definition: xlogutils.c:806
int read_local_xlog_page(XLogReaderState *state, XLogRecPtr targetPagePtr, int reqLen, XLogRecPtr targetRecPtr, char *cur_page)
Definition: xlogutils.c:845