PostgreSQL Source Code  git master
tablesync.c File Reference
Include dependency graph for tablesync.c:

Go to the source code of this file.

Functions

static void pg_attribute_noreturn ()
 
static bool wait_for_relation_state_change (Oid relid, char expected_state)
 
static bool wait_for_worker_state_change (char expected_state)
 
void invalidate_syncing_table_states (Datum arg, int cacheid, uint32 hashvalue)
 
static void process_syncing_tables_for_sync (XLogRecPtr current_lsn)
 
static void process_syncing_tables_for_apply (XLogRecPtr current_lsn)
 
void process_syncing_tables (XLogRecPtr current_lsn)
 
static Listmake_copy_attnamelist (LogicalRepRelMapEntry *rel)
 
static int copy_read_data (void *outbuf, int minread, int maxread)
 
static void fetch_remote_table_info (char *nspname, char *relname, LogicalRepRelation *lrel)
 
static void copy_table (Relation rel)
 
void ReplicationSlotNameForTablesync (Oid suboid, Oid relid, char *syncslotname, int szslot)
 
void ReplicationOriginNameForTablesync (Oid suboid, Oid relid, char *originname, int szorgname)
 
char * LogicalRepSyncTableStart (XLogRecPtr *origin_startpos)
 

Variables

static bool table_states_valid = false
 
StringInfo copybuf = NULL
 

Function Documentation

◆ copy_read_data()

static int copy_read_data ( void *  outbuf,
int  minread,
int  maxread 
)
static

Definition at line 619 of file tablesync.c.

References buf, CHECK_FOR_INTERRUPTS, StringInfoData::cursor, StringInfoData::data, fd(), StringInfoData::len, MyLatch, PGINVALID_SOCKET, ResetLatch(), WAIT_EVENT_LOGICAL_SYNC_DATA, WaitLatchOrSocket(), walrcv_receive, WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, WL_SOCKET_READABLE, WL_TIMEOUT, and wrconn.

Referenced by copy_table().

620 {
621  int bytesread = 0;
622  int avail;
623 
624  /* If there are some leftover data from previous read, use it. */
625  avail = copybuf->len - copybuf->cursor;
626  if (avail)
627  {
628  if (avail > maxread)
629  avail = maxread;
630  memcpy(outbuf, &copybuf->data[copybuf->cursor], avail);
631  copybuf->cursor += avail;
632  maxread -= avail;
633  bytesread += avail;
634  }
635 
636  while (maxread > 0 && bytesread < minread)
637  {
639  int len;
640  char *buf = NULL;
641 
642  for (;;)
643  {
644  /* Try read the data. */
645  len = walrcv_receive(wrconn, &buf, &fd);
646 
648 
649  if (len == 0)
650  break;
651  else if (len < 0)
652  return bytesread;
653  else
654  {
655  /* Process the data */
656  copybuf->data = buf;
657  copybuf->len = len;
658  copybuf->cursor = 0;
659 
660  avail = copybuf->len - copybuf->cursor;
661  if (avail > maxread)
662  avail = maxread;
663  memcpy(outbuf, &copybuf->data[copybuf->cursor], avail);
664  outbuf = (void *) ((char *) outbuf + avail);
665  copybuf->cursor += avail;
666  maxread -= avail;
667  bytesread += avail;
668  }
669 
670  if (maxread <= 0 || bytesread >= minread)
671  return bytesread;
672  }
673 
674  /*
675  * Wait for more data or latch.
676  */
677  (void) WaitLatchOrSocket(MyLatch,
680  fd, 1000L, WAIT_EVENT_LOGICAL_SYNC_DATA);
681 
683  }
684 
685  return bytesread;
686 }
WalReceiverConn * wrconn
Definition: worker.c:159
#define WL_TIMEOUT
Definition: latch.h:128
#define walrcv_receive(conn, buffer, wait_fd)
Definition: walreceiver.h:419
#define WL_SOCKET_READABLE
Definition: latch.h:126
static int fd(const char *x, int i)
Definition: preproc-init.c:105
void ResetLatch(Latch *latch)
Definition: latch.c:660
static char * buf
Definition: pg_test_fsync.c:68
int WaitLatchOrSocket(Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition: latch.c:500
int pgsocket
Definition: port.h:31
#define PGINVALID_SOCKET
Definition: port.h:33
StringInfo copybuf
Definition: tablesync.c:120
struct Latch * MyLatch
Definition: globals.c:57
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:102
#define WL_LATCH_SET
Definition: latch.h:125
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130

◆ copy_table()

static void copy_table ( Relation  rel)
static

Definition at line 802 of file tablesync.c.

References AccessShareLock, addRangeTableEntryForRelation(), appendStringInfo(), appendStringInfoString(), Assert, LogicalRepRelation::attnames, BeginCopyFrom(), copy_read_data(), CopyFrom(), StringInfoData::data, ereport, WalRcvExecResult::err, errmsg(), ERROR, fetch_remote_table_info(), get_namespace_name(), i, initStringInfo(), LogicalRepRelMapEntry::localrel, logicalrep_rel_close(), logicalrep_rel_open(), logicalrep_relmap_update(), make_copy_attnamelist(), make_parsestate(), makeStringInfo(), LogicalRepRelation::natts, NIL, NoLock, LogicalRepRelation::nspname, pfree(), quote_identifier(), quote_qualified_identifier(), RelationGetNamespace, RelationGetRelationName, LogicalRepRelation::relkind, LogicalRepRelation::relname, LogicalRepRelation::remoteid, WalRcvExecResult::status, walrcv_clear_result(), walrcv_exec, WALRCV_OK_COPY_OUT, and wrconn.

Referenced by LogicalRepSyncTableStart().

803 {
804  LogicalRepRelMapEntry *relmapentry;
805  LogicalRepRelation lrel;
806  WalRcvExecResult *res;
807  StringInfoData cmd;
808  CopyFromState cstate;
809  List *attnamelist;
810  ParseState *pstate;
811 
812  /* Get the publisher relation info. */
814  RelationGetRelationName(rel), &lrel);
815 
816  /* Put the relation into relmap. */
818 
819  /* Map the publisher relation to local one. */
820  relmapentry = logicalrep_rel_open(lrel.remoteid, NoLock);
821  Assert(rel == relmapentry->localrel);
822 
823  /* Start copy on the publisher. */
824  initStringInfo(&cmd);
825  if (lrel.relkind == RELKIND_RELATION)
826  appendStringInfo(&cmd, "COPY %s TO STDOUT",
828  else
829  {
830  /*
831  * For non-tables, we need to do COPY (SELECT ...), but we can't just
832  * do SELECT * because we need to not copy generated columns.
833  */
834  appendStringInfoString(&cmd, "COPY (SELECT ");
835  for (int i = 0; i < lrel.natts; i++)
836  {
838  if (i < lrel.natts - 1)
839  appendStringInfoString(&cmd, ", ");
840  }
841  appendStringInfo(&cmd, " FROM %s) TO STDOUT",
843  }
844  res = walrcv_exec(wrconn, cmd.data, 0, NULL);
845  pfree(cmd.data);
846  if (res->status != WALRCV_OK_COPY_OUT)
847  ereport(ERROR,
848  (errmsg("could not start initial contents copy for table \"%s.%s\": %s",
849  lrel.nspname, lrel.relname, res->err)));
850  walrcv_clear_result(res);
851 
853 
854  pstate = make_parsestate(NULL);
856  NULL, false, false);
857 
858  attnamelist = make_copy_attnamelist(relmapentry);
859  cstate = BeginCopyFrom(pstate, rel, NULL, NULL, false, copy_read_data, attnamelist, NIL);
860 
861  /* Do the copy */
862  (void) CopyFrom(cstate);
863 
864  logicalrep_rel_close(relmapentry, NoLock);
865 }
#define NIL
Definition: pg_list.h:65
WalReceiverConn * wrconn
Definition: worker.c:159
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:11323
uint64 CopyFrom(CopyFromState cstate)
Definition: copyfrom.c:525
StringInfo makeStringInfo(void)
Definition: stringinfo.c:41
#define AccessShareLock
Definition: lockdefs.h:36
void logicalrep_rel_close(LogicalRepRelMapEntry *rel, LOCKMODE lockmode)
Definition: relation.c:447
LogicalRepRelId remoteid
Definition: logicalproto.h:91
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void logicalrep_relmap_update(LogicalRepRelation *remoterel)
Definition: relation.c:171
static void walrcv_clear_result(WalRcvExecResult *walres)
Definition: walreceiver.h:433
void pfree(void *pointer)
Definition: mcxt.c:1169
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
#define ERROR
Definition: elog.h:46
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
#define NoLock
Definition: lockdefs.h:34
#define RelationGetRelationName(relation)
Definition: rel.h:506
LogicalRepRelMapEntry * logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
Definition: relation.c:272
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:11407
StringInfo copybuf
Definition: tablesync.c:120
static void fetch_remote_table_info(char *nspname, char *relname, LogicalRepRelation *lrel)
Definition: tablesync.c:694
#define ereport(elevel,...)
Definition: elog.h:157
CopyFromState BeginCopyFrom(ParseState *pstate, Relation rel, Node *whereClause, const char *filename, bool is_program, copy_data_source_cb data_source_cb, List *attnamelist, List *options)
Definition: copyfrom.c:1186
#define Assert(condition)
Definition: c.h:804
WalRcvExecStatus status
Definition: walreceiver.h:214
int errmsg(const char *fmt,...)
Definition: elog.c:909
int i
static int copy_read_data(void *outbuf, int minread, int maxread)
Definition: tablesync.c:619
static List * make_copy_attnamelist(LogicalRepRelMapEntry *rel)
Definition: tablesync.c:599
Definition: pg_list.h:50
#define walrcv_exec(conn, exec, nRetTypes, retTypes)
Definition: walreceiver.h:427
#define RelationGetNamespace(relation)
Definition: rel.h:513

◆ fetch_remote_table_info()

static void fetch_remote_table_info ( char *  nspname,
char *  relname,
LogicalRepRelation lrel 
)
static

Definition at line 694 of file tablesync.c.

References appendStringInfo(), Assert, LogicalRepRelation::attkeys, LogicalRepRelation::attnames, LogicalRepRelation::atttyps, bms_add_member(), StringInfoData::data, DatumGetBool, DatumGetChar, DatumGetObjectId, elog, ereport, WalRcvExecResult::err, errmsg(), ERROR, ExecClearTuple(), ExecDropSingleTupleTableSlot(), initStringInfo(), lengthof, MakeSingleTupleTableSlot(), MaxTupleAttributeNumber, LogicalRepRelation::natts, LogicalRepRelation::nspname, palloc0(), pfree(), quote_literal_cstr(), LogicalRepRelation::relkind, relname, LogicalRepRelation::relname, LogicalRepRelation::remoteid, LogicalRepRelation::replident, resetStringInfo(), slot_getattr(), WalRcvExecResult::status, TextDatumGetCString, TTSOpsMinimalTuple, WalRcvExecResult::tupledesc, WalRcvExecResult::tuplestore, tuplestore_gettupleslot(), walrcv_clear_result(), walrcv_exec, WALRCV_OK_TUPLES, walrcv_server_version, and wrconn.

Referenced by copy_table().

696 {
697  WalRcvExecResult *res;
698  StringInfoData cmd;
699  TupleTableSlot *slot;
700  Oid tableRow[] = {OIDOID, CHAROID, CHAROID};
701  Oid attrRow[] = {TEXTOID, OIDOID, BOOLOID};
702  bool isnull;
703  int natt;
704 
705  lrel->nspname = nspname;
706  lrel->relname = relname;
707 
708  /* First fetch Oid and replica identity. */
709  initStringInfo(&cmd);
710  appendStringInfo(&cmd, "SELECT c.oid, c.relreplident, c.relkind"
711  " FROM pg_catalog.pg_class c"
712  " INNER JOIN pg_catalog.pg_namespace n"
713  " ON (c.relnamespace = n.oid)"
714  " WHERE n.nspname = %s"
715  " AND c.relname = %s",
716  quote_literal_cstr(nspname),
718  res = walrcv_exec(wrconn, cmd.data, lengthof(tableRow), tableRow);
719 
720  if (res->status != WALRCV_OK_TUPLES)
721  ereport(ERROR,
722  (errmsg("could not fetch table info for table \"%s.%s\" from publisher: %s",
723  nspname, relname, res->err)));
724 
726  if (!tuplestore_gettupleslot(res->tuplestore, true, false, slot))
727  ereport(ERROR,
728  (errmsg("table \"%s.%s\" not found on publisher",
729  nspname, relname)));
730 
731  lrel->remoteid = DatumGetObjectId(slot_getattr(slot, 1, &isnull));
732  Assert(!isnull);
733  lrel->replident = DatumGetChar(slot_getattr(slot, 2, &isnull));
734  Assert(!isnull);
735  lrel->relkind = DatumGetChar(slot_getattr(slot, 3, &isnull));
736  Assert(!isnull);
737 
739  walrcv_clear_result(res);
740 
741  /* Now fetch columns. */
742  resetStringInfo(&cmd);
743  appendStringInfo(&cmd,
744  "SELECT a.attname,"
745  " a.atttypid,"
746  " a.attnum = ANY(i.indkey)"
747  " FROM pg_catalog.pg_attribute a"
748  " LEFT JOIN pg_catalog.pg_index i"
749  " ON (i.indexrelid = pg_get_replica_identity_index(%u))"
750  " WHERE a.attnum > 0::pg_catalog.int2"
751  " AND NOT a.attisdropped %s"
752  " AND a.attrelid = %u"
753  " ORDER BY a.attnum",
754  lrel->remoteid,
755  (walrcv_server_version(wrconn) >= 120000 ? "AND a.attgenerated = ''" : ""),
756  lrel->remoteid);
757  res = walrcv_exec(wrconn, cmd.data, lengthof(attrRow), attrRow);
758 
759  if (res->status != WALRCV_OK_TUPLES)
760  ereport(ERROR,
761  (errmsg("could not fetch table info for table \"%s.%s\" from publisher: %s",
762  nspname, relname, res->err)));
763 
764  /* We don't know the number of rows coming, so allocate enough space. */
765  lrel->attnames = palloc0(MaxTupleAttributeNumber * sizeof(char *));
766  lrel->atttyps = palloc0(MaxTupleAttributeNumber * sizeof(Oid));
767  lrel->attkeys = NULL;
768 
769  natt = 0;
771  while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
772  {
773  lrel->attnames[natt] =
774  TextDatumGetCString(slot_getattr(slot, 1, &isnull));
775  Assert(!isnull);
776  lrel->atttyps[natt] = DatumGetObjectId(slot_getattr(slot, 2, &isnull));
777  Assert(!isnull);
778  if (DatumGetBool(slot_getattr(slot, 3, &isnull)))
779  lrel->attkeys = bms_add_member(lrel->attkeys, natt);
780 
781  /* Should never happen. */
782  if (++natt >= MaxTupleAttributeNumber)
783  elog(ERROR, "too many columns in remote table \"%s.%s\"",
784  nspname, relname);
785 
786  ExecClearTuple(slot);
787  }
789 
790  lrel->natts = natt;
791 
792  walrcv_clear_result(res);
793  pfree(cmd.data);
794 }
WalReceiverConn * wrconn
Definition: worker.c:159
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:102
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
#define MaxTupleAttributeNumber
Definition: htup_details.h:33
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1238
#define DatumGetObjectId(X)
Definition: postgres.h:544
#define walrcv_server_version(conn)
Definition: walreceiver.h:411
#define lengthof(array)
Definition: c.h:734
NameData relname
Definition: pg_class.h:38
unsigned int Oid
Definition: postgres_ext.h:31
Bitmapset * attkeys
Definition: logicalproto.h:99
LogicalRepRelId remoteid
Definition: logicalproto.h:91
static void walrcv_clear_result(WalRcvExecResult *walres)
Definition: walreceiver.h:433
void pfree(void *pointer)
Definition: mcxt.c:1169
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
TupleDesc tupledesc
Definition: walreceiver.h:218
#define ERROR
Definition: elog.h:46
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1254
#define DatumGetBool(X)
Definition: postgres.h:437
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
#define TextDatumGetCString(d)
Definition: builtins.h:83
void * palloc0(Size size)
Definition: mcxt.c:1093
#define DatumGetChar(X)
Definition: postgres.h:453
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:381
#define ereport(elevel,...)
Definition: elog.h:157
bool tuplestore_gettupleslot(Tuplestorestate *state, bool forward, bool copy, TupleTableSlot *slot)
Definition: tuplestore.c:1078
Tuplestorestate * tuplestore
Definition: walreceiver.h:217
#define Assert(condition)
Definition: c.h:804
WalRcvExecStatus status
Definition: walreceiver.h:214
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
const TupleTableSlotOps TTSOpsMinimalTuple
Definition: execTuples.c:85
#define walrcv_exec(conn, exec, nRetTypes, retTypes)
Definition: walreceiver.h:427

◆ invalidate_syncing_table_states()

void invalidate_syncing_table_states ( Datum  arg,
int  cacheid,
uint32  hashvalue 
)

Definition at line 264 of file tablesync.c.

References table_states_valid.

Referenced by ApplyWorkerMain().

265 {
266  table_states_valid = false;
267 }
static bool table_states_valid
Definition: tablesync.c:118

◆ LogicalRepSyncTableStart()

char* LogicalRepSyncTableStart ( XLogRecPtr origin_startpos)

Definition at line 913 of file tablesync.c.

References Assert, CommandCounterIncrement(), CommitTransactionCommand(), Subscription::conninfo, copy_table(), CRS_USE_SNAPSHOT, DEBUG1, elog, ereport, WalRcvExecResult::err, errcode(), ERRCODE_DUPLICATE_OBJECT, errmsg(), ERROR, GetSubscriptionRelState(), GetTransactionSnapshot(), HOLD_INTERRUPTS, InvalidXLogRecPtr, LockRelationOid(), LSN_FORMAT_ARGS, MyLogicalRepWorker, MySubscription, NAMEDATALEN, NoLock, Subscription::oid, OidIsValid, palloc(), pgstat_report_stat(), PopActiveSnapshot(), PushActiveSnapshot(), LogicalRepWorker::relid, LogicalRepWorker::relmutex, LogicalRepWorker::relstate, LogicalRepWorker::relstate_lsn, ReplicationOriginNameForTablesync(), ReplicationSlotDropAtPubNode(), ReplicationSlotNameForTablesync(), replorigin_advance(), replorigin_by_name(), replorigin_create(), replorigin_session_get_progress(), replorigin_session_origin, replorigin_session_setup(), RESUME_INTERRUPTS, RowExclusiveLock, SpinLockAcquire, SpinLockRelease, StartTransactionCommand(), WalRcvExecResult::status, LogicalRepWorker::subid, table_close(), table_open(), UnlockRelationOid(), UpdateSubscriptionRelState(), wait_for_worker_state_change(), walrcv_clear_result(), walrcv_connect, walrcv_create_slot, walrcv_exec, WALRCV_OK_COMMAND, and wrconn.

Referenced by ApplyWorkerMain().

914 {
915  char *slotname;
916  char *err;
917  char relstate;
918  XLogRecPtr relstate_lsn;
919  Relation rel;
920  WalRcvExecResult *res;
921  char originname[NAMEDATALEN];
922  RepOriginId originid;
923 
924  /* Check the state of the table synchronization. */
928  &relstate_lsn);
930 
932  MyLogicalRepWorker->relstate = relstate;
933  MyLogicalRepWorker->relstate_lsn = relstate_lsn;
935 
936  /*
937  * If synchronization is already done or no longer necessary, exit now
938  * that we've updated shared memory state.
939  */
940  switch (relstate)
941  {
942  case SUBREL_STATE_SYNCDONE:
943  case SUBREL_STATE_READY:
944  case SUBREL_STATE_UNKNOWN:
945  finish_sync_worker(); /* doesn't return */
946  }
947 
948  /* Calculate the name of the tablesync slot. */
949  slotname = (char *) palloc(NAMEDATALEN);
952  slotname,
953  NAMEDATALEN);
954 
955  /*
956  * Here we use the slot name instead of the subscription name as the
957  * application_name, so that it is different from the main apply worker,
958  * so that synchronous replication can distinguish them.
959  */
960  wrconn = walrcv_connect(MySubscription->conninfo, true, slotname, &err);
961  if (wrconn == NULL)
962  ereport(ERROR,
963  (errmsg("could not connect to the publisher: %s", err)));
964 
965  Assert(MyLogicalRepWorker->relstate == SUBREL_STATE_INIT ||
966  MyLogicalRepWorker->relstate == SUBREL_STATE_DATASYNC ||
967  MyLogicalRepWorker->relstate == SUBREL_STATE_FINISHEDCOPY);
968 
969  /* Assign the origin tracking record name. */
972  originname,
973  sizeof(originname));
974 
975  if (MyLogicalRepWorker->relstate == SUBREL_STATE_DATASYNC)
976  {
977  /*
978  * We have previously errored out before finishing the copy so the
979  * replication slot might exist. We want to remove the slot if it
980  * already exists and proceed.
981  *
982  * XXX We could also instead try to drop the slot, last time we failed
983  * but for that, we might need to clean up the copy state as it might
984  * be in the middle of fetching the rows. Also, if there is a network
985  * breakdown then it wouldn't have succeeded so trying it next time
986  * seems like a better bet.
987  */
988  ReplicationSlotDropAtPubNode(wrconn, slotname, true);
989  }
990  else if (MyLogicalRepWorker->relstate == SUBREL_STATE_FINISHEDCOPY)
991  {
992  /*
993  * The COPY phase was previously done, but tablesync then crashed
994  * before it was able to finish normally.
995  */
997 
998  /*
999  * The origin tracking name must already exist. It was created first
1000  * time this tablesync was launched.
1001  */
1002  originid = replorigin_by_name(originname, false);
1003  replorigin_session_setup(originid);
1004  replorigin_session_origin = originid;
1005  *origin_startpos = replorigin_session_get_progress(false);
1006 
1008 
1009  goto copy_table_done;
1010  }
1011 
1013  MyLogicalRepWorker->relstate = SUBREL_STATE_DATASYNC;
1016 
1017  /* Update the state and make it visible to others. */
1024  pgstat_report_stat(false);
1025 
1027 
1028  /*
1029  * Use a standard write lock here. It might be better to disallow access
1030  * to the table while it's being synchronized. But we don't want to block
1031  * the main apply process from working and it has to open the relation in
1032  * RowExclusiveLock when remapping remote relation id to local one.
1033  */
1035 
1036  /*
1037  * Start a transaction in the remote node in REPEATABLE READ mode. This
1038  * ensures that both the replication slot we create (see below) and the
1039  * COPY are consistent with each other.
1040  */
1041  res = walrcv_exec(wrconn,
1042  "BEGIN READ ONLY ISOLATION LEVEL REPEATABLE READ",
1043  0, NULL);
1044  if (res->status != WALRCV_OK_COMMAND)
1045  ereport(ERROR,
1046  (errmsg("table copy could not start transaction on publisher: %s",
1047  res->err)));
1048  walrcv_clear_result(res);
1049 
1050  /*
1051  * Create a new permanent logical decoding slot. This slot will be used
1052  * for the catchup phase after COPY is done, so tell it to use the
1053  * snapshot to make the final data consistent.
1054  *
1055  * Prevent cancel/die interrupts while creating slot here because it is
1056  * possible that before the server finishes this command, a concurrent
1057  * drop subscription happens which would complete without removing this
1058  * slot leading to a dangling slot on the server.
1059  */
1060  HOLD_INTERRUPTS();
1061  walrcv_create_slot(wrconn, slotname, false /* permanent */ ,
1062  CRS_USE_SNAPSHOT, origin_startpos);
1064 
1065  /*
1066  * Setup replication origin tracking. The purpose of doing this before the
1067  * copy is to avoid doing the copy again due to any error in setting up
1068  * origin tracking.
1069  */
1070  originid = replorigin_by_name(originname, true);
1071  if (!OidIsValid(originid))
1072  {
1073  /*
1074  * Origin tracking does not exist, so create it now.
1075  *
1076  * Then advance to the LSN got from walrcv_create_slot. This is WAL
1077  * logged for the purpose of recovery. Locks are to prevent the
1078  * replication origin from vanishing while advancing.
1079  */
1080  originid = replorigin_create(originname);
1081 
1082  LockRelationOid(ReplicationOriginRelationId, RowExclusiveLock);
1083  replorigin_advance(originid, *origin_startpos, InvalidXLogRecPtr,
1084  true /* go backward */ , true /* WAL log */ );
1085  UnlockRelationOid(ReplicationOriginRelationId, RowExclusiveLock);
1086 
1087  replorigin_session_setup(originid);
1088  replorigin_session_origin = originid;
1089  }
1090  else
1091  {
1092  ereport(ERROR,
1094  errmsg("replication origin \"%s\" already exists",
1095  originname)));
1096  }
1097 
1098  /* Now do the initial data copy */
1100  copy_table(rel);
1102 
1103  res = walrcv_exec(wrconn, "COMMIT", 0, NULL);
1104  if (res->status != WALRCV_OK_COMMAND)
1105  ereport(ERROR,
1106  (errmsg("table copy could not finish transaction on publisher: %s",
1107  res->err)));
1108  walrcv_clear_result(res);
1109 
1110  table_close(rel, NoLock);
1111 
1112  /* Make the copy visible. */
1114 
1115  /*
1116  * Update the persisted state to indicate the COPY phase is done; make it
1117  * visible to others.
1118  */
1121  SUBREL_STATE_FINISHEDCOPY,
1123 
1125 
1126 copy_table_done:
1127 
1128  elog(DEBUG1,
1129  "LogicalRepSyncTableStart: '%s' origin_startpos lsn %X/%X",
1130  originname, LSN_FORMAT_ARGS(*origin_startpos));
1131 
1132  /*
1133  * We are done with the initial data synchronization, update the state.
1134  */
1136  MyLogicalRepWorker->relstate = SUBREL_STATE_SYNCWAIT;
1137  MyLogicalRepWorker->relstate_lsn = *origin_startpos;
1139 
1140  /*
1141  * Finally, wait until the main apply worker tells us to catch up and then
1142  * return to let LogicalRepApplyLoop do it.
1143  */
1144  wait_for_worker_state_change(SUBREL_STATE_CATCHUP);
1145  return slotname;
1146 }
Subscription * MySubscription
Definition: worker.c:161
WalReceiverConn * wrconn
Definition: worker.c:159
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define DEBUG1
Definition: elog.h:25
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
void ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok)
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:200
void CommitTransactionCommand(void)
Definition: xact.c:2939
uint16 RepOriginId
Definition: xlogdefs.h:65
static void copy_table(Relation rel)
Definition: tablesync.c:802
XLogRecPtr replorigin_session_get_progress(bool flush)
Definition: origin.c:1203
int errcode(int sqlerrcode)
Definition: elog.c:698
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
void replorigin_advance(RepOriginId node, XLogRecPtr remote_commit, XLogRecPtr local_commit, bool go_backward, bool wal_log)
Definition: origin.c:872
void pgstat_report_stat(bool disconnect)
Definition: pgstat.c:846
void replorigin_session_setup(RepOriginId node)
Definition: origin.c:1068
#define walrcv_create_slot(conn, slotname, temporary, snapshot_action, lsn)
Definition: walreceiver.h:423
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
#define OidIsValid(objectId)
Definition: c.h:710
RepOriginId replorigin_by_name(char *roname, bool missing_ok)
Definition: origin.c:209
XLogRecPtr relstate_lsn
#define RESUME_INTERRUPTS()
Definition: miscadmin.h:121
#define NAMEDATALEN
#define SpinLockAcquire(lock)
Definition: spin.h:62
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
static void walrcv_clear_result(WalRcvExecResult *walres)
Definition: walreceiver.h:433
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
#define ERROR
Definition: elog.h:46
#define NoLock
Definition: lockdefs.h:34
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
#define RowExclusiveLock
Definition: lockdefs.h:38
RepOriginId replorigin_create(char *roname)
Definition: origin.c:240
#define SpinLockRelease(lock)
Definition: spin.h:64
char GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn)
void CommandCounterIncrement(void)
Definition: xact.c:1021
void UpdateSubscriptionRelState(Oid subid, Oid relid, char state, XLogRecPtr sublsn)
#define ereport(elevel,...)
Definition: elog.h:157
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:804
WalRcvExecStatus status
Definition: walreceiver.h:214
RepOriginId replorigin_session_origin
Definition: origin.c:154
void StartTransactionCommand(void)
Definition: xact.c:2838
void ReplicationOriginNameForTablesync(Oid suboid, Oid relid, char *originname, int szorgname)
Definition: tablesync.c:898
void * palloc(Size size)
Definition: mcxt.c:1062
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define HOLD_INTERRUPTS()
Definition: miscadmin.h:119
#define elog(elevel,...)
Definition: elog.h:232
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:109
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
static bool wait_for_worker_state_change(char expected_state)
Definition: tablesync.c:215
#define walrcv_exec(conn, exec, nRetTypes, retTypes)
Definition: walreceiver.h:427
void ReplicationSlotNameForTablesync(Oid suboid, Oid relid, char *syncslotname, int szslot)
Definition: tablesync.c:885
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:401

◆ make_copy_attnamelist()

static List* make_copy_attnamelist ( LogicalRepRelMapEntry rel)
static

Definition at line 599 of file tablesync.c.

References LogicalRepRelation::attnames, i, lappend(), makeString(), LogicalRepRelation::natts, NIL, and LogicalRepRelMapEntry::remoterel.

Referenced by copy_table().

600 {
601  List *attnamelist = NIL;
602  int i;
603 
604  for (i = 0; i < rel->remoterel.natts; i++)
605  {
606  attnamelist = lappend(attnamelist,
607  makeString(rel->remoterel.attnames[i]));
608  }
609 
610 
611  return attnamelist;
612 }
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
LogicalRepRelation remoterel
List * lappend(List *list, void *datum)
Definition: list.c:336
int i
Definition: pg_list.h:50

◆ pg_attribute_noreturn()

static void pg_attribute_noreturn ( )
static

Definition at line 126 of file tablesync.c.

References CommitTransactionCommand(), ereport, errmsg(), get_rel_name(), GetXLogWriteRecPtr(), InvalidOid, IsTransactionState(), LOG, logicalrep_worker_wakeup(), MyLogicalRepWorker, MySubscription, Subscription::name, pgstat_report_stat(), proc_exit(), LogicalRepWorker::relid, StartTransactionCommand(), LogicalRepWorker::subid, and XLogFlush().

128 {
129  /*
130  * Commit any outstanding transaction. This is the usual case, unless
131  * there was nothing to do for the table.
132  */
133  if (IsTransactionState())
134  {
136  pgstat_report_stat(false);
137  }
138 
139  /* And flush all writes. */
141 
143  ereport(LOG,
144  (errmsg("logical replication table synchronization worker for subscription \"%s\", table \"%s\" has finished",
148 
149  /* Find the main apply worker and signal it. */
151 
152  /* Stop gracefully */
153  proc_exit(0);
154 }
Subscription * MySubscription
Definition: worker.c:161
void logicalrep_worker_wakeup(Oid subid, Oid relid)
Definition: launcher.c:539
void CommitTransactionCommand(void)
Definition: xact.c:2939
void proc_exit(int code)
Definition: ipc.c:104
void pgstat_report_stat(bool disconnect)
Definition: pgstat.c:846
#define LOG
Definition: elog.h:26
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2881
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
XLogRecPtr GetXLogWriteRecPtr(void)
Definition: xlog.c:11763
void StartTransactionCommand(void)
Definition: xact.c:2838
bool IsTransactionState(void)
Definition: xact.c:371
int errmsg(const char *fmt,...)
Definition: elog.c:909
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899

◆ process_syncing_tables()

void process_syncing_tables ( XLogRecPtr  current_lsn)

Definition at line 587 of file tablesync.c.

References am_tablesync_worker(), process_syncing_tables_for_apply(), and process_syncing_tables_for_sync().

Referenced by apply_handle_commit(), apply_handle_stream_commit(), and LogicalRepApplyLoop().

588 {
589  if (am_tablesync_worker())
590  process_syncing_tables_for_sync(current_lsn);
591  else
593 }
static void process_syncing_tables_for_apply(XLogRecPtr current_lsn)
Definition: tablesync.c:355
static bool am_tablesync_worker(void)
static void process_syncing_tables_for_sync(XLogRecPtr current_lsn)
Definition: tablesync.c:278

◆ process_syncing_tables_for_apply()

static void process_syncing_tables_for_apply ( XLogRecPtr  current_lsn)
static

Definition at line 355 of file tablesync.c.

References Assert, CacheMemoryContext, CommitTransactionCommand(), LogicalRepWorker::dbid, HASHCTL::entrysize, GetCurrentTimestamp(), GetSubscriptionNotReadyRelations(), HASH_BLOBS, hash_create(), hash_destroy(), HASH_ELEM, HASH_ENTER, hash_search(), IsTransactionState(), HASHCTL::keysize, lappend(), lfirst, list_free_deep(), logicalrep_sync_worker_count(), logicalrep_worker_find(), logicalrep_worker_launch(), logicalrep_worker_wakeup_ptr(), SubscriptionRelState::lsn, LW_SHARED, LWLockAcquire(), LWLockRelease(), Max, max_sync_workers_per_subscription, MemoryContextSwitchTo(), MyLogicalRepWorker, MySubscription, Subscription::name, NAMEDATALEN, NIL, now(), Subscription::oid, palloc(), pgstat_report_stat(), LogicalRepWorker::proc, SubscriptionRelState::relid, LogicalRepWorker::relmutex, LogicalRepWorker::relstate, LogicalRepWorker::relstate_lsn, ReplicationOriginNameForTablesync(), replorigin_drop_by_name(), SpinLockAcquire, SpinLockRelease, StartTransactionCommand(), SubscriptionRelState::state, LogicalRepWorker::subid, table_states_valid, TimestampDifferenceExceeds(), UpdateSubscriptionRelState(), LogicalRepWorker::userid, wait_for_relation_state_change(), and wal_retrieve_retry_interval.

Referenced by process_syncing_tables().

356 {
357  struct tablesync_start_time_mapping
358  {
359  Oid relid;
360  TimestampTz last_start_time;
361  };
362  static List *table_states = NIL;
363  static HTAB *last_start_times = NULL;
364  ListCell *lc;
365  bool started_tx = false;
366 
368 
369  /* We need up-to-date sync state info for subscription tables here. */
370  if (!table_states_valid)
371  {
372  MemoryContext oldctx;
373  List *rstates;
374  ListCell *lc;
375  SubscriptionRelState *rstate;
376 
377  /* Clean the old list. */
378  list_free_deep(table_states);
379  table_states = NIL;
380 
382  started_tx = true;
383 
384  /* Fetch all non-ready tables. */
386 
387  /* Allocate the tracking info in a permanent memory context. */
389  foreach(lc, rstates)
390  {
391  rstate = palloc(sizeof(SubscriptionRelState));
392  memcpy(rstate, lfirst(lc), sizeof(SubscriptionRelState));
393  table_states = lappend(table_states, rstate);
394  }
395  MemoryContextSwitchTo(oldctx);
396 
397  table_states_valid = true;
398  }
399 
400  /*
401  * Prepare a hash table for tracking last start times of workers, to avoid
402  * immediate restarts. We don't need it if there are no tables that need
403  * syncing.
404  */
405  if (table_states && !last_start_times)
406  {
407  HASHCTL ctl;
408 
409  ctl.keysize = sizeof(Oid);
410  ctl.entrysize = sizeof(struct tablesync_start_time_mapping);
411  last_start_times = hash_create("Logical replication table sync worker start times",
412  256, &ctl, HASH_ELEM | HASH_BLOBS);
413  }
414 
415  /*
416  * Clean up the hash table when we're done with all tables (just to
417  * release the bit of memory).
418  */
419  else if (!table_states && last_start_times)
420  {
421  hash_destroy(last_start_times);
422  last_start_times = NULL;
423  }
424 
425  /*
426  * Process all tables that are being synchronized.
427  */
428  foreach(lc, table_states)
429  {
431 
432  if (rstate->state == SUBREL_STATE_SYNCDONE)
433  {
434  /*
435  * Apply has caught up to the position where the table sync has
436  * finished. Mark the table as ready so that the apply will just
437  * continue to replicate it normally.
438  */
439  if (current_lsn >= rstate->lsn)
440  {
441  char originname[NAMEDATALEN];
442 
443  rstate->state = SUBREL_STATE_READY;
444  rstate->lsn = current_lsn;
445  if (!started_tx)
446  {
448  started_tx = true;
449  }
450 
451  /*
452  * Remove the tablesync origin tracking if exists.
453  *
454  * The normal case origin drop is done here instead of in the
455  * process_syncing_tables_for_sync function because we don't
456  * allow to drop the origin till the process owning the origin
457  * is alive.
458  *
459  * There is a chance that the user is concurrently performing
460  * refresh for the subscription where we remove the table
461  * state and its origin and by this time the origin might be
462  * already removed. So passing missing_ok = true.
463  */
465  rstate->relid,
466  originname,
467  sizeof(originname));
468  replorigin_drop_by_name(originname, true, false);
469 
470  /*
471  * Update the state to READY only after the origin cleanup.
472  */
474  rstate->relid, rstate->state,
475  rstate->lsn);
476  }
477  }
478  else
479  {
480  LogicalRepWorker *syncworker;
481 
482  /*
483  * Look for a sync worker for this relation.
484  */
485  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
486 
488  rstate->relid, false);
489 
490  if (syncworker)
491  {
492  /* Found one, update our copy of its state */
493  SpinLockAcquire(&syncworker->relmutex);
494  rstate->state = syncworker->relstate;
495  rstate->lsn = syncworker->relstate_lsn;
496  if (rstate->state == SUBREL_STATE_SYNCWAIT)
497  {
498  /*
499  * Sync worker is waiting for apply. Tell sync worker it
500  * can catchup now.
501  */
502  syncworker->relstate = SUBREL_STATE_CATCHUP;
503  syncworker->relstate_lsn =
504  Max(syncworker->relstate_lsn, current_lsn);
505  }
506  SpinLockRelease(&syncworker->relmutex);
507 
508  /* If we told worker to catch up, wait for it. */
509  if (rstate->state == SUBREL_STATE_SYNCWAIT)
510  {
511  /* Signal the sync worker, as it may be waiting for us. */
512  if (syncworker->proc)
513  logicalrep_worker_wakeup_ptr(syncworker);
514 
515  /* Now safe to release the LWLock */
516  LWLockRelease(LogicalRepWorkerLock);
517 
518  /*
519  * Enter busy loop and wait for synchronization worker to
520  * reach expected state (or die trying).
521  */
522  if (!started_tx)
523  {
525  started_tx = true;
526  }
527 
529  SUBREL_STATE_SYNCDONE);
530  }
531  else
532  LWLockRelease(LogicalRepWorkerLock);
533  }
534  else
535  {
536  /*
537  * If there is no sync worker for this table yet, count
538  * running sync workers for this subscription, while we have
539  * the lock.
540  */
541  int nsyncworkers =
543 
544  /* Now safe to release the LWLock */
545  LWLockRelease(LogicalRepWorkerLock);
546 
547  /*
548  * If there are free sync worker slot(s), start a new sync
549  * worker for the table.
550  */
551  if (nsyncworkers < max_sync_workers_per_subscription)
552  {
554  struct tablesync_start_time_mapping *hentry;
555  bool found;
556 
557  hentry = hash_search(last_start_times, &rstate->relid,
558  HASH_ENTER, &found);
559 
560  if (!found ||
561  TimestampDifferenceExceeds(hentry->last_start_time, now,
563  {
568  rstate->relid);
569  hentry->last_start_time = now;
570  }
571  }
572  }
573  }
574  }
575 
576  if (started_tx)
577  {
579  pgstat_report_stat(false);
580  }
581 }
Subscription * MySubscription
Definition: worker.c:161
#define NIL
Definition: pg_list.h:65
void hash_destroy(HTAB *hashp)
Definition: dynahash.c:862
#define HASH_ELEM
Definition: hsearch.h:95
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
int64 TimestampTz
Definition: timestamp.h:39
void replorigin_drop_by_name(char *name, bool missing_ok, bool nowait)
Definition: origin.c:414
void CommitTransactionCommand(void)
Definition: xact.c:2939
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Size entrysize
Definition: hsearch.h:76
static bool wait_for_relation_state_change(Oid relid, char expected_state)
Definition: tablesync.c:167
void pgstat_report_stat(bool disconnect)
Definition: pgstat.c:846
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
unsigned int Oid
Definition: postgres_ext.h:31
static bool table_states_valid
Definition: tablesync.c:118
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1711
void list_free_deep(List *list)
Definition: list.c:1405
XLogRecPtr relstate_lsn
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1816
#define NAMEDATALEN
void logicalrep_worker_wakeup_ptr(LogicalRepWorker *worker)
Definition: launcher.c:559
#define SpinLockAcquire(lock)
Definition: spin.h:62
Definition: dynahash.c:219
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
int max_sync_workers_per_subscription
Definition: launcher.c:55
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:349
List * lappend(List *list, void *datum)
Definition: list.c:336
int wal_retrieve_retry_interval
Definition: xlog.c:112
#define SpinLockRelease(lock)
Definition: spin.h:64
#define HASH_BLOBS
Definition: hsearch.h:97
void UpdateSubscriptionRelState(Oid subid, Oid relid, char state, XLogRecPtr sublsn)
Size keysize
Definition: hsearch.h:75
int logicalrep_sync_worker_count(Oid subid)
Definition: launcher.c:665
#define Max(x, y)
Definition: c.h:980
void logicalrep_worker_launch(Oid dbid, Oid subid, const char *subname, Oid userid, Oid relid)
Definition: launcher.c:272
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:221
void StartTransactionCommand(void)
Definition: xact.c:2838
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1203
bool IsTransactionState(void)
Definition: xact.c:371
void ReplicationOriginNameForTablesync(Oid suboid, Oid relid, char *originname, int szorgname)
Definition: tablesync.c:898
void * palloc(Size size)
Definition: mcxt.c:1062
Definition: pg_list.h:50
List * GetSubscriptionNotReadyRelations(Oid subid)
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1544
MemoryContext CacheMemoryContext
Definition: mcxt.c:51

◆ process_syncing_tables_for_sync()

static void process_syncing_tables_for_sync ( XLogRecPtr  current_lsn)
static

Definition at line 278 of file tablesync.c.

References IsTransactionState(), MyLogicalRepWorker, NAMEDATALEN, LogicalRepWorker::relid, LogicalRepWorker::relmutex, LogicalRepWorker::relstate, LogicalRepWorker::relstate_lsn, ReplicationSlotDropAtPubNode(), ReplicationSlotNameForTablesync(), SpinLockAcquire, SpinLockRelease, StartTransactionCommand(), LogicalRepWorker::subid, UpdateSubscriptionRelState(), walrcv_endstreaming, and wrconn.

Referenced by process_syncing_tables().

279 {
281 
282  if (MyLogicalRepWorker->relstate == SUBREL_STATE_CATCHUP &&
283  current_lsn >= MyLogicalRepWorker->relstate_lsn)
284  {
285  TimeLineID tli;
286  char syncslotname[NAMEDATALEN] = {0};
287 
288  MyLogicalRepWorker->relstate = SUBREL_STATE_SYNCDONE;
289  MyLogicalRepWorker->relstate_lsn = current_lsn;
290 
292 
293  /*
294  * UpdateSubscriptionRelState must be called within a transaction.
295  * That transaction will be ended within the finish_sync_worker().
296  */
297  if (!IsTransactionState())
299 
304 
305  /* End wal streaming so wrconn can be re-used to drop the slot. */
307 
308  /*
309  * Cleanup the tablesync slot.
310  *
311  * This has to be done after updating the state because otherwise if
312  * there is an error while doing the database operations we won't be
313  * able to rollback dropped slot.
314  */
317  syncslotname,
318  sizeof(syncslotname));
319 
320  /*
321  * It is important to give an error if we are unable to drop the slot,
322  * otherwise, it won't be dropped till the corresponding subscription
323  * is dropped. So passing missing_ok = false.
324  */
325  ReplicationSlotDropAtPubNode(wrconn, syncslotname, false);
326 
327  finish_sync_worker();
328  }
329  else
331 }
WalReceiverConn * wrconn
Definition: worker.c:159
#define walrcv_endstreaming(conn, next_tli)
Definition: walreceiver.h:417
uint32 TimeLineID
Definition: xlogdefs.h:59
void ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok)
XLogRecPtr relstate_lsn
#define NAMEDATALEN
#define SpinLockAcquire(lock)
Definition: spin.h:62
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
#define SpinLockRelease(lock)
Definition: spin.h:64
void UpdateSubscriptionRelState(Oid subid, Oid relid, char state, XLogRecPtr sublsn)
void StartTransactionCommand(void)
Definition: xact.c:2838
bool IsTransactionState(void)
Definition: xact.c:371
void ReplicationSlotNameForTablesync(Oid suboid, Oid relid, char *syncslotname, int szslot)
Definition: tablesync.c:885

◆ ReplicationOriginNameForTablesync()

void ReplicationOriginNameForTablesync ( Oid  suboid,
Oid  relid,
char *  originname,
int  szorgname 
)

Definition at line 898 of file tablesync.c.

References snprintf.

Referenced by AlterSubscription_refresh(), DropSubscription(), LogicalRepSyncTableStart(), and process_syncing_tables_for_apply().

900 {
901  snprintf(originname, szorgname, "pg_%u_%u", suboid, relid);
902 }
#define snprintf
Definition: port.h:216

◆ ReplicationSlotNameForTablesync()

void ReplicationSlotNameForTablesync ( Oid  suboid,
Oid  relid,
char *  syncslotname,
int  szslot 
)

Definition at line 885 of file tablesync.c.

References GetSystemIdentifier(), snprintf, and UINT64_FORMAT.

Referenced by AlterSubscription_refresh(), DropSubscription(), LogicalRepSyncTableStart(), process_syncing_tables_for_sync(), and ReportSlotConnectionError().

887 {
888  snprintf(syncslotname, szslot, "pg_%u_sync_%u_" UINT64_FORMAT, suboid,
889  relid, GetSystemIdentifier());
890 }
uint64 GetSystemIdentifier(void)
Definition: xlog.c:4965
#define snprintf
Definition: port.h:216
#define UINT64_FORMAT
Definition: c.h:484

◆ wait_for_relation_state_change()

static bool wait_for_relation_state_change ( Oid  relid,
char  expected_state 
)
static

Definition at line 167 of file tablesync.c.

References CHECK_FOR_INTERRUPTS, GetSubscriptionRelState(), InvalidateCatalogSnapshot(), logicalrep_worker_find(), LW_SHARED, LWLockAcquire(), LWLockRelease(), MyLatch, MyLogicalRepWorker, ResetLatch(), LogicalRepWorker::subid, WAIT_EVENT_LOGICAL_SYNC_STATE_CHANGE, WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, and WL_TIMEOUT.

Referenced by process_syncing_tables_for_apply().

168 {
169  char state;
170 
171  for (;;)
172  {
173  LogicalRepWorker *worker;
174  XLogRecPtr statelsn;
175 
177 
180  relid, &statelsn);
181 
182  if (state == SUBREL_STATE_UNKNOWN)
183  break;
184 
185  if (state == expected_state)
186  return true;
187 
188  /* Check if the sync worker is still running and bail if not. */
189  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
191  false);
192  LWLockRelease(LogicalRepWorkerLock);
193  if (!worker)
194  break;
195 
196  (void) WaitLatch(MyLatch,
199 
201  }
202 
203  return false;
204 }
#define WL_TIMEOUT
Definition: latch.h:128
void ResetLatch(Latch *latch)
Definition: latch.c:660
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:452
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1816
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:456
char GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn)
uint64 XLogRecPtr
Definition: xlogdefs.h:21
Definition: regguts.h:317
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:221
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1203
struct Latch * MyLatch
Definition: globals.c:57
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:102
#define WL_LATCH_SET
Definition: latch.h:125
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130

◆ wait_for_worker_state_change()

static bool wait_for_worker_state_change ( char  expected_state)
static

Definition at line 215 of file tablesync.c.

References CHECK_FOR_INTERRUPTS, InvalidOid, logicalrep_worker_find(), logicalrep_worker_wakeup_ptr(), LW_SHARED, LWLockAcquire(), LWLockRelease(), MyLatch, MyLogicalRepWorker, LogicalRepWorker::proc, LogicalRepWorker::relstate, ResetLatch(), LogicalRepWorker::subid, WAIT_EVENT_LOGICAL_SYNC_STATE_CHANGE, WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, and WL_TIMEOUT.

Referenced by LogicalRepSyncTableStart().

216 {
217  int rc;
218 
219  for (;;)
220  {
221  LogicalRepWorker *worker;
222 
224 
225  /*
226  * Done if already in correct state. (We assume this fetch is atomic
227  * enough to not give a misleading answer if we do it with no lock.)
228  */
229  if (MyLogicalRepWorker->relstate == expected_state)
230  return true;
231 
232  /*
233  * Bail out if the apply worker has died, else signal it we're
234  * waiting.
235  */
236  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
238  InvalidOid, false);
239  if (worker && worker->proc)
241  LWLockRelease(LogicalRepWorkerLock);
242  if (!worker)
243  break;
244 
245  /*
246  * Wait. We expect to get a latch signal back from the apply worker,
247  * but use a timeout in case it dies without sending one.
248  */
249  rc = WaitLatch(MyLatch,
252 
253  if (rc & WL_LATCH_SET)
255  }
256 
257  return false;
258 }
#define WL_TIMEOUT
Definition: latch.h:128
void ResetLatch(Latch *latch)
Definition: latch.c:660
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:452
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1816
void logicalrep_worker_wakeup_ptr(LogicalRepWorker *worker)
Definition: launcher.c:559
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
#define InvalidOid
Definition: postgres_ext.h:36
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:221
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1203
struct Latch * MyLatch
Definition: globals.c:57
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:102
#define WL_LATCH_SET
Definition: latch.h:125
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130

Variable Documentation

◆ copybuf

◆ table_states_valid

bool table_states_valid = false
static