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
 

Macros

#define DEFAULT_NAPTIME_PER_CYCLE   180000L
 
#define PG_STAT_GET_SUBSCRIPTION_COLS   8
 

Typedefs

typedef struct LogicalRepCtxStruct LogicalRepCtxStruct
 

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_wakeup (Oid subid, Oid relid)
 
void logicalrep_worker_wakeup_ptr (LogicalRepWorker *worker)
 
void logicalrep_worker_attach (int slot)
 
int logicalrep_sync_worker_count (Oid subid)
 
Size ApplyLauncherShmemSize (void)
 
void ApplyLauncherRegister (void)
 
void ApplyLauncherShmemInit (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 bool on_commit_launcher_wakeup = false
 

Macro Definition Documentation

◆ DEFAULT_NAPTIME_PER_CYCLE

#define DEFAULT_NAPTIME_PER_CYCLE   180000L

Definition at line 52 of file launcher.c.

Referenced by ApplyLauncherMain().

◆ PG_STAT_GET_SUBSCRIPTION_COLS

#define PG_STAT_GET_SUBSCRIPTION_COLS   8

Typedef Documentation

◆ LogicalRepCtxStruct

Function Documentation

◆ ApplyLauncherMain()

void ApplyLauncherMain ( Datum  main_arg)

Definition at line 797 of file launcher.c.

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, Assert, BackgroundWorkerInitializeConnection(), BackgroundWorkerUnblockSignals(), before_shmem_exit(), CHECK_FOR_INTERRUPTS, ConfigReloadPending, Subscription::dbid, DEBUG1, DEFAULT_NAPTIME_PER_CYCLE, die, Subscription::enabled, ereport, errmsg_internal(), get_subscription_list(), GetCurrentTimestamp(), InvalidOid, LogicalRepCtxStruct::launcher_pid, lfirst, logicalrep_launcher_onexit(), 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, SignalHandlerForConfigReload(), TimestampDifferenceExceeds(), TopMemoryContext, WAIT_EVENT_LOGICAL_LAUNCHER_MAIN, WaitLatch(), wal_retrieve_retry_interval, WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, and WL_TIMEOUT.

798 {
799  TimestampTz last_start_time = 0;
800 
801  ereport(DEBUG1,
802  (errmsg_internal("logical replication launcher started")));
803 
805 
808 
809  /* Establish signal handlers. */
811  pqsignal(SIGTERM, die);
813 
814  /*
815  * Establish connection to nailed catalogs (we only ever access
816  * pg_subscription).
817  */
819 
820  /* Enter main loop */
821  for (;;)
822  {
823  int rc;
824  List *sublist;
825  ListCell *lc;
826  MemoryContext subctx;
827  MemoryContext oldctx;
829  long wait_time = DEFAULT_NAPTIME_PER_CYCLE;
830 
832 
833  now = GetCurrentTimestamp();
834 
835  /* Limit the start retry to once a wal_retrieve_retry_interval */
836  if (TimestampDifferenceExceeds(last_start_time, now,
838  {
839  /* Use temporary context for the database list and worker info. */
841  "Logical Replication Launcher sublist",
843  oldctx = MemoryContextSwitchTo(subctx);
844 
845  /* search for subscriptions to start or stop. */
846  sublist = get_subscription_list();
847 
848  /* Start the missing workers for enabled subscriptions. */
849  foreach(lc, sublist)
850  {
851  Subscription *sub = (Subscription *) lfirst(lc);
852  LogicalRepWorker *w;
853 
854  if (!sub->enabled)
855  continue;
856 
857  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
858  w = logicalrep_worker_find(sub->oid, InvalidOid, false);
859  LWLockRelease(LogicalRepWorkerLock);
860 
861  if (w == NULL)
862  {
863  last_start_time = now;
864  wait_time = wal_retrieve_retry_interval;
865 
866  logicalrep_worker_launch(sub->dbid, sub->oid, sub->name,
867  sub->owner, InvalidOid);
868  }
869  }
870 
871  /* Switch back to original memory context. */
872  MemoryContextSwitchTo(oldctx);
873  /* Clean the temporary memory. */
874  MemoryContextDelete(subctx);
875  }
876  else
877  {
878  /*
879  * The wait in previous cycle was interrupted in less than
880  * wal_retrieve_retry_interval since last worker was started, this
881  * usually means crash of the worker, so we should retry in
882  * wal_retrieve_retry_interval again.
883  */
884  wait_time = wal_retrieve_retry_interval;
885  }
886 
887  /* Wait for more work. */
888  rc = WaitLatch(MyLatch,
890  wait_time,
892 
893  if (rc & WL_LATCH_SET)
894  {
897  }
898 
900  {
901  ConfigReloadPending = false;
903  }
904  }
905 
906  /* Not reachable */
907 }
void MemoryContextDelete(MemoryContext context)
Definition: mcxt.c:218
#define AllocSetContextCreate
Definition: memutils.h:173
#define DEBUG1
Definition: elog.h:25
int MyProcPid
Definition: globals.c:43
#define WL_TIMEOUT
Definition: latch.h:128
void ProcessConfigFile(GucContext context)
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
int64 TimestampTz
Definition: timestamp.h:39
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition: interrupt.c:56
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1711
void ResetLatch(Latch *latch)
Definition: latch.c:660
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:452
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#define ALLOCSET_DEFAULT_SIZES
Definition: memutils.h:195
#define SIGHUP
Definition: win32_port.h:159
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:632
MemoryContext TopMemoryContext
Definition: mcxt.c:48
Definition: guc.h:72
int wal_retrieve_retry_interval
Definition: xlog.c:111
void BackgroundWorkerInitializeConnection(const char *dbname, const char *username, uint32 flags)
Definition: postmaster.c:5688
#define DEFAULT_NAPTIME_PER_CYCLE
Definition: launcher.c:52
uintptr_t Datum
Definition: postgres.h:411
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
pqsigfunc pqsignal(int signum, pqsigfunc handler)
Definition: signal.c:170
static List * get_subscription_list(void)
Definition: launcher.c:88
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
void logicalrep_worker_launch(Oid dbid, Oid subid, const char *subname, Oid userid, Oid relid)
Definition: launcher.c:266
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:215
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:68
volatile sig_atomic_t ConfigReloadPending
Definition: interrupt.c:26
struct Latch * MyLatch
Definition: globals.c:57
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
Definition: pg_list.h:50
#define WL_LATCH_SET
Definition: latch.h:125
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1544
#define die(msg)
Definition: pg_test_fsync.c:97
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130
void BackgroundWorkerUnblockSignals(void)
Definition: postmaster.c:5740

◆ ApplyLauncherRegister()

void ApplyLauncherRegister ( void  )

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

703 {
704  BackgroundWorker bgw;
705 
707  return;
708 
709  memset(&bgw, 0, sizeof(bgw));
713  snprintf(bgw.bgw_library_name, BGW_MAXLEN, "postgres");
714  snprintf(bgw.bgw_function_name, BGW_MAXLEN, "ApplyLauncherMain");
716  "logical replication launcher");
718  "logical replication launcher");
719  bgw.bgw_restart_time = 5;
720  bgw.bgw_notify_pid = 0;
721  bgw.bgw_main_arg = (Datum) 0;
722 
724 }
void RegisterBackgroundWorker(BackgroundWorker *worker)
Definition: bgworker.c:889
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:411
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:54
#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:216

◆ ApplyLauncherShmemInit()

void ApplyLauncherShmemInit ( void  )

Definition at line 731 of file launcher.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

732 {
733  bool found;
734 
736  ShmemInitStruct("Logical Replication Launcher Data",
738  &found);
739 
740  if (!found)
741  {
742  int slot;
743 
745 
746  /* Initialize memory and spin locks for each worker slot. */
747  for (slot = 0; slot < max_logical_replication_workers; slot++)
748  {
749  LogicalRepWorker *worker = &LogicalRepCtx->workers[slot];
750 
751  memset(worker, 0, sizeof(LogicalRepWorker));
752  SpinLockInit(&worker->relmutex);
753  }
754  }
755 }
#define SpinLockInit(lock)
Definition: spin.h:60
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:65
void * ShmemInitStruct(const char *name, Size size, bool *foundPtr)
Definition: shmem.c:396
Size ApplyLauncherShmemSize(void)
Definition: launcher.c:683
int max_logical_replication_workers
Definition: launcher.c:54
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:68

◆ ApplyLauncherShmemSize()

Size ApplyLauncherShmemSize ( void  )

Definition at line 683 of file launcher.c.

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

Referenced by ApplyLauncherShmemInit(), and CreateSharedMemoryAndSemaphores().

684 {
685  Size size;
686 
687  /*
688  * Need the fixed struct and the array of LogicalRepWorker.
689  */
690  size = sizeof(LogicalRepCtxStruct);
691  size = MAXALIGN(size);
693  sizeof(LogicalRepWorker)));
694  return size;
695 }
Size mul_size(Size s1, Size s2)
Definition: shmem.c:519
Size add_size(Size s1, Size s2)
Definition: shmem.c:502
int max_logical_replication_workers
Definition: launcher.c:54
size_t Size
Definition: c.h:540
#define MAXALIGN(LEN)
Definition: c.h:757
struct LogicalRepCtxStruct LogicalRepCtxStruct

◆ ApplyLauncherWakeup()

static void ApplyLauncherWakeup ( void  )
static

Definition at line 787 of file launcher.c.

References kill, LogicalRepCtxStruct::launcher_pid, and SIGUSR1.

Referenced by AtEOXact_ApplyLauncher(), and logicalrep_worker_onexit().

788 {
789  if (LogicalRepCtx->launcher_pid != 0)
791 }
#define SIGUSR1
Definition: win32_port.h:171
#define kill(pid, sig)
Definition: win32_port.h:454
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:68

◆ ApplyLauncherWakeupAtCommit()

void ApplyLauncherWakeupAtCommit ( void  )

Definition at line 780 of file launcher.c.

References on_commit_launcher_wakeup.

Referenced by AlterSubscription(), and CreateSubscription().

781 {
784 }
static bool on_commit_launcher_wakeup
Definition: launcher.c:76

◆ AtEOXact_ApplyLauncher()

void AtEOXact_ApplyLauncher ( bool  isCommit)

Definition at line 761 of file launcher.c.

References ApplyLauncherWakeup(), and on_commit_launcher_wakeup.

Referenced by AbortTransaction(), and CommitTransaction().

762 {
763  if (isCommit)
764  {
767  }
768 
770 }
static bool on_commit_launcher_wakeup
Definition: launcher.c:76
static void ApplyLauncherWakeup(void)
Definition: launcher.c:787

◆ get_subscription_list()

static List* get_subscription_list ( void  )
static

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

89 {
90  List *res = NIL;
91  Relation rel;
92  TableScanDesc scan;
93  HeapTuple tup;
94  MemoryContext resultcxt;
95 
96  /* This is the context that we will allocate our output data in */
97  resultcxt = CurrentMemoryContext;
98 
99  /*
100  * Start a transaction so we can access pg_database, and get a snapshot.
101  * We don't have a use for the snapshot itself, but we're interested in
102  * the secondary effect that it sets RecentGlobalXmin. (This is critical
103  * for anything that reads heap pages, because HOT may decide to prune
104  * them even if the process doesn't attempt to modify any tuples.)
105  *
106  * FIXME: This comment is inaccurate / the code buggy. A snapshot that is
107  * not pushed/active does not reliably prevent HOT pruning (->xmin could
108  * e.g. be cleared when cache invalidations are processed).
109  */
111  (void) GetTransactionSnapshot();
112 
113  rel = table_open(SubscriptionRelationId, AccessShareLock);
114  scan = table_beginscan_catalog(rel, 0, NULL);
115 
117  {
119  Subscription *sub;
120  MemoryContext oldcxt;
121 
122  /*
123  * Allocate our results in the caller's context, not the
124  * transaction's. We do this inside the loop, and restore the original
125  * context at the end, so that leaky things like heap_getnext() are
126  * not called in a potentially long-lived context.
127  */
128  oldcxt = MemoryContextSwitchTo(resultcxt);
129 
130  sub = (Subscription *) palloc0(sizeof(Subscription));
131  sub->oid = subform->oid;
132  sub->dbid = subform->subdbid;
133  sub->owner = subform->subowner;
134  sub->enabled = subform->subenabled;
135  sub->name = pstrdup(NameStr(subform->subname));
136  /* We don't fill fields we are not interested in. */
137 
138  res = lappend(res, sub);
139  MemoryContextSwitchTo(oldcxt);
140  }
141 
142  table_endscan(scan);
144 
146 
147  return res;
148 }
#define NIL
Definition: pg_list.h:65
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
#define GETSTRUCT(TUP)
Definition: htup_details.h:654
TableScanDesc table_beginscan_catalog(Relation relation, int nkeys, struct ScanKeyData *key)
Definition: tableam.c:112
char * pstrdup(const char *in)
Definition: mcxt.c:1299
void CommitTransactionCommand(void)
Definition: xact.c:2939
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:250
HeapTuple heap_getnext(TableScanDesc sscan, ScanDirection direction)
Definition: heapam.c:1340
MemoryContext CurrentMemoryContext
Definition: mcxt.c:42
List * lappend(List *list, void *datum)
Definition: list.c:336
void * palloc0(Size size)
Definition: mcxt.c:1093
#define HeapTupleIsValid(tuple)
Definition: htup.h:78
void StartTransactionCommand(void)
Definition: xact.c:2838
static void table_endscan(TableScanDesc scan)
Definition: tableam.h:991
#define NameStr(name)
Definition: c.h:681
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
Definition: pg_list.h:50

◆ IsLogicalLauncher()

bool IsLogicalLauncher ( void  )

Definition at line 913 of file launcher.c.

References LogicalRepCtxStruct::launcher_pid, and MyProcPid.

Referenced by ProcessInterrupts().

914 {
916 }
int MyProcPid
Definition: globals.c:43
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:68

◆ logicalrep_launcher_onexit()

static void logicalrep_launcher_onexit ( int  code,
Datum  arg 
)
static

Definition at line 632 of file launcher.c.

References LogicalRepCtxStruct::launcher_pid.

Referenced by ApplyLauncherMain().

633 {
635 }
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:68

◆ logicalrep_sync_worker_count()

int logicalrep_sync_worker_count ( Oid  subid)

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

660 {
661  int i;
662  int res = 0;
663 
664  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
665 
666  /* Search for attached worker for a given subscription id. */
667  for (i = 0; i < max_logical_replication_workers; i++)
668  {
670 
671  if (w->subid == subid && OidIsValid(w->relid))
672  res++;
673  }
674 
675  return res;
676 }
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1919
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:65
#define OidIsValid(objectId)
Definition: c.h:710
#define Assert(condition)
Definition: c.h:804
int max_logical_replication_workers
Definition: launcher.c:54
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:68
int i

◆ logicalrep_worker_attach()

void logicalrep_worker_attach ( int  slot)

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

565 {
566  /* Block concurrent access. */
567  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
568 
569  Assert(slot >= 0 && slot < max_logical_replication_workers);
571 
573  {
574  LWLockRelease(LogicalRepWorkerLock);
575  ereport(ERROR,
576  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
577  errmsg("logical replication worker slot %d is empty, cannot attach",
578  slot)));
579  }
580 
582  {
583  LWLockRelease(LogicalRepWorkerLock);
584  ereport(ERROR,
585  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
586  errmsg("logical replication worker slot %d is already used by "
587  "another worker, cannot attach", slot)));
588  }
589 
592 
593  LWLockRelease(LogicalRepWorkerLock);
594 }
PGPROC * MyProc
Definition: proc.c:68
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:65
int errcode(int sqlerrcode)
Definition: elog.c:698
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
#define ERROR
Definition: elog.h:46
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:333
static void logicalrep_worker_onexit(int code, Datum arg)
Definition: launcher.c:643
uintptr_t Datum
Definition: postgres.h:411
#define ereport(elevel,...)
Definition: elog.h:157
#define Assert(condition)
Definition: c.h:804
int max_logical_replication_workers
Definition: launcher.c:54
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
int errmsg(const char *fmt,...)
Definition: elog.c:909
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:68

◆ logicalrep_worker_cleanup()

static void logicalrep_worker_cleanup ( LogicalRepWorker worker)
static

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

615 {
616  Assert(LWLockHeldByMeInMode(LogicalRepWorkerLock, LW_EXCLUSIVE));
617 
618  worker->in_use = false;
619  worker->proc = NULL;
620  worker->dbid = InvalidOid;
621  worker->userid = InvalidOid;
622  worker->subid = InvalidOid;
623  worker->relid = InvalidOid;
624 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1937
#define InvalidOid
Definition: postgres_ext.h:36
#define Assert(condition)
Definition: c.h:804

◆ logicalrep_worker_detach()

static void logicalrep_worker_detach ( void  )
static

Definition at line 600 of file launcher.c.

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

Referenced by logicalrep_worker_onexit().

601 {
602  /* Block concurrent access. */
603  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
604 
606 
607  LWLockRelease(LogicalRepWorkerLock);
608 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
static void logicalrep_worker_cleanup(LogicalRepWorker *worker)
Definition: launcher.c:614
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199

◆ logicalrep_worker_find()

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

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

216 {
217  int i;
218  LogicalRepWorker *res = NULL;
219 
220  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
221 
222  /* Search for attached worker for a given subscription id. */
223  for (i = 0; i < max_logical_replication_workers; i++)
224  {
226 
227  if (w->in_use && w->subid == subid && w->relid == relid &&
228  (!only_running || w->proc))
229  {
230  res = w;
231  break;
232  }
233  }
234 
235  return res;
236 }
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1919
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:65
#define Assert(condition)
Definition: c.h:804
int max_logical_replication_workers
Definition: launcher.c:54
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:68
int i

◆ logicalrep_worker_launch()

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

Definition at line 266 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(), errmsg_internal(), 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().

268 {
269  BackgroundWorker bgw;
270  BackgroundWorkerHandle *bgw_handle;
271  uint16 generation;
272  int i;
273  int slot = 0;
274  LogicalRepWorker *worker = NULL;
275  int nsyncworkers;
277 
278  ereport(DEBUG1,
279  (errmsg_internal("starting logical replication worker for subscription \"%s\"",
280  subname)));
281 
282  /* Report this after the initial starting message for consistency. */
283  if (max_replication_slots == 0)
284  ereport(ERROR,
285  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
286  errmsg("cannot start logical replication workers when max_replication_slots = 0")));
287 
288  /*
289  * We need to do the modification of the shared memory under lock so that
290  * we have consistent view.
291  */
292  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
293 
294 retry:
295  /* Find unused worker slot. */
296  for (i = 0; i < max_logical_replication_workers; i++)
297  {
299 
300  if (!w->in_use)
301  {
302  worker = w;
303  slot = i;
304  break;
305  }
306  }
307 
308  nsyncworkers = logicalrep_sync_worker_count(subid);
309 
310  now = GetCurrentTimestamp();
311 
312  /*
313  * If we didn't find a free slot, try to do garbage collection. The
314  * reason we do this is because if some worker failed to start up and its
315  * parent has crashed while waiting, the in_use state was never cleared.
316  */
317  if (worker == NULL || nsyncworkers >= max_sync_workers_per_subscription)
318  {
319  bool did_cleanup = false;
320 
321  for (i = 0; i < max_logical_replication_workers; i++)
322  {
324 
325  /*
326  * If the worker was marked in use but didn't manage to attach in
327  * time, clean it up.
328  */
329  if (w->in_use && !w->proc &&
332  {
333  elog(WARNING,
334  "logical replication worker for subscription %u took too long to start; canceled",
335  w->subid);
336 
338  did_cleanup = true;
339  }
340  }
341 
342  if (did_cleanup)
343  goto retry;
344  }
345 
346  /*
347  * If we reached the sync worker limit per subscription, just exit
348  * silently as we might get here because of an otherwise harmless race
349  * condition.
350  */
351  if (nsyncworkers >= max_sync_workers_per_subscription)
352  {
353  LWLockRelease(LogicalRepWorkerLock);
354  return;
355  }
356 
357  /*
358  * However if there are no more free worker slots, inform user about it
359  * before exiting.
360  */
361  if (worker == NULL)
362  {
363  LWLockRelease(LogicalRepWorkerLock);
365  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
366  errmsg("out of logical replication worker slots"),
367  errhint("You might need to increase max_logical_replication_workers.")));
368  return;
369  }
370 
371  /* Prepare the worker slot. */
372  worker->launch_time = now;
373  worker->in_use = true;
374  worker->generation++;
375  worker->proc = NULL;
376  worker->dbid = dbid;
377  worker->userid = userid;
378  worker->subid = subid;
379  worker->relid = relid;
380  worker->relstate = SUBREL_STATE_UNKNOWN;
382  worker->last_lsn = InvalidXLogRecPtr;
385  worker->reply_lsn = InvalidXLogRecPtr;
386  TIMESTAMP_NOBEGIN(worker->reply_time);
387 
388  /* Before releasing lock, remember generation for future identification. */
389  generation = worker->generation;
390 
391  LWLockRelease(LogicalRepWorkerLock);
392 
393  /* Register the new dynamic worker. */
394  memset(&bgw, 0, sizeof(bgw));
398  snprintf(bgw.bgw_library_name, BGW_MAXLEN, "postgres");
399  snprintf(bgw.bgw_function_name, BGW_MAXLEN, "ApplyWorkerMain");
400  if (OidIsValid(relid))
402  "logical replication worker for subscription %u sync %u", subid, relid);
403  else
405  "logical replication worker for subscription %u", subid);
406  snprintf(bgw.bgw_type, BGW_MAXLEN, "logical replication worker");
407 
410  bgw.bgw_main_arg = Int32GetDatum(slot);
411 
412  if (!RegisterDynamicBackgroundWorker(&bgw, &bgw_handle))
413  {
414  /* Failed to start worker, so clean up the worker slot. */
415  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
416  Assert(generation == worker->generation);
418  LWLockRelease(LogicalRepWorkerLock);
419 
421  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
422  errmsg("out of background worker slots"),
423  errhint("You might need to increase max_worker_processes.")));
424  return;
425  }
426 
427  /* Now wait until it attaches. */
428  WaitForReplicationWorkerAttach(worker, generation, bgw_handle);
429 }
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define DEBUG1
Definition: elog.h:25
int MyProcPid
Definition: globals.c:43
int errhint(const char *fmt,...)
Definition: elog.c:1156
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1580
int64 TimestampTz
Definition: timestamp.h:39
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:65
TimestampTz last_send_time
XLogRecPtr last_lsn
int bgw_restart_time
Definition: bgworker.h:94
int errcode(int sqlerrcode)
Definition: elog.c:698
NameData subname
#define BGWORKER_SHMEM_ACCESS
Definition: bgworker.h:52
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1711
#define OidIsValid(objectId)
Definition: c.h:710
char bgw_function_name[BGW_MAXLEN]
Definition: bgworker.h:96
int wal_receiver_timeout
Definition: walreceiver.c:90
XLogRecPtr relstate_lsn
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
Datum bgw_main_arg
Definition: bgworker.h:97
unsigned short uint16
Definition: c.h:440
#define ERROR
Definition: elog.h:46
int max_sync_workers_per_subscription
Definition: launcher.c:55
XLogRecPtr reply_lsn
static void logicalrep_worker_cleanup(LogicalRepWorker *worker)
Definition: launcher.c:614
#define BGW_NEVER_RESTART
Definition: bgworker.h:84
#define TIMESTAMP_NOBEGIN(j)
Definition: timestamp.h:112
#define WARNING
Definition: elog.h:40
int logicalrep_sync_worker_count(Oid subid)
Definition: launcher.c:659
static void WaitForReplicationWorkerAttach(LogicalRepWorker *worker, uint16 generation, BackgroundWorkerHandle *handle)
Definition: launcher.c:157
#define ereport(elevel,...)
Definition: elog.h:157
TimestampTz launch_time
int errmsg_internal(const char *fmt,...)
Definition: elog.c:996
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:804
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
int max_logical_replication_workers
Definition: launcher.c:54
#define BGW_MAXLEN
Definition: bgworker.h:85
BgWorkerStartTime bgw_start_time
Definition: bgworker.h:93
bool RegisterDynamicBackgroundWorker(BackgroundWorker *worker, BackgroundWorkerHandle **handle)
Definition: bgworker.c:973
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
#define Int32GetDatum(X)
Definition: postgres.h:523
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:91
int errmsg(const char *fmt,...)
Definition: elog.c:909
pid_t bgw_notify_pid
Definition: bgworker.h:99
#define elog(elevel,...)
Definition: elog.h:232
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:68
int i
char bgw_library_name[BGW_MAXLEN]
Definition: bgworker.h:95
#define snprintf
Definition: port.h:216
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1544
TimestampTz reply_time

◆ logicalrep_worker_onexit()

static void logicalrep_worker_onexit ( int  code,
Datum  arg 
)
static

Definition at line 643 of file launcher.c.

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

Referenced by logicalrep_worker_attach().

644 {
645  /* Disconnect gracefully from the remote side. */
648 
650 
652 }
WalReceiverConn * LogRepWorkerWalRcvConn
Definition: worker.c:244
static void logicalrep_worker_detach(void)
Definition: launcher.c:600
#define walrcv_disconnect(conn)
Definition: walreceiver.h:432
static void ApplyLauncherWakeup(void)
Definition: launcher.c:787

◆ logicalrep_worker_stop()

void logicalrep_worker_stop ( Oid  subid,
Oid  relid 
)

Definition at line 436 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 AlterSubscription_refresh(), and DropSubscription().

437 {
438  LogicalRepWorker *worker;
439  uint16 generation;
440 
441  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
442 
443  worker = logicalrep_worker_find(subid, relid, false);
444 
445  /* No worker, nothing to do. */
446  if (!worker)
447  {
448  LWLockRelease(LogicalRepWorkerLock);
449  return;
450  }
451 
452  /*
453  * Remember which generation was our worker so we can check if what we see
454  * is still the same one.
455  */
456  generation = worker->generation;
457 
458  /*
459  * If we found a worker but it does not have proc set then it is still
460  * starting up; wait for it to finish starting and then kill it.
461  */
462  while (worker->in_use && !worker->proc)
463  {
464  int rc;
465 
466  LWLockRelease(LogicalRepWorkerLock);
467 
468  /* Wait a bit --- we don't expect to have to wait long. */
469  rc = WaitLatch(MyLatch,
472 
473  if (rc & WL_LATCH_SET)
474  {
477  }
478 
479  /* Recheck worker status. */
480  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
481 
482  /*
483  * Check whether the worker slot is no longer used, which would mean
484  * that the worker has exited, or whether the worker generation is
485  * different, meaning that a different worker has taken the slot.
486  */
487  if (!worker->in_use || worker->generation != generation)
488  {
489  LWLockRelease(LogicalRepWorkerLock);
490  return;
491  }
492 
493  /* Worker has assigned proc, so it has started. */
494  if (worker->proc)
495  break;
496  }
497 
498  /* Now terminate the worker ... */
499  kill(worker->proc->pid, SIGTERM);
500 
501  /* ... and wait for it to die. */
502  for (;;)
503  {
504  int rc;
505 
506  /* is it gone? */
507  if (!worker->proc || worker->generation != generation)
508  break;
509 
510  LWLockRelease(LogicalRepWorkerLock);
511 
512  /* Wait a bit --- we don't expect to have to wait long. */
513  rc = WaitLatch(MyLatch,
514  WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
516 
517  if (rc & WL_LATCH_SET)
518  {
521  }
522 
523  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
524  }
525 
526  LWLockRelease(LogicalRepWorkerLock);
527 }
#define WL_TIMEOUT
Definition: latch.h:128
#define kill(pid, sig)
Definition: win32_port.h:454
void ResetLatch(Latch *latch)
Definition: latch.c:660
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:452
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
unsigned short uint16
Definition: c.h:440
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:215
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
struct Latch * MyLatch
Definition: globals.c:57
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
int pid
Definition: proc.h:146
#define WL_LATCH_SET
Definition: latch.h:125
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130

◆ logicalrep_worker_wakeup()

void logicalrep_worker_wakeup ( Oid  subid,
Oid  relid 
)

Definition at line 533 of file launcher.c.

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

Referenced by pg_attribute_noreturn().

534 {
535  LogicalRepWorker *worker;
536 
537  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
538 
539  worker = logicalrep_worker_find(subid, relid, true);
540 
541  if (worker)
543 
544  LWLockRelease(LogicalRepWorkerLock);
545 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
void logicalrep_worker_wakeup_ptr(LogicalRepWorker *worker)
Definition: launcher.c:553
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:215
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199

◆ logicalrep_worker_wakeup_ptr()

void logicalrep_worker_wakeup_ptr ( LogicalRepWorker worker)

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

554 {
555  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
556 
557  SetLatch(&worker->proc->procLatch);
558 }
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1919
void SetLatch(Latch *latch)
Definition: latch.c:567
Latch procLatch
Definition: proc.h:130
#define Assert(condition)
Definition: c.h:804

◆ logicalrep_workers_find()

List* logicalrep_workers_find ( Oid  subid,
bool  only_running 
)

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

244 {
245  int i;
246  List *res = NIL;
247 
248  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
249 
250  /* Search for attached worker for a given subscription id. */
251  for (i = 0; i < max_logical_replication_workers; i++)
252  {
254 
255  if (w->in_use && w->subid == subid && (!only_running || w->proc))
256  res = lappend(res, w);
257  }
258 
259  return res;
260 }
#define NIL
Definition: pg_list.h:65
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1919
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:65
List * lappend(List *list, void *datum)
Definition: list.c:336
#define Assert(condition)
Definition: c.h:804
int max_logical_replication_workers
Definition: launcher.c:54
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:68
int i
Definition: pg_list.h:50

◆ pg_stat_get_subscription()

Datum pg_stat_get_subscription ( PG_FUNCTION_ARGS  )

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

923 {
924 #define PG_STAT_GET_SUBSCRIPTION_COLS 8
925  Oid subid = PG_ARGISNULL(0) ? InvalidOid : PG_GETARG_OID(0);
926  int i;
927  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
928  TupleDesc tupdesc;
929  Tuplestorestate *tupstore;
930  MemoryContext per_query_ctx;
931  MemoryContext oldcontext;
932 
933  /* check to see if caller supports us returning a tuplestore */
934  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
935  ereport(ERROR,
936  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
937  errmsg("set-valued function called in context that cannot accept a set")));
938  if (!(rsinfo->allowedModes & SFRM_Materialize))
939  ereport(ERROR,
940  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
941  errmsg("materialize mode required, but it is not allowed in this context")));
942 
943  /* Build a tuple descriptor for our result type */
944  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
945  elog(ERROR, "return type must be a row type");
946 
947  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
948  oldcontext = MemoryContextSwitchTo(per_query_ctx);
949 
950  tupstore = tuplestore_begin_heap(true, false, work_mem);
951  rsinfo->returnMode = SFRM_Materialize;
952  rsinfo->setResult = tupstore;
953  rsinfo->setDesc = tupdesc;
954 
955  MemoryContextSwitchTo(oldcontext);
956 
957  /* Make sure we get consistent view of the workers. */
958  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
959 
960  for (i = 0; i <= max_logical_replication_workers; i++)
961  {
962  /* for each row */
964  bool nulls[PG_STAT_GET_SUBSCRIPTION_COLS];
965  int worker_pid;
966  LogicalRepWorker worker;
967 
968  memcpy(&worker, &LogicalRepCtx->workers[i],
969  sizeof(LogicalRepWorker));
970  if (!worker.proc || !IsBackendPid(worker.proc->pid))
971  continue;
972 
973  if (OidIsValid(subid) && worker.subid != subid)
974  continue;
975 
976  worker_pid = worker.proc->pid;
977 
978  MemSet(values, 0, sizeof(values));
979  MemSet(nulls, 0, sizeof(nulls));
980 
981  values[0] = ObjectIdGetDatum(worker.subid);
982  if (OidIsValid(worker.relid))
983  values[1] = ObjectIdGetDatum(worker.relid);
984  else
985  nulls[1] = true;
986  values[2] = Int32GetDatum(worker_pid);
987  if (XLogRecPtrIsInvalid(worker.last_lsn))
988  nulls[3] = true;
989  else
990  values[3] = LSNGetDatum(worker.last_lsn);
991  if (worker.last_send_time == 0)
992  nulls[4] = true;
993  else
994  values[4] = TimestampTzGetDatum(worker.last_send_time);
995  if (worker.last_recv_time == 0)
996  nulls[5] = true;
997  else
998  values[5] = TimestampTzGetDatum(worker.last_recv_time);
999  if (XLogRecPtrIsInvalid(worker.reply_lsn))
1000  nulls[6] = true;
1001  else
1002  values[6] = LSNGetDatum(worker.reply_lsn);
1003  if (worker.reply_time == 0)
1004  nulls[7] = true;
1005  else
1006  values[7] = TimestampTzGetDatum(worker.reply_time);
1007 
1008  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
1009 
1010  /*
1011  * If only a single subscription was requested, and we found it,
1012  * break.
1013  */
1014  if (OidIsValid(subid))
1015  break;
1016  }
1017 
1018  LWLockRelease(LogicalRepWorkerLock);
1019 
1020  /* clean up and return the tuplestore */
1021  tuplestore_donestoring(tupstore);
1022 
1023  return (Datum) 0;
1024 }
void tuplestore_putvalues(Tuplestorestate *state, TupleDesc tdesc, Datum *values, bool *isnull)
Definition: tuplestore.c:750
#define IsA(nodeptr, _type_)
Definition: nodes.h:590
TypeFuncClass get_call_result_type(FunctionCallInfo fcinfo, Oid *resultTypeId, TupleDesc *resultTupleDesc)
Definition: funcapi.c:207
#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:65
TimestampTz last_send_time
XLogRecPtr last_lsn
int errcode(int sqlerrcode)
Definition: elog.c:698
#define LSNGetDatum(X)
Definition: pg_lsn.h:22
#define MemSet(start, val, len)
Definition: c.h:1008
unsigned int Oid
Definition: postgres_ext.h:31
#define OidIsValid(objectId)
Definition: c.h:710
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
#define ObjectIdGetDatum(X)
Definition: postgres.h:551
#define ERROR
Definition: elog.h:46
#define TimestampTzGetDatum(X)
Definition: timestamp.h:32
XLogRecPtr reply_lsn
#define PG_GETARG_OID(n)
Definition: fmgr.h:275
#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:411
#define PG_STAT_GET_SUBSCRIPTION_COLS
int work_mem
Definition: globals.c:124
#define InvalidOid
Definition: postgres_ext.h:36
#define ereport(elevel,...)
Definition: elog.h:157
int allowedModes
Definition: execnodes.h:305
SetFunctionReturnMode returnMode
Definition: execnodes.h:307
TimestampTz last_recv_time
#define PG_ARGISNULL(n)
Definition: fmgr.h:209
int max_logical_replication_workers
Definition: launcher.c:54
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
MemoryContext ecxt_per_query_memory
Definition: execnodes.h:233
Tuplestorestate * setResult
Definition: execnodes.h:310
static Datum values[MAXATTR]
Definition: bootstrap.c:166
ExprContext * econtext
Definition: execnodes.h:303
#define Int32GetDatum(X)
Definition: postgres.h:523
TupleDesc setDesc
Definition: execnodes.h:311
int errmsg(const char *fmt,...)
Definition: elog.c:909
#define elog(elevel,...)
Definition: elog.h:232
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:68
int i
bool IsBackendPid(int pid)
Definition: procarray.c:3228
int pid
Definition: proc.h:146
TimestampTz reply_time

◆ WaitForReplicationWorkerAttach()

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

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

160 {
162  int rc;
163 
164  for (;;)
165  {
166  pid_t pid;
167 
169 
170  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
171 
172  /* Worker either died or has started; no need to do anything. */
173  if (!worker->in_use || worker->proc)
174  {
175  LWLockRelease(LogicalRepWorkerLock);
176  return;
177  }
178 
179  LWLockRelease(LogicalRepWorkerLock);
180 
181  /* Check if worker has died before attaching, and clean up after it. */
182  status = GetBackgroundWorkerPid(handle, &pid);
183 
184  if (status == BGWH_STOPPED)
185  {
186  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
187  /* Ensure that this was indeed the worker we waited for. */
188  if (generation == worker->generation)
190  LWLockRelease(LogicalRepWorkerLock);
191  return;
192  }
193 
194  /*
195  * We need timeout because we generally don't get notified via latch
196  * about the worker attach. But we don't expect to have to wait long.
197  */
198  rc = WaitLatch(MyLatch,
201 
202  if (rc & WL_LATCH_SET)
203  {
206  }
207  }
208 }
#define WL_TIMEOUT
Definition: latch.h:128
void ResetLatch(Latch *latch)
Definition: latch.c:660
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:452
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1803
static void logicalrep_worker_cleanup(LogicalRepWorker *worker)
Definition: launcher.c:614
BgwHandleStatus
Definition: bgworker.h:102
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1199
struct Latch * MyLatch
Definition: globals.c:57
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:120
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:227
#define WL_LATCH_SET
Definition: latch.h:125
BgwHandleStatus GetBackgroundWorkerPid(BackgroundWorkerHandle *handle, pid_t *pidp)
Definition: bgworker.c:1085
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130

Variable Documentation

◆ LogicalRepCtx

LogicalRepCtxStruct* LogicalRepCtx

Definition at line 68 of file launcher.c.

◆ max_logical_replication_workers

◆ max_sync_workers_per_subscription

int max_sync_workers_per_subscription = 2

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

Referenced by ApplyLauncherWakeupAtCommit(), and AtEOXact_ApplyLauncher().