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

Go to the source code of this file.

Data Structures

struct  LogicalRepCtxStruct
 
struct  LogicalRepWorkerId
 
struct  StopWorkersData
 

Macros

#define DEFAULT_NAPTIME_PER_CYCLE   180000L
 
#define PG_STAT_GET_SUBSCRIPTION_COLS   8
 

Typedefs

typedef struct LogicalRepCtxStruct LogicalRepCtxStruct
 
typedef struct LogicalRepWorkerId LogicalRepWorkerId
 
typedef struct StopWorkersData StopWorkersData
 

Functions

static void ApplyLauncherWakeup (void)
 
static void logicalrep_launcher_onexit (int code, Datum arg)
 
static void logicalrep_worker_onexit (int code, Datum arg)
 
static void logicalrep_worker_detach (void)
 
static void logicalrep_worker_cleanup (LogicalRepWorker *worker)
 
Datum pg_stat_get_subscription (PG_FUNCTION_ARGS)
 
static Listget_subscription_list (void)
 
static void WaitForReplicationWorkerAttach (LogicalRepWorker *worker, uint16 generation, BackgroundWorkerHandle *handle)
 
LogicalRepWorkerlogicalrep_worker_find (Oid subid, Oid relid, bool only_running)
 
Listlogicalrep_workers_find (Oid subid, bool only_running)
 
void logicalrep_worker_launch (Oid dbid, Oid subid, const char *subname, Oid userid, Oid relid)
 
void logicalrep_worker_stop (Oid subid, Oid relid)
 
void logicalrep_worker_stop_at_commit (Oid subid, Oid relid)
 
void logicalrep_worker_wakeup (Oid subid, Oid relid)
 
void logicalrep_worker_wakeup_ptr (LogicalRepWorker *worker)
 
void logicalrep_worker_attach (int slot)
 
static void logicalrep_launcher_sighup (SIGNAL_ARGS)
 
int logicalrep_sync_worker_count (Oid subid)
 
Size ApplyLauncherShmemSize (void)
 
void ApplyLauncherRegister (void)
 
void ApplyLauncherShmemInit (void)
 
bool XactManipulatesLogicalReplicationWorkers (void)
 
void AtEOXact_ApplyLauncher (bool isCommit)
 
void AtEOSubXact_ApplyLauncher (bool isCommit, int nestDepth)
 
void ApplyLauncherWakeupAtCommit (void)
 
void ApplyLauncherMain (Datum main_arg)
 
bool IsLogicalLauncher (void)
 

Variables

int max_logical_replication_workers = 4
 
int max_sync_workers_per_subscription = 2
 
LogicalRepWorkerMyLogicalRepWorker = NULL
 
LogicalRepCtxStructLogicalRepCtx
 
static StopWorkersDataon_commit_stop_workers = NULL
 
static volatile sig_atomic_t got_SIGHUP = false
 
static bool on_commit_launcher_wakeup = false
 

Macro Definition Documentation

◆ DEFAULT_NAPTIME_PER_CYCLE

#define DEFAULT_NAPTIME_PER_CYCLE   180000L

Definition at line 59 of file launcher.c.

Referenced by ApplyLauncherMain().

◆ PG_STAT_GET_SUBSCRIPTION_COLS

#define PG_STAT_GET_SUBSCRIPTION_COLS   8

Typedef Documentation

◆ LogicalRepCtxStruct

◆ LogicalRepWorkerId

◆ StopWorkersData

Function Documentation

◆ ApplyLauncherMain()

void ApplyLauncherMain ( Datum  main_arg)

Definition at line 972 of file launcher.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, BackgroundWorkerInitializeConnection(), BackgroundWorkerUnblockSignals(), before_shmem_exit(), CHECK_FOR_INTERRUPTS, Subscription::dbid, DEBUG1, DEFAULT_NAPTIME_PER_CYCLE, die, Subscription::enabled, ereport, errmsg(), get_subscription_list(), GetCurrentTimestamp(), got_SIGHUP, InvalidOid, LogicalRepCtxStruct::launcher_pid, lfirst, logicalrep_launcher_onexit(), logicalrep_launcher_sighup(), logicalrep_worker_find(), logicalrep_worker_launch(), LW_SHARED, LWLockAcquire(), LWLockRelease(), MemoryContextDelete(), MemoryContextSwitchTo(), MyLatch, MyProcPid, Subscription::name, now(), Subscription::oid, Subscription::owner, PGC_SIGHUP, pqsignal(), ProcessConfigFile(), ResetLatch(), SIGHUP, TimestampDifferenceExceeds(), TopMemoryContext, WAIT_EVENT_LOGICAL_LAUNCHER_MAIN, WaitLatch(), wal_retrieve_retry_interval, WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, and WL_TIMEOUT.

973 {
974  TimestampTz last_start_time = 0;
975 
976  ereport(DEBUG1,
977  (errmsg("logical replication launcher started")));
978 
980 
983 
984  /* Establish signal handlers. */
986  pqsignal(SIGTERM, die);
988 
989  /*
990  * Establish connection to nailed catalogs (we only ever access
991  * pg_subscription).
992  */
994 
995  /* Enter main loop */
996  for (;;)
997  {
998  int rc;
999  List *sublist;
1000  ListCell *lc;
1001  MemoryContext subctx;
1002  MemoryContext oldctx;
1003  TimestampTz now;
1004  long wait_time = DEFAULT_NAPTIME_PER_CYCLE;
1005 
1007 
1008  now = GetCurrentTimestamp();
1009 
1010  /* Limit the start retry to once a wal_retrieve_retry_interval */
1011  if (TimestampDifferenceExceeds(last_start_time, now,
1013  {
1014  /* Use temporary context for the database list and worker info. */
1016  "Logical Replication Launcher sublist",
1018  oldctx = MemoryContextSwitchTo(subctx);
1019 
1020  /* search for subscriptions to start or stop. */
1021  sublist = get_subscription_list();
1022 
1023  /* Start the missing workers for enabled subscriptions. */
1024  foreach(lc, sublist)
1025  {
1026  Subscription *sub = (Subscription *) lfirst(lc);
1027  LogicalRepWorker *w;
1028 
1029  if (!sub->enabled)
1030  continue;
1031 
1032  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
1033  w = logicalrep_worker_find(sub->oid, InvalidOid, false);
1034  LWLockRelease(LogicalRepWorkerLock);
1035 
1036  if (w == NULL)
1037  {
1038  last_start_time = now;
1039  wait_time = wal_retrieve_retry_interval;
1040 
1041  logicalrep_worker_launch(sub->dbid, sub->oid, sub->name,
1042  sub->owner, InvalidOid);
1043  }
1044  }
1045 
1046  /* Switch back to original memory context. */
1047  MemoryContextSwitchTo(oldctx);
1048  /* Clean the temporary memory. */
1049  MemoryContextDelete(subctx);
1050  }
1051  else
1052  {
1053  /*
1054  * The wait in previous cycle was interrupted in less than
1055  * wal_retrieve_retry_interval since last worker was started, this
1056  * usually means crash of the worker, so we should retry in
1057  * wal_retrieve_retry_interval again.
1058  */
1059  wait_time = wal_retrieve_retry_interval;
1060  }
1061 
1062  /* Wait for more work. */
1063  rc = WaitLatch(MyLatch,
1065  wait_time,
1067 
1068  if (rc & WL_LATCH_SET)
1069  {
1072  }
1073 
1074  if (got_SIGHUP)
1075  {
1076  got_SIGHUP = false;
1078  }
1079  }
1080 
1081  /* Not reachable */
1082 }
static volatile sig_atomic_t got_SIGHUP
Definition: launcher.c:104
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:169
#define DEBUG1
Definition: elog.h:25
int MyProcPid
Definition: globals.c:40
#define WL_TIMEOUT
Definition: latch.h:127
void ProcessConfigFile(GucContext context)
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1569
int64 TimestampTz
Definition: timestamp.h:39
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1668
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
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:191
#define SIGHUP
Definition: win32_port.h:163
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:333
static void logicalrep_launcher_onexit(int code, Datum arg)
Definition: launcher.c:705
#define ereport(elevel, rest)
Definition: elog.h:141
MemoryContext TopMemoryContext
Definition: mcxt.c:44
Definition: guc.h:72
int wal_retrieve_retry_interval
Definition: xlog.c:106
void BackgroundWorkerInitializeConnection(const char *dbname, const char *username, uint32 flags)
Definition: postmaster.c:5610
#define DEFAULT_NAPTIME_PER_CYCLE
Definition: launcher.c:59
uintptr_t Datum
Definition: postgres.h:367
static void logicalrep_launcher_sighup(SIGNAL_ARGS)
Definition: launcher.c:729
#define InvalidOid
Definition: postgres_ext.h:36
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
static List * get_subscription_list(void)
Definition: launcher.c:118
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
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
int errmsg(const char *fmt,...)
Definition: elog.c:784
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:75
struct Latch * MyLatch
Definition: globals.c:54
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:99
Definition: pg_list.h:50
#define WL_LATCH_SET
Definition: latch.h:124
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1533
#define die(msg)
Definition: pg_test_fsync.c:97
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:129
void BackgroundWorkerUnblockSignals(void)
Definition: postmaster.c:5662

◆ ApplyLauncherRegister()

void ApplyLauncherRegister ( void  )

Definition at line 789 of file launcher.c.

References BackgroundWorker::bgw_flags, BackgroundWorker::bgw_function_name, BackgroundWorker::bgw_library_name, BackgroundWorker::bgw_main_arg, BGW_MAXLEN, BackgroundWorker::bgw_name, BackgroundWorker::bgw_notify_pid, BackgroundWorker::bgw_restart_time, BackgroundWorker::bgw_start_time, BackgroundWorker::bgw_type, BGWORKER_BACKEND_DATABASE_CONNECTION, BGWORKER_SHMEM_ACCESS, BgWorkerStart_RecoveryFinished, max_logical_replication_workers, RegisterBackgroundWorker(), and snprintf.

Referenced by PostmasterMain().

790 {
791  BackgroundWorker bgw;
792 
794  return;
795 
796  memset(&bgw, 0, sizeof(bgw));
800  snprintf(bgw.bgw_library_name, BGW_MAXLEN, "postgres");
801  snprintf(bgw.bgw_function_name, BGW_MAXLEN, "ApplyLauncherMain");
803  "logical replication launcher");
805  "logical replication launcher");
806  bgw.bgw_restart_time = 5;
807  bgw.bgw_notify_pid = 0;
808  bgw.bgw_main_arg = (Datum) 0;
809 
811 }
void RegisterBackgroundWorker(BackgroundWorker *worker)
Definition: bgworker.c:848
int bgw_restart_time
Definition: bgworker.h:94
#define BGWORKER_SHMEM_ACCESS
Definition: bgworker.h:52
char bgw_function_name[BGW_MAXLEN]
Definition: bgworker.h:96
Datum bgw_main_arg
Definition: bgworker.h:97
uintptr_t Datum
Definition: postgres.h:367
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:90
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
int max_logical_replication_workers
Definition: launcher.c:61
#define BGW_MAXLEN
Definition: bgworker.h:85
BgWorkerStartTime bgw_start_time
Definition: bgworker.h:93
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:91
pid_t bgw_notify_pid
Definition: bgworker.h:99
char bgw_library_name[BGW_MAXLEN]
Definition: bgworker.h:95
#define snprintf
Definition: port.h:192

◆ ApplyLauncherShmemInit()

void ApplyLauncherShmemInit ( void  )

Definition at line 818 of file launcher.c.

References ApplyLauncherShmemSize(), max_logical_replication_workers, LogicalRepWorker::relmutex, ShmemInitStruct(), SpinLockInit, and LogicalRepCtxStruct::workers.

Referenced by CreateSharedMemoryAndSemaphores().

819 {
820  bool found;
821 
823  ShmemInitStruct("Logical Replication Launcher Data",
825  &found);
826 
827  if (!found)
828  {
829  int slot;
830 
832 
833  /* Initialize memory and spin locks for each worker slot. */
834  for (slot = 0; slot < max_logical_replication_workers; slot++)
835  {
836  LogicalRepWorker *worker = &LogicalRepCtx->workers[slot];
837 
838  memset(worker, 0, sizeof(LogicalRepWorker));
839  SpinLockInit(&worker->relmutex);
840  }
841  }
842 }
#define SpinLockInit(lock)
Definition: spin.h:60
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:72
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:372
Size ApplyLauncherShmemSize(void)
Definition: launcher.c:770
int max_logical_replication_workers
Definition: launcher.c:61
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:75

◆ ApplyLauncherShmemSize()

Size ApplyLauncherShmemSize ( void  )

Definition at line 770 of file launcher.c.

References add_size(), max_logical_replication_workers, MAXALIGN, and mul_size().

Referenced by ApplyLauncherShmemInit(), and CreateSharedMemoryAndSemaphores().

771 {
772  Size size;
773 
774  /*
775  * Need the fixed struct and the array of LogicalRepWorker.
776  */
777  size = sizeof(LogicalRepCtxStruct);
778  size = MAXALIGN(size);
780  sizeof(LogicalRepWorker)));
781  return size;
782 }
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
Size add_size(Size s1, Size s2)
Definition: shmem.c:475
int max_logical_replication_workers
Definition: launcher.c:61
size_t Size
Definition: c.h:466
#define MAXALIGN(LEN)
Definition: c.h:685
struct LogicalRepCtxStruct LogicalRepCtxStruct

◆ ApplyLauncherWakeup()

static void ApplyLauncherWakeup ( void  )
static

Definition at line 962 of file launcher.c.

References kill, LogicalRepCtxStruct::launcher_pid, and SIGUSR1.

Referenced by AtEOXact_ApplyLauncher(), and logicalrep_worker_onexit().

963 {
964  if (LogicalRepCtx->launcher_pid != 0)
966 }
#define SIGUSR1
Definition: win32_port.h:175
#define kill(pid, sig)
Definition: win32_port.h:435
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:75

◆ ApplyLauncherWakeupAtCommit()

void ApplyLauncherWakeupAtCommit ( void  )

Definition at line 955 of file launcher.c.

References on_commit_launcher_wakeup.

Referenced by AlterSubscription(), and CreateSubscription().

956 {
959 }
static bool on_commit_launcher_wakeup
Definition: launcher.c:106

◆ AtEOSubXact_ApplyLauncher()

void AtEOSubXact_ApplyLauncher ( bool  isCommit,
int  nestDepth 
)

Definition at line 900 of file launcher.c.

References Assert, list_concat(), list_free_deep(), StopWorkersData::nestDepth, StopWorkersData::parent, pfree(), and StopWorkersData::workers.

Referenced by AbortSubTransaction(), and CommitSubTransaction().

901 {
902  StopWorkersData *parent;
903 
904  /* Exit immediately if there's no work to do at this level. */
905  if (on_commit_stop_workers == NULL ||
906  on_commit_stop_workers->nestDepth < nestDepth)
907  return;
908 
909  Assert(on_commit_stop_workers->nestDepth == nestDepth);
910 
911  parent = on_commit_stop_workers->parent;
912 
913  if (isCommit)
914  {
915  /*
916  * If the upper stack element is not an immediate parent
917  * subtransaction, just decrement the notional nesting depth without
918  * doing any real work. Else, we need to merge the current workers
919  * list into the parent.
920  */
921  if (!parent || parent->nestDepth < nestDepth - 1)
922  {
924  return;
925  }
926 
927  parent->workers =
929  }
930  else
931  {
932  /*
933  * Abandon everything that was done at this nesting level. Explicitly
934  * free memory to avoid a transaction-lifespan leak.
935  */
937  }
938 
939  /*
940  * We have taken care of the current subtransaction workers list for both
941  * abort or commit. So we are ready to pop the stack.
942  */
944  on_commit_stop_workers = parent;
945 }
List * workers
Definition: launcher.c:86
List * list_concat(List *list1, const List *list2)
Definition: list.c:515
static StopWorkersData * on_commit_stop_workers
Definition: launcher.c:95
void list_free_deep(List *list)
Definition: list.c:1387
void pfree(void *pointer)
Definition: mcxt.c:1031
#define Assert(condition)
Definition: c.h:732
struct StopWorkersData * parent
Definition: launcher.c:87

◆ AtEOXact_ApplyLauncher()

void AtEOXact_ApplyLauncher ( bool  isCommit)

Definition at line 858 of file launcher.c.

References ApplyLauncherWakeup(), Assert, lfirst, logicalrep_worker_stop(), StopWorkersData::nestDepth, on_commit_launcher_wakeup, StopWorkersData::parent, LogicalRepWorkerId::relid, LogicalRepWorkerId::subid, LogicalRepCtxStruct::workers, and StopWorkersData::workers.

Referenced by AbortTransaction(), and CommitTransaction().

859 {
860 
861  Assert(on_commit_stop_workers == NULL ||
863  on_commit_stop_workers->parent == NULL));
864 
865  if (isCommit)
866  {
867  ListCell *lc;
868 
869  if (on_commit_stop_workers != NULL)
870  {
871  List *workers = on_commit_stop_workers->workers;
872 
873  foreach(lc, workers)
874  {
875  LogicalRepWorkerId *wid = lfirst(lc);
876 
877  logicalrep_worker_stop(wid->subid, wid->relid);
878  }
879  }
880 
883  }
884 
885  /*
886  * No need to pfree on_commit_stop_workers. It was allocated in
887  * transaction memory context, which is going to be cleaned soon.
888  */
889  on_commit_stop_workers = NULL;
891 }
List * workers
Definition: launcher.c:86
static StopWorkersData * on_commit_stop_workers
Definition: launcher.c:95
void logicalrep_worker_stop(Oid subid, Oid relid)
Definition: launcher.c:464
static bool on_commit_launcher_wakeup
Definition: launcher.c:106
#define Assert(condition)
Definition: c.h:732
#define lfirst(lc)
Definition: pg_list.h:190
struct StopWorkersData * parent
Definition: launcher.c:87
static void ApplyLauncherWakeup(void)
Definition: launcher.c:962
Definition: pg_list.h:50

◆ get_subscription_list()

static List* get_subscription_list ( void  )
static

Definition at line 118 of file launcher.c.

References AccessShareLock, CommitTransactionCommand(), CurrentMemoryContext, Subscription::dbid, Subscription::enabled, ForwardScanDirection, GETSTRUCT, GetTransactionSnapshot(), heap_getnext(), HeapTupleIsValid, lappend(), MemoryContextSwitchTo(), Subscription::name, NameStr, NIL, Subscription::oid, Subscription::owner, palloc0(), pstrdup(), StartTransactionCommand(), table_beginscan_catalog(), table_close(), table_endscan(), and table_open().

Referenced by ApplyLauncherMain().

119 {
120  List *res = NIL;
121  Relation rel;
122  TableScanDesc scan;
123  HeapTuple tup;
124  MemoryContext resultcxt;
125 
126  /* This is the context that we will allocate our output data in */
127  resultcxt = CurrentMemoryContext;
128 
129  /*
130  * Start a transaction so we can access pg_database, and get a snapshot.
131  * We don't have a use for the snapshot itself, but we're interested in
132  * the secondary effect that it sets RecentGlobalXmin. (This is critical
133  * for anything that reads heap pages, because HOT may decide to prune
134  * them even if the process doesn't attempt to modify any tuples.)
135  */
137  (void) GetTransactionSnapshot();
138 
139  rel = table_open(SubscriptionRelationId, AccessShareLock);
140  scan = table_beginscan_catalog(rel, 0, NULL);
141 
143  {
145  Subscription *sub;
146  MemoryContext oldcxt;
147 
148  /*
149  * Allocate our results in the caller's context, not the
150  * transaction's. We do this inside the loop, and restore the original
151  * context at the end, so that leaky things like heap_getnext() are
152  * not called in a potentially long-lived context.
153  */
154  oldcxt = MemoryContextSwitchTo(resultcxt);
155 
156  sub = (Subscription *) palloc0(sizeof(Subscription));
157  sub->oid = subform->oid;
158  sub->dbid = subform->subdbid;
159  sub->owner = subform->subowner;
160  sub->enabled = subform->subenabled;
161  sub->name = pstrdup(NameStr(subform->subname));
162  /* We don't fill fields we are not interested in. */
163 
164  res = lappend(res, sub);
165  MemoryContextSwitchTo(oldcxt);
166  }
167 
168  table_endscan(scan);
170 
172 
173  return res;
174 }
#define NIL
Definition: pg_list.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
#define GETSTRUCT(TUP)
Definition: htup_details.h:655
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:98
char * pstrdup(const char *in)
Definition: mcxt.c:1161
void CommitTransactionCommand(void)
Definition: xact.c:2895
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
FormData_pg_subscription * Form_pg_subscription
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1290
MemoryContext CurrentMemoryContext
Definition: mcxt.c:38
List * lappend(List *list, void *datum)
Definition: list.c:321
void * palloc0(Size size)
Definition: mcxt.c:955
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void StartTransactionCommand(void)
Definition: xact.c:2794
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:831
#define NameStr(name)
Definition: c.h:609
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50

◆ IsLogicalLauncher()

bool IsLogicalLauncher ( void  )

Definition at line 1088 of file launcher.c.

References LogicalRepCtxStruct::launcher_pid, and MyProcPid.

Referenced by ProcessInterrupts().

1089 {
1091 }
int MyProcPid
Definition: globals.c:40
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:75

◆ logicalrep_launcher_onexit()

static void logicalrep_launcher_onexit ( int  code,
Datum  arg 
)
static

Definition at line 705 of file launcher.c.

References LogicalRepCtxStruct::launcher_pid.

Referenced by ApplyLauncherMain().

706 {
708 }
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:75

◆ logicalrep_launcher_sighup()

static void logicalrep_launcher_sighup ( SIGNAL_ARGS  )
static

Definition at line 729 of file launcher.c.

References got_SIGHUP, MyLatch, and SetLatch().

Referenced by ApplyLauncherMain().

730 {
731  int save_errno = errno;
732 
733  got_SIGHUP = true;
734 
735  /* Waken anything waiting on the process latch */
736  SetLatch(MyLatch);
737 
738  errno = save_errno;
739 }
static volatile sig_atomic_t got_SIGHUP
Definition: launcher.c:104
void SetLatch(Latch *latch)
Definition: latch.c:436
struct Latch * MyLatch
Definition: globals.c:54

◆ logicalrep_sync_worker_count()

int logicalrep_sync_worker_count ( Oid  subid)

Definition at line 746 of file launcher.c.

References Assert, i, LWLockHeldByMe(), max_logical_replication_workers, OidIsValid, LogicalRepWorker::relid, LogicalRepWorker::subid, and LogicalRepCtxStruct::workers.

Referenced by logicalrep_worker_launch(), and process_syncing_tables_for_apply().

747 {
748  int i;
749  int res = 0;
750 
751  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
752 
753  /* Search for attached worker for a given subscription id. */
754  for (i = 0; i < max_logical_replication_workers; i++)
755  {
757 
758  if (w->subid == subid && OidIsValid(w->relid))
759  res++;
760  }
761 
762  return res;
763 }
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1842
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:72
#define OidIsValid(objectId)
Definition: c.h:638
#define Assert(condition)
Definition: c.h:732
int max_logical_replication_workers
Definition: launcher.c:61
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:75
int i

◆ logicalrep_worker_attach()

void logicalrep_worker_attach ( int  slot)

Definition at line 637 of file launcher.c.

References Assert, before_shmem_exit(), ereport, errcode(), errmsg(), ERROR, LogicalRepWorker::in_use, logicalrep_worker_onexit(), LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), max_logical_replication_workers, MyProc, LogicalRepWorker::proc, and LogicalRepCtxStruct::workers.

Referenced by ApplyWorkerMain().

638 {
639  /* Block concurrent access. */
640  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
641 
642  Assert(slot >= 0 && slot < max_logical_replication_workers);
644 
646  {
647  LWLockRelease(LogicalRepWorkerLock);
648  ereport(ERROR,
649  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
650  errmsg("logical replication worker slot %d is empty, cannot attach",
651  slot)));
652  }
653 
655  {
656  LWLockRelease(LogicalRepWorkerLock);
657  ereport(ERROR,
658  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
659  errmsg("logical replication worker slot %d is already used by "
660  "another worker, cannot attach", slot)));
661  }
662 
665 
666  LWLockRelease(LogicalRepWorkerLock);
667 }
PGPROC * MyProc
Definition: proc.c:68
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:72
int errcode(int sqlerrcode)
Definition: elog.c:570
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:64
#define ERROR
Definition: elog.h:43
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:333
#define ereport(elevel, rest)
Definition: elog.h:141
static void logicalrep_worker_onexit(int code, Datum arg)
Definition: launcher.c:716
uintptr_t Datum
Definition: postgres.h:367
#define Assert(condition)
Definition: c.h:732
int max_logical_replication_workers
Definition: launcher.c:61
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
int errmsg(const char *fmt,...)
Definition: elog.c:784
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:75

◆ logicalrep_worker_cleanup()

static void logicalrep_worker_cleanup ( LogicalRepWorker worker)
static

Definition at line 687 of file launcher.c.

References Assert, LogicalRepWorker::dbid, LogicalRepWorker::in_use, InvalidOid, LW_EXCLUSIVE, LWLockHeldByMeInMode(), LogicalRepWorker::proc, LogicalRepWorker::relid, LogicalRepWorker::subid, and LogicalRepWorker::userid.

Referenced by logicalrep_worker_detach(), logicalrep_worker_launch(), and WaitForReplicationWorkerAttach().

688 {
689  Assert(LWLockHeldByMeInMode(LogicalRepWorkerLock, LW_EXCLUSIVE));
690 
691  worker->in_use = false;
692  worker->proc = NULL;
693  worker->dbid = InvalidOid;
694  worker->userid = InvalidOid;
695  worker->subid = InvalidOid;
696  worker->relid = InvalidOid;
697 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1860
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:732

◆ logicalrep_worker_detach()

static void logicalrep_worker_detach ( void  )
static

Definition at line 673 of file launcher.c.

References logicalrep_worker_cleanup(), LW_EXCLUSIVE, LWLockAcquire(), and LWLockRelease().

Referenced by logicalrep_worker_onexit().

674 {
675  /* Block concurrent access. */
676  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
677 
679 
680  LWLockRelease(LogicalRepWorkerLock);
681 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:64
static void logicalrep_worker_cleanup(LogicalRepWorker *worker)
Definition: launcher.c:687
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122

◆ logicalrep_worker_find()

LogicalRepWorker* logicalrep_worker_find ( Oid  subid,
Oid  relid,
bool  only_running 
)

Definition at line 243 of file launcher.c.

References Assert, i, LogicalRepWorker::in_use, LWLockHeldByMe(), max_logical_replication_workers, LogicalRepWorker::proc, LogicalRepWorker::relid, LogicalRepWorker::subid, and LogicalRepCtxStruct::workers.

Referenced by ApplyLauncherMain(), logicalrep_worker_stop(), logicalrep_worker_wakeup(), process_syncing_tables_for_apply(), wait_for_relation_state_change(), and wait_for_worker_state_change().

244 {
245  int i;
246  LogicalRepWorker *res = NULL;
247 
248  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
249 
250  /* Search for attached worker for a given subscription id. */
251  for (i = 0; i < max_logical_replication_workers; i++)
252  {
254 
255  if (w->in_use && w->subid == subid && w->relid == relid &&
256  (!only_running || w->proc))
257  {
258  res = w;
259  break;
260  }
261  }
262 
263  return res;
264 }
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1842
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:72
#define Assert(condition)
Definition: c.h:732
int max_logical_replication_workers
Definition: launcher.c:61
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:75
int i

◆ logicalrep_worker_launch()

void logicalrep_worker_launch ( Oid  dbid,
Oid  subid,
const char *  subname,
Oid  userid,
Oid  relid 
)

Definition at line 294 of file launcher.c.

References Assert, BackgroundWorker::bgw_flags, BackgroundWorker::bgw_function_name, BackgroundWorker::bgw_library_name, BackgroundWorker::bgw_main_arg, BGW_MAXLEN, BackgroundWorker::bgw_name, BGW_NEVER_RESTART, BackgroundWorker::bgw_notify_pid, BackgroundWorker::bgw_restart_time, BackgroundWorker::bgw_start_time, BackgroundWorker::bgw_type, BGWORKER_BACKEND_DATABASE_CONNECTION, BGWORKER_SHMEM_ACCESS, BgWorkerStart_RecoveryFinished, LogicalRepWorker::dbid, DEBUG1, elog, ereport, errcode(), errhint(), errmsg(), ERROR, LogicalRepWorker::generation, GetCurrentTimestamp(), i, LogicalRepWorker::in_use, Int32GetDatum, InvalidXLogRecPtr, LogicalRepWorker::last_lsn, LogicalRepWorker::last_recv_time, LogicalRepWorker::last_send_time, LogicalRepWorker::launch_time, logicalrep_sync_worker_count(), logicalrep_worker_cleanup(), LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), max_logical_replication_workers, max_replication_slots, max_sync_workers_per_subscription, MyProcPid, now(), OidIsValid, LogicalRepWorker::proc, RegisterDynamicBackgroundWorker(), LogicalRepWorker::relid, LogicalRepWorker::relstate, LogicalRepWorker::relstate_lsn, LogicalRepWorker::reply_lsn, LogicalRepWorker::reply_time, snprintf, LogicalRepWorker::subid, TIMESTAMP_NOBEGIN, TimestampDifferenceExceeds(), LogicalRepWorker::userid, WaitForReplicationWorkerAttach(), wal_receiver_timeout, WARNING, and LogicalRepCtxStruct::workers.

Referenced by ApplyLauncherMain(), and process_syncing_tables_for_apply().

296 {
297  BackgroundWorker bgw;
298  BackgroundWorkerHandle *bgw_handle;
299  uint16 generation;
300  int i;
301  int slot = 0;
302  LogicalRepWorker *worker = NULL;
303  int nsyncworkers;
305 
306  ereport(DEBUG1,
307  (errmsg("starting logical replication worker for subscription \"%s\"",
308  subname)));
309 
310  /* Report this after the initial starting message for consistency. */
311  if (max_replication_slots == 0)
312  ereport(ERROR,
313  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
314  errmsg("cannot start logical replication workers when max_replication_slots = 0")));
315 
316  /*
317  * We need to do the modification of the shared memory under lock so that
318  * we have consistent view.
319  */
320  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
321 
322 retry:
323  /* Find unused worker slot. */
324  for (i = 0; i < max_logical_replication_workers; i++)
325  {
327 
328  if (!w->in_use)
329  {
330  worker = w;
331  slot = i;
332  break;
333  }
334  }
335 
336  nsyncworkers = logicalrep_sync_worker_count(subid);
337 
338  now = GetCurrentTimestamp();
339 
340  /*
341  * If we didn't find a free slot, try to do garbage collection. The
342  * reason we do this is because if some worker failed to start up and its
343  * parent has crashed while waiting, the in_use state was never cleared.
344  */
345  if (worker == NULL || nsyncworkers >= max_sync_workers_per_subscription)
346  {
347  bool did_cleanup = false;
348 
349  for (i = 0; i < max_logical_replication_workers; i++)
350  {
352 
353  /*
354  * If the worker was marked in use but didn't manage to attach in
355  * time, clean it up.
356  */
357  if (w->in_use && !w->proc &&
360  {
361  elog(WARNING,
362  "logical replication worker for subscription %u took too long to start; canceled",
363  w->subid);
364 
366  did_cleanup = true;
367  }
368  }
369 
370  if (did_cleanup)
371  goto retry;
372  }
373 
374  /*
375  * If we reached the sync worker limit per subscription, just exit
376  * silently as we might get here because of an otherwise harmless race
377  * condition.
378  */
379  if (nsyncworkers >= max_sync_workers_per_subscription)
380  {
381  LWLockRelease(LogicalRepWorkerLock);
382  return;
383  }
384 
385  /*
386  * However if there are no more free worker slots, inform user about it
387  * before exiting.
388  */
389  if (worker == NULL)
390  {
391  LWLockRelease(LogicalRepWorkerLock);
393  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
394  errmsg("out of logical replication worker slots"),
395  errhint("You might need to increase max_logical_replication_workers.")));
396  return;
397  }
398 
399  /* Prepare the worker slot. */
400  worker->launch_time = now;
401  worker->in_use = true;
402  worker->generation++;
403  worker->proc = NULL;
404  worker->dbid = dbid;
405  worker->userid = userid;
406  worker->subid = subid;
407  worker->relid = relid;
408  worker->relstate = SUBREL_STATE_UNKNOWN;
410  worker->last_lsn = InvalidXLogRecPtr;
413  worker->reply_lsn = InvalidXLogRecPtr;
414  TIMESTAMP_NOBEGIN(worker->reply_time);
415 
416  /* Before releasing lock, remember generation for future identification. */
417  generation = worker->generation;
418 
419  LWLockRelease(LogicalRepWorkerLock);
420 
421  /* Register the new dynamic worker. */
422  memset(&bgw, 0, sizeof(bgw));
426  snprintf(bgw.bgw_library_name, BGW_MAXLEN, "postgres");
427  snprintf(bgw.bgw_function_name, BGW_MAXLEN, "ApplyWorkerMain");
428  if (OidIsValid(relid))
430  "logical replication worker for subscription %u sync %u", subid, relid);
431  else
433  "logical replication worker for subscription %u", subid);
434  snprintf(bgw.bgw_type, BGW_MAXLEN, "logical replication worker");
435 
438  bgw.bgw_main_arg = Int32GetDatum(slot);
439 
440  if (!RegisterDynamicBackgroundWorker(&bgw, &bgw_handle))
441  {
442  /* Failed to start worker, so clean up the worker slot. */
443  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
444  Assert(generation == worker->generation);
446  LWLockRelease(LogicalRepWorkerLock);
447 
449  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
450  errmsg("out of background worker slots"),
451  errhint("You might need to increase max_worker_processes.")));
452  return;
453  }
454 
455  /* Now wait until it attaches. */
456  WaitForReplicationWorkerAttach(worker, generation, bgw_handle);
457 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define DEBUG1
Definition: elog.h:25
int MyProcPid
Definition: globals.c:40
int errhint(const char *fmt,...)
Definition: elog.c:974
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1569
int64 TimestampTz
Definition: timestamp.h:39
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:72
TimestampTz last_send_time
XLogRecPtr last_lsn
int bgw_restart_time
Definition: bgworker.h:94
int errcode(int sqlerrcode)
Definition: elog.c:570
NameData subname
#define BGWORKER_SHMEM_ACCESS
Definition: bgworker.h:52
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1668
#define OidIsValid(objectId)
Definition: c.h:638
char bgw_function_name[BGW_MAXLEN]
Definition: bgworker.h:96
int wal_receiver_timeout
Definition: walreceiver.c:76
XLogRecPtr relstate_lsn
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
Datum bgw_main_arg
Definition: bgworker.h:97
unsigned short uint16
Definition: c.h:357
#define ERROR
Definition: elog.h:43
int max_sync_workers_per_subscription
Definition: launcher.c:62
XLogRecPtr reply_lsn
static void logicalrep_worker_cleanup(LogicalRepWorker *worker)
Definition: launcher.c:687
#define BGW_NEVER_RESTART
Definition: bgworker.h:84
#define TIMESTAMP_NOBEGIN(j)
Definition: timestamp.h:112
#define ereport(elevel, rest)
Definition: elog.h:141
#define WARNING
Definition: elog.h:40
int logicalrep_sync_worker_count(Oid subid)
Definition: launcher.c:746
static void WaitForReplicationWorkerAttach(LogicalRepWorker *worker, uint16 generation, BackgroundWorkerHandle *handle)
Definition: launcher.c:183
TimestampTz launch_time
int max_replication_slots
Definition: slot.c:99
TimestampTz last_recv_time
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:90
#define Assert(condition)
Definition: c.h:732
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
int max_logical_replication_workers
Definition: launcher.c:61
#define BGW_MAXLEN
Definition: bgworker.h:85
BgWorkerStartTime bgw_start_time
Definition: bgworker.h:93
bool RegisterDynamicBackgroundWorker(BackgroundWorker *worker, BackgroundWorkerHandle **handle)
Definition: bgworker.c:932
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
#define Int32GetDatum(X)
Definition: postgres.h:479
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:91
int errmsg(const char *fmt,...)
Definition: elog.c:784
pid_t bgw_notify_pid
Definition: bgworker.h:99
#define elog(elevel,...)
Definition: elog.h:226
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:75
int i
char bgw_library_name[BGW_MAXLEN]
Definition: bgworker.h:95
#define snprintf
Definition: port.h:192
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1533
TimestampTz reply_time

◆ logicalrep_worker_onexit()

static void logicalrep_worker_onexit ( int  code,
Datum  arg 
)
static

Definition at line 716 of file launcher.c.

References ApplyLauncherWakeup(), logicalrep_worker_detach(), walrcv_disconnect, and wrconn.

Referenced by logicalrep_worker_attach().

717 {
718  /* Disconnect gracefully from the remote side. */
719  if (wrconn)
721 
723 
725 }
WalReceiverConn * wrconn
Definition: worker.c:100
static void logicalrep_worker_detach(void)
Definition: launcher.c:673
#define walrcv_disconnect(conn)
Definition: walreceiver.h:281
static void ApplyLauncherWakeup(void)
Definition: launcher.c:962

◆ logicalrep_worker_stop()

void logicalrep_worker_stop ( Oid  subid,
Oid  relid 
)

Definition at line 464 of file launcher.c.

References CHECK_FOR_INTERRUPTS, LogicalRepWorker::generation, LogicalRepWorker::in_use, kill, logicalrep_worker_find(), LW_SHARED, LWLockAcquire(), LWLockRelease(), MyLatch, PGPROC::pid, LogicalRepWorker::proc, ResetLatch(), WAIT_EVENT_BGWORKER_SHUTDOWN, WAIT_EVENT_BGWORKER_STARTUP, WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, and WL_TIMEOUT.

Referenced by AtEOXact_ApplyLauncher(), and DropSubscription().

465 {
466  LogicalRepWorker *worker;
467  uint16 generation;
468 
469  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
470 
471  worker = logicalrep_worker_find(subid, relid, false);
472 
473  /* No worker, nothing to do. */
474  if (!worker)
475  {
476  LWLockRelease(LogicalRepWorkerLock);
477  return;
478  }
479 
480  /*
481  * Remember which generation was our worker so we can check if what we see
482  * is still the same one.
483  */
484  generation = worker->generation;
485 
486  /*
487  * If we found a worker but it does not have proc set then it is still
488  * starting up; wait for it to finish starting and then kill it.
489  */
490  while (worker->in_use && !worker->proc)
491  {
492  int rc;
493 
494  LWLockRelease(LogicalRepWorkerLock);
495 
496  /* Wait a bit --- we don't expect to have to wait long. */
497  rc = WaitLatch(MyLatch,
500 
501  if (rc & WL_LATCH_SET)
502  {
505  }
506 
507  /* Recheck worker status. */
508  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
509 
510  /*
511  * Check whether the worker slot is no longer used, which would mean
512  * that the worker has exited, or whether the worker generation is
513  * different, meaning that a different worker has taken the slot.
514  */
515  if (!worker->in_use || worker->generation != generation)
516  {
517  LWLockRelease(LogicalRepWorkerLock);
518  return;
519  }
520 
521  /* Worker has assigned proc, so it has started. */
522  if (worker->proc)
523  break;
524  }
525 
526  /* Now terminate the worker ... */
527  kill(worker->proc->pid, SIGTERM);
528 
529  /* ... and wait for it to die. */
530  for (;;)
531  {
532  int rc;
533 
534  /* is it gone? */
535  if (!worker->proc || worker->generation != generation)
536  break;
537 
538  LWLockRelease(LogicalRepWorkerLock);
539 
540  /* Wait a bit --- we don't expect to have to wait long. */
541  rc = WaitLatch(MyLatch,
542  WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
544 
545  if (rc & WL_LATCH_SET)
546  {
549  }
550 
551  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
552  }
553 
554  LWLockRelease(LogicalRepWorkerLock);
555 }
#define WL_TIMEOUT
Definition: latch.h:127
#define kill(pid, sig)
Definition: win32_port.h:435
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
unsigned short uint16
Definition: c.h:357
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
int pid
Definition: proc.h:109
#define WL_LATCH_SET
Definition: latch.h:124
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:129

◆ logicalrep_worker_stop_at_commit()

void logicalrep_worker_stop_at_commit ( Oid  subid,
Oid  relid 
)

Definition at line 561 of file launcher.c.

References Assert, GetCurrentTransactionNestLevel(), lappend(), MemoryContextSwitchTo(), StopWorkersData::nestDepth, NIL, on_commit_stop_workers, palloc(), StopWorkersData::parent, LogicalRepWorkerId::relid, LogicalRepWorkerId::subid, TopTransactionContext, and StopWorkersData::workers.

Referenced by AlterSubscription_refresh().

562 {
563  int nestDepth = GetCurrentTransactionNestLevel();
564  LogicalRepWorkerId *wid;
565  MemoryContext oldctx;
566 
567  /* Make sure we store the info in context that survives until commit. */
569 
570  /* Check that previous transactions were properly cleaned up. */
571  Assert(on_commit_stop_workers == NULL ||
572  nestDepth >= on_commit_stop_workers->nestDepth);
573 
574  /*
575  * Push a new stack element if we don't already have one for the current
576  * nestDepth.
577  */
578  if (on_commit_stop_workers == NULL ||
579  nestDepth > on_commit_stop_workers->nestDepth)
580  {
581  StopWorkersData *newdata = palloc(sizeof(StopWorkersData));
582 
583  newdata->nestDepth = nestDepth;
584  newdata->workers = NIL;
585  newdata->parent = on_commit_stop_workers;
586  on_commit_stop_workers = newdata;
587  }
588 
589  /*
590  * Finally add a new worker into the worker list of the current
591  * subtransaction.
592  */
593  wid = palloc(sizeof(LogicalRepWorkerId));
594  wid->subid = subid;
595  wid->relid = relid;
598 
599  MemoryContextSwitchTo(oldctx);
600 }
#define NIL
Definition: pg_list.h:65
MemoryContext TopTransactionContext
Definition: mcxt.c:49
List * workers
Definition: launcher.c:86
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static StopWorkersData * on_commit_stop_workers
Definition: launcher.c:95
List * lappend(List *list, void *datum)
Definition: list.c:321
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:842
#define Assert(condition)
Definition: c.h:732
struct StopWorkersData * parent
Definition: launcher.c:87
void * palloc(Size size)
Definition: mcxt.c:924

◆ logicalrep_worker_wakeup()

void logicalrep_worker_wakeup ( Oid  subid,
Oid  relid 
)

Definition at line 606 of file launcher.c.

References logicalrep_worker_find(), logicalrep_worker_wakeup_ptr(), LW_SHARED, LWLockAcquire(), and LWLockRelease().

Referenced by pg_attribute_noreturn().

607 {
608  LogicalRepWorker *worker;
609 
610  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
611 
612  worker = logicalrep_worker_find(subid, relid, true);
613 
614  if (worker)
616 
617  LWLockRelease(LogicalRepWorkerLock);
618 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
void logicalrep_worker_wakeup_ptr(LogicalRepWorker *worker)
Definition: launcher.c:626
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

◆ logicalrep_worker_wakeup_ptr()

void logicalrep_worker_wakeup_ptr ( LogicalRepWorker worker)

Definition at line 626 of file launcher.c.

References Assert, LWLockHeldByMe(), LogicalRepWorker::proc, PGPROC::procLatch, and SetLatch().

Referenced by logicalrep_worker_wakeup(), process_syncing_tables_for_apply(), and wait_for_worker_state_change().

627 {
628  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
629 
630  SetLatch(&worker->proc->procLatch);
631 }
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1842
void SetLatch(Latch *latch)
Definition: latch.c:436
Latch procLatch
Definition: proc.h:104
#define Assert(condition)
Definition: c.h:732

◆ logicalrep_workers_find()

List* logicalrep_workers_find ( Oid  subid,
bool  only_running 
)

Definition at line 271 of file launcher.c.

References Assert, i, LogicalRepWorker::in_use, lappend(), LWLockHeldByMe(), max_logical_replication_workers, NIL, LogicalRepWorker::proc, LogicalRepWorker::subid, and LogicalRepCtxStruct::workers.

Referenced by DropSubscription().

272 {
273  int i;
274  List *res = NIL;
275 
276  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
277 
278  /* Search for attached worker for a given subscription id. */
279  for (i = 0; i < max_logical_replication_workers; i++)
280  {
282 
283  if (w->in_use && w->subid == subid && (!only_running || w->proc))
284  res = lappend(res, w);
285  }
286 
287  return res;
288 }
#define NIL
Definition: pg_list.h:65
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1842
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:72
List * lappend(List *list, void *datum)
Definition: list.c:321
#define Assert(condition)
Definition: c.h:732
int max_logical_replication_workers
Definition: launcher.c:61
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:75
int i
Definition: pg_list.h:50

◆ pg_stat_get_subscription()

Datum pg_stat_get_subscription ( PG_FUNCTION_ARGS  )

Definition at line 1097 of file launcher.c.

References ReturnSetInfo::allowedModes, ReturnSetInfo::econtext, ExprContext::ecxt_per_query_memory, elog, ereport, errcode(), errmsg(), ERROR, get_call_result_type(), i, Int32GetDatum, InvalidOid, IsA, IsBackendPid(), LogicalRepWorker::last_lsn, LogicalRepWorker::last_recv_time, LogicalRepWorker::last_send_time, LSNGetDatum, LW_SHARED, LWLockAcquire(), LWLockRelease(), max_logical_replication_workers, MemoryContextSwitchTo(), MemSet, ObjectIdGetDatum, OidIsValid, PG_ARGISNULL, PG_GETARG_OID, PG_STAT_GET_SUBSCRIPTION_COLS, PGPROC::pid, LogicalRepWorker::proc, LogicalRepWorker::relid, LogicalRepWorker::reply_lsn, LogicalRepWorker::reply_time, ReturnSetInfo::returnMode, ReturnSetInfo::setDesc, ReturnSetInfo::setResult, SFRM_Materialize, LogicalRepWorker::subid, TimestampTzGetDatum, tuplestore_begin_heap(), tuplestore_donestoring, tuplestore_putvalues(), TYPEFUNC_COMPOSITE, values, work_mem, LogicalRepCtxStruct::workers, and XLogRecPtrIsInvalid.

1098 {
1099 #define PG_STAT_GET_SUBSCRIPTION_COLS 8
1100  Oid subid = PG_ARGISNULL(0) ? InvalidOid : PG_GETARG_OID(0);
1101  int i;
1102  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1103  TupleDesc tupdesc;
1104  Tuplestorestate *tupstore;
1105  MemoryContext per_query_ctx;
1106  MemoryContext oldcontext;
1107 
1108  /* check to see if caller supports us returning a tuplestore */
1109  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
1110  ereport(ERROR,
1111  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1112  errmsg("set-valued function called in context that cannot accept a set")));
1113  if (!(rsinfo->allowedModes & SFRM_Materialize))
1114  ereport(ERROR,
1115  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1116  errmsg("materialize mode required, but it is not " \
1117  "allowed in this context")));
1118 
1119  /* Build a tuple descriptor for our result type */
1120  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1121  elog(ERROR, "return type must be a row type");
1122 
1123  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1124  oldcontext = MemoryContextSwitchTo(per_query_ctx);
1125 
1126  tupstore = tuplestore_begin_heap(true, false, work_mem);
1127  rsinfo->returnMode = SFRM_Materialize;
1128  rsinfo->setResult = tupstore;
1129  rsinfo->setDesc = tupdesc;
1130 
1131  MemoryContextSwitchTo(oldcontext);
1132 
1133  /* Make sure we get consistent view of the workers. */
1134  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
1135 
1136  for (i = 0; i <= max_logical_replication_workers; i++)
1137  {
1138  /* for each row */
1140  bool nulls[PG_STAT_GET_SUBSCRIPTION_COLS];
1141  int worker_pid;
1142  LogicalRepWorker worker;
1143 
1144  memcpy(&worker, &LogicalRepCtx->workers[i],
1145  sizeof(LogicalRepWorker));
1146  if (!worker.proc || !IsBackendPid(worker.proc->pid))
1147  continue;
1148 
1149  if (OidIsValid(subid) && worker.subid != subid)
1150  continue;
1151 
1152  worker_pid = worker.proc->pid;
1153 
1154  MemSet(values, 0, sizeof(values));
1155  MemSet(nulls, 0, sizeof(nulls));
1156 
1157  values[0] = ObjectIdGetDatum(worker.subid);
1158  if (OidIsValid(worker.relid))
1159  values[1] = ObjectIdGetDatum(worker.relid);
1160  else
1161  nulls[1] = true;
1162  values[2] = Int32GetDatum(worker_pid);
1163  if (XLogRecPtrIsInvalid(worker.last_lsn))
1164  nulls[3] = true;
1165  else
1166  values[3] = LSNGetDatum(worker.last_lsn);
1167  if (worker.last_send_time == 0)
1168  nulls[4] = true;
1169  else
1170  values[4] = TimestampTzGetDatum(worker.last_send_time);
1171  if (worker.last_recv_time == 0)
1172  nulls[5] = true;
1173  else
1174  values[5] = TimestampTzGetDatum(worker.last_recv_time);
1175  if (XLogRecPtrIsInvalid(worker.reply_lsn))
1176  nulls[6] = true;
1177  else
1178  values[6] = LSNGetDatum(worker.reply_lsn);
1179  if (worker.reply_time == 0)
1180  nulls[7] = true;
1181  else
1182  values[7] = TimestampTzGetDatum(worker.reply_time);
1183 
1184  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
1185 
1186  /*
1187  * If only a single subscription was requested, and we found it,
1188  * break.
1189  */
1190  if (OidIsValid(subid))
1191  break;
1192  }
1193 
1194  LWLockRelease(LogicalRepWorkerLock);
1195 
1196  /* clean up and return the tuplestore */
1197  tuplestore_donestoring(tupstore);
1198 
1199  return (Datum) 0;
1200 }
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, Datum *values, bool *isnull)
Definition: tuplestore.c:750
#define IsA(nodeptr, _type_)
Definition: nodes.h:575
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:196
#define tuplestore_donestoring(state)
Definition: tuplestore.h:60
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:72
TimestampTz last_send_time
XLogRecPtr last_lsn
int errcode(int sqlerrcode)
Definition: elog.c:570
#define LSNGetDatum(X)
Definition: pg_lsn.h:22
#define MemSet(start, val, len)
Definition: c.h:955
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:638
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
#define ObjectIdGetDatum(X)
Definition: postgres.h:507
#define ERROR
Definition: elog.h:43
#define TimestampTzGetDatum(X)
Definition: timestamp.h:32
XLogRecPtr reply_lsn
#define PG_GETARG_OID(n)
Definition: fmgr.h:270
#define ereport(elevel, rest)
Definition: elog.h:141
#define XLogRecPtrIsInvalid(r)
Definition: xlogdefs.h:29
Tuplestorestate * tuplestore_begin_heap(bool randomAccess, bool interXact, int maxKBytes)
Definition: tuplestore.c:318
uintptr_t Datum
Definition: postgres.h:367
#define PG_STAT_GET_SUBSCRIPTION_COLS
int work_mem
Definition: globals.c:121
#define InvalidOid
Definition: postgres_ext.h:36
int allowedModes
Definition: execnodes.h:303
SetFunctionReturnMode returnMode
Definition: execnodes.h:305
TimestampTz last_recv_time
#define PG_ARGISNULL(n)
Definition: fmgr.h:204
int max_logical_replication_workers
Definition: launcher.c:61
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:231
Tuplestorestate * setResult
Definition: execnodes.h:308
static Datum values[MAXATTR]
Definition: bootstrap.c:167
ExprContext * econtext
Definition: execnodes.h:301
#define Int32GetDatum(X)
Definition: postgres.h:479
TupleDesc setDesc
Definition: execnodes.h:309
int errmsg(const char *fmt,...)
Definition: elog.c:784
#define elog(elevel,...)
Definition: elog.h:226
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:75
int i
bool IsBackendPid(int pid)
Definition: procarray.c:2458
int pid
Definition: proc.h:109
TimestampTz reply_time

◆ WaitForReplicationWorkerAttach()

static void WaitForReplicationWorkerAttach ( LogicalRepWorker worker,
uint16  generation,
BackgroundWorkerHandle handle 
)
static

Definition at line 183 of file launcher.c.

References BGWH_STOPPED, CHECK_FOR_INTERRUPTS, LogicalRepWorker::generation, GetBackgroundWorkerPid(), LogicalRepWorker::in_use, logicalrep_worker_cleanup(), LW_EXCLUSIVE, LW_SHARED, LWLockAcquire(), LWLockRelease(), MyLatch, LogicalRepWorker::proc, ResetLatch(), status(), WAIT_EVENT_BGWORKER_STARTUP, WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, and WL_TIMEOUT.

Referenced by logicalrep_worker_launch().

186 {
188  int rc;
189 
190  for (;;)
191  {
192  pid_t pid;
193 
195 
196  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
197 
198  /* Worker either died or has started; no need to do anything. */
199  if (!worker->in_use || worker->proc)
200  {
201  LWLockRelease(LogicalRepWorkerLock);
202  return;
203  }
204 
205  LWLockRelease(LogicalRepWorkerLock);
206 
207  /* Check if worker has died before attaching, and clean up after it. */
208  status = GetBackgroundWorkerPid(handle, &pid);
209 
210  if (status == BGWH_STOPPED)
211  {
212  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
213  /* Ensure that this was indeed the worker we waited for. */
214  if (generation == worker->generation)
216  LWLockRelease(LogicalRepWorkerLock);
217  return;
218  }
219 
220  /*
221  * We need timeout because we generally don't get notified via latch
222  * about the worker attach. But we don't expect to have to wait long.
223  */
224  rc = WaitLatch(MyLatch,
227 
228  if (rc & WL_LATCH_SET)
229  {
232  }
233  }
234 
235  return;
236 }
#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
static void logicalrep_worker_cleanup(LogicalRepWorker *worker)
Definition: launcher.c:687
BgwHandleStatus
Definition: bgworker.h:102
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
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
#define WL_LATCH_SET
Definition: latch.h:124
BgwHandleStatus GetBackgroundWorkerPid(BackgroundWorkerHandle *handle, pid_t *pidp)
Definition: bgworker.c:1044
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:129

◆ XactManipulatesLogicalReplicationWorkers()

bool XactManipulatesLogicalReplicationWorkers ( void  )

Definition at line 849 of file launcher.c.

Referenced by PrepareTransaction().

850 {
851  return (on_commit_stop_workers != NULL);
852 }
static StopWorkersData * on_commit_stop_workers
Definition: launcher.c:95

Variable Documentation

◆ got_SIGHUP

volatile sig_atomic_t got_SIGHUP = false
static

Definition at line 104 of file launcher.c.

Referenced by ApplyLauncherMain(), and logicalrep_launcher_sighup().

◆ LogicalRepCtx

LogicalRepCtxStruct* LogicalRepCtx

Definition at line 75 of file launcher.c.

◆ max_logical_replication_workers

◆ max_sync_workers_per_subscription

int max_sync_workers_per_subscription = 2

Definition at line 62 of file launcher.c.

Referenced by logicalrep_worker_launch(), and process_syncing_tables_for_apply().

◆ MyLogicalRepWorker

◆ on_commit_launcher_wakeup

bool on_commit_launcher_wakeup = false
static

Definition at line 106 of file launcher.c.

Referenced by ApplyLauncherWakeupAtCommit(), and AtEOXact_ApplyLauncher().

◆ on_commit_stop_workers

StopWorkersData* on_commit_stop_workers = NULL
static

Definition at line 95 of file launcher.c.

Referenced by logicalrep_worker_stop_at_commit().