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 "storage/spin.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

◆ invalidate_syncing_table_states()

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

Definition at line 257 of file tablesync.c.

References table_states_valid.

Referenced by ApplyWorkerMain().

258 {
259  table_states_valid = false;
260 }
static bool table_states_valid
Definition: tablesync.c:111

◆ logicalrep_sync_worker_count()

int logicalrep_sync_worker_count ( Oid  subid)

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

725 {
726  int i;
727  int res = 0;
728 
729  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
730 
731  /* Search for attached worker for a given subscription id. */
732  for (i = 0; i < max_logical_replication_workers; i++)
733  {
735 
736  if (w->subid == subid && OidIsValid(w->relid))
737  res++;
738  }
739 
740  return res;
741 }
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1927
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:65
#define OidIsValid(objectId)
Definition: c.h:706
#define Assert(condition)
Definition: c.h:800
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 629 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().

630 {
631  /* Block concurrent access. */
632  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
633 
634  Assert(slot >= 0 && slot < max_logical_replication_workers);
636 
638  {
639  LWLockRelease(LogicalRepWorkerLock);
640  ereport(ERROR,
641  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
642  errmsg("logical replication worker slot %d is empty, cannot attach",
643  slot)));
644  }
645 
647  {
648  LWLockRelease(LogicalRepWorkerLock);
649  ereport(ERROR,
650  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
651  errmsg("logical replication worker slot %d is already used by "
652  "another worker, cannot attach", slot)));
653  }
654 
657 
658  LWLockRelease(LogicalRepWorkerLock);
659 }
PGPROC * MyProc
Definition: proc.c:67
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:65
int errcode(int sqlerrcode)
Definition: elog.c:691
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1811
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
static void logicalrep_worker_onexit(int code, Datum arg)
Definition: launcher.c:708
uintptr_t Datum
Definition: postgres.h:367
#define ereport(elevel,...)
Definition: elog.h:155
#define Assert(condition)
Definition: c.h:800
int max_logical_replication_workers
Definition: launcher.c:54
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1207
int errmsg(const char *fmt,...)
Definition: elog.c:902
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:68

◆ logicalrep_worker_find()

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

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

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

288 {
289  BackgroundWorker bgw;
290  BackgroundWorkerHandle *bgw_handle;
291  uint16 generation;
292  int i;
293  int slot = 0;
294  LogicalRepWorker *worker = NULL;
295  int nsyncworkers;
297 
298  ereport(DEBUG1,
299  (errmsg("starting logical replication worker for subscription \"%s\"",
300  subname)));
301 
302  /* Report this after the initial starting message for consistency. */
303  if (max_replication_slots == 0)
304  ereport(ERROR,
305  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
306  errmsg("cannot start logical replication workers when max_replication_slots = 0")));
307 
308  /*
309  * We need to do the modification of the shared memory under lock so that
310  * we have consistent view.
311  */
312  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
313 
314 retry:
315  /* Find unused worker slot. */
316  for (i = 0; i < max_logical_replication_workers; i++)
317  {
319 
320  if (!w->in_use)
321  {
322  worker = w;
323  slot = i;
324  break;
325  }
326  }
327 
328  nsyncworkers = logicalrep_sync_worker_count(subid);
329 
330  now = GetCurrentTimestamp();
331 
332  /*
333  * If we didn't find a free slot, try to do garbage collection. The
334  * reason we do this is because if some worker failed to start up and its
335  * parent has crashed while waiting, the in_use state was never cleared.
336  */
337  if (worker == NULL || nsyncworkers >= max_sync_workers_per_subscription)
338  {
339  bool did_cleanup = false;
340 
341  for (i = 0; i < max_logical_replication_workers; i++)
342  {
344 
345  /*
346  * If the worker was marked in use but didn't manage to attach in
347  * time, clean it up.
348  */
349  if (w->in_use && !w->proc &&
352  {
353  elog(WARNING,
354  "logical replication worker for subscription %u took too long to start; canceled",
355  w->subid);
356 
358  did_cleanup = true;
359  }
360  }
361 
362  if (did_cleanup)
363  goto retry;
364  }
365 
366  /*
367  * If we reached the sync worker limit per subscription, just exit
368  * silently as we might get here because of an otherwise harmless race
369  * condition.
370  */
371  if (nsyncworkers >= max_sync_workers_per_subscription)
372  {
373  LWLockRelease(LogicalRepWorkerLock);
374  return;
375  }
376 
377  /*
378  * However if there are no more free worker slots, inform user about it
379  * before exiting.
380  */
381  if (worker == NULL)
382  {
383  LWLockRelease(LogicalRepWorkerLock);
385  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
386  errmsg("out of logical replication worker slots"),
387  errhint("You might need to increase max_logical_replication_workers.")));
388  return;
389  }
390 
391  /* Prepare the worker slot. */
392  worker->launch_time = now;
393  worker->in_use = true;
394  worker->generation++;
395  worker->proc = NULL;
396  worker->dbid = dbid;
397  worker->userid = userid;
398  worker->subid = subid;
399  worker->relid = relid;
400  worker->relstate = SUBREL_STATE_UNKNOWN;
402  worker->last_lsn = InvalidXLogRecPtr;
405  worker->reply_lsn = InvalidXLogRecPtr;
406  TIMESTAMP_NOBEGIN(worker->reply_time);
407 
408  /* Before releasing lock, remember generation for future identification. */
409  generation = worker->generation;
410 
411  LWLockRelease(LogicalRepWorkerLock);
412 
413  /* Register the new dynamic worker. */
414  memset(&bgw, 0, sizeof(bgw));
418  snprintf(bgw.bgw_library_name, BGW_MAXLEN, "postgres");
419  snprintf(bgw.bgw_function_name, BGW_MAXLEN, "ApplyWorkerMain");
420  if (OidIsValid(relid))
422  "logical replication worker for subscription %u sync %u", subid, relid);
423  else
425  "logical replication worker for subscription %u", subid);
426  snprintf(bgw.bgw_type, BGW_MAXLEN, "logical replication worker");
427 
430  bgw.bgw_main_arg = Int32GetDatum(slot);
431 
432  if (!RegisterDynamicBackgroundWorker(&bgw, &bgw_handle))
433  {
434  /* Failed to start worker, so clean up the worker slot. */
435  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
436  Assert(generation == worker->generation);
438  LWLockRelease(LogicalRepWorkerLock);
439 
441  (errcode(ERRCODE_CONFIGURATION_LIMIT_EXCEEDED),
442  errmsg("out of background worker slots"),
443  errhint("You might need to increase max_worker_processes.")));
444  return;
445  }
446 
447  /* Now wait until it attaches. */
448  WaitForReplicationWorkerAttach(worker, generation, bgw_handle);
449 }
#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:1149
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1578
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:691
NameData subname
#define BGWORKER_SHMEM_ACCESS
Definition: bgworker.h:52
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1709
#define OidIsValid(objectId)
Definition: c.h:706
char bgw_function_name[BGW_MAXLEN]
Definition: bgworker.h:96
int wal_receiver_timeout
Definition: walreceiver.c:89
XLogRecPtr relstate_lsn
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1811
Datum bgw_main_arg
Definition: bgworker.h:97
unsigned short uint16
Definition: c.h:428
#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:679
#define BGW_NEVER_RESTART
Definition: bgworker.h:84
#define TIMESTAMP_NOBEGIN(j)
Definition: timestamp.h:112
#define WARNING
Definition: elog.h:40
int logicalrep_sync_worker_count(Oid subid)
Definition: launcher.c:724
static void WaitForReplicationWorkerAttach(LogicalRepWorker *worker, uint16 generation, BackgroundWorkerHandle *handle)
Definition: launcher.c:177
#define ereport(elevel,...)
Definition: elog.h:155
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:800
#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:918
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1207
#define Int32GetDatum(X)
Definition: postgres.h:479
char bgw_type[BGW_MAXLEN]
Definition: bgworker.h:91
int errmsg(const char *fmt,...)
Definition: elog.c:902
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:215
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1542
TimestampTz reply_time

◆ logicalrep_worker_stop()

void logicalrep_worker_stop ( Oid  subid,
Oid  relid 
)

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

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

554 {
555  int nestDepth = GetCurrentTransactionNestLevel();
556  LogicalRepWorkerId *wid;
557  MemoryContext oldctx;
558 
559  /* Make sure we store the info in context that survives until commit. */
561 
562  /* Check that previous transactions were properly cleaned up. */
563  Assert(on_commit_stop_workers == NULL ||
564  nestDepth >= on_commit_stop_workers->nestDepth);
565 
566  /*
567  * Push a new stack element if we don't already have one for the current
568  * nestDepth.
569  */
570  if (on_commit_stop_workers == NULL ||
571  nestDepth > on_commit_stop_workers->nestDepth)
572  {
573  StopWorkersData *newdata = palloc(sizeof(StopWorkersData));
574 
575  newdata->nestDepth = nestDepth;
576  newdata->workers = NIL;
577  newdata->parent = on_commit_stop_workers;
578  on_commit_stop_workers = newdata;
579  }
580 
581  /*
582  * Finally add a new worker into the worker list of the current
583  * subtransaction.
584  */
585  wid = palloc(sizeof(LogicalRepWorkerId));
586  wid->subid = subid;
587  wid->relid = relid;
590 
591  MemoryContextSwitchTo(oldctx);
592 }
#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:321
int GetCurrentTransactionNestLevel(void)
Definition: xact.c:857
#define Assert(condition)
Definition: c.h:800
struct StopWorkersData * parent
Definition: launcher.c:80
void * palloc(Size size)
Definition: mcxt.c:950

◆ logicalrep_worker_wakeup()

void logicalrep_worker_wakeup ( Oid  subid,
Oid  relid 
)

Definition at line 598 of file launcher.c.

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

Referenced by pg_attribute_noreturn().

599 {
600  LogicalRepWorker *worker;
601 
602  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
603 
604  worker = logicalrep_worker_find(subid, relid, true);
605 
606  if (worker)
608 
609  LWLockRelease(LogicalRepWorkerLock);
610 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1811
void logicalrep_worker_wakeup_ptr(LogicalRepWorker *worker)
Definition: launcher.c:618
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:235
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1207

◆ logicalrep_worker_wakeup_ptr()

void logicalrep_worker_wakeup_ptr ( LogicalRepWorker worker)

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

619 {
620  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
621 
622  SetLatch(&worker->proc->procLatch);
623 }
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1927
void SetLatch(Latch *latch)
Definition: latch.c:505
Latch procLatch
Definition: proc.h:129
#define Assert(condition)
Definition: c.h:800

◆ logicalrep_workers_find()

List* logicalrep_workers_find ( Oid  subid,
bool  only_running 
)

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

264 {
265  int i;
266  List *res = NIL;
267 
268  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
269 
270  /* Search for attached worker for a given subscription id. */
271  for (i = 0; i < max_logical_replication_workers; i++)
272  {
274 
275  if (w->in_use && w->subid == subid && (!only_running || w->proc))
276  res = lappend(res, w);
277  }
278 
279  return res;
280 }
#define NIL
Definition: pg_list.h:65
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1927
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:65
List * lappend(List *list, void *datum)
Definition: list.c:321
#define Assert(condition)
Definition: c.h:800
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 820 of file tablesync.c.

References Assert, CommandCounterIncrement(), CommitTransactionCommand(), Subscription::conninfo, copy_table(), CRS_USE_SNAPSHOT, 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().

821 {
822  char *slotname;
823  char *err;
824  char relstate;
825  XLogRecPtr relstate_lsn;
826  Relation rel;
827  WalRcvExecResult *res;
828 
829  /* Check the state of the table synchronization. */
833  &relstate_lsn);
835 
837  MyLogicalRepWorker->relstate = relstate;
838  MyLogicalRepWorker->relstate_lsn = relstate_lsn;
840 
841  /*
842  * If synchronization is already done or no longer necessary, exit now
843  * that we've updated shared memory state.
844  */
845  switch (relstate)
846  {
847  case SUBREL_STATE_SYNCDONE:
848  case SUBREL_STATE_READY:
849  case SUBREL_STATE_UNKNOWN:
850  finish_sync_worker(); /* doesn't return */
851  }
852 
853  /*
854  * To build a slot name for the sync work, we are limited to NAMEDATALEN -
855  * 1 characters. We cut the original slot name to NAMEDATALEN - 28 chars
856  * and append _%u_sync_%u (1 + 10 + 6 + 10 + '\0'). (It's actually the
857  * NAMEDATALEN on the remote that matters, but this scheme will also work
858  * reasonably if that is different.)
859  */
860  StaticAssertStmt(NAMEDATALEN >= 32, "NAMEDATALEN too small"); /* for sanity */
861  slotname = psprintf("%.*s_%u_sync_%u",
862  NAMEDATALEN - 28,
866 
867  /*
868  * Here we use the slot name instead of the subscription name as the
869  * application_name, so that it is different from the main apply worker,
870  * so that synchronous replication can distinguish them.
871  */
872  wrconn = walrcv_connect(MySubscription->conninfo, true, slotname, &err);
873  if (wrconn == NULL)
874  ereport(ERROR,
875  (errmsg("could not connect to the publisher: %s", err)));
876 
877  Assert(MyLogicalRepWorker->relstate == SUBREL_STATE_INIT ||
878  MyLogicalRepWorker->relstate == SUBREL_STATE_DATASYNC);
879 
881  MyLogicalRepWorker->relstate = SUBREL_STATE_DATASYNC;
884 
885  /* Update the state and make it visible to others. */
892  pgstat_report_stat(false);
893 
894  /*
895  * We want to do the table data sync in a single transaction.
896  */
898 
899  /*
900  * Use a standard write lock here. It might be better to disallow access
901  * to the table while it's being synchronized. But we don't want to block
902  * the main apply process from working and it has to open the relation in
903  * RowExclusiveLock when remapping remote relation id to local one.
904  */
906 
907  /*
908  * Start a transaction in the remote node in REPEATABLE READ mode. This
909  * ensures that both the replication slot we create (see below) and the
910  * COPY are consistent with each other.
911  */
912  res = walrcv_exec(wrconn,
913  "BEGIN READ ONLY ISOLATION LEVEL REPEATABLE READ",
914  0, NULL);
915  if (res->status != WALRCV_OK_COMMAND)
916  ereport(ERROR,
917  (errmsg("table copy could not start transaction on publisher"),
918  errdetail("The error was: %s", res->err)));
919  walrcv_clear_result(res);
920 
921  /*
922  * Create a new temporary logical decoding slot. This slot will be used
923  * for the catchup phase after COPY is done, so tell it to use the
924  * snapshot to make the final data consistent.
925  */
926  walrcv_create_slot(wrconn, slotname, true,
927  CRS_USE_SNAPSHOT, origin_startpos);
928 
929  /* Now do the initial data copy */
931  copy_table(rel);
933 
934  res = walrcv_exec(wrconn, "COMMIT", 0, NULL);
935  if (res->status != WALRCV_OK_COMMAND)
936  ereport(ERROR,
937  (errmsg("table copy could not finish transaction on publisher"),
938  errdetail("The error was: %s", res->err)));
939  walrcv_clear_result(res);
940 
941  table_close(rel, NoLock);
942 
943  /* Make the copy visible. */
945 
946  /*
947  * We are done with the initial data synchronization, update the state.
948  */
950  MyLogicalRepWorker->relstate = SUBREL_STATE_SYNCWAIT;
951  MyLogicalRepWorker->relstate_lsn = *origin_startpos;
953 
954  /*
955  * Finally, wait until the main apply worker tells us to catch up and then
956  * return to let LogicalRepApplyLoop do it.
957  */
958  wait_for_worker_state_change(SUBREL_STATE_CATCHUP);
959  return slotname;
960 }
Subscription * MySubscription
Definition: worker.c:161
WalReceiverConn * wrconn
Definition: worker.c:159
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
void CommitTransactionCommand(void)
Definition: xact.c:2948
char * psprintf(const char *fmt,...)
Definition: psprintf.c:46
static void copy_table(Relation rel)
Definition: tablesync.c:746
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
#define walrcv_create_slot(conn, slotname, temporary, snapshot_action, lsn)
Definition: walreceiver.h:420
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
XLogRecPtr relstate_lsn
#define NAMEDATALEN
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:914
#define SpinLockAcquire(lock)
Definition: spin.h:62
static void walrcv_clear_result(WalRcvExecResult *walres)
Definition: walreceiver.h:430
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:680
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:1035
#define SpinLockRelease(lock)
Definition: spin.h:64
char GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn)
void CommandCounterIncrement(void)
Definition: xact.c:1021
void UpdateSubscriptionRelState(Oid subid, Oid relid, char state, XLogRecPtr sublsn)
#define ereport(elevel,...)
Definition: elog.h:155
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:800
WalRcvExecStatus status
Definition: walreceiver.h:212
void StartTransactionCommand(void)
Definition: xact.c:2847
int errmsg(const char *fmt,...)
Definition: elog.c:902
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
static bool wait_for_worker_state_change(char expected_state)
Definition: tablesync.c:208
#define walrcv_exec(conn, exec, nRetTypes, retTypes)
Definition: walreceiver.h:424
void pgstat_report_stat(bool force)
Definition: pgstat.c:850
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:398

◆ process_syncing_tables()

void process_syncing_tables ( XLogRecPtr  current_lsn)

Definition at line 530 of file tablesync.c.

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

Referenced by apply_handle_commit(), apply_handle_stream_commit(), and LogicalRepApplyLoop().

531 {
532  if (am_tablesync_worker())
533  process_syncing_tables_for_sync(current_lsn);
534  else
536 }
static void process_syncing_tables_for_apply(XLogRecPtr current_lsn)
Definition: tablesync.c:321
static bool am_tablesync_worker(void)
static void process_syncing_tables_for_sync(XLogRecPtr current_lsn)
Definition: tablesync.c:271

Variable Documentation

◆ ApplyContext

MemoryContext ApplyContext

Definition at line 154 of file worker.c.

Referenced by apply_handle_stream_start().

◆ in_remote_transaction

◆ MyLogicalRepWorker

◆ MySubscription

◆ wrconn