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
 

Macros

#define DEFAULT_NAPTIME_PER_CYCLE   180000L
 
#define PG_STAT_GET_SUBSCRIPTION_COLS   8
 

Typedefs

typedef struct LogicalRepCtxStruct LogicalRepCtxStruct
 
typedef struct LogicalRepWorkerId LogicalRepWorkerId
 

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 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 Liston_commit_stop_workers = NIL
 
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 58 of file launcher.c.

Referenced by ApplyLauncherMain().

◆ PG_STAT_GET_SUBSCRIPTION_COLS

#define PG_STAT_GET_SUBSCRIPTION_COLS   8

Typedef Documentation

◆ LogicalRepCtxStruct

◆ LogicalRepWorkerId

Function Documentation

◆ ApplyLauncherMain()

void ApplyLauncherMain ( Datum  main_arg)

Definition at line 883 of file launcher.c.

References ALLOCSET_DEFAULT_INITSIZE, ALLOCSET_DEFAULT_MAXSIZE, ALLOCSET_DEFAULT_MINSIZE, 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(), proc_exit(), ProcessConfigFile(), ResetLatch(), SIGHUP, TimestampDifferenceExceeds(), TopMemoryContext, WAIT_EVENT_LOGICAL_LAUNCHER_MAIN, WaitLatch(), wal_retrieve_retry_interval, WL_LATCH_SET, WL_POSTMASTER_DEATH, and WL_TIMEOUT.

884 {
885  TimestampTz last_start_time = 0;
886 
887  ereport(DEBUG1,
888  (errmsg("logical replication launcher started")));
889 
891 
894 
895  /* Establish signal handlers. */
897  pqsignal(SIGTERM, die);
899 
900  /*
901  * Establish connection to nailed catalogs (we only ever access
902  * pg_subscription).
903  */
905 
906  /* Enter main loop */
907  for (;;)
908  {
909  int rc;
910  List *sublist;
911  ListCell *lc;
912  MemoryContext subctx;
913  MemoryContext oldctx;
915  long wait_time = DEFAULT_NAPTIME_PER_CYCLE;
916 
918 
919  now = GetCurrentTimestamp();
920 
921  /* Limit the start retry to once a wal_retrieve_retry_interval */
922  if (TimestampDifferenceExceeds(last_start_time, now,
924  {
925  /* Use temporary context for the database list and worker info. */
927  "Logical Replication Launcher sublist",
931  oldctx = MemoryContextSwitchTo(subctx);
932 
933  /* search for subscriptions to start or stop. */
934  sublist = get_subscription_list();
935 
936  /* Start the missing workers for enabled subscriptions. */
937  foreach(lc, sublist)
938  {
939  Subscription *sub = (Subscription *) lfirst(lc);
940  LogicalRepWorker *w;
941 
942  if (!sub->enabled)
943  continue;
944 
945  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
946  w = logicalrep_worker_find(sub->oid, InvalidOid, false);
947  LWLockRelease(LogicalRepWorkerLock);
948 
949  if (w == NULL)
950  {
951  last_start_time = now;
952  wait_time = wal_retrieve_retry_interval;
953 
954  logicalrep_worker_launch(sub->dbid, sub->oid, sub->name,
955  sub->owner, InvalidOid);
956  }
957  }
958 
959  /* Switch back to original memory context. */
960  MemoryContextSwitchTo(oldctx);
961  /* Clean the temporary memory. */
962  MemoryContextDelete(subctx);
963  }
964  else
965  {
966  /*
967  * The wait in previous cycle was interrupted in less than
968  * wal_retrieve_retry_interval since last worker was started, this
969  * usually means crash of the worker, so we should retry in
970  * wal_retrieve_retry_interval again.
971  */
972  wait_time = wal_retrieve_retry_interval;
973  }
974 
975  /* Wait for more work. */
976  rc = WaitLatch(MyLatch,
978  wait_time,
980 
981  /* emergency bailout if postmaster has died */
982  if (rc & WL_POSTMASTER_DEATH)
983  proc_exit(1);
984 
985  if (rc & WL_LATCH_SET)
986  {
989  }
990 
991  if (got_SIGHUP)
992  {
993  got_SIGHUP = false;
995  }
996  }
997 
998  /* Not reachable */
999 }
static volatile sig_atomic_t got_SIGHUP
Definition: launcher.c:91
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:200
#define DEBUG1
Definition: elog.h:25
int MyProcPid
Definition: globals.c:39
#define WL_TIMEOUT
Definition: latch.h:127
void ProcessConfigFile(GucContext context)
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
int64 TimestampTz
Definition: timestamp.h:39
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
void proc_exit(int code)
Definition: ipc.c:99
void ResetLatch(volatile Latch *latch)
Definition: latch.c:497
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1649
#define ALLOCSET_DEFAULT_MINSIZE
Definition: memutils.h:167
void BackgroundWorkerInitializeConnection(const char *dbname, const char *username)
Definition: postmaster.c:5588
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
int WaitLatch(volatile Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:336
#define SIGHUP
Definition: win32_port.h:163
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:320
static void logicalrep_launcher_onexit(int code, Datum arg)
Definition: launcher.c:680
#define ereport(elevel, rest)
Definition: elog.h:122
MemoryContext TopMemoryContext
Definition: mcxt.c:43
Definition: guc.h:72
int wal_retrieve_retry_interval
Definition: xlog.c:107
#define WL_POSTMASTER_DEATH
Definition: latch.h:128
MemoryContext AllocSetContextCreate(MemoryContext parent, const char *name, Size minContextSize, Size initBlockSize, Size maxBlockSize)
Definition: aset.c:322
#define DEFAULT_NAPTIME_PER_CYCLE
Definition: launcher.c:58
uintptr_t Datum
Definition: postgres.h:372
static void logicalrep_launcher_sighup(SIGNAL_ARGS)
Definition: launcher.c:704
#define InvalidOid
Definition: postgres_ext.h:36
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:168
static List * get_subscription_list(void)
Definition: launcher.c:105
void logicalrep_worker_launch(Oid dbid, Oid subid, const char *subname, Oid userid, Oid relid)
Definition: launcher.c:285
#define Assert(condition)
Definition: c.h:670
#define lfirst(lc)
Definition: pg_list.h:106
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:234
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
int errmsg(const char *fmt,...)
Definition: elog.c:797
void die(SIGNAL_ARGS)
Definition: postgres.c:2652
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:74
#define ALLOCSET_DEFAULT_INITSIZE
Definition: memutils.h:168
struct Latch * MyLatch
Definition: globals.c:52
#define ALLOCSET_DEFAULT_MAXSIZE
Definition: memutils.h:169
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
Definition: pg_list.h:45
#define WL_LATCH_SET
Definition: latch.h:124
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1534
void BackgroundWorkerUnblockSignals(void)
Definition: postmaster.c:5640

◆ ApplyLauncherRegister()

void ApplyLauncherRegister ( void  )

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

765 {
766  BackgroundWorker bgw;
767 
769  return;
770 
771  memset(&bgw, 0, sizeof(bgw));
775  snprintf(bgw.bgw_library_name, BGW_MAXLEN, "postgres");
776  snprintf(bgw.bgw_function_name, BGW_MAXLEN, "ApplyLauncherMain");
778  "logical replication launcher");
780  "logical replication launcher");
781  bgw.bgw_restart_time = 5;
782  bgw.bgw_notify_pid = 0;
783  bgw.bgw_main_arg = (Datum) 0;
784 
786 }
void RegisterBackgroundWorker(BackgroundWorker *worker)
Definition: bgworker.c:855
int bgw_restart_time
Definition: bgworker.h:94
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#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:372
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:60
#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

◆ ApplyLauncherShmemInit()

void ApplyLauncherShmemInit ( void  )

Definition at line 793 of file launcher.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

794 {
795  bool found;
796 
798  ShmemInitStruct("Logical Replication Launcher Data",
800  &found);
801 
802  if (!found)
803  {
804  int slot;
805 
807 
808  /* Initialize memory and spin locks for each worker slot. */
809  for (slot = 0; slot < max_logical_replication_workers; slot++)
810  {
811  LogicalRepWorker *worker = &LogicalRepCtx->workers[slot];
812 
813  memset(worker, 0, sizeof(LogicalRepWorker));
814  SpinLockInit(&worker->relmutex);
815  }
816  }
817 }
#define SpinLockInit(lock)
Definition: spin.h:60
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:71
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:372
Size ApplyLauncherShmemSize(void)
Definition: launcher.c:745
int max_logical_replication_workers
Definition: launcher.c:60
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:74

◆ ApplyLauncherShmemSize()

Size ApplyLauncherShmemSize ( void  )

Definition at line 745 of file launcher.c.

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

Referenced by ApplyLauncherShmemInit(), and CreateSharedMemoryAndSemaphores().

746 {
747  Size size;
748 
749  /*
750  * Need the fixed struct and the array of LogicalRepWorker.
751  */
752  size = sizeof(LogicalRepCtxStruct);
753  size = MAXALIGN(size);
755  sizeof(LogicalRepWorker)));
756  return size;
757 }
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:60
size_t Size
Definition: c.h:404
#define MAXALIGN(LEN)
Definition: c.h:623
struct LogicalRepCtxStruct LogicalRepCtxStruct

◆ ApplyLauncherWakeup()

static void ApplyLauncherWakeup ( void  )
static

Definition at line 873 of file launcher.c.

References kill, LogicalRepCtxStruct::launcher_pid, and SIGUSR1.

Referenced by AtEOXact_ApplyLauncher(), and logicalrep_worker_onexit().

874 {
875  if (LogicalRepCtx->launcher_pid != 0)
877 }
#define SIGUSR1
Definition: win32_port.h:177
#define kill(pid, sig)
Definition: win32_port.h:437
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:74

◆ ApplyLauncherWakeupAtCommit()

void ApplyLauncherWakeupAtCommit ( void  )

Definition at line 866 of file launcher.c.

References on_commit_launcher_wakeup.

Referenced by AlterSubscription(), and CreateSubscription().

867 {
870 }
static bool on_commit_launcher_wakeup
Definition: launcher.c:93

◆ AtEOXact_ApplyLauncher()

void AtEOXact_ApplyLauncher ( bool  isCommit)

Definition at line 833 of file launcher.c.

References ApplyLauncherWakeup(), lfirst, logicalrep_worker_stop(), NIL, on_commit_launcher_wakeup, LogicalRepWorkerId::relid, and LogicalRepWorkerId::subid.

Referenced by AbortTransaction(), and CommitTransaction().

834 {
835  if (isCommit)
836  {
837  ListCell *lc;
838 
839  foreach(lc, on_commit_stop_workers)
840  {
841  LogicalRepWorkerId *wid = lfirst(lc);
842 
843  logicalrep_worker_stop(wid->subid, wid->relid);
844  }
845 
848  }
849 
850  /*
851  * No need to pfree on_commit_stop_workers. It was allocated in
852  * transaction memory context, which is going to be cleaned soon.
853  */
856 }
#define NIL
Definition: pg_list.h:69
void logicalrep_worker_stop(Oid subid, Oid relid)
Definition: launcher.c:455
static bool on_commit_launcher_wakeup
Definition: launcher.c:93
#define lfirst(lc)
Definition: pg_list.h:106
static List * on_commit_stop_workers
Definition: launcher.c:82
static void ApplyLauncherWakeup(void)
Definition: launcher.c:873

◆ get_subscription_list()

static List* get_subscription_list ( void  )
static

Definition at line 105 of file launcher.c.

References AccessShareLock, CommitTransactionCommand(), CurrentMemoryContext, Subscription::dbid, Subscription::enabled, ForwardScanDirection, GETSTRUCT, GetTransactionSnapshot(), heap_beginscan_catalog(), heap_close, heap_endscan(), heap_getnext(), heap_open(), HeapTupleGetOid, HeapTupleIsValid, lappend(), MemoryContextSwitchTo(), Subscription::name, NameStr, NIL, Subscription::oid, Subscription::owner, palloc0(), pstrdup(), StartTransactionCommand(), and SubscriptionRelationId.

Referenced by ApplyLauncherMain().

106 {
107  List *res = NIL;
108  Relation rel;
109  HeapScanDesc scan;
110  HeapTuple tup;
111  MemoryContext resultcxt;
112 
113  /* This is the context that we will allocate our output data in */
114  resultcxt = CurrentMemoryContext;
115 
116  /*
117  * Start a transaction so we can access pg_database, and get a snapshot.
118  * We don't have a use for the snapshot itself, but we're interested in
119  * the secondary effect that it sets RecentGlobalXmin. (This is critical
120  * for anything that reads heap pages, because HOT may decide to prune
121  * them even if the process doesn't attempt to modify any tuples.)
122  */
124  (void) GetTransactionSnapshot();
125 
127  scan = heap_beginscan_catalog(rel, 0, NULL);
128 
130  {
132  Subscription *sub;
133  MemoryContext oldcxt;
134 
135  /*
136  * Allocate our results in the caller's context, not the
137  * transaction's. We do this inside the loop, and restore the original
138  * context at the end, so that leaky things like heap_getnext() are
139  * not called in a potentially long-lived context.
140  */
141  oldcxt = MemoryContextSwitchTo(resultcxt);
142 
143  sub = (Subscription *) palloc0(sizeof(Subscription));
144  sub->oid = HeapTupleGetOid(tup);
145  sub->dbid = subform->subdbid;
146  sub->owner = subform->subowner;
147  sub->enabled = subform->subenabled;
148  sub->name = pstrdup(NameStr(subform->subname));
149  /* We don't fill fields we are not interested in. */
150 
151  res = lappend(res, sub);
152  MemoryContextSwitchTo(oldcxt);
153  }
154 
155  heap_endscan(scan);
157 
159 
160  return res;
161 }
#define NIL
Definition: pg_list.h:69
#define GETSTRUCT(TUP)
Definition: htup_details.h:661
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1565
char * pstrdup(const char *in)
Definition: mcxt.c:1076
void CommitTransactionCommand(void)
Definition: xact.c:2744
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
#define heap_close(r, l)
Definition: heapam.h:97
FormData_pg_subscription * Form_pg_subscription
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:304
#define SubscriptionRelationId
MemoryContext CurrentMemoryContext
Definition: mcxt.c:37
HeapScanDesc heap_beginscan_catalog(Relation relation, int nkeys, ScanKey key)
Definition: heapam.c:1405
List * lappend(List *list, void *datum)
Definition: list.c:128
void * palloc0(Size size)
Definition: mcxt.c:877
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1808
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
void StartTransactionCommand(void)
Definition: xact.c:2673
#define NameStr(name)
Definition: c.h:547
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:700
Definition: pg_list.h:45

◆ IsLogicalLauncher()

bool IsLogicalLauncher ( void  )

Definition at line 1005 of file launcher.c.

References LogicalRepCtxStruct::launcher_pid, and MyProcPid.

Referenced by ProcessInterrupts().

1006 {
1008 }
int MyProcPid
Definition: globals.c:39
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:74

◆ logicalrep_launcher_onexit()

static void logicalrep_launcher_onexit ( int  code,
Datum  arg 
)
static

Definition at line 680 of file launcher.c.

References LogicalRepCtxStruct::launcher_pid.

Referenced by ApplyLauncherMain().

681 {
683 }
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:74

◆ logicalrep_launcher_sighup()

static void logicalrep_launcher_sighup ( SIGNAL_ARGS  )
static

Definition at line 704 of file launcher.c.

References got_SIGHUP, MyLatch, and SetLatch().

Referenced by ApplyLauncherMain().

705 {
706  int save_errno = errno;
707 
708  got_SIGHUP = true;
709 
710  /* Waken anything waiting on the process latch */
711  SetLatch(MyLatch);
712 
713  errno = save_errno;
714 }
static volatile sig_atomic_t got_SIGHUP
Definition: launcher.c:91
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
struct Latch * MyLatch
Definition: globals.c:52

◆ logicalrep_sync_worker_count()

int logicalrep_sync_worker_count ( Oid  subid)

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

722 {
723  int i;
724  int res = 0;
725 
726  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
727 
728  /* Search for attached worker for a given subscription id. */
729  for (i = 0; i < max_logical_replication_workers; i++)
730  {
732 
733  if (w->subid == subid && OidIsValid(w->relid))
734  res++;
735  }
736 
737  return res;
738 }
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1837
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:71
#define OidIsValid(objectId)
Definition: c.h:576
#define Assert(condition)
Definition: c.h:670
int max_logical_replication_workers
Definition: launcher.c:60
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:74
int i

◆ logicalrep_worker_attach()

void logicalrep_worker_attach ( int  slot)

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

613 {
614  /* Block concurrent access. */
615  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
616 
617  Assert(slot >= 0 && slot < max_logical_replication_workers);
619 
621  {
622  LWLockRelease(LogicalRepWorkerLock);
623  ereport(ERROR,
624  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
625  errmsg("logical replication worker slot %d is empty, cannot attach",
626  slot)));
627  }
628 
630  {
631  LWLockRelease(LogicalRepWorkerLock);
632  ereport(ERROR,
633  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
634  errmsg("logical replication worker slot %d is already used by "
635  "another worker, cannot attach", slot)));
636  }
637 
640 
641  LWLockRelease(LogicalRepWorkerLock);
642 }
PGPROC * MyProc
Definition: proc.c:67
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:71
int errcode(int sqlerrcode)
Definition: elog.c:575
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:63
#define ERROR
Definition: elog.h:43
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:320
#define ereport(elevel, rest)
Definition: elog.h:122
static void logicalrep_worker_onexit(int code, Datum arg)
Definition: launcher.c:691
uintptr_t Datum
Definition: postgres.h:372
#define Assert(condition)
Definition: c.h:670
int max_logical_replication_workers
Definition: launcher.c:60
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
int errmsg(const char *fmt,...)
Definition: elog.c:797
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:74

◆ logicalrep_worker_cleanup()

static void logicalrep_worker_cleanup ( LogicalRepWorker worker)
static

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

663 {
664  Assert(LWLockHeldByMeInMode(LogicalRepWorkerLock, LW_EXCLUSIVE));
665 
666  worker->in_use = false;
667  worker->proc = NULL;
668  worker->dbid = InvalidOid;
669  worker->userid = InvalidOid;
670  worker->subid = InvalidOid;
671  worker->relid = InvalidOid;
672 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1855
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:670

◆ logicalrep_worker_detach()

static void logicalrep_worker_detach ( void  )
static

Definition at line 648 of file launcher.c.

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

Referenced by logicalrep_worker_onexit().

649 {
650  /* Block concurrent access. */
651  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
652 
654 
655  LWLockRelease(LogicalRepWorkerLock);
656 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:63
static void logicalrep_worker_cleanup(LogicalRepWorker *worker)
Definition: launcher.c:662
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117

◆ logicalrep_worker_find()

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

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

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

◆ logicalrep_worker_launch()

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

Definition at line 285 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, SUBREL_STATE_UNKNOWN, TIMESTAMP_NOBEGIN, TimestampDifferenceExceeds(), LogicalRepWorker::userid, WaitForReplicationWorkerAttach(), wal_receiver_timeout, WARNING, and LogicalRepCtxStruct::workers.

Referenced by ApplyLauncherMain(), and process_syncing_tables_for_apply().

287 {
288  BackgroundWorker bgw;
289  BackgroundWorkerHandle *bgw_handle;
290  uint16 generation;
291  int i;
292  int slot = 0;
293  LogicalRepWorker *worker = NULL;
294  int nsyncworkers;
296 
297  ereport(DEBUG1,
298  (errmsg("starting logical replication worker for subscription \"%s\"",
299  subname)));
300 
301  /* Report this after the initial starting message for consistency. */
302  if (max_replication_slots == 0)
303  ereport(ERROR,
304  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
305  errmsg("cannot start logical replication workers when max_replication_slots = 0")));
306 
307  /*
308  * We need to do the modification of the shared memory under lock so that
309  * we have consistent view.
310  */
311  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
312 
313 retry:
314  /* Find unused worker slot. */
315  for (i = 0; i < max_logical_replication_workers; i++)
316  {
318 
319  if (!w->in_use)
320  {
321  worker = w;
322  slot = i;
323  break;
324  }
325  }
326 
327  nsyncworkers = logicalrep_sync_worker_count(subid);
328 
329  now = GetCurrentTimestamp();
330 
331  /*
332  * If we didn't find a free slot, try to do garbage collection. The
333  * reason we do this is because if some worker failed to start up and its
334  * parent has crashed while waiting, the in_use state was never cleared.
335  */
336  if (worker == NULL || nsyncworkers >= max_sync_workers_per_subscription)
337  {
338  bool did_cleanup = false;
339 
340  for (i = 0; i < max_logical_replication_workers; i++)
341  {
343 
344  /*
345  * If the worker was marked in use but didn't manage to attach in
346  * time, clean it up.
347  */
348  if (w->in_use && !w->proc &&
351  {
352  elog(WARNING,
353  "logical replication worker for subscription %u took too long to start; canceled",
354  w->subid);
355 
357  did_cleanup = true;
358  }
359  }
360 
361  if (did_cleanup)
362  goto retry;
363  }
364 
365  /*
366  * If we reached the sync worker limit per subscription, just exit
367  * silently as we might get here because of an otherwise harmless race
368  * condition.
369  */
370  if (nsyncworkers >= max_sync_workers_per_subscription)
371  {
372  LWLockRelease(LogicalRepWorkerLock);
373  return;
374  }
375 
376  /*
377  * However if there are no more free worker slots, inform user about it
378  * before exiting.
379  */
380  if (worker == NULL)
381  {
382  LWLockRelease(LogicalRepWorkerLock);
384  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
385  errmsg("out of logical replication worker slots"),
386  errhint("You might need to increase max_logical_replication_workers.")));
387  return;
388  }
389 
390  /* Prepare the worker slot. */
391  worker->launch_time = now;
392  worker->in_use = true;
393  worker->generation++;
394  worker->proc = NULL;
395  worker->dbid = dbid;
396  worker->userid = userid;
397  worker->subid = subid;
398  worker->relid = relid;
399  worker->relstate = SUBREL_STATE_UNKNOWN;
401  worker->last_lsn = InvalidXLogRecPtr;
404  worker->reply_lsn = InvalidXLogRecPtr;
405  TIMESTAMP_NOBEGIN(worker->reply_time);
406 
407  /* Before releasing lock, remember generation for future identification. */
408  generation = worker->generation;
409 
410  LWLockRelease(LogicalRepWorkerLock);
411 
412  /* Register the new dynamic worker. */
413  memset(&bgw, 0, sizeof(bgw));
417  snprintf(bgw.bgw_library_name, BGW_MAXLEN, "postgres");
418  snprintf(bgw.bgw_function_name, BGW_MAXLEN, "ApplyWorkerMain");
419  if (OidIsValid(relid))
421  "logical replication worker for subscription %u sync %u", subid, relid);
422  else
424  "logical replication worker for subscription %u", subid);
425  snprintf(bgw.bgw_type, BGW_MAXLEN, "logical replication worker");
426 
429  bgw.bgw_main_arg = Int32GetDatum(slot);
430 
431  if (!RegisterDynamicBackgroundWorker(&bgw, &bgw_handle))
432  {
433  /* Failed to start worker, so clean up the worker slot. */
434  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
435  Assert(generation == worker->generation);
437  LWLockRelease(LogicalRepWorkerLock);
438 
440  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
441  errmsg("out of background worker slots"),
442  errhint("You might need to increase max_worker_processes.")));
443  return;
444  }
445 
446  /* Now wait until it attaches. */
447  WaitForReplicationWorkerAttach(worker, generation, bgw_handle);
448 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define DEBUG1
Definition: elog.h:25
int MyProcPid
Definition: globals.c:39
int errhint(const char *fmt,...)
Definition: elog.c:987
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1570
int64 TimestampTz
Definition: timestamp.h:39
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:71
TimestampTz last_send_time
XLogRecPtr last_lsn
int bgw_restart_time
Definition: bgworker.h:94
int errcode(int sqlerrcode)
Definition: elog.c:575
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define BGWORKER_SHMEM_ACCESS
Definition: bgworker.h:52
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1649
#define OidIsValid(objectId)
Definition: c.h:576
char bgw_function_name[BGW_MAXLEN]
Definition: bgworker.h:96
int wal_receiver_timeout
Definition: walreceiver.c:75
XLogRecPtr relstate_lsn
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
Datum bgw_main_arg
Definition: bgworker.h:97
unsigned short uint16
Definition: c.h:295
#define ERROR
Definition: elog.h:43
int max_sync_workers_per_subscription
Definition: launcher.c:61
XLogRecPtr reply_lsn
static void logicalrep_worker_cleanup(LogicalRepWorker *worker)
Definition: launcher.c:662
#define SUBREL_STATE_UNKNOWN
#define BGW_NEVER_RESTART
Definition: bgworker.h:84
#define TIMESTAMP_NOBEGIN(j)
Definition: timestamp.h:112
#define ereport(elevel, rest)
Definition: elog.h:122
#define WARNING
Definition: elog.h:40
int logicalrep_sync_worker_count(Oid subid)
Definition: launcher.c:721
static void WaitForReplicationWorkerAttach(LogicalRepWorker *worker, uint16 generation, BackgroundWorkerHandle *handle)
Definition: launcher.c:170
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:670
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
int max_logical_replication_workers
Definition: launcher.c:60
#define BGW_MAXLEN
Definition: bgworker.h:85
BgWorkerStartTime bgw_start_time
Definition: bgworker.h:93
bool RegisterDynamicBackgroundWorker(BackgroundWorker *worker, BackgroundWorkerHandle **handle)
Definition: bgworker.c:939
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
#define Int32GetDatum(X)
Definition: postgres.h:485
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:91
int errmsg(const char *fmt,...)
Definition: elog.c:797
pid_t bgw_notify_pid
Definition: bgworker.h:99
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:74
int i
#define elog
Definition: elog.h:219
char bgw_library_name[BGW_MAXLEN]
Definition: bgworker.h:95
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1534
TimestampTz reply_time

◆ logicalrep_worker_onexit()

static void logicalrep_worker_onexit ( int  code,
Datum  arg 
)
static

Definition at line 691 of file launcher.c.

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

Referenced by logicalrep_worker_attach().

692 {
693  /* Disconnect gracefully from the remote side. */
694  if (wrconn)
696 
698 
700 }
WalReceiverConn * wrconn
Definition: worker.c:110
static void logicalrep_worker_detach(void)
Definition: launcher.c:648
#define walrcv_disconnect(conn)
Definition: walreceiver.h:265
static void ApplyLauncherWakeup(void)
Definition: launcher.c:873

◆ logicalrep_worker_stop()

void logicalrep_worker_stop ( Oid  subid,
Oid  relid 
)

Definition at line 455 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, proc_exit(), ResetLatch(), WAIT_EVENT_BGWORKER_SHUTDOWN, WAIT_EVENT_BGWORKER_STARTUP, WaitLatch(), WL_LATCH_SET, WL_POSTMASTER_DEATH, and WL_TIMEOUT.

Referenced by AtEOXact_ApplyLauncher(), and DropSubscription().

456 {
457  LogicalRepWorker *worker;
458  uint16 generation;
459 
460  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
461 
462  worker = logicalrep_worker_find(subid, relid, false);
463 
464  /* No worker, nothing to do. */
465  if (!worker)
466  {
467  LWLockRelease(LogicalRepWorkerLock);
468  return;
469  }
470 
471  /*
472  * Remember which generation was our worker so we can check if what we see
473  * is still the same one.
474  */
475  generation = worker->generation;
476 
477  /*
478  * If we found a worker but it does not have proc set then it is still
479  * starting up; wait for it to finish starting and then kill it.
480  */
481  while (worker->in_use && !worker->proc)
482  {
483  int rc;
484 
485  LWLockRelease(LogicalRepWorkerLock);
486 
487  /* Wait a bit --- we don't expect to have to wait long. */
488  rc = WaitLatch(MyLatch,
491 
492  /* emergency bailout if postmaster has died */
493  if (rc & WL_POSTMASTER_DEATH)
494  proc_exit(1);
495 
496  if (rc & WL_LATCH_SET)
497  {
500  }
501 
502  /* Recheck worker status. */
503  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
504 
505  /*
506  * Check whether the worker slot is no longer used, which would mean
507  * that the worker has exited, or whether the worker generation is
508  * different, meaning that a different worker has taken the slot.
509  */
510  if (!worker->in_use || worker->generation != generation)
511  {
512  LWLockRelease(LogicalRepWorkerLock);
513  return;
514  }
515 
516  /* Worker has assigned proc, so it has started. */
517  if (worker->proc)
518  break;
519  }
520 
521  /* Now terminate the worker ... */
522  kill(worker->proc->pid, SIGTERM);
523 
524  /* ... and wait for it to die. */
525  for (;;)
526  {
527  int rc;
528 
529  /* is it gone? */
530  if (!worker->proc || worker->generation != generation)
531  break;
532 
533  LWLockRelease(LogicalRepWorkerLock);
534 
535  /* Wait a bit --- we don't expect to have to wait long. */
536  rc = WaitLatch(MyLatch,
537  WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
539 
540  /* emergency bailout if postmaster has died */
541  if (rc & WL_POSTMASTER_DEATH)
542  proc_exit(1);
543 
544  if (rc & WL_LATCH_SET)
545  {
548  }
549 
550  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
551  }
552 
553  LWLockRelease(LogicalRepWorkerLock);
554 }
#define WL_TIMEOUT
Definition: latch.h:127
void proc_exit(int code)
Definition: ipc.c:99
#define kill(pid, sig)
Definition: win32_port.h:437
void ResetLatch(volatile Latch *latch)
Definition: latch.c:497
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
int WaitLatch(volatile Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:336
unsigned short uint16
Definition: c.h:295
#define WL_POSTMASTER_DEATH
Definition: latch.h:128
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:234
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
struct Latch * MyLatch
Definition: globals.c:52
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
int pid
Definition: proc.h:109
#define WL_LATCH_SET
Definition: latch.h:124

◆ logicalrep_worker_stop_at_commit()

void logicalrep_worker_stop_at_commit ( Oid  subid,
Oid  relid 
)

Definition at line 560 of file launcher.c.

References lappend(), MemoryContextSwitchTo(), palloc(), LogicalRepWorkerId::relid, LogicalRepWorkerId::subid, and TopTransactionContext.

Referenced by AlterSubscription_refresh().

561 {
562  LogicalRepWorkerId *wid;
563  MemoryContext oldctx;
564 
565  /* Make sure we store the info in context that survives until commit. */
567 
568  wid = palloc(sizeof(LogicalRepWorkerId));
569  wid->subid = subid;
570  wid->relid = relid;
571 
573 
574  MemoryContextSwitchTo(oldctx);
575 }
MemoryContext TopTransactionContext
Definition: mcxt.c:48
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
List * lappend(List *list, void *datum)
Definition: list.c:128
void * palloc(Size size)
Definition: mcxt.c:848
static List * on_commit_stop_workers
Definition: launcher.c:82

◆ logicalrep_worker_wakeup()

void logicalrep_worker_wakeup ( Oid  subid,
Oid  relid 
)

Definition at line 581 of file launcher.c.

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

Referenced by pg_attribute_noreturn().

582 {
583  LogicalRepWorker *worker;
584 
585  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
586 
587  worker = logicalrep_worker_find(subid, relid, true);
588 
589  if (worker)
591 
592  LWLockRelease(LogicalRepWorkerLock);
593 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
void logicalrep_worker_wakeup_ptr(LogicalRepWorker *worker)
Definition: launcher.c:601
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:234
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117

◆ logicalrep_worker_wakeup_ptr()

void logicalrep_worker_wakeup_ptr ( LogicalRepWorker worker)

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

602 {
603  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
604 
605  SetLatch(&worker->proc->procLatch);
606 }
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1837
Latch procLatch
Definition: proc.h:104
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
#define Assert(condition)
Definition: c.h:670

◆ logicalrep_workers_find()

List* logicalrep_workers_find ( Oid  subid,
bool  only_running 
)

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

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

◆ pg_stat_get_subscription()

Datum pg_stat_get_subscription ( PG_FUNCTION_ARGS  )

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

1015 {
1016 #define PG_STAT_GET_SUBSCRIPTION_COLS 8
1017  Oid subid = PG_ARGISNULL(0) ? InvalidOid : PG_GETARG_OID(0);
1018  int i;
1019  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
1020  TupleDesc tupdesc;
1021  Tuplestorestate *tupstore;
1022  MemoryContext per_query_ctx;
1023  MemoryContext oldcontext;
1024 
1025  /* check to see if caller supports us returning a tuplestore */
1026  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
1027  ereport(ERROR,
1028  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1029  errmsg("set-valued function called in context that cannot accept a set")));
1030  if (!(rsinfo->allowedModes & SFRM_Materialize))
1031  ereport(ERROR,
1032  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1033  errmsg("materialize mode required, but it is not " \
1034  "allowed in this context")));
1035 
1036  /* Build a tuple descriptor for our result type */
1037  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
1038  elog(ERROR, "return type must be a row type");
1039 
1040  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
1041  oldcontext = MemoryContextSwitchTo(per_query_ctx);
1042 
1043  tupstore = tuplestore_begin_heap(true, false, work_mem);
1044  rsinfo->returnMode = SFRM_Materialize;
1045  rsinfo->setResult = tupstore;
1046  rsinfo->setDesc = tupdesc;
1047 
1048  MemoryContextSwitchTo(oldcontext);
1049 
1050  /* Make sure we get consistent view of the workers. */
1051  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
1052 
1053  for (i = 0; i <= max_logical_replication_workers; i++)
1054  {
1055  /* for each row */
1057  bool nulls[PG_STAT_GET_SUBSCRIPTION_COLS];
1058  int worker_pid;
1059  LogicalRepWorker worker;
1060 
1061  memcpy(&worker, &LogicalRepCtx->workers[i],
1062  sizeof(LogicalRepWorker));
1063  if (!worker.proc || !IsBackendPid(worker.proc->pid))
1064  continue;
1065 
1066  if (OidIsValid(subid) && worker.subid != subid)
1067  continue;
1068 
1069  worker_pid = worker.proc->pid;
1070 
1071  MemSet(values, 0, sizeof(values));
1072  MemSet(nulls, 0, sizeof(nulls));
1073 
1074  values[0] = ObjectIdGetDatum(worker.subid);
1075  if (OidIsValid(worker.relid))
1076  values[1] = ObjectIdGetDatum(worker.relid);
1077  else
1078  nulls[1] = true;
1079  values[2] = Int32GetDatum(worker_pid);
1080  if (XLogRecPtrIsInvalid(worker.last_lsn))
1081  nulls[3] = true;
1082  else
1083  values[3] = LSNGetDatum(worker.last_lsn);
1084  if (worker.last_send_time == 0)
1085  nulls[4] = true;
1086  else
1087  values[4] = TimestampTzGetDatum(worker.last_send_time);
1088  if (worker.last_recv_time == 0)
1089  nulls[5] = true;
1090  else
1091  values[5] = TimestampTzGetDatum(worker.last_recv_time);
1092  if (XLogRecPtrIsInvalid(worker.reply_lsn))
1093  nulls[6] = true;
1094  else
1095  values[6] = LSNGetDatum(worker.reply_lsn);
1096  if (worker.reply_time == 0)
1097  nulls[7] = true;
1098  else
1099  values[7] = TimestampTzGetDatum(worker.reply_time);
1100 
1101  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
1102 
1103  /*
1104  * If only a single subscription was requested, and we found it,
1105  * break.
1106  */
1107  if (OidIsValid(subid))
1108  break;
1109  }
1110 
1111  LWLockRelease(LogicalRepWorkerLock);
1112 
1113  /* clean up and return the tuplestore */
1114  tuplestore_donestoring(tupstore);
1115 
1116  return (Datum) 0;
1117 }
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, Datum *values, bool *isnull)
Definition: tuplestore.c:750
#define IsA(nodeptr, _type_)
Definition: nodes.h:562
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:211
#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:71
TimestampTz last_send_time
XLogRecPtr last_lsn
int errcode(int sqlerrcode)
Definition: elog.c:575
#define LSNGetDatum(X)
Definition: pg_lsn.h:22
#define MemSet(start, val, len)
Definition: c.h:853
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:576
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
#define ObjectIdGetDatum(X)
Definition: postgres.h:513
#define ERROR
Definition: elog.h:43
#define TimestampTzGetDatum(X)
Definition: timestamp.h:32
XLogRecPtr reply_lsn
#define PG_GETARG_OID(n)
Definition: fmgr.h:240
#define ereport(elevel, rest)
Definition: elog.h:122
#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:372
#define PG_STAT_GET_SUBSCRIPTION_COLS
int work_mem
Definition: globals.c:113
#define InvalidOid
Definition: postgres_ext.h:36
int allowedModes
Definition: execnodes.h:268
SetFunctionReturnMode returnMode
Definition: execnodes.h:270
TimestampTz last_recv_time
#define PG_ARGISNULL(n)
Definition: fmgr.h:174
int max_logical_replication_workers
Definition: launcher.c:60
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:202
Tuplestorestate * setResult
Definition: execnodes.h:273
static Datum values[MAXATTR]
Definition: bootstrap.c:164
ExprContext * econtext
Definition: execnodes.h:266
#define Int32GetDatum(X)
Definition: postgres.h:485
TupleDesc setDesc
Definition: execnodes.h:274
int errmsg(const char *fmt,...)
Definition: elog.c:797
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:74
int i
bool IsBackendPid(int pid)
Definition: procarray.c:2441
#define elog
Definition: elog.h:219
int pid
Definition: proc.h:109
TimestampTz reply_time

◆ WaitForReplicationWorkerAttach()

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

Definition at line 170 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, proc_exit(), ResetLatch(), status(), WAIT_EVENT_BGWORKER_STARTUP, WaitLatch(), WL_LATCH_SET, WL_POSTMASTER_DEATH, and WL_TIMEOUT.

Referenced by logicalrep_worker_launch().

173 {
175  int rc;
176 
177  for (;;)
178  {
179  pid_t pid;
180 
182 
183  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
184 
185  /* Worker either died or has started; no need to do anything. */
186  if (!worker->in_use || worker->proc)
187  {
188  LWLockRelease(LogicalRepWorkerLock);
189  return;
190  }
191 
192  LWLockRelease(LogicalRepWorkerLock);
193 
194  /* Check if worker has died before attaching, and clean up after it. */
195  status = GetBackgroundWorkerPid(handle, &pid);
196 
197  if (status == BGWH_STOPPED)
198  {
199  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
200  /* Ensure that this was indeed the worker we waited for. */
201  if (generation == worker->generation)
203  LWLockRelease(LogicalRepWorkerLock);
204  return;
205  }
206 
207  /*
208  * We need timeout because we generally don't get notified via latch
209  * about the worker attach. But we don't expect to have to wait long.
210  */
211  rc = WaitLatch(MyLatch,
214 
215  /* emergency bailout if postmaster has died */
216  if (rc & WL_POSTMASTER_DEATH)
217  proc_exit(1);
218 
219  if (rc & WL_LATCH_SET)
220  {
223  }
224  }
225 
226  return;
227 }
#define WL_TIMEOUT
Definition: latch.h:127
void proc_exit(int code)
Definition: ipc.c:99
void ResetLatch(volatile Latch *latch)
Definition: latch.c:497
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
int WaitLatch(volatile Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:336
static void logicalrep_worker_cleanup(LogicalRepWorker *worker)
Definition: launcher.c:662
BgwHandleStatus
Definition: bgworker.h:102
#define WL_POSTMASTER_DEATH
Definition: latch.h:128
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
struct Latch * MyLatch
Definition: globals.c:52
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225
#define WL_LATCH_SET
Definition: latch.h:124
BgwHandleStatus GetBackgroundWorkerPid(BackgroundWorkerHandle *handle, pid_t *pidp)
Definition: bgworker.c:1047

◆ XactManipulatesLogicalReplicationWorkers()

bool XactManipulatesLogicalReplicationWorkers ( void  )

Definition at line 824 of file launcher.c.

References NIL.

Referenced by PrepareTransaction().

825 {
826  return (on_commit_stop_workers != NIL);
827 }
#define NIL
Definition: pg_list.h:69
static List * on_commit_stop_workers
Definition: launcher.c:82

Variable Documentation

◆ got_SIGHUP

volatile sig_atomic_t got_SIGHUP = false
static

Definition at line 91 of file launcher.c.

Referenced by ApplyLauncherMain(), and logicalrep_launcher_sighup().

◆ LogicalRepCtx

LogicalRepCtxStruct* LogicalRepCtx

Definition at line 74 of file launcher.c.

◆ max_logical_replication_workers

◆ max_sync_workers_per_subscription

int max_sync_workers_per_subscription = 2

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

Referenced by ApplyLauncherWakeupAtCommit(), and AtEOXact_ApplyLauncher().

◆ on_commit_stop_workers

List* on_commit_stop_workers = NIL
static

Definition at line 82 of file launcher.c.