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)
 
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 568 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().

569 {
570  int bytesread = 0;
571  int avail;
572 
573  /* If there are some leftover data from previous read, use it. */
574  avail = copybuf->len - copybuf->cursor;
575  if (avail)
576  {
577  if (avail > maxread)
578  avail = maxread;
579  memcpy(outbuf, &copybuf->data[copybuf->cursor], avail);
580  copybuf->cursor += avail;
581  maxread -= avail;
582  bytesread += avail;
583  }
584 
585  while (maxread > 0 && bytesread < minread)
586  {
588  int len;
589  char *buf = NULL;
590 
591  for (;;)
592  {
593  /* Try read the data. */
594  len = walrcv_receive(wrconn, &buf, &fd);
595 
597 
598  if (len == 0)
599  break;
600  else if (len < 0)
601  return bytesread;
602  else
603  {
604  /* Process the data */
605  copybuf->data = buf;
606  copybuf->len = len;
607  copybuf->cursor = 0;
608 
609  avail = copybuf->len - copybuf->cursor;
610  if (avail > maxread)
611  avail = maxread;
612  memcpy(outbuf, &copybuf->data[copybuf->cursor], avail);
613  outbuf = (void *) ((char *) outbuf + avail);
614  copybuf->cursor += avail;
615  maxread -= avail;
616  bytesread += avail;
617  }
618 
619  if (maxread <= 0 || bytesread >= minread)
620  return bytesread;
621  }
622 
623  /*
624  * Wait for more data or latch.
625  */
626  (void) WaitLatchOrSocket(MyLatch,
629  fd, 1000L, WAIT_EVENT_LOGICAL_SYNC_DATA);
630 
632  }
633 
634  return bytesread;
635 }
WalReceiverConn * wrconn
Definition: worker.c:100
#define WL_TIMEOUT
Definition: latch.h:127
#define walrcv_receive(conn, buffer, wait_fd)
Definition: walreceiver.h:273
#define WL_SOCKET_READABLE
Definition: latch.h:125
static int fd(const char *x, int i)
Definition: preproc-init.c:105
void ResetLatch(Latch *latch)
Definition: latch.c:519
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:369
int pgsocket
Definition: port.h:31
#define PGINVALID_SOCKET
Definition: port.h:33
StringInfo copybuf
Definition: tablesync.c:115
struct Latch * MyLatch
Definition: globals.c:54
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
#define WL_LATCH_SET
Definition: latch.h:124
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:129

◆ copy_table()

static void copy_table ( Relation  rel)
static

Definition at line 751 of file tablesync.c.

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

Referenced by LogicalRepSyncTableStart().

752 {
753  LogicalRepRelMapEntry *relmapentry;
754  LogicalRepRelation lrel;
755  WalRcvExecResult *res;
756  StringInfoData cmd;
757  CopyState cstate;
758  List *attnamelist;
759  ParseState *pstate;
760 
761  /* Get the publisher relation info. */
763  RelationGetRelationName(rel), &lrel);
764 
765  /* Put the relation into relmap. */
767 
768  /* Map the publisher relation to local one. */
769  relmapentry = logicalrep_rel_open(lrel.remoteid, NoLock);
770  Assert(rel == relmapentry->localrel);
771 
772  /* Start copy on the publisher. */
773  initStringInfo(&cmd);
774  appendStringInfo(&cmd, "COPY %s TO STDOUT",
776  res = walrcv_exec(wrconn, cmd.data, 0, NULL);
777  pfree(cmd.data);
778  if (res->status != WALRCV_OK_COPY_OUT)
779  ereport(ERROR,
780  (errmsg("could not start initial contents copy for table \"%s.%s\": %s",
781  lrel.nspname, lrel.relname, res->err)));
782  walrcv_clear_result(res);
783 
785 
786  pstate = make_parsestate(NULL);
788  NULL, false, false);
789 
790  attnamelist = make_copy_attnamelist(relmapentry);
791  cstate = BeginCopyFrom(pstate, rel, NULL, false, copy_read_data, attnamelist, NIL);
792 
793  /* Do the copy */
794  (void) CopyFrom(cstate);
795 
796  logicalrep_rel_close(relmapentry, NoLock);
797 }
#define NIL
Definition: pg_list.h:65
WalReceiverConn * wrconn
Definition: worker.c:100
CopyState BeginCopyFrom(ParseState *pstate, Relation rel, const char *filename, bool is_program, copy_data_source_cb data_source_cb, List *attnamelist, List *options)
Definition: copy.c:3387
StringInfo makeStringInfo(void)
Definition: stringinfo.c:28
#define AccessShareLock
Definition: lockdefs.h:36
uint64 CopyFrom(CopyState cstate)
Definition: copy.c:2658
void logicalrep_rel_close(LogicalRepRelMapEntry *rel, LOCKMODE lockmode)
Definition: relation.c:368
LogicalRepRelId remoteid
Definition: logicalproto.h:45
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void logicalrep_relmap_update(LogicalRepRelation *remoterel)
Definition: relation.c:154
static void walrcv_clear_result(WalRcvExecResult *walres)
Definition: walreceiver.h:285
void pfree(void *pointer)
Definition: mcxt.c:1031
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
#define ERROR
Definition: elog.h:43
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3094
#define NoLock
Definition: lockdefs.h:34
RangeTblEntry * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
#define RelationGetRelationName(relation)
Definition: rel.h:450
LogicalRepRelMapEntry * logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
Definition: relation.c:219
#define ereport(elevel, rest)
Definition: elog.h:141
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:10712
StringInfo copybuf
Definition: tablesync.c:115
static void fetch_remote_table_info(char *nspname, char *relname, LogicalRepRelation *lrel)
Definition: tablesync.c:643
#define Assert(condition)
Definition: c.h:732
WalRcvExecStatus status
Definition: walreceiver.h:195
int errmsg(const char *fmt,...)
Definition: elog.c:784
static int copy_read_data(void *outbuf, int minread, int maxread)
Definition: tablesync.c:568
static List * make_copy_attnamelist(LogicalRepRelMapEntry *rel)
Definition: tablesync.c:548
Definition: pg_list.h:50
#define walrcv_exec(conn, exec, nRetTypes, retTypes)
Definition: walreceiver.h:279
#define RelationGetNamespace(relation)
Definition: rel.h:457

◆ fetch_remote_table_info()

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

Definition at line 643 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(), MakeSingleTupleTableSlot(), MaxTupleAttributeNumber, LogicalRepRelation::natts, LogicalRepRelation::nspname, palloc0(), pfree(), quote_literal_cstr(), 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().

645 {
646  WalRcvExecResult *res;
647  StringInfoData cmd;
648  TupleTableSlot *slot;
649  Oid tableRow[2] = {OIDOID, CHAROID};
650  Oid attrRow[4] = {TEXTOID, OIDOID, INT4OID, BOOLOID};
651  bool isnull;
652  int natt;
653 
654  lrel->nspname = nspname;
655  lrel->relname = relname;
656 
657  /* First fetch Oid and replica identity. */
658  initStringInfo(&cmd);
659  appendStringInfo(&cmd, "SELECT c.oid, c.relreplident"
660  " FROM pg_catalog.pg_class c"
661  " INNER JOIN pg_catalog.pg_namespace n"
662  " ON (c.relnamespace = n.oid)"
663  " WHERE n.nspname = %s"
664  " AND c.relname = %s"
665  " AND c.relkind = 'r'",
666  quote_literal_cstr(nspname),
668  res = walrcv_exec(wrconn, cmd.data, 2, tableRow);
669 
670  if (res->status != WALRCV_OK_TUPLES)
671  ereport(ERROR,
672  (errmsg("could not fetch table info for table \"%s.%s\" from publisher: %s",
673  nspname, relname, res->err)));
674 
676  if (!tuplestore_gettupleslot(res->tuplestore, true, false, slot))
677  ereport(ERROR,
678  (errmsg("table \"%s.%s\" not found on publisher",
679  nspname, relname)));
680 
681  lrel->remoteid = DatumGetObjectId(slot_getattr(slot, 1, &isnull));
682  Assert(!isnull);
683  lrel->replident = DatumGetChar(slot_getattr(slot, 2, &isnull));
684  Assert(!isnull);
685 
687  walrcv_clear_result(res);
688 
689  /* Now fetch columns. */
690  resetStringInfo(&cmd);
691  appendStringInfo(&cmd,
692  "SELECT a.attname,"
693  " a.atttypid,"
694  " a.atttypmod,"
695  " a.attnum = ANY(i.indkey)"
696  " FROM pg_catalog.pg_attribute a"
697  " LEFT JOIN pg_catalog.pg_index i"
698  " ON (i.indexrelid = pg_get_replica_identity_index(%u))"
699  " WHERE a.attnum > 0::pg_catalog.int2"
700  " AND NOT a.attisdropped %s"
701  " AND a.attrelid = %u"
702  " ORDER BY a.attnum",
703  lrel->remoteid,
704  (walrcv_server_version(wrconn) >= 120000 ? "AND a.attgenerated = ''" : ""),
705  lrel->remoteid);
706  res = walrcv_exec(wrconn, cmd.data, 4, attrRow);
707 
708  if (res->status != WALRCV_OK_TUPLES)
709  ereport(ERROR,
710  (errmsg("could not fetch table info for table \"%s.%s\": %s",
711  nspname, relname, res->err)));
712 
713  /* We don't know the number of rows coming, so allocate enough space. */
714  lrel->attnames = palloc0(MaxTupleAttributeNumber * sizeof(char *));
715  lrel->atttyps = palloc0(MaxTupleAttributeNumber * sizeof(Oid));
716  lrel->attkeys = NULL;
717 
718  natt = 0;
720  while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
721  {
722  lrel->attnames[natt] =
723  TextDatumGetCString(slot_getattr(slot, 1, &isnull));
724  Assert(!isnull);
725  lrel->atttyps[natt] = DatumGetObjectId(slot_getattr(slot, 2, &isnull));
726  Assert(!isnull);
727  if (DatumGetBool(slot_getattr(slot, 4, &isnull)))
728  lrel->attkeys = bms_add_member(lrel->attkeys, natt);
729 
730  /* Should never happen. */
731  if (++natt >= MaxTupleAttributeNumber)
732  elog(ERROR, "too many columns in remote table \"%s.%s\"",
733  nspname, relname);
734 
735  ExecClearTuple(slot);
736  }
738 
739  lrel->natts = natt;
740 
741  walrcv_clear_result(res);
742  pfree(cmd.data);
743 }
WalReceiverConn * wrconn
Definition: worker.c:100
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:102
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:426
#define MaxTupleAttributeNumber
Definition: htup_details.h:33
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1203
#define DatumGetObjectId(X)
Definition: postgres.h:500
#define walrcv_server_version(conn)
Definition: walreceiver.h:265
NameData relname
Definition: pg_class.h:35
unsigned int Oid
Definition: postgres_ext.h:31
Bitmapset * attkeys
Definition: logicalproto.h:52
LogicalRepRelId remoteid
Definition: logicalproto.h:45
static void walrcv_clear_result(WalRcvExecResult *walres)
Definition: walreceiver.h:285
void pfree(void *pointer)
Definition: mcxt.c:1031
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:78
TupleDesc tupledesc
Definition: walreceiver.h:198
#define ERROR
Definition: elog.h:43
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1219
#define DatumGetBool(X)
Definition: postgres.h:393
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:62
#define ereport(elevel, rest)
Definition: elog.h:141
void initStringInfo(StringInfo str)
Definition: stringinfo.c:46
#define TextDatumGetCString(d)
Definition: builtins.h:84
void * palloc0(Size size)
Definition: mcxt.c:955
#define DatumGetChar(X)
Definition: postgres.h:409
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:382
bool tuplestore_gettupleslot(Tuplestorestate *state, bool forward, bool copy, TupleTableSlot *slot)
Definition: tuplestore.c:1078
Tuplestorestate * tuplestore
Definition: walreceiver.h:197
#define Assert(condition)
Definition: c.h:732
WalRcvExecStatus status
Definition: walreceiver.h:195
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
const TupleTableSlotOps TTSOpsMinimalTuple
Definition: execTuples.c:86
#define walrcv_exec(conn, exec, nRetTypes, retTypes)
Definition: walreceiver.h:279

◆ invalidate_syncing_table_states()

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

Definition at line 263 of file tablesync.c.

References table_states_valid.

Referenced by ApplyWorkerMain().

264 {
265  table_states_valid = false;
266 }
static bool table_states_valid
Definition: tablesync.c:113

◆ LogicalRepSyncTableStart()

char* LogicalRepSyncTableStart ( XLogRecPtr origin_startpos)

Definition at line 805 of file tablesync.c.

References CommandCounterIncrement(), CommitTransactionCommand(), Subscription::conninfo, copy_table(), CRS_USE_SNAPSHOT, elog, ereport, WalRcvExecResult::err, errdetail(), errmsg(), ERROR, GetSubscriptionRelState(), GetTransactionSnapshot(), InvalidXLogRecPtr, MyLogicalRepWorker, MySubscription, NAMEDATALEN, NoLock, Subscription::oid, pgstat_report_stat(), PopActiveSnapshot(), psprintf(), PushActiveSnapshot(), LogicalRepWorker::relid, LogicalRepWorker::relmutex, LogicalRepWorker::relstate, LogicalRepWorker::relstate_lsn, RowExclusiveLock, Subscription::slotname, SpinLockAcquire, SpinLockRelease, StartTransactionCommand(), StaticAssertStmt, WalRcvExecResult::status, LogicalRepWorker::subid, table_close(), table_open(), UpdateSubscriptionRelState(), wait_for_worker_state_change(), walrcv_clear_result(), walrcv_connect, walrcv_create_slot, walrcv_exec, WALRCV_OK_COMMAND, and wrconn.

Referenced by ApplyWorkerMain().

806 {
807  char *slotname;
808  char *err;
809  char relstate;
810  XLogRecPtr relstate_lsn;
811 
812  /* Check the state of the table synchronization. */
816  &relstate_lsn, true);
818 
820  MyLogicalRepWorker->relstate = relstate;
821  MyLogicalRepWorker->relstate_lsn = relstate_lsn;
823 
824  /*
825  * To build a slot name for the sync work, we are limited to NAMEDATALEN -
826  * 1 characters. We cut the original slot name to NAMEDATALEN - 28 chars
827  * and append _%u_sync_%u (1 + 10 + 6 + 10 + '\0'). (It's actually the
828  * NAMEDATALEN on the remote that matters, but this scheme will also work
829  * reasonably if that is different.)
830  */
831  StaticAssertStmt(NAMEDATALEN >= 32, "NAMEDATALEN too small"); /* for sanity */
832  slotname = psprintf("%.*s_%u_sync_%u",
833  NAMEDATALEN - 28,
837 
838  /*
839  * Here we use the slot name instead of the subscription name as the
840  * application_name, so that it is different from the main apply worker,
841  * so that synchronous replication can distinguish them.
842  */
843  wrconn = walrcv_connect(MySubscription->conninfo, true, slotname, &err);
844  if (wrconn == NULL)
845  ereport(ERROR,
846  (errmsg("could not connect to the publisher: %s", err)));
847 
848  switch (MyLogicalRepWorker->relstate)
849  {
850  case SUBREL_STATE_INIT:
851  case SUBREL_STATE_DATASYNC:
852  {
853  Relation rel;
854  WalRcvExecResult *res;
855 
857  MyLogicalRepWorker->relstate = SUBREL_STATE_DATASYNC;
860 
861  /* Update the state and make it visible to others. */
868  pgstat_report_stat(false);
869 
870  /*
871  * We want to do the table data sync in a single transaction.
872  */
874 
875  /*
876  * Use a standard write lock here. It might be better to
877  * disallow access to the table while it's being synchronized.
878  * But we don't want to block the main apply process from
879  * working and it has to open the relation in RowExclusiveLock
880  * when remapping remote relation id to local one.
881  */
883 
884  /*
885  * Create a temporary slot for the sync process. We do this
886  * inside the transaction so that we can use the snapshot made
887  * by the slot to get existing data.
888  */
889  res = walrcv_exec(wrconn,
890  "BEGIN READ ONLY ISOLATION LEVEL "
891  "REPEATABLE READ", 0, NULL);
892  if (res->status != WALRCV_OK_COMMAND)
893  ereport(ERROR,
894  (errmsg("table copy could not start transaction on publisher"),
895  errdetail("The error was: %s", res->err)));
896  walrcv_clear_result(res);
897 
898  /*
899  * Create new temporary logical decoding slot.
900  *
901  * We'll use slot for data copy so make sure the snapshot is
902  * used for the transaction; that way the COPY will get data
903  * that is consistent with the lsn used by the slot to start
904  * decoding.
905  */
906  walrcv_create_slot(wrconn, slotname, true,
907  CRS_USE_SNAPSHOT, origin_startpos);
908 
910  copy_table(rel);
912 
913  res = walrcv_exec(wrconn, "COMMIT", 0, NULL);
914  if (res->status != WALRCV_OK_COMMAND)
915  ereport(ERROR,
916  (errmsg("table copy could not finish transaction on publisher"),
917  errdetail("The error was: %s", res->err)));
918  walrcv_clear_result(res);
919 
920  table_close(rel, NoLock);
921 
922  /* Make the copy visible. */
924 
925  /*
926  * We are done with the initial data synchronization, update
927  * the state.
928  */
930  MyLogicalRepWorker->relstate = SUBREL_STATE_SYNCWAIT;
931  MyLogicalRepWorker->relstate_lsn = *origin_startpos;
933 
934  /* Wait for main apply worker to tell us to catchup. */
935  wait_for_worker_state_change(SUBREL_STATE_CATCHUP);
936 
937  /*----------
938  * There are now two possible states here:
939  * a) Sync is behind the apply. If that's the case we need to
940  * catch up with it by consuming the logical replication
941  * stream up to the relstate_lsn. For that, we exit this
942  * function and continue in ApplyWorkerMain().
943  * b) Sync is caught up with the apply. So it can just set
944  * the state to SYNCDONE and finish.
945  *----------
946  */
947  if (*origin_startpos >= MyLogicalRepWorker->relstate_lsn)
948  {
949  /*
950  * Update the new state in catalog. No need to bother
951  * with the shmem state as we are exiting for good.
952  */
955  SUBREL_STATE_SYNCDONE,
956  *origin_startpos);
957  finish_sync_worker();
958  }
959  break;
960  }
961  case SUBREL_STATE_SYNCDONE:
962  case SUBREL_STATE_READY:
963  case SUBREL_STATE_UNKNOWN:
964 
965  /*
966  * Nothing to do here but finish. (UNKNOWN means the relation was
967  * removed from pg_subscription_rel before the sync worker could
968  * start.)
969  */
970  finish_sync_worker();
971  break;
972  default:
973  elog(ERROR, "unknown relation state \"%c\"",
975  }
976 
977  return slotname;
978 }
Subscription * MySubscription
Definition: worker.c:102
WalReceiverConn * wrconn
Definition: worker.c:100
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
void CommitTransactionCommand(void)
Definition: xact.c:2895
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
static void copy_table(Relation rel)
Definition: tablesync.c:751
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
#define walrcv_create_slot(conn, slotname, temporary, snapshot_action, lsn)
Definition: walreceiver.h:277
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
XLogRecPtr relstate_lsn
#define NAMEDATALEN
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:842
#define SpinLockAcquire(lock)
Definition: spin.h:62
static void walrcv_clear_result(WalRcvExecResult *walres)
Definition: walreceiver.h:285
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:64
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:735
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:860
#define ereport(elevel, rest)
Definition: elog.h:141
#define SpinLockRelease(lock)
Definition: spin.h:64
void CommandCounterIncrement(void)
Definition: xact.c:1003
void UpdateSubscriptionRelState(Oid subid, Oid relid, char state, XLogRecPtr sublsn)
uint64 XLogRecPtr
Definition: xlogdefs.h:21
WalRcvExecStatus status
Definition: walreceiver.h:195
void StartTransactionCommand(void)
Definition: xact.c:2794
char GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn, bool missing_ok)
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
static bool wait_for_worker_state_change(char expected_state)
Definition: tablesync.c:214
#define walrcv_exec(conn, exec, nRetTypes, retTypes)
Definition: walreceiver.h:279
void pgstat_report_stat(bool force)
Definition: pgstat.c:813
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:255

◆ make_copy_attnamelist()

static List* make_copy_attnamelist ( LogicalRepRelMapEntry rel)
static

Definition at line 548 of file tablesync.c.

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

Referenced by copy_table().

549 {
550  List *attnamelist = NIL;
551  int i;
552 
553  for (i = 0; i < rel->remoterel.natts; i++)
554  {
555  attnamelist = lappend(attnamelist,
556  makeString(rel->remoterel.attnames[i]));
557  }
558 
559 
560  return attnamelist;
561 }
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:321
int i
Definition: pg_list.h:50

◆ pg_attribute_noreturn()

static void pg_attribute_noreturn ( )
static

Definition at line 121 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().

123 {
124  /*
125  * Commit any outstanding transaction. This is the usual case, unless
126  * there was nothing to do for the table.
127  */
128  if (IsTransactionState())
129  {
131  pgstat_report_stat(false);
132  }
133 
134  /* And flush all writes. */
136 
138  ereport(LOG,
139  (errmsg("logical replication table synchronization worker for subscription \"%s\", table \"%s\" has finished",
143 
144  /* Find the main apply worker and signal it. */
146 
147  /* Stop gracefully */
148  proc_exit(0);
149 }
Subscription * MySubscription
Definition: worker.c:102
void logicalrep_worker_wakeup(Oid subid, Oid relid)
Definition: launcher.c:606
void CommitTransactionCommand(void)
Definition: xact.c:2895
void proc_exit(int code)
Definition: ipc.c:104
#define LOG
Definition: elog.h:26
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2798
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:64
#define ereport(elevel, rest)
Definition: elog.h:141
#define InvalidOid
Definition: postgres_ext.h:36
XLogRecPtr GetXLogWriteRecPtr(void)
Definition: xlog.c:11165
void StartTransactionCommand(void)
Definition: xact.c:2794
bool IsTransactionState(void)
Definition: xact.c:356
int errmsg(const char *fmt,...)
Definition: elog.c:784
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1730
void pgstat_report_stat(bool force)
Definition: pgstat.c:813

◆ process_syncing_tables()

void process_syncing_tables ( XLogRecPtr  current_lsn)

Definition at line 536 of file tablesync.c.

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

Referenced by apply_handle_commit(), and LogicalRepApplyLoop().

537 {
538  if (am_tablesync_worker())
539  process_syncing_tables_for_sync(current_lsn);
540  else
542 }
static void process_syncing_tables_for_apply(XLogRecPtr current_lsn)
Definition: tablesync.c:327
static bool am_tablesync_worker(void)
static void process_syncing_tables_for_sync(XLogRecPtr current_lsn)
Definition: tablesync.c:277

◆ process_syncing_tables_for_apply()

static void process_syncing_tables_for_apply ( XLogRecPtr  current_lsn)
static

Definition at line 327 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, NIL, now(), Subscription::oid, palloc(), pgstat_report_stat(), LogicalRepWorker::proc, SubscriptionRelState::relid, LogicalRepWorker::relmutex, LogicalRepWorker::relstate, LogicalRepWorker::relstate_lsn, 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().

328 {
329  struct tablesync_start_time_mapping
330  {
331  Oid relid;
332  TimestampTz last_start_time;
333  };
334  static List *table_states = NIL;
335  static HTAB *last_start_times = NULL;
336  ListCell *lc;
337  bool started_tx = false;
338 
340 
341  /* We need up-to-date sync state info for subscription tables here. */
342  if (!table_states_valid)
343  {
344  MemoryContext oldctx;
345  List *rstates;
346  ListCell *lc;
347  SubscriptionRelState *rstate;
348 
349  /* Clean the old list. */
350  list_free_deep(table_states);
351  table_states = NIL;
352 
354  started_tx = true;
355 
356  /* Fetch all non-ready tables. */
358 
359  /* Allocate the tracking info in a permanent memory context. */
361  foreach(lc, rstates)
362  {
363  rstate = palloc(sizeof(SubscriptionRelState));
364  memcpy(rstate, lfirst(lc), sizeof(SubscriptionRelState));
365  table_states = lappend(table_states, rstate);
366  }
367  MemoryContextSwitchTo(oldctx);
368 
369  table_states_valid = true;
370  }
371 
372  /*
373  * Prepare a hash table for tracking last start times of workers, to avoid
374  * immediate restarts. We don't need it if there are no tables that need
375  * syncing.
376  */
377  if (table_states && !last_start_times)
378  {
379  HASHCTL ctl;
380 
381  memset(&ctl, 0, sizeof(ctl));
382  ctl.keysize = sizeof(Oid);
383  ctl.entrysize = sizeof(struct tablesync_start_time_mapping);
384  last_start_times = hash_create("Logical replication table sync worker start times",
385  256, &ctl, HASH_ELEM | HASH_BLOBS);
386  }
387 
388  /*
389  * Clean up the hash table when we're done with all tables (just to
390  * release the bit of memory).
391  */
392  else if (!table_states && last_start_times)
393  {
394  hash_destroy(last_start_times);
395  last_start_times = NULL;
396  }
397 
398  /*
399  * Process all tables that are being synchronized.
400  */
401  foreach(lc, table_states)
402  {
404 
405  if (rstate->state == SUBREL_STATE_SYNCDONE)
406  {
407  /*
408  * Apply has caught up to the position where the table sync has
409  * finished. Mark the table as ready so that the apply will just
410  * continue to replicate it normally.
411  */
412  if (current_lsn >= rstate->lsn)
413  {
414  rstate->state = SUBREL_STATE_READY;
415  rstate->lsn = current_lsn;
416  if (!started_tx)
417  {
419  started_tx = true;
420  }
421 
423  rstate->relid, rstate->state,
424  rstate->lsn);
425  }
426  }
427  else
428  {
429  LogicalRepWorker *syncworker;
430 
431  /*
432  * Look for a sync worker for this relation.
433  */
434  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
435 
437  rstate->relid, false);
438 
439  if (syncworker)
440  {
441  /* Found one, update our copy of its state */
442  SpinLockAcquire(&syncworker->relmutex);
443  rstate->state = syncworker->relstate;
444  rstate->lsn = syncworker->relstate_lsn;
445  if (rstate->state == SUBREL_STATE_SYNCWAIT)
446  {
447  /*
448  * Sync worker is waiting for apply. Tell sync worker it
449  * can catchup now.
450  */
451  syncworker->relstate = SUBREL_STATE_CATCHUP;
452  syncworker->relstate_lsn =
453  Max(syncworker->relstate_lsn, current_lsn);
454  }
455  SpinLockRelease(&syncworker->relmutex);
456 
457  /* If we told worker to catch up, wait for it. */
458  if (rstate->state == SUBREL_STATE_SYNCWAIT)
459  {
460  /* Signal the sync worker, as it may be waiting for us. */
461  if (syncworker->proc)
462  logicalrep_worker_wakeup_ptr(syncworker);
463 
464  /* Now safe to release the LWLock */
465  LWLockRelease(LogicalRepWorkerLock);
466 
467  /*
468  * Enter busy loop and wait for synchronization worker to
469  * reach expected state (or die trying).
470  */
471  if (!started_tx)
472  {
474  started_tx = true;
475  }
476 
478  SUBREL_STATE_SYNCDONE);
479  }
480  else
481  LWLockRelease(LogicalRepWorkerLock);
482  }
483  else
484  {
485  /*
486  * If there is no sync worker for this table yet, count
487  * running sync workers for this subscription, while we have
488  * the lock.
489  */
490  int nsyncworkers =
492 
493  /* Now safe to release the LWLock */
494  LWLockRelease(LogicalRepWorkerLock);
495 
496  /*
497  * If there are free sync worker slot(s), start a new sync
498  * worker for the table.
499  */
500  if (nsyncworkers < max_sync_workers_per_subscription)
501  {
503  struct tablesync_start_time_mapping *hentry;
504  bool found;
505 
506  hentry = hash_search(last_start_times, &rstate->relid,
507  HASH_ENTER, &found);
508 
509  if (!found ||
510  TimestampDifferenceExceeds(hentry->last_start_time, now,
512  {
517  rstate->relid);
518  hentry->last_start_time = now;
519  }
520  }
521  }
522  }
523  }
524 
525  if (started_tx)
526  {
528  pgstat_report_stat(false);
529  }
530 }
Subscription * MySubscription
Definition: worker.c:102
#define NIL
Definition: pg_list.h:65
void hash_destroy(HTAB *hashp)
Definition: dynahash.c:814
#define HASH_ELEM
Definition: hsearch.h:87
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1569
int64 TimestampTz
Definition: timestamp.h:39
void CommitTransactionCommand(void)
Definition: xact.c:2895
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
Size entrysize
Definition: hsearch.h:73
static bool wait_for_relation_state_change(Oid relid, char expected_state)
Definition: tablesync.c:161
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:906
unsigned int Oid
Definition: postgres_ext.h:31
static bool table_states_valid
Definition: tablesync.c:113
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1668
void list_free_deep(List *list)
Definition: list.c:1387
XLogRecPtr relstate_lsn
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
void logicalrep_worker_wakeup_ptr(LogicalRepWorker *worker)
Definition: launcher.c:626
#define SpinLockAcquire(lock)
Definition: spin.h:62
Definition: dynahash.c:208
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:64
int max_sync_workers_per_subscription
Definition: launcher.c:62
List * lappend(List *list, void *datum)
Definition: list.c:321
int wal_retrieve_retry_interval
Definition: xlog.c:106
#define SpinLockRelease(lock)
Definition: spin.h:64
#define HASH_BLOBS
Definition: hsearch.h:88
HTAB * hash_create(const char *tabname, long nelem, HASHCTL *info, int flags)
Definition: dynahash.c:316
void UpdateSubscriptionRelState(Oid subid, Oid relid, char state, XLogRecPtr sublsn)
Size keysize
Definition: hsearch.h:72
int logicalrep_sync_worker_count(Oid subid)
Definition: launcher.c:746
#define Max(x, y)
Definition: c.h:898
void logicalrep_worker_launch(Oid dbid, Oid subid, const char *subname, Oid userid, Oid relid)
Definition: launcher.c:294
#define Assert(condition)
Definition: c.h:732
#define lfirst(lc)
Definition: pg_list.h:190
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:243
void StartTransactionCommand(void)
Definition: xact.c:2794
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
bool IsTransactionState(void)
Definition: xact.c:356
void * palloc(Size size)
Definition: mcxt.c:924
Definition: pg_list.h:50
List * GetSubscriptionNotReadyRelations(Oid subid)
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1533
MemoryContext CacheMemoryContext
Definition: mcxt.c:47
void pgstat_report_stat(bool force)
Definition: pgstat.c:813

◆ process_syncing_tables_for_sync()

static void process_syncing_tables_for_sync ( XLogRecPtr  current_lsn)
static

Definition at line 277 of file tablesync.c.

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

Referenced by process_syncing_tables().

278 {
280 
282 
283  if (MyLogicalRepWorker->relstate == SUBREL_STATE_CATCHUP &&
284  current_lsn >= MyLogicalRepWorker->relstate_lsn)
285  {
286  TimeLineID tli;
287 
288  MyLogicalRepWorker->relstate = SUBREL_STATE_SYNCDONE;
289  MyLogicalRepWorker->relstate_lsn = current_lsn;
290 
292 
297 
299  finish_sync_worker();
300  }
301  else
303 }
WalReceiverConn * wrconn
Definition: worker.c:100
#define walrcv_endstreaming(conn, next_tli)
Definition: walreceiver.h:271
uint32 TimeLineID
Definition: xlogdefs.h:52
XLogRecPtr relstate_lsn
#define SpinLockAcquire(lock)
Definition: spin.h:62
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:64
#define SpinLockRelease(lock)
Definition: spin.h:64
void UpdateSubscriptionRelState(Oid subid, Oid relid, char state, XLogRecPtr sublsn)
#define Assert(condition)
Definition: c.h:732
bool IsTransactionState(void)
Definition: xact.c:356

◆ wait_for_relation_state_change()

static bool wait_for_relation_state_change ( Oid  relid,
char  expected_state 
)
static

Definition at line 161 of file tablesync.c.

References am_tablesync_worker(), CHECK_FOR_INTERRUPTS, GetLatestSnapshot(), GetSubscriptionRelState(), InvalidOid, logicalrep_worker_find(), LW_SHARED, LWLockAcquire(), LWLockRelease(), MyLatch, MyLogicalRepWorker, PopActiveSnapshot(), PushActiveSnapshot(), 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().

162 {
163  char state;
164 
165  for (;;)
166  {
167  LogicalRepWorker *worker;
168  XLogRecPtr statelsn;
169 
171 
172  /* XXX use cache invalidation here to improve performance? */
175  relid, &statelsn, true);
177 
178  if (state == SUBREL_STATE_UNKNOWN)
179  return false;
180 
181  if (state == expected_state)
182  return true;
183 
184  /* Check if the sync worker is still running and bail if not. */
185  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
186 
187  /* Check if the opposite worker is still running and bail if not. */
189  am_tablesync_worker() ? InvalidOid : relid,
190  false);
191  LWLockRelease(LogicalRepWorkerLock);
192  if (!worker)
193  return false;
194 
195  (void) WaitLatch(MyLatch,
198 
200  }
201 
202  return false;
203 }
#define WL_TIMEOUT
Definition: latch.h:127
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
void ResetLatch(Latch *latch)
Definition: latch.c:519
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:344
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:64
static bool am_tablesync_worker(void)
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:735
#define InvalidOid
Definition: postgres_ext.h:36
uint64 XLogRecPtr
Definition: xlogdefs.h:21
Definition: regguts.h:298
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:243
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
char GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn, bool missing_ok)
Snapshot GetLatestSnapshot(void)
Definition: snapmgr.c:381
struct Latch * MyLatch
Definition: globals.c:54
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
#define WL_LATCH_SET
Definition: latch.h:124
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:129

◆ wait_for_worker_state_change()

static bool wait_for_worker_state_change ( char  expected_state)
static

Definition at line 214 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().

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

Variable Documentation

◆ copybuf

◆ table_states_valid

bool table_states_valid = false
static