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:645
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57

◆ invalidate_syncing_table_states()

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

Definition at line 256 of file tablesync.c.

References table_states_valid.

Referenced by ApplyWorkerMain().

257 {
258  table_states_valid = false;
259 }
static bool table_states_valid
Definition: tablesync.c:106

◆ logicalrep_sync_worker_count()

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:1843
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:65
#define OidIsValid(objectId)
Definition: c.h:645
#define Assert(condition)
Definition: c.h:739
int max_logical_replication_workers
Definition: launcher.c:54
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:68
int i

◆ logicalrep_worker_attach()

void logicalrep_worker_attach ( int  slot)

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

626 {
627  /* Block concurrent access. */
628  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
629 
630  Assert(slot >= 0 && slot < max_logical_replication_workers);
632 
634  {
635  LWLockRelease(LogicalRepWorkerLock);
636  ereport(ERROR,
637  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
638  errmsg("logical replication worker slot %d is empty, cannot attach",
639  slot)));
640  }
641 
643  {
644  LWLockRelease(LogicalRepWorkerLock);
645  ereport(ERROR,
646  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
647  errmsg("logical replication worker slot %d is already used by "
648  "another worker, cannot attach", slot)));
649  }
650 
653 
654  LWLockRelease(LogicalRepWorkerLock);
655 }
PGPROC * MyProc
Definition: proc.c:67
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:65
int errcode(int sqlerrcode)
Definition: elog.c:608
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1727
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
#define ERROR
Definition: elog.h:43
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:333
#define ereport(elevel, rest)
Definition: elog.h:141
static void logicalrep_worker_onexit(int code, Datum arg)
Definition: launcher.c:704
uintptr_t Datum
Definition: postgres.h:367
#define Assert(condition)
Definition: c.h:739
int max_logical_replication_workers
Definition: launcher.c:54
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1123
int errmsg(const char *fmt,...)
Definition: elog.c:822
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:68

◆ logicalrep_worker_find()

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

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

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

◆ logicalrep_worker_launch()

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

Definition at line 282 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, TIMESTAMP_NOBEGIN, TimestampDifferenceExceeds(), LogicalRepWorker::userid, WaitForReplicationWorkerAttach(), wal_receiver_timeout, WARNING, and LogicalRepCtxStruct::workers.

Referenced by ApplyLauncherMain(), and process_syncing_tables_for_apply().

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

◆ logicalrep_worker_stop()

void logicalrep_worker_stop ( Oid  subid,
Oid  relid 
)

Definition at line 452 of file launcher.c.

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

Referenced by AtEOXact_ApplyLauncher(), and DropSubscription().

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

◆ logicalrep_worker_stop_at_commit()

void logicalrep_worker_stop_at_commit ( Oid  subid,
Oid  relid 
)

Definition at line 549 of file launcher.c.

References Assert, GetCurrentTransactionNestLevel(), lappend(), MemoryContextSwitchTo(), StopWorkersData::nestDepth, NIL, on_commit_stop_workers, palloc(), StopWorkersData::parent, LogicalRepWorkerId::relid, LogicalRepWorkerId::subid, TopTransactionContext, and StopWorkersData::workers.

Referenced by AlterSubscription_refresh().

550 {
551  int nestDepth = GetCurrentTransactionNestLevel();
552  LogicalRepWorkerId *wid;
553  MemoryContext oldctx;
554 
555  /* Make sure we store the info in context that survives until commit. */
557 
558  /* Check that previous transactions were properly cleaned up. */
559  Assert(on_commit_stop_workers == NULL ||
560  nestDepth >= on_commit_stop_workers->nestDepth);
561 
562  /*
563  * Push a new stack element if we don't already have one for the current
564  * nestDepth.
565  */
566  if (on_commit_stop_workers == NULL ||
567  nestDepth > on_commit_stop_workers->nestDepth)
568  {
569  StopWorkersData *newdata = palloc(sizeof(StopWorkersData));
570 
571  newdata->nestDepth = nestDepth;
572  newdata->workers = NIL;
573  newdata->parent = on_commit_stop_workers;
574  on_commit_stop_workers = newdata;
575  }
576 
577  /*
578  * Finally add a new worker into the worker list of the current
579  * subtransaction.
580  */
581  wid = palloc(sizeof(LogicalRepWorkerId));
582  wid->subid = subid;
583  wid->relid = relid;
586 
587  MemoryContextSwitchTo(oldctx);
588 }
#define NIL
Definition: pg_list.h:65
MemoryContext TopTransactionContext
Definition: mcxt.c:49
List * workers
Definition: launcher.c:79
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
static StopWorkersData * on_commit_stop_workers
Definition: launcher.c:88
List * lappend(List *list, void *datum)
Definition: list.c:322
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:841
#define Assert(condition)
Definition: c.h:739
struct StopWorkersData * parent
Definition: launcher.c:80
void * palloc(Size size)
Definition: mcxt.c:949

◆ logicalrep_worker_wakeup()

void logicalrep_worker_wakeup ( Oid  subid,
Oid  relid 
)

Definition at line 594 of file launcher.c.

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

Referenced by pg_attribute_noreturn().

595 {
596  LogicalRepWorker *worker;
597 
598  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
599 
600  worker = logicalrep_worker_find(subid, relid, true);
601 
602  if (worker)
604 
605  LWLockRelease(LogicalRepWorkerLock);
606 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1727
void logicalrep_worker_wakeup_ptr(LogicalRepWorker *worker)
Definition: launcher.c:614
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:231
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1123

◆ logicalrep_worker_wakeup_ptr()

void logicalrep_worker_wakeup_ptr ( LogicalRepWorker worker)

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

615 {
616  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
617 
618  SetLatch(&worker->proc->procLatch);
619 }
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1843
void SetLatch(Latch *latch)
Definition: latch.c:448
Latch procLatch
Definition: proc.h:104
#define Assert(condition)
Definition: c.h:739

◆ logicalrep_workers_find()

List* logicalrep_workers_find ( Oid  subid,
bool  only_running 
)

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

260 {
261  int i;
262  List *res = NIL;
263 
264  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
265 
266  /* Search for attached worker for a given subscription id. */
267  for (i = 0; i < max_logical_replication_workers; i++)
268  {
270 
271  if (w->in_use && w->subid == subid && (!only_running || w->proc))
272  res = lappend(res, w);
273  }
274 
275  return res;
276 }
#define NIL
Definition: pg_list.h:65
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1843
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:65
List * lappend(List *list, void *datum)
Definition: list.c:322
#define Assert(condition)
Definition: c.h:739
int max_logical_replication_workers
Definition: launcher.c:54
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:68
int i
Definition: pg_list.h:50

◆ LogicalRepSyncTableStart()

char* LogicalRepSyncTableStart ( XLogRecPtr origin_startpos)

Definition at line 798 of file tablesync.c.

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

Referenced by ApplyWorkerMain().

799 {
800  char *slotname;
801  char *err;
802  char relstate;
803  XLogRecPtr relstate_lsn;
804 
805  /* Check the state of the table synchronization. */
809  &relstate_lsn, true);
811 
813  MyLogicalRepWorker->relstate = relstate;
814  MyLogicalRepWorker->relstate_lsn = relstate_lsn;
816 
817  /*
818  * To build a slot name for the sync work, we are limited to NAMEDATALEN -
819  * 1 characters. We cut the original slot name to NAMEDATALEN - 28 chars
820  * and append _%u_sync_%u (1 + 10 + 6 + 10 + '\0'). (It's actually the
821  * NAMEDATALEN on the remote that matters, but this scheme will also work
822  * reasonably if that is different.)
823  */
824  StaticAssertStmt(NAMEDATALEN >= 32, "NAMEDATALEN too small"); /* for sanity */
825  slotname = psprintf("%.*s_%u_sync_%u",
826  NAMEDATALEN - 28,
830 
831  /*
832  * Here we use the slot name instead of the subscription name as the
833  * application_name, so that it is different from the main apply worker,
834  * so that synchronous replication can distinguish them.
835  */
836  wrconn = walrcv_connect(MySubscription->conninfo, true, slotname, &err);
837  if (wrconn == NULL)
838  ereport(ERROR,
839  (errmsg("could not connect to the publisher: %s", err)));
840 
841  switch (MyLogicalRepWorker->relstate)
842  {
843  case SUBREL_STATE_INIT:
844  case SUBREL_STATE_DATASYNC:
845  {
846  Relation rel;
847  WalRcvExecResult *res;
848 
850  MyLogicalRepWorker->relstate = SUBREL_STATE_DATASYNC;
853 
854  /* Update the state and make it visible to others. */
861  pgstat_report_stat(false);
862 
863  /*
864  * We want to do the table data sync in a single transaction.
865  */
867 
868  /*
869  * Use a standard write lock here. It might be better to
870  * disallow access to the table while it's being synchronized.
871  * But we don't want to block the main apply process from
872  * working and it has to open the relation in RowExclusiveLock
873  * when remapping remote relation id to local one.
874  */
876 
877  /*
878  * Create a temporary slot for the sync process. We do this
879  * inside the transaction so that we can use the snapshot made
880  * by the slot to get existing data.
881  */
882  res = walrcv_exec(wrconn,
883  "BEGIN READ ONLY ISOLATION LEVEL "
884  "REPEATABLE READ", 0, NULL);
885  if (res->status != WALRCV_OK_COMMAND)
886  ereport(ERROR,
887  (errmsg("table copy could not start transaction on publisher"),
888  errdetail("The error was: %s", res->err)));
889  walrcv_clear_result(res);
890 
891  /*
892  * Create new temporary logical decoding slot.
893  *
894  * We'll use slot for data copy so make sure the snapshot is
895  * used for the transaction; that way the COPY will get data
896  * that is consistent with the lsn used by the slot to start
897  * decoding.
898  */
899  walrcv_create_slot(wrconn, slotname, true,
900  CRS_USE_SNAPSHOT, origin_startpos);
901 
903  copy_table(rel);
905 
906  res = walrcv_exec(wrconn, "COMMIT", 0, NULL);
907  if (res->status != WALRCV_OK_COMMAND)
908  ereport(ERROR,
909  (errmsg("table copy could not finish transaction on publisher"),
910  errdetail("The error was: %s", res->err)));
911  walrcv_clear_result(res);
912 
913  table_close(rel, NoLock);
914 
915  /* Make the copy visible. */
917 
918  /*
919  * We are done with the initial data synchronization, update
920  * the state.
921  */
923  MyLogicalRepWorker->relstate = SUBREL_STATE_SYNCWAIT;
924  MyLogicalRepWorker->relstate_lsn = *origin_startpos;
926 
927  /* Wait for main apply worker to tell us to catchup. */
928  wait_for_worker_state_change(SUBREL_STATE_CATCHUP);
929 
930  /*----------
931  * There are now two possible states here:
932  * a) Sync is behind the apply. If that's the case we need to
933  * catch up with it by consuming the logical replication
934  * stream up to the relstate_lsn. For that, we exit this
935  * function and continue in ApplyWorkerMain().
936  * b) Sync is caught up with the apply. So it can just set
937  * the state to SYNCDONE and finish.
938  *----------
939  */
940  if (*origin_startpos >= MyLogicalRepWorker->relstate_lsn)
941  {
942  /*
943  * Update the new state in catalog. No need to bother
944  * with the shmem state as we are exiting for good.
945  */
948  SUBREL_STATE_SYNCDONE,
949  *origin_startpos);
950  finish_sync_worker();
951  }
952  break;
953  }
954  case SUBREL_STATE_SYNCDONE:
955  case SUBREL_STATE_READY:
956  case SUBREL_STATE_UNKNOWN:
957 
958  /*
959  * Nothing to do here but finish. (UNKNOWN means the relation was
960  * removed from pg_subscription_rel before the sync worker could
961  * start.)
962  */
963  finish_sync_worker();
964  break;
965  default:
966  elog(ERROR, "unknown relation state \"%c\"",
968  }
969 
970  return slotname;
971 }
Subscription * MySubscription
Definition: worker.c:103
WalReceiverConn * wrconn
Definition: worker.c:101
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:133
void CommitTransactionCommand(void)
Definition: xact.c:2898
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
static void copy_table(Relation rel)
Definition: tablesync.c:744
void PopActiveSnapshot(void)
Definition: snapmgr.c:814
#define walrcv_create_slot(conn, slotname, temporary, snapshot_action, lsn)
Definition: walreceiver.h:286
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:306
XLogRecPtr relstate_lsn
#define NAMEDATALEN
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:853
#define SpinLockAcquire(lock)
Definition: spin.h:62
static void walrcv_clear_result(WalRcvExecResult *walres)
Definition: walreceiver.h:296
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
#define ERROR
Definition: elog.h:43
#define NoLock
Definition: lockdefs.h:34
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:735
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:955
#define ereport(elevel, rest)
Definition: elog.h:141
#define SpinLockRelease(lock)
Definition: spin.h:64
void CommandCounterIncrement(void)
Definition: xact.c:1005
void UpdateSubscriptionRelState(Oid subid, Oid relid, char state, XLogRecPtr sublsn)
uint64 XLogRecPtr
Definition: xlogdefs.h:21
WalRcvExecStatus status
Definition: walreceiver.h:202
void StartTransactionCommand(void)
Definition: xact.c:2797
char GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn, bool missing_ok)
int errmsg(const char *fmt,...)
Definition: elog.c:822
#define elog(elevel,...)
Definition: elog.h:228
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
static bool wait_for_worker_state_change(char expected_state)
Definition: tablesync.c:207
#define walrcv_exec(conn, exec, nRetTypes, retTypes)
Definition: walreceiver.h:290
void pgstat_report_stat(bool force)
Definition: pgstat.c:806
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:264

◆ process_syncing_tables()

void process_syncing_tables ( XLogRecPtr  current_lsn)

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

530 {
531  if (am_tablesync_worker())
532  process_syncing_tables_for_sync(current_lsn);
533  else
535 }
static void process_syncing_tables_for_apply(XLogRecPtr current_lsn)
Definition: tablesync.c:320
static bool am_tablesync_worker(void)
static void process_syncing_tables_for_sync(XLogRecPtr current_lsn)
Definition: tablesync.c:270

Variable Documentation

◆ ApplyContext

MemoryContext ApplyContext

Definition at line 99 of file worker.c.

◆ in_remote_transaction

bool in_remote_transaction

◆ MyLogicalRepWorker

◆ MySubscription

◆ wrconn