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 51 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 962 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.

963 {
964  TimestampTz last_start_time = 0;
965 
966  ereport(DEBUG1,
967  (errmsg("logical replication launcher started")));
968 
970 
973 
974  /* Establish signal handlers. */
976  pqsignal(SIGTERM, die);
978 
979  /*
980  * Establish connection to nailed catalogs (we only ever access
981  * pg_subscription).
982  */
984 
985  /* Enter main loop */
986  for (;;)
987  {
988  int rc;
989  List *sublist;
990  ListCell *lc;
991  MemoryContext subctx;
992  MemoryContext oldctx;
994  long wait_time = DEFAULT_NAPTIME_PER_CYCLE;
995 
997 
998  now = GetCurrentTimestamp();
999 
1000  /* Limit the start retry to once a wal_retrieve_retry_interval */
1001  if (TimestampDifferenceExceeds(last_start_time, now,
1003  {
1004  /* Use temporary context for the database list and worker info. */
1006  "Logical Replication Launcher sublist",
1008  oldctx = MemoryContextSwitchTo(subctx);
1009 
1010  /* search for subscriptions to start or stop. */
1011  sublist = get_subscription_list();
1012 
1013  /* Start the missing workers for enabled subscriptions. */
1014  foreach(lc, sublist)
1015  {
1016  Subscription *sub = (Subscription *) lfirst(lc);
1017  LogicalRepWorker *w;
1018 
1019  if (!sub->enabled)
1020  continue;
1021 
1022  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
1023  w = logicalrep_worker_find(sub->oid, InvalidOid, false);
1024  LWLockRelease(LogicalRepWorkerLock);
1025 
1026  if (w == NULL)
1027  {
1028  last_start_time = now;
1029  wait_time = wal_retrieve_retry_interval;
1030 
1031  logicalrep_worker_launch(sub->dbid, sub->oid, sub->name,
1032  sub->owner, InvalidOid);
1033  }
1034  }
1035 
1036  /* Switch back to original memory context. */
1037  MemoryContextSwitchTo(oldctx);
1038  /* Clean the temporary memory. */
1039  MemoryContextDelete(subctx);
1040  }
1041  else
1042  {
1043  /*
1044  * The wait in previous cycle was interrupted in less than
1045  * wal_retrieve_retry_interval since last worker was started, this
1046  * usually means crash of the worker, so we should retry in
1047  * wal_retrieve_retry_interval again.
1048  */
1049  wait_time = wal_retrieve_retry_interval;
1050  }
1051 
1052  /* Wait for more work. */
1053  rc = WaitLatch(MyLatch,
1055  wait_time,
1057 
1058  if (rc & WL_LATCH_SET)
1059  {
1062  }
1063 
1064  if (got_SIGHUP)
1065  {
1066  got_SIGHUP = false;
1068  }
1069  }
1070 
1071  /* Not reachable */
1072 }
static volatile sig_atomic_t got_SIGHUP
Definition: launcher.c:96
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:211
#define AllocSetContextCreate
Definition: memutils.h:170
#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:1583
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:1682
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:192
#define SIGHUP
Definition: win32_port.h:154
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:695
#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:5685
#define DEFAULT_NAPTIME_PER_CYCLE
Definition: launcher.c:51
uintptr_t Datum
Definition: postgres.h:367
static void logicalrep_launcher_sighup(SIGNAL_ARGS)
Definition: launcher.c:719
#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:110
void logicalrep_worker_launch(Oid dbid, Oid subid, const char *subname, Oid userid, Oid relid)
Definition: launcher.c:284
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:233
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
int errmsg(const char *fmt,...)
Definition: elog.c:822
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:67
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:1547
#define die(msg)
Definition: pg_test_fsync.c:96
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:129
void BackgroundWorkerUnblockSignals(void)
Definition: postmaster.c:5737

◆ ApplyLauncherRegister()

void ApplyLauncherRegister ( void  )

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

780 {
781  BackgroundWorker bgw;
782 
784  return;
785 
786  memset(&bgw, 0, sizeof(bgw));
790  snprintf(bgw.bgw_library_name, BGW_MAXLEN, "postgres");
791  snprintf(bgw.bgw_function_name, BGW_MAXLEN, "ApplyLauncherMain");
793  "logical replication launcher");
795  "logical replication launcher");
796  bgw.bgw_restart_time = 5;
797  bgw.bgw_notify_pid = 0;
798  bgw.bgw_main_arg = (Datum) 0;
799 
801 }
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:53
#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 808 of file launcher.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

809 {
810  bool found;
811 
813  ShmemInitStruct("Logical Replication Launcher Data",
815  &found);
816 
817  if (!found)
818  {
819  int slot;
820 
822 
823  /* Initialize memory and spin locks for each worker slot. */
824  for (slot = 0; slot < max_logical_replication_workers; slot++)
825  {
826  LogicalRepWorker *worker = &LogicalRepCtx->workers[slot];
827 
828  memset(worker, 0, sizeof(LogicalRepWorker));
829  SpinLockInit(&worker->relmutex);
830  }
831  }
832 }
#define SpinLockInit(lock)
Definition: spin.h:60
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:64
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:372
Size ApplyLauncherShmemSize(void)
Definition: launcher.c:760
int max_logical_replication_workers
Definition: launcher.c:53
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:67

◆ ApplyLauncherShmemSize()

Size ApplyLauncherShmemSize ( void  )

Definition at line 760 of file launcher.c.

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

Referenced by ApplyLauncherShmemInit(), and CreateSharedMemoryAndSemaphores().

761 {
762  Size size;
763 
764  /*
765  * Need the fixed struct and the array of LogicalRepWorker.
766  */
767  size = sizeof(LogicalRepCtxStruct);
768  size = MAXALIGN(size);
770  sizeof(LogicalRepWorker)));
771  return size;
772 }
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:53
size_t Size
Definition: c.h:467
#define MAXALIGN(LEN)
Definition: c.h:692
struct LogicalRepCtxStruct LogicalRepCtxStruct

◆ ApplyLauncherWakeup()

static void ApplyLauncherWakeup ( void  )
static

Definition at line 952 of file launcher.c.

References kill, LogicalRepCtxStruct::launcher_pid, and SIGUSR1.

Referenced by AtEOXact_ApplyLauncher(), and logicalrep_worker_onexit().

953 {
954  if (LogicalRepCtx->launcher_pid != 0)
956 }
#define SIGUSR1
Definition: win32_port.h:166
#define kill(pid, sig)
Definition: win32_port.h:426
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:67

◆ ApplyLauncherWakeupAtCommit()

void ApplyLauncherWakeupAtCommit ( void  )

Definition at line 945 of file launcher.c.

References on_commit_launcher_wakeup.

Referenced by AlterSubscription(), and CreateSubscription().

946 {
949 }
static bool on_commit_launcher_wakeup
Definition: launcher.c:98

◆ AtEOSubXact_ApplyLauncher()

void AtEOSubXact_ApplyLauncher ( bool  isCommit,
int  nestDepth 
)

Definition at line 890 of file launcher.c.

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

Referenced by AbortSubTransaction(), and CommitSubTransaction().

891 {
892  StopWorkersData *parent;
893 
894  /* Exit immediately if there's no work to do at this level. */
895  if (on_commit_stop_workers == NULL ||
896  on_commit_stop_workers->nestDepth < nestDepth)
897  return;
898 
899  Assert(on_commit_stop_workers->nestDepth == nestDepth);
900 
901  parent = on_commit_stop_workers->parent;
902 
903  if (isCommit)
904  {
905  /*
906  * If the upper stack element is not an immediate parent
907  * subtransaction, just decrement the notional nesting depth without
908  * doing any real work. Else, we need to merge the current workers
909  * list into the parent.
910  */
911  if (!parent || parent->nestDepth < nestDepth - 1)
912  {
914  return;
915  }
916 
917  parent->workers =
919  }
920  else
921  {
922  /*
923  * Abandon everything that was done at this nesting level. Explicitly
924  * free memory to avoid a transaction-lifespan leak.
925  */
927  }
928 
929  /*
930  * We have taken care of the current subtransaction workers list for both
931  * abort or commit. So we are ready to pop the stack.
932  */
934  on_commit_stop_workers = parent;
935 }
List * workers
Definition: launcher.c:78
List * list_concat(List *list1, const List *list2)
Definition: list.c:516
static StopWorkersData * on_commit_stop_workers
Definition: launcher.c:87
void list_free_deep(List *list)
Definition: list.c:1391
void pfree(void *pointer)
Definition: mcxt.c:1056
#define Assert(condition)
Definition: c.h:739
struct StopWorkersData * parent
Definition: launcher.c:79

◆ AtEOXact_ApplyLauncher()

void AtEOXact_ApplyLauncher ( bool  isCommit)

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

849 {
850 
851  Assert(on_commit_stop_workers == NULL ||
853  on_commit_stop_workers->parent == NULL));
854 
855  if (isCommit)
856  {
857  ListCell *lc;
858 
859  if (on_commit_stop_workers != NULL)
860  {
861  List *workers = on_commit_stop_workers->workers;
862 
863  foreach(lc, workers)
864  {
865  LogicalRepWorkerId *wid = lfirst(lc);
866 
867  logicalrep_worker_stop(wid->subid, wid->relid);
868  }
869  }
870 
873  }
874 
875  /*
876  * No need to pfree on_commit_stop_workers. It was allocated in
877  * transaction memory context, which is going to be cleaned soon.
878  */
879  on_commit_stop_workers = NULL;
881 }
List * workers
Definition: launcher.c:78
static StopWorkersData * on_commit_stop_workers
Definition: launcher.c:87
void logicalrep_worker_stop(Oid subid, Oid relid)
Definition: launcher.c:454
static bool on_commit_launcher_wakeup
Definition: launcher.c:98
#define Assert(condition)
Definition: c.h:739
#define lfirst(lc)
Definition: pg_list.h:190
struct StopWorkersData * parent
Definition: launcher.c:79
static void ApplyLauncherWakeup(void)
Definition: launcher.c:952
Definition: pg_list.h:50

◆ get_subscription_list()

static List* get_subscription_list ( void  )
static

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

111 {
112  List *res = NIL;
113  Relation rel;
114  TableScanDesc scan;
115  HeapTuple tup;
116  MemoryContext resultcxt;
117 
118  /* This is the context that we will allocate our output data in */
119  resultcxt = CurrentMemoryContext;
120 
121  /*
122  * Start a transaction so we can access pg_database, and get a snapshot.
123  * We don't have a use for the snapshot itself, but we're interested in
124  * the secondary effect that it sets RecentGlobalXmin. (This is critical
125  * for anything that reads heap pages, because HOT may decide to prune
126  * them even if the process doesn't attempt to modify any tuples.)
127  */
129  (void) GetTransactionSnapshot();
130 
131  rel = table_open(SubscriptionRelationId, AccessShareLock);
132  scan = table_beginscan_catalog(rel, 0, NULL);
133 
135  {
137  Subscription *sub;
138  MemoryContext oldcxt;
139 
140  /*
141  * Allocate our results in the caller's context, not the
142  * transaction's. We do this inside the loop, and restore the original
143  * context at the end, so that leaky things like heap_getnext() are
144  * not called in a potentially long-lived context.
145  */
146  oldcxt = MemoryContextSwitchTo(resultcxt);
147 
148  sub = (Subscription *) palloc0(sizeof(Subscription));
149  sub->oid = subform->oid;
150  sub->dbid = subform->subdbid;
151  sub->owner = subform->subowner;
152  sub->enabled = subform->subenabled;
153  sub->name = pstrdup(NameStr(subform->subname));
154  /* We don't fill fields we are not interested in. */
155 
156  res = lappend(res, sub);
157  MemoryContextSwitchTo(oldcxt);
158  }
159 
160  table_endscan(scan);
162 
164 
165  return res;
166 }
#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:1186
void CommitTransactionCommand(void)
Definition: xact.c:2898
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:322
void * palloc0(Size size)
Definition: mcxt.c:980
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void StartTransactionCommand(void)
Definition: xact.c:2797
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:831
#define NameStr(name)
Definition: c.h:616
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50

◆ IsLogicalLauncher()

bool IsLogicalLauncher ( void  )

Definition at line 1078 of file launcher.c.

References LogicalRepCtxStruct::launcher_pid, and MyProcPid.

Referenced by ProcessInterrupts().

1079 {
1081 }
int MyProcPid
Definition: globals.c:40
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:67

◆ logicalrep_launcher_onexit()

static void logicalrep_launcher_onexit ( int  code,
Datum  arg 
)
static

Definition at line 695 of file launcher.c.

References LogicalRepCtxStruct::launcher_pid.

Referenced by ApplyLauncherMain().

696 {
698 }
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:67

◆ logicalrep_launcher_sighup()

static void logicalrep_launcher_sighup ( SIGNAL_ARGS  )
static

Definition at line 719 of file launcher.c.

References got_SIGHUP, MyLatch, and SetLatch().

Referenced by ApplyLauncherMain().

720 {
721  int save_errno = errno;
722 
723  got_SIGHUP = true;
724 
725  /* Waken anything waiting on the process latch */
726  SetLatch(MyLatch);
727 
728  errno = save_errno;
729 }
static volatile sig_atomic_t got_SIGHUP
Definition: launcher.c:96
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 736 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().

737 {
738  int i;
739  int res = 0;
740 
741  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
742 
743  /* Search for attached worker for a given subscription id. */
744  for (i = 0; i < max_logical_replication_workers; i++)
745  {
747 
748  if (w->subid == subid && OidIsValid(w->relid))
749  res++;
750  }
751 
752  return res;
753 }
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1842
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:64
#define OidIsValid(objectId)
Definition: c.h:645
#define Assert(condition)
Definition: c.h:739
int max_logical_replication_workers
Definition: launcher.c:53
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:67
int i

◆ logicalrep_worker_attach()

void logicalrep_worker_attach ( int  slot)

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

628 {
629  /* Block concurrent access. */
630  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
631 
632  Assert(slot >= 0 && slot < max_logical_replication_workers);
634 
636  {
637  LWLockRelease(LogicalRepWorkerLock);
638  ereport(ERROR,
639  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
640  errmsg("logical replication worker slot %d is empty, cannot attach",
641  slot)));
642  }
643 
645  {
646  LWLockRelease(LogicalRepWorkerLock);
647  ereport(ERROR,
648  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
649  errmsg("logical replication worker slot %d is already used by "
650  "another worker, cannot attach", slot)));
651  }
652 
655 
656  LWLockRelease(LogicalRepWorkerLock);
657 }
PGPROC * MyProc
Definition: proc.c:67
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:64
int errcode(int sqlerrcode)
Definition: elog.c:608
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:56
#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:706
uintptr_t Datum
Definition: postgres.h:367
#define Assert(condition)
Definition: c.h:739
int max_logical_replication_workers
Definition: launcher.c:53
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
int errmsg(const char *fmt,...)
Definition: elog.c:822
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:67

◆ logicalrep_worker_cleanup()

static void logicalrep_worker_cleanup ( LogicalRepWorker worker)
static

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

678 {
679  Assert(LWLockHeldByMeInMode(LogicalRepWorkerLock, LW_EXCLUSIVE));
680 
681  worker->in_use = false;
682  worker->proc = NULL;
683  worker->dbid = InvalidOid;
684  worker->userid = InvalidOid;
685  worker->subid = InvalidOid;
686  worker->relid = InvalidOid;
687 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1860
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:739

◆ logicalrep_worker_detach()

static void logicalrep_worker_detach ( void  )
static

Definition at line 663 of file launcher.c.

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

Referenced by logicalrep_worker_onexit().

664 {
665  /* Block concurrent access. */
666  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
667 
669 
670  LWLockRelease(LogicalRepWorkerLock);
671 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:56
static void logicalrep_worker_cleanup(LogicalRepWorker *worker)
Definition: launcher.c:677
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 233 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().

234 {
235  int i;
236  LogicalRepWorker *res = NULL;
237 
238  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
239 
240  /* Search for attached worker for a given subscription id. */
241  for (i = 0; i < max_logical_replication_workers; i++)
242  {
244 
245  if (w->in_use && w->subid == subid && w->relid == relid &&
246  (!only_running || w->proc))
247  {
248  res = w;
249  break;
250  }
251  }
252 
253  return res;
254 }
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1842
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:64
#define Assert(condition)
Definition: c.h:739
int max_logical_replication_workers
Definition: launcher.c:53
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:67
int i

◆ logicalrep_worker_launch()

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

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

286 {
287  BackgroundWorker bgw;
288  BackgroundWorkerHandle *bgw_handle;
289  uint16 generation;
290  int i;
291  int slot = 0;
292  LogicalRepWorker *worker = NULL;
293  int nsyncworkers;
295 
296  ereport(DEBUG1,
297  (errmsg("starting logical replication worker for subscription \"%s\"",
298  subname)));
299 
300  /* Report this after the initial starting message for consistency. */
301  if (max_replication_slots == 0)
302  ereport(ERROR,
303  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
304  errmsg("cannot start logical replication workers when max_replication_slots = 0")));
305 
306  /*
307  * We need to do the modification of the shared memory under lock so that
308  * we have consistent view.
309  */
310  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
311 
312 retry:
313  /* Find unused worker slot. */
314  for (i = 0; i < max_logical_replication_workers; i++)
315  {
317 
318  if (!w->in_use)
319  {
320  worker = w;
321  slot = i;
322  break;
323  }
324  }
325 
326  nsyncworkers = logicalrep_sync_worker_count(subid);
327 
328  now = GetCurrentTimestamp();
329 
330  /*
331  * If we didn't find a free slot, try to do garbage collection. The
332  * reason we do this is because if some worker failed to start up and its
333  * parent has crashed while waiting, the in_use state was never cleared.
334  */
335  if (worker == NULL || nsyncworkers >= max_sync_workers_per_subscription)
336  {
337  bool did_cleanup = false;
338 
339  for (i = 0; i < max_logical_replication_workers; i++)
340  {
342 
343  /*
344  * If the worker was marked in use but didn't manage to attach in
345  * time, clean it up.
346  */
347  if (w->in_use && !w->proc &&
350  {
351  elog(WARNING,
352  "logical replication worker for subscription %u took too long to start; canceled",
353  w->subid);
354 
356  did_cleanup = true;
357  }
358  }
359 
360  if (did_cleanup)
361  goto retry;
362  }
363 
364  /*
365  * If we reached the sync worker limit per subscription, just exit
366  * silently as we might get here because of an otherwise harmless race
367  * condition.
368  */
369  if (nsyncworkers >= max_sync_workers_per_subscription)
370  {
371  LWLockRelease(LogicalRepWorkerLock);
372  return;
373  }
374 
375  /*
376  * However if there are no more free worker slots, inform user about it
377  * before exiting.
378  */
379  if (worker == NULL)
380  {
381  LWLockRelease(LogicalRepWorkerLock);
383  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
384  errmsg("out of logical replication worker slots"),
385  errhint("You might need to increase max_logical_replication_workers.")));
386  return;
387  }
388 
389  /* Prepare the worker slot. */
390  worker->launch_time = now;
391  worker->in_use = true;
392  worker->generation++;
393  worker->proc = NULL;
394  worker->dbid = dbid;
395  worker->userid = userid;
396  worker->subid = subid;
397  worker->relid = relid;
398  worker->relstate = SUBREL_STATE_UNKNOWN;
400  worker->last_lsn = InvalidXLogRecPtr;
403  worker->reply_lsn = InvalidXLogRecPtr;
404  TIMESTAMP_NOBEGIN(worker->reply_time);
405 
406  /* Before releasing lock, remember generation for future identification. */
407  generation = worker->generation;
408 
409  LWLockRelease(LogicalRepWorkerLock);
410 
411  /* Register the new dynamic worker. */
412  memset(&bgw, 0, sizeof(bgw));
416  snprintf(bgw.bgw_library_name, BGW_MAXLEN, "postgres");
417  snprintf(bgw.bgw_function_name, BGW_MAXLEN, "ApplyWorkerMain");
418  if (OidIsValid(relid))
420  "logical replication worker for subscription %u sync %u", subid, relid);
421  else
423  "logical replication worker for subscription %u", subid);
424  snprintf(bgw.bgw_type, BGW_MAXLEN, "logical replication worker");
425 
428  bgw.bgw_main_arg = Int32GetDatum(slot);
429 
430  if (!RegisterDynamicBackgroundWorker(&bgw, &bgw_handle))
431  {
432  /* Failed to start worker, so clean up the worker slot. */
433  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
434  Assert(generation == worker->generation);
436  LWLockRelease(LogicalRepWorkerLock);
437 
439  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
440  errmsg("out of background worker slots"),
441  errhint("You might need to increase max_worker_processes.")));
442  return;
443  }
444 
445  /* Now wait until it attaches. */
446  WaitForReplicationWorkerAttach(worker, generation, bgw_handle);
447 }
#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:1069
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1583
int64 TimestampTz
Definition: timestamp.h:39
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:64
TimestampTz last_send_time
XLogRecPtr last_lsn
int bgw_restart_time
Definition: bgworker.h:94
int errcode(int sqlerrcode)
Definition: elog.c:608
NameData subname
#define BGWORKER_SHMEM_ACCESS
Definition: bgworker.h:52
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1682
#define OidIsValid(objectId)
Definition: c.h:645
char bgw_function_name[BGW_MAXLEN]
Definition: bgworker.h:96
int wal_receiver_timeout
Definition: walreceiver.c:77
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:358
#define ERROR
Definition: elog.h:43
int max_sync_workers_per_subscription
Definition: launcher.c:54
XLogRecPtr reply_lsn
static void logicalrep_worker_cleanup(LogicalRepWorker *worker)
Definition: launcher.c:677
#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:736
static void WaitForReplicationWorkerAttach(LogicalRepWorker *worker, uint16 generation, BackgroundWorkerHandle *handle)
Definition: launcher.c:175
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:739
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
int max_logical_replication_workers
Definition: launcher.c:53
#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:822
pid_t bgw_notify_pid
Definition: bgworker.h:99
#define elog(elevel,...)
Definition: elog.h:228
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:67
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:1547
TimestampTz reply_time

◆ logicalrep_worker_onexit()

static void logicalrep_worker_onexit ( int  code,
Datum  arg 
)
static

Definition at line 706 of file launcher.c.

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

Referenced by logicalrep_worker_attach().

707 {
708  /* Disconnect gracefully from the remote side. */
709  if (wrconn)
711 
713 
715 }
WalReceiverConn * wrconn
Definition: worker.c:100
static void logicalrep_worker_detach(void)
Definition: launcher.c:663
#define walrcv_disconnect(conn)
Definition: walreceiver.h:281
static void ApplyLauncherWakeup(void)
Definition: launcher.c:952

◆ logicalrep_worker_stop()

void logicalrep_worker_stop ( Oid  subid,
Oid  relid 
)

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

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

552 {
553  int nestDepth = GetCurrentTransactionNestLevel();
554  LogicalRepWorkerId *wid;
555  MemoryContext oldctx;
556 
557  /* Make sure we store the info in context that survives until commit. */
559 
560  /* Check that previous transactions were properly cleaned up. */
561  Assert(on_commit_stop_workers == NULL ||
562  nestDepth >= on_commit_stop_workers->nestDepth);
563 
564  /*
565  * Push a new stack element if we don't already have one for the current
566  * nestDepth.
567  */
568  if (on_commit_stop_workers == NULL ||
569  nestDepth > on_commit_stop_workers->nestDepth)
570  {
571  StopWorkersData *newdata = palloc(sizeof(StopWorkersData));
572 
573  newdata->nestDepth = nestDepth;
574  newdata->workers = NIL;
575  newdata->parent = on_commit_stop_workers;
576  on_commit_stop_workers = newdata;
577  }
578 
579  /*
580  * Finally add a new worker into the worker list of the current
581  * subtransaction.
582  */
583  wid = palloc(sizeof(LogicalRepWorkerId));
584  wid->subid = subid;
585  wid->relid = relid;
588 
589  MemoryContextSwitchTo(oldctx);
590 }
#define NIL
Definition: pg_list.h:65
MemoryContext TopTransactionContext
Definition: mcxt.c:49
List * workers
Definition: launcher.c:78
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static StopWorkersData * on_commit_stop_workers
Definition: launcher.c:87
List * lappend(List *list, void *datum)
Definition: list.c:322
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:841
#define Assert(condition)
Definition: c.h:739
struct StopWorkersData * parent
Definition: launcher.c:79
void * palloc(Size size)
Definition: mcxt.c:949

◆ logicalrep_worker_wakeup()

void logicalrep_worker_wakeup ( Oid  subid,
Oid  relid 
)

Definition at line 596 of file launcher.c.

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

Referenced by pg_attribute_noreturn().

597 {
598  LogicalRepWorker *worker;
599 
600  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
601 
602  worker = logicalrep_worker_find(subid, relid, true);
603 
604  if (worker)
606 
607  LWLockRelease(LogicalRepWorkerLock);
608 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1726
void logicalrep_worker_wakeup_ptr(LogicalRepWorker *worker)
Definition: launcher.c:616
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:233
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122

◆ logicalrep_worker_wakeup_ptr()

void logicalrep_worker_wakeup_ptr ( LogicalRepWorker worker)

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

617 {
618  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
619 
620  SetLatch(&worker->proc->procLatch);
621 }
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:739

◆ logicalrep_workers_find()

List* logicalrep_workers_find ( Oid  subid,
bool  only_running 
)

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

262 {
263  int i;
264  List *res = NIL;
265 
266  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
267 
268  /* Search for attached worker for a given subscription id. */
269  for (i = 0; i < max_logical_replication_workers; i++)
270  {
272 
273  if (w->in_use && w->subid == subid && (!only_running || w->proc))
274  res = lappend(res, w);
275  }
276 
277  return res;
278 }
#define NIL
Definition: pg_list.h:65
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1842
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:64
List * lappend(List *list, void *datum)
Definition: list.c:322
#define Assert(condition)
Definition: c.h:739
int max_logical_replication_workers
Definition: launcher.c:53
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:67
int i
Definition: pg_list.h:50

◆ pg_stat_get_subscription()

Datum pg_stat_get_subscription ( PG_FUNCTION_ARGS  )

Definition at line 1087 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.

1088 {
1089 #define PG_STAT_GET_SUBSCRIPTION_COLS 8
1090  Oid subid = PG_ARGISNULL(0) ? InvalidOid : PG_GETARG_OID(0);
1091  int i;
1092  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1093  TupleDesc tupdesc;
1094  Tuplestorestate *tupstore;
1095  MemoryContext per_query_ctx;
1096  MemoryContext oldcontext;
1097 
1098  /* check to see if caller supports us returning a tuplestore */
1099  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
1100  ereport(ERROR,
1101  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1102  errmsg("set-valued function called in context that cannot accept a set")));
1103  if (!(rsinfo->allowedModes & SFRM_Materialize))
1104  ereport(ERROR,
1105  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1106  errmsg("materialize mode required, but it is not " \
1107  "allowed in this context")));
1108 
1109  /* Build a tuple descriptor for our result type */
1110  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1111  elog(ERROR, "return type must be a row type");
1112 
1113  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1114  oldcontext = MemoryContextSwitchTo(per_query_ctx);
1115 
1116  tupstore = tuplestore_begin_heap(true, false, work_mem);
1117  rsinfo->returnMode = SFRM_Materialize;
1118  rsinfo->setResult = tupstore;
1119  rsinfo->setDesc = tupdesc;
1120 
1121  MemoryContextSwitchTo(oldcontext);
1122 
1123  /* Make sure we get consistent view of the workers. */
1124  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
1125 
1126  for (i = 0; i <= max_logical_replication_workers; i++)
1127  {
1128  /* for each row */
1130  bool nulls[PG_STAT_GET_SUBSCRIPTION_COLS];
1131  int worker_pid;
1132  LogicalRepWorker worker;
1133 
1134  memcpy(&worker, &LogicalRepCtx->workers[i],
1135  sizeof(LogicalRepWorker));
1136  if (!worker.proc || !IsBackendPid(worker.proc->pid))
1137  continue;
1138 
1139  if (OidIsValid(subid) && worker.subid != subid)
1140  continue;
1141 
1142  worker_pid = worker.proc->pid;
1143 
1144  MemSet(values, 0, sizeof(values));
1145  MemSet(nulls, 0, sizeof(nulls));
1146 
1147  values[0] = ObjectIdGetDatum(worker.subid);
1148  if (OidIsValid(worker.relid))
1149  values[1] = ObjectIdGetDatum(worker.relid);
1150  else
1151  nulls[1] = true;
1152  values[2] = Int32GetDatum(worker_pid);
1153  if (XLogRecPtrIsInvalid(worker.last_lsn))
1154  nulls[3] = true;
1155  else
1156  values[3] = LSNGetDatum(worker.last_lsn);
1157  if (worker.last_send_time == 0)
1158  nulls[4] = true;
1159  else
1160  values[4] = TimestampTzGetDatum(worker.last_send_time);
1161  if (worker.last_recv_time == 0)
1162  nulls[5] = true;
1163  else
1164  values[5] = TimestampTzGetDatum(worker.last_recv_time);
1165  if (XLogRecPtrIsInvalid(worker.reply_lsn))
1166  nulls[6] = true;
1167  else
1168  values[6] = LSNGetDatum(worker.reply_lsn);
1169  if (worker.reply_time == 0)
1170  nulls[7] = true;
1171  else
1172  values[7] = TimestampTzGetDatum(worker.reply_time);
1173 
1174  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
1175 
1176  /*
1177  * If only a single subscription was requested, and we found it,
1178  * break.
1179  */
1180  if (OidIsValid(subid))
1181  break;
1182  }
1183 
1184  LWLockRelease(LogicalRepWorkerLock);
1185 
1186  /* clean up and return the tuplestore */
1187  tuplestore_donestoring(tupstore);
1188 
1189  return (Datum) 0;
1190 }
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, Datum *values, bool *isnull)
Definition: tuplestore.c:750
#define IsA(nodeptr, _type_)
Definition: nodes.h:576
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:64
TimestampTz last_send_time
XLogRecPtr last_lsn
int errcode(int sqlerrcode)
Definition: elog.c:608
#define LSNGetDatum(X)
Definition: pg_lsn.h:22
#define MemSet(start, val, len)
Definition: c.h:962
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:645
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:302
SetFunctionReturnMode returnMode
Definition: execnodes.h:304
TimestampTz last_recv_time
#define PG_ARGISNULL(n)
Definition: fmgr.h:204
int max_logical_replication_workers
Definition: launcher.c:53
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1122
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:230
Tuplestorestate * setResult
Definition: execnodes.h:307
static Datum values[MAXATTR]
Definition: bootstrap.c:167
ExprContext * econtext
Definition: execnodes.h:300
#define Int32GetDatum(X)
Definition: postgres.h:479
TupleDesc setDesc
Definition: execnodes.h:308
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:67
int i
bool IsBackendPid(int pid)
Definition: procarray.c:2460
int pid
Definition: proc.h:109
TimestampTz reply_time

◆ WaitForReplicationWorkerAttach()

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

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

178 {
180  int rc;
181 
182  for (;;)
183  {
184  pid_t pid;
185 
187 
188  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
189 
190  /* Worker either died or has started; no need to do anything. */
191  if (!worker->in_use || worker->proc)
192  {
193  LWLockRelease(LogicalRepWorkerLock);
194  return;
195  }
196 
197  LWLockRelease(LogicalRepWorkerLock);
198 
199  /* Check if worker has died before attaching, and clean up after it. */
200  status = GetBackgroundWorkerPid(handle, &pid);
201 
202  if (status == BGWH_STOPPED)
203  {
204  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
205  /* Ensure that this was indeed the worker we waited for. */
206  if (generation == worker->generation)
208  LWLockRelease(LogicalRepWorkerLock);
209  return;
210  }
211 
212  /*
213  * We need timeout because we generally don't get notified via latch
214  * about the worker attach. But we don't expect to have to wait long.
215  */
216  rc = WaitLatch(MyLatch,
219 
220  if (rc & WL_LATCH_SET)
221  {
224  }
225  }
226 }
#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:677
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:226
#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 839 of file launcher.c.

Referenced by PrepareTransaction().

840 {
841  return (on_commit_stop_workers != NULL);
842 }
static StopWorkersData * on_commit_stop_workers
Definition: launcher.c:87

Variable Documentation

◆ got_SIGHUP

volatile sig_atomic_t got_SIGHUP = false
static

Definition at line 96 of file launcher.c.

Referenced by ApplyLauncherMain(), and logicalrep_launcher_sighup().

◆ LogicalRepCtx

LogicalRepCtxStruct* LogicalRepCtx

Definition at line 67 of file launcher.c.

◆ max_logical_replication_workers

◆ max_sync_workers_per_subscription

int max_sync_workers_per_subscription = 2

Definition at line 54 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 98 of file launcher.c.

Referenced by ApplyLauncherWakeupAtCommit(), and AtEOXact_ApplyLauncher().

◆ on_commit_stop_workers

StopWorkersData* on_commit_stop_workers = NULL
static

Definition at line 87 of file launcher.c.

Referenced by logicalrep_worker_stop_at_commit().