PostgreSQL Source Code  git master
origin.h File Reference
Include dependency graph for origin.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  xl_replorigin_set
 
struct  xl_replorigin_drop
 

Macros

#define XLOG_REPLORIGIN_SET   0x00
 
#define XLOG_REPLORIGIN_DROP   0x10
 
#define InvalidRepOriginId   0
 
#define DoNotReplicateId   PG_UINT16_MAX
 

Typedefs

typedef struct xl_replorigin_set xl_replorigin_set
 
typedef struct xl_replorigin_drop xl_replorigin_drop
 

Functions

RepOriginId replorigin_by_name (const char *roname, bool missing_ok)
 
RepOriginId replorigin_create (const char *roname)
 
void replorigin_drop_by_name (const char *name, bool missing_ok, bool nowait)
 
bool replorigin_by_oid (RepOriginId roident, bool missing_ok, char **roname)
 
void replorigin_advance (RepOriginId node, XLogRecPtr remote_commit, XLogRecPtr local_commit, bool go_backward, bool wal_log)
 
XLogRecPtr replorigin_get_progress (RepOriginId node, bool flush)
 
void replorigin_session_advance (XLogRecPtr remote_commit, XLogRecPtr local_commit)
 
void replorigin_session_setup (RepOriginId node)
 
void replorigin_session_reset (void)
 
XLogRecPtr replorigin_session_get_progress (bool flush)
 
void CheckPointReplicationOrigin (void)
 
void StartupReplicationOrigin (void)
 
void replorigin_redo (XLogReaderState *record)
 
void replorigin_desc (StringInfo buf, XLogReaderState *record)
 
const char * replorigin_identify (uint8 info)
 
Size ReplicationOriginShmemSize (void)
 
void ReplicationOriginShmemInit (void)
 

Variables

PGDLLIMPORT RepOriginId replorigin_session_origin
 
PGDLLIMPORT XLogRecPtr replorigin_session_origin_lsn
 
PGDLLIMPORT TimestampTz replorigin_session_origin_timestamp
 

Macro Definition Documentation

◆ DoNotReplicateId

#define DoNotReplicateId   PG_UINT16_MAX

Definition at line 34 of file origin.h.

◆ InvalidRepOriginId

#define InvalidRepOriginId   0

Definition at line 33 of file origin.h.

◆ XLOG_REPLORIGIN_DROP

#define XLOG_REPLORIGIN_DROP   0x10

Definition at line 31 of file origin.h.

◆ XLOG_REPLORIGIN_SET

#define XLOG_REPLORIGIN_SET   0x00

Definition at line 30 of file origin.h.

Typedef Documentation

◆ xl_replorigin_drop

◆ xl_replorigin_set

Function Documentation

◆ CheckPointReplicationOrigin()

void CheckPointReplicationOrigin ( void  )

Definition at line 569 of file origin.c.

570 {
571  const char *tmppath = "pg_logical/replorigin_checkpoint.tmp";
572  const char *path = "pg_logical/replorigin_checkpoint";
573  int tmpfd;
574  int i;
576  pg_crc32c crc;
577 
578  if (max_replication_slots == 0)
579  return;
580 
581  INIT_CRC32C(crc);
582 
583  /* make sure no old temp file is remaining */
584  if (unlink(tmppath) < 0 && errno != ENOENT)
585  ereport(PANIC,
587  errmsg("could not remove file \"%s\": %m",
588  tmppath)));
589 
590  /*
591  * no other backend can perform this at the same time; only one checkpoint
592  * can happen at a time.
593  */
594  tmpfd = OpenTransientFile(tmppath,
595  O_CREAT | O_EXCL | O_WRONLY | PG_BINARY);
596  if (tmpfd < 0)
597  ereport(PANIC,
599  errmsg("could not create file \"%s\": %m",
600  tmppath)));
601 
602  /* write magic */
603  errno = 0;
604  if ((write(tmpfd, &magic, sizeof(magic))) != sizeof(magic))
605  {
606  /* if write didn't set errno, assume problem is no disk space */
607  if (errno == 0)
608  errno = ENOSPC;
609  ereport(PANIC,
611  errmsg("could not write to file \"%s\": %m",
612  tmppath)));
613  }
614  COMP_CRC32C(crc, &magic, sizeof(magic));
615 
616  /* prevent concurrent creations/drops */
617  LWLockAcquire(ReplicationOriginLock, LW_SHARED);
618 
619  /* write actual data */
620  for (i = 0; i < max_replication_slots; i++)
621  {
622  ReplicationStateOnDisk disk_state;
623  ReplicationState *curstate = &replication_states[i];
624  XLogRecPtr local_lsn;
625 
626  if (curstate->roident == InvalidRepOriginId)
627  continue;
628 
629  /* zero, to avoid uninitialized padding bytes */
630  memset(&disk_state, 0, sizeof(disk_state));
631 
632  LWLockAcquire(&curstate->lock, LW_SHARED);
633 
634  disk_state.roident = curstate->roident;
635 
636  disk_state.remote_lsn = curstate->remote_lsn;
637  local_lsn = curstate->local_lsn;
638 
639  LWLockRelease(&curstate->lock);
640 
641  /* make sure we only write out a commit that's persistent */
642  XLogFlush(local_lsn);
643 
644  errno = 0;
645  if ((write(tmpfd, &disk_state, sizeof(disk_state))) !=
646  sizeof(disk_state))
647  {
648  /* if write didn't set errno, assume problem is no disk space */
649  if (errno == 0)
650  errno = ENOSPC;
651  ereport(PANIC,
653  errmsg("could not write to file \"%s\": %m",
654  tmppath)));
655  }
656 
657  COMP_CRC32C(crc, &disk_state, sizeof(disk_state));
658  }
659 
660  LWLockRelease(ReplicationOriginLock);
661 
662  /* write out the CRC */
663  FIN_CRC32C(crc);
664  errno = 0;
665  if ((write(tmpfd, &crc, sizeof(crc))) != sizeof(crc))
666  {
667  /* if write didn't set errno, assume problem is no disk space */
668  if (errno == 0)
669  errno = ENOSPC;
670  ereport(PANIC,
672  errmsg("could not write to file \"%s\": %m",
673  tmppath)));
674  }
675 
676  if (CloseTransientFile(tmpfd) != 0)
677  ereport(PANIC,
679  errmsg("could not close file \"%s\": %m",
680  tmppath)));
681 
682  /* fsync, rename to permanent file, fsync file and directory */
683  durable_rename(tmppath, path, PANIC);
684 }
unsigned int uint32
Definition: c.h:442
#define PG_BINARY
Definition: c.h:1209
int errcode_for_file_access(void)
Definition: elog.c:758
int errmsg(const char *fmt,...)
Definition: elog.c:946
#define PANIC
Definition: elog.h:38
#define ereport(elevel,...)
Definition: elog.h:145
int durable_rename(const char *oldfile, const char *newfile, int elevel)
Definition: fd.c:688
int CloseTransientFile(int fd)
Definition: fd.c:2609
int OpenTransientFile(const char *fileName, int fileFlags)
Definition: fd.c:2433
#define write(a, b, c)
Definition: win32.h:14
int i
Definition: isn.c:73
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1194
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1802
@ LW_SHARED
Definition: lwlock.h:113
static ReplicationState * replication_states
Definition: origin.c:167
#define REPLICATION_STATE_MAGIC
Definition: origin.c:182
#define InvalidRepOriginId
Definition: origin.h:33
uint32 pg_crc32c
Definition: pg_crc32c.h:38
#define COMP_CRC32C(crc, data, len)
Definition: pg_crc32c.h:89
#define INIT_CRC32C(crc)
Definition: pg_crc32c.h:41
#define FIN_CRC32C(crc)
Definition: pg_crc32c.h:94
return crc
int max_replication_slots
Definition: slot.c:101
XLogRecPtr remote_lsn
Definition: origin.c:143
RepOriginId roident
Definition: origin.c:142
XLogRecPtr remote_lsn
Definition: origin.c:112
XLogRecPtr local_lsn
Definition: origin.c:119
RepOriginId roident
Definition: origin.c:107
LWLock lock
Definition: origin.c:134
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2512
uint64 XLogRecPtr
Definition: xlogdefs.h:21

References CloseTransientFile(), COMP_CRC32C, crc, durable_rename(), ereport, errcode_for_file_access(), errmsg(), FIN_CRC32C, i, INIT_CRC32C, InvalidRepOriginId, ReplicationState::local_lsn, ReplicationState::lock, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_replication_slots, OpenTransientFile(), PANIC, PG_BINARY, ReplicationState::remote_lsn, ReplicationStateOnDisk::remote_lsn, REPLICATION_STATE_MAGIC, replication_states, ReplicationState::roident, ReplicationStateOnDisk::roident, write, and XLogFlush().

Referenced by CheckPointGuts().

◆ ReplicationOriginShmemInit()

void ReplicationOriginShmemInit ( void  )

Definition at line 522 of file origin.c.

523 {
524  bool found;
525 
526  if (max_replication_slots == 0)
527  return;
528 
530  ShmemInitStruct("ReplicationOriginState",
532  &found);
534 
535  if (!found)
536  {
537  int i;
538 
540 
542 
543  for (i = 0; i < max_replication_slots; i++)
544  {
548  }
549  }
550 }
#define MemSet(start, val, len)
Definition: c.h:953
void ConditionVariableInit(ConditionVariable *cv)
void LWLockInitialize(LWLock *lock, int tranche_id)
Definition: lwlock.c:729
@ LWTRANCHE_REPLICATION_ORIGIN_STATE
Definition: lwlock.h:186
static ReplicationStateCtl * replication_states_ctl
Definition: origin.c:172
Size ReplicationOriginShmemSize(void)
Definition: origin.c:502
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:396
ReplicationState states[FLEXIBLE_ARRAY_MEMBER]
Definition: origin.c:152

References ConditionVariableInit(), i, LWLockInitialize(), LWTRANCHE_REPLICATION_ORIGIN_STATE, max_replication_slots, MemSet, replication_states, replication_states_ctl, ReplicationOriginShmemSize(), ShmemInitStruct(), ReplicationStateCtl::states, and ReplicationStateCtl::tranche_id.

Referenced by CreateSharedMemoryAndSemaphores().

◆ ReplicationOriginShmemSize()

Size ReplicationOriginShmemSize ( void  )

Definition at line 502 of file origin.c.

503 {
504  Size size = 0;
505 
506  /*
507  * XXX: max_replication_slots is arguably the wrong thing to use, as here
508  * we keep the replay state of *remote* transactions. But for now it seems
509  * sufficient to reuse it, rather than introduce a separate GUC.
510  */
511  if (max_replication_slots == 0)
512  return size;
513 
514  size = add_size(size, offsetof(ReplicationStateCtl, states));
515 
516  size = add_size(size,
518  return size;
519 }
size_t Size
Definition: c.h:541
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519

References add_size(), max_replication_slots, and mul_size().

Referenced by CalculateShmemSize(), and ReplicationOriginShmemInit().

◆ replorigin_advance()

void replorigin_advance ( RepOriginId  node,
XLogRecPtr  remote_commit,
XLogRecPtr  local_commit,
bool  go_backward,
bool  wal_log 
)

Definition at line 884 of file origin.c.

887 {
888  int i;
889  ReplicationState *replication_state = NULL;
890  ReplicationState *free_state = NULL;
891 
892  Assert(node != InvalidRepOriginId);
893 
894  /* we don't track DoNotReplicateId */
895  if (node == DoNotReplicateId)
896  return;
897 
898  /*
899  * XXX: For the case where this is called by WAL replay, it'd be more
900  * efficient to restore into a backend local hashtable and only dump into
901  * shmem after recovery is finished. Let's wait with implementing that
902  * till it's shown to be a measurable expense
903  */
904 
905  /* Lock exclusively, as we may have to create a new table entry. */
906  LWLockAcquire(ReplicationOriginLock, LW_EXCLUSIVE);
907 
908  /*
909  * Search for either an existing slot for the origin, or a free one we can
910  * use.
911  */
912  for (i = 0; i < max_replication_slots; i++)
913  {
914  ReplicationState *curstate = &replication_states[i];
915 
916  /* remember where to insert if necessary */
917  if (curstate->roident == InvalidRepOriginId &&
918  free_state == NULL)
919  {
920  free_state = curstate;
921  continue;
922  }
923 
924  /* not our slot */
925  if (curstate->roident != node)
926  {
927  continue;
928  }
929 
930  /* ok, found slot */
931  replication_state = curstate;
932 
933  LWLockAcquire(&replication_state->lock, LW_EXCLUSIVE);
934 
935  /* Make sure it's not used by somebody else */
936  if (replication_state->acquired_by != 0)
937  {
938  ereport(ERROR,
939  (errcode(ERRCODE_OBJECT_IN_USE),
940  errmsg("replication origin with ID %d is already active for PID %d",
941  replication_state->roident,
942  replication_state->acquired_by)));
943  }
944 
945  break;
946  }
947 
948  if (replication_state == NULL && free_state == NULL)
949  ereport(ERROR,
950  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
951  errmsg("could not find free replication state slot for replication origin with ID %d",
952  node),
953  errhint("Increase max_replication_slots and try again.")));
954 
955  if (replication_state == NULL)
956  {
957  /* initialize new slot */
958  LWLockAcquire(&free_state->lock, LW_EXCLUSIVE);
959  replication_state = free_state;
960  Assert(replication_state->remote_lsn == InvalidXLogRecPtr);
961  Assert(replication_state->local_lsn == InvalidXLogRecPtr);
962  replication_state->roident = node;
963  }
964 
965  Assert(replication_state->roident != InvalidRepOriginId);
966 
967  /*
968  * If somebody "forcefully" sets this slot, WAL log it, so it's durable
969  * and the standby gets the message. Primarily this will be called during
970  * WAL replay (of commit records) where no WAL logging is necessary.
971  */
972  if (wal_log)
973  {
974  xl_replorigin_set xlrec;
975 
976  xlrec.remote_lsn = remote_commit;
977  xlrec.node_id = node;
978  xlrec.force = go_backward;
979 
980  XLogBeginInsert();
981  XLogRegisterData((char *) (&xlrec), sizeof(xlrec));
982 
983  XLogInsert(RM_REPLORIGIN_ID, XLOG_REPLORIGIN_SET);
984  }
985 
986  /*
987  * Due to - harmless - race conditions during a checkpoint we could see
988  * values here that are older than the ones we already have in memory. We
989  * could also see older values for prepared transactions when the prepare
990  * is sent at a later point of time along with commit prepared and there
991  * are other transactions commits between prepare and commit prepared. See
992  * ReorderBufferFinishPrepared. Don't overwrite those.
993  */
994  if (go_backward || replication_state->remote_lsn < remote_commit)
995  replication_state->remote_lsn = remote_commit;
996  if (local_commit != InvalidXLogRecPtr &&
997  (go_backward || replication_state->local_lsn < local_commit))
998  replication_state->local_lsn = local_commit;
999  LWLockRelease(&replication_state->lock);
1000 
1001  /*
1002  * Release *after* changing the LSNs, slot isn't acquired and thus could
1003  * otherwise be dropped anytime.
1004  */
1005  LWLockRelease(ReplicationOriginLock);
1006 }
int errhint(const char *fmt,...)
Definition: elog.c:1193
int errcode(int sqlerrcode)
Definition: elog.c:735
#define ERROR
Definition: elog.h:35
Assert(fmt[strlen(fmt) - 1] !='\n')
@ LW_EXCLUSIVE
Definition: lwlock.h:112
#define DoNotReplicateId
Definition: origin.h:34
#define XLOG_REPLORIGIN_SET
Definition: origin.h:30
RepOriginId node_id
Definition: origin.h:21
XLogRecPtr remote_lsn
Definition: origin.h:20
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
void XLogRegisterData(char *data, uint32 len)
Definition: xloginsert.c:351
XLogRecPtr XLogInsert(RmgrId rmid, uint8 info)
Definition: xloginsert.c:451
void XLogBeginInsert(void)
Definition: xloginsert.c:150

References ReplicationState::acquired_by, Assert(), DoNotReplicateId, ereport, errcode(), errhint(), errmsg(), ERROR, xl_replorigin_set::force, i, InvalidRepOriginId, InvalidXLogRecPtr, ReplicationState::local_lsn, ReplicationState::lock, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), max_replication_slots, xl_replorigin_set::node_id, ReplicationState::remote_lsn, xl_replorigin_set::remote_lsn, replication_states, ReplicationState::roident, XLOG_REPLORIGIN_SET, XLogBeginInsert(), XLogInsert(), and XLogRegisterData().

Referenced by LogicalRepSyncTableStart(), pg_replication_origin_advance(), PrepareRedoAdd(), replorigin_redo(), xact_redo_abort(), and xact_redo_commit().

◆ replorigin_by_name()

RepOriginId replorigin_by_name ( const char *  roname,
bool  missing_ok 
)

Definition at line 221 of file origin.c.

222 {
224  Oid roident = InvalidOid;
225  HeapTuple tuple;
226  Datum roname_d;
227 
228  roname_d = CStringGetTextDatum(roname);
229 
230  tuple = SearchSysCache1(REPLORIGNAME, roname_d);
231  if (HeapTupleIsValid(tuple))
232  {
233  ident = (Form_pg_replication_origin) GETSTRUCT(tuple);
234  roident = ident->roident;
235  ReleaseSysCache(tuple);
236  }
237  else if (!missing_ok)
238  ereport(ERROR,
239  (errcode(ERRCODE_UNDEFINED_OBJECT),
240  errmsg("replication origin \"%s\" does not exist",
241  roname)));
242 
243  return roident;
244 }
#define CStringGetTextDatum(s)
Definition: builtins.h:85
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
#define GETSTRUCT(TUP)
Definition: htup_details.h:649
FormData_pg_replication_origin * Form_pg_replication_origin
uintptr_t Datum
Definition: postgres.h:412
#define InvalidOid
Definition: postgres_ext.h:36
unsigned int Oid
Definition: postgres_ext.h:31
void ReleaseSysCache(HeapTuple tuple)
Definition: syscache.c:1221
HeapTuple SearchSysCache1(int cacheId, Datum key1)
Definition: syscache.c:1173
@ REPLORIGNAME
Definition: syscache.h:91

References CStringGetTextDatum, ereport, errcode(), errmsg(), ERROR, GETSTRUCT, HeapTupleIsValid, InvalidOid, ReleaseSysCache(), REPLORIGNAME, and SearchSysCache1().

Referenced by AlterSubscription(), ApplyWorkerMain(), LogicalRepSyncTableStart(), pg_replication_origin_advance(), pg_replication_origin_oid(), pg_replication_origin_progress(), pg_replication_origin_session_setup(), and replorigin_drop_by_name().

◆ replorigin_by_oid()

bool replorigin_by_oid ( RepOriginId  roident,
bool  missing_ok,
char **  roname 
)

Definition at line 461 of file origin.c.

462 {
463  HeapTuple tuple;
465 
466  Assert(OidIsValid((Oid) roident));
467  Assert(roident != InvalidRepOriginId);
468  Assert(roident != DoNotReplicateId);
469 
471  ObjectIdGetDatum((Oid) roident));
472 
473  if (HeapTupleIsValid(tuple))
474  {
475  ric = (Form_pg_replication_origin) GETSTRUCT(tuple);
476  *roname = text_to_cstring(&ric->roname);
477  ReleaseSysCache(tuple);
478 
479  return true;
480  }
481  else
482  {
483  *roname = NULL;
484 
485  if (!missing_ok)
486  ereport(ERROR,
487  (errcode(ERRCODE_UNDEFINED_OBJECT),
488  errmsg("replication origin with ID %d does not exist",
489  roident)));
490 
491  return false;
492  }
493 }
#define OidIsValid(objectId)
Definition: c.h:711
static Datum ObjectIdGetDatum(Oid X)
Definition: postgres.h:600
@ REPLORIGIDENT
Definition: syscache.h:90
char * text_to_cstring(const text *t)
Definition: varlena.c:222

References Assert(), DoNotReplicateId, ereport, errcode(), errmsg(), ERROR, GETSTRUCT, HeapTupleIsValid, InvalidRepOriginId, ObjectIdGetDatum(), OidIsValid, ReleaseSysCache(), REPLORIGIDENT, SearchSysCache1(), and text_to_cstring().

Referenced by pg_show_replication_origin_status(), and send_repl_origin().

◆ replorigin_create()

RepOriginId replorigin_create ( const char *  roname)

Definition at line 252 of file origin.c.

253 {
254  Oid roident;
255  HeapTuple tuple = NULL;
256  Relation rel;
257  Datum roname_d;
258  SnapshotData SnapshotDirty;
259  SysScanDesc scan;
261 
262  roname_d = CStringGetTextDatum(roname);
263 
265 
266  /*
267  * We need the numeric replication origin to be 16bit wide, so we cannot
268  * rely on the normal oid allocation. Instead we simply scan
269  * pg_replication_origin for the first unused id. That's not particularly
270  * efficient, but this should be a fairly infrequent operation - we can
271  * easily spend a bit more code on this when it turns out it needs to be
272  * faster.
273  *
274  * We handle concurrency by taking an exclusive lock (allowing reads!)
275  * over the table for the duration of the search. Because we use a "dirty
276  * snapshot" we can read rows that other in-progress sessions have
277  * written, even though they would be invisible with normal snapshots. Due
278  * to the exclusive lock there's no danger that new rows can appear while
279  * we're checking.
280  */
281  InitDirtySnapshot(SnapshotDirty);
282 
283  rel = table_open(ReplicationOriginRelationId, ExclusiveLock);
284 
285  for (roident = InvalidOid + 1; roident < PG_UINT16_MAX; roident++)
286  {
287  bool nulls[Natts_pg_replication_origin];
288  Datum values[Natts_pg_replication_origin];
289  bool collides;
290 
292 
293  ScanKeyInit(&key,
294  Anum_pg_replication_origin_roident,
295  BTEqualStrategyNumber, F_OIDEQ,
296  ObjectIdGetDatum(roident));
297 
298  scan = systable_beginscan(rel, ReplicationOriginIdentIndex,
299  true /* indexOK */ ,
300  &SnapshotDirty,
301  1, &key);
302 
303  collides = HeapTupleIsValid(systable_getnext(scan));
304 
305  systable_endscan(scan);
306 
307  if (!collides)
308  {
309  /*
310  * Ok, found an unused roident, insert the new row and do a CCI,
311  * so our callers can look it up if they want to.
312  */
313  memset(&nulls, 0, sizeof(nulls));
314 
315  values[Anum_pg_replication_origin_roident - 1] = ObjectIdGetDatum(roident);
316  values[Anum_pg_replication_origin_roname - 1] = roname_d;
317 
318  tuple = heap_form_tuple(RelationGetDescr(rel), values, nulls);
319  CatalogTupleInsert(rel, tuple);
321  break;
322  }
323  }
324 
325  /* now release lock again, */
327 
328  if (tuple == NULL)
329  ereport(ERROR,
330  (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
331  errmsg("could not find free replication origin ID")));
332 
333  heap_freetuple(tuple);
334  return roident;
335 }
static Datum values[MAXATTR]
Definition: bootstrap.c:156
#define PG_UINT16_MAX
Definition: c.h:523
void systable_endscan(SysScanDesc sysscan)
Definition: genam.c:599
HeapTuple systable_getnext(SysScanDesc sysscan)
Definition: genam.c:506
SysScanDesc systable_beginscan(Relation heapRelation, Oid indexId, bool indexOK, Snapshot snapshot, int nkeys, ScanKey key)
Definition: genam.c:387
HeapTuple heap_form_tuple(TupleDesc tupleDescriptor, Datum *values, bool *isnull)
Definition: heaptuple.c:1020
void heap_freetuple(HeapTuple htup)
Definition: heaptuple.c:1338
void CatalogTupleInsert(Relation heapRel, HeapTuple tup)
Definition: indexing.c:221
#define ExclusiveLock
Definition: lockdefs.h:42
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:121
#define RelationGetDescr(relation)
Definition: rel.h:527
void ScanKeyInit(ScanKey entry, AttrNumber attributeNumber, StrategyNumber strategy, RegProcedure procedure, Datum argument)
Definition: scankey.c:76
#define InitDirtySnapshot(snapshotdata)
Definition: snapmgr.h:74
#define BTEqualStrategyNumber
Definition: stratnum.h:31
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:126
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:40
bool IsTransactionState(void)
Definition: xact.c:377
void CommandCounterIncrement(void)
Definition: xact.c:1077

References Assert(), BTEqualStrategyNumber, CatalogTupleInsert(), CHECK_FOR_INTERRUPTS, CommandCounterIncrement(), CStringGetTextDatum, ereport, errcode(), errmsg(), ERROR, ExclusiveLock, heap_form_tuple(), heap_freetuple(), HeapTupleIsValid, InitDirtySnapshot, InvalidOid, IsTransactionState(), sort-test::key, ObjectIdGetDatum(), PG_UINT16_MAX, RelationGetDescr, ScanKeyInit(), systable_beginscan(), systable_endscan(), systable_getnext(), table_close(), table_open(), and values.

Referenced by ApplyWorkerMain(), CreateSubscription(), LogicalRepSyncTableStart(), and pg_replication_origin_create().

◆ replorigin_desc()

void replorigin_desc ( StringInfo  buf,
XLogReaderState record 
)

Definition at line 19 of file replorigindesc.c.

20 {
21  char *rec = XLogRecGetData(record);
22  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
23 
24  switch (info)
25  {
27  {
28  xl_replorigin_set *xlrec;
29 
30  xlrec = (xl_replorigin_set *) rec;
31 
32  appendStringInfo(buf, "set %u; lsn %X/%X; force: %d",
33  xlrec->node_id,
35  xlrec->force);
36  break;
37  }
39  {
40  xl_replorigin_drop *xlrec;
41 
42  xlrec = (xl_replorigin_drop *) rec;
43 
44  appendStringInfo(buf, "drop %u", xlrec->node_id);
45  break;
46  }
47  }
48 }
unsigned char uint8
Definition: c.h:440
#define XLOG_REPLORIGIN_DROP
Definition: origin.h:31
static char * buf
Definition: pg_test_fsync.c:67
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
RepOriginId node_id
Definition: origin.h:27
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
#define XLogRecGetInfo(decoder)
Definition: xlogreader.h:411
#define XLogRecGetData(decoder)
Definition: xlogreader.h:416
#define XLR_INFO_MASK
Definition: xlogrecord.h:62

References appendStringInfo(), buf, xl_replorigin_set::force, LSN_FORMAT_ARGS, xl_replorigin_set::node_id, xl_replorigin_drop::node_id, xl_replorigin_set::remote_lsn, XLOG_REPLORIGIN_DROP, XLOG_REPLORIGIN_SET, XLogRecGetData, XLogRecGetInfo, and XLR_INFO_MASK.

◆ replorigin_drop_by_name()

void replorigin_drop_by_name ( const char *  name,
bool  missing_ok,
bool  nowait 
)

Definition at line 426 of file origin.c.

427 {
428  RepOriginId roident;
429  Relation rel;
430 
432 
433  /*
434  * To interlock against concurrent drops, we hold ExclusiveLock on
435  * pg_replication_origin till xact commit.
436  *
437  * XXX We can optimize this by acquiring the lock on a specific origin by
438  * using LockSharedObject if required. However, for that, we first to
439  * acquire a lock on ReplicationOriginRelationId, get the origin_id, lock
440  * the specific origin and then re-check if the origin still exists.
441  */
442  rel = table_open(ReplicationOriginRelationId, ExclusiveLock);
443 
444  roident = replorigin_by_name(name, missing_ok);
445 
446  if (OidIsValid(roident))
447  replorigin_drop_guts(rel, roident, nowait);
448 
449  /* We keep the lock on pg_replication_origin until commit */
450  table_close(rel, NoLock);
451 }
const char * name
Definition: encode.c:561
#define NoLock
Definition: lockdefs.h:34
RepOriginId replorigin_by_name(const char *roname, bool missing_ok)
Definition: origin.c:221
static void replorigin_drop_guts(Relation rel, RepOriginId roident, bool nowait)
Definition: origin.c:341
uint16 RepOriginId
Definition: xlogdefs.h:65

References Assert(), ExclusiveLock, IsTransactionState(), name, NoLock, OidIsValid, replorigin_by_name(), replorigin_drop_guts(), table_close(), and table_open().

Referenced by AlterSubscription_refresh(), DropSubscription(), pg_replication_origin_drop(), process_syncing_tables_for_apply(), and process_syncing_tables_for_sync().

◆ replorigin_get_progress()

XLogRecPtr replorigin_get_progress ( RepOriginId  node,
bool  flush 
)

Definition at line 1010 of file origin.c.

1011 {
1012  int i;
1013  XLogRecPtr local_lsn = InvalidXLogRecPtr;
1014  XLogRecPtr remote_lsn = InvalidXLogRecPtr;
1015 
1016  /* prevent slots from being concurrently dropped */
1017  LWLockAcquire(ReplicationOriginLock, LW_SHARED);
1018 
1019  for (i = 0; i < max_replication_slots; i++)
1020  {
1022 
1024 
1025  if (state->roident == node)
1026  {
1027  LWLockAcquire(&state->lock, LW_SHARED);
1028 
1029  remote_lsn = state->remote_lsn;
1030  local_lsn = state->local_lsn;
1031 
1032  LWLockRelease(&state->lock);
1033 
1034  break;
1035  }
1036  }
1037 
1038  LWLockRelease(ReplicationOriginLock);
1039 
1040  if (flush && local_lsn != InvalidXLogRecPtr)
1041  XLogFlush(local_lsn);
1042 
1043  return remote_lsn;
1044 }
Definition: regguts.h:318

References i, InvalidXLogRecPtr, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_replication_slots, replication_states, and XLogFlush().

Referenced by AlterSubscription(), and pg_replication_origin_progress().

◆ replorigin_identify()

const char* replorigin_identify ( uint8  info)

Definition at line 51 of file replorigindesc.c.

52 {
53  switch (info)
54  {
56  return "SET";
58  return "DROP";
59  default:
60  return NULL;
61  }
62 }

References XLOG_REPLORIGIN_DROP, and XLOG_REPLORIGIN_SET.

◆ replorigin_redo()

void replorigin_redo ( XLogReaderState record)

Definition at line 823 of file origin.c.

824 {
825  uint8 info = XLogRecGetInfo(record) & ~XLR_INFO_MASK;
826 
827  switch (info)
828  {
829  case XLOG_REPLORIGIN_SET:
830  {
831  xl_replorigin_set *xlrec =
832  (xl_replorigin_set *) XLogRecGetData(record);
833 
835  xlrec->remote_lsn, record->EndRecPtr,
836  xlrec->force /* backward */ ,
837  false /* WAL log */ );
838  break;
839  }
841  {
842  xl_replorigin_drop *xlrec;
843  int i;
844 
845  xlrec = (xl_replorigin_drop *) XLogRecGetData(record);
846 
847  for (i = 0; i < max_replication_slots; i++)
848  {
850 
851  /* found our slot */
852  if (state->roident == xlrec->node_id)
853  {
854  /* reset entry */
855  state->roident = InvalidRepOriginId;
856  state->remote_lsn = InvalidXLogRecPtr;
857  state->local_lsn = InvalidXLogRecPtr;
858  break;
859  }
860  }
861  break;
862  }
863  default:
864  elog(PANIC, "replorigin_redo: unknown op code %u", info);
865  }
866 }
void replorigin_advance(RepOriginId node, XLogRecPtr remote_commit, XLogRecPtr local_commit, bool go_backward, bool wal_log)
Definition: origin.c:884
XLogRecPtr EndRecPtr
Definition: xlogreader.h:207

References elog(), XLogReaderState::EndRecPtr, xl_replorigin_set::force, i, InvalidRepOriginId, InvalidXLogRecPtr, max_replication_slots, xl_replorigin_set::node_id, xl_replorigin_drop::node_id, PANIC, xl_replorigin_set::remote_lsn, replication_states, replorigin_advance(), XLOG_REPLORIGIN_DROP, XLOG_REPLORIGIN_SET, XLogRecGetData, XLogRecGetInfo, and XLR_INFO_MASK.

◆ replorigin_session_advance()

◆ replorigin_session_get_progress()

XLogRecPtr replorigin_session_get_progress ( bool  flush)

Definition at line 1218 of file origin.c.

1219 {
1220  XLogRecPtr remote_lsn;
1221  XLogRecPtr local_lsn;
1222 
1224 
1226  remote_lsn = session_replication_state->remote_lsn;
1227  local_lsn = session_replication_state->local_lsn;
1229 
1230  if (flush && local_lsn != InvalidXLogRecPtr)
1231  XLogFlush(local_lsn);
1232 
1233  return remote_lsn;
1234 }

References Assert(), InvalidXLogRecPtr, ReplicationState::local_lsn, ReplicationState::lock, LW_SHARED, LWLockAcquire(), LWLockRelease(), ReplicationState::remote_lsn, session_replication_state, and XLogFlush().

Referenced by ApplyWorkerMain(), LogicalRepSyncTableStart(), and pg_replication_origin_session_progress().

◆ replorigin_session_reset()

void replorigin_session_reset ( void  )

Definition at line 1171 of file origin.c.

1172 {
1173  ConditionVariable *cv;
1174 
1176 
1177  if (session_replication_state == NULL)
1178  ereport(ERROR,
1179  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1180  errmsg("no replication origin is configured")));
1181 
1182  LWLockAcquire(ReplicationOriginLock, LW_EXCLUSIVE);
1183 
1187 
1188  LWLockRelease(ReplicationOriginLock);
1189 
1191 }
void ConditionVariableBroadcast(ConditionVariable *cv)
ConditionVariable origin_cv
Definition: origin.c:129

References ReplicationState::acquired_by, Assert(), ConditionVariableBroadcast(), ereport, errcode(), errmsg(), ERROR, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), max_replication_slots, ReplicationState::origin_cv, and session_replication_state.

Referenced by pg_replication_origin_session_reset(), and process_syncing_tables_for_sync().

◆ replorigin_session_setup()

void replorigin_session_setup ( RepOriginId  node)

Definition at line 1083 of file origin.c.

1084 {
1085  static bool registered_cleanup;
1086  int i;
1087  int free_slot = -1;
1088 
1089  if (!registered_cleanup)
1090  {
1092  registered_cleanup = true;
1093  }
1094 
1096 
1097  if (session_replication_state != NULL)
1098  ereport(ERROR,
1099  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1100  errmsg("cannot setup replication origin when one is already setup")));
1101 
1102  /* Lock exclusively, as we may have to create a new table entry. */
1103  LWLockAcquire(ReplicationOriginLock, LW_EXCLUSIVE);
1104 
1105  /*
1106  * Search for either an existing slot for the origin, or a free one we can
1107  * use.
1108  */
1109  for (i = 0; i < max_replication_slots; i++)
1110  {
1111  ReplicationState *curstate = &replication_states[i];
1112 
1113  /* remember where to insert if necessary */
1114  if (curstate->roident == InvalidRepOriginId &&
1115  free_slot == -1)
1116  {
1117  free_slot = i;
1118  continue;
1119  }
1120 
1121  /* not our slot */
1122  if (curstate->roident != node)
1123  continue;
1124 
1125  else if (curstate->acquired_by != 0)
1126  {
1127  ereport(ERROR,
1128  (errcode(ERRCODE_OBJECT_IN_USE),
1129  errmsg("replication origin with ID %d is already active for PID %d",
1130  curstate->roident, curstate->acquired_by)));
1131  }
1132 
1133  /* ok, found slot */
1134  session_replication_state = curstate;
1135  }
1136 
1137 
1138  if (session_replication_state == NULL && free_slot == -1)
1139  ereport(ERROR,
1140  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
1141  errmsg("could not find free replication state slot for replication origin with ID %d",
1142  node),
1143  errhint("Increase max_replication_slots and try again.")));
1144  else if (session_replication_state == NULL)
1145  {
1146  /* initialize new slot */
1151  }
1152 
1153 
1155 
1157 
1158  LWLockRelease(ReplicationOriginLock);
1159 
1160  /* probably this one is pointless */
1162 }
int MyProcPid
Definition: globals.c:44
void on_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:361
static void ReplicationOriginExitCleanup(int code, Datum arg)
Definition: origin.c:1051

References ReplicationState::acquired_by, Assert(), ConditionVariableBroadcast(), ereport, errcode(), errhint(), errmsg(), ERROR, i, InvalidRepOriginId, InvalidXLogRecPtr, ReplicationState::local_lsn, LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), max_replication_slots, MyProcPid, on_shmem_exit(), ReplicationState::origin_cv, ReplicationState::remote_lsn, replication_states, ReplicationOriginExitCleanup(), ReplicationState::roident, and session_replication_state.

Referenced by ApplyWorkerMain(), LogicalRepSyncTableStart(), and pg_replication_origin_session_setup().

◆ StartupReplicationOrigin()

void StartupReplicationOrigin ( void  )

Definition at line 695 of file origin.c.

696 {
697  const char *path = "pg_logical/replorigin_checkpoint";
698  int fd;
699  int readBytes;
701  int last_state = 0;
702  pg_crc32c file_crc;
703  pg_crc32c crc;
704 
705  /* don't want to overwrite already existing state */
706 #ifdef USE_ASSERT_CHECKING
707  static bool already_started = false;
708 
709  Assert(!already_started);
710  already_started = true;
711 #endif
712 
713  if (max_replication_slots == 0)
714  return;
715 
716  INIT_CRC32C(crc);
717 
718  elog(DEBUG2, "starting up replication origin progress state");
719 
720  fd = OpenTransientFile(path, O_RDONLY | PG_BINARY);
721 
722  /*
723  * might have had max_replication_slots == 0 last run, or we just brought
724  * up a standby.
725  */
726  if (fd < 0 && errno == ENOENT)
727  return;
728  else if (fd < 0)
729  ereport(PANIC,
731  errmsg("could not open file \"%s\": %m",
732  path)));
733 
734  /* verify magic, that is written even if nothing was active */
735  readBytes = read(fd, &magic, sizeof(magic));
736  if (readBytes != sizeof(magic))
737  {
738  if (readBytes < 0)
739  ereport(PANIC,
741  errmsg("could not read file \"%s\": %m",
742  path)));
743  else
744  ereport(PANIC,
746  errmsg("could not read file \"%s\": read %d of %zu",
747  path, readBytes, sizeof(magic))));
748  }
749  COMP_CRC32C(crc, &magic, sizeof(magic));
750 
751  if (magic != REPLICATION_STATE_MAGIC)
752  ereport(PANIC,
753  (errmsg("replication checkpoint has wrong magic %u instead of %u",
754  magic, REPLICATION_STATE_MAGIC)));
755 
756  /* we can skip locking here, no other access is possible */
757 
758  /* recover individual states, until there are no more to be found */
759  while (true)
760  {
761  ReplicationStateOnDisk disk_state;
762 
763  readBytes = read(fd, &disk_state, sizeof(disk_state));
764 
765  /* no further data */
766  if (readBytes == sizeof(crc))
767  {
768  /* not pretty, but simple ... */
769  file_crc = *(pg_crc32c *) &disk_state;
770  break;
771  }
772 
773  if (readBytes < 0)
774  {
775  ereport(PANIC,
777  errmsg("could not read file \"%s\": %m",
778  path)));
779  }
780 
781  if (readBytes != sizeof(disk_state))
782  {
783  ereport(PANIC,
785  errmsg("could not read file \"%s\": read %d of %zu",
786  path, readBytes, sizeof(disk_state))));
787  }
788 
789  COMP_CRC32C(crc, &disk_state, sizeof(disk_state));
790 
791  if (last_state == max_replication_slots)
792  ereport(PANIC,
793  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
794  errmsg("could not find free replication state, increase max_replication_slots")));
795 
796  /* copy data to shared memory */
797  replication_states[last_state].roident = disk_state.roident;
798  replication_states[last_state].remote_lsn = disk_state.remote_lsn;
799  last_state++;
800 
801  ereport(LOG,
802  (errmsg("recovered replication state of node %d to %X/%X",
803  disk_state.roident,
804  LSN_FORMAT_ARGS(disk_state.remote_lsn))));
805  }
806 
807  /* now check checksum */
808  FIN_CRC32C(crc);
809  if (file_crc != crc)
810  ereport(PANIC,
812  errmsg("replication slot checkpoint has wrong checksum %u, expected %u",
813  crc, file_crc)));
814 
815  if (CloseTransientFile(fd) != 0)
816  ereport(PANIC,
818  errmsg("could not close file \"%s\": %m",
819  path)));
820 }
#define LOG
Definition: elog.h:27
#define DEBUG2
Definition: elog.h:25
#define read(a, b, c)
Definition: win32.h:13
#define ERRCODE_DATA_CORRUPTED
Definition: pg_basebackup.c:41
static int fd(const char *x, int i)
Definition: preproc-init.c:105

References Assert(), CloseTransientFile(), COMP_CRC32C, crc, DEBUG2, elog(), ereport, errcode(), ERRCODE_DATA_CORRUPTED, errcode_for_file_access(), errmsg(), fd(), FIN_CRC32C, INIT_CRC32C, LOG, LSN_FORMAT_ARGS, max_replication_slots, OpenTransientFile(), PANIC, PG_BINARY, read, ReplicationState::remote_lsn, ReplicationStateOnDisk::remote_lsn, REPLICATION_STATE_MAGIC, replication_states, ReplicationState::roident, and ReplicationStateOnDisk::roident.

Referenced by StartupXLOG().

Variable Documentation

◆ replorigin_session_origin

◆ replorigin_session_origin_lsn

◆ replorigin_session_origin_timestamp