Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : * applyparallelworker.c
3 : : * Support routines for applying xact by parallel apply worker
4 : : *
5 : : * Copyright (c) 2023-2026, PostgreSQL Global Development Group
6 : : *
7 : : * IDENTIFICATION
8 : : * src/backend/replication/logical/applyparallelworker.c
9 : : *
10 : : * This file contains the code to launch, set up, and teardown a parallel apply
11 : : * worker which receives the changes from the leader worker and invokes routines
12 : : * to apply those on the subscriber database. Additionally, this file contains
13 : : * routines that are intended to support setting up, using, and tearing down a
14 : : * ParallelApplyWorkerInfo which is required so the leader worker and parallel
15 : : * apply workers can communicate with each other.
16 : : *
17 : : * The parallel apply workers are assigned (if available) as soon as xact's
18 : : * first stream is received for subscriptions that have set their 'streaming'
19 : : * option as parallel. The leader apply worker will send changes to this new
20 : : * worker via shared memory. We keep this worker assigned till the transaction
21 : : * commit is received and also wait for the worker to finish at commit. This
22 : : * preserves commit ordering and avoid file I/O in most cases, although we
23 : : * still need to spill to a file if there is no worker available. See comments
24 : : * atop logical/worker to know more about streamed xacts whose changes are
25 : : * spilled to disk. It is important to maintain commit order to avoid failures
26 : : * due to: (a) transaction dependencies - say if we insert a row in the first
27 : : * transaction and update it in the second transaction on publisher then
28 : : * allowing the subscriber to apply both in parallel can lead to failure in the
29 : : * update; (b) deadlocks - allowing transactions that update the same set of
30 : : * rows/tables in the opposite order to be applied in parallel can lead to
31 : : * deadlocks.
32 : : *
33 : : * A worker pool is used to avoid restarting workers for each streaming
34 : : * transaction. We maintain each worker's information (ParallelApplyWorkerInfo)
35 : : * in the ParallelApplyWorkerPool. After successfully launching a new worker,
36 : : * its information is added to the ParallelApplyWorkerPool. Once the worker
37 : : * finishes applying the transaction, it is marked as available for re-use.
38 : : * Now, before starting a new worker to apply the streaming transaction, we
39 : : * check the list for any available worker. Note that we retain a maximum of
40 : : * half the max_parallel_apply_workers_per_subscription workers in the pool and
41 : : * after that, we simply exit the worker after applying the transaction.
42 : : *
43 : : * XXX This worker pool threshold is arbitrary and we can provide a GUC
44 : : * variable for this in the future if required.
45 : : *
46 : : * The leader apply worker will create a separate dynamic shared memory segment
47 : : * when each parallel apply worker starts. The reason for this design is that
48 : : * we cannot predict how many workers will be needed. It may be possible to
49 : : * allocate enough shared memory in one segment based on the maximum number of
50 : : * parallel apply workers (max_parallel_apply_workers_per_subscription), but
51 : : * this would waste memory if no process is actually started.
52 : : *
53 : : * The dynamic shared memory segment contains: (a) a shm_mq that is used to
54 : : * send changes in the transaction from leader apply worker to parallel apply
55 : : * worker; (b) another shm_mq that is used to send errors (and other messages
56 : : * reported via elog/ereport) from the parallel apply worker to leader apply
57 : : * worker; (c) necessary information to be shared among parallel apply workers
58 : : * and the leader apply worker (i.e. members of ParallelApplyWorkerShared).
59 : : *
60 : : * Locking Considerations
61 : : * ----------------------
62 : : * We have a risk of deadlock due to concurrently applying the transactions in
63 : : * parallel mode that were independent on the publisher side but became
64 : : * dependent on the subscriber side due to the different database structures
65 : : * (like schema of subscription tables, constraints, etc.) on each side. This
66 : : * can happen even without parallel mode when there are concurrent operations
67 : : * on the subscriber. In order to detect the deadlocks among leader (LA) and
68 : : * parallel apply (PA) workers, we used lmgr locks when the PA waits for the
69 : : * next stream (set of changes) and LA waits for PA to finish the transaction.
70 : : * An alternative approach could be to not allow parallelism when the schema of
71 : : * tables is different between the publisher and subscriber but that would be
72 : : * too restrictive and would require the publisher to send much more
73 : : * information than it is currently sending.
74 : : *
75 : : * Consider a case where the subscribed table does not have a unique key on the
76 : : * publisher and has a unique key on the subscriber. The deadlock can happen in
77 : : * the following ways:
78 : : *
79 : : * 1) Deadlock between the leader apply worker and a parallel apply worker
80 : : *
81 : : * Consider that the parallel apply worker (PA) is executing TX-1 and the
82 : : * leader apply worker (LA) is executing TX-2 concurrently on the subscriber.
83 : : * Now, LA is waiting for PA because of the unique key constraint of the
84 : : * subscribed table while PA is waiting for LA to send the next stream of
85 : : * changes or transaction finish command message.
86 : : *
87 : : * In order for lmgr to detect this, we have LA acquire a session lock on the
88 : : * remote transaction (by pa_lock_stream()) and have PA wait on the lock before
89 : : * trying to receive the next stream of changes. Specifically, LA will acquire
90 : : * the lock in AccessExclusive mode before sending the STREAM_STOP and will
91 : : * release it if already acquired after sending the STREAM_START, STREAM_ABORT
92 : : * (for toplevel transaction), STREAM_PREPARE, and STREAM_COMMIT. The PA will
93 : : * acquire the lock in AccessShare mode after processing STREAM_STOP and
94 : : * STREAM_ABORT (for subtransaction) and then release the lock immediately
95 : : * after acquiring it.
96 : : *
97 : : * The lock graph for the above example will look as follows:
98 : : * LA (waiting to acquire the lock on the unique index) -> PA (waiting to
99 : : * acquire the stream lock) -> LA
100 : : *
101 : : * This way, when PA is waiting for LA for the next stream of changes, we can
102 : : * have a wait-edge from PA to LA in lmgr, which will make us detect the
103 : : * deadlock between LA and PA.
104 : : *
105 : : * 2) Deadlock between the leader apply worker and parallel apply workers
106 : : *
107 : : * This scenario is similar to the first case but TX-1 and TX-2 are executed by
108 : : * two parallel apply workers (PA-1 and PA-2 respectively). In this scenario,
109 : : * PA-2 is waiting for PA-1 to complete its transaction while PA-1 is waiting
110 : : * for subsequent input from LA. Also, LA is waiting for PA-2 to complete its
111 : : * transaction in order to preserve the commit order. There is a deadlock among
112 : : * the three processes.
113 : : *
114 : : * In order for lmgr to detect this, we have PA acquire a session lock (this is
115 : : * a different lock than referred in the previous case, see
116 : : * pa_lock_transaction()) on the transaction being applied and have LA wait on
117 : : * the lock before proceeding in the transaction finish commands. Specifically,
118 : : * PA will acquire this lock in AccessExclusive mode before executing the first
119 : : * message of the transaction and release it at the xact end. LA will acquire
120 : : * this lock in AccessShare mode at transaction finish commands and release it
121 : : * immediately.
122 : : *
123 : : * The lock graph for the above example will look as follows:
124 : : * LA (waiting to acquire the transaction lock) -> PA-2 (waiting to acquire the
125 : : * lock due to unique index constraint) -> PA-1 (waiting to acquire the stream
126 : : * lock) -> LA
127 : : *
128 : : * This way when LA is waiting to finish the transaction end command to preserve
129 : : * the commit order, we will be able to detect deadlock, if any.
130 : : *
131 : : * One might think we can use XactLockTableWait(), but XactLockTableWait()
132 : : * considers PREPARED TRANSACTION as still in progress which means the lock
133 : : * won't be released even after the parallel apply worker has prepared the
134 : : * transaction.
135 : : *
136 : : * 3) Deadlock when the shm_mq buffer is full
137 : : *
138 : : * In the previous scenario (ie. PA-1 and PA-2 are executing transactions
139 : : * concurrently), if the shm_mq buffer between LA and PA-2 is full, LA has to
140 : : * wait to send messages, and this wait doesn't appear in lmgr.
141 : : *
142 : : * To avoid this wait, we use a non-blocking write and wait with a timeout. If
143 : : * the timeout is exceeded, the LA will serialize all the pending messages to
144 : : * a file and indicate PA-2 that it needs to read that file for the remaining
145 : : * messages. Then LA will start waiting for commit as in the previous case
146 : : * which will detect deadlock if any. See pa_send_data() and
147 : : * enum TransApplyAction.
148 : : *
149 : : * Lock types
150 : : * ----------
151 : : * Both the stream lock and the transaction lock mentioned above are
152 : : * session-level locks because both locks could be acquired outside the
153 : : * transaction, and the stream lock in the leader needs to persist across
154 : : * transaction boundaries i.e. until the end of the streaming transaction.
155 : : *-------------------------------------------------------------------------
156 : : */
157 : :
158 : : #include "postgres.h"
159 : :
160 : : #include "libpq/pqformat.h"
161 : : #include "libpq/pqmq.h"
162 : : #include "pgstat.h"
163 : : #include "postmaster/interrupt.h"
164 : : #include "replication/logicallauncher.h"
165 : : #include "replication/logicalworker.h"
166 : : #include "replication/origin.h"
167 : : #include "replication/worker_internal.h"
168 : : #include "storage/ipc.h"
169 : : #include "storage/latch.h"
170 : : #include "storage/lmgr.h"
171 : : #include "storage/proc.h"
172 : : #include "storage/procsignal.h"
173 : : #include "tcop/tcopprot.h"
174 : : #include "utils/inval.h"
175 : : #include "utils/memutils.h"
176 : : #include "utils/syscache.h"
177 : : #include "utils/wait_event.h"
178 : :
179 : : #define PG_LOGICAL_APPLY_SHM_MAGIC 0x787ca067
180 : :
181 : : /*
182 : : * DSM keys for parallel apply worker. Unlike other parallel execution code,
183 : : * since we don't need to worry about DSM keys conflicting with plan_node_id we
184 : : * can use small integers.
185 : : */
186 : : #define PARALLEL_APPLY_KEY_SHARED 1
187 : : #define PARALLEL_APPLY_KEY_MQ 2
188 : : #define PARALLEL_APPLY_KEY_ERROR_QUEUE 3
189 : :
190 : : /* Queue size of DSM, 16 MB for now. */
191 : : #define DSM_QUEUE_SIZE (16 * 1024 * 1024)
192 : :
193 : : /*
194 : : * Error queue size of DSM. It is desirable to make it large enough that a
195 : : * typical ErrorResponse can be sent without blocking. That way, a worker that
196 : : * errors out can write the whole message into the queue and terminate without
197 : : * waiting for the user backend.
198 : : */
199 : : #define DSM_ERROR_QUEUE_SIZE (16 * 1024)
200 : :
201 : : /*
202 : : * There are three fields in each message received by the parallel apply
203 : : * worker: start_lsn, end_lsn and send_time. Because we have updated these
204 : : * statistics in the leader apply worker, we can ignore these fields in the
205 : : * parallel apply worker (see function LogicalRepApplyLoop).
206 : : */
207 : : #define SIZE_STATS_MESSAGE (2 * sizeof(XLogRecPtr) + sizeof(TimestampTz))
208 : :
209 : : /*
210 : : * The type of session-level lock on a transaction being applied on a logical
211 : : * replication subscriber.
212 : : */
213 : : #define PARALLEL_APPLY_LOCK_STREAM 0
214 : : #define PARALLEL_APPLY_LOCK_XACT 1
215 : :
216 : : /*
217 : : * Hash table entry to map xid to the parallel apply worker state.
218 : : */
219 : : typedef struct ParallelApplyWorkerEntry
220 : : {
221 : : TransactionId xid; /* Hash key -- must be first */
222 : : ParallelApplyWorkerInfo *winfo;
223 : : } ParallelApplyWorkerEntry;
224 : :
225 : : /*
226 : : * A hash table used to cache the state of streaming transactions being applied
227 : : * by the parallel apply workers.
228 : : */
229 : : static HTAB *ParallelApplyTxnHash = NULL;
230 : :
231 : : /*
232 : : * A list (pool) of active parallel apply workers. The information for
233 : : * the new worker is added to the list after successfully launching it. The
234 : : * list entry is removed if there are already enough workers in the worker
235 : : * pool at the end of the transaction. For more information about the worker
236 : : * pool, see comments atop this file.
237 : : */
238 : : static List *ParallelApplyWorkerPool = NIL;
239 : :
240 : : /*
241 : : * Information shared between leader apply worker and parallel apply worker.
242 : : */
243 : : ParallelApplyWorkerShared *MyParallelShared = NULL;
244 : :
245 : : /*
246 : : * Is there a message sent by a parallel apply worker that the leader apply
247 : : * worker needs to receive?
248 : : */
249 : : volatile sig_atomic_t ParallelApplyMessagePending = false;
250 : :
251 : : /*
252 : : * Cache the parallel apply worker information required for applying the
253 : : * current streaming transaction. It is used to save the cost of searching the
254 : : * hash table when applying the changes between STREAM_START and STREAM_STOP.
255 : : */
256 : : static ParallelApplyWorkerInfo *stream_apply_worker = NULL;
257 : :
258 : : /* A list to maintain subtransactions, if any. */
259 : : static List *subxactlist = NIL;
260 : :
261 : : static void pa_free_worker_info(ParallelApplyWorkerInfo *winfo);
262 : : static ParallelTransState pa_get_xact_state(ParallelApplyWorkerShared *wshared);
263 : : static PartialFileSetState pa_get_fileset_state(void);
264 : :
265 : : /*
266 : : * Returns true if it is OK to start a parallel apply worker, false otherwise.
267 : : */
268 : : static bool
1419 akapila@postgresql.o 269 :CBC 86 : pa_can_start(void)
270 : : {
271 : : /* Only leader apply workers can start parallel apply workers. */
272 [ + + ]: 86 : if (!am_leader_apply_worker())
273 : 29 : return false;
274 : :
275 : : /*
276 : : * It is good to check for any change in the subscription parameter to
277 : : * avoid the case where for a very long time the change doesn't get
278 : : * reflected. This can happen when there is a constant flow of streaming
279 : : * transactions that are handled by parallel apply workers.
280 : : *
281 : : * It is better to do it before the below checks so that the latest values
282 : : * of subscription can be used for the checks.
283 : : */
284 : 57 : maybe_reread_subscription();
285 : :
286 : : /*
287 : : * Don't start a new parallel apply worker if the subscription is not
288 : : * using parallel streaming mode, or if the publisher does not support
289 : : * parallel apply.
290 : : */
291 [ + + ]: 57 : if (!MyLogicalRepWorker->parallel_apply)
292 : 28 : return false;
293 : :
294 : : /*
295 : : * Don't start a new parallel worker if user has set skiplsn as it's
296 : : * possible that they want to skip the streaming transaction. For
297 : : * streaming transactions, we need to serialize the transaction to a file
298 : : * so that we can get the last LSN of the transaction to judge whether to
299 : : * skip before starting to apply the change.
300 : : *
301 : : * One might think that we could allow parallelism if the first lsn of the
302 : : * transaction is greater than skiplsn, but we don't send it with the
303 : : * STREAM START message, and it doesn't seem worth sending the extra eight
304 : : * bytes with the STREAM START to enable parallelism for this case.
305 : : */
387 alvherre@kurilemu.de 306 [ - + ]: 29 : if (XLogRecPtrIsValid(MySubscription->skiplsn))
1419 akapila@postgresql.o 307 :UBC 0 : return false;
308 : :
309 : : /*
310 : : * For streaming transactions that are being applied using a parallel
311 : : * apply worker, we cannot decide whether to apply the change for a
312 : : * relation that is not in the READY state (see
313 : : * should_apply_changes_for_rel) as we won't know the finish LSN of the
314 : : * transaction by that time. So, we don't start the new parallel apply
315 : : * worker in this case.
316 : : */
1419 akapila@postgresql.o 317 [ - + ]:CBC 29 : if (!AllTablesyncsReady())
1419 akapila@postgresql.o 318 :UBC 0 : return false;
319 : :
1419 akapila@postgresql.o 320 :CBC 29 : return true;
321 : : }
322 : :
323 : : /*
324 : : * Set up a dynamic shared memory segment.
325 : : *
326 : : * We set up a control region that contains a fixed-size worker info
327 : : * (ParallelApplyWorkerShared), a message queue, and an error queue.
328 : : *
329 : : * Returns true on success, false on failure.
330 : : */
331 : : static bool
332 : 12 : pa_setup_dsm(ParallelApplyWorkerInfo *winfo)
333 : : {
334 : : shm_toc_estimator e;
335 : : Size segsize;
336 : : dsm_segment *seg;
337 : : shm_toc *toc;
338 : : ParallelApplyWorkerShared *shared;
339 : : shm_mq *mq;
340 : 12 : Size queue_size = DSM_QUEUE_SIZE;
341 : 12 : Size error_queue_size = DSM_ERROR_QUEUE_SIZE;
342 : :
343 : : /*
344 : : * Estimate how much shared memory we need.
345 : : *
346 : : * Because the TOC machinery may choose to insert padding of oddly-sized
347 : : * requests, we must estimate each chunk separately.
348 : : *
349 : : * We need one key to register the location of the header, and two other
350 : : * keys to track the locations of the message queue and the error message
351 : : * queue.
352 : : */
353 : 12 : shm_toc_initialize_estimator(&e);
354 : 12 : shm_toc_estimate_chunk(&e, sizeof(ParallelApplyWorkerShared));
355 : 12 : shm_toc_estimate_chunk(&e, queue_size);
356 : 12 : shm_toc_estimate_chunk(&e, error_queue_size);
357 : :
358 : 12 : shm_toc_estimate_keys(&e, 3);
359 : 12 : segsize = shm_toc_estimate(&e);
360 : :
361 : : /* Create the shared memory segment and establish a table of contents. */
10 msawada@postgresql.o 362 : 12 : seg = dsm_create(shm_toc_estimate(&e), DSM_CREATE_NULL_IF_MAXSEGMENTS);
1419 akapila@postgresql.o 363 [ - + ]: 12 : if (!seg)
1419 akapila@postgresql.o 364 :UBC 0 : return false;
365 : :
1419 akapila@postgresql.o 366 :CBC 12 : toc = shm_toc_create(PG_LOGICAL_APPLY_SHM_MAGIC, dsm_segment_address(seg),
367 : : segsize);
368 : :
369 : : /* Set up the header region. */
370 : 12 : shared = shm_toc_allocate(toc, sizeof(ParallelApplyWorkerShared));
371 : 12 : SpinLockInit(&shared->mutex);
372 : :
373 : 12 : shared->xact_state = PARALLEL_TRANS_UNKNOWN;
374 : 12 : pg_atomic_init_u32(&(shared->pending_stream_count), 0);
375 : 12 : shared->last_commit_end = InvalidXLogRecPtr;
376 : 12 : shared->fileset_state = FS_EMPTY;
377 : :
378 : 12 : shm_toc_insert(toc, PARALLEL_APPLY_KEY_SHARED, shared);
379 : :
380 : : /* Set up message queue for the worker. */
381 : 12 : mq = shm_mq_create(shm_toc_allocate(toc, queue_size), queue_size);
382 : 12 : shm_toc_insert(toc, PARALLEL_APPLY_KEY_MQ, mq);
383 : 12 : shm_mq_set_sender(mq, MyProc);
384 : :
385 : : /* Attach the queue. */
386 : 12 : winfo->mq_handle = shm_mq_attach(mq, seg, NULL);
387 : :
388 : : /* Set up error queue for the worker. */
389 : 12 : mq = shm_mq_create(shm_toc_allocate(toc, error_queue_size),
390 : : error_queue_size);
391 : 12 : shm_toc_insert(toc, PARALLEL_APPLY_KEY_ERROR_QUEUE, mq);
392 : 12 : shm_mq_set_receiver(mq, MyProc);
393 : :
394 : : /* Attach the queue. */
395 : 12 : winfo->error_mq_handle = shm_mq_attach(mq, seg, NULL);
396 : :
397 : : /* Return results to caller. */
398 : 12 : winfo->dsm_seg = seg;
399 : 12 : winfo->shared = shared;
400 : :
401 : 12 : return true;
402 : : }
403 : :
404 : : /*
405 : : * Try to get a parallel apply worker from the pool. If none is available then
406 : : * start a new one.
407 : : */
408 : : static ParallelApplyWorkerInfo *
409 : 29 : pa_launch_parallel_worker(void)
410 : : {
411 : : MemoryContext oldcontext;
412 : : bool launched;
413 : : ParallelApplyWorkerInfo *winfo;
414 : : ListCell *lc;
415 : :
416 : : /* Try to get an available parallel apply worker from the worker pool. */
417 [ + + + + : 31 : foreach(lc, ParallelApplyWorkerPool)
+ + ]
418 : : {
419 : 19 : winfo = (ParallelApplyWorkerInfo *) lfirst(lc);
420 : :
421 [ + + ]: 19 : if (!winfo->in_use)
422 : 17 : return winfo;
423 : : }
424 : :
425 : : /*
426 : : * Start a new parallel apply worker.
427 : : *
428 : : * The worker info can be used for the lifetime of the worker process, so
429 : : * create it in a permanent context.
430 : : */
431 : 12 : oldcontext = MemoryContextSwitchTo(ApplyContext);
432 : :
353 michael@paquier.xyz 433 : 12 : winfo = palloc0_object(ParallelApplyWorkerInfo);
434 : :
435 : : /* Setup shared memory. */
1419 akapila@postgresql.o 436 [ - + ]: 12 : if (!pa_setup_dsm(winfo))
437 : : {
1419 akapila@postgresql.o 438 :UBC 0 : MemoryContextSwitchTo(oldcontext);
439 : 0 : pfree(winfo);
440 : 0 : return NULL;
441 : : }
442 : :
1202 akapila@postgresql.o 443 :CBC 12 : launched = logicalrep_worker_launch(WORKERTYPE_PARALLEL_APPLY,
444 : 12 : MyLogicalRepWorker->dbid,
1419 445 : 12 : MySubscription->oid,
446 : 12 : MySubscription->name,
447 : 12 : MyLogicalRepWorker->userid,
448 : : InvalidOid,
449 : : dsm_segment_handle(winfo->dsm_seg),
450 : : false);
451 : :
452 [ + - ]: 12 : if (launched)
453 : : {
454 : 12 : ParallelApplyWorkerPool = lappend(ParallelApplyWorkerPool, winfo);
455 : : }
456 : : else
457 : : {
1419 akapila@postgresql.o 458 :UBC 0 : pa_free_worker_info(winfo);
459 : 0 : winfo = NULL;
460 : : }
461 : :
1419 akapila@postgresql.o 462 :CBC 12 : MemoryContextSwitchTo(oldcontext);
463 : :
464 : 12 : return winfo;
465 : : }
466 : :
467 : : /*
468 : : * Allocate a parallel apply worker that will be used for the specified xid.
469 : : *
470 : : * We first try to get an available worker from the pool, if any and then try
471 : : * to launch a new worker. On successful allocation, remember the worker
472 : : * information in the hash table so that we can get it later for processing the
473 : : * streaming changes.
474 : : */
475 : : void
476 : 86 : pa_allocate_worker(TransactionId xid)
477 : : {
478 : : bool found;
479 : 86 : ParallelApplyWorkerInfo *winfo = NULL;
480 : : ParallelApplyWorkerEntry *entry;
481 : :
482 [ + + ]: 86 : if (!pa_can_start())
483 : 57 : return;
484 : :
1415 485 : 29 : winfo = pa_launch_parallel_worker();
486 [ - + ]: 29 : if (!winfo)
1415 akapila@postgresql.o 487 :UBC 0 : return;
488 : :
489 : : /* First time through, initialize parallel apply worker state hashtable. */
1419 akapila@postgresql.o 490 [ + + ]:CBC 29 : if (!ParallelApplyTxnHash)
491 : : {
492 : : HASHCTL ctl;
493 : :
494 [ + - + - : 99 : MemSet(&ctl, 0, sizeof(ctl));
+ - + - +
+ ]
495 : 9 : ctl.keysize = sizeof(TransactionId);
496 : 9 : ctl.entrysize = sizeof(ParallelApplyWorkerEntry);
497 : 9 : ctl.hcxt = ApplyContext;
498 : :
499 : 9 : ParallelApplyTxnHash = hash_create("logical replication parallel apply workers hash",
500 : : 16, &ctl,
501 : : HASH_ELEM | HASH_BLOBS | HASH_CONTEXT);
502 : : }
503 : :
504 : : /* Create an entry for the requested transaction. */
505 : 29 : entry = hash_search(ParallelApplyTxnHash, &xid, HASH_ENTER, &found);
506 [ - + ]: 29 : if (found)
1419 akapila@postgresql.o 507 [ # # ]:UBC 0 : elog(ERROR, "hash table corrupted");
508 : :
509 : : /* Update the transaction information in shared memory. */
1419 akapila@postgresql.o 510 :CBC 29 : SpinLockAcquire(&winfo->shared->mutex);
511 : 29 : winfo->shared->xact_state = PARALLEL_TRANS_UNKNOWN;
512 : 29 : winfo->shared->xid = xid;
513 : 29 : SpinLockRelease(&winfo->shared->mutex);
514 : :
515 : 29 : winfo->in_use = true;
516 : 29 : winfo->serialize_changes = false;
517 : 29 : entry->winfo = winfo;
518 : : }
519 : :
520 : : /*
521 : : * Find the assigned worker for the given transaction, if any.
522 : : */
523 : : ParallelApplyWorkerInfo *
524 : 277748 : pa_find_worker(TransactionId xid)
525 : : {
526 : : bool found;
527 : : ParallelApplyWorkerEntry *entry;
528 : :
529 [ + + ]: 277748 : if (!TransactionIdIsValid(xid))
530 : 100800 : return NULL;
531 : :
532 [ + + ]: 176948 : if (!ParallelApplyTxnHash)
533 : 103213 : return NULL;
534 : :
535 : : /* Return the cached parallel apply worker if valid. */
536 [ + + ]: 73735 : if (stream_apply_worker)
537 : 73422 : return stream_apply_worker;
538 : :
539 : : /* Find an entry for the requested transaction. */
540 : 313 : entry = hash_search(ParallelApplyTxnHash, &xid, HASH_FIND, &found);
541 [ + - ]: 313 : if (found)
542 : : {
543 : : /* The worker must not have exited. */
544 [ - + ]: 313 : Assert(entry->winfo->in_use);
545 : 313 : return entry->winfo;
546 : : }
547 : :
1419 akapila@postgresql.o 548 :UBC 0 : return NULL;
549 : : }
550 : :
551 : : /*
552 : : * Makes the worker available for reuse.
553 : : *
554 : : * This removes the parallel apply worker entry from the hash table so that it
555 : : * can't be used. If there are enough workers in the pool, it stops the worker
556 : : * and frees the corresponding info. Otherwise it just marks the worker as
557 : : * available for reuse.
558 : : *
559 : : * For more information about the worker pool, see comments atop this file.
560 : : */
561 : : static void
1419 akapila@postgresql.o 562 :CBC 25 : pa_free_worker(ParallelApplyWorkerInfo *winfo)
563 : : {
564 [ - + ]: 25 : Assert(!am_parallel_apply_worker());
565 [ - + ]: 25 : Assert(winfo->in_use);
566 [ - + ]: 25 : Assert(pa_get_xact_state(winfo->shared) == PARALLEL_TRANS_FINISHED);
567 : :
568 [ - + ]: 25 : if (!hash_search(ParallelApplyTxnHash, &winfo->shared->xid, HASH_REMOVE, NULL))
1419 akapila@postgresql.o 569 [ # # ]:UBC 0 : elog(ERROR, "hash table corrupted");
570 : :
571 : : /*
572 : : * Stop the worker if there are enough workers in the pool.
573 : : *
574 : : * XXX Additionally, we also stop the worker if the leader apply worker
575 : : * serialize part of the transaction data due to a send timeout. This is
576 : : * because the message could be partially written to the queue and there
577 : : * is no way to clean the queue other than resending the message until it
578 : : * succeeds. Instead of trying to send the data which anyway would have
579 : : * been serialized and then letting the parallel apply worker deal with
580 : : * the spurious message, we stop the worker.
581 : : */
1419 akapila@postgresql.o 582 [ + + ]:CBC 25 : if (winfo->serialize_changes ||
583 : 21 : list_length(ParallelApplyWorkerPool) >
584 [ + + ]: 21 : (max_parallel_apply_workers_per_subscription / 2))
585 : : {
1299 586 : 5 : logicalrep_pa_worker_stop(winfo);
1419 587 : 5 : pa_free_worker_info(winfo);
588 : :
589 : 5 : return;
590 : : }
591 : :
592 : 20 : winfo->in_use = false;
593 : 20 : winfo->serialize_changes = false;
594 : : }
595 : :
596 : : /*
597 : : * Free the parallel apply worker information and unlink the files with
598 : : * serialized changes if any.
599 : : */
600 : : static void
601 : 5 : pa_free_worker_info(ParallelApplyWorkerInfo *winfo)
602 : : {
603 [ - + ]: 5 : Assert(winfo);
604 : :
605 [ + - ]: 5 : if (winfo->mq_handle)
606 : 5 : shm_mq_detach(winfo->mq_handle);
607 : :
608 [ - + ]: 5 : if (winfo->error_mq_handle)
1419 akapila@postgresql.o 609 :UBC 0 : shm_mq_detach(winfo->error_mq_handle);
610 : :
611 : : /* Unlink the files with serialized changes. */
1419 akapila@postgresql.o 612 [ + + ]:CBC 5 : if (winfo->serialize_changes)
613 : 4 : stream_cleanup_files(MyLogicalRepWorker->subid, winfo->shared->xid);
614 : :
615 [ + - ]: 5 : if (winfo->dsm_seg)
616 : 5 : dsm_detach(winfo->dsm_seg);
617 : :
618 : : /* Remove from the worker pool. */
619 : 5 : ParallelApplyWorkerPool = list_delete_ptr(ParallelApplyWorkerPool, winfo);
620 : :
621 : 5 : pfree(winfo);
622 : 5 : }
623 : :
624 : : /*
625 : : * Detach the error queue for all parallel apply workers.
626 : : */
627 : : void
628 : 573 : pa_detach_all_error_mq(void)
629 : : {
630 : : ListCell *lc;
631 : :
632 [ + + + + : 580 : foreach(lc, ParallelApplyWorkerPool)
+ + ]
633 : : {
634 : 7 : ParallelApplyWorkerInfo *winfo = (ParallelApplyWorkerInfo *) lfirst(lc);
635 : :
1299 636 [ + - ]: 7 : if (winfo->error_mq_handle)
637 : : {
638 : 7 : shm_mq_detach(winfo->error_mq_handle);
639 : 7 : winfo->error_mq_handle = NULL;
640 : : }
641 : : }
1419 642 : 573 : }
643 : :
644 : : /*
645 : : * Check if there are any pending spooled messages.
646 : : */
647 : : static bool
360 nathan@postgresql.or 648 : 16 : pa_has_spooled_message_pending(void)
649 : : {
650 : : PartialFileSetState fileset_state;
651 : :
1419 akapila@postgresql.o 652 : 16 : fileset_state = pa_get_fileset_state();
653 : :
654 : 16 : return (fileset_state != FS_EMPTY);
655 : : }
656 : :
657 : : /*
658 : : * Replay the spooled messages once the leader apply worker has finished
659 : : * serializing changes to the file.
660 : : *
661 : : * Returns false if there aren't any pending spooled messages, true otherwise.
662 : : */
663 : : static bool
664 : 69 : pa_process_spooled_messages_if_required(void)
665 : : {
666 : : PartialFileSetState fileset_state;
667 : :
668 : 69 : fileset_state = pa_get_fileset_state();
669 : :
670 [ + + ]: 69 : if (fileset_state == FS_EMPTY)
671 : 61 : return false;
672 : :
673 : : /*
674 : : * If the leader apply worker is busy serializing the partial changes then
675 : : * acquire the stream lock now and wait for the leader worker to finish
676 : : * serializing the changes. Otherwise, the parallel apply worker won't get
677 : : * a chance to receive a STREAM_STOP (and acquire the stream lock) until
678 : : * the leader had serialized all changes which can lead to undetected
679 : : * deadlock.
680 : : *
681 : : * Note that the fileset state can be FS_SERIALIZE_DONE once the leader
682 : : * worker has finished serializing the changes.
683 : : */
684 [ - + ]: 8 : if (fileset_state == FS_SERIALIZE_IN_PROGRESS)
685 : : {
1419 akapila@postgresql.o 686 :UBC 0 : pa_lock_stream(MyParallelShared->xid, AccessShareLock);
687 : 0 : pa_unlock_stream(MyParallelShared->xid, AccessShareLock);
688 : :
689 : 0 : fileset_state = pa_get_fileset_state();
690 : : }
691 : :
692 : : /*
693 : : * We cannot read the file immediately after the leader has serialized all
694 : : * changes to the file because there may still be messages in the memory
695 : : * queue. We will apply all spooled messages the next time we call this
696 : : * function and that will ensure there are no messages left in the memory
697 : : * queue.
698 : : */
1419 akapila@postgresql.o 699 [ + + ]:CBC 8 : if (fileset_state == FS_SERIALIZE_DONE)
700 : : {
701 : 4 : pa_set_fileset_state(MyParallelShared, FS_READY);
702 : : }
703 [ + - ]: 4 : else if (fileset_state == FS_READY)
704 : : {
705 : 4 : apply_spooled_messages(&MyParallelShared->fileset,
706 : 4 : MyParallelShared->xid,
707 : : InvalidXLogRecPtr);
708 : 4 : pa_set_fileset_state(MyParallelShared, FS_EMPTY);
709 : : }
710 : :
711 : 8 : return true;
712 : : }
713 : :
714 : : /*
715 : : * Interrupt handler for main loop of parallel apply worker.
716 : : */
717 : : static void
718 : 63851 : ProcessParallelApplyInterrupts(void)
719 : : {
720 [ + + ]: 63851 : CHECK_FOR_INTERRUPTS();
721 : :
722 [ + + ]: 63847 : if (ShutdownRequestPending)
723 : : {
724 [ + - ]: 5 : ereport(LOG,
725 : : (errmsg("logical replication parallel apply worker for subscription \"%s\" has finished",
726 : : MySubscription->name)));
727 : :
728 : 5 : proc_exit(0);
729 : : }
730 : :
731 [ + + ]: 63842 : if (ConfigReloadPending)
732 : : {
733 : 4 : ConfigReloadPending = false;
734 : 4 : ProcessConfigFile(PGC_SIGHUP);
735 : : }
736 : 63842 : }
737 : :
738 : : /* Parallel apply worker main loop. */
739 : : static void
740 : 12 : LogicalParallelApplyLoop(shm_mq_handle *mqh)
741 : : {
742 : : shm_mq_result shmq_res;
743 : : ErrorContextCallback errcallback;
744 : 12 : MemoryContext oldcxt = CurrentMemoryContext;
745 : :
746 : : /*
747 : : * Init the ApplyMessageContext which we clean up after each replication
748 : : * protocol message.
749 : : */
750 : 12 : ApplyMessageContext = AllocSetContextCreate(ApplyContext,
751 : : "ApplyMessageContext",
752 : : ALLOCSET_DEFAULT_SIZES);
753 : :
754 : : /*
755 : : * Push apply error context callback. Fields will be filled while applying
756 : : * a change.
757 : : */
758 : 12 : errcallback.callback = apply_error_callback;
759 : 12 : errcallback.previous = error_context_stack;
760 : 12 : error_context_stack = &errcallback;
761 : :
762 : : for (;;)
763 : 63839 : {
764 : : void *data;
765 : : Size len;
766 : :
767 : 63851 : ProcessParallelApplyInterrupts();
768 : :
769 : : /* Ensure we are reading the data into our memory context. */
770 : 63842 : MemoryContextSwitchTo(ApplyMessageContext);
771 : :
772 : 63842 : shmq_res = shm_mq_receive(mqh, &len, &data, true);
773 : :
774 [ + + ]: 63842 : if (shmq_res == SHM_MQ_SUCCESS)
775 : : {
776 : : StringInfoData s;
777 : : int c;
778 : :
779 [ - + ]: 63773 : if (len == 0)
1419 akapila@postgresql.o 780 [ # # ]:UBC 0 : elog(ERROR, "invalid message length");
781 : :
1129 drowley@postgresql.o 782 :CBC 63773 : initReadOnlyStringInfo(&s, data, len);
783 : :
784 : : /*
785 : : * The first byte of messages sent from leader apply worker to
786 : : * parallel apply workers can only be PqReplMsg_WALData.
787 : : */
1419 akapila@postgresql.o 788 : 63773 : c = pq_getmsgbyte(&s);
479 nathan@postgresql.or 789 [ - + ]: 63773 : if (c != PqReplMsg_WALData)
1419 akapila@postgresql.o 790 [ # # ]:UBC 0 : elog(ERROR, "unexpected message \"%c\"", c);
791 : :
792 : : /*
793 : : * Ignore statistics fields that have been updated by the leader
794 : : * apply worker.
795 : : *
796 : : * XXX We can avoid sending the statistics fields from the leader
797 : : * apply worker but for that, it needs to rebuild the entire
798 : : * message by removing these fields which could be more work than
799 : : * simply ignoring these fields in the parallel apply worker.
800 : : */
1419 akapila@postgresql.o 801 :CBC 63773 : s.cursor += SIZE_STATS_MESSAGE;
802 : :
803 : 63773 : apply_dispatch(&s);
804 : : }
805 [ + - ]: 69 : else if (shmq_res == SHM_MQ_WOULD_BLOCK)
806 : : {
807 : : /* Replay the changes from the file, if any. */
808 [ + + ]: 69 : if (!pa_process_spooled_messages_if_required())
809 : : {
810 : : int rc;
811 : :
812 : : /* Wait for more work. */
813 : 61 : rc = WaitLatch(MyLatch,
814 : : WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
815 : : 1000L,
816 : : WAIT_EVENT_LOGICAL_PARALLEL_APPLY_MAIN);
817 : :
818 [ + + ]: 61 : if (rc & WL_LATCH_SET)
819 : 58 : ResetLatch(MyLatch);
820 : :
821 : : /*
822 : : * Force stats reporting to avoid long delays. There can be
823 : : * long idle gaps before the leader assigns the next
824 : : * transaction, and the only opportunity to report stats
825 : : * during such gaps is here.
826 : : */
222 827 [ + + + - ]: 61 : if ((rc & WL_TIMEOUT) && !IsTransactionState())
828 : 3 : pgstat_report_stat(true);
829 : : }
830 : : }
831 : : else
832 : : {
1419 akapila@postgresql.o 833 [ # # ]:UBC 0 : Assert(shmq_res == SHM_MQ_DETACHED);
834 : :
835 [ # # ]: 0 : ereport(ERROR,
836 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
837 : : errmsg("lost connection to the logical replication apply worker")));
838 : : }
839 : :
1419 akapila@postgresql.o 840 :CBC 63839 : MemoryContextReset(ApplyMessageContext);
841 : 63839 : MemoryContextSwitchTo(oldcxt);
842 : : }
843 : :
844 : : /* Pop the error context stack. */
845 : : error_context_stack = errcallback.previous;
846 : :
847 : : MemoryContextSwitchTo(oldcxt);
848 : : }
849 : :
850 : : /*
851 : : * Make sure the leader apply worker tries to read from our error queue one more
852 : : * time. This guards against the case where we exit uncleanly without sending
853 : : * an ErrorResponse, for example because some code calls proc_exit directly.
854 : : *
855 : : * Also explicitly detach from dsm segment to invoke on_dsm_detach callbacks,
856 : : * if any. See ParallelWorkerShutdown for details.
857 : : */
858 : : static void
859 : 12 : pa_shutdown(int code, Datum arg)
860 : : {
1410 861 : 12 : SendProcSignal(MyLogicalRepWorker->leader_pid,
862 : : PROCSIG_PARALLEL_APPLY_MESSAGE,
863 : : INVALID_PROC_NUMBER);
864 : :
1419 865 : 12 : dsm_detach((dsm_segment *) DatumGetPointer(arg));
866 : 12 : }
867 : :
868 : : /*
869 : : * Parallel apply worker entry point.
870 : : */
871 : : void
872 : 12 : ParallelApplyWorkerMain(Datum main_arg)
873 : : {
874 : : ParallelApplyWorkerShared *shared;
875 : : dsm_handle handle;
876 : : dsm_segment *seg;
877 : : shm_toc *toc;
878 : : shm_mq *mq;
879 : : shm_mq_handle *mqh;
880 : : shm_mq_handle *error_mqh;
881 : : ReplOriginId originid;
882 : 12 : int worker_slot = DatumGetInt32(main_arg);
883 : : char originname[NAMEDATALEN];
884 : :
1305 885 : 12 : InitializingApplyWorker = true;
886 : :
887 : : /*
888 : : * Setup signal handling.
889 : : *
890 : : * Note: We intentionally used SIGUSR2 to trigger a graceful shutdown
891 : : * initiated by the leader apply worker. This helps to differentiate it
892 : : * from the case where we abort the current transaction and exit on
893 : : * receiving SIGTERM.
894 : : */
1419 895 : 12 : pqsignal(SIGHUP, SignalHandlerForConfigReload);
430 896 : 12 : pqsignal(SIGUSR2, SignalHandlerForShutdownRequest);
1419 897 : 12 : BackgroundWorkerUnblockSignals();
898 : :
899 : : /*
900 : : * Attach to the dynamic shared memory segment for the parallel apply, and
901 : : * find its table of contents.
902 : : *
903 : : * Like parallel query, we don't need resource owner by this time. See
904 : : * ParallelWorkerMain.
905 : : */
906 : 12 : memcpy(&handle, MyBgworkerEntry->bgw_extra, sizeof(dsm_handle));
907 : 12 : seg = dsm_attach(handle);
908 [ - + ]: 12 : if (!seg)
1419 akapila@postgresql.o 909 [ # # ]:UBC 0 : ereport(ERROR,
910 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
911 : : errmsg("could not map dynamic shared memory segment")));
912 : :
1419 akapila@postgresql.o 913 :CBC 12 : toc = shm_toc_attach(PG_LOGICAL_APPLY_SHM_MAGIC, dsm_segment_address(seg));
914 [ - + ]: 12 : if (!toc)
1419 akapila@postgresql.o 915 [ # # ]:UBC 0 : ereport(ERROR,
916 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
917 : : errmsg("invalid magic number in dynamic shared memory segment")));
918 : :
919 : : /* Look up the shared information. */
1419 akapila@postgresql.o 920 :CBC 12 : shared = shm_toc_lookup(toc, PARALLEL_APPLY_KEY_SHARED, false);
921 : 12 : MyParallelShared = shared;
922 : :
923 : : /*
924 : : * Attach to the message queue.
925 : : */
926 : 12 : mq = shm_toc_lookup(toc, PARALLEL_APPLY_KEY_MQ, false);
927 : 12 : shm_mq_set_receiver(mq, MyProc);
928 : 12 : mqh = shm_mq_attach(mq, seg, NULL);
929 : :
930 : : /*
931 : : * Primary initialization is complete. Now, we can attach to our slot.
932 : : * This is to ensure that the leader apply worker does not write data to
933 : : * the uninitialized memory queue.
934 : : */
935 : 12 : logicalrep_worker_attach(worker_slot);
936 : :
937 : : /*
938 : : * Register the shutdown callback after we are attached to the worker
939 : : * slot. This is to ensure that MyLogicalRepWorker remains valid when this
940 : : * callback is invoked.
941 : : */
1299 942 : 12 : before_shmem_exit(pa_shutdown, PointerGetDatum(seg));
943 : :
1419 944 : 12 : SpinLockAcquire(&MyParallelShared->mutex);
945 : 12 : MyParallelShared->logicalrep_worker_generation = MyLogicalRepWorker->generation;
946 : 12 : MyParallelShared->logicalrep_worker_slot_no = worker_slot;
947 : 12 : SpinLockRelease(&MyParallelShared->mutex);
948 : :
949 : : /*
950 : : * Attach to the error queue.
951 : : */
952 : 12 : mq = shm_toc_lookup(toc, PARALLEL_APPLY_KEY_ERROR_QUEUE, false);
953 : 12 : shm_mq_set_sender(mq, MyProc);
954 : 12 : error_mqh = shm_mq_attach(mq, seg, NULL);
955 : :
956 : 12 : pq_redirect_to_shm_mq(seg, error_mqh);
1410 957 : 12 : pq_set_parallel_leader(MyLogicalRepWorker->leader_pid,
958 : : INVALID_PROC_NUMBER);
959 : :
1419 960 : 12 : MyLogicalRepWorker->last_send_time = MyLogicalRepWorker->last_recv_time =
961 : 12 : MyLogicalRepWorker->reply_time = 0;
962 : :
1213 963 : 12 : InitializeLogRepWorker();
964 : :
1305 965 : 12 : InitializingApplyWorker = false;
966 : :
967 : : /* Setup replication origin tracking. */
1419 968 : 12 : StartTransactionCommand();
969 : 12 : ReplicationOriginNameForLogicalRep(MySubscription->oid, InvalidOid,
970 : : originname, sizeof(originname));
971 : 12 : originid = replorigin_by_name(originname, false);
972 : :
973 : : /*
974 : : * The parallel apply worker doesn't need to monopolize this replication
975 : : * origin which was already acquired by its leader process.
976 : : */
1410 977 : 12 : replorigin_session_setup(originid, MyLogicalRepWorker->leader_pid);
304 msawada@postgresql.o 978 : 12 : replorigin_xact_state.origin = originid;
1419 akapila@postgresql.o 979 : 12 : CommitTransactionCommand();
980 : :
981 : : /*
982 : : * Setup callback for syscache so that we know when something changes in
983 : : * the subscription relation state.
984 : : */
985 : 12 : CacheRegisterSyscacheCallback(SUBSCRIPTIONRELMAP,
986 : : InvalidateSyncingRelStates,
987 : : (Datum) 0);
988 : :
989 : 12 : set_apply_error_context_origin(originname);
990 : :
991 : 12 : LogicalParallelApplyLoop(mqh);
992 : :
993 : : /*
994 : : * The parallel apply worker must not get here because the parallel apply
995 : : * worker will only stop when it receives a SIGTERM or SIGUSR2 from the
996 : : * leader, or SIGINT from itself, or when there is an error. None of these
997 : : * cases will allow the code to reach here.
998 : : */
1419 akapila@postgresql.o 999 :UBC 0 : Assert(false);
1000 : : }
1001 : :
1002 : : /*
1003 : : * Handle receipt of an interrupt indicating a parallel apply worker message.
1004 : : *
1005 : : * Note: this is called within a signal handler! All we can do is set a flag
1006 : : * that will cause the next CHECK_FOR_INTERRUPTS() to invoke
1007 : : * ProcessParallelApplyMessages().
1008 : : */
1009 : : void
1419 akapila@postgresql.o 1010 :CBC 14 : HandleParallelApplyMessageInterrupt(void)
1011 : : {
1012 : 14 : InterruptPending = true;
1013 : 14 : ParallelApplyMessagePending = true;
1014 : : /* latch will be set by procsignal_sigusr1_handler */
1015 : 14 : }
1016 : :
1017 : : /*
1018 : : * Process a single protocol message received from a single parallel apply
1019 : : * worker.
1020 : : */
1021 : : static void
633 heikki.linnakangas@i 1022 : 3 : ProcessParallelApplyMessage(StringInfo msg)
1023 : : {
1024 : : char msgtype;
1025 : :
1419 akapila@postgresql.o 1026 : 3 : msgtype = pq_getmsgbyte(msg);
1027 : :
1028 [ + - - ]: 3 : switch (msgtype)
1029 : : {
460 nathan@postgresql.or 1030 : 3 : case PqMsg_ErrorResponse:
1031 : :
1032 : : /*
1033 : : * The parallel apply worker has already reported the error with
1034 : : * the context of the transaction that failed. Report the error
1035 : : * of the leader apply worker with the error context callbacks
1036 : : * that were in effect.
1037 : : */
18 akapila@postgresql.o 1038 :GNC 3 : error_context_stack = apply_error_context_stack;
1039 : :
1040 : : /*
1041 : : * The actual error must have been reported by the parallel apply
1042 : : * worker.
1043 : : */
1044 [ + - ]: 3 : ereport(ERROR,
1045 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1046 : : errmsg("logical replication parallel apply worker exited due to error"),
1047 : : errdetail("The leader apply worker will now exit and terminate any other parallel apply workers.")));
1048 : :
1049 : : /*
1050 : : * Don't need to do anything about NoticeResponse and
1051 : : * NotificationResponse as the logical replication worker doesn't
1052 : : * need to send messages to the client.
1053 : : */
460 nathan@postgresql.or 1054 :EUB : case PqMsg_NoticeResponse:
1055 : : case PqMsg_NotificationResponse:
1419 akapila@postgresql.o 1056 :UBC 0 : break;
1057 : :
1058 : 0 : default:
1059 [ # # ]: 0 : elog(ERROR, "unrecognized message type received from logical replication parallel apply worker: %c (message length %d bytes)",
1060 : : msgtype, msg->len);
1061 : : }
1062 : 0 : }
1063 : :
1064 : : /*
1065 : : * Handle any queued protocol messages received from parallel apply workers.
1066 : : */
1067 : : void
633 heikki.linnakangas@i 1068 :CBC 8 : ProcessParallelApplyMessages(void)
1069 : : {
1070 : : ListCell *lc;
1071 : : MemoryContext oldcontext;
1072 : :
1073 : : static MemoryContext hpam_context = NULL;
1074 : :
1075 : : /*
1076 : : * This is invoked from ProcessInterrupts(), and since some of the
1077 : : * functions it calls contain CHECK_FOR_INTERRUPTS(), there is a potential
1078 : : * for recursive calls if more signals are received while this runs. It's
1079 : : * unclear that recursive entry would be safe, and it doesn't seem useful
1080 : : * even if it is safe, so let's block interrupts until done.
1081 : : */
1419 akapila@postgresql.o 1082 : 8 : HOLD_INTERRUPTS();
1083 : :
1084 : : /*
1085 : : * Moreover, CurrentMemoryContext might be pointing almost anywhere. We
1086 : : * don't want to risk leaking data into long-lived contexts, so let's do
1087 : : * our work here in a private context that we can reset on each use.
1088 : : */
1089 [ + + ]: 8 : if (!hpam_context) /* first time through? */
1090 : 7 : hpam_context = AllocSetContextCreate(TopMemoryContext,
1091 : : "ProcessParallelApplyMessages",
1092 : : ALLOCSET_DEFAULT_SIZES);
1093 : : else
1094 : 1 : MemoryContextReset(hpam_context);
1095 : :
1096 : 8 : oldcontext = MemoryContextSwitchTo(hpam_context);
1097 : :
1098 : 8 : ParallelApplyMessagePending = false;
1099 : :
1100 [ + - + + : 14 : foreach(lc, ParallelApplyWorkerPool)
+ + ]
1101 : : {
1102 : : shm_mq_result res;
1103 : : Size nbytes;
1104 : : void *data;
1105 : 9 : ParallelApplyWorkerInfo *winfo = (ParallelApplyWorkerInfo *) lfirst(lc);
1106 : :
1107 : : /*
1108 : : * The leader will detach from the error queue and set it to NULL
1109 : : * before preparing to stop all parallel apply workers, so we don't
1110 : : * need to handle error messages anymore. See
1111 : : * logicalrep_worker_detach.
1112 : : */
1113 [ + + ]: 9 : if (!winfo->error_mq_handle)
1114 : 6 : continue;
1115 : :
1116 : 4 : res = shm_mq_receive(winfo->error_mq_handle, &nbytes, &data, true);
1117 : :
1118 [ + + ]: 4 : if (res == SHM_MQ_WOULD_BLOCK)
1119 : 1 : continue;
1120 [ + - ]: 3 : else if (res == SHM_MQ_SUCCESS)
1121 : : {
1122 : : StringInfoData msg;
1123 : :
1124 : 3 : initStringInfo(&msg);
1125 : 3 : appendBinaryStringInfo(&msg, data, nbytes);
633 heikki.linnakangas@i 1126 : 3 : ProcessParallelApplyMessage(&msg);
1419 akapila@postgresql.o 1127 :UBC 0 : pfree(msg.data);
1128 : : }
1129 : : else
1130 [ # # ]: 0 : ereport(ERROR,
1131 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1132 : : errmsg("lost connection to the logical replication parallel apply worker")));
1133 : : }
1134 : :
1419 akapila@postgresql.o 1135 :CBC 5 : MemoryContextSwitchTo(oldcontext);
1136 : :
1137 : : /* Might as well clear the context on our way out */
1138 : 5 : MemoryContextReset(hpam_context);
1139 : :
1140 [ - + ]: 5 : RESUME_INTERRUPTS();
1141 : 5 : }
1142 : :
1143 : : /*
1144 : : * Send the data to the specified parallel apply worker via shared-memory
1145 : : * queue.
1146 : : *
1147 : : * Returns false if the attempt to send data via shared memory times out, true
1148 : : * otherwise.
1149 : : */
1150 : : bool
1151 : 68698 : pa_send_data(ParallelApplyWorkerInfo *winfo, Size nbytes, const void *data)
1152 : : {
1153 : : int rc;
1154 : : shm_mq_result result;
1155 : 68698 : TimestampTz startTime = 0;
1156 : :
1157 [ - + ]: 68698 : Assert(!IsTransactionState());
1158 [ - + ]: 68698 : Assert(!winfo->serialize_changes);
1159 : :
1160 : : /*
1161 : : * We don't try to send data to parallel worker for 'immediate' mode. This
1162 : : * is primarily used for testing purposes.
1163 : : */
1187 peter@eisentraut.org 1164 [ + + ]: 68698 : if (unlikely(debug_logical_replication_streaming == DEBUG_LOGICAL_REP_STREAMING_IMMEDIATE))
1395 akapila@postgresql.o 1165 : 4 : return false;
1166 : :
1167 : : /*
1168 : : * This timeout is a bit arbitrary but testing revealed that it is sufficient
1169 : : * to send the message unless the parallel apply worker is waiting on some
1170 : : * lock or there is a serious resource crunch. See the comments atop this file
1171 : : * to know why we are using a non-blocking way to send the message.
1172 : : */
1173 : : #define SHM_SEND_RETRY_INTERVAL_MS 1000
1174 : : #define SHM_SEND_TIMEOUT_MS (10000 - SHM_SEND_RETRY_INTERVAL_MS)
1175 : :
1176 : : for (;;)
1177 : : {
1419 1178 : 68694 : result = shm_mq_send(winfo->mq_handle, nbytes, data, true, true);
1179 : :
1180 [ + - ]: 68694 : if (result == SHM_MQ_SUCCESS)
1181 : 68694 : return true;
1419 akapila@postgresql.o 1182 [ # # ]:UBC 0 : else if (result == SHM_MQ_DETACHED)
1183 [ # # ]: 0 : ereport(ERROR,
1184 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1185 : : errmsg("could not send data to shared-memory queue")));
1186 : :
1187 [ # # ]: 0 : Assert(result == SHM_MQ_WOULD_BLOCK);
1188 : :
1189 : : /* Wait before retrying. */
1190 : 0 : rc = WaitLatch(MyLatch,
1191 : : WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
1192 : : SHM_SEND_RETRY_INTERVAL_MS,
1193 : : WAIT_EVENT_LOGICAL_APPLY_SEND_DATA);
1194 : :
1195 [ # # ]: 0 : if (rc & WL_LATCH_SET)
1196 : : {
1197 : 0 : ResetLatch(MyLatch);
1198 [ # # ]: 0 : CHECK_FOR_INTERRUPTS();
1199 : : }
1200 : :
1201 [ # # ]: 0 : if (startTime == 0)
1202 : 0 : startTime = GetCurrentTimestamp();
1203 [ # # ]: 0 : else if (TimestampDifferenceExceeds(startTime, GetCurrentTimestamp(),
1204 : : SHM_SEND_TIMEOUT_MS))
1205 : 0 : return false;
1206 : : }
1207 : : }
1208 : :
1209 : : /*
1210 : : * Switch to PARTIAL_SERIALIZE mode for the current transaction -- this means
1211 : : * that the current data and any subsequent data for this transaction will be
1212 : : * serialized to a file. This is done to prevent possible deadlocks with
1213 : : * another parallel apply worker (refer to the comments atop this file).
1214 : : */
1215 : : void
1419 akapila@postgresql.o 1216 :CBC 4 : pa_switch_to_partial_serialize(ParallelApplyWorkerInfo *winfo,
1217 : : bool stream_locked)
1218 : : {
1395 1219 [ + - ]: 4 : ereport(LOG,
1220 : : (errmsg("logical replication apply worker will serialize the remaining changes of remote transaction %u to a file",
1221 : : winfo->shared->xid)));
1222 : :
1223 : : /*
1224 : : * The parallel apply worker could be stuck for some reason (say waiting
1225 : : * on some lock by other backend), so stop trying to send data directly to
1226 : : * it and start serializing data to the file instead.
1227 : : */
1419 1228 : 4 : winfo->serialize_changes = true;
1229 : :
1230 : : /* Initialize the stream fileset. */
1231 : 4 : stream_start_internal(winfo->shared->xid, true);
1232 : :
1233 : : /*
1234 : : * Acquires the stream lock if not already to make sure that the parallel
1235 : : * apply worker will wait for the leader to release the stream lock until
1236 : : * the end of the transaction.
1237 : : */
1238 [ + - ]: 4 : if (!stream_locked)
1239 : 4 : pa_lock_stream(winfo->shared->xid, AccessExclusiveLock);
1240 : :
1241 : 4 : pa_set_fileset_state(winfo->shared, FS_SERIALIZE_IN_PROGRESS);
1242 : 4 : }
1243 : :
1244 : : /*
1245 : : * Wait until the parallel apply worker's transaction state has reached or
1246 : : * exceeded the given xact_state.
1247 : : */
1248 : : static void
1249 : 27 : pa_wait_for_xact_state(ParallelApplyWorkerInfo *winfo,
1250 : : ParallelTransState xact_state)
1251 : : {
1252 : : for (;;)
1253 : : {
1254 : : /*
1255 : : * Stop if the transaction state has reached or exceeded the given
1256 : : * xact_state.
1257 : : */
1258 [ + + ]: 254 : if (pa_get_xact_state(winfo->shared) >= xact_state)
1259 : 26 : break;
1260 : :
1261 : : /* Wait to be signalled. */
1262 : 228 : (void) WaitLatch(MyLatch,
1263 : : WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
1264 : : 10L,
1265 : : WAIT_EVENT_LOGICAL_PARALLEL_APPLY_STATE_CHANGE);
1266 : :
1267 : : /* Reset the latch so we don't spin. */
1268 : 228 : ResetLatch(MyLatch);
1269 : :
1270 : : /* An interrupt may have occurred while we were waiting. */
1271 [ + + ]: 228 : CHECK_FOR_INTERRUPTS();
1272 : : }
1273 : 26 : }
1274 : :
1275 : : /*
1276 : : * Wait until the parallel apply worker's transaction finishes.
1277 : : */
1278 : : static void
1279 : 27 : pa_wait_for_xact_finish(ParallelApplyWorkerInfo *winfo)
1280 : : {
1281 : : /*
1282 : : * Wait until the parallel apply worker set the state to
1283 : : * PARALLEL_TRANS_STARTED which means it has acquired the transaction
1284 : : * lock. This is to prevent leader apply worker from acquiring the
1285 : : * transaction lock earlier than the parallel apply worker.
1286 : : */
1287 : 27 : pa_wait_for_xact_state(winfo, PARALLEL_TRANS_STARTED);
1288 : :
1289 : : /*
1290 : : * Wait for the transaction lock to be released. This is required to
1291 : : * detect deadlock among leader and parallel apply workers. Refer to the
1292 : : * comments atop this file.
1293 : : */
1294 : 26 : pa_lock_transaction(winfo->shared->xid, AccessShareLock);
1295 : 25 : pa_unlock_transaction(winfo->shared->xid, AccessShareLock);
1296 : :
1297 : : /*
1298 : : * Check if the state becomes PARALLEL_TRANS_FINISHED in case the parallel
1299 : : * apply worker failed while applying changes causing the lock to be
1300 : : * released.
1301 : : */
1302 [ - + ]: 25 : if (pa_get_xact_state(winfo->shared) != PARALLEL_TRANS_FINISHED)
1419 akapila@postgresql.o 1303 [ # # ]:UBC 0 : ereport(ERROR,
1304 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1305 : : errmsg("lost connection to the logical replication parallel apply worker")));
1419 akapila@postgresql.o 1306 :CBC 25 : }
1307 : :
1308 : : /*
1309 : : * Set the transaction state for a given parallel apply worker.
1310 : : */
1311 : : void
1312 : 54 : pa_set_xact_state(ParallelApplyWorkerShared *wshared,
1313 : : ParallelTransState xact_state)
1314 : : {
1315 : 54 : SpinLockAcquire(&wshared->mutex);
1316 : 54 : wshared->xact_state = xact_state;
1317 : 54 : SpinLockRelease(&wshared->mutex);
1318 : 54 : }
1319 : :
1320 : : /*
1321 : : * Get the transaction state for a given parallel apply worker.
1322 : : */
1323 : : static ParallelTransState
1324 : 304 : pa_get_xact_state(ParallelApplyWorkerShared *wshared)
1325 : : {
1326 : : ParallelTransState xact_state;
1327 : :
1328 : 304 : SpinLockAcquire(&wshared->mutex);
1329 : 304 : xact_state = wshared->xact_state;
1330 : 304 : SpinLockRelease(&wshared->mutex);
1331 : :
1332 : 304 : return xact_state;
1333 : : }
1334 : :
1335 : : /*
1336 : : * Cache the parallel apply worker information.
1337 : : */
1338 : : void
1339 : 552 : pa_set_stream_apply_worker(ParallelApplyWorkerInfo *winfo)
1340 : : {
1341 : 552 : stream_apply_worker = winfo;
1342 : 552 : }
1343 : :
1344 : : /*
1345 : : * Form a unique savepoint name for the streaming transaction.
1346 : : *
1347 : : * Note that different subscriptions for publications on different nodes can
1348 : : * receive same remote xid, so we need to use subscription id along with it.
1349 : : *
1350 : : * Returns the name in the supplied buffer.
1351 : : */
1352 : : static void
1353 : 27 : pa_savepoint_name(Oid suboid, TransactionId xid, char *spname, Size szsp)
1354 : : {
1355 : 27 : snprintf(spname, szsp, "pg_sp_%u_%u", suboid, xid);
1356 : 27 : }
1357 : :
1358 : : /*
1359 : : * Define a savepoint for a subxact in parallel apply worker if needed.
1360 : : *
1361 : : * The parallel apply worker can figure out if a new subtransaction was
1362 : : * started by checking if the new change arrived with a different xid. In that
1363 : : * case define a named savepoint, so that we are able to rollback to it
1364 : : * if required.
1365 : : */
1366 : : void
1367 : 68247 : pa_start_subtrans(TransactionId current_xid, TransactionId top_xid)
1368 : : {
1369 [ + + ]: 68247 : if (current_xid != top_xid &&
1370 [ + + ]: 52 : !list_member_xid(subxactlist, current_xid))
1371 : : {
1372 : : MemoryContext oldctx;
1373 : : char spname[NAMEDATALEN];
1374 : :
1375 : 17 : pa_savepoint_name(MySubscription->oid, current_xid,
1376 : : spname, sizeof(spname));
1377 : :
1378 [ + + ]: 17 : elog(DEBUG1, "defining savepoint %s in logical replication parallel apply worker", spname);
1379 : :
1380 : : /* We must be in transaction block to define the SAVEPOINT. */
1381 [ + + ]: 17 : if (!IsTransactionBlock())
1382 : : {
1383 [ - + ]: 5 : if (!IsTransactionState())
1419 akapila@postgresql.o 1384 :UBC 0 : StartTransactionCommand();
1385 : :
1419 akapila@postgresql.o 1386 :CBC 5 : BeginTransactionBlock();
1387 : 5 : CommitTransactionCommand();
1388 : : }
1389 : :
1390 : 17 : DefineSavepoint(spname);
1391 : :
1392 : : /*
1393 : : * CommitTransactionCommand is needed to start a subtransaction after
1394 : : * issuing a SAVEPOINT inside a transaction block (see
1395 : : * StartSubTransaction()).
1396 : : */
1397 : 17 : CommitTransactionCommand();
1398 : :
1399 : 17 : oldctx = MemoryContextSwitchTo(TopTransactionContext);
1400 : 17 : subxactlist = lappend_xid(subxactlist, current_xid);
1401 : 17 : MemoryContextSwitchTo(oldctx);
1402 : : }
1403 : 68247 : }
1404 : :
1405 : : /* Reset the list that maintains subtransactions. */
1406 : : void
1407 : 25 : pa_reset_subtrans(void)
1408 : : {
1409 : : /*
1410 : : * We don't need to free this explicitly as the allocated memory will be
1411 : : * freed at the transaction end.
1412 : : */
1413 : 25 : subxactlist = NIL;
1414 : 25 : }
1415 : :
1416 : : /*
1417 : : * Handle STREAM ABORT message when the transaction was applied in a parallel
1418 : : * apply worker.
1419 : : */
1420 : : void
1421 : 12 : pa_stream_abort(LogicalRepStreamAbortData *abort_data)
1422 : : {
1423 : 12 : TransactionId xid = abort_data->xid;
1424 : 12 : TransactionId subxid = abort_data->subxid;
1425 : :
1426 : : /*
1427 : : * Update origin state so we can restart streaming from correct position
1428 : : * in case of crash.
1429 : : */
304 msawada@postgresql.o 1430 : 12 : replorigin_xact_state.origin_lsn = abort_data->abort_lsn;
1431 : 12 : replorigin_xact_state.origin_timestamp = abort_data->abort_time;
1432 : :
1433 : : /*
1434 : : * If the two XIDs are the same, it's in fact abort of toplevel xact, so
1435 : : * just free the subxactlist.
1436 : : */
1419 akapila@postgresql.o 1437 [ + + ]: 12 : if (subxid == xid)
1438 : : {
1439 : 2 : pa_set_xact_state(MyParallelShared, PARALLEL_TRANS_FINISHED);
1440 : :
1441 : : /*
1442 : : * Release the lock as we might be processing an empty streaming
1443 : : * transaction in which case the lock won't be released during
1444 : : * transaction rollback.
1445 : : *
1446 : : * Note that it's ok to release the transaction lock before aborting
1447 : : * the transaction because even if the parallel apply worker dies due
1448 : : * to crash or some other reason, such a transaction would still be
1449 : : * considered aborted.
1450 : : */
1451 : 2 : pa_unlock_transaction(xid, AccessExclusiveLock);
1452 : :
1453 : 2 : AbortCurrentTransaction();
1454 : :
1455 [ + + ]: 2 : if (IsTransactionBlock())
1456 : : {
1457 : 1 : EndTransactionBlock(false);
1458 : 1 : CommitTransactionCommand();
1459 : : }
1460 : :
1461 : 2 : pa_reset_subtrans();
1462 : :
1463 : 2 : pgstat_report_activity(STATE_IDLE, NULL);
1464 : : }
1465 : : else
1466 : : {
1467 : : /* OK, so it's a subxact. Rollback to the savepoint. */
1468 : : int i;
1469 : : char spname[NAMEDATALEN];
1470 : :
1471 : 10 : pa_savepoint_name(MySubscription->oid, subxid, spname, sizeof(spname));
1472 : :
1473 [ + + ]: 10 : elog(DEBUG1, "rolling back to savepoint %s in logical replication parallel apply worker", spname);
1474 : :
1475 : : /*
1476 : : * Search the subxactlist, determine the offset tracked for the
1477 : : * subxact, and truncate the list.
1478 : : *
1479 : : * Note that for an empty sub-transaction we won't find the subxid
1480 : : * here.
1481 : : */
1482 [ + + ]: 12 : for (i = list_length(subxactlist) - 1; i >= 0; i--)
1483 : : {
1484 : 11 : TransactionId xid_tmp = lfirst_xid(list_nth_cell(subxactlist, i));
1485 : :
1486 [ + + ]: 11 : if (xid_tmp == subxid)
1487 : : {
1488 : 9 : RollbackToSavepoint(spname);
1489 : 9 : CommitTransactionCommand();
1490 : 9 : subxactlist = list_truncate(subxactlist, i);
1491 : 9 : break;
1492 : : }
1493 : : }
1494 : : }
1495 : 12 : }
1496 : :
1497 : : /*
1498 : : * Set the fileset state for a particular parallel apply worker. The fileset
1499 : : * will be set once the leader worker serialized all changes to the file
1500 : : * so that it can be used by parallel apply worker.
1501 : : */
1502 : : void
1503 : 16 : pa_set_fileset_state(ParallelApplyWorkerShared *wshared,
1504 : : PartialFileSetState fileset_state)
1505 : : {
1506 : 16 : SpinLockAcquire(&wshared->mutex);
1507 : 16 : wshared->fileset_state = fileset_state;
1508 : :
1509 [ + + ]: 16 : if (fileset_state == FS_SERIALIZE_DONE)
1510 : : {
1511 [ - + ]: 4 : Assert(am_leader_apply_worker());
1512 [ - + ]: 4 : Assert(MyLogicalRepWorker->stream_fileset);
1513 : 4 : wshared->fileset = *MyLogicalRepWorker->stream_fileset;
1514 : : }
1515 : :
1516 : 16 : SpinLockRelease(&wshared->mutex);
1517 : 16 : }
1518 : :
1519 : : /*
1520 : : * Get the fileset state for the current parallel apply worker.
1521 : : */
1522 : : static PartialFileSetState
1523 : 85 : pa_get_fileset_state(void)
1524 : : {
1525 : : PartialFileSetState fileset_state;
1526 : :
1527 [ - + ]: 85 : Assert(am_parallel_apply_worker());
1528 : :
1529 : 85 : SpinLockAcquire(&MyParallelShared->mutex);
1530 : 85 : fileset_state = MyParallelShared->fileset_state;
1531 : 85 : SpinLockRelease(&MyParallelShared->mutex);
1532 : :
1533 : 85 : return fileset_state;
1534 : : }
1535 : :
1536 : : /*
1537 : : * Helper functions to acquire and release a lock for each stream block.
1538 : : *
1539 : : * Set locktag_field4 to PARALLEL_APPLY_LOCK_STREAM to indicate that it's a
1540 : : * stream lock.
1541 : : *
1542 : : * Refer to the comments atop this file to see how the stream lock is used.
1543 : : */
1544 : : void
1545 : 302 : pa_lock_stream(TransactionId xid, LOCKMODE lockmode)
1546 : : {
1547 : 302 : LockApplyTransactionForSession(MyLogicalRepWorker->subid, xid,
1548 : : PARALLEL_APPLY_LOCK_STREAM, lockmode);
1549 : 300 : }
1550 : :
1551 : : void
1552 : 298 : pa_unlock_stream(TransactionId xid, LOCKMODE lockmode)
1553 : : {
1554 : 298 : UnlockApplyTransactionForSession(MyLogicalRepWorker->subid, xid,
1555 : : PARALLEL_APPLY_LOCK_STREAM, lockmode);
1556 : 298 : }
1557 : :
1558 : : /*
1559 : : * Helper functions to acquire and release a lock for each local transaction
1560 : : * apply.
1561 : : *
1562 : : * Set locktag_field4 to PARALLEL_APPLY_LOCK_XACT to indicate that it's a
1563 : : * transaction lock.
1564 : : *
1565 : : * Note that all the callers must pass a remote transaction ID instead of a
1566 : : * local transaction ID as xid. This is because the local transaction ID will
1567 : : * only be assigned while applying the first change in the parallel apply but
1568 : : * it's possible that the first change in the parallel apply worker is blocked
1569 : : * by a concurrently executing transaction in another parallel apply worker. We
1570 : : * can only communicate the local transaction id to the leader after applying
1571 : : * the first change so it won't be able to wait after sending the xact finish
1572 : : * command using this lock.
1573 : : *
1574 : : * Refer to the comments atop this file to see how the transaction lock is
1575 : : * used.
1576 : : */
1577 : : void
1578 : 55 : pa_lock_transaction(TransactionId xid, LOCKMODE lockmode)
1579 : : {
1580 : 55 : LockApplyTransactionForSession(MyLogicalRepWorker->subid, xid,
1581 : : PARALLEL_APPLY_LOCK_XACT, lockmode);
1582 : 54 : }
1583 : :
1584 : : void
1585 : 50 : pa_unlock_transaction(TransactionId xid, LOCKMODE lockmode)
1586 : : {
1587 : 50 : UnlockApplyTransactionForSession(MyLogicalRepWorker->subid, xid,
1588 : : PARALLEL_APPLY_LOCK_XACT, lockmode);
1589 : 50 : }
1590 : :
1591 : : /*
1592 : : * Decrement the number of pending streaming blocks and wait on the stream lock
1593 : : * if there is no pending block available.
1594 : : */
1595 : : void
1596 : 275 : pa_decr_and_wait_stream_block(void)
1597 : : {
1598 [ - + ]: 275 : Assert(am_parallel_apply_worker());
1599 : :
1600 : : /*
1601 : : * It is only possible to not have any pending stream chunks when we are
1602 : : * applying spooled messages.
1603 : : */
1604 [ + + ]: 275 : if (pg_atomic_read_u32(&MyParallelShared->pending_stream_count) == 0)
1605 : : {
1606 [ + - ]: 16 : if (pa_has_spooled_message_pending())
1607 : 16 : return;
1608 : :
1419 akapila@postgresql.o 1609 [ # # ]:UBC 0 : elog(ERROR, "invalid pending streaming chunk 0");
1610 : : }
1611 : :
1419 akapila@postgresql.o 1612 [ + + ]:CBC 259 : if (pg_atomic_sub_fetch_u32(&MyParallelShared->pending_stream_count, 1) == 0)
1613 : : {
1614 : 28 : pa_lock_stream(MyParallelShared->xid, AccessShareLock);
1615 : 26 : pa_unlock_stream(MyParallelShared->xid, AccessShareLock);
1616 : : }
1617 : : }
1618 : :
1619 : : /*
1620 : : * Finish processing the streaming transaction in the leader apply worker.
1621 : : */
1622 : : void
1623 : 27 : pa_xact_finish(ParallelApplyWorkerInfo *winfo, XLogRecPtr remote_lsn)
1624 : : {
1625 [ - + ]: 27 : Assert(am_leader_apply_worker());
1626 : :
1627 : : /*
1628 : : * Unlock the shared object lock so that parallel apply worker can
1629 : : * continue to receive and apply changes.
1630 : : */
1631 : 27 : pa_unlock_stream(winfo->shared->xid, AccessExclusiveLock);
1632 : :
1633 : : /*
1634 : : * Wait for that worker to finish. This is necessary to maintain commit
1635 : : * order which avoids failures due to transaction dependencies and
1636 : : * deadlocks.
1637 : : */
1638 : 27 : pa_wait_for_xact_finish(winfo);
1639 : :
387 alvherre@kurilemu.de 1640 [ + + ]: 25 : if (XLogRecPtrIsValid(remote_lsn))
1419 akapila@postgresql.o 1641 : 23 : store_flush_position(remote_lsn, winfo->shared->last_commit_end);
1642 : :
1643 : 25 : pa_free_worker(winfo);
1644 : 25 : }
|