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_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

◆ LogicalRepWorkerId

Function Documentation

◆ ApplyLauncherMain()

void ApplyLauncherMain ( Datum  main_arg)

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

804 {
805  TimestampTz last_start_time = 0;
806 
807  ereport(DEBUG1,
808  (errmsg_internal("logical replication launcher started")));
809 
811 
814 
815  /* Establish signal handlers. */
817  pqsignal(SIGTERM, die);
819 
820  /*
821  * Establish connection to nailed catalogs (we only ever access
822  * pg_subscription).
823  */
825 
826  /* Enter main loop */
827  for (;;)
828  {
829  int rc;
830  List *sublist;
831  ListCell *lc;
832  MemoryContext subctx;
833  MemoryContext oldctx;
835  long wait_time = DEFAULT_NAPTIME_PER_CYCLE;
836 
838 
839  now = GetCurrentTimestamp();
840 
841  /* Limit the start retry to once a wal_retrieve_retry_interval */
842  if (TimestampDifferenceExceeds(last_start_time, now,
844  {
845  /* Use temporary context for the database list and worker info. */
847  "Logical Replication Launcher sublist",
849  oldctx = MemoryContextSwitchTo(subctx);
850 
851  /* search for subscriptions to start or stop. */
852  sublist = get_subscription_list();
853 
854  /* Start the missing workers for enabled subscriptions. */
855  foreach(lc, sublist)
856  {
857  Subscription *sub = (Subscription *) lfirst(lc);
858  LogicalRepWorker *w;
859 
860  if (!sub->enabled)
861  continue;
862 
863  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
864  w = logicalrep_worker_find(sub->oid, InvalidOid, false);
865  LWLockRelease(LogicalRepWorkerLock);
866 
867  if (w == NULL)
868  {
869  last_start_time = now;
870  wait_time = wal_retrieve_retry_interval;
871 
872  logicalrep_worker_launch(sub->dbid, sub->oid, sub->name,
873  sub->owner, InvalidOid);
874  }
875  }
876 
877  /* Switch back to original memory context. */
878  MemoryContextSwitchTo(oldctx);
879  /* Clean the temporary memory. */
880  MemoryContextDelete(subctx);
881  }
882  else
883  {
884  /*
885  * The wait in previous cycle was interrupted in less than
886  * wal_retrieve_retry_interval since last worker was started, this
887  * usually means crash of the worker, so we should retry in
888  * wal_retrieve_retry_interval again.
889  */
890  wait_time = wal_retrieve_retry_interval;
891  }
892 
893  /* Wait for more work. */
894  rc = WaitLatch(MyLatch,
896  wait_time,
898 
899  if (rc & WL_LATCH_SET)
900  {
903  }
904 
906  {
907  ConfigReloadPending = false;
909  }
910  }
911 
912  /* Not reachable */
913 }
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:1805
#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:638
MemoryContext TopMemoryContext
Definition: mcxt.c:48
Definition: guc.h:72
int wal_retrieve_retry_interval
Definition: xlog.c:112
void BackgroundWorkerInitializeConnection(const char *dbname, const char *username, uint32 flags)
Definition: postmaster.c:5666
#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:94
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:272
#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:221
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1203
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:102
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:5718

◆ ApplyLauncherRegister()

void ApplyLauncherRegister ( void  )

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

709 {
710  BackgroundWorker bgw;
711 
713  return;
714 
715  memset(&bgw, 0, sizeof(bgw));
719  snprintf(bgw.bgw_library_name, BGW_MAXLEN, "postgres");
720  snprintf(bgw.bgw_function_name, BGW_MAXLEN, "ApplyLauncherMain");
722  "logical replication launcher");
724  "logical replication launcher");
725  bgw.bgw_restart_time = 5;
726  bgw.bgw_notify_pid = 0;
727  bgw.bgw_main_arg = (Datum) 0;
728 
730 }
void RegisterBackgroundWorker(BackgroundWorker *worker)
Definition: bgworker.c:878
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 737 of file launcher.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

738 {
739  bool found;
740 
742  ShmemInitStruct("Logical Replication Launcher Data",
744  &found);
745 
746  if (!found)
747  {
748  int slot;
749 
751 
752  /* Initialize memory and spin locks for each worker slot. */
753  for (slot = 0; slot < max_logical_replication_workers; slot++)
754  {
755  LogicalRepWorker *worker = &LogicalRepCtx->workers[slot];
756 
757  memset(worker, 0, sizeof(LogicalRepWorker));
758  SpinLockInit(&worker->relmutex);
759  }
760  }
761 }
#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:689
int max_logical_replication_workers
Definition: launcher.c:54
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:68

◆ ApplyLauncherShmemSize()

Size ApplyLauncherShmemSize ( void  )

Definition at line 689 of file launcher.c.

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

Referenced by ApplyLauncherShmemInit(), and CreateSharedMemoryAndSemaphores().

690 {
691  Size size;
692 
693  /*
694  * Need the fixed struct and the array of LogicalRepWorker.
695  */
696  size = sizeof(LogicalRepCtxStruct);
697  size = MAXALIGN(size);
699  sizeof(LogicalRepWorker)));
700  return size;
701 }
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 793 of file launcher.c.

References kill, LogicalRepCtxStruct::launcher_pid, and SIGUSR1.

Referenced by AtEOXact_ApplyLauncher(), and logicalrep_worker_onexit().

794 {
795  if (LogicalRepCtx->launcher_pid != 0)
797 }
#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 786 of file launcher.c.

References on_commit_launcher_wakeup.

Referenced by AlterSubscription(), and CreateSubscription().

787 {
790 }
static bool on_commit_launcher_wakeup
Definition: launcher.c:82

◆ AtEOXact_ApplyLauncher()

void AtEOXact_ApplyLauncher ( bool  isCommit)

Definition at line 767 of file launcher.c.

References ApplyLauncherWakeup(), and on_commit_launcher_wakeup.

Referenced by AbortTransaction(), and CommitTransaction().

768 {
769  if (isCommit)
770  {
773  }
774 
776 }
static bool on_commit_launcher_wakeup
Definition: launcher.c:82
static void ApplyLauncherWakeup(void)
Definition: launcher.c:793

◆ get_subscription_list()

static List* get_subscription_list ( void  )
static

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

95 {
96  List *res = NIL;
97  Relation rel;
98  TableScanDesc scan;
99  HeapTuple tup;
100  MemoryContext resultcxt;
101 
102  /* This is the context that we will allocate our output data in */
103  resultcxt = CurrentMemoryContext;
104 
105  /*
106  * Start a transaction so we can access pg_database, and get a snapshot.
107  * We don't have a use for the snapshot itself, but we're interested in
108  * the secondary effect that it sets RecentGlobalXmin. (This is critical
109  * for anything that reads heap pages, because HOT may decide to prune
110  * them even if the process doesn't attempt to modify any tuples.)
111  *
112  * FIXME: This comment is inaccurate / the code buggy. A snapshot that is
113  * not pushed/active does not reliably prevent HOT pruning (->xmin could
114  * e.g. be cleared when cache invalidations are processed).
115  */
117  (void) GetTransactionSnapshot();
118 
119  rel = table_open(SubscriptionRelationId, AccessShareLock);
120  scan = table_beginscan_catalog(rel, 0, NULL);
121 
123  {
125  Subscription *sub;
126  MemoryContext oldcxt;
127 
128  /*
129  * Allocate our results in the caller's context, not the
130  * transaction's. We do this inside the loop, and restore the original
131  * context at the end, so that leaky things like heap_getnext() are
132  * not called in a potentially long-lived context.
133  */
134  oldcxt = MemoryContextSwitchTo(resultcxt);
135 
136  sub = (Subscription *) palloc0(sizeof(Subscription));
137  sub->oid = subform->oid;
138  sub->dbid = subform->subdbid;
139  sub->owner = subform->subowner;
140  sub->enabled = subform->subenabled;
141  sub->name = pstrdup(NameStr(subform->subname));
142  /* We don't fill fields we are not interested in. */
143 
144  res = lappend(res, sub);
145  MemoryContextSwitchTo(oldcxt);
146  }
147 
148  table_endscan(scan);
150 
152 
153  return res;
154 }
#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 919 of file launcher.c.

References LogicalRepCtxStruct::launcher_pid, and MyProcPid.

Referenced by ProcessInterrupts().

920 {
922 }
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 638 of file launcher.c.

References LogicalRepCtxStruct::launcher_pid.

Referenced by ApplyLauncherMain().

639 {
641 }
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:68

◆ logicalrep_sync_worker_count()

int logicalrep_sync_worker_count ( Oid  subid)

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

666 {
667  int i;
668  int res = 0;
669 
670  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
671 
672  /* Search for attached worker for a given subscription id. */
673  for (i = 0; i < max_logical_replication_workers; i++)
674  {
676 
677  if (w->subid == subid && OidIsValid(w->relid))
678  res++;
679  }
680 
681  return res;
682 }
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1920
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 570 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().

571 {
572  /* Block concurrent access. */
573  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
574 
575  Assert(slot >= 0 && slot < max_logical_replication_workers);
577 
579  {
580  LWLockRelease(LogicalRepWorkerLock);
581  ereport(ERROR,
582  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
583  errmsg("logical replication worker slot %d is empty, cannot attach",
584  slot)));
585  }
586 
588  {
589  LWLockRelease(LogicalRepWorkerLock);
590  ereport(ERROR,
591  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
592  errmsg("logical replication worker slot %d is already used by "
593  "another worker, cannot attach", slot)));
594  }
595 
598 
599  LWLockRelease(LogicalRepWorkerLock);
600 }
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:1805
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:649
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:1203
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 620 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().

621 {
622  Assert(LWLockHeldByMeInMode(LogicalRepWorkerLock, LW_EXCLUSIVE));
623 
624  worker->in_use = false;
625  worker->proc = NULL;
626  worker->dbid = InvalidOid;
627  worker->userid = InvalidOid;
628  worker->subid = InvalidOid;
629  worker->relid = InvalidOid;
630 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1938
#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 606 of file launcher.c.

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

Referenced by logicalrep_worker_onexit().

607 {
608  /* Block concurrent access. */
609  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
610 
612 
613  LWLockRelease(LogicalRepWorkerLock);
614 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1805
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
static void logicalrep_worker_cleanup(LogicalRepWorker *worker)
Definition: launcher.c:620
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1203

◆ logicalrep_worker_find()

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

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

222 {
223  int i;
224  LogicalRepWorker *res = NULL;
225 
226  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
227 
228  /* Search for attached worker for a given subscription id. */
229  for (i = 0; i < max_logical_replication_workers; i++)
230  {
232 
233  if (w->in_use && w->subid == subid && w->relid == relid &&
234  (!only_running || w->proc))
235  {
236  res = w;
237  break;
238  }
239  }
240 
241  return res;
242 }
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1920
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 272 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().

274 {
275  BackgroundWorker bgw;
276  BackgroundWorkerHandle *bgw_handle;
277  uint16 generation;
278  int i;
279  int slot = 0;
280  LogicalRepWorker *worker = NULL;
281  int nsyncworkers;
283 
284  ereport(DEBUG1,
285  (errmsg_internal("starting logical replication worker for subscription \"%s\"",
286  subname)));
287 
288  /* Report this after the initial starting message for consistency. */
289  if (max_replication_slots == 0)
290  ereport(ERROR,
291  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
292  errmsg("cannot start logical replication workers when max_replication_slots = 0")));
293 
294  /*
295  * We need to do the modification of the shared memory under lock so that
296  * we have consistent view.
297  */
298  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
299 
300 retry:
301  /* Find unused worker slot. */
302  for (i = 0; i < max_logical_replication_workers; i++)
303  {
305 
306  if (!w->in_use)
307  {
308  worker = w;
309  slot = i;
310  break;
311  }
312  }
313 
314  nsyncworkers = logicalrep_sync_worker_count(subid);
315 
316  now = GetCurrentTimestamp();
317 
318  /*
319  * If we didn't find a free slot, try to do garbage collection. The
320  * reason we do this is because if some worker failed to start up and its
321  * parent has crashed while waiting, the in_use state was never cleared.
322  */
323  if (worker == NULL || nsyncworkers >= max_sync_workers_per_subscription)
324  {
325  bool did_cleanup = false;
326 
327  for (i = 0; i < max_logical_replication_workers; i++)
328  {
330 
331  /*
332  * If the worker was marked in use but didn't manage to attach in
333  * time, clean it up.
334  */
335  if (w->in_use && !w->proc &&
338  {
339  elog(WARNING,
340  "logical replication worker for subscription %u took too long to start; canceled",
341  w->subid);
342 
344  did_cleanup = true;
345  }
346  }
347 
348  if (did_cleanup)
349  goto retry;
350  }
351 
352  /*
353  * If we reached the sync worker limit per subscription, just exit
354  * silently as we might get here because of an otherwise harmless race
355  * condition.
356  */
357  if (nsyncworkers >= max_sync_workers_per_subscription)
358  {
359  LWLockRelease(LogicalRepWorkerLock);
360  return;
361  }
362 
363  /*
364  * However if there are no more free worker slots, inform user about it
365  * before exiting.
366  */
367  if (worker == NULL)
368  {
369  LWLockRelease(LogicalRepWorkerLock);
371  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
372  errmsg("out of logical replication worker slots"),
373  errhint("You might need to increase max_logical_replication_workers.")));
374  return;
375  }
376 
377  /* Prepare the worker slot. */
378  worker->launch_time = now;
379  worker->in_use = true;
380  worker->generation++;
381  worker->proc = NULL;
382  worker->dbid = dbid;
383  worker->userid = userid;
384  worker->subid = subid;
385  worker->relid = relid;
386  worker->relstate = SUBREL_STATE_UNKNOWN;
388  worker->last_lsn = InvalidXLogRecPtr;
391  worker->reply_lsn = InvalidXLogRecPtr;
392  TIMESTAMP_NOBEGIN(worker->reply_time);
393 
394  /* Before releasing lock, remember generation for future identification. */
395  generation = worker->generation;
396 
397  LWLockRelease(LogicalRepWorkerLock);
398 
399  /* Register the new dynamic worker. */
400  memset(&bgw, 0, sizeof(bgw));
404  snprintf(bgw.bgw_library_name, BGW_MAXLEN, "postgres");
405  snprintf(bgw.bgw_function_name, BGW_MAXLEN, "ApplyWorkerMain");
406  if (OidIsValid(relid))
408  "logical replication worker for subscription %u sync %u", subid, relid);
409  else
411  "logical replication worker for subscription %u", subid);
412  snprintf(bgw.bgw_type, BGW_MAXLEN, "logical replication worker");
413 
416  bgw.bgw_main_arg = Int32GetDatum(slot);
417 
418  if (!RegisterDynamicBackgroundWorker(&bgw, &bgw_handle))
419  {
420  /* Failed to start worker, so clean up the worker slot. */
421  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
422  Assert(generation == worker->generation);
424  LWLockRelease(LogicalRepWorkerLock);
425 
427  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
428  errmsg("out of background worker slots"),
429  errhint("You might need to increase max_worker_processes.")));
430  return;
431  }
432 
433  /* Now wait until it attaches. */
434  WaitForReplicationWorkerAttach(worker, generation, bgw_handle);
435 }
#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:1805
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:620
#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:665
static void WaitForReplicationWorkerAttach(LogicalRepWorker *worker, uint16 generation, BackgroundWorkerHandle *handle)
Definition: launcher.c:163
#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:962
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1203
#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 649 of file launcher.c.

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

Referenced by logicalrep_worker_attach().

650 {
651  /* Disconnect gracefully from the remote side. */
652  if (wrconn)
654 
656 
658 }
WalReceiverConn * wrconn
Definition: worker.c:159
static void logicalrep_worker_detach(void)
Definition: launcher.c:606
#define walrcv_disconnect(conn)
Definition: walreceiver.h:429
static void ApplyLauncherWakeup(void)
Definition: launcher.c:793

◆ logicalrep_worker_stop()

void logicalrep_worker_stop ( Oid  subid,
Oid  relid 
)

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

443 {
444  LogicalRepWorker *worker;
445  uint16 generation;
446 
447  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
448 
449  worker = logicalrep_worker_find(subid, relid, false);
450 
451  /* No worker, nothing to do. */
452  if (!worker)
453  {
454  LWLockRelease(LogicalRepWorkerLock);
455  return;
456  }
457 
458  /*
459  * Remember which generation was our worker so we can check if what we see
460  * is still the same one.
461  */
462  generation = worker->generation;
463 
464  /*
465  * If we found a worker but it does not have proc set then it is still
466  * starting up; wait for it to finish starting and then kill it.
467  */
468  while (worker->in_use && !worker->proc)
469  {
470  int rc;
471 
472  LWLockRelease(LogicalRepWorkerLock);
473 
474  /* Wait a bit --- we don't expect to have to wait long. */
475  rc = WaitLatch(MyLatch,
478 
479  if (rc & WL_LATCH_SET)
480  {
483  }
484 
485  /* Recheck worker status. */
486  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
487 
488  /*
489  * Check whether the worker slot is no longer used, which would mean
490  * that the worker has exited, or whether the worker generation is
491  * different, meaning that a different worker has taken the slot.
492  */
493  if (!worker->in_use || worker->generation != generation)
494  {
495  LWLockRelease(LogicalRepWorkerLock);
496  return;
497  }
498 
499  /* Worker has assigned proc, so it has started. */
500  if (worker->proc)
501  break;
502  }
503 
504  /* Now terminate the worker ... */
505  kill(worker->proc->pid, SIGTERM);
506 
507  /* ... and wait for it to die. */
508  for (;;)
509  {
510  int rc;
511 
512  /* is it gone? */
513  if (!worker->proc || worker->generation != generation)
514  break;
515 
516  LWLockRelease(LogicalRepWorkerLock);
517 
518  /* Wait a bit --- we don't expect to have to wait long. */
519  rc = WaitLatch(MyLatch,
520  WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
522 
523  if (rc & WL_LATCH_SET)
524  {
527  }
528 
529  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
530  }
531 
532  LWLockRelease(LogicalRepWorkerLock);
533 }
#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:1805
unsigned short uint16
Definition: c.h:440
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:221
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1203
struct Latch * MyLatch
Definition: globals.c:57
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:102
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 539 of file launcher.c.

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

Referenced by pg_attribute_noreturn().

540 {
541  LogicalRepWorker *worker;
542 
543  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
544 
545  worker = logicalrep_worker_find(subid, relid, true);
546 
547  if (worker)
549 
550  LWLockRelease(LogicalRepWorkerLock);
551 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1805
void logicalrep_worker_wakeup_ptr(LogicalRepWorker *worker)
Definition: launcher.c:559
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:221
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1203

◆ logicalrep_worker_wakeup_ptr()

void logicalrep_worker_wakeup_ptr ( LogicalRepWorker worker)

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

560 {
561  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
562 
563  SetLatch(&worker->proc->procLatch);
564 }
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1920
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 249 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().

250 {
251  int i;
252  List *res = NIL;
253 
254  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
255 
256  /* Search for attached worker for a given subscription id. */
257  for (i = 0; i < max_logical_replication_workers; i++)
258  {
260 
261  if (w->in_use && w->subid == subid && (!only_running || w->proc))
262  res = lappend(res, w);
263  }
264 
265  return res;
266 }
#define NIL
Definition: pg_list.h:65
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1920
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 928 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.

929 {
930 #define PG_STAT_GET_SUBSCRIPTION_COLS 8
931  Oid subid = PG_ARGISNULL(0) ? InvalidOid : PG_GETARG_OID(0);
932  int i;
933  ReturnSetInfo *rsinfo = (ReturnSetInfo *) fcinfo->resultinfo;
934  TupleDesc tupdesc;
935  Tuplestorestate *tupstore;
936  MemoryContext per_query_ctx;
937  MemoryContext oldcontext;
938 
939  /* check to see if caller supports us returning a tuplestore */
940  if (rsinfo == NULL || !IsA(rsinfo, ReturnSetInfo))
941  ereport(ERROR,
942  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
943  errmsg("set-valued function called in context that cannot accept a set")));
944  if (!(rsinfo->allowedModes & SFRM_Materialize))
945  ereport(ERROR,
946  (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
947  errmsg("materialize mode required, but it is not allowed in this context")));
948 
949  /* Build a tuple descriptor for our result type */
950  if (get_call_result_type(fcinfo, NULL, &tupdesc) != TYPEFUNC_COMPOSITE)
951  elog(ERROR, "return type must be a row type");
952 
953  per_query_ctx = rsinfo->econtext->ecxt_per_query_memory;
954  oldcontext = MemoryContextSwitchTo(per_query_ctx);
955 
956  tupstore = tuplestore_begin_heap(true, false, work_mem);
957  rsinfo->returnMode = SFRM_Materialize;
958  rsinfo->setResult = tupstore;
959  rsinfo->setDesc = tupdesc;
960 
961  MemoryContextSwitchTo(oldcontext);
962 
963  /* Make sure we get consistent view of the workers. */
964  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
965 
966  for (i = 0; i <= max_logical_replication_workers; i++)
967  {
968  /* for each row */
970  bool nulls[PG_STAT_GET_SUBSCRIPTION_COLS];
971  int worker_pid;
972  LogicalRepWorker worker;
973 
974  memcpy(&worker, &LogicalRepCtx->workers[i],
975  sizeof(LogicalRepWorker));
976  if (!worker.proc || !IsBackendPid(worker.proc->pid))
977  continue;
978 
979  if (OidIsValid(subid) && worker.subid != subid)
980  continue;
981 
982  worker_pid = worker.proc->pid;
983 
984  MemSet(values, 0, sizeof(values));
985  MemSet(nulls, 0, sizeof(nulls));
986 
987  values[0] = ObjectIdGetDatum(worker.subid);
988  if (OidIsValid(worker.relid))
989  values[1] = ObjectIdGetDatum(worker.relid);
990  else
991  nulls[1] = true;
992  values[2] = Int32GetDatum(worker_pid);
993  if (XLogRecPtrIsInvalid(worker.last_lsn))
994  nulls[3] = true;
995  else
996  values[3] = LSNGetDatum(worker.last_lsn);
997  if (worker.last_send_time == 0)
998  nulls[4] = true;
999  else
1000  values[4] = TimestampTzGetDatum(worker.last_send_time);
1001  if (worker.last_recv_time == 0)
1002  nulls[5] = true;
1003  else
1004  values[5] = TimestampTzGetDatum(worker.last_recv_time);
1005  if (XLogRecPtrIsInvalid(worker.reply_lsn))
1006  nulls[6] = true;
1007  else
1008  values[6] = LSNGetDatum(worker.reply_lsn);
1009  if (worker.reply_time == 0)
1010  nulls[7] = true;
1011  else
1012  values[7] = TimestampTzGetDatum(worker.reply_time);
1013 
1014  tuplestore_putvalues(tupstore, tupdesc, values, nulls);
1015 
1016  /*
1017  * If only a single subscription was requested, and we found it,
1018  * break.
1019  */
1020  if (OidIsValid(subid))
1021  break;
1022  }
1023 
1024  LWLockRelease(LogicalRepWorkerLock);
1025 
1026  /* clean up and return the tuplestore */
1027  tuplestore_donestoring(tupstore);
1028 
1029  return (Datum) 0;
1030 }
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:1805
#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:1203
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:3162
int pid
Definition: proc.h:146
TimestampTz reply_time

◆ WaitForReplicationWorkerAttach()

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

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

166 {
168  int rc;
169 
170  for (;;)
171  {
172  pid_t pid;
173 
175 
176  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
177 
178  /* Worker either died or has started; no need to do anything. */
179  if (!worker->in_use || worker->proc)
180  {
181  LWLockRelease(LogicalRepWorkerLock);
182  return;
183  }
184 
185  LWLockRelease(LogicalRepWorkerLock);
186 
187  /* Check if worker has died before attaching, and clean up after it. */
188  status = GetBackgroundWorkerPid(handle, &pid);
189 
190  if (status == BGWH_STOPPED)
191  {
192  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
193  /* Ensure that this was indeed the worker we waited for. */
194  if (generation == worker->generation)
196  LWLockRelease(LogicalRepWorkerLock);
197  return;
198  }
199 
200  /*
201  * We need timeout because we generally don't get notified via latch
202  * about the worker attach. But we don't expect to have to wait long.
203  */
204  rc = WaitLatch(MyLatch,
207 
208  if (rc & WL_LATCH_SET)
209  {
212  }
213  }
214 }
#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:1805
static void logicalrep_worker_cleanup(LogicalRepWorker *worker)
Definition: launcher.c:620
BgwHandleStatus
Definition: bgworker.h:102
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1203
struct Latch * MyLatch
Definition: globals.c:57
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:102
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:1074
#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 82 of file launcher.c.

Referenced by ApplyLauncherWakeupAtCommit(), and AtEOXact_ApplyLauncher().