PostgreSQL Source Code git master
Loading...
Searching...
No Matches
applyparallelworker.c File Reference
#include "postgres.h"
#include "libpq/pqformat.h"
#include "libpq/pqmq.h"
#include "pgstat.h"
#include "postmaster/interrupt.h"
#include "replication/logicallauncher.h"
#include "replication/logicalworker.h"
#include "replication/origin.h"
#include "replication/worker_internal.h"
#include "storage/ipc.h"
#include "storage/latch.h"
#include "storage/lmgr.h"
#include "storage/proc.h"
#include "tcop/tcopprot.h"
#include "utils/inval.h"
#include "utils/memutils.h"
#include "utils/syscache.h"
Include dependency graph for applyparallelworker.c:

Go to the source code of this file.

Data Structures

struct  ParallelApplyWorkerEntry
 

Macros

#define PG_LOGICAL_APPLY_SHM_MAGIC   0x787ca067
 
#define PARALLEL_APPLY_KEY_SHARED   1
 
#define PARALLEL_APPLY_KEY_MQ   2
 
#define PARALLEL_APPLY_KEY_ERROR_QUEUE   3
 
#define DSM_QUEUE_SIZE   (16 * 1024 * 1024)
 
#define DSM_ERROR_QUEUE_SIZE   (16 * 1024)
 
#define SIZE_STATS_MESSAGE   (2 * sizeof(XLogRecPtr) + sizeof(TimestampTz))
 
#define PARALLEL_APPLY_LOCK_STREAM   0
 
#define PARALLEL_APPLY_LOCK_XACT   1
 
#define SHM_SEND_RETRY_INTERVAL_MS   1000
 
#define SHM_SEND_TIMEOUT_MS   (10000 - SHM_SEND_RETRY_INTERVAL_MS)
 

Typedefs

typedef struct ParallelApplyWorkerEntry ParallelApplyWorkerEntry
 

Functions

static void pa_free_worker_info (ParallelApplyWorkerInfo *winfo)
 
static ParallelTransState pa_get_xact_state (ParallelApplyWorkerShared *wshared)
 
static PartialFileSetState pa_get_fileset_state (void)
 
static bool pa_can_start (void)
 
static bool pa_setup_dsm (ParallelApplyWorkerInfo *winfo)
 
static ParallelApplyWorkerInfopa_launch_parallel_worker (void)
 
void pa_allocate_worker (TransactionId xid)
 
ParallelApplyWorkerInfopa_find_worker (TransactionId xid)
 
static void pa_free_worker (ParallelApplyWorkerInfo *winfo)
 
void pa_detach_all_error_mq (void)
 
static bool pa_has_spooled_message_pending (void)
 
static bool pa_process_spooled_messages_if_required (void)
 
static void ProcessParallelApplyInterrupts (void)
 
static void LogicalParallelApplyLoop (shm_mq_handle *mqh)
 
static void pa_shutdown (int code, Datum arg)
 
void ParallelApplyWorkerMain (Datum main_arg)
 
void HandleParallelApplyMessageInterrupt (void)
 
static void ProcessParallelApplyMessage (StringInfo msg)
 
void ProcessParallelApplyMessages (void)
 
bool pa_send_data (ParallelApplyWorkerInfo *winfo, Size nbytes, const void *data)
 
void pa_switch_to_partial_serialize (ParallelApplyWorkerInfo *winfo, bool stream_locked)
 
static void pa_wait_for_xact_state (ParallelApplyWorkerInfo *winfo, ParallelTransState xact_state)
 
static void pa_wait_for_xact_finish (ParallelApplyWorkerInfo *winfo)
 
void pa_set_xact_state (ParallelApplyWorkerShared *wshared, ParallelTransState xact_state)
 
void pa_set_stream_apply_worker (ParallelApplyWorkerInfo *winfo)
 
static void pa_savepoint_name (Oid suboid, TransactionId xid, char *spname, Size szsp)
 
void pa_start_subtrans (TransactionId current_xid, TransactionId top_xid)
 
void pa_reset_subtrans (void)
 
void pa_stream_abort (LogicalRepStreamAbortData *abort_data)
 
void pa_set_fileset_state (ParallelApplyWorkerShared *wshared, PartialFileSetState fileset_state)
 
void pa_lock_stream (TransactionId xid, LOCKMODE lockmode)
 
void pa_unlock_stream (TransactionId xid, LOCKMODE lockmode)
 
void pa_lock_transaction (TransactionId xid, LOCKMODE lockmode)
 
void pa_unlock_transaction (TransactionId xid, LOCKMODE lockmode)
 
void pa_decr_and_wait_stream_block (void)
 
void pa_xact_finish (ParallelApplyWorkerInfo *winfo, XLogRecPtr remote_lsn)
 

Variables

static HTABParallelApplyTxnHash = NULL
 
static ListParallelApplyWorkerPool = NIL
 
ParallelApplyWorkerSharedMyParallelShared = NULL
 
volatile sig_atomic_t ParallelApplyMessagePending = false
 
static ParallelApplyWorkerInfostream_apply_worker = NULL
 
static Listsubxactlist = NIL
 

Macro Definition Documentation

◆ DSM_ERROR_QUEUE_SIZE

#define DSM_ERROR_QUEUE_SIZE   (16 * 1024)

Definition at line 197 of file applyparallelworker.c.

◆ DSM_QUEUE_SIZE

#define DSM_QUEUE_SIZE   (16 * 1024 * 1024)

Definition at line 189 of file applyparallelworker.c.

◆ PARALLEL_APPLY_KEY_ERROR_QUEUE

#define PARALLEL_APPLY_KEY_ERROR_QUEUE   3

Definition at line 186 of file applyparallelworker.c.

◆ PARALLEL_APPLY_KEY_MQ

#define PARALLEL_APPLY_KEY_MQ   2

Definition at line 185 of file applyparallelworker.c.

◆ PARALLEL_APPLY_KEY_SHARED

#define PARALLEL_APPLY_KEY_SHARED   1

Definition at line 184 of file applyparallelworker.c.

◆ PARALLEL_APPLY_LOCK_STREAM

#define PARALLEL_APPLY_LOCK_STREAM   0

Definition at line 211 of file applyparallelworker.c.

◆ PARALLEL_APPLY_LOCK_XACT

#define PARALLEL_APPLY_LOCK_XACT   1

Definition at line 212 of file applyparallelworker.c.

◆ PG_LOGICAL_APPLY_SHM_MAGIC

#define PG_LOGICAL_APPLY_SHM_MAGIC   0x787ca067

Definition at line 177 of file applyparallelworker.c.

◆ SHM_SEND_RETRY_INTERVAL_MS

#define SHM_SEND_RETRY_INTERVAL_MS   1000

◆ SHM_SEND_TIMEOUT_MS

#define SHM_SEND_TIMEOUT_MS   (10000 - SHM_SEND_RETRY_INTERVAL_MS)

◆ SIZE_STATS_MESSAGE

#define SIZE_STATS_MESSAGE   (2 * sizeof(XLogRecPtr) + sizeof(TimestampTz))

Definition at line 205 of file applyparallelworker.c.

Typedef Documentation

◆ ParallelApplyWorkerEntry

Function Documentation

◆ HandleParallelApplyMessageInterrupt()

void HandleParallelApplyMessageInterrupt ( void  )

Definition at line 998 of file applyparallelworker.c.

999{
1000 InterruptPending = true;
1003}
volatile sig_atomic_t ParallelApplyMessagePending
volatile sig_atomic_t InterruptPending
Definition globals.c:32
struct Latch * MyLatch
Definition globals.c:63
void SetLatch(Latch *latch)
Definition latch.c:290

References InterruptPending, MyLatch, ParallelApplyMessagePending, and SetLatch().

Referenced by procsignal_sigusr1_handler().

◆ LogicalParallelApplyLoop()

static void LogicalParallelApplyLoop ( shm_mq_handle mqh)
static

Definition at line 737 of file applyparallelworker.c.

738{
740 ErrorContextCallback errcallback;
742
743 /*
744 * Init the ApplyMessageContext which we clean up after each replication
745 * protocol message.
746 */
748 "ApplyMessageContext",
750
751 /*
752 * Push apply error context callback. Fields will be filled while applying
753 * a change.
754 */
755 errcallback.callback = apply_error_callback;
756 errcallback.previous = error_context_stack;
757 error_context_stack = &errcallback;
758
759 for (;;)
760 {
761 void *data;
762 Size len;
763
765
766 /* Ensure we are reading the data into our memory context. */
768
769 shmq_res = shm_mq_receive(mqh, &len, &data, true);
770
772 {
774 int c;
775
776 if (len == 0)
777 elog(ERROR, "invalid message length");
778
780
781 /*
782 * The first byte of messages sent from leader apply worker to
783 * parallel apply workers can only be PqReplMsg_WALData.
784 */
785 c = pq_getmsgbyte(&s);
786 if (c != PqReplMsg_WALData)
787 elog(ERROR, "unexpected message \"%c\"", c);
788
789 /*
790 * Ignore statistics fields that have been updated by the leader
791 * apply worker.
792 *
793 * XXX We can avoid sending the statistics fields from the leader
794 * apply worker but for that, it needs to rebuild the entire
795 * message by removing these fields which could be more work than
796 * simply ignoring these fields in the parallel apply worker.
797 */
799
800 apply_dispatch(&s);
801 }
802 else if (shmq_res == SHM_MQ_WOULD_BLOCK)
803 {
804 /* Replay the changes from the file, if any. */
806 {
807 int rc;
808
809 /* Wait for more work. */
810 rc = WaitLatch(MyLatch,
812 1000L,
814
815 if (rc & WL_LATCH_SET)
817 }
818 }
819 else
820 {
822
825 errmsg("lost connection to the logical replication apply worker")));
826 }
827
830 }
831
832 /* Pop the error context stack. */
833 error_context_stack = errcallback.previous;
834
836}
static void ProcessParallelApplyInterrupts(void)
#define SIZE_STATS_MESSAGE
static bool pa_process_spooled_messages_if_required(void)
MemoryContext ApplyMessageContext
Definition worker.c:472
void apply_dispatch(StringInfo s)
Definition worker.c:3778
MemoryContext ApplyContext
Definition worker.c:473
void apply_error_callback(void *arg)
Definition worker.c:6200
#define Assert(condition)
Definition c.h:885
size_t Size
Definition c.h:631
ErrorContextCallback * error_context_stack
Definition elog.c:99
int errcode(int sqlerrcode)
Definition elog.c:874
int errmsg(const char *fmt,...)
Definition elog.c:1093
#define ERROR
Definition elog.h:39
#define elog(elevel,...)
Definition elog.h:226
#define ereport(elevel,...)
Definition elog.h:150
void ResetLatch(Latch *latch)
Definition latch.c:374
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition latch.c:172
void MemoryContextReset(MemoryContext context)
Definition mcxt.c:403
MemoryContext CurrentMemoryContext
Definition mcxt.c:160
#define AllocSetContextCreate
Definition memutils.h:129
#define ALLOCSET_DEFAULT_SIZES
Definition memutils.h:160
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition palloc.h:124
const void size_t len
const void * data
int pq_getmsgbyte(StringInfo msg)
Definition pqformat.c:398
char * c
static int fb(int x)
#define PqReplMsg_WALData
Definition protocol.h:77
shm_mq_result shm_mq_receive(shm_mq_handle *mqh, Size *nbytesp, void **datap, bool nowait)
Definition shm_mq.c:573
shm_mq_result
Definition shm_mq.h:39
@ SHM_MQ_SUCCESS
Definition shm_mq.h:40
@ SHM_MQ_WOULD_BLOCK
Definition shm_mq.h:41
@ SHM_MQ_DETACHED
Definition shm_mq.h:42
static void initReadOnlyStringInfo(StringInfo str, char *data, int len)
Definition stringinfo.h:157
struct ErrorContextCallback * previous
Definition elog.h:297
void(* callback)(void *arg)
Definition elog.h:298
#define WL_TIMEOUT
#define WL_EXIT_ON_PM_DEATH
#define WL_LATCH_SET

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, apply_dispatch(), apply_error_callback(), ApplyContext, ApplyMessageContext, Assert, ErrorContextCallback::callback, CurrentMemoryContext, StringInfoData::cursor, data, elog, ereport, errcode(), errmsg(), ERROR, error_context_stack, fb(), initReadOnlyStringInfo(), len, MemoryContextReset(), MemoryContextSwitchTo(), MyLatch, pa_process_spooled_messages_if_required(), pq_getmsgbyte(), PqReplMsg_WALData, ErrorContextCallback::previous, ProcessParallelApplyInterrupts(), ResetLatch(), SHM_MQ_DETACHED, shm_mq_receive(), SHM_MQ_SUCCESS, SHM_MQ_WOULD_BLOCK, SIZE_STATS_MESSAGE, WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, and WL_TIMEOUT.

Referenced by ParallelApplyWorkerMain().

◆ pa_allocate_worker()

void pa_allocate_worker ( TransactionId  xid)

Definition at line 473 of file applyparallelworker.c.

474{
475 bool found;
478
479 if (!pa_can_start())
480 return;
481
483 if (!winfo)
484 return;
485
486 /* First time through, initialize parallel apply worker state hashtable. */
488 {
489 HASHCTL ctl;
490
491 MemSet(&ctl, 0, sizeof(ctl));
492 ctl.keysize = sizeof(TransactionId);
493 ctl.entrysize = sizeof(ParallelApplyWorkerEntry);
494 ctl.hcxt = ApplyContext;
495
496 ParallelApplyTxnHash = hash_create("logical replication parallel apply workers hash",
497 16, &ctl,
499 }
500
501 /* Create an entry for the requested transaction. */
502 entry = hash_search(ParallelApplyTxnHash, &xid, HASH_ENTER, &found);
503 if (found)
504 elog(ERROR, "hash table corrupted");
505
506 /* Update the transaction information in shared memory. */
507 SpinLockAcquire(&winfo->shared->mutex);
509 winfo->shared->xid = xid;
510 SpinLockRelease(&winfo->shared->mutex);
511
512 winfo->in_use = true;
513 winfo->serialize_changes = false;
514 entry->winfo = winfo;
515}
static bool pa_can_start(void)
static HTAB * ParallelApplyTxnHash
static ParallelApplyWorkerInfo * pa_launch_parallel_worker(void)
#define MemSet(start, val, len)
Definition c.h:1035
uint32 TransactionId
Definition c.h:678
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition dynahash.c:952
HTAB * hash_create(const char *tabname, int64 nelem, const HASHCTL *info, int flags)
Definition dynahash.c:358
@ HASH_ENTER
Definition hsearch.h:114
#define HASH_CONTEXT
Definition hsearch.h:102
#define HASH_ELEM
Definition hsearch.h:95
#define HASH_BLOBS
Definition hsearch.h:97
tree ctl
Definition radixtree.h:1838
static void SpinLockRelease(volatile slock_t *lock)
Definition spin.h:62
static void SpinLockAcquire(volatile slock_t *lock)
Definition spin.h:56
ParallelApplyWorkerInfo * winfo
ParallelApplyWorkerShared * shared
ParallelTransState xact_state
@ PARALLEL_TRANS_UNKNOWN

References ApplyContext, ctl, elog, ERROR, fb(), HASH_BLOBS, HASH_CONTEXT, hash_create(), HASH_ELEM, HASH_ENTER, hash_search(), ParallelApplyWorkerInfo::in_use, MemSet, ParallelApplyWorkerShared::mutex, pa_can_start(), pa_launch_parallel_worker(), PARALLEL_TRANS_UNKNOWN, ParallelApplyTxnHash, ParallelApplyWorkerInfo::serialize_changes, ParallelApplyWorkerInfo::shared, SpinLockAcquire(), SpinLockRelease(), ParallelApplyWorkerEntry::winfo, ParallelApplyWorkerShared::xact_state, and ParallelApplyWorkerShared::xid.

Referenced by apply_handle_stream_start().

◆ pa_can_start()

static bool pa_can_start ( void  )
static

Definition at line 267 of file applyparallelworker.c.

268{
269 /* Only leader apply workers can start parallel apply workers. */
271 return false;
272
273 /*
274 * It is good to check for any change in the subscription parameter to
275 * avoid the case where for a very long time the change doesn't get
276 * reflected. This can happen when there is a constant flow of streaming
277 * transactions that are handled by parallel apply workers.
278 *
279 * It is better to do it before the below checks so that the latest values
280 * of subscription can be used for the checks.
281 */
283
284 /*
285 * Don't start a new parallel apply worker if the subscription is not
286 * using parallel streaming mode, or if the publisher does not support
287 * parallel apply.
288 */
290 return false;
291
292 /*
293 * Don't start a new parallel worker if user has set skiplsn as it's
294 * possible that they want to skip the streaming transaction. For
295 * streaming transactions, we need to serialize the transaction to a file
296 * so that we can get the last LSN of the transaction to judge whether to
297 * skip before starting to apply the change.
298 *
299 * One might think that we could allow parallelism if the first lsn of the
300 * transaction is greater than skiplsn, but we don't send it with the
301 * STREAM START message, and it doesn't seem worth sending the extra eight
302 * bytes with the STREAM START to enable parallelism for this case.
303 */
305 return false;
306
307 /*
308 * For streaming transactions that are being applied using a parallel
309 * apply worker, we cannot decide whether to apply the change for a
310 * relation that is not in the READY state (see
311 * should_apply_changes_for_rel) as we won't know remote_final_lsn by that
312 * time. So, we don't start the new parallel apply worker in this case.
313 */
314 if (!AllTablesyncsReady())
315 return false;
316
317 return true;
318}
void maybe_reread_subscription(void)
Definition worker.c:5041
Subscription * MySubscription
Definition worker.c:480
LogicalRepWorker * MyLogicalRepWorker
Definition launcher.c:56
XLogRecPtr skiplsn
bool AllTablesyncsReady(void)
Definition tablesync.c:1596
static bool am_leader_apply_worker(void)
#define XLogRecPtrIsValid(r)
Definition xlogdefs.h:29

References AllTablesyncsReady(), am_leader_apply_worker(), maybe_reread_subscription(), MyLogicalRepWorker, MySubscription, LogicalRepWorker::parallel_apply, Subscription::skiplsn, and XLogRecPtrIsValid.

Referenced by pa_allocate_worker().

◆ pa_decr_and_wait_stream_block()

void pa_decr_and_wait_stream_block ( void  )

Definition at line 1600 of file applyparallelworker.c.

1601{
1603
1604 /*
1605 * It is only possible to not have any pending stream chunks when we are
1606 * applying spooled messages.
1607 */
1609 {
1611 return;
1612
1613 elog(ERROR, "invalid pending streaming chunk 0");
1614 }
1615
1617 {
1620 }
1621}
void pa_unlock_stream(TransactionId xid, LOCKMODE lockmode)
void pa_lock_stream(TransactionId xid, LOCKMODE lockmode)
ParallelApplyWorkerShared * MyParallelShared
static bool pa_has_spooled_message_pending(void)
static uint32 pg_atomic_sub_fetch_u32(volatile pg_atomic_uint32 *ptr, int32 sub_)
Definition atomics.h:439
static uint32 pg_atomic_read_u32(volatile pg_atomic_uint32 *ptr)
Definition atomics.h:237
#define AccessShareLock
Definition lockdefs.h:36
pg_atomic_uint32 pending_stream_count
static bool am_parallel_apply_worker(void)

References AccessShareLock, am_parallel_apply_worker(), Assert, elog, ERROR, MyParallelShared, pa_has_spooled_message_pending(), pa_lock_stream(), pa_unlock_stream(), ParallelApplyWorkerShared::pending_stream_count, pg_atomic_read_u32(), pg_atomic_sub_fetch_u32(), and ParallelApplyWorkerShared::xid.

Referenced by apply_handle_stream_abort(), and apply_handle_stream_stop().

◆ pa_detach_all_error_mq()

void pa_detach_all_error_mq ( void  )

Definition at line 625 of file applyparallelworker.c.

626{
627 ListCell *lc;
628
630 {
632
633 if (winfo->error_mq_handle)
634 {
636 winfo->error_mq_handle = NULL;
637 }
638 }
639}
static List * ParallelApplyWorkerPool
#define lfirst(lc)
Definition pg_list.h:172
void shm_mq_detach(shm_mq_handle *mqh)
Definition shm_mq.c:844
shm_mq_handle * error_mq_handle

References ParallelApplyWorkerInfo::error_mq_handle, fb(), lfirst, ParallelApplyWorkerPool, and shm_mq_detach().

Referenced by logicalrep_worker_detach().

◆ pa_find_worker()

ParallelApplyWorkerInfo * pa_find_worker ( TransactionId  xid)

Definition at line 521 of file applyparallelworker.c.

522{
523 bool found;
525
526 if (!TransactionIdIsValid(xid))
527 return NULL;
528
530 return NULL;
531
532 /* Return the cached parallel apply worker if valid. */
534 return stream_apply_worker;
535
536 /* Find an entry for the requested transaction. */
537 entry = hash_search(ParallelApplyTxnHash, &xid, HASH_FIND, &found);
538 if (found)
539 {
540 /* The worker must not have exited. */
541 Assert(entry->winfo->in_use);
542 return entry->winfo;
543 }
544
545 return NULL;
546}
static ParallelApplyWorkerInfo * stream_apply_worker
@ HASH_FIND
Definition hsearch.h:113
#define TransactionIdIsValid(xid)
Definition transam.h:41

References Assert, fb(), HASH_FIND, hash_search(), ParallelApplyWorkerInfo::in_use, ParallelApplyTxnHash, stream_apply_worker, TransactionIdIsValid, and ParallelApplyWorkerEntry::winfo.

Referenced by get_transaction_apply_action().

◆ pa_free_worker()

static void pa_free_worker ( ParallelApplyWorkerInfo winfo)
static

Definition at line 559 of file applyparallelworker.c.

560{
562 Assert(winfo->in_use);
564
566 elog(ERROR, "hash table corrupted");
567
568 /*
569 * Stop the worker if there are enough workers in the pool.
570 *
571 * XXX Additionally, we also stop the worker if the leader apply worker
572 * serialize part of the transaction data due to a send timeout. This is
573 * because the message could be partially written to the queue and there
574 * is no way to clean the queue other than resending the message until it
575 * succeeds. Instead of trying to send the data which anyway would have
576 * been serialized and then letting the parallel apply worker deal with
577 * the spurious message, we stop the worker.
578 */
579 if (winfo->serialize_changes ||
582 {
584 pa_free_worker_info(winfo);
585
586 return;
587 }
588
589 winfo->in_use = false;
590 winfo->serialize_changes = false;
591}
static void pa_free_worker_info(ParallelApplyWorkerInfo *winfo)
static ParallelTransState pa_get_xact_state(ParallelApplyWorkerShared *wshared)
@ HASH_REMOVE
Definition hsearch.h:115
void logicalrep_pa_worker_stop(ParallelApplyWorkerInfo *winfo)
Definition launcher.c:679
int max_parallel_apply_workers_per_subscription
Definition launcher.c:54
static int list_length(const List *l)
Definition pg_list.h:152
@ PARALLEL_TRANS_FINISHED

References am_parallel_apply_worker(), Assert, elog, ERROR, fb(), HASH_REMOVE, hash_search(), ParallelApplyWorkerInfo::in_use, list_length(), logicalrep_pa_worker_stop(), max_parallel_apply_workers_per_subscription, pa_free_worker_info(), pa_get_xact_state(), PARALLEL_TRANS_FINISHED, ParallelApplyTxnHash, ParallelApplyWorkerPool, ParallelApplyWorkerInfo::serialize_changes, ParallelApplyWorkerInfo::shared, and ParallelApplyWorkerShared::xid.

Referenced by pa_xact_finish().

◆ pa_free_worker_info()

static void pa_free_worker_info ( ParallelApplyWorkerInfo winfo)
static

Definition at line 598 of file applyparallelworker.c.

599{
600 Assert(winfo);
601
602 if (winfo->mq_handle)
603 shm_mq_detach(winfo->mq_handle);
604
605 if (winfo->error_mq_handle)
607
608 /* Unlink the files with serialized changes. */
609 if (winfo->serialize_changes)
611
612 if (winfo->dsm_seg)
613 dsm_detach(winfo->dsm_seg);
614
615 /* Remove from the worker pool. */
617
618 pfree(winfo);
619}
void stream_cleanup_files(Oid subid, TransactionId xid)
Definition worker.c:5420
void dsm_detach(dsm_segment *seg)
Definition dsm.c:803
List * list_delete_ptr(List *list, void *datum)
Definition list.c:872
void pfree(void *pointer)
Definition mcxt.c:1616

References Assert, dsm_detach(), ParallelApplyWorkerInfo::dsm_seg, ParallelApplyWorkerInfo::error_mq_handle, list_delete_ptr(), ParallelApplyWorkerInfo::mq_handle, MyLogicalRepWorker, ParallelApplyWorkerPool, pfree(), ParallelApplyWorkerInfo::serialize_changes, ParallelApplyWorkerInfo::shared, shm_mq_detach(), stream_cleanup_files(), LogicalRepWorker::subid, and ParallelApplyWorkerShared::xid.

Referenced by pa_free_worker(), and pa_launch_parallel_worker().

◆ pa_get_fileset_state()

◆ pa_get_xact_state()

static ParallelTransState pa_get_xact_state ( ParallelApplyWorkerShared wshared)
static

Definition at line 1328 of file applyparallelworker.c.

1329{
1330 ParallelTransState xact_state;
1331
1332 SpinLockAcquire(&wshared->mutex);
1333 xact_state = wshared->xact_state;
1334 SpinLockRelease(&wshared->mutex);
1335
1336 return xact_state;
1337}
ParallelTransState

References fb(), SpinLockAcquire(), and SpinLockRelease().

Referenced by pa_free_worker(), pa_wait_for_xact_finish(), and pa_wait_for_xact_state().

◆ pa_has_spooled_message_pending()

static bool pa_has_spooled_message_pending ( void  )
static

Definition at line 645 of file applyparallelworker.c.

646{
647 PartialFileSetState fileset_state;
648
649 fileset_state = pa_get_fileset_state();
650
651 return (fileset_state != FS_EMPTY);
652}
static PartialFileSetState pa_get_fileset_state(void)
@ FS_EMPTY

References FS_EMPTY, and pa_get_fileset_state().

Referenced by pa_decr_and_wait_stream_block().

◆ pa_launch_parallel_worker()

static ParallelApplyWorkerInfo * pa_launch_parallel_worker ( void  )
static

Definition at line 406 of file applyparallelworker.c.

407{
408 MemoryContext oldcontext;
409 bool launched;
411 ListCell *lc;
412
413 /* Try to get an available parallel apply worker from the worker pool. */
415 {
416 winfo = (ParallelApplyWorkerInfo *) lfirst(lc);
417
418 if (!winfo->in_use)
419 return winfo;
420 }
421
422 /*
423 * Start a new parallel apply worker.
424 *
425 * The worker info can be used for the lifetime of the worker process, so
426 * create it in a permanent context.
427 */
429
431
432 /* Setup shared memory. */
433 if (!pa_setup_dsm(winfo))
434 {
435 MemoryContextSwitchTo(oldcontext);
436 pfree(winfo);
437 return NULL;
438 }
439
447 false);
448
449 if (launched)
450 {
452 }
453 else
454 {
455 pa_free_worker_info(winfo);
456 winfo = NULL;
457 }
458
459 MemoryContextSwitchTo(oldcontext);
460
461 return winfo;
462}
static bool pa_setup_dsm(ParallelApplyWorkerInfo *winfo)
dsm_handle dsm_segment_handle(dsm_segment *seg)
Definition dsm.c:1123
#define palloc0_object(type)
Definition fe_memutils.h:75
bool logicalrep_worker_launch(LogicalRepWorkerType wtype, Oid dbid, Oid subid, const char *subname, Oid userid, Oid relid, dsm_handle subworker_dsm, bool retain_dead_tuples)
Definition launcher.c:324
List * lappend(List *list, void *datum)
Definition list.c:339
#define InvalidOid
@ WORKERTYPE_PARALLEL_APPLY

References ApplyContext, LogicalRepWorker::dbid, ParallelApplyWorkerInfo::dsm_seg, dsm_segment_handle(), fb(), ParallelApplyWorkerInfo::in_use, InvalidOid, lappend(), lfirst, logicalrep_worker_launch(), MemoryContextSwitchTo(), MyLogicalRepWorker, MySubscription, Subscription::name, Subscription::oid, pa_free_worker_info(), pa_setup_dsm(), palloc0_object, ParallelApplyWorkerPool, pfree(), LogicalRepWorker::userid, and WORKERTYPE_PARALLEL_APPLY.

Referenced by pa_allocate_worker().

◆ pa_lock_stream()

void pa_lock_stream ( TransactionId  xid,
LOCKMODE  lockmode 
)

◆ pa_lock_transaction()

◆ pa_process_spooled_messages_if_required()

static bool pa_process_spooled_messages_if_required ( void  )
static

Definition at line 661 of file applyparallelworker.c.

662{
663 PartialFileSetState fileset_state;
664
665 fileset_state = pa_get_fileset_state();
666
667 if (fileset_state == FS_EMPTY)
668 return false;
669
670 /*
671 * If the leader apply worker is busy serializing the partial changes then
672 * acquire the stream lock now and wait for the leader worker to finish
673 * serializing the changes. Otherwise, the parallel apply worker won't get
674 * a chance to receive a STREAM_STOP (and acquire the stream lock) until
675 * the leader had serialized all changes which can lead to undetected
676 * deadlock.
677 *
678 * Note that the fileset state can be FS_SERIALIZE_DONE once the leader
679 * worker has finished serializing the changes.
680 */
681 if (fileset_state == FS_SERIALIZE_IN_PROGRESS)
682 {
685
686 fileset_state = pa_get_fileset_state();
687 }
688
689 /*
690 * We cannot read the file immediately after the leader has serialized all
691 * changes to the file because there may still be messages in the memory
692 * queue. We will apply all spooled messages the next time we call this
693 * function and that will ensure there are no messages left in the memory
694 * queue.
695 */
696 if (fileset_state == FS_SERIALIZE_DONE)
697 {
699 }
700 else if (fileset_state == FS_READY)
701 {
706 }
707
708 return true;
709}
void pa_set_fileset_state(ParallelApplyWorkerShared *wshared, PartialFileSetState fileset_state)
void apply_spooled_messages(FileSet *stream_fileset, TransactionId xid, XLogRecPtr lsn)
Definition worker.c:2263
@ FS_SERIALIZE_DONE
@ FS_READY
@ FS_SERIALIZE_IN_PROGRESS
#define InvalidXLogRecPtr
Definition xlogdefs.h:28

References AccessShareLock, apply_spooled_messages(), ParallelApplyWorkerShared::fileset, FS_EMPTY, FS_READY, FS_SERIALIZE_DONE, FS_SERIALIZE_IN_PROGRESS, InvalidXLogRecPtr, MyParallelShared, pa_get_fileset_state(), pa_lock_stream(), pa_set_fileset_state(), pa_unlock_stream(), and ParallelApplyWorkerShared::xid.

Referenced by LogicalParallelApplyLoop().

◆ pa_reset_subtrans()

void pa_reset_subtrans ( void  )

Definition at line 1411 of file applyparallelworker.c.

1412{
1413 /*
1414 * We don't need to free this explicitly as the allocated memory will be
1415 * freed at the transaction end.
1416 */
1417 subxactlist = NIL;
1418}
static List * subxactlist
#define NIL
Definition pg_list.h:68

References NIL, and subxactlist.

Referenced by apply_handle_stream_commit(), apply_handle_stream_prepare(), and pa_stream_abort().

◆ pa_savepoint_name()

static void pa_savepoint_name ( Oid  suboid,
TransactionId  xid,
char spname,
Size  szsp 
)
static

Definition at line 1357 of file applyparallelworker.c.

1358{
1359 snprintf(spname, szsp, "pg_sp_%u_%u", suboid, xid);
1360}
#define snprintf
Definition port.h:260

References fb(), and snprintf.

Referenced by pa_start_subtrans(), and pa_stream_abort().

◆ pa_send_data()

bool pa_send_data ( ParallelApplyWorkerInfo winfo,
Size  nbytes,
const void data 
)

Definition at line 1155 of file applyparallelworker.c.

1156{
1157 int rc;
1158 shm_mq_result result;
1159 TimestampTz startTime = 0;
1160
1162 Assert(!winfo->serialize_changes);
1163
1164 /*
1165 * We don't try to send data to parallel worker for 'immediate' mode. This
1166 * is primarily used for testing purposes.
1167 */
1169 return false;
1170
1171/*
1172 * This timeout is a bit arbitrary but testing revealed that it is sufficient
1173 * to send the message unless the parallel apply worker is waiting on some
1174 * lock or there is a serious resource crunch. See the comments atop this file
1175 * to know why we are using a non-blocking way to send the message.
1176 */
1177#define SHM_SEND_RETRY_INTERVAL_MS 1000
1178#define SHM_SEND_TIMEOUT_MS (10000 - SHM_SEND_RETRY_INTERVAL_MS)
1179
1180 for (;;)
1181 {
1182 result = shm_mq_send(winfo->mq_handle, nbytes, data, true, true);
1183
1184 if (result == SHM_MQ_SUCCESS)
1185 return true;
1186 else if (result == SHM_MQ_DETACHED)
1187 ereport(ERROR,
1189 errmsg("could not send data to shared-memory queue")));
1190
1191 Assert(result == SHM_MQ_WOULD_BLOCK);
1192
1193 /* Wait before retrying. */
1194 rc = WaitLatch(MyLatch,
1198
1199 if (rc & WL_LATCH_SET)
1200 {
1203 }
1204
1205 if (startTime == 0)
1206 startTime = GetCurrentTimestamp();
1207 else if (TimestampDifferenceExceeds(startTime, GetCurrentTimestamp(),
1209 return false;
1210 }
1211}
#define SHM_SEND_TIMEOUT_MS
#define SHM_SEND_RETRY_INTERVAL_MS
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition timestamp.c:1781
TimestampTz GetCurrentTimestamp(void)
Definition timestamp.c:1645
#define unlikely(x)
Definition c.h:424
int64 TimestampTz
Definition timestamp.h:39
#define CHECK_FOR_INTERRUPTS()
Definition miscadmin.h:123
int debug_logical_replication_streaming
@ DEBUG_LOGICAL_REP_STREAMING_IMMEDIATE
shm_mq_result shm_mq_send(shm_mq_handle *mqh, Size nbytes, const void *data, bool nowait, bool force_flush)
Definition shm_mq.c:330
bool IsTransactionState(void)
Definition xact.c:388

References Assert, CHECK_FOR_INTERRUPTS, data, DEBUG_LOGICAL_REP_STREAMING_IMMEDIATE, debug_logical_replication_streaming, ereport, errcode(), errmsg(), ERROR, fb(), GetCurrentTimestamp(), IsTransactionState(), ParallelApplyWorkerInfo::mq_handle, MyLatch, ResetLatch(), ParallelApplyWorkerInfo::serialize_changes, SHM_MQ_DETACHED, shm_mq_send(), SHM_MQ_SUCCESS, SHM_MQ_WOULD_BLOCK, SHM_SEND_RETRY_INTERVAL_MS, SHM_SEND_TIMEOUT_MS, TimestampDifferenceExceeds(), unlikely, WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, and WL_TIMEOUT.

Referenced by apply_handle_stream_abort(), apply_handle_stream_commit(), apply_handle_stream_prepare(), apply_handle_stream_start(), apply_handle_stream_stop(), and handle_streamed_transaction().

◆ pa_set_fileset_state()

◆ pa_set_stream_apply_worker()

void pa_set_stream_apply_worker ( ParallelApplyWorkerInfo winfo)

Definition at line 1343 of file applyparallelworker.c.

1344{
1345 stream_apply_worker = winfo;
1346}

References stream_apply_worker.

Referenced by apply_handle_stream_start(), and apply_handle_stream_stop().

◆ pa_set_xact_state()

void pa_set_xact_state ( ParallelApplyWorkerShared wshared,
ParallelTransState  xact_state 
)

Definition at line 1316 of file applyparallelworker.c.

1318{
1319 SpinLockAcquire(&wshared->mutex);
1320 wshared->xact_state = xact_state;
1321 SpinLockRelease(&wshared->mutex);
1322}

References fb(), SpinLockAcquire(), and SpinLockRelease().

Referenced by apply_handle_stream_commit(), apply_handle_stream_prepare(), apply_handle_stream_start(), and pa_stream_abort().

◆ pa_setup_dsm()

static bool pa_setup_dsm ( ParallelApplyWorkerInfo winfo)
static

Definition at line 329 of file applyparallelworker.c.

330{
333 dsm_segment *seg;
334 shm_toc *toc;
336 shm_mq *mq;
337 Size queue_size = DSM_QUEUE_SIZE;
339
340 /*
341 * Estimate how much shared memory we need.
342 *
343 * Because the TOC machinery may choose to insert padding of oddly-sized
344 * requests, we must estimate each chunk separately.
345 *
346 * We need one key to register the location of the header, and two other
347 * keys to track the locations of the message queue and the error message
348 * queue.
349 */
352 shm_toc_estimate_chunk(&e, queue_size);
354
357
358 /* Create the shared memory segment and establish a table of contents. */
359 seg = dsm_create(shm_toc_estimate(&e), 0);
360 if (!seg)
361 return false;
362
364 segsize);
365
366 /* Set up the header region. */
367 shared = shm_toc_allocate(toc, sizeof(ParallelApplyWorkerShared));
368 SpinLockInit(&shared->mutex);
369
373 shared->fileset_state = FS_EMPTY;
374
376
377 /* Set up message queue for the worker. */
378 mq = shm_mq_create(shm_toc_allocate(toc, queue_size), queue_size);
381
382 /* Attach the queue. */
383 winfo->mq_handle = shm_mq_attach(mq, seg, NULL);
384
385 /* Set up error queue for the worker. */
390
391 /* Attach the queue. */
392 winfo->error_mq_handle = shm_mq_attach(mq, seg, NULL);
393
394 /* Return results to caller. */
395 winfo->dsm_seg = seg;
396 winfo->shared = shared;
397
398 return true;
399}
#define DSM_ERROR_QUEUE_SIZE
#define DSM_QUEUE_SIZE
#define PARALLEL_APPLY_KEY_SHARED
#define PARALLEL_APPLY_KEY_ERROR_QUEUE
#define PARALLEL_APPLY_KEY_MQ
#define PG_LOGICAL_APPLY_SHM_MAGIC
static void pg_atomic_init_u32(volatile pg_atomic_uint32 *ptr, uint32 val)
Definition atomics.h:219
void * dsm_segment_address(dsm_segment *seg)
Definition dsm.c:1095
dsm_segment * dsm_create(Size size, int flags)
Definition dsm.c:516
e
void shm_mq_set_sender(shm_mq *mq, PGPROC *proc)
Definition shm_mq.c:225
shm_mq * shm_mq_create(void *address, Size size)
Definition shm_mq.c:178
void shm_mq_set_receiver(shm_mq *mq, PGPROC *proc)
Definition shm_mq.c:207
shm_mq_handle * shm_mq_attach(shm_mq *mq, dsm_segment *seg, BackgroundWorkerHandle *handle)
Definition shm_mq.c:291
void * shm_toc_allocate(shm_toc *toc, Size nbytes)
Definition shm_toc.c:88
Size shm_toc_estimate(shm_toc_estimator *e)
Definition shm_toc.c:263
shm_toc * shm_toc_create(uint64 magic, void *address, Size nbytes)
Definition shm_toc.c:40
void shm_toc_insert(shm_toc *toc, uint64 key, void *address)
Definition shm_toc.c:171
#define shm_toc_estimate_chunk(e, sz)
Definition shm_toc.h:51
#define shm_toc_initialize_estimator(e)
Definition shm_toc.h:49
#define shm_toc_estimate_keys(e, cnt)
Definition shm_toc.h:53
static void SpinLockInit(volatile slock_t *lock)
Definition spin.h:50
PGPROC * MyProc
Definition proc.c:67

References dsm_create(), DSM_ERROR_QUEUE_SIZE, DSM_QUEUE_SIZE, ParallelApplyWorkerInfo::dsm_seg, dsm_segment_address(), ParallelApplyWorkerInfo::error_mq_handle, fb(), ParallelApplyWorkerShared::fileset_state, FS_EMPTY, InvalidXLogRecPtr, ParallelApplyWorkerShared::last_commit_end, ParallelApplyWorkerInfo::mq_handle, ParallelApplyWorkerShared::mutex, MyProc, PARALLEL_APPLY_KEY_ERROR_QUEUE, PARALLEL_APPLY_KEY_MQ, PARALLEL_APPLY_KEY_SHARED, PARALLEL_TRANS_UNKNOWN, ParallelApplyWorkerShared::pending_stream_count, pg_atomic_init_u32(), PG_LOGICAL_APPLY_SHM_MAGIC, ParallelApplyWorkerInfo::shared, shm_mq_attach(), shm_mq_create(), shm_mq_set_receiver(), shm_mq_set_sender(), shm_toc_allocate(), shm_toc_create(), shm_toc_estimate(), shm_toc_estimate_chunk, shm_toc_estimate_keys, shm_toc_initialize_estimator, shm_toc_insert(), SpinLockInit(), and ParallelApplyWorkerShared::xact_state.

Referenced by pa_launch_parallel_worker().

◆ pa_shutdown()

static void pa_shutdown ( int  code,
Datum  arg 
)
static

Definition at line 847 of file applyparallelworker.c.

848{
852
854}
Datum arg
Definition elog.c:1322
static Pointer DatumGetPointer(Datum X)
Definition postgres.h:342
#define INVALID_PROC_NUMBER
Definition procnumber.h:26
int SendProcSignal(pid_t pid, ProcSignalReason reason, ProcNumber procNumber)
Definition procsignal.c:286
@ PROCSIG_PARALLEL_APPLY_MESSAGE
Definition procsignal.h:38

References arg, DatumGetPointer(), dsm_detach(), INVALID_PROC_NUMBER, LogicalRepWorker::leader_pid, MyLogicalRepWorker, PROCSIG_PARALLEL_APPLY_MESSAGE, and SendProcSignal().

Referenced by ParallelApplyWorkerMain().

◆ pa_start_subtrans()

void pa_start_subtrans ( TransactionId  current_xid,
TransactionId  top_xid 
)

Definition at line 1371 of file applyparallelworker.c.

1372{
1373 if (current_xid != top_xid &&
1375 {
1377 char spname[NAMEDATALEN];
1378
1380 spname, sizeof(spname));
1381
1382 elog(DEBUG1, "defining savepoint %s in logical replication parallel apply worker", spname);
1383
1384 /* We must be in transaction block to define the SAVEPOINT. */
1385 if (!IsTransactionBlock())
1386 {
1387 if (!IsTransactionState())
1389
1392 }
1393
1395
1396 /*
1397 * CommitTransactionCommand is needed to start a subtransaction after
1398 * issuing a SAVEPOINT inside a transaction block (see
1399 * StartSubTransaction()).
1400 */
1402
1406 }
1407}
static void pa_savepoint_name(Oid suboid, TransactionId xid, char *spname, Size szsp)
#define DEBUG1
Definition elog.h:30
List * lappend_xid(List *list, TransactionId datum)
Definition list.c:393
bool list_member_xid(const List *list, TransactionId datum)
Definition list.c:742
MemoryContext TopTransactionContext
Definition mcxt.c:171
#define NAMEDATALEN
void DefineSavepoint(const char *name)
Definition xact.c:4395
void StartTransactionCommand(void)
Definition xact.c:3080
bool IsTransactionBlock(void)
Definition xact.c:4993
void BeginTransactionBlock(void)
Definition xact.c:3946
void CommitTransactionCommand(void)
Definition xact.c:3178

References BeginTransactionBlock(), CommitTransactionCommand(), DEBUG1, DefineSavepoint(), elog, fb(), IsTransactionBlock(), IsTransactionState(), lappend_xid(), list_member_xid(), MemoryContextSwitchTo(), MySubscription, NAMEDATALEN, Subscription::oid, pa_savepoint_name(), StartTransactionCommand(), subxactlist, and TopTransactionContext.

Referenced by handle_streamed_transaction().

◆ pa_stream_abort()

void pa_stream_abort ( LogicalRepStreamAbortData abort_data)

Definition at line 1425 of file applyparallelworker.c.

1426{
1427 TransactionId xid = abort_data->xid;
1428 TransactionId subxid = abort_data->subxid;
1429
1430 /*
1431 * Update origin state so we can restart streaming from correct position
1432 * in case of crash.
1433 */
1436
1437 /*
1438 * If the two XIDs are the same, it's in fact abort of toplevel xact, so
1439 * just free the subxactlist.
1440 */
1441 if (subxid == xid)
1442 {
1444
1445 /*
1446 * Release the lock as we might be processing an empty streaming
1447 * transaction in which case the lock won't be released during
1448 * transaction rollback.
1449 *
1450 * Note that it's ok to release the transaction lock before aborting
1451 * the transaction because even if the parallel apply worker dies due
1452 * to crash or some other reason, such a transaction would still be
1453 * considered aborted.
1454 */
1456
1458
1459 if (IsTransactionBlock())
1460 {
1461 EndTransactionBlock(false);
1463 }
1464
1466
1468 }
1469 else
1470 {
1471 /* OK, so it's a subxact. Rollback to the savepoint. */
1472 int i;
1473 char spname[NAMEDATALEN];
1474
1475 pa_savepoint_name(MySubscription->oid, subxid, spname, sizeof(spname));
1476
1477 elog(DEBUG1, "rolling back to savepoint %s in logical replication parallel apply worker", spname);
1478
1479 /*
1480 * Search the subxactlist, determine the offset tracked for the
1481 * subxact, and truncate the list.
1482 *
1483 * Note that for an empty sub-transaction we won't find the subxid
1484 * here.
1485 */
1486 for (i = list_length(subxactlist) - 1; i >= 0; i--)
1487 {
1489
1490 if (xid_tmp == subxid)
1491 {
1495 break;
1496 }
1497 }
1498 }
1499}
void pa_set_xact_state(ParallelApplyWorkerShared *wshared, ParallelTransState xact_state)
void pa_reset_subtrans(void)
void pa_unlock_transaction(TransactionId xid, LOCKMODE lockmode)
void pgstat_report_activity(BackendState state, const char *cmd_str)
@ STATE_IDLE
int i
Definition isn.c:77
List * list_truncate(List *list, int new_size)
Definition list.c:631
#define AccessExclusiveLock
Definition lockdefs.h:43
ReplOriginXactState replorigin_xact_state
Definition origin.c:166
static ListCell * list_nth_cell(const List *list, int n)
Definition pg_list.h:277
#define lfirst_xid(lc)
Definition pg_list.h:175
XLogRecPtr origin_lsn
Definition origin.h:46
TimestampTz origin_timestamp
Definition origin.h:47
void RollbackToSavepoint(const char *name)
Definition xact.c:4589
bool EndTransactionBlock(bool chain)
Definition xact.c:4066
void AbortCurrentTransaction(void)
Definition xact.c:3472

References AbortCurrentTransaction(), AccessExclusiveLock, CommitTransactionCommand(), DEBUG1, elog, EndTransactionBlock(), fb(), i, IsTransactionBlock(), lfirst_xid, list_length(), list_nth_cell(), list_truncate(), MyParallelShared, MySubscription, NAMEDATALEN, Subscription::oid, ReplOriginXactState::origin_lsn, ReplOriginXactState::origin_timestamp, pa_reset_subtrans(), pa_savepoint_name(), pa_set_xact_state(), pa_unlock_transaction(), PARALLEL_TRANS_FINISHED, pgstat_report_activity(), replorigin_xact_state, RollbackToSavepoint(), STATE_IDLE, and subxactlist.

Referenced by apply_handle_stream_abort().

◆ pa_switch_to_partial_serialize()

void pa_switch_to_partial_serialize ( ParallelApplyWorkerInfo winfo,
bool  stream_locked 
)

Definition at line 1220 of file applyparallelworker.c.

1222{
1223 ereport(LOG,
1224 (errmsg("logical replication apply worker will serialize the remaining changes of remote transaction %u to a file",
1225 winfo->shared->xid)));
1226
1227 /*
1228 * The parallel apply worker could be stuck for some reason (say waiting
1229 * on some lock by other backend), so stop trying to send data directly to
1230 * it and start serializing data to the file instead.
1231 */
1232 winfo->serialize_changes = true;
1233
1234 /* Initialize the stream fileset. */
1235 stream_start_internal(winfo->shared->xid, true);
1236
1237 /*
1238 * Acquires the stream lock if not already to make sure that the parallel
1239 * apply worker will wait for the leader to release the stream lock until
1240 * the end of the transaction.
1241 */
1242 if (!stream_locked)
1244
1246}
void stream_start_internal(TransactionId xid, bool first_segment)
Definition worker.c:1690
#define LOG
Definition elog.h:31

References AccessExclusiveLock, ereport, errmsg(), fb(), FS_SERIALIZE_IN_PROGRESS, LOG, pa_lock_stream(), pa_set_fileset_state(), ParallelApplyWorkerInfo::serialize_changes, ParallelApplyWorkerInfo::shared, stream_start_internal(), and ParallelApplyWorkerShared::xid.

Referenced by apply_handle_stream_abort(), apply_handle_stream_commit(), apply_handle_stream_prepare(), apply_handle_stream_start(), apply_handle_stream_stop(), and handle_streamed_transaction().

◆ pa_unlock_stream()

void pa_unlock_stream ( TransactionId  xid,
LOCKMODE  lockmode 
)

◆ pa_unlock_transaction()

◆ pa_wait_for_xact_finish()

static void pa_wait_for_xact_finish ( ParallelApplyWorkerInfo winfo)
static

Definition at line 1283 of file applyparallelworker.c.

1284{
1285 /*
1286 * Wait until the parallel apply worker set the state to
1287 * PARALLEL_TRANS_STARTED which means it has acquired the transaction
1288 * lock. This is to prevent leader apply worker from acquiring the
1289 * transaction lock earlier than the parallel apply worker.
1290 */
1292
1293 /*
1294 * Wait for the transaction lock to be released. This is required to
1295 * detect deadlock among leader and parallel apply workers. Refer to the
1296 * comments atop this file.
1297 */
1300
1301 /*
1302 * Check if the state becomes PARALLEL_TRANS_FINISHED in case the parallel
1303 * apply worker failed while applying changes causing the lock to be
1304 * released.
1305 */
1307 ereport(ERROR,
1309 errmsg("lost connection to the logical replication parallel apply worker")));
1310}
void pa_lock_transaction(TransactionId xid, LOCKMODE lockmode)
static void pa_wait_for_xact_state(ParallelApplyWorkerInfo *winfo, ParallelTransState xact_state)
@ PARALLEL_TRANS_STARTED

References AccessShareLock, ereport, errcode(), errmsg(), ERROR, fb(), pa_get_xact_state(), pa_lock_transaction(), pa_unlock_transaction(), pa_wait_for_xact_state(), PARALLEL_TRANS_FINISHED, PARALLEL_TRANS_STARTED, ParallelApplyWorkerInfo::shared, and ParallelApplyWorkerShared::xid.

Referenced by pa_xact_finish().

◆ pa_wait_for_xact_state()

static void pa_wait_for_xact_state ( ParallelApplyWorkerInfo winfo,
ParallelTransState  xact_state 
)
static

Definition at line 1253 of file applyparallelworker.c.

1255{
1256 for (;;)
1257 {
1258 /*
1259 * Stop if the transaction state has reached or exceeded the given
1260 * xact_state.
1261 */
1262 if (pa_get_xact_state(winfo->shared) >= xact_state)
1263 break;
1264
1265 /* Wait to be signalled. */
1268 10L,
1270
1271 /* Reset the latch so we don't spin. */
1273
1274 /* An interrupt may have occurred while we were waiting. */
1276 }
1277}

References CHECK_FOR_INTERRUPTS, fb(), MyLatch, pa_get_xact_state(), ResetLatch(), ParallelApplyWorkerInfo::shared, WaitLatch(), WL_EXIT_ON_PM_DEATH, WL_LATCH_SET, and WL_TIMEOUT.

Referenced by pa_wait_for_xact_finish().

◆ pa_xact_finish()

void pa_xact_finish ( ParallelApplyWorkerInfo winfo,
XLogRecPtr  remote_lsn 
)

Definition at line 1627 of file applyparallelworker.c.

1628{
1630
1631 /*
1632 * Unlock the shared object lock so that parallel apply worker can
1633 * continue to receive and apply changes.
1634 */
1636
1637 /*
1638 * Wait for that worker to finish. This is necessary to maintain commit
1639 * order which avoids failures due to transaction dependencies and
1640 * deadlocks.
1641 */
1643
1644 if (XLogRecPtrIsValid(remote_lsn))
1645 store_flush_position(remote_lsn, winfo->shared->last_commit_end);
1646
1647 pa_free_worker(winfo);
1648}
static void pa_free_worker(ParallelApplyWorkerInfo *winfo)
static void pa_wait_for_xact_finish(ParallelApplyWorkerInfo *winfo)
void store_flush_position(XLogRecPtr remote_lsn, XLogRecPtr local_lsn)
Definition worker.c:3942

References AccessExclusiveLock, am_leader_apply_worker(), Assert, ParallelApplyWorkerShared::last_commit_end, pa_free_worker(), pa_unlock_stream(), pa_wait_for_xact_finish(), ParallelApplyWorkerInfo::shared, store_flush_position(), ParallelApplyWorkerShared::xid, and XLogRecPtrIsValid.

Referenced by apply_handle_stream_abort(), apply_handle_stream_commit(), and apply_handle_stream_prepare().

◆ ParallelApplyWorkerMain()

void ParallelApplyWorkerMain ( Datum  main_arg)

Definition at line 860 of file applyparallelworker.c.

861{
863 dsm_handle handle;
864 dsm_segment *seg;
865 shm_toc *toc;
866 shm_mq *mq;
868 shm_mq_handle *error_mqh;
872
874
875 /*
876 * Setup signal handling.
877 *
878 * Note: We intentionally used SIGUSR2 to trigger a graceful shutdown
879 * initiated by the leader apply worker. This helps to differentiate it
880 * from the case where we abort the current transaction and exit on
881 * receiving SIGTERM.
882 */
886
887 /*
888 * Attach to the dynamic shared memory segment for the parallel apply, and
889 * find its table of contents.
890 *
891 * Like parallel query, we don't need resource owner by this time. See
892 * ParallelWorkerMain.
893 */
894 memcpy(&handle, MyBgworkerEntry->bgw_extra, sizeof(dsm_handle));
895 seg = dsm_attach(handle);
896 if (!seg)
899 errmsg("could not map dynamic shared memory segment")));
900
902 if (!toc)
905 errmsg("invalid magic number in dynamic shared memory segment")));
906
907 /* Look up the shared information. */
908 shared = shm_toc_lookup(toc, PARALLEL_APPLY_KEY_SHARED, false);
909 MyParallelShared = shared;
910
911 /*
912 * Attach to the message queue.
913 */
916 mqh = shm_mq_attach(mq, seg, NULL);
917
918 /*
919 * Primary initialization is complete. Now, we can attach to our slot.
920 * This is to ensure that the leader apply worker does not write data to
921 * the uninitialized memory queue.
922 */
924
925 /*
926 * Register the shutdown callback after we are attached to the worker
927 * slot. This is to ensure that MyLogicalRepWorker remains valid when this
928 * callback is invoked.
929 */
931
936
937 /*
938 * Attach to the error queue.
939 */
942 error_mqh = shm_mq_attach(mq, seg, NULL);
943
944 pq_redirect_to_shm_mq(seg, error_mqh);
947
950
952
954
955 /* Setup replication origin tracking. */
958 originname, sizeof(originname));
960
961 /*
962 * The parallel apply worker doesn't need to monopolize this replication
963 * origin which was already acquired by its leader process.
964 */
968
969 /*
970 * Setup callback for syscache so that we know when something changes in
971 * the subscription relation state.
972 */
975 (Datum) 0);
976
978
980
981 /*
982 * The parallel apply worker must not get here because the parallel apply
983 * worker will only stop when it receives a SIGTERM or SIGUSR2 from the
984 * leader, or SIGINT from itself, or when there is an error. None of these
985 * cases will allow the code to reach here.
986 */
987 Assert(false);
988}
static void pa_shutdown(int code, Datum arg)
static void LogicalParallelApplyLoop(shm_mq_handle *mqh)
bool InitializingApplyWorker
Definition worker.c:500
void ReplicationOriginNameForLogicalRep(Oid suboid, Oid relid, char *originname, Size szoriginname)
Definition worker.c:644
void set_apply_error_context_origin(char *originname)
Definition worker.c:6342
void InitializeLogRepWorker(void)
Definition worker.c:5775
void BackgroundWorkerUnblockSignals(void)
Definition bgworker.c:933
dsm_segment * dsm_attach(dsm_handle h)
Definition dsm.c:665
uint32 dsm_handle
Definition dsm_impl.h:55
void SignalHandlerForShutdownRequest(SIGNAL_ARGS)
Definition interrupt.c:104
void SignalHandlerForConfigReload(SIGNAL_ARGS)
Definition interrupt.c:61
void CacheRegisterSyscacheCallback(SysCacheIdentifier cacheid, SyscacheCallbackFunction func, Datum arg)
Definition inval.c:1816
void before_shmem_exit(pg_on_exit_callback function, Datum arg)
Definition ipc.c:344
void logicalrep_worker_attach(int slot)
Definition launcher.c:757
ReplOriginId replorigin_by_name(const char *roname, bool missing_ok)
Definition origin.c:231
void replorigin_session_setup(ReplOriginId node, int acquired_by)
Definition origin.c:1146
#define pqsignal
Definition port.h:547
static Datum PointerGetDatum(const void *X)
Definition postgres.h:352
uint64_t Datum
Definition postgres.h:70
static int32 DatumGetInt32(Datum X)
Definition postgres.h:212
BackgroundWorker * MyBgworkerEntry
Definition postmaster.c:200
void pq_set_parallel_leader(pid_t pid, ProcNumber procNumber)
Definition pqmq.c:83
void pq_redirect_to_shm_mq(dsm_segment *seg, shm_mq_handle *mqh)
Definition pqmq.c:54
void * shm_toc_lookup(shm_toc *toc, uint64 key, bool noError)
Definition shm_toc.c:232
shm_toc * shm_toc_attach(uint64 magic, void *address)
Definition shm_toc.c:64
char bgw_extra[BGW_EXTRALEN]
Definition bgworker.h:106
TimestampTz last_recv_time
TimestampTz reply_time
TimestampTz last_send_time
ReplOriginId origin
Definition origin.h:45
void InvalidateSyncingRelStates(Datum arg, SysCacheIdentifier cacheid, uint32 hashvalue)
Definition syncutils.c:101
#define SIGHUP
Definition win32_port.h:158
#define SIGUSR2
Definition win32_port.h:171
uint16 ReplOriginId
Definition xlogdefs.h:69

References Assert, BackgroundWorkerUnblockSignals(), before_shmem_exit(), BackgroundWorker::bgw_extra, CacheRegisterSyscacheCallback(), CommitTransactionCommand(), DatumGetInt32(), dsm_attach(), dsm_segment_address(), ereport, errcode(), errmsg(), ERROR, fb(), LogicalRepWorker::generation, InitializeLogRepWorker(), InitializingApplyWorker, INVALID_PROC_NUMBER, InvalidateSyncingRelStates(), InvalidOid, LogicalRepWorker::last_recv_time, LogicalRepWorker::last_send_time, LogicalRepWorker::leader_pid, LogicalParallelApplyLoop(), logicalrep_worker_attach(), ParallelApplyWorkerShared::logicalrep_worker_generation, ParallelApplyWorkerShared::logicalrep_worker_slot_no, ParallelApplyWorkerShared::mutex, MyBgworkerEntry, MyLogicalRepWorker, MyParallelShared, MyProc, MySubscription, NAMEDATALEN, Subscription::oid, ReplOriginXactState::origin, pa_shutdown(), PARALLEL_APPLY_KEY_ERROR_QUEUE, PARALLEL_APPLY_KEY_MQ, PARALLEL_APPLY_KEY_SHARED, PG_LOGICAL_APPLY_SHM_MAGIC, PointerGetDatum(), pq_redirect_to_shm_mq(), pq_set_parallel_leader(), pqsignal, ReplicationOriginNameForLogicalRep(), replorigin_by_name(), replorigin_session_setup(), replorigin_xact_state, LogicalRepWorker::reply_time, set_apply_error_context_origin(), shm_mq_attach(), shm_mq_set_receiver(), shm_mq_set_sender(), shm_toc_attach(), shm_toc_lookup(), SIGHUP, SignalHandlerForConfigReload(), SignalHandlerForShutdownRequest(), SIGUSR2, SpinLockAcquire(), SpinLockRelease(), and StartTransactionCommand().

◆ ProcessParallelApplyInterrupts()

static void ProcessParallelApplyInterrupts ( void  )
static

Definition at line 715 of file applyparallelworker.c.

716{
718
720 {
721 ereport(LOG,
722 (errmsg("logical replication parallel apply worker for subscription \"%s\" has finished",
724
725 proc_exit(0);
726 }
727
729 {
730 ConfigReloadPending = false;
732 }
733}
void ProcessConfigFile(GucContext context)
Definition guc-file.l:120
@ PGC_SIGHUP
Definition guc.h:75
volatile sig_atomic_t ShutdownRequestPending
Definition interrupt.c:28
volatile sig_atomic_t ConfigReloadPending
Definition interrupt.c:27
void proc_exit(int code)
Definition ipc.c:105

References CHECK_FOR_INTERRUPTS, ConfigReloadPending, ereport, errmsg(), LOG, MySubscription, Subscription::name, PGC_SIGHUP, proc_exit(), ProcessConfigFile(), and ShutdownRequestPending.

Referenced by LogicalParallelApplyLoop().

◆ ProcessParallelApplyMessage()

static void ProcessParallelApplyMessage ( StringInfo  msg)
static

Definition at line 1010 of file applyparallelworker.c.

1011{
1012 char msgtype;
1013
1014 msgtype = pq_getmsgbyte(msg);
1015
1016 switch (msgtype)
1017 {
1019 {
1021
1022 /* Parse ErrorResponse. */
1024
1025 /*
1026 * If desired, add a context line to show that this is a
1027 * message propagated from a parallel apply worker. Otherwise,
1028 * it can sometimes be confusing to understand what actually
1029 * happened.
1030 */
1031 if (edata.context)
1032 edata.context = psprintf("%s\n%s", edata.context,
1033 _("logical replication parallel apply worker"));
1034 else
1035 edata.context = pstrdup(_("logical replication parallel apply worker"));
1036
1037 /*
1038 * Context beyond that should use the error context callbacks
1039 * that were in effect in LogicalRepApplyLoop().
1040 */
1042
1043 /*
1044 * The actual error must have been reported by the parallel
1045 * apply worker.
1046 */
1047 ereport(ERROR,
1049 errmsg("logical replication parallel apply worker exited due to error"),
1050 errcontext("%s", edata.context)));
1051 }
1052
1053 /*
1054 * Don't need to do anything about NoticeResponse and
1055 * NotificationResponse as the logical replication worker doesn't
1056 * need to send messages to the client.
1057 */
1060 break;
1061
1062 default:
1063 elog(ERROR, "unrecognized message type received from logical replication parallel apply worker: %c (message length %d bytes)",
1064 msgtype, msg->len);
1065 }
1066}
ErrorContextCallback * apply_error_context_stack
Definition worker.c:470
#define _(x)
Definition elog.c:95
#define errcontext
Definition elog.h:198
char * pstrdup(const char *in)
Definition mcxt.c:1781
void pq_parse_errornotice(StringInfo msg, ErrorData *edata)
Definition pqmq.c:223
#define PqMsg_NotificationResponse
Definition protocol.h:41
#define PqMsg_ErrorResponse
Definition protocol.h:44
#define PqMsg_NoticeResponse
Definition protocol.h:49
char * psprintf(const char *fmt,...)
Definition psprintf.c:43

References _, apply_error_context_stack, elog, ereport, errcode(), errcontext, errmsg(), ERROR, error_context_stack, fb(), StringInfoData::len, pq_getmsgbyte(), pq_parse_errornotice(), PqMsg_ErrorResponse, PqMsg_NoticeResponse, PqMsg_NotificationResponse, psprintf(), and pstrdup().

Referenced by ProcessParallelApplyMessages().

◆ ProcessParallelApplyMessages()

void ProcessParallelApplyMessages ( void  )

Definition at line 1072 of file applyparallelworker.c.

1073{
1074 ListCell *lc;
1075 MemoryContext oldcontext;
1076
1078
1079 /*
1080 * This is invoked from ProcessInterrupts(), and since some of the
1081 * functions it calls contain CHECK_FOR_INTERRUPTS(), there is a potential
1082 * for recursive calls if more signals are received while this runs. It's
1083 * unclear that recursive entry would be safe, and it doesn't seem useful
1084 * even if it is safe, so let's block interrupts until done.
1085 */
1087
1088 /*
1089 * Moreover, CurrentMemoryContext might be pointing almost anywhere. We
1090 * don't want to risk leaking data into long-lived contexts, so let's do
1091 * our work here in a private context that we can reset on each use.
1092 */
1093 if (!hpam_context) /* first time through? */
1095 "ProcessParallelApplyMessages",
1097 else
1099
1100 oldcontext = MemoryContextSwitchTo(hpam_context);
1101
1103
1104 foreach(lc, ParallelApplyWorkerPool)
1105 {
1106 shm_mq_result res;
1107 Size nbytes;
1108 void *data;
1110
1111 /*
1112 * The leader will detach from the error queue and set it to NULL
1113 * before preparing to stop all parallel apply workers, so we don't
1114 * need to handle error messages anymore. See
1115 * logicalrep_worker_detach.
1116 */
1117 if (!winfo->error_mq_handle)
1118 continue;
1119
1120 res = shm_mq_receive(winfo->error_mq_handle, &nbytes, &data, true);
1121
1122 if (res == SHM_MQ_WOULD_BLOCK)
1123 continue;
1124 else if (res == SHM_MQ_SUCCESS)
1125 {
1126 StringInfoData msg;
1127
1128 initStringInfo(&msg);
1129 appendBinaryStringInfo(&msg, data, nbytes);
1131 pfree(msg.data);
1132 }
1133 else
1134 ereport(ERROR,
1136 errmsg("lost connection to the logical replication parallel apply worker")));
1137 }
1138
1139 MemoryContextSwitchTo(oldcontext);
1140
1141 /* Might as well clear the context on our way out */
1143
1145}
static void ProcessParallelApplyMessage(StringInfo msg)
MemoryContext TopMemoryContext
Definition mcxt.c:166
#define RESUME_INTERRUPTS()
Definition miscadmin.h:136
#define HOLD_INTERRUPTS()
Definition miscadmin.h:134
void appendBinaryStringInfo(StringInfo str, const void *data, int datalen)
Definition stringinfo.c:281
void initStringInfo(StringInfo str)
Definition stringinfo.c:97

References ALLOCSET_DEFAULT_SIZES, AllocSetContextCreate, appendBinaryStringInfo(), StringInfoData::data, data, ereport, errcode(), errmsg(), ERROR, ParallelApplyWorkerInfo::error_mq_handle, fb(), HOLD_INTERRUPTS, initStringInfo(), lfirst, MemoryContextReset(), MemoryContextSwitchTo(), ParallelApplyMessagePending, ParallelApplyWorkerPool, pfree(), ProcessParallelApplyMessage(), RESUME_INTERRUPTS, shm_mq_receive(), SHM_MQ_SUCCESS, SHM_MQ_WOULD_BLOCK, and TopMemoryContext.

Referenced by ProcessInterrupts().

Variable Documentation

◆ MyParallelShared

◆ ParallelApplyMessagePending

◆ ParallelApplyTxnHash

HTAB* ParallelApplyTxnHash = NULL
static

Definition at line 227 of file applyparallelworker.c.

Referenced by pa_allocate_worker(), pa_find_worker(), and pa_free_worker().

◆ ParallelApplyWorkerPool

◆ stream_apply_worker

ParallelApplyWorkerInfo* stream_apply_worker = NULL
static

Definition at line 254 of file applyparallelworker.c.

Referenced by pa_find_worker(), and pa_set_stream_apply_worker().

◆ subxactlist

List* subxactlist = NIL
static

Definition at line 257 of file applyparallelworker.c.

Referenced by pa_reset_subtrans(), pa_start_subtrans(), and pa_stream_abort().