PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
launcher.c File Reference
Include dependency graph for launcher.c:

Go to the source code of this file.

Data Structures

struct  LogicalRepCtxStruct
 
struct  LogicalRepWorkerId
 

Macros

#define DEFAULT_NAPTIME_PER_CYCLE   180000L
 
#define PG_STAT_GET_SUBSCRIPTION_COLS   8
 

Typedefs

typedef struct LogicalRepCtxStruct LogicalRepCtxStruct
 
typedef struct LogicalRepWorkerId LogicalRepWorkerId
 

Functions

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

Variables

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

Macro Definition Documentation

#define DEFAULT_NAPTIME_PER_CYCLE   180000L

Definition at line 58 of file launcher.c.

Referenced by ApplyLauncherMain().

#define PG_STAT_GET_SUBSCRIPTION_COLS   8

Typedef Documentation

Function Documentation

void ApplyLauncherMain ( Datum  main_arg)

Definition at line 880 of file launcher.c.

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

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

Definition at line 763 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, BGWORKER_BACKEND_DATABASE_CONNECTION, BGWORKER_SHMEM_ACCESS, BgWorkerStart_RecoveryFinished, max_logical_replication_workers, RegisterBackgroundWorker(), and snprintf().

Referenced by PostmasterMain().

764 {
765  BackgroundWorker bgw;
766 
768  return;
769 
770  memset(&bgw, 0, sizeof(bgw));
774  snprintf(bgw.bgw_library_name, BGW_MAXLEN, "postgres");
775  snprintf(bgw.bgw_function_name, BGW_MAXLEN, "ApplyLauncherMain");
777  "logical replication launcher");
778  bgw.bgw_restart_time = 5;
779  bgw.bgw_notify_pid = 0;
780  bgw.bgw_main_arg = (Datum) 0;
781 
783 }
void RegisterBackgroundWorker(BackgroundWorker *worker)
Definition: bgworker.c:849
int bgw_restart_time
Definition: bgworker.h:93
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
#define BGWORKER_SHMEM_ACCESS
Definition: bgworker.h:52
char bgw_function_name[BGW_MAXLEN]
Definition: bgworker.h:95
Datum bgw_main_arg
Definition: bgworker.h:96
uintptr_t Datum
Definition: postgres.h:372
char bgw_name[BGW_MAXLEN]
Definition: bgworker.h:90
#define BGWORKER_BACKEND_DATABASE_CONNECTION
Definition: bgworker.h:59
int max_logical_replication_workers
Definition: launcher.c:60
#define BGW_MAXLEN
Definition: bgworker.h:85
BgWorkerStartTime bgw_start_time
Definition: bgworker.h:92
pid_t bgw_notify_pid
Definition: bgworker.h:98
char bgw_library_name[BGW_MAXLEN]
Definition: bgworker.h:94
void ApplyLauncherShmemInit ( void  )

Definition at line 790 of file launcher.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

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

Definition at line 744 of file launcher.c.

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

Referenced by ApplyLauncherShmemInit(), and CreateSharedMemoryAndSemaphores().

745 {
746  Size size;
747 
748  /*
749  * Need the fixed struct and the array of LogicalRepWorker.
750  */
751  size = sizeof(LogicalRepCtxStruct);
752  size = MAXALIGN(size);
754  sizeof(LogicalRepWorker)));
755  return size;
756 }
Size mul_size(Size s1, Size s2)
Definition: shmem.c:492
Size add_size(Size s1, Size s2)
Definition: shmem.c:475
int max_logical_replication_workers
Definition: launcher.c:60
size_t Size
Definition: c.h:350
#define MAXALIGN(LEN)
Definition: c.h:576
struct LogicalRepCtxStruct LogicalRepCtxStruct
static void ApplyLauncherWakeup ( void  )
static

Definition at line 870 of file launcher.c.

References LogicalRepCtxStruct::launcher_pid, and SIGUSR1.

Referenced by AtEOXact_ApplyLauncher(), and logicalrep_worker_onexit().

871 {
872  if (LogicalRepCtx->launcher_pid != 0)
874 }
#define SIGUSR1
Definition: win32.h:202
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:74
void ApplyLauncherWakeupAtCommit ( void  )

Definition at line 863 of file launcher.c.

References on_commit_launcher_wakeup.

Referenced by AlterSubscription(), and CreateSubscription().

864 {
867 }
static bool on_commit_launcher_wakeup
Definition: launcher.c:93
void AtEOXact_ApplyLauncher ( bool  isCommit)

Definition at line 830 of file launcher.c.

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

Referenced by AbortTransaction(), and CommitTransaction().

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

Definition at line 105 of file launcher.c.

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

Referenced by ApplyLauncherMain().

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

Definition at line 1002 of file launcher.c.

References LogicalRepCtxStruct::launcher_pid, and MyProcPid.

Referenced by ProcessInterrupts().

1003 {
1005 }
int MyProcPid
Definition: globals.c:39
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:74
static void logicalrep_launcher_onexit ( int  code,
Datum  arg 
)
static

Definition at line 679 of file launcher.c.

References LogicalRepCtxStruct::launcher_pid.

Referenced by ApplyLauncherMain().

680 {
682 }
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:74
static void logicalrep_launcher_sighup ( SIGNAL_ARGS  )
static

Definition at line 703 of file launcher.c.

References got_SIGHUP, MyLatch, and SetLatch().

Referenced by ApplyLauncherMain().

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

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

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

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

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

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

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

Definition at line 647 of file launcher.c.

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

Referenced by logicalrep_worker_onexit().

648 {
649  /* Block concurrent access. */
650  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
651 
653 
654  LWLockRelease(LogicalRepWorkerLock);
655 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1721
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:63
static void logicalrep_worker_cleanup(LogicalRepWorker *worker)
Definition: launcher.c:661
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1117
LogicalRepWorker* logicalrep_worker_find ( Oid  subid,
Oid  relid,
bool  only_running 
)

Definition at line 234 of file launcher.c.

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

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

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

Definition at line 285 of file launcher.c.

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

Referenced by ApplyLauncherMain(), and process_syncing_tables_for_apply().

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

Definition at line 690 of file launcher.c.

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

Referenced by logicalrep_worker_attach().

691 {
692  /* Disconnect gracefully from the remote side. */
693  if (wrconn)
695 
697 
699 }
WalReceiverConn * wrconn
Definition: worker.c:110
static void logicalrep_worker_detach(void)
Definition: launcher.c:647
#define walrcv_disconnect(conn)
Definition: walreceiver.h:264
static void ApplyLauncherWakeup(void)
Definition: launcher.c:870
void logicalrep_worker_stop ( Oid  subid,
Oid  relid 
)

Definition at line 454 of file launcher.c.

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

Referenced by AtEOXact_ApplyLauncher(), and DropSubscription().

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

Definition at line 559 of file launcher.c.

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

Referenced by AlterSubscription_refresh().

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

Definition at line 580 of file launcher.c.

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

Referenced by pg_attribute_noreturn().

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

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

601 {
602  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
603 
604  SetLatch(&worker->proc->procLatch);
605 }
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1837
Latch procLatch
Definition: proc.h:104
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
#define Assert(condition)
Definition: c.h:664
List* logicalrep_workers_find ( Oid  subid,
bool  only_running 
)

Definition at line 262 of file launcher.c.

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

Referenced by DropSubscription().

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

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

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

Definition at line 170 of file launcher.c.

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

Referenced by logicalrep_worker_launch().

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

Definition at line 821 of file launcher.c.

References NIL.

Referenced by PrepareTransaction().

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

Variable Documentation

volatile sig_atomic_t got_SIGHUP = false
static

Definition at line 91 of file launcher.c.

Referenced by ApplyLauncherMain(), and logicalrep_launcher_sighup().

LogicalRepCtxStruct* LogicalRepCtx

Definition at line 74 of file launcher.c.

int max_sync_workers_per_subscription = 2

Definition at line 61 of file launcher.c.

Referenced by logicalrep_worker_launch(), and process_syncing_tables_for_apply().

bool on_commit_launcher_wakeup = false
static

Definition at line 93 of file launcher.c.

Referenced by ApplyLauncherWakeupAtCommit(), and AtEOXact_ApplyLauncher().

List* on_commit_stop_workers = NIL
static

Definition at line 82 of file launcher.c.