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
 

Macros

#define DEFAULT_NAPTIME_PER_CYCLE   180000L
 
#define PG_STAT_GET_SUBSCRIPTION_COLS   8
 

Typedefs

typedef struct LogicalRepCtxStruct LogicalRepCtxStruct
 

Functions

static void ApplyLauncherWakeup (void)
 
static void logicalrep_launcher_onexit (int code, Datum arg)
 
static void logicalrep_worker_onexit (int code, Datum arg)
 
static void logicalrep_worker_detach (void)
 
static void logicalrep_worker_cleanup (LogicalRepWorker *worker)
 
Datum pg_stat_get_subscription (PG_FUNCTION_ARGS)
 
static Listget_subscription_list (void)
 
static void WaitForReplicationWorkerAttach (LogicalRepWorker *worker, BackgroundWorkerHandle *handle)
 
LogicalRepWorkerlogicalrep_worker_find (Oid subid, Oid relid, 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)
 
static void logicalrep_launcher_sighup (SIGNAL_ARGS)
 
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 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 793 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(), NULL, 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.

794 {
795  TimestampTz last_start_time = 0;
796 
797  ereport(DEBUG1,
798  (errmsg("logical replication launcher started")));
799 
801 
804 
805  /* Establish signal handlers. */
807  pqsignal(SIGTERM, die);
809 
810  /*
811  * Establish connection to nailed catalogs (we only ever access
812  * pg_subscription).
813  */
815 
816  /* Enter main loop */
817  for (;;)
818  {
819  int rc;
820  List *sublist;
821  ListCell *lc;
822  MemoryContext subctx;
823  MemoryContext oldctx;
825  long wait_time = DEFAULT_NAPTIME_PER_CYCLE;
826 
828 
829  now = GetCurrentTimestamp();
830 
831  /* Limit the start retry to once a wal_retrieve_retry_interval */
832  if (TimestampDifferenceExceeds(last_start_time, now,
834  {
835  /* Use temporary context for the database list and worker info. */
837  "Logical Replication Launcher sublist",
841  oldctx = MemoryContextSwitchTo(subctx);
842 
843  /* search for subscriptions to start or stop. */
844  sublist = get_subscription_list();
845 
846  /* Start the missing workers for enabled subscriptions. */
847  foreach(lc, sublist)
848  {
849  Subscription *sub = (Subscription *) lfirst(lc);
850  LogicalRepWorker *w;
851 
852  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
853  w = logicalrep_worker_find(sub->oid, InvalidOid, false);
854  LWLockRelease(LogicalRepWorkerLock);
855 
856  if (sub->enabled && w == NULL)
857  {
858  last_start_time = now;
859  wait_time = wal_retrieve_retry_interval;
860 
861  logicalrep_worker_launch(sub->dbid, sub->oid, sub->name,
862  sub->owner, InvalidOid);
863  }
864  }
865 
866  /* Switch back to original memory context. */
867  MemoryContextSwitchTo(oldctx);
868  /* Clean the temporary memory. */
869  MemoryContextDelete(subctx);
870  }
871  else
872  {
873  /*
874  * The wait in previous cycle was interrupted in less than
875  * wal_retrieve_retry_interval since last worker was started, this
876  * usually means crash of the worker, so we should retry in
877  * wal_retrieve_retry_interval again.
878  */
879  wait_time = wal_retrieve_retry_interval;
880  }
881 
882  /* Wait for more work. */
883  rc = WaitLatch(MyLatch,
885  wait_time,
887 
888  /* emergency bailout if postmaster has died */
889  if (rc & WL_POSTMASTER_DEATH)
890  proc_exit(1);
891 
892  if (rc & WL_LATCH_SET)
893  {
896  }
897 
898  if (got_SIGHUP)
899  {
900  got_SIGHUP = false;
902  }
903  }
904 
905  /* Not reachable */
906 }
static volatile sig_atomic_t got_SIGHUP
Definition: launcher.c:83
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:498
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:1715
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:619
#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:643
#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:97
#define NULL
Definition: c.h:229
void logicalrep_worker_launch(Oid dbid, Oid subid, const char *subname, Oid userid, Oid relid)
Definition: launcher.c:256
#define Assert(condition)
Definition: c.h:675
#define lfirst(lc)
Definition: pg_list.h:106
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:229
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
int errmsg(const char *fmt,...)
Definition: elog.c:797
void die(SIGNAL_ARGS)
Definition: postgres.c:2617
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:5527
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1534
void BackgroundWorkerUnblockSignals(void)
Definition: postmaster.c:5579
void ApplyLauncherRegister ( void  )

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

704 {
705  BackgroundWorker bgw;
706 
708  return;
709 
710  memset(&bgw, 0, sizeof(bgw));
714  snprintf(bgw.bgw_library_name, BGW_MAXLEN, "postgres");
715  snprintf(bgw.bgw_function_name, BGW_MAXLEN, "ApplyLauncherMain");
717  "logical replication launcher");
718  bgw.bgw_restart_time = 5;
719  bgw.bgw_notify_pid = 0;
720  bgw.bgw_main_arg = (Datum) 0;
721 
723 }
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 730 of file launcher.c.

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

Referenced by CreateSharedMemoryAndSemaphores().

731 {
732  bool found;
733 
735  ShmemInitStruct("Logical Replication Launcher Data",
737  &found);
738 
739  if (!found)
740  {
741  int slot;
742 
744 
745  /* Initialize memory and spin locks for each worker slot. */
746  for (slot = 0; slot < max_logical_replication_workers; slot++)
747  {
748  LogicalRepWorker *worker = &LogicalRepCtx->workers[slot];
749 
750  memset(worker, 0, sizeof(LogicalRepWorker));
751  SpinLockInit(&worker->relmutex);
752  }
753  }
754 }
#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:684
int max_logical_replication_workers
Definition: launcher.c:60
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:74
Size ApplyLauncherShmemSize ( void  )

Definition at line 684 of file launcher.c.

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

Referenced by ApplyLauncherShmemInit(), and CreateSharedMemoryAndSemaphores().

685 {
686  Size size;
687 
688  /*
689  * Need the fixed struct and the array of LogicalRepWorker.
690  */
691  size = sizeof(LogicalRepCtxStruct);
692  size = MAXALIGN(size);
694  sizeof(LogicalRepWorker)));
695  return size;
696 }
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:356
#define MAXALIGN(LEN)
Definition: c.h:588
struct LogicalRepCtxStruct LogicalRepCtxStruct
static void ApplyLauncherWakeup ( void  )
static

Definition at line 783 of file launcher.c.

References LogicalRepCtxStruct::launcher_pid, and SIGUSR1.

Referenced by AtEOXact_ApplyLauncher(), and logicalrep_worker_onexit().

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

Definition at line 776 of file launcher.c.

References on_commit_launcher_wakeup.

Referenced by AlterSubscription(), and CreateSubscription().

777 {
780 }
static bool on_commit_launcher_wakeup
Definition: launcher.c:85
void AtEOXact_ApplyLauncher ( bool  isCommit)

Definition at line 760 of file launcher.c.

References ApplyLauncherWakeup(), and on_commit_launcher_wakeup.

Referenced by AbortTransaction(), and CommitTransaction().

761 {
762  if (isCommit && on_commit_launcher_wakeup)
764 
766 }
static bool on_commit_launcher_wakeup
Definition: launcher.c:85
static void ApplyLauncherWakeup(void)
Definition: launcher.c:783
static List* get_subscription_list ( void  )
static

Definition at line 97 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, NULL, Subscription::oid, Subscription::owner, palloc0(), pstrdup(), StartTransactionCommand(), and SubscriptionRelationId.

Referenced by ApplyLauncherMain().

98 {
99  List *res = NIL;
100  Relation rel;
101  HeapScanDesc scan;
102  HeapTuple tup;
103  MemoryContext resultcxt;
104 
105  /* This is the context that we will allocate our output data in */
106  resultcxt = CurrentMemoryContext;
107 
108  /*
109  * Start a transaction so we can access pg_database, and get a snapshot.
110  * We don't have a use for the snapshot itself, but we're interested in
111  * the secondary effect that it sets RecentGlobalXmin. (This is critical
112  * for anything that reads heap pages, because HOT may decide to prune
113  * them even if the process doesn't attempt to modify any tuples.)
114  */
116  (void) GetTransactionSnapshot();
117 
119  scan = heap_beginscan_catalog(rel, 0, NULL);
120 
122  {
124  Subscription *sub;
125  MemoryContext oldcxt;
126 
127  /*
128  * Allocate our results in the caller's context, not the
129  * transaction's. We do this inside the loop, and restore the original
130  * context at the end, so that leaky things like heap_getnext() are
131  * not called in a potentially long-lived context.
132  */
133  oldcxt = MemoryContextSwitchTo(resultcxt);
134 
135  sub = (Subscription *) palloc0(sizeof(Subscription));
136  sub->oid = HeapTupleGetOid(tup);
137  sub->dbid = subform->subdbid;
138  sub->owner = subform->subowner;
139  sub->enabled = subform->subenabled;
140  sub->name = pstrdup(NameStr(subform->subname));
141  /* We don't fill fields we are not interested in. */
142 
143  res = lappend(res, sub);
144  MemoryContextSwitchTo(oldcxt);
145  }
146 
147  heap_endscan(scan);
149 
151 
152  return res;
153 }
#define NIL
Definition: pg_list.h:69
#define GETSTRUCT(TUP)
Definition: htup_details.h:656
void heap_endscan(HeapScanDesc scan)
Definition: heapam.c:1578
char * pstrdup(const char *in)
Definition: mcxt.c:1077
void CommitTransactionCommand(void)
Definition: xact.c:2748
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:1399
List * lappend(List *list, void *datum)
Definition: list.c:128
void * palloc0(Size size)
Definition: mcxt.c:878
HeapTuple heap_getnext(HeapScanDesc scan, ScanDirection direction)
Definition: heapam.c:1794
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1284
#define HeapTupleIsValid(tuple)
Definition: htup.h:77
#define NULL
Definition: c.h:229
void StartTransactionCommand(void)
Definition: xact.c:2678
#define NameStr(name)
Definition: c.h:499
#define HeapTupleGetOid(tuple)
Definition: htup_details.h:695
Definition: pg_list.h:45
bool IsLogicalLauncher ( void  )

Definition at line 912 of file launcher.c.

References LogicalRepCtxStruct::launcher_pid, and MyProcPid.

Referenced by ProcessInterrupts().

913 {
915 }
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 619 of file launcher.c.

References LogicalRepCtxStruct::launcher_pid.

Referenced by ApplyLauncherMain().

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

Definition at line 643 of file launcher.c.

References got_SIGHUP, MyLatch, and SetLatch().

Referenced by ApplyLauncherMain().

644 {
645  int save_errno = errno;
646 
647  got_SIGHUP = true;
648 
649  /* Waken anything waiting on the process latch */
650  SetLatch(MyLatch);
651 
652  errno = save_errno;
653 }
static volatile sig_atomic_t got_SIGHUP
Definition: launcher.c:83
void SetLatch(volatile Latch *latch)
Definition: latch.c:415
struct Latch * MyLatch
Definition: globals.c:52
int logicalrep_sync_worker_count ( Oid  subid)

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

661 {
662  int i;
663  int res = 0;
664 
665  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
666 
667  /* Search for attached worker for a given subscription id. */
668  for (i = 0; i < max_logical_replication_workers; i++)
669  {
671 
672  if (w->subid == subid && OidIsValid(w->relid))
673  res++;
674  }
675 
676  return res;
677 }
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1831
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:71
#define OidIsValid(objectId)
Definition: c.h:538
#define Assert(condition)
Definition: c.h:675
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 551 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().

552 {
553  /* Block concurrent access. */
554  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
555 
556  Assert(slot >= 0 && slot < max_logical_replication_workers);
558 
560  {
561  LWLockRelease(LogicalRepWorkerLock);
562  ereport(ERROR,
563  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
564  errmsg("logical replication worker slot %d is empty, cannot attach",
565  slot)));
566  }
567 
569  {
570  LWLockRelease(LogicalRepWorkerLock);
571  ereport(ERROR,
572  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
573  errmsg("logical replication worker slot %d is already used by "
574  "another worker, cannot attach", slot)));
575  }
576 
579 
580  LWLockRelease(LogicalRepWorkerLock);
581 }
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:1715
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:630
uintptr_t Datum
Definition: postgres.h:372
#define Assert(condition)
Definition: c.h:675
int max_logical_replication_workers
Definition: launcher.c:60
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
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 601 of file launcher.c.

References Assert, LogicalRepWorker::dbid, LogicalRepWorker::in_use, InvalidOid, LW_EXCLUSIVE, LWLockHeldByMeInMode(), NULL, LogicalRepWorker::proc, LogicalRepWorker::relid, LogicalRepWorker::subid, and LogicalRepWorker::userid.

Referenced by logicalrep_worker_detach(), logicalrep_worker_launch(), and WaitForReplicationWorkerAttach().

602 {
603  Assert(LWLockHeldByMeInMode(LogicalRepWorkerLock, LW_EXCLUSIVE));
604 
605  worker->in_use = false;
606  worker->proc = NULL;
607  worker->dbid = InvalidOid;
608  worker->userid = InvalidOid;
609  worker->subid = InvalidOid;
610  worker->relid = InvalidOid;
611 }
bool LWLockHeldByMeInMode(LWLock *l, LWLockMode mode)
Definition: lwlock.c:1849
#define InvalidOid
Definition: postgres_ext.h:36
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
static void logicalrep_worker_detach ( void  )
static

Definition at line 587 of file launcher.c.

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

Referenced by logicalrep_worker_onexit().

588 {
589  /* Block concurrent access. */
590  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
591 
593 
594  LWLockRelease(LogicalRepWorkerLock);
595 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:63
static void logicalrep_worker_cleanup(LogicalRepWorker *worker)
Definition: launcher.c:601
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
LogicalRepWorker* logicalrep_worker_find ( Oid  subid,
Oid  relid,
bool  only_running 
)

Definition at line 229 of file launcher.c.

References Assert, i, LogicalRepWorker::in_use, LWLockHeldByMe(), max_logical_replication_workers, NULL, 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().

230 {
231  int i;
232  LogicalRepWorker *res = NULL;
233 
234  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
235 
236  /* Search for attached worker for a given subscription id. */
237  for (i = 0; i < max_logical_replication_workers; i++)
238  {
240 
241  if (w->in_use && w->subid == subid && w->relid == relid &&
242  (!only_running || w->proc))
243  {
244  res = w;
245  break;
246  }
247  }
248 
249  return res;
250 }
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1831
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:71
#define NULL
Definition: c.h:229
#define Assert(condition)
Definition: c.h:675
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 256 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, 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(), NULL, 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().

258 {
259  BackgroundWorker bgw;
260  BackgroundWorkerHandle *bgw_handle;
261  int i;
262  int slot = 0;
263  LogicalRepWorker *worker = NULL;
264  int nsyncworkers;
266 
267  ereport(DEBUG1,
268  (errmsg("starting logical replication worker for subscription \"%s\"",
269  subname)));
270 
271  /* Report this after the initial starting message for consistency. */
272  if (max_replication_slots == 0)
273  ereport(ERROR,
274  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
275  errmsg("cannot start logical replication workers when max_replication_slots = 0")));
276 
277  /*
278  * We need to do the modification of the shared memory under lock so that
279  * we have consistent view.
280  */
281  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
282 
283 retry:
284  /* Find unused worker slot. */
285  for (i = 0; i < max_logical_replication_workers; i++)
286  {
288 
289  if (!w->in_use)
290  {
291  worker = w;
292  slot = i;
293  break;
294  }
295  }
296 
297  nsyncworkers = logicalrep_sync_worker_count(subid);
298 
299  now = GetCurrentTimestamp();
300 
301  /*
302  * If we didn't find a free slot, try to do garbage collection. The
303  * reason we do this is because if some worker failed to start up and its
304  * parent has crashed while waiting, the in_use state was never cleared.
305  */
306  if (worker == NULL || nsyncworkers >= max_sync_workers_per_subscription)
307  {
308  bool did_cleanup = false;
309 
310  for (i = 0; i < max_logical_replication_workers; i++)
311  {
313 
314  /*
315  * If the worker was marked in use but didn't manage to attach in
316  * time, clean it up.
317  */
318  if (w->in_use && !w->proc &&
321  {
322  elog(WARNING,
323  "logical replication worker for subscription %u took too long to start; canceled",
324  w->subid);
325 
327  did_cleanup = true;
328  }
329  }
330 
331  if (did_cleanup)
332  goto retry;
333  }
334 
335  /*
336  * If we reached the sync worker limit per subscription, just exit
337  * silently as we might get here because of an otherwise harmless race
338  * condition.
339  */
340  if (nsyncworkers >= max_sync_workers_per_subscription)
341  {
342  LWLockRelease(LogicalRepWorkerLock);
343  return;
344  }
345 
346  /*
347  * However if there are no more free worker slots, inform user about it
348  * before exiting.
349  */
350  if (worker == NULL)
351  {
352  LWLockRelease(LogicalRepWorkerLock);
354  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
355  errmsg("out of logical replication worker slots"),
356  errhint("You might need to increase max_logical_replication_workers.")));
357  return;
358  }
359 
360  /* Prepare the worker slot. */
361  worker->launch_time = now;
362  worker->in_use = true;
363  worker->generation++;
364  worker->proc = NULL;
365  worker->dbid = dbid;
366  worker->userid = userid;
367  worker->subid = subid;
368  worker->relid = relid;
369  worker->relstate = SUBREL_STATE_UNKNOWN;
371  worker->last_lsn = InvalidXLogRecPtr;
374  worker->reply_lsn = InvalidXLogRecPtr;
375  TIMESTAMP_NOBEGIN(worker->reply_time);
376 
377  LWLockRelease(LogicalRepWorkerLock);
378 
379  /* Register the new dynamic worker. */
380  memset(&bgw, 0, sizeof(bgw));
384  snprintf(bgw.bgw_library_name, BGW_MAXLEN, "postgres");
385  snprintf(bgw.bgw_function_name, BGW_MAXLEN, "ApplyWorkerMain");
386  if (OidIsValid(relid))
388  "logical replication worker for subscription %u sync %u", subid, relid);
389  else
391  "logical replication worker for subscription %u", subid);
392 
395  bgw.bgw_main_arg = Int32GetDatum(slot);
396 
397  if (!RegisterDynamicBackgroundWorker(&bgw, &bgw_handle))
398  {
400  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
401  errmsg("out of background worker slots"),
402  errhint("You might need to increase max_worker_processes.")));
403  return;
404  }
405 
406  /* Now wait until it attaches. */
407  WaitForReplicationWorkerAttach(worker, bgw_handle);
408 }
#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:538
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:1715
Datum bgw_main_arg
Definition: bgworker.h:96
#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:601
#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:660
TimestampTz launch_time
int max_replication_slots
Definition: slot.c:99
TimestampTz last_recv_time
#define NULL
Definition: c.h:229
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
bool RegisterDynamicBackgroundWorker(BackgroundWorker *worker, BackgroundWorkerHandle **handle)
Definition: bgworker.c:933
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
static void WaitForReplicationWorkerAttach(LogicalRepWorker *worker, BackgroundWorkerHandle *handle)
Definition: launcher.c:162
#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 630 of file launcher.c.

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

Referenced by logicalrep_worker_attach().

631 {
632  /* Disconnect gracefully from the remote side. */
633  if (wrconn)
635 
637 
639 }
WalReceiverConn * wrconn
Definition: worker.c:110
static void logicalrep_worker_detach(void)
Definition: launcher.c:587
#define walrcv_disconnect(conn)
Definition: walreceiver.h:264
static void ApplyLauncherWakeup(void)
Definition: launcher.c:783
void logicalrep_worker_stop ( Oid  subid,
Oid  relid 
)

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

416 {
417  LogicalRepWorker *worker;
418  uint16 generation;
419 
420  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
421 
422  worker = logicalrep_worker_find(subid, relid, false);
423 
424  /* No worker, nothing to do. */
425  if (!worker)
426  {
427  LWLockRelease(LogicalRepWorkerLock);
428  return;
429  }
430 
431  /*
432  * Remember which generation was our worker so we can check if what we see
433  * is still the same one.
434  */
435  generation = worker->generation;
436 
437  /*
438  * If we found a worker but it does not have proc set then it is still
439  * starting up; wait for it to finish starting and then kill it.
440  */
441  while (worker->in_use && !worker->proc)
442  {
443  int rc;
444 
445  LWLockRelease(LogicalRepWorkerLock);
446 
447  /* Wait a bit --- we don't expect to have to wait long. */
448  rc = WaitLatch(MyLatch,
451 
452  /* emergency bailout if postmaster has died */
453  if (rc & WL_POSTMASTER_DEATH)
454  proc_exit(1);
455 
456  if (rc & WL_LATCH_SET)
457  {
460  }
461 
462  /* Recheck worker status. */
463  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
464 
465  /*
466  * Check whether the worker slot is no longer used, which would mean
467  * that the worker has exited, or whether the worker generation is
468  * different, meaning that a different worker has taken the slot.
469  */
470  if (!worker->in_use || worker->generation != generation)
471  {
472  LWLockRelease(LogicalRepWorkerLock);
473  return;
474  }
475 
476  /* Worker has assigned proc, so it has started. */
477  if (worker->proc)
478  break;
479  }
480 
481  /* Now terminate the worker ... */
482  kill(worker->proc->pid, SIGTERM);
483 
484  /* ... and wait for it to die. */
485  for (;;)
486  {
487  int rc;
488 
489  /* is it gone? */
490  if (!worker->proc || worker->generation != generation)
491  break;
492 
493  LWLockRelease(LogicalRepWorkerLock);
494 
495  /* Wait a bit --- we don't expect to have to wait long. */
496  rc = WaitLatch(MyLatch,
497  WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
499 
500  /* emergency bailout if postmaster has died */
501  if (rc & WL_POSTMASTER_DEATH)
502  proc_exit(1);
503 
504  if (rc & WL_LATCH_SET)
505  {
508  }
509 
510  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
511  }
512 
513  LWLockRelease(LogicalRepWorkerLock);
514 }
#define WL_TIMEOUT
Definition: latch.h:127
void proc_exit(int code)
Definition: ipc.c:99
void ResetLatch(volatile Latch *latch)
Definition: latch.c:498
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
int WaitLatch(volatile Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:336
unsigned short uint16
Definition: c.h:267
#define WL_POSTMASTER_DEATH
Definition: latch.h:128
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:229
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
struct Latch * MyLatch
Definition: globals.c:52
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:98
int pid
Definition: proc.h:108
#define WL_LATCH_SET
Definition: latch.h:124
void logicalrep_worker_wakeup ( Oid  subid,
Oid  relid 
)

Definition at line 520 of file launcher.c.

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

Referenced by pg_attribute_noreturn().

521 {
522  LogicalRepWorker *worker;
523 
524  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
525 
526  worker = logicalrep_worker_find(subid, relid, true);
527 
528  if (worker)
530 
531  LWLockRelease(LogicalRepWorkerLock);
532 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
void logicalrep_worker_wakeup_ptr(LogicalRepWorker *worker)
Definition: launcher.c:540
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:229
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
void logicalrep_worker_wakeup_ptr ( LogicalRepWorker worker)

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

541 {
542  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
543 
544  SetLatch(&worker->proc->procLatch);
545 }
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1831
Latch procLatch
Definition: proc.h:103
void SetLatch(volatile Latch *latch)
Definition: latch.c:415
#define Assert(condition)
Definition: c.h:675
Datum pg_stat_get_subscription ( PG_FUNCTION_ARGS  )

Definition at line 921 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, NULL, 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.

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

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

164 {
166  int rc;
167  uint16 generation;
168 
169  /* Remember generation for future identification. */
170  generation = worker->generation;
171 
172  for (;;)
173  {
174  pid_t pid;
175 
177 
178  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
179 
180  /* Worker either died or has started; no need to do anything. */
181  if (!worker->in_use || worker->proc)
182  {
183  LWLockRelease(LogicalRepWorkerLock);
184  return;
185  }
186 
187  LWLockRelease(LogicalRepWorkerLock);
188 
189  /* Check if worker has died before attaching, and clean up after it. */
190  status = GetBackgroundWorkerPid(handle, &pid);
191 
192  if (status == BGWH_STOPPED)
193  {
194  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
195  /* Ensure that this was indeed the worker we waited for. */
196  if (generation == worker->generation)
198  LWLockRelease(LogicalRepWorkerLock);
199  return;
200  }
201 
202  /*
203  * We need timeout because we generally don't get notified via latch
204  * about the worker attach. But we don't expect to have to wait long.
205  */
206  rc = WaitLatch(MyLatch,
209 
210  /* emergency bailout if postmaster has died */
211  if (rc & WL_POSTMASTER_DEATH)
212  proc_exit(1);
213 
214  if (rc & WL_LATCH_SET)
215  {
218  }
219  }
220 
221  return;
222 }
#define WL_TIMEOUT
Definition: latch.h:127
void proc_exit(int code)
Definition: ipc.c:99
void ResetLatch(volatile Latch *latch)
Definition: latch.c:498
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
int WaitLatch(volatile Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:336
unsigned short uint16
Definition: c.h:267
static void logicalrep_worker_cleanup(LogicalRepWorker *worker)
Definition: launcher.c:601
BgwHandleStatus
Definition: bgworker.h:101
#define WL_POSTMASTER_DEATH
Definition: latch.h:128
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
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

Variable Documentation

volatile sig_atomic_t got_SIGHUP = false
static

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

Referenced by ApplyLauncherWakeupAtCommit(), and AtEOXact_ApplyLauncher().