PostgreSQL Source Code  git master
 All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Macros
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

Function Documentation

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:538
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:63
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
int logicalrep_sync_worker_count ( Oid  subid)

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

714 {
715  int i;
716  int res = 0;
717 
718  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
719 
720  /* Search for attached worker for a given subscription id. */
721  for (i = 0; i < max_logical_replication_workers; i++)
722  {
724 
725  if (w->subid == subid && OidIsValid(w->relid))
726  res++;
727  }
728 
729  return res;
730 }
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1831
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:71
#define OidIsValid(objectId)
Definition: c.h:538
#define Assert(condition)
Definition: c.h:676
int max_logical_replication_workers
Definition: launcher.c:60
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:74
int i
void logicalrep_worker_attach ( int  slot)

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

605 {
606  /* Block concurrent access. */
607  LWLockAcquire(LogicalRepWorkerLock, LW_EXCLUSIVE);
608 
609  Assert(slot >= 0 && slot < max_logical_replication_workers);
611 
613  {
614  LWLockRelease(LogicalRepWorkerLock);
615  ereport(ERROR,
616  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
617  errmsg("logical replication worker slot %d is empty, cannot attach",
618  slot)));
619  }
620 
622  {
623  LWLockRelease(LogicalRepWorkerLock);
624  ereport(ERROR,
625  (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
626  errmsg("logical replication worker slot %d is already used by "
627  "another worker, cannot attach", slot)));
628  }
629 
632 
633  LWLockRelease(LogicalRepWorkerLock);
634 }
PGPROC * MyProc
Definition: proc.c:67
LogicalRepWorker workers[FLEXIBLE_ARRAY_MEMBER]
Definition: launcher.c:71
int errcode(int sqlerrcode)
Definition: elog.c:575
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:63
#define ERROR
Definition: elog.h:43
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition: ipc.c:320
#define ereport(elevel, rest)
Definition: elog.h:122
static void logicalrep_worker_onexit(int code, Datum arg)
Definition: launcher.c:683
uintptr_t Datum
Definition: postgres.h:372
#define Assert(condition)
Definition: c.h:676
int max_logical_replication_workers
Definition: launcher.c:60
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
int errmsg(const char *fmt,...)
Definition: elog.c:797
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:74
LogicalRepWorker* logicalrep_worker_find ( Oid  subid,
Oid  relid,
bool  only_running 
)

Definition at line 237 of file launcher.c.

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

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

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

Definition at line 288 of file launcher.c.

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

Referenced by ApplyLauncherMain(), and process_syncing_tables_for_apply().

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

Definition at line 447 of file launcher.c.

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

Referenced by AtEOXact_ApplyLauncher(), and DropSubscription().

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

Definition at line 552 of file launcher.c.

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

Referenced by AlterSubscription_refresh(), and DropSubscription().

553 {
554  LogicalRepWorkerId *wid;
555  MemoryContext oldctx;
556 
557  /* Make sure we store the info in context that survives until commit. */
559 
560  wid = palloc(sizeof(LogicalRepWorkerId));
561  wid->subid = subid;
562  wid->relid = relid;
563 
565 
566  MemoryContextSwitchTo(oldctx);
567 }
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:849
static List * on_commit_stop_workers
Definition: launcher.c:82
void logicalrep_worker_wakeup ( Oid  subid,
Oid  relid 
)

Definition at line 573 of file launcher.c.

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

Referenced by pg_attribute_noreturn().

574 {
575  LogicalRepWorker *worker;
576 
577  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
578 
579  worker = logicalrep_worker_find(subid, relid, true);
580 
581  if (worker)
583 
584  LWLockRelease(LogicalRepWorkerLock);
585 }
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1715
void logicalrep_worker_wakeup_ptr(LogicalRepWorker *worker)
Definition: launcher.c:593
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:237
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1111
void logicalrep_worker_wakeup_ptr ( LogicalRepWorker worker)

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

594 {
595  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
596 
597  SetLatch(&worker->proc->procLatch);
598 }
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1831
Latch procLatch
Definition: proc.h:103
void SetLatch(volatile Latch *latch)
Definition: latch.c:414
#define Assert(condition)
Definition: c.h:676
List* logicalrep_workers_find ( Oid  subid,
bool  only_running 
)

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

266 {
267  int i;
268  List *res = NIL;
269 
270  Assert(LWLockHeldByMe(LogicalRepWorkerLock));
271 
272  /* Search for attached worker for a given subscription id. */
273  for (i = 0; i < max_logical_replication_workers; i++)
274  {
276 
277  if (w->in_use && w->subid == subid && (!only_running || w->proc))
278  res = lappend(res, w);
279  }
280 
281  return res;
282 }
#define NIL
Definition: pg_list.h:69
bool LWLockHeldByMe(LWLock *l)
Definition: lwlock.c:1831
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:676
int max_logical_replication_workers
Definition: launcher.c:60
LogicalRepCtxStruct * LogicalRepCtx
Definition: launcher.c:74
int i
Definition: pg_list.h:45
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, NULL, 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:2750
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:260
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:304
#define SUBREL_STATE_SYNCWAIT
XLogRecPtr relstate_lsn
#define NAMEDATALEN
#define StaticAssertStmt(condition, errmessage)
Definition: c.h:758
#define SpinLockAcquire(lock)
Definition: spin.h:62
static void walrcv_clear_result(WalRcvExecResult *walres)
Definition: walreceiver.h:268
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:922
Relation heap_open(Oid relationId, LOCKMODE lockmode)
Definition: heapam.c:1290
#define NULL
Definition: c.h:229
uint64 XLogRecPtr
Definition: xlogdefs.h:21
WalRcvExecStatus status
Definition: walreceiver.h:187
void StartTransactionCommand(void)
Definition: xact.c:2680
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:262
void pgstat_report_stat(bool force)
Definition: pgstat.c:812
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:242
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

MemoryContext ApplyContext

Definition at line 108 of file worker.c.

bool in_remote_transaction