PostgreSQL Source Code  git master
worker_internal.h File Reference
#include <signal.h>
#include "access/xlogdefs.h"
#include "catalog/pg_subscription.h"
#include "datatype/timestamp.h"
#include "storage/lock.h"
Include dependency graph for worker_internal.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Data Structures

struct  LogicalRepWorker
 

Typedefs

typedef struct LogicalRepWorker LogicalRepWorker
 

Functions

void logicalrep_worker_attach (int slot)
 
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)
 
int logicalrep_sync_worker_count (Oid subid)
 
char * LogicalRepSyncTableStart (XLogRecPtr *origin_startpos)
 
void process_syncing_tables (XLogRecPtr current_lsn)
 
void invalidate_syncing_table_states (Datum arg, int cacheid, uint32 hashvalue)
 
static bool am_tablesync_worker (void)
 

Variables

MemoryContext ApplyContext
 
struct WalReceiverConnwrconn
 
SubscriptionMySubscription
 
LogicalRepWorkerMyLogicalRepWorker
 
bool in_remote_transaction
 

Typedef Documentation

◆ LogicalRepWorker

Function Documentation

◆ am_tablesync_worker()

static bool am_tablesync_worker ( void  )
inlinestatic

Definition at line 90 of file worker_internal.h.

References OidIsValid, and LogicalRepWorker::relid.

Referenced by apply_handle_commit(), apply_handle_origin(), ApplyWorkerMain(), process_syncing_tables(), should_apply_changes_for_rel(), and wait_for_relation_state_change().

91 {
93 }
#define OidIsValid(objectId)
Definition: c.h:576
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:63

◆ invalidate_syncing_table_states()

void invalidate_syncing_table_states ( Datum  arg,
int  cacheid,
uint32  hashvalue 
)

Definition at line 271 of file tablesync.c.

References table_states_valid.

Referenced by ApplyWorkerMain().

272 {
273  table_states_valid = false;
274 }
static bool table_states_valid
Definition: tablesync.c:112

◆ logicalrep_sync_worker_count()

int logicalrep_sync_worker_count ( Oid  subid)

Definition at line 721 of file launcher.c.

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

Referenced by logicalrep_worker_launch(), and process_syncing_tables_for_apply().

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

◆ logicalrep_worker_attach()

void logicalrep_worker_attach ( int  slot)

Definition at line 612 of file launcher.c.

References Assert, before_shmem_exit(), ereport, errcode(), errmsg(), ERROR, LogicalRepWorker::in_use, logicalrep_worker_onexit(), LW_EXCLUSIVE, LWLockAcquire(), LWLockRelease(), max_logical_replication_workers, MyProc, LogicalRepWorker::proc, and LogicalRepCtxStruct::workers.

Referenced by ApplyWorkerMain().

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

◆ logicalrep_worker_find()

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

Definition at line 234 of file launcher.c.

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

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

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

◆ logicalrep_worker_launch()

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

Definition at line 285 of file launcher.c.

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

Referenced by ApplyLauncherMain(), and process_syncing_tables_for_apply().

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

◆ logicalrep_worker_stop()

void logicalrep_worker_stop ( Oid  subid,
Oid  relid 
)

Definition at line 455 of file launcher.c.

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

Referenced by AtEOXact_ApplyLauncher(), and DropSubscription().

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

◆ logicalrep_worker_stop_at_commit()

void logicalrep_worker_stop_at_commit ( Oid  subid,
Oid  relid 
)

Definition at line 560 of file launcher.c.

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

Referenced by AlterSubscription_refresh().

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

◆ logicalrep_worker_wakeup()

void logicalrep_worker_wakeup ( Oid  subid,
Oid  relid 
)

Definition at line 581 of file launcher.c.

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

Referenced by pg_attribute_noreturn().

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

◆ logicalrep_worker_wakeup_ptr()

void logicalrep_worker_wakeup_ptr ( LogicalRepWorker worker)

Definition at line 601 of file launcher.c.

References Assert, LWLockHeldByMe(), LogicalRepWorker::proc, PGPROC::procLatch, and SetLatch().

Referenced by logicalrep_worker_wakeup(), process_syncing_tables_for_apply(), and wait_for_worker_state_change().

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

◆ logicalrep_workers_find()

List* logicalrep_workers_find ( Oid  subid,
bool  only_running 
)

Definition at line 262 of file launcher.c.

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

Referenced by DropSubscription().

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

◆ LogicalRepSyncTableStart()

char* LogicalRepSyncTableStart ( XLogRecPtr origin_startpos)

Definition at line 815 of file tablesync.c.

References CommandCounterIncrement(), CommitTransactionCommand(), Subscription::conninfo, copy_table(), CRS_USE_SNAPSHOT, elog, ereport, WalRcvExecResult::err, errdetail(), errmsg(), ERROR, GetSubscriptionRelState(), GetTransactionSnapshot(), heap_close, heap_open(), InvalidXLogRecPtr, MyLogicalRepWorker, MySubscription, NAMEDATALEN, NoLock, Subscription::oid, pgstat_report_stat(), PopActiveSnapshot(), psprintf(), PushActiveSnapshot(), LogicalRepWorker::relid, LogicalRepWorker::relmutex, LogicalRepWorker::relstate, LogicalRepWorker::relstate_lsn, RowExclusiveLock, SetSubscriptionRelState(), Subscription::slotname, SpinLockAcquire, SpinLockRelease, StartTransactionCommand(), StaticAssertStmt, WalRcvExecResult::status, LogicalRepWorker::subid, SUBREL_STATE_CATCHUP, SUBREL_STATE_DATASYNC, SUBREL_STATE_INIT, SUBREL_STATE_READY, SUBREL_STATE_SYNCDONE, SUBREL_STATE_SYNCWAIT, SUBREL_STATE_UNKNOWN, wait_for_worker_state_change(), walrcv_clear_result(), walrcv_connect, walrcv_create_slot, walrcv_exec, WALRCV_OK_COMMAND, and wrconn.

Referenced by ApplyWorkerMain().

816 {
817  char *slotname;
818  char *err;
819  char relstate;
820  XLogRecPtr relstate_lsn;
821 
822  /* Check the state of the table synchronization. */
826  &relstate_lsn, true);
828 
830  MyLogicalRepWorker->relstate = relstate;
831  MyLogicalRepWorker->relstate_lsn = relstate_lsn;
833 
834  /*
835  * To build a slot name for the sync work, we are limited to NAMEDATALEN -
836  * 1 characters. We cut the original slot name to NAMEDATALEN - 28 chars
837  * and append _%u_sync_%u (1 + 10 + 6 + 10 + '\0'). (It's actually the
838  * NAMEDATALEN on the remote that matters, but this scheme will also work
839  * reasonably if that is different.)
840  */
841  StaticAssertStmt(NAMEDATALEN >= 32, "NAMEDATALEN too small"); /* for sanity */
842  slotname = psprintf("%.*s_%u_sync_%u",
843  NAMEDATALEN - 28,
847 
848  /*
849  * Here we use the slot name instead of the subscription name as the
850  * application_name, so that it is different from the main apply worker,
851  * so that synchronous replication can distinguish them.
852  */
853  wrconn = walrcv_connect(MySubscription->conninfo, true, slotname, &err);
854  if (wrconn == NULL)
855  ereport(ERROR,
856  (errmsg("could not connect to the publisher: %s", err)));
857 
858  switch (MyLogicalRepWorker->relstate)
859  {
860  case SUBREL_STATE_INIT:
862  {
863  Relation rel;
864  WalRcvExecResult *res;
865 
870 
871  /* Update the state and make it visible to others. */
877  true);
879  pgstat_report_stat(false);
880 
881  /*
882  * We want to do the table data sync in a single transaction.
883  */
885 
886  /*
887  * Use a standard write lock here. It might be better to
888  * disallow access to the table while it's being synchronized.
889  * But we don't want to block the main apply process from
890  * working and it has to open the relation in RowExclusiveLock
891  * when remapping remote relation id to local one.
892  */
894 
895  /*
896  * Create a temporary slot for the sync process. We do this
897  * inside the transaction so that we can use the snapshot made
898  * by the slot to get existing data.
899  */
900  res = walrcv_exec(wrconn,
901  "BEGIN READ ONLY ISOLATION LEVEL "
902  "REPEATABLE READ", 0, NULL);
903  if (res->status != WALRCV_OK_COMMAND)
904  ereport(ERROR,
905  (errmsg("table copy could not start transaction on publisher"),
906  errdetail("The error was: %s", res->err)));
907  walrcv_clear_result(res);
908 
909  /*
910  * Create new temporary logical decoding slot.
911  *
912  * We'll use slot for data copy so make sure the snapshot is
913  * used for the transaction; that way the COPY will get data
914  * that is consistent with the lsn used by the slot to start
915  * decoding.
916  */
917  walrcv_create_slot(wrconn, slotname, true,
918  CRS_USE_SNAPSHOT, origin_startpos);
919 
921  copy_table(rel);
923 
924  res = walrcv_exec(wrconn, "COMMIT", 0, NULL);
925  if (res->status != WALRCV_OK_COMMAND)
926  ereport(ERROR,
927  (errmsg("table copy could not finish transaction on publisher"),
928  errdetail("The error was: %s", res->err)));
929  walrcv_clear_result(res);
930 
931  heap_close(rel, NoLock);
932 
933  /* Make the copy visible. */
935 
936  /*
937  * We are done with the initial data synchronization, update
938  * the state.
939  */
942  MyLogicalRepWorker->relstate_lsn = *origin_startpos;
944 
945  /* Wait for main apply worker to tell us to catchup. */
947 
948  /*----------
949  * There are now two possible states here:
950  * a) Sync is behind the apply. If that's the case we need to
951  * catch up with it by consuming the logical replication
952  * stream up to the relstate_lsn. For that, we exit this
953  * function and continue in ApplyWorkerMain().
954  * b) Sync is caught up with the apply. So it can just set
955  * the state to SYNCDONE and finish.
956  *----------
957  */
958  if (*origin_startpos >= MyLogicalRepWorker->relstate_lsn)
959  {
960  /*
961  * Update the new state in catalog. No need to bother
962  * with the shmem state as we are exiting for good.
963  */
967  *origin_startpos,
968  true);
969  finish_sync_worker();
970  }
971  break;
972  }
974  case SUBREL_STATE_READY:
976 
977  /*
978  * Nothing to do here but finish. (UNKNOWN means the relation was
979  * removed from pg_subscription_rel before the sync worker could
980  * start.)
981  */
982  finish_sync_worker();
983  break;
984  default:
985  elog(ERROR, "unknown relation state \"%c\"",
987  }
988 
989  return slotname;
990 }
Subscription * MySubscription
Definition: worker.c:112
#define SUBREL_STATE_INIT
WalReceiverConn * wrconn
Definition: worker.c:110
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define SUBREL_STATE_DATASYNC
void CommitTransactionCommand(void)
Definition: xact.c:2744
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
static void copy_table(Relation rel)
Definition: tablesync.c:762
void PopActiveSnapshot(void)
Definition: snapmgr.c:812
#define heap_close(r, l)
Definition: heapam.h:97
#define walrcv_create_slot(conn, slotname, temporary, snapshot_action, lsn)
Definition: walreceiver.h:261
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:304
#define SUBREL_STATE_SYNCWAIT
XLogRecPtr relstate_lsn
#define NAMEDATALEN
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:753
#define SpinLockAcquire(lock)
Definition: spin.h:62
static void walrcv_clear_result(WalRcvExecResult *walres)
Definition: walreceiver.h:269
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:63
#define ERROR
Definition: elog.h:43
#define SUBREL_STATE_UNKNOWN
#define NoLock
Definition: lockdefs.h:34
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:733
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:873
#define ereport(elevel, rest)
Definition: elog.h:122
#define SpinLockRelease(lock)
Definition: spin.h:64
Oid SetSubscriptionRelState(Oid subid, Oid relid, char state, XLogRecPtr sublsn, bool update_only)
#define SUBREL_STATE_SYNCDONE
void CommandCounterIncrement(void)
Definition: xact.c:915
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
uint64 XLogRecPtr
Definition: xlogdefs.h:21
WalRcvExecStatus status
Definition: walreceiver.h:188
void StartTransactionCommand(void)
Definition: xact.c:2673
char GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn, bool missing_ok)
int errmsg(const char *fmt,...)
Definition: elog.c:797
#define elog
Definition: elog.h:219
static bool wait_for_worker_state_change(char expected_state)
Definition: tablesync.c:218
#define SUBREL_STATE_READY
#define SUBREL_STATE_CATCHUP
#define walrcv_exec(conn, exec, nRetTypes, retTypes)
Definition: walreceiver.h:263
void pgstat_report_stat(bool force)
Definition: pgstat.c:812
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:243

◆ process_syncing_tables()

void process_syncing_tables ( XLogRecPtr  current_lsn)

Definition at line 544 of file tablesync.c.

References am_tablesync_worker(), process_syncing_tables_for_apply(), and process_syncing_tables_for_sync().

Referenced by apply_handle_commit(), and LogicalRepApplyLoop().

545 {
546  if (am_tablesync_worker())
547  process_syncing_tables_for_sync(current_lsn);
548  else
550 }
static void process_syncing_tables_for_apply(XLogRecPtr current_lsn)
Definition: tablesync.c:336
static bool am_tablesync_worker(void)
static void process_syncing_tables_for_sync(XLogRecPtr current_lsn)
Definition: tablesync.c:285

Variable Documentation

◆ ApplyContext

MemoryContext ApplyContext

Definition at line 108 of file worker.c.

◆ in_remote_transaction

bool in_remote_transaction

◆ MyLogicalRepWorker

◆ MySubscription

◆ wrconn