Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : * worker.c
3 : : * PostgreSQL logical replication worker (apply)
4 : : *
5 : : * Copyright (c) 2016-2026, PostgreSQL Global Development Group
6 : : *
7 : : * IDENTIFICATION
8 : : * src/backend/replication/logical/worker.c
9 : : *
10 : : * NOTES
11 : : * This file contains the worker which applies logical changes as they come
12 : : * from remote logical replication stream.
13 : : *
14 : : * The main worker (apply) is started by logical replication worker
15 : : * launcher for every enabled subscription in a database. It uses
16 : : * walsender protocol to communicate with publisher.
17 : : *
18 : : * This module includes server facing code and shares libpqwalreceiver
19 : : * module with walreceiver for providing the libpq specific functionality.
20 : : *
21 : : *
22 : : * STREAMED TRANSACTIONS
23 : : * ---------------------
24 : : * Streamed transactions (large transactions exceeding a memory limit on the
25 : : * upstream) are applied using one of two approaches:
26 : : *
27 : : * 1) Write to temporary files and apply when the final commit arrives
28 : : *
29 : : * This approach is used when the user has set the subscription's streaming
30 : : * option as on.
31 : : *
32 : : * Unlike the regular (non-streamed) case, handling streamed transactions has
33 : : * to handle aborts of both the toplevel transaction and subtransactions. This
34 : : * is achieved by tracking offsets for subtransactions, which is then used
35 : : * to truncate the file with serialized changes.
36 : : *
37 : : * The files are placed in tmp file directory by default, and the filenames
38 : : * include both the XID of the toplevel transaction and OID of the
39 : : * subscription. This is necessary so that different workers processing a
40 : : * remote transaction with the same XID doesn't interfere.
41 : : *
42 : : * We use BufFiles instead of using normal temporary files because (a) the
43 : : * BufFile infrastructure supports temporary files that exceed the OS file size
44 : : * limit, (b) provides a way for automatic clean up on the error and (c) provides
45 : : * a way to survive these files across local transactions and allow to open and
46 : : * close at stream start and close. We decided to use FileSet
47 : : * infrastructure as without that it deletes the files on the closure of the
48 : : * file and if we decide to keep stream files open across the start/stop stream
49 : : * then it will consume a lot of memory (more than 8K for each BufFile and
50 : : * there could be multiple such BufFiles as the subscriber could receive
51 : : * multiple start/stop streams for different transactions before getting the
52 : : * commit). Moreover, if we don't use FileSet then we also need to invent
53 : : * a new way to pass filenames to BufFile APIs so that we are allowed to open
54 : : * the file we desired across multiple stream-open calls for the same
55 : : * transaction.
56 : : *
57 : : * 2) Parallel apply workers.
58 : : *
59 : : * This approach is used when the user has set the subscription's streaming
60 : : * option as parallel. See logical/applyparallelworker.c for information about
61 : : * this approach.
62 : : *
63 : : * TWO_PHASE TRANSACTIONS
64 : : * ----------------------
65 : : * Two phase transactions are replayed at prepare and then committed or
66 : : * rolled back at commit prepared and rollback prepared respectively. It is
67 : : * possible to have a prepared transaction that arrives at the apply worker
68 : : * when the tablesync is busy doing the initial copy. In this case, the apply
69 : : * worker skips all the prepared operations [e.g. inserts] while the tablesync
70 : : * is still busy (see the condition of should_apply_changes_for_rel). The
71 : : * tablesync worker might not get such a prepared transaction because say it
72 : : * was prior to the initial consistent point but might have got some later
73 : : * commits. Now, the tablesync worker will exit without doing anything for the
74 : : * prepared transaction skipped by the apply worker as the sync location for it
75 : : * will be already ahead of the apply worker's current location. This would lead
76 : : * to an "empty prepare", because later when the apply worker does the commit
77 : : * prepare, there is nothing in it (the inserts were skipped earlier).
78 : : *
79 : : * To avoid this, and similar prepare confusions the subscription's two_phase
80 : : * commit is enabled only after the initial sync is over. The two_phase option
81 : : * has been implemented as a tri-state with values DISABLED, PENDING, and
82 : : * ENABLED.
83 : : *
84 : : * Even if the user specifies they want a subscription with two_phase = on,
85 : : * internally it will start with a tri-state of PENDING which only becomes
86 : : * ENABLED after all tablesync initializations are completed - i.e. when all
87 : : * tablesync workers have reached their READY state. In other words, the value
88 : : * PENDING is only a temporary state for subscription start-up.
89 : : *
90 : : * Until the two_phase is properly available (ENABLED) the subscription will
91 : : * behave as if two_phase = off. When the apply worker detects that all
92 : : * tablesyncs have become READY (while the tri-state was PENDING) it will
93 : : * restart the apply worker process. This happens in
94 : : * ProcessSyncingTablesForApply.
95 : : *
96 : : * When the (re-started) apply worker finds that all tablesyncs are READY for a
97 : : * two_phase tri-state of PENDING it start streaming messages with the
98 : : * two_phase option which in turn enables the decoding of two-phase commits at
99 : : * the publisher. Then, it updates the tri-state value from PENDING to ENABLED.
100 : : * Now, it is possible that during the time we have not enabled two_phase, the
101 : : * publisher (replication server) would have skipped some prepares but we
102 : : * ensure that such prepares are sent along with commit prepare, see
103 : : * ReorderBufferFinishPrepared.
104 : : *
105 : : * If the subscription has no tables then a two_phase tri-state PENDING is
106 : : * left unchanged. This lets the user still do an ALTER SUBSCRIPTION REFRESH
107 : : * PUBLICATION which might otherwise be disallowed (see below).
108 : : *
109 : : * If ever a user needs to be aware of the tri-state value, they can fetch it
110 : : * from the pg_subscription catalog (see column subtwophasestate).
111 : : *
112 : : * Finally, to avoid problems mentioned in previous paragraphs from any
113 : : * subsequent (not READY) tablesyncs (need to toggle two_phase option from 'on'
114 : : * to 'off' and then again back to 'on') there is a restriction for
115 : : * ALTER SUBSCRIPTION REFRESH PUBLICATION. This command is not permitted when
116 : : * the two_phase tri-state is ENABLED, except when copy_data = false.
117 : : *
118 : : * We can get prepare of the same GID more than once for the genuine cases
119 : : * where we have defined multiple subscriptions for publications on the same
120 : : * server and prepared transaction has operations on tables subscribed to those
121 : : * subscriptions. For such cases, if we use the GID sent by publisher one of
122 : : * the prepares will be successful and others will fail, in which case the
123 : : * server will send them again. Now, this can lead to a deadlock if user has
124 : : * set synchronous_standby_names for all the subscriptions on subscriber. To
125 : : * avoid such deadlocks, we generate a unique GID (consisting of the
126 : : * subscription oid and the xid of the prepared transaction) for each prepare
127 : : * transaction on the subscriber.
128 : : *
129 : : * FAILOVER
130 : : * ----------------------
131 : : * The logical slot on the primary can be synced to the standby by specifying
132 : : * failover = true when creating the subscription. Enabling failover allows us
133 : : * to smoothly transition to the promoted standby, ensuring that we can
134 : : * subscribe to the new primary without losing any data.
135 : : *
136 : : * RETAIN DEAD TUPLES
137 : : * ----------------------
138 : : * Each apply worker that enabled retain_dead_tuples option maintains a
139 : : * non-removable transaction ID (oldest_nonremovable_xid) in shared memory to
140 : : * prevent dead rows from being removed prematurely when the apply worker still
141 : : * needs them to detect update_deleted conflicts. Additionally, this helps to
142 : : * retain the required commit_ts module information, which further helps to
143 : : * detect update_origin_differs and delete_origin_differs conflicts reliably, as
144 : : * otherwise, vacuum freeze could remove the required information.
145 : : *
146 : : * The logical replication launcher manages an internal replication slot named
147 : : * "pg_conflict_detection". It asynchronously aggregates the non-removable
148 : : * transaction ID from all apply workers to determine the appropriate xmin for
149 : : * the slot, thereby retaining necessary tuples.
150 : : *
151 : : * The non-removable transaction ID in the apply worker is advanced to the
152 : : * oldest running transaction ID once all concurrent transactions on the
153 : : * publisher have been applied and flushed locally. The process involves:
154 : : *
155 : : * - RDT_GET_CANDIDATE_XID:
156 : : * Call GetOldestActiveTransactionId() to take oldestRunningXid as the
157 : : * candidate xid.
158 : : *
159 : : * - RDT_REQUEST_PUBLISHER_STATUS:
160 : : * Send a message to the walsender requesting the publisher status, which
161 : : * includes the latest WAL insert position and information about
162 : : * transactions that are in the commit phase.
163 : : *
164 : : * - RDT_WAIT_FOR_PUBLISHER_STATUS:
165 : : * Wait for the status from the walsender. After receiving the first status,
166 : : * do not proceed if there are concurrent remote transactions that are still
167 : : * in the commit phase. These transactions might have been assigned an
168 : : * earlier commit timestamp but have not yet written the commit WAL record.
169 : : * Continue to request the publisher status (RDT_REQUEST_PUBLISHER_STATUS)
170 : : * until all these transactions have completed.
171 : : *
172 : : * - RDT_WAIT_FOR_LOCAL_FLUSH:
173 : : * Advance the non-removable transaction ID if the current flush location has
174 : : * reached or surpassed the last received WAL position.
175 : : *
176 : : * - RDT_STOP_CONFLICT_INFO_RETENTION:
177 : : * This phase is required only when max_retention_duration is defined. We
178 : : * enter this phase if the wait time in either the
179 : : * RDT_WAIT_FOR_PUBLISHER_STATUS or RDT_WAIT_FOR_LOCAL_FLUSH phase exceeds
180 : : * configured max_retention_duration. In this phase,
181 : : * pg_subscription.subretentionactive is updated to false within a new
182 : : * transaction, and oldest_nonremovable_xid is set to InvalidTransactionId.
183 : : *
184 : : * - RDT_RESUME_CONFLICT_INFO_RETENTION:
185 : : * This phase is required only when max_retention_duration is defined. We
186 : : * enter this phase if the retention was previously stopped, and the time
187 : : * required to advance the non-removable transaction ID in the
188 : : * RDT_WAIT_FOR_LOCAL_FLUSH phase has decreased to within acceptable limits
189 : : * (or if max_retention_duration is set to 0). During this phase,
190 : : * pg_subscription.subretentionactive is updated to true within a new
191 : : * transaction, and the worker will be restarted.
192 : : *
193 : : * The overall state progression is: GET_CANDIDATE_XID ->
194 : : * REQUEST_PUBLISHER_STATUS -> WAIT_FOR_PUBLISHER_STATUS -> (loop to
195 : : * REQUEST_PUBLISHER_STATUS till concurrent remote transactions end) ->
196 : : * WAIT_FOR_LOCAL_FLUSH -> loop back to GET_CANDIDATE_XID.
197 : : *
198 : : * Retaining the dead tuples for this period is sufficient for ensuring
199 : : * eventual consistency using last-update-wins strategy, as dead tuples are
200 : : * useful for detecting conflicts only during the application of concurrent
201 : : * transactions from remote nodes. After applying and flushing all remote
202 : : * transactions that occurred concurrently with the tuple DELETE, any
203 : : * subsequent UPDATE from a remote node should have a later timestamp. In such
204 : : * cases, it is acceptable to detect an update_missing scenario and convert the
205 : : * UPDATE to an INSERT when applying it. But, for concurrent remote
206 : : * transactions with earlier timestamps than the DELETE, detecting
207 : : * update_deleted is necessary, as the UPDATEs in remote transactions should be
208 : : * ignored if their timestamp is earlier than that of the dead tuples.
209 : : *
210 : : * Note that advancing the non-removable transaction ID is not supported if the
211 : : * publisher is also a physical standby. This is because the logical walsender
212 : : * on the standby can only get the WAL replay position but there may be more
213 : : * WALs that are being replicated from the primary and those WALs could have
214 : : * earlier commit timestamp.
215 : : *
216 : : * Similarly, when the publisher has subscribed to another publisher,
217 : : * information necessary for conflict detection cannot be retained for
218 : : * changes from origins other than the publisher. This is because publisher
219 : : * lacks the information on concurrent transactions of other publishers to
220 : : * which it subscribes. As the information on concurrent transactions is
221 : : * unavailable beyond subscriber's immediate publishers, the non-removable
222 : : * transaction ID might be advanced prematurely before changes from other
223 : : * origins have been fully applied.
224 : : *
225 : : * XXX Retaining information for changes from other origins might be possible
226 : : * by requesting the subscription on that origin to enable retain_dead_tuples
227 : : * and fetching the conflict detection slot.xmin along with the publisher's
228 : : * status. In the RDT_WAIT_FOR_PUBLISHER_STATUS phase, the apply worker could
229 : : * wait for the remote slot's xmin to reach the oldest active transaction ID,
230 : : * ensuring that all transactions from other origins have been applied on the
231 : : * publisher, thereby getting the latest WAL position that includes all
232 : : * concurrent changes. However, this approach may impact performance, so it
233 : : * might not worth the effort.
234 : : *
235 : : * XXX It seems feasible to get the latest commit's WAL location from the
236 : : * publisher and wait till that is applied. However, we can't do that
237 : : * because commit timestamps can regress as a commit with a later LSN is not
238 : : * guaranteed to have a later timestamp than those with earlier LSNs. Having
239 : : * said that, even if that is possible, it won't improve performance much as
240 : : * the apply always lag and moves slowly as compared with the transactions
241 : : * on the publisher.
242 : : *-------------------------------------------------------------------------
243 : : */
244 : :
245 : : #include "postgres.h"
246 : :
247 : : #include <sys/stat.h>
248 : : #include <unistd.h>
249 : :
250 : : #include "access/genam.h"
251 : : #include "access/commit_ts.h"
252 : : #include "access/table.h"
253 : : #include "access/tableam.h"
254 : : #include "access/tupconvert.h"
255 : : #include "access/twophase.h"
256 : : #include "access/xact.h"
257 : : #include "catalog/indexing.h"
258 : : #include "catalog/pg_inherits.h"
259 : : #include "catalog/pg_subscription.h"
260 : : #include "catalog/pg_subscription_rel.h"
261 : : #include "commands/subscriptioncmds.h"
262 : : #include "commands/tablecmds.h"
263 : : #include "commands/trigger.h"
264 : : #include "executor/executor.h"
265 : : #include "executor/execPartition.h"
266 : : #include "libpq/pqformat.h"
267 : : #include "miscadmin.h"
268 : : #include "optimizer/optimizer.h"
269 : : #include "parser/parse_relation.h"
270 : : #include "pgstat.h"
271 : : #include "port/pg_bitutils.h"
272 : : #include "postmaster/bgworker.h"
273 : : #include "postmaster/interrupt.h"
274 : : #include "postmaster/walwriter.h"
275 : : #include "replication/conflict.h"
276 : : #include "replication/logicallauncher.h"
277 : : #include "replication/logicalproto.h"
278 : : #include "replication/logicalrelation.h"
279 : : #include "replication/logicalworker.h"
280 : : #include "replication/origin.h"
281 : : #include "replication/slot.h"
282 : : #include "replication/walreceiver.h"
283 : : #include "replication/worker_internal.h"
284 : : #include "rewrite/rewriteHandler.h"
285 : : #include "storage/buffile.h"
286 : : #include "storage/ipc.h"
287 : : #include "storage/latch.h"
288 : : #include "storage/lmgr.h"
289 : : #include "storage/procarray.h"
290 : : #include "tcop/tcopprot.h"
291 : : #include "utils/acl.h"
292 : : #include "utils/guc.h"
293 : : #include "utils/inval.h"
294 : : #include "utils/lsyscache.h"
295 : : #include "utils/memutils.h"
296 : : #include "utils/pg_lsn.h"
297 : : #include "utils/rel.h"
298 : : #include "utils/rls.h"
299 : : #include "utils/snapmgr.h"
300 : : #include "utils/syscache.h"
301 : : #include "utils/usercontext.h"
302 : : #include "utils/wait_event.h"
303 : :
304 : : #define NAPTIME_PER_CYCLE 1000 /* max sleep time between cycles (1s) */
305 : :
306 : : typedef struct FlushPosition
307 : : {
308 : : dlist_node node;
309 : : XLogRecPtr local_end;
310 : : XLogRecPtr remote_end;
311 : : } FlushPosition;
312 : :
313 : : static dlist_head lsn_mapping = DLIST_STATIC_INIT(lsn_mapping);
314 : :
315 : : typedef struct ApplyExecutionData
316 : : {
317 : : EState *estate; /* executor state, used to track resources */
318 : :
319 : : LogicalRepRelMapEntry *targetRel; /* replication target rel */
320 : : ResultRelInfo *targetRelInfo; /* ResultRelInfo for same */
321 : :
322 : : /* These fields are used when the target relation is partitioned: */
323 : : ModifyTableState *mtstate; /* dummy ModifyTable state */
324 : : PartitionTupleRouting *proute; /* partition routing info */
325 : : } ApplyExecutionData;
326 : :
327 : : /*
328 : : * Context describing the remote transaction whose changes are currently
329 : : * being applied, and the change within it.
330 : : *
331 : : * The remote transaction information (remote_xid and finish_lsn) is set when
332 : : * the transaction's changes begin to be applied. finish_lsn is invalid when
333 : : * the final LSN of the remote transaction is not yet known (e.g. while
334 : : * streaming an in-progress transaction).
335 : : *
336 : : * The remaining fields describe the individual change being applied and are
337 : : * used only for error context reporting.
338 : : */
339 : : typedef struct ApplyRemoteCtx
340 : : {
341 : : LogicalRepMsgType command; /* 0 if invalid */
342 : : LogicalRepRelMapEntry *rel;
343 : :
344 : : /* Remote node information */
345 : : int remote_attnum; /* -1 if invalid */
346 : : TransactionId remote_xid;
347 : : XLogRecPtr finish_lsn;
348 : : char *origin_name;
349 : : } ApplyRemoteCtx;
350 : :
351 : : /*
352 : : * The action to be taken for the changes in the transaction.
353 : : *
354 : : * TRANS_LEADER_APPLY:
355 : : * This action means that we are in the leader apply worker or table sync
356 : : * worker. The changes of the transaction are either directly applied or
357 : : * are read from temporary files (for streaming transactions) and then
358 : : * applied by the worker.
359 : : *
360 : : * TRANS_LEADER_SERIALIZE:
361 : : * This action means that we are in the leader apply worker or table sync
362 : : * worker. Changes are written to temporary files and then applied when the
363 : : * final commit arrives.
364 : : *
365 : : * TRANS_LEADER_SEND_TO_PARALLEL:
366 : : * This action means that we are in the leader apply worker and need to send
367 : : * the changes to the parallel apply worker.
368 : : *
369 : : * TRANS_LEADER_PARTIAL_SERIALIZE:
370 : : * This action means that we are in the leader apply worker and have sent some
371 : : * changes directly to the parallel apply worker and the remaining changes are
372 : : * serialized to a file, due to timeout while sending data. The parallel apply
373 : : * worker will apply these serialized changes when the final commit arrives.
374 : : *
375 : : * We can't use TRANS_LEADER_SERIALIZE for this case because, in addition to
376 : : * serializing changes, the leader worker also needs to serialize the
377 : : * STREAM_XXX message to a file, and wait for the parallel apply worker to
378 : : * finish the transaction when processing the transaction finish command. So
379 : : * this new action was introduced to keep the code and logic clear.
380 : : *
381 : : * TRANS_PARALLEL_APPLY:
382 : : * This action means that we are in the parallel apply worker and changes of
383 : : * the transaction are applied directly by the worker.
384 : : */
385 : : typedef enum
386 : : {
387 : : /* The action for non-streaming transactions. */
388 : : TRANS_LEADER_APPLY,
389 : :
390 : : /* Actions for streaming transactions. */
391 : : TRANS_LEADER_SERIALIZE,
392 : : TRANS_LEADER_SEND_TO_PARALLEL,
393 : : TRANS_LEADER_PARTIAL_SERIALIZE,
394 : : TRANS_PARALLEL_APPLY,
395 : : } TransApplyAction;
396 : :
397 : : /*
398 : : * The phases involved in advancing the non-removable transaction ID.
399 : : *
400 : : * See comments atop worker.c for details of the transition between these
401 : : * phases.
402 : : */
403 : : typedef enum
404 : : {
405 : : RDT_GET_CANDIDATE_XID,
406 : : RDT_REQUEST_PUBLISHER_STATUS,
407 : : RDT_WAIT_FOR_PUBLISHER_STATUS,
408 : : RDT_WAIT_FOR_LOCAL_FLUSH,
409 : : RDT_STOP_CONFLICT_INFO_RETENTION,
410 : : RDT_RESUME_CONFLICT_INFO_RETENTION,
411 : : } RetainDeadTuplesPhase;
412 : :
413 : : /*
414 : : * Critical information for managing phase transitions within the
415 : : * RetainDeadTuplesPhase.
416 : : */
417 : : typedef struct RetainDeadTuplesData
418 : : {
419 : : RetainDeadTuplesPhase phase; /* current phase */
420 : : XLogRecPtr remote_lsn; /* WAL insert position on the publisher */
421 : :
422 : : /*
423 : : * Oldest transaction ID that was in the commit phase on the publisher.
424 : : * Use FullTransactionId to prevent issues with transaction ID wraparound,
425 : : * where a new remote_oldestxid could falsely appear to originate from the
426 : : * past and block advancement.
427 : : */
428 : : FullTransactionId remote_oldestxid;
429 : :
430 : : /*
431 : : * Next transaction ID to be assigned on the publisher. Use
432 : : * FullTransactionId for consistency and to allow straightforward
433 : : * comparisons with remote_oldestxid.
434 : : */
435 : : FullTransactionId remote_nextxid;
436 : :
437 : : TimestampTz reply_time; /* when the publisher responds with status */
438 : :
439 : : /*
440 : : * Publisher transaction ID that must be awaited to complete before
441 : : * entering the final phase (RDT_WAIT_FOR_LOCAL_FLUSH). Use
442 : : * FullTransactionId for the same reason as remote_nextxid.
443 : : */
444 : : FullTransactionId remote_wait_for;
445 : :
446 : : TransactionId candidate_xid; /* candidate for the non-removable
447 : : * transaction ID */
448 : : TimestampTz flushpos_update_time; /* when the remote flush position was
449 : : * updated in final phase
450 : : * (RDT_WAIT_FOR_LOCAL_FLUSH) */
451 : :
452 : : long table_sync_wait_time; /* time spent waiting for table sync
453 : : * to finish */
454 : :
455 : : /*
456 : : * The following fields are used to determine the timing for the next
457 : : * round of transaction ID advancement.
458 : : */
459 : : TimestampTz last_recv_time; /* when the last message was received */
460 : : TimestampTz candidate_xid_time; /* when the candidate_xid is decided */
461 : : int xid_advance_interval; /* how much time (ms) to wait before
462 : : * attempting to advance the
463 : : * non-removable transaction ID */
464 : : } RetainDeadTuplesData;
465 : :
466 : : /*
467 : : * The minimum (100ms) and maximum (3 minutes) intervals for advancing
468 : : * non-removable transaction IDs. The maximum interval is a bit arbitrary but
469 : : * is sufficient to not cause any undue network traffic.
470 : : */
471 : : #define MIN_XID_ADVANCE_INTERVAL 100
472 : : #define MAX_XID_ADVANCE_INTERVAL 180000
473 : :
474 : : /* Context of the remote transaction being applied */
475 : : static ApplyRemoteCtx remote_ctx =
476 : : {
477 : : .command = 0,
478 : : .rel = NULL,
479 : : .remote_attnum = -1,
480 : : .remote_xid = InvalidTransactionId,
481 : : .finish_lsn = InvalidXLogRecPtr,
482 : : .origin_name = NULL,
483 : : };
484 : :
485 : : ErrorContextCallback *apply_error_context_stack = NULL;
486 : :
487 : : MemoryContext ApplyMessageContext = NULL;
488 : : MemoryContext ApplyContext = NULL;
489 : :
490 : : /* per stream context for streaming transactions */
491 : : static MemoryContext LogicalStreamingContext = NULL;
492 : :
493 : : WalReceiverConn *LogRepWorkerWalRcvConn = NULL;
494 : :
495 : : Subscription *MySubscription = NULL;
496 : : char *MySubscriptionConninfo = NULL;
497 : : static bool MySubscriptionValid = false;
498 : :
499 : : static List *on_commit_wakeup_workers_subids = NIL;
500 : :
501 : : bool in_remote_transaction = false;
502 : :
503 : : /* fields valid only when processing streamed transaction */
504 : : static bool in_streamed_transaction = false;
505 : :
506 : : static TransactionId stream_xid = InvalidTransactionId;
507 : :
508 : : /*
509 : : * The number of changes applied by parallel apply worker during one streaming
510 : : * block.
511 : : */
512 : : static uint32 parallel_stream_nchanges = 0;
513 : :
514 : : /* Are we initializing an apply worker? */
515 : : bool InitializingApplyWorker = false;
516 : :
517 : : /*
518 : : * We enable skipping all data modification changes (INSERT, UPDATE, etc.) for
519 : : * the subscription if the remote transaction's finish LSN matches the subskiplsn.
520 : : * Once we start skipping changes, we don't stop it until we skip all changes of
521 : : * the transaction even if pg_subscription is updated and MySubscription->skiplsn
522 : : * gets changed or reset during that. Also, in streaming transaction cases (streaming = on),
523 : : * we don't skip receiving and spooling the changes since we decide whether or not
524 : : * to skip applying the changes when starting to apply changes. The subskiplsn is
525 : : * cleared after successfully skipping the transaction or applying non-empty
526 : : * transaction. The latter prevents the mistakenly specified subskiplsn from
527 : : * being left. Note that we cannot skip the streaming transactions when using
528 : : * parallel apply workers because we cannot get the finish LSN before applying
529 : : * the changes. So, we don't start parallel apply worker when finish LSN is set
530 : : * by the user.
531 : : */
532 : : static XLogRecPtr skip_xact_finish_lsn = InvalidXLogRecPtr;
533 : : #define is_skipping_changes() (unlikely(XLogRecPtrIsValid(skip_xact_finish_lsn)))
534 : :
535 : : /* BufFile handle of the current streaming file */
536 : : static BufFile *stream_fd = NULL;
537 : :
538 : : /*
539 : : * The remote WAL position that has been applied and flushed locally. We record
540 : : * and use this information both while sending feedback to the server and
541 : : * advancing oldest_nonremovable_xid.
542 : : */
543 : : static XLogRecPtr last_flushpos = InvalidXLogRecPtr;
544 : :
545 : : typedef struct SubXactInfo
546 : : {
547 : : TransactionId xid; /* XID of the subxact */
548 : : int fileno; /* file number in the buffile */
549 : : pgoff_t offset; /* offset in the file */
550 : : } SubXactInfo;
551 : :
552 : : /* Sub-transaction data for the current streaming transaction */
553 : : typedef struct ApplySubXactData
554 : : {
555 : : uint32 nsubxacts; /* number of sub-transactions */
556 : : uint32 nsubxacts_max; /* current capacity of subxacts */
557 : : TransactionId subxact_last; /* xid of the last sub-transaction */
558 : : SubXactInfo *subxacts; /* sub-xact offset in changes file */
559 : : } ApplySubXactData;
560 : :
561 : : static ApplySubXactData subxact_data = {0, 0, InvalidTransactionId, NULL};
562 : :
563 : : static inline void subxact_filename(char *path, Oid subid, TransactionId xid);
564 : : static inline void changes_filename(char *path, Oid subid, TransactionId xid);
565 : :
566 : : /*
567 : : * Information about subtransactions of a given toplevel transaction.
568 : : */
569 : : static void subxact_info_write(Oid subid, TransactionId xid);
570 : : static void subxact_info_read(Oid subid, TransactionId xid);
571 : : static void subxact_info_add(TransactionId xid);
572 : : static inline void cleanup_subxact_info(void);
573 : :
574 : : /*
575 : : * Serialize and deserialize changes for a toplevel transaction.
576 : : */
577 : : static void stream_open_file(Oid subid, TransactionId xid,
578 : : bool first_segment);
579 : : static void stream_write_change(char action, StringInfo s);
580 : : static void stream_open_and_write_change(TransactionId xid, char action, StringInfo s);
581 : : static void stream_close_file(void);
582 : :
583 : : static void send_feedback(XLogRecPtr recvpos, bool force, bool requestReply);
584 : :
585 : : static void maybe_advance_nonremovable_xid(RetainDeadTuplesData *rdt_data,
586 : : bool status_received);
587 : : static bool can_advance_nonremovable_xid(RetainDeadTuplesData *rdt_data);
588 : : static void process_rdt_phase_transition(RetainDeadTuplesData *rdt_data,
589 : : bool status_received);
590 : : static void get_candidate_xid(RetainDeadTuplesData *rdt_data);
591 : : static void request_publisher_status(RetainDeadTuplesData *rdt_data);
592 : : static void wait_for_publisher_status(RetainDeadTuplesData *rdt_data,
593 : : bool status_received);
594 : : static void wait_for_local_flush(RetainDeadTuplesData *rdt_data);
595 : : static bool should_stop_conflict_info_retention(RetainDeadTuplesData *rdt_data);
596 : : static void stop_conflict_info_retention(RetainDeadTuplesData *rdt_data);
597 : : static void resume_conflict_info_retention(RetainDeadTuplesData *rdt_data);
598 : : static bool update_retention_status(bool active);
599 : : static void reset_retention_data_fields(RetainDeadTuplesData *rdt_data);
600 : : static void adjust_xid_advance_interval(RetainDeadTuplesData *rdt_data,
601 : : bool new_xid_found);
602 : :
603 : : static void apply_worker_exit(void);
604 : :
605 : : static void apply_handle_commit_internal(LogicalRepCommitData *commit_data);
606 : : static void apply_handle_insert_internal(ApplyExecutionData *edata,
607 : : ResultRelInfo *relinfo,
608 : : TupleTableSlot *remoteslot);
609 : : static void apply_handle_update_internal(ApplyExecutionData *edata,
610 : : ResultRelInfo *relinfo,
611 : : TupleTableSlot *remoteslot,
612 : : LogicalRepTupleData *newtup,
613 : : Oid localindexoid);
614 : : static void apply_handle_delete_internal(ApplyExecutionData *edata,
615 : : ResultRelInfo *relinfo,
616 : : TupleTableSlot *remoteslot,
617 : : Oid localindexoid);
618 : : static bool FindReplTupleInLocalRel(ApplyExecutionData *edata, Relation localrel,
619 : : LogicalRepRelation *remoterel,
620 : : Oid localidxoid,
621 : : TupleTableSlot *remoteslot,
622 : : TupleTableSlot **localslot);
623 : : static bool FindDeletedTupleInLocalRel(Relation localrel,
624 : : Oid localidxoid,
625 : : TupleTableSlot *remoteslot,
626 : : TransactionId *delete_xid,
627 : : ReplOriginId *delete_origin,
628 : : TimestampTz *delete_time);
629 : : static void apply_handle_tuple_routing(ApplyExecutionData *edata,
630 : : TupleTableSlot *remoteslot,
631 : : LogicalRepTupleData *newtup,
632 : : CmdType operation);
633 : :
634 : : /* Functions for skipping changes */
635 : : static void maybe_start_skipping_changes(XLogRecPtr finish_lsn);
636 : : static void stop_skipping_changes(void);
637 : : static void clear_subscription_skip_lsn(XLogRecPtr finish_lsn);
638 : :
639 : : /* Functions to maintain the context of the remote transaction being applied */
640 : : static inline void set_remote_transaction_info(TransactionId xid, XLogRecPtr lsn);
641 : : static inline void reset_apply_remote_context(void);
642 : :
643 : : static TransApplyAction get_transaction_apply_action(TransactionId xid,
644 : : ParallelApplyWorkerInfo **winfo);
645 : :
646 : : static void set_wal_receiver_timeout(void);
647 : :
648 : : static void on_exit_clear_xact_state(int code, Datum arg);
649 : :
650 : : /*
651 : : * Form the origin name for the subscription.
652 : : *
653 : : * This is a common function for tablesync and other workers. Tablesync workers
654 : : * must pass a valid relid. Other callers must pass relid = InvalidOid.
655 : : *
656 : : * Return the name in the supplied buffer.
657 : : */
658 : : void
659 : 1560 : ReplicationOriginNameForLogicalRep(Oid suboid, Oid relid,
660 : : char *originname, Size szoriginname)
661 : : {
662 [ + + ]: 1560 : if (OidIsValid(relid))
663 : : {
664 : : /* Replication origin name for tablesync workers. */
665 : 819 : snprintf(originname, szoriginname, "pg_%u_%u", suboid, relid);
666 : : }
667 : : else
668 : : {
669 : : /* Replication origin name for non-tablesync workers. */
670 : 741 : snprintf(originname, szoriginname, "pg_%u", suboid);
671 : : }
672 : 1560 : }
673 : :
674 : : /*
675 : : * Should this worker apply changes for given relation.
676 : : *
677 : : * This is mainly needed for initial relation data sync as that runs in
678 : : * separate worker process running in parallel and we need some way to skip
679 : : * changes coming to the leader apply worker during the sync of a table.
680 : : *
681 : : * Note we need to do smaller or equals comparison for SYNCDONE state because
682 : : * it might hold position of end of initial slot consistent point WAL
683 : : * record + 1 (ie start of next record) and next record can be COMMIT of
684 : : * transaction we are now processing (which is what we set the finish LSN of
685 : : * the remote transaction context to in apply_handle_begin).
686 : : *
687 : : * Note that for streaming transactions that are being applied in the parallel
688 : : * apply worker, we disallow applying changes if the target table in the
689 : : * subscription is not in the READY state, because we cannot decide whether to
690 : : * apply the change as we won't know the finish LSN of the transaction by
691 : : * that time.
692 : : *
693 : : * We already checked this in pa_can_start() before assigning the
694 : : * streaming transaction to the parallel worker, but it also needs to be
695 : : * checked here because if the user executes ALTER SUBSCRIPTION ... REFRESH
696 : : * PUBLICATION in parallel, the new table can be added to pg_subscription_rel
697 : : * while applying this transaction.
698 : : */
699 : : static bool
700 : 169011 : should_apply_changes_for_rel(LogicalRepRelMapEntry *rel)
701 : : {
702 [ - + + - : 169011 : switch (MyLogicalRepWorker->type)
- - ]
703 : : {
704 : 0 : case WORKERTYPE_TABLESYNC:
705 : 0 : return MyLogicalRepWorker->relid == rel->localreloid;
706 : :
707 : 68516 : case WORKERTYPE_PARALLEL_APPLY:
708 : : /* We don't synchronize rel's that are in unknown state. */
709 [ - + ]: 68516 : if (rel->state != SUBREL_STATE_READY &&
710 [ # # ]: 0 : rel->state != SUBREL_STATE_UNKNOWN)
711 [ # # ]: 0 : ereport(ERROR,
712 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
713 : : errmsg("logical replication parallel apply worker for subscription \"%s\" will stop",
714 : : MySubscription->name),
715 : : errdetail("Cannot handle streamed replication transactions using parallel apply workers until all tables have been synchronized.")));
716 : :
717 : 68516 : return rel->state == SUBREL_STATE_READY;
718 : :
719 : 100495 : case WORKERTYPE_APPLY:
720 [ + + ]: 100561 : return (rel->state == SUBREL_STATE_READY ||
721 [ + + ]: 66 : (rel->state == SUBREL_STATE_SYNCDONE &&
722 [ + - ]: 18 : rel->statelsn <= remote_ctx.finish_lsn));
723 : :
724 : 0 : case WORKERTYPE_SEQUENCESYNC:
725 : : /* Should never happen. */
726 [ # # ]: 0 : elog(ERROR, "sequence synchronization worker is not expected to apply changes");
727 : : break;
728 : :
729 : 0 : case WORKERTYPE_UNKNOWN:
730 : : /* Should never happen. */
731 [ # # ]: 0 : elog(ERROR, "Unknown worker type");
732 : : }
733 : :
734 : 0 : return false; /* dummy for compiler */
735 : : }
736 : :
737 : : /*
738 : : * Begin one step (one INSERT, UPDATE, etc) of a replication transaction.
739 : : *
740 : : * Start a transaction, if this is the first step (else we keep using the
741 : : * existing transaction).
742 : : * Also provide a global snapshot and ensure we run in ApplyMessageContext.
743 : : */
744 : : static void
745 : 169477 : begin_replication_step(void)
746 : : {
747 : 169477 : SetCurrentStatementStartTimestamp();
748 : :
749 [ + + ]: 169477 : if (!IsTransactionState())
750 : : {
751 : 1036 : StartTransactionCommand();
752 : 1036 : maybe_reread_subscription();
753 : : }
754 : :
755 : 169474 : PushActiveSnapshot(GetTransactionSnapshot());
756 : :
757 : 169474 : MemoryContextSwitchTo(ApplyMessageContext);
758 : 169474 : }
759 : :
760 : : /*
761 : : * Finish up one step of a replication transaction.
762 : : * Callers of begin_replication_step() must also call this.
763 : : *
764 : : * We don't close out the transaction here, but we should increment
765 : : * the command counter to make the effects of this step visible.
766 : : */
767 : : static void
768 : 169396 : end_replication_step(void)
769 : : {
770 : 169396 : PopActiveSnapshot();
771 : :
772 : 169396 : CommandCounterIncrement();
773 : 169396 : }
774 : :
775 : : /*
776 : : * Handle streamed transactions for both the leader apply worker and the
777 : : * parallel apply workers.
778 : : *
779 : : * In the streaming case (receiving a block of the streamed transaction), for
780 : : * serialize mode, simply redirect it to a file for the proper toplevel
781 : : * transaction, and for parallel mode, the leader apply worker will send the
782 : : * changes to parallel apply workers and the parallel apply worker will define
783 : : * savepoints if needed. (LOGICAL_REP_MSG_RELATION or LOGICAL_REP_MSG_TYPE
784 : : * messages will be applied by both leader apply worker and parallel apply
785 : : * workers).
786 : : *
787 : : * Returns true for streamed transactions (when the change is either serialized
788 : : * to file or sent to parallel apply worker), false otherwise (regular mode or
789 : : * needs to be processed by parallel apply worker).
790 : : *
791 : : * Exception: If the message being processed is LOGICAL_REP_MSG_RELATION
792 : : * or LOGICAL_REP_MSG_TYPE, return false even if the message needs to be sent
793 : : * to a parallel apply worker.
794 : : */
795 : : static bool
796 : 345413 : handle_streamed_transaction(LogicalRepMsgType action, StringInfo s)
797 : : {
798 : : TransactionId current_xid;
799 : : ParallelApplyWorkerInfo *winfo;
800 : : TransApplyAction apply_action;
801 : : StringInfoData original_msg;
802 : :
803 : 345413 : apply_action = get_transaction_apply_action(stream_xid, &winfo);
804 : :
805 : : /* not in streaming mode */
806 [ + + ]: 345413 : if (apply_action == TRANS_LEADER_APPLY)
807 : 100958 : return false;
808 : :
809 : : Assert(TransactionIdIsValid(stream_xid));
810 : :
811 : : /*
812 : : * The parallel apply worker needs the xid in this message to decide
813 : : * whether to define a savepoint, so save the original message that has
814 : : * not moved the cursor after the xid. We will serialize this message to a
815 : : * file in PARTIAL_SERIALIZE mode.
816 : : */
817 : 244455 : original_msg = *s;
818 : :
819 : : /*
820 : : * We should have received XID of the subxact as the first part of the
821 : : * message, so extract it.
822 : : */
823 : 244455 : current_xid = pq_getmsgint(s, 4);
824 : :
825 [ - + ]: 244455 : if (!TransactionIdIsValid(current_xid))
826 [ # # ]: 0 : ereport(ERROR,
827 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
828 : : errmsg_internal("invalid transaction ID in streamed replication transaction")));
829 : :
830 [ + + + + : 244455 : switch (apply_action)
- ]
831 : : {
832 : 102513 : case TRANS_LEADER_SERIALIZE:
833 : : Assert(stream_fd);
834 : :
835 : : /* Add the new subxact to the array (unless already there). */
836 : 102513 : subxact_info_add(current_xid);
837 : :
838 : : /* Write the change to the current file */
839 : 102513 : stream_write_change(action, s);
840 : 102513 : return true;
841 : :
842 : 68390 : case TRANS_LEADER_SEND_TO_PARALLEL:
843 : : Assert(winfo);
844 : :
845 : : /*
846 : : * XXX The publisher side doesn't always send relation/type update
847 : : * messages after the streaming transaction, so also update the
848 : : * relation/type in leader apply worker. See function
849 : : * cleanup_rel_sync_cache.
850 : : */
851 [ + - ]: 68390 : if (pa_send_data(winfo, s->len, s->data))
852 [ + + + - ]: 68390 : return (action != LOGICAL_REP_MSG_RELATION &&
853 : : action != LOGICAL_REP_MSG_TYPE);
854 : :
855 : : /*
856 : : * Switch to serialize mode when we are not able to send the
857 : : * change to parallel apply worker.
858 : : */
859 : 0 : pa_switch_to_partial_serialize(winfo, false);
860 : :
861 : : pg_fallthrough;
862 : 5006 : case TRANS_LEADER_PARTIAL_SERIALIZE:
863 : 5006 : stream_write_change(action, &original_msg);
864 : :
865 : : /* Same reason as TRANS_LEADER_SEND_TO_PARALLEL case. */
866 [ + + + - ]: 5006 : return (action != LOGICAL_REP_MSG_RELATION &&
867 : : action != LOGICAL_REP_MSG_TYPE);
868 : :
869 : 68546 : case TRANS_PARALLEL_APPLY:
870 : 68546 : parallel_stream_nchanges += 1;
871 : :
872 : : /* Define a savepoint for a subxact if needed. */
873 : 68546 : pa_start_subtrans(current_xid, stream_xid);
874 : 68546 : return false;
875 : :
876 : 0 : default:
877 [ # # ]: 0 : elog(ERROR, "unexpected apply action: %d", (int) apply_action);
878 : : return false; /* silence compiler warning */
879 : : }
880 : : }
881 : :
882 : : /*
883 : : * Executor state preparation for evaluation of constraint expressions,
884 : : * indexes and triggers for the specified relation.
885 : : *
886 : : * Note that the caller must open and close any indexes to be updated.
887 : : */
888 : : static ApplyExecutionData *
889 : 168933 : create_edata_for_relation(LogicalRepRelMapEntry *rel)
890 : : {
891 : : ApplyExecutionData *edata;
892 : : EState *estate;
893 : : RangeTblEntry *rte;
894 : 168933 : List *perminfos = NIL;
895 : : ResultRelInfo *resultRelInfo;
896 : :
897 : 168933 : edata = palloc0_object(ApplyExecutionData);
898 : 168933 : edata->targetRel = rel;
899 : :
900 : 168933 : edata->estate = estate = CreateExecutorState();
901 : :
902 : 168933 : rte = makeNode(RangeTblEntry);
903 : 168933 : rte->rtekind = RTE_RELATION;
904 : 168933 : rte->relid = RelationGetRelid(rel->localrel);
905 : 168933 : rte->relkind = rel->localrel->rd_rel->relkind;
906 : 168933 : rte->rellockmode = AccessShareLock;
907 : :
908 : 168933 : addRTEPermissionInfo(&perminfos, rte);
909 : :
910 : 168933 : ExecInitRangeTable(estate, list_make1(rte), perminfos,
911 : : bms_make_singleton(1));
912 : :
913 : 168933 : edata->targetRelInfo = resultRelInfo = makeNode(ResultRelInfo);
914 : :
915 : : /*
916 : : * Use Relation opened by logicalrep_rel_open() instead of opening it
917 : : * again.
918 : : */
919 : 168933 : InitResultRelInfo(resultRelInfo, rel->localrel, 1, NULL, 0);
920 : :
921 : : /*
922 : : * We put the ResultRelInfo in the es_opened_result_relations list, even
923 : : * though we don't populate the es_result_relations array. That's a bit
924 : : * bogus, but it's enough to make ExecGetTriggerResultRel() find them.
925 : : *
926 : : * ExecOpenIndices() is not called here either, each execution path doing
927 : : * an apply operation being responsible for that.
928 : : */
929 : 168933 : estate->es_opened_result_relations =
930 : 168933 : lappend(estate->es_opened_result_relations, resultRelInfo);
931 : :
932 : 168933 : estate->es_output_cid = GetCurrentCommandId(true);
933 : :
934 : : /* Prepare to catch AFTER triggers. */
935 : 168933 : AfterTriggerBeginQuery();
936 : :
937 : : /* other fields of edata remain NULL for now */
938 : :
939 : 168933 : return edata;
940 : : }
941 : :
942 : : /*
943 : : * Finish any operations related to the executor state created by
944 : : * create_edata_for_relation().
945 : : */
946 : : static void
947 : 168869 : finish_edata(ApplyExecutionData *edata)
948 : : {
949 : 168869 : EState *estate = edata->estate;
950 : :
951 : : /* Handle any queued AFTER triggers. */
952 : 168869 : AfterTriggerEndQuery(estate);
953 : :
954 : : /* Shut down tuple routing, if any was done. */
955 [ + + ]: 168869 : if (edata->proute)
956 : 74 : ExecCleanupTupleRouting(edata->mtstate, edata->proute);
957 : :
958 : : /*
959 : : * Close relations opened specifically for trigger targets. It might seem
960 : : * that we should call ExecCloseResultRelations() here, but we
961 : : * intentionally don't as that would close the rel we added to
962 : : * es_opened_result_relations above, which is wrong because we took no
963 : : * corresponding refcount. ExecCleanupTupleRouting() closes relations
964 : : * opened for tuple routing, while ExecCloseTrigTargetRelations() closes
965 : : * any relations we opened for AFTER triggers.
966 : : */
967 : 168869 : ExecCloseTrigTargetRelations(estate);
968 : :
969 : 168869 : ExecResetTupleTable(estate->es_tupleTable, false);
970 : 168869 : FreeExecutorState(estate);
971 : 168869 : pfree(edata);
972 : 168869 : }
973 : :
974 : : /*
975 : : * Executes default values for columns for which we can't map to remote
976 : : * relation columns.
977 : : *
978 : : * This allows us to support tables which have more columns on the downstream
979 : : * than on the upstream.
980 : : */
981 : : static void
982 : 96643 : slot_fill_defaults(LogicalRepRelMapEntry *rel, EState *estate,
983 : : TupleTableSlot *slot)
984 : : {
985 : 96643 : TupleDesc desc = RelationGetDescr(rel->localrel);
986 : 96643 : int num_phys_attrs = desc->natts;
987 : : int i;
988 : : int attnum,
989 : 96643 : num_defaults = 0;
990 : : int *defmap;
991 : : ExprState **defexprs;
992 : : ExprContext *econtext;
993 : :
994 [ + - ]: 96643 : econtext = GetPerTupleExprContext(estate);
995 : :
996 : : /* We got all the data via replication, no need to evaluate anything. */
997 [ + + ]: 96643 : if (num_phys_attrs == rel->remoterel.natts)
998 : 56498 : return;
999 : :
1000 : 40145 : defmap = palloc_array(int, num_phys_attrs);
1001 : 40145 : defexprs = palloc_array(ExprState *, num_phys_attrs);
1002 : :
1003 : : Assert(rel->attrmap->maplen == num_phys_attrs);
1004 [ + + ]: 210663 : for (attnum = 0; attnum < num_phys_attrs; attnum++)
1005 : : {
1006 : 170518 : CompactAttribute *cattr = TupleDescCompactAttr(desc, attnum);
1007 : : Expr *defexpr;
1008 : :
1009 [ + - + + ]: 170518 : if (cattr->attisdropped || cattr->attgenerated)
1010 : 9 : continue;
1011 : :
1012 [ + + ]: 170509 : if (rel->attrmap->attnums[attnum] >= 0)
1013 : 92268 : continue;
1014 : :
1015 : 78241 : defexpr = (Expr *) build_column_default(rel->localrel, attnum + 1);
1016 : :
1017 [ + + ]: 78241 : if (defexpr != NULL)
1018 : : {
1019 : : /* Run the expression through planner */
1020 : 70131 : defexpr = expression_planner(defexpr);
1021 : :
1022 : : /* Initialize executable expression in copycontext */
1023 : 70131 : defexprs[num_defaults] = ExecInitExpr(defexpr, NULL);
1024 : 70131 : defmap[num_defaults] = attnum;
1025 : 70131 : num_defaults++;
1026 : : }
1027 : : }
1028 : :
1029 [ + + ]: 110276 : for (i = 0; i < num_defaults; i++)
1030 : 70131 : slot->tts_values[defmap[i]] =
1031 : 70131 : ExecEvalExpr(defexprs[i], econtext, &slot->tts_isnull[defmap[i]]);
1032 : : }
1033 : :
1034 : : /*
1035 : : * Store tuple data into slot.
1036 : : *
1037 : : * Incoming data can be either text or binary format.
1038 : : */
1039 : : static void
1040 : 168961 : slot_store_data(TupleTableSlot *slot, LogicalRepRelMapEntry *rel,
1041 : : LogicalRepTupleData *tupleData)
1042 : : {
1043 : 168961 : int natts = slot->tts_tupleDescriptor->natts;
1044 : : int i;
1045 : :
1046 : 168961 : ExecClearTuple(slot);
1047 : :
1048 : : /* Call the "in" function for each non-dropped, non-null attribute */
1049 : : Assert(natts == rel->attrmap->maplen);
1050 [ + + ]: 699688 : for (i = 0; i < natts; i++)
1051 : : {
1052 : 530727 : Form_pg_attribute att = TupleDescAttr(slot->tts_tupleDescriptor, i);
1053 : 530727 : int remoteattnum = rel->attrmap->attnums[i];
1054 : :
1055 [ + + + + ]: 530727 : if (!att->attisdropped && remoteattnum >= 0)
1056 : 323810 : {
1057 : : StringInfo colvalue;
1058 : :
1059 [ - + ]: 323810 : if (remoteattnum >= tupleData->ncols)
1060 [ # # ]: 0 : ereport(ERROR,
1061 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
1062 : : errmsg_plural("logical replication column %d not found in tuple: only %d column received",
1063 : : "logical replication column %d not found in tuple: only %d columns received",
1064 : : tupleData->ncols,
1065 : : remoteattnum + 1, tupleData->ncols)));
1066 : :
1067 : 323810 : colvalue = &tupleData->colvalues[remoteattnum];
1068 : :
1069 : : /* Set attnum for error callback */
1070 : 323810 : remote_ctx.remote_attnum = remoteattnum;
1071 : :
1072 [ + + ]: 323810 : if (tupleData->colstatus[remoteattnum] == LOGICALREP_COLUMN_TEXT)
1073 : : {
1074 : : Oid typinput;
1075 : : Oid typioparam;
1076 : :
1077 : 163315 : getTypeInputInfo(att->atttypid, &typinput, &typioparam);
1078 : 326630 : slot->tts_values[i] =
1079 : 163315 : OidInputFunctionCall(typinput, colvalue->data,
1080 : : typioparam, att->atttypmod);
1081 : 163315 : slot->tts_isnull[i] = false;
1082 : : }
1083 [ + + ]: 160495 : else if (tupleData->colstatus[remoteattnum] == LOGICALREP_COLUMN_BINARY)
1084 : : {
1085 : : Oid typreceive;
1086 : : Oid typioparam;
1087 : :
1088 : : /*
1089 : : * In some code paths we may be asked to re-parse the same
1090 : : * tuple data. Reset the StringInfo's cursor so that works.
1091 : : */
1092 : 110129 : colvalue->cursor = 0;
1093 : :
1094 : 110129 : getTypeBinaryInputInfo(att->atttypid, &typreceive, &typioparam);
1095 : 220258 : slot->tts_values[i] =
1096 : 110129 : OidReceiveFunctionCall(typreceive, colvalue,
1097 : : typioparam, att->atttypmod);
1098 : :
1099 : : /* Trouble if it didn't eat the whole buffer */
1100 [ - + ]: 110129 : if (colvalue->cursor != colvalue->len)
1101 [ # # ]: 0 : ereport(ERROR,
1102 : : (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1103 : : errmsg("incorrect binary data format in logical replication column %d",
1104 : : remoteattnum + 1)));
1105 : 110129 : slot->tts_isnull[i] = false;
1106 : : }
1107 : : else
1108 : : {
1109 : : /*
1110 : : * NULL value from remote. (We don't expect to see
1111 : : * LOGICALREP_COLUMN_UNCHANGED here, but if we do, treat it as
1112 : : * NULL.)
1113 : : */
1114 : 50366 : slot->tts_values[i] = (Datum) 0;
1115 : 50366 : slot->tts_isnull[i] = true;
1116 : : }
1117 : :
1118 : : /* Reset attnum for error callback */
1119 : 323810 : remote_ctx.remote_attnum = -1;
1120 : : }
1121 : : else
1122 : : {
1123 : : /*
1124 : : * We assign NULL to dropped attributes and missing values
1125 : : * (missing values should be later filled using
1126 : : * slot_fill_defaults).
1127 : : */
1128 : 206917 : slot->tts_values[i] = (Datum) 0;
1129 : 206917 : slot->tts_isnull[i] = true;
1130 : : }
1131 : : }
1132 : :
1133 : 168961 : ExecStoreVirtualTuple(slot);
1134 : 168961 : }
1135 : :
1136 : : /*
1137 : : * Replace updated columns with data from the LogicalRepTupleData struct.
1138 : : * This is somewhat similar to heap_modify_tuple but also calls the type
1139 : : * input functions on the user data.
1140 : : *
1141 : : * "slot" is filled with a copy of the tuple in "srcslot", replacing
1142 : : * columns provided in "tupleData" and leaving others as-is.
1143 : : *
1144 : : * Caution: unreplaced pass-by-ref columns in "slot" will point into the
1145 : : * storage for "srcslot". This is OK for current usage, but someday we may
1146 : : * need to materialize "slot" at the end to make it independent of "srcslot".
1147 : : */
1148 : : static void
1149 : 31932 : slot_modify_data(TupleTableSlot *slot, TupleTableSlot *srcslot,
1150 : : LogicalRepRelMapEntry *rel,
1151 : : LogicalRepTupleData *tupleData)
1152 : : {
1153 : 31932 : int natts = slot->tts_tupleDescriptor->natts;
1154 : : int i;
1155 : :
1156 : : /* We'll fill "slot" with a virtual tuple, so we must start with ... */
1157 : 31932 : ExecClearTuple(slot);
1158 : :
1159 : : /*
1160 : : * Copy all the column data from srcslot, so that we'll have valid values
1161 : : * for unreplaced columns.
1162 : : */
1163 : : Assert(natts == srcslot->tts_tupleDescriptor->natts);
1164 : 31932 : slot_getallattrs(srcslot);
1165 : 31932 : memcpy(slot->tts_values, srcslot->tts_values, natts * sizeof(Datum));
1166 : 31932 : memcpy(slot->tts_isnull, srcslot->tts_isnull, natts * sizeof(bool));
1167 : :
1168 : : /* Call the "in" function for each replaced attribute */
1169 : : Assert(natts == rel->attrmap->maplen);
1170 [ + + ]: 159311 : for (i = 0; i < natts; i++)
1171 : : {
1172 : 127379 : Form_pg_attribute att = TupleDescAttr(slot->tts_tupleDescriptor, i);
1173 : 127379 : int remoteattnum = rel->attrmap->attnums[i];
1174 : :
1175 [ + + ]: 127379 : if (remoteattnum < 0)
1176 : 58519 : continue;
1177 : :
1178 [ - + ]: 68860 : if (remoteattnum >= tupleData->ncols)
1179 [ # # ]: 0 : ereport(ERROR,
1180 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
1181 : : errmsg_plural("logical replication column %d not found in tuple: only %d column received",
1182 : : "logical replication column %d not found in tuple: only %d columns received",
1183 : : tupleData->ncols,
1184 : : remoteattnum + 1, tupleData->ncols)));
1185 : :
1186 [ + - ]: 68860 : if (tupleData->colstatus[remoteattnum] != LOGICALREP_COLUMN_UNCHANGED)
1187 : : {
1188 : 68860 : StringInfo colvalue = &tupleData->colvalues[remoteattnum];
1189 : :
1190 : : /* Set attnum for error callback */
1191 : 68860 : remote_ctx.remote_attnum = remoteattnum;
1192 : :
1193 [ + + ]: 68860 : if (tupleData->colstatus[remoteattnum] == LOGICALREP_COLUMN_TEXT)
1194 : : {
1195 : : Oid typinput;
1196 : : Oid typioparam;
1197 : :
1198 : 25456 : getTypeInputInfo(att->atttypid, &typinput, &typioparam);
1199 : 50912 : slot->tts_values[i] =
1200 : 25456 : OidInputFunctionCall(typinput, colvalue->data,
1201 : : typioparam, att->atttypmod);
1202 : 25456 : slot->tts_isnull[i] = false;
1203 : : }
1204 [ + + ]: 43404 : else if (tupleData->colstatus[remoteattnum] == LOGICALREP_COLUMN_BINARY)
1205 : : {
1206 : : Oid typreceive;
1207 : : Oid typioparam;
1208 : :
1209 : : /*
1210 : : * In some code paths we may be asked to re-parse the same
1211 : : * tuple data. Reset the StringInfo's cursor so that works.
1212 : : */
1213 : 43356 : colvalue->cursor = 0;
1214 : :
1215 : 43356 : getTypeBinaryInputInfo(att->atttypid, &typreceive, &typioparam);
1216 : 86712 : slot->tts_values[i] =
1217 : 43356 : OidReceiveFunctionCall(typreceive, colvalue,
1218 : : typioparam, att->atttypmod);
1219 : :
1220 : : /* Trouble if it didn't eat the whole buffer */
1221 [ - + ]: 43356 : if (colvalue->cursor != colvalue->len)
1222 [ # # ]: 0 : ereport(ERROR,
1223 : : (errcode(ERRCODE_INVALID_BINARY_REPRESENTATION),
1224 : : errmsg("incorrect binary data format in logical replication column %d",
1225 : : remoteattnum + 1)));
1226 : 43356 : slot->tts_isnull[i] = false;
1227 : : }
1228 : : else
1229 : : {
1230 : : /* must be LOGICALREP_COLUMN_NULL */
1231 : 48 : slot->tts_values[i] = (Datum) 0;
1232 : 48 : slot->tts_isnull[i] = true;
1233 : : }
1234 : :
1235 : : /* Reset attnum for error callback */
1236 : 68860 : remote_ctx.remote_attnum = -1;
1237 : : }
1238 : : }
1239 : :
1240 : : /* And finally, declare that "slot" contains a valid virtual tuple */
1241 : 31932 : ExecStoreVirtualTuple(slot);
1242 : 31932 : }
1243 : :
1244 : : /*
1245 : : * Handle BEGIN message.
1246 : : */
1247 : : static void
1248 : 557 : apply_handle_begin(StringInfo s)
1249 : : {
1250 : : LogicalRepBeginData begin_data;
1251 : :
1252 : : /* There must not be an active streaming transaction. */
1253 : : Assert(!TransactionIdIsValid(stream_xid));
1254 : :
1255 : 557 : logicalrep_read_begin(s, &begin_data);
1256 : 557 : set_remote_transaction_info(begin_data.xid, begin_data.final_lsn);
1257 : :
1258 : 557 : maybe_start_skipping_changes(begin_data.final_lsn);
1259 : :
1260 : 557 : in_remote_transaction = true;
1261 : :
1262 : 557 : pgstat_report_activity(STATE_RUNNING, NULL);
1263 : 557 : }
1264 : :
1265 : : /*
1266 : : * Handle COMMIT message.
1267 : : *
1268 : : * TODO, support tracking of multiple origins
1269 : : */
1270 : : static void
1271 : 477 : apply_handle_commit(StringInfo s)
1272 : : {
1273 : : LogicalRepCommitData commit_data;
1274 : :
1275 : 477 : logicalrep_read_commit(s, &commit_data);
1276 : :
1277 [ - + ]: 477 : if (commit_data.commit_lsn != remote_ctx.finish_lsn)
1278 [ # # ]: 0 : ereport(ERROR,
1279 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
1280 : : errmsg_internal("incorrect commit LSN %X/%08X in commit message (expected %X/%08X)",
1281 : : LSN_FORMAT_ARGS(commit_data.commit_lsn),
1282 : : LSN_FORMAT_ARGS(remote_ctx.finish_lsn))));
1283 : :
1284 : 477 : apply_handle_commit_internal(&commit_data);
1285 : :
1286 : : /*
1287 : : * Process any tables that are being synchronized in parallel, as well as
1288 : : * any newly added tables or sequences.
1289 : : */
1290 : 477 : ProcessSyncingRelations(commit_data.end_lsn);
1291 : :
1292 : 477 : pgstat_report_activity(STATE_IDLE, NULL);
1293 : 477 : reset_apply_remote_context();
1294 : 477 : }
1295 : :
1296 : : /*
1297 : : * Handle BEGIN PREPARE message.
1298 : : */
1299 : : static void
1300 : 17 : apply_handle_begin_prepare(StringInfo s)
1301 : : {
1302 : : LogicalRepPreparedTxnData begin_data;
1303 : :
1304 : : /* Tablesync should never receive prepare. */
1305 [ - + ]: 17 : if (am_tablesync_worker())
1306 [ # # ]: 0 : ereport(ERROR,
1307 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
1308 : : errmsg_internal("tablesync worker received a BEGIN PREPARE message")));
1309 : :
1310 : : /* There must not be an active streaming transaction. */
1311 : : Assert(!TransactionIdIsValid(stream_xid));
1312 : :
1313 : 17 : logicalrep_read_begin_prepare(s, &begin_data);
1314 : 17 : set_remote_transaction_info(begin_data.xid, begin_data.prepare_lsn);
1315 : :
1316 : 17 : maybe_start_skipping_changes(begin_data.prepare_lsn);
1317 : :
1318 : 17 : in_remote_transaction = true;
1319 : :
1320 : 17 : pgstat_report_activity(STATE_RUNNING, NULL);
1321 : 17 : }
1322 : :
1323 : : /*
1324 : : * Common function to prepare the GID.
1325 : : */
1326 : : static void
1327 : 26 : apply_handle_prepare_internal(LogicalRepPreparedTxnData *prepare_data)
1328 : : {
1329 : : char gid[GIDSIZE];
1330 : :
1331 : : /*
1332 : : * Compute unique GID for two_phase transactions. We don't use GID of
1333 : : * prepared transaction sent by server as that can lead to deadlock when
1334 : : * we have multiple subscriptions from same node point to publications on
1335 : : * the same node. See comments atop worker.c
1336 : : */
1337 : 26 : TwoPhaseTransactionGid(MySubscription->oid, prepare_data->xid,
1338 : : gid, sizeof(gid));
1339 : :
1340 : : /*
1341 : : * BeginTransactionBlock is necessary to balance the EndTransactionBlock
1342 : : * called within the PrepareTransactionBlock below.
1343 : : */
1344 [ + - ]: 26 : if (!IsTransactionBlock())
1345 : : {
1346 : 26 : BeginTransactionBlock();
1347 : 26 : CommitTransactionCommand(); /* Completes the preceding Begin command. */
1348 : : }
1349 : :
1350 : : /*
1351 : : * Update origin state so we can restart streaming from correct position
1352 : : * in case of crash.
1353 : : */
1354 : 26 : replorigin_xact_state.origin_lsn = prepare_data->end_lsn;
1355 : 26 : replorigin_xact_state.origin_timestamp = prepare_data->prepare_time;
1356 : :
1357 : 26 : PrepareTransactionBlock(gid);
1358 : 26 : }
1359 : :
1360 : : /*
1361 : : * Handle PREPARE message.
1362 : : */
1363 : : static void
1364 : 16 : apply_handle_prepare(StringInfo s)
1365 : : {
1366 : : LogicalRepPreparedTxnData prepare_data;
1367 : :
1368 : 16 : logicalrep_read_prepare(s, &prepare_data);
1369 : :
1370 [ - + ]: 16 : if (prepare_data.prepare_lsn != remote_ctx.finish_lsn)
1371 [ # # ]: 0 : ereport(ERROR,
1372 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
1373 : : errmsg_internal("incorrect prepare LSN %X/%08X in prepare message (expected %X/%08X)",
1374 : : LSN_FORMAT_ARGS(prepare_data.prepare_lsn),
1375 : : LSN_FORMAT_ARGS(remote_ctx.finish_lsn))));
1376 : :
1377 : : /*
1378 : : * Unlike commit, here, we always prepare the transaction even though no
1379 : : * change has happened in this transaction or all changes are skipped. It
1380 : : * is done this way because at commit prepared time, we won't know whether
1381 : : * we have skipped preparing a transaction because of those reasons.
1382 : : *
1383 : : * XXX, We can optimize such that at commit prepared time, we first check
1384 : : * whether we have prepared the transaction or not but that doesn't seem
1385 : : * worthwhile because such cases shouldn't be common.
1386 : : */
1387 : 16 : begin_replication_step();
1388 : :
1389 : 16 : apply_handle_prepare_internal(&prepare_data);
1390 : :
1391 : 16 : end_replication_step();
1392 : 16 : CommitTransactionCommand();
1393 : 15 : pgstat_report_stat(false);
1394 : :
1395 : : /*
1396 : : * It is okay not to set the local_end LSN for the prepare because we
1397 : : * always flush the prepare record. So, we can send the acknowledgment of
1398 : : * the remote_end LSN as soon as prepare is finished.
1399 : : *
1400 : : * XXX For the sake of consistency with commit, we could have set it with
1401 : : * the LSN of prepare but as of now we don't track that value similar to
1402 : : * XactLastCommitEnd, and adding it for this purpose doesn't seems worth
1403 : : * it.
1404 : : */
1405 : 15 : store_flush_position(prepare_data.end_lsn, InvalidXLogRecPtr);
1406 : :
1407 : 15 : in_remote_transaction = false;
1408 : :
1409 : : /*
1410 : : * Process any tables that are being synchronized in parallel, as well as
1411 : : * any newly added tables or sequences.
1412 : : */
1413 : 15 : ProcessSyncingRelations(prepare_data.end_lsn);
1414 : :
1415 : : /*
1416 : : * Since we have already prepared the transaction, in a case where the
1417 : : * server crashes before clearing the subskiplsn, it will be left but the
1418 : : * transaction won't be resent. But that's okay because it's a rare case
1419 : : * and the subskiplsn will be cleared when finishing the next transaction.
1420 : : */
1421 : 15 : stop_skipping_changes();
1422 : 15 : clear_subscription_skip_lsn(prepare_data.prepare_lsn);
1423 : :
1424 : 15 : pgstat_report_activity(STATE_IDLE, NULL);
1425 : 15 : reset_apply_remote_context();
1426 : 15 : }
1427 : :
1428 : : /*
1429 : : * Handle a COMMIT PREPARED of a previously PREPARED transaction.
1430 : : *
1431 : : * Note that we don't need to wait here if the transaction was prepared in a
1432 : : * parallel apply worker. In that case, we have already waited for the prepare
1433 : : * to finish in apply_handle_stream_prepare() which will ensure all the
1434 : : * operations in that transaction have happened in the subscriber, so no
1435 : : * concurrent transaction can cause deadlock or transaction dependency issues.
1436 : : */
1437 : : static void
1438 : 22 : apply_handle_commit_prepared(StringInfo s)
1439 : : {
1440 : : LogicalRepCommitPreparedTxnData prepare_data;
1441 : : char gid[GIDSIZE];
1442 : :
1443 : 22 : logicalrep_read_commit_prepared(s, &prepare_data);
1444 : 22 : set_remote_transaction_info(prepare_data.xid, prepare_data.commit_lsn);
1445 : :
1446 : : /* Compute GID for two_phase transactions. */
1447 : 22 : TwoPhaseTransactionGid(MySubscription->oid, prepare_data.xid,
1448 : : gid, sizeof(gid));
1449 : :
1450 : : /* There is no transaction when COMMIT PREPARED is called */
1451 : 22 : begin_replication_step();
1452 : :
1453 : : /*
1454 : : * Update origin state so we can restart streaming from correct position
1455 : : * in case of crash.
1456 : : */
1457 : 22 : replorigin_xact_state.origin_lsn = prepare_data.end_lsn;
1458 : 22 : replorigin_xact_state.origin_timestamp = prepare_data.commit_time;
1459 : :
1460 : 22 : FinishPreparedTransaction(gid, true);
1461 : 22 : end_replication_step();
1462 : 22 : CommitTransactionCommand();
1463 : 22 : pgstat_report_stat(false);
1464 : :
1465 : 22 : store_flush_position(prepare_data.end_lsn, XactLastCommitEnd);
1466 : 22 : in_remote_transaction = false;
1467 : :
1468 : : /*
1469 : : * Process any tables that are being synchronized in parallel, as well as
1470 : : * any newly added tables or sequences.
1471 : : */
1472 : 22 : ProcessSyncingRelations(prepare_data.end_lsn);
1473 : :
1474 : 22 : clear_subscription_skip_lsn(prepare_data.end_lsn);
1475 : :
1476 : 22 : pgstat_report_activity(STATE_IDLE, NULL);
1477 : 22 : reset_apply_remote_context();
1478 : 22 : }
1479 : :
1480 : : /*
1481 : : * Handle a ROLLBACK PREPARED of a previously PREPARED TRANSACTION.
1482 : : *
1483 : : * Note that we don't need to wait here if the transaction was prepared in a
1484 : : * parallel apply worker. In that case, we have already waited for the prepare
1485 : : * to finish in apply_handle_stream_prepare() which will ensure all the
1486 : : * operations in that transaction have happened in the subscriber, so no
1487 : : * concurrent transaction can cause deadlock or transaction dependency issues.
1488 : : */
1489 : : static void
1490 : 5 : apply_handle_rollback_prepared(StringInfo s)
1491 : : {
1492 : : LogicalRepRollbackPreparedTxnData rollback_data;
1493 : : char gid[GIDSIZE];
1494 : :
1495 : 5 : logicalrep_read_rollback_prepared(s, &rollback_data);
1496 : 5 : set_remote_transaction_info(rollback_data.xid, rollback_data.rollback_end_lsn);
1497 : :
1498 : : /* Compute GID for two_phase transactions. */
1499 : 5 : TwoPhaseTransactionGid(MySubscription->oid, rollback_data.xid,
1500 : : gid, sizeof(gid));
1501 : :
1502 : : /*
1503 : : * It is possible that we haven't received prepare because it occurred
1504 : : * before walsender reached a consistent point or the two_phase was still
1505 : : * not enabled by that time, so in such cases, we need to skip rollback
1506 : : * prepared.
1507 : : */
1508 [ + - ]: 5 : if (LookupGXact(gid, rollback_data.prepare_end_lsn,
1509 : : rollback_data.prepare_time))
1510 : : {
1511 : : /*
1512 : : * Update origin state so we can restart streaming from correct
1513 : : * position in case of crash.
1514 : : */
1515 : 5 : replorigin_xact_state.origin_lsn = rollback_data.rollback_end_lsn;
1516 : 5 : replorigin_xact_state.origin_timestamp = rollback_data.rollback_time;
1517 : :
1518 : : /* There is no transaction when ABORT/ROLLBACK PREPARED is called */
1519 : 5 : begin_replication_step();
1520 : 5 : FinishPreparedTransaction(gid, false);
1521 : 5 : end_replication_step();
1522 : 5 : CommitTransactionCommand();
1523 : :
1524 : 5 : clear_subscription_skip_lsn(rollback_data.rollback_end_lsn);
1525 : : }
1526 : :
1527 : 5 : pgstat_report_stat(false);
1528 : :
1529 : : /*
1530 : : * It is okay not to set the local_end LSN for the rollback of prepared
1531 : : * transaction because we always flush the WAL record for it. See
1532 : : * apply_handle_prepare.
1533 : : */
1534 : 5 : store_flush_position(rollback_data.rollback_end_lsn, InvalidXLogRecPtr);
1535 : 5 : in_remote_transaction = false;
1536 : :
1537 : : /*
1538 : : * Process any tables that are being synchronized in parallel, as well as
1539 : : * any newly added tables or sequences.
1540 : : */
1541 : 5 : ProcessSyncingRelations(rollback_data.rollback_end_lsn);
1542 : :
1543 : 5 : pgstat_report_activity(STATE_IDLE, NULL);
1544 : 5 : reset_apply_remote_context();
1545 : 5 : }
1546 : :
1547 : : /*
1548 : : * Handle STREAM PREPARE.
1549 : : */
1550 : : static void
1551 : 15 : apply_handle_stream_prepare(StringInfo s)
1552 : : {
1553 : : LogicalRepPreparedTxnData prepare_data;
1554 : : ParallelApplyWorkerInfo *winfo;
1555 : : TransApplyAction apply_action;
1556 : :
1557 : : /* Save the message before it is consumed. */
1558 : 15 : StringInfoData original_msg = *s;
1559 : :
1560 [ - + ]: 15 : if (in_streamed_transaction)
1561 [ # # ]: 0 : ereport(ERROR,
1562 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
1563 : : errmsg_internal("STREAM PREPARE message without STREAM STOP")));
1564 : :
1565 : : /* Tablesync should never receive prepare. */
1566 [ - + ]: 15 : if (am_tablesync_worker())
1567 [ # # ]: 0 : ereport(ERROR,
1568 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
1569 : : errmsg_internal("tablesync worker received a STREAM PREPARE message")));
1570 : :
1571 : 15 : logicalrep_read_stream_prepare(s, &prepare_data);
1572 : 15 : set_remote_transaction_info(prepare_data.xid, prepare_data.prepare_lsn);
1573 : :
1574 : 15 : apply_action = get_transaction_apply_action(prepare_data.xid, &winfo);
1575 : :
1576 [ + + + + : 15 : switch (apply_action)
- ]
1577 : : {
1578 : 5 : case TRANS_LEADER_APPLY:
1579 : :
1580 : : /*
1581 : : * The transaction has been serialized to file, so replay all the
1582 : : * spooled operations.
1583 : : */
1584 : 5 : apply_spooled_messages(MyLogicalRepWorker->stream_fileset,
1585 : : prepare_data.xid, prepare_data.prepare_lsn);
1586 : :
1587 : : /* Mark the transaction as prepared. */
1588 : 5 : apply_handle_prepare_internal(&prepare_data);
1589 : :
1590 : 5 : CommitTransactionCommand();
1591 : :
1592 : : /*
1593 : : * It is okay not to set the local_end LSN for the prepare because
1594 : : * we always flush the prepare record. See apply_handle_prepare.
1595 : : */
1596 : 5 : store_flush_position(prepare_data.end_lsn, InvalidXLogRecPtr);
1597 : :
1598 : 5 : in_remote_transaction = false;
1599 : :
1600 : : /* Unlink the files with serialized changes and subxact info. */
1601 : 5 : stream_cleanup_files(MyLogicalRepWorker->subid, prepare_data.xid);
1602 : :
1603 [ - + ]: 5 : elog(DEBUG1, "finished processing the STREAM PREPARE command");
1604 : 5 : break;
1605 : :
1606 : 4 : case TRANS_LEADER_SEND_TO_PARALLEL:
1607 : : Assert(winfo);
1608 : :
1609 [ + - ]: 4 : if (pa_send_data(winfo, s->len, s->data))
1610 : : {
1611 : : /* Finish processing the streaming transaction. */
1612 : 4 : pa_xact_finish(winfo, prepare_data.end_lsn);
1613 : 3 : break;
1614 : : }
1615 : :
1616 : : /*
1617 : : * Switch to serialize mode when we are not able to send the
1618 : : * change to parallel apply worker.
1619 : : */
1620 : 0 : pa_switch_to_partial_serialize(winfo, true);
1621 : :
1622 : : pg_fallthrough;
1623 : 1 : case TRANS_LEADER_PARTIAL_SERIALIZE:
1624 : : Assert(winfo);
1625 : :
1626 : 1 : stream_open_and_write_change(prepare_data.xid,
1627 : : LOGICAL_REP_MSG_STREAM_PREPARE,
1628 : : &original_msg);
1629 : :
1630 : 1 : pa_set_fileset_state(winfo->shared, FS_SERIALIZE_DONE);
1631 : :
1632 : : /* Finish processing the streaming transaction. */
1633 : 1 : pa_xact_finish(winfo, prepare_data.end_lsn);
1634 : 1 : break;
1635 : :
1636 : 5 : case TRANS_PARALLEL_APPLY:
1637 : :
1638 : : /*
1639 : : * If the parallel apply worker is applying spooled messages then
1640 : : * close the file before preparing.
1641 : : */
1642 [ + + ]: 5 : if (stream_fd)
1643 : 1 : stream_close_file();
1644 : :
1645 : 5 : begin_replication_step();
1646 : :
1647 : : /* Mark the transaction as prepared. */
1648 : 5 : apply_handle_prepare_internal(&prepare_data);
1649 : :
1650 : 5 : end_replication_step();
1651 : :
1652 : 5 : CommitTransactionCommand();
1653 : :
1654 : : /*
1655 : : * It is okay not to set the local_end LSN for the prepare because
1656 : : * we always flush the prepare record. See apply_handle_prepare.
1657 : : */
1658 : 4 : MyParallelShared->last_commit_end = InvalidXLogRecPtr;
1659 : :
1660 : 4 : pa_set_xact_state(MyParallelShared, PARALLEL_TRANS_FINISHED);
1661 : 4 : pa_unlock_transaction(MyParallelShared->xid, AccessExclusiveLock);
1662 : :
1663 : 4 : pa_reset_subtrans();
1664 : :
1665 [ + + ]: 4 : elog(DEBUG1, "finished processing the STREAM PREPARE command");
1666 : 4 : break;
1667 : :
1668 : 0 : default:
1669 [ # # ]: 0 : elog(ERROR, "unexpected apply action: %d", (int) apply_action);
1670 : : break;
1671 : : }
1672 : :
1673 : 13 : pgstat_report_stat(false);
1674 : :
1675 : : /*
1676 : : * Process any tables that are being synchronized in parallel, as well as
1677 : : * any newly added tables or sequences.
1678 : : */
1679 : 13 : ProcessSyncingRelations(prepare_data.end_lsn);
1680 : :
1681 : : /*
1682 : : * Similar to prepare case, the subskiplsn could be left in a case of
1683 : : * server crash but it's okay. See the comments in apply_handle_prepare().
1684 : : */
1685 : 13 : stop_skipping_changes();
1686 : 13 : clear_subscription_skip_lsn(prepare_data.prepare_lsn);
1687 : :
1688 : 13 : pgstat_report_activity(STATE_IDLE, NULL);
1689 : :
1690 : 13 : reset_apply_remote_context();
1691 : 13 : }
1692 : :
1693 : : /*
1694 : : * Handle ORIGIN message.
1695 : : *
1696 : : * TODO, support tracking of multiple origins
1697 : : */
1698 : : static void
1699 : 7 : apply_handle_origin(StringInfo s)
1700 : : {
1701 : : /*
1702 : : * ORIGIN message can only come inside streaming transaction or inside
1703 : : * remote transaction and before any actual writes.
1704 : : */
1705 [ + + ]: 7 : if (!in_streamed_transaction &&
1706 [ + - - + ]: 10 : (!in_remote_transaction ||
1707 [ - - ]: 5 : (IsTransactionState() && !am_tablesync_worker())))
1708 [ # # ]: 0 : ereport(ERROR,
1709 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
1710 : : errmsg_internal("ORIGIN message sent out of order")));
1711 : 7 : }
1712 : :
1713 : : /*
1714 : : * Initialize fileset (if not already done).
1715 : : *
1716 : : * Create a new file when first_segment is true, otherwise open the existing
1717 : : * file.
1718 : : */
1719 : : void
1720 : 363 : stream_start_internal(TransactionId xid, bool first_segment)
1721 : : {
1722 : 363 : begin_replication_step();
1723 : :
1724 : : /*
1725 : : * Initialize the worker's stream_fileset if we haven't yet. This will be
1726 : : * used for the entire duration of the worker so create it in a permanent
1727 : : * context. We create this on the very first streaming message from any
1728 : : * transaction and then use it for this and other streaming transactions.
1729 : : * Now, we could create a fileset at the start of the worker as well but
1730 : : * then we won't be sure that it will ever be used.
1731 : : */
1732 [ + + ]: 363 : if (!MyLogicalRepWorker->stream_fileset)
1733 : : {
1734 : : MemoryContext oldctx;
1735 : :
1736 : 14 : oldctx = MemoryContextSwitchTo(ApplyContext);
1737 : :
1738 : 14 : MyLogicalRepWorker->stream_fileset = palloc_object(FileSet);
1739 : 14 : FileSetInit(MyLogicalRepWorker->stream_fileset);
1740 : :
1741 : 14 : MemoryContextSwitchTo(oldctx);
1742 : : }
1743 : :
1744 : : /* Open the spool file for this transaction. */
1745 : 363 : stream_open_file(MyLogicalRepWorker->subid, xid, first_segment);
1746 : :
1747 : : /* If this is not the first segment, open existing subxact file. */
1748 [ + + ]: 363 : if (!first_segment)
1749 : 331 : subxact_info_read(MyLogicalRepWorker->subid, xid);
1750 : :
1751 : 363 : end_replication_step();
1752 : 363 : }
1753 : :
1754 : : /*
1755 : : * Handle STREAM START message.
1756 : : */
1757 : : static void
1758 : 841 : apply_handle_stream_start(StringInfo s)
1759 : : {
1760 : : bool first_segment;
1761 : : ParallelApplyWorkerInfo *winfo;
1762 : : TransApplyAction apply_action;
1763 : :
1764 : : /* Save the message before it is consumed. */
1765 : 841 : StringInfoData original_msg = *s;
1766 : :
1767 [ - + ]: 841 : if (in_streamed_transaction)
1768 [ # # ]: 0 : ereport(ERROR,
1769 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
1770 : : errmsg_internal("duplicate STREAM START message")));
1771 : :
1772 : : /* There must not be an active streaming transaction. */
1773 : : Assert(!TransactionIdIsValid(stream_xid));
1774 : :
1775 : : /* notify handle methods we're processing a remote transaction */
1776 : 841 : in_streamed_transaction = true;
1777 : :
1778 : : /* extract XID of the top-level transaction */
1779 : 841 : stream_xid = logicalrep_read_stream_start(s, &first_segment);
1780 : :
1781 [ - + ]: 841 : if (!TransactionIdIsValid(stream_xid))
1782 [ # # ]: 0 : ereport(ERROR,
1783 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
1784 : : errmsg_internal("invalid transaction ID in streamed replication transaction")));
1785 : :
1786 : : /*
1787 : : * The final LSN of the streamed transaction is known only when its commit
1788 : : * record arrives.
1789 : : */
1790 : 841 : set_remote_transaction_info(stream_xid, InvalidXLogRecPtr);
1791 : :
1792 : : /* Try to allocate a worker for the streaming transaction. */
1793 [ + + ]: 841 : if (first_segment)
1794 : 86 : pa_allocate_worker(stream_xid);
1795 : :
1796 : 841 : apply_action = get_transaction_apply_action(stream_xid, &winfo);
1797 : :
1798 [ + + + + : 841 : switch (apply_action)
- ]
1799 : : {
1800 : 343 : case TRANS_LEADER_SERIALIZE:
1801 : :
1802 : : /*
1803 : : * Function stream_start_internal starts a transaction. This
1804 : : * transaction will be committed on the stream stop unless it is a
1805 : : * tablesync worker in which case it will be committed after
1806 : : * processing all the messages. We need this transaction for
1807 : : * handling the BufFile, used for serializing the streaming data
1808 : : * and subxact info.
1809 : : */
1810 : 343 : stream_start_internal(stream_xid, first_segment);
1811 : 343 : break;
1812 : :
1813 : 243 : case TRANS_LEADER_SEND_TO_PARALLEL:
1814 : : Assert(winfo);
1815 : :
1816 : : /*
1817 : : * Once we start serializing the changes, the parallel apply
1818 : : * worker will wait for the leader to release the stream lock
1819 : : * until the end of the transaction. So, we don't need to release
1820 : : * the lock or increment the stream count in that case.
1821 : : */
1822 [ + + ]: 243 : if (pa_send_data(winfo, s->len, s->data))
1823 : : {
1824 : : /*
1825 : : * Unlock the shared object lock so that the parallel apply
1826 : : * worker can continue to receive changes.
1827 : : */
1828 [ + + ]: 239 : if (!first_segment)
1829 : 214 : pa_unlock_stream(winfo->shared->xid, AccessExclusiveLock);
1830 : :
1831 : : /*
1832 : : * Increment the number of streaming blocks waiting to be
1833 : : * processed by parallel apply worker.
1834 : : */
1835 : 239 : pg_atomic_add_fetch_u32(&winfo->shared->pending_stream_count, 1);
1836 : :
1837 : : /* Cache the parallel apply worker for this transaction. */
1838 : 239 : pa_set_stream_apply_worker(winfo);
1839 : 239 : break;
1840 : : }
1841 : :
1842 : : /*
1843 : : * Switch to serialize mode when we are not able to send the
1844 : : * change to parallel apply worker.
1845 : : */
1846 : 4 : pa_switch_to_partial_serialize(winfo, !first_segment);
1847 : :
1848 : : pg_fallthrough;
1849 : 15 : case TRANS_LEADER_PARTIAL_SERIALIZE:
1850 : : Assert(winfo);
1851 : :
1852 : : /*
1853 : : * Open the spool file unless it was already opened when switching
1854 : : * to serialize mode. The transaction started in
1855 : : * stream_start_internal will be committed on the stream stop.
1856 : : */
1857 [ + + ]: 15 : if (apply_action != TRANS_LEADER_SEND_TO_PARALLEL)
1858 : 11 : stream_start_internal(stream_xid, first_segment);
1859 : :
1860 : 15 : stream_write_change(LOGICAL_REP_MSG_STREAM_START, &original_msg);
1861 : :
1862 : : /* Cache the parallel apply worker for this transaction. */
1863 : 15 : pa_set_stream_apply_worker(winfo);
1864 : 15 : break;
1865 : :
1866 : 244 : case TRANS_PARALLEL_APPLY:
1867 [ + + ]: 244 : if (first_segment)
1868 : : {
1869 : : /* Hold the lock until the end of the transaction. */
1870 : 29 : pa_lock_transaction(MyParallelShared->xid, AccessExclusiveLock);
1871 : 29 : pa_set_xact_state(MyParallelShared, PARALLEL_TRANS_STARTED);
1872 : :
1873 : : /*
1874 : : * Signal the leader apply worker, as it may be waiting for
1875 : : * us.
1876 : : */
1877 : 29 : logicalrep_worker_wakeup(WORKERTYPE_APPLY,
1878 : 29 : MyLogicalRepWorker->subid, InvalidOid);
1879 : : }
1880 : :
1881 : 244 : parallel_stream_nchanges = 0;
1882 : 244 : break;
1883 : :
1884 : 0 : default:
1885 [ # # ]: 0 : elog(ERROR, "unexpected apply action: %d", (int) apply_action);
1886 : : break;
1887 : : }
1888 : :
1889 : 841 : pgstat_report_activity(STATE_RUNNING, NULL);
1890 : 841 : }
1891 : :
1892 : : /*
1893 : : * Update the information about subxacts and close the file.
1894 : : *
1895 : : * This function should be called when the stream_start_internal function has
1896 : : * been called.
1897 : : */
1898 : : void
1899 : 363 : stream_stop_internal(TransactionId xid)
1900 : : {
1901 : : /*
1902 : : * Serialize information about subxacts for the toplevel transaction, then
1903 : : * close the stream messages spool file.
1904 : : */
1905 : 363 : subxact_info_write(MyLogicalRepWorker->subid, xid);
1906 : 363 : stream_close_file();
1907 : :
1908 : : /* We must be in a valid transaction state */
1909 : : Assert(IsTransactionState());
1910 : :
1911 : : /* Commit the per-stream transaction */
1912 : 363 : CommitTransactionCommand();
1913 : :
1914 : : /* Reset per-stream context */
1915 : 363 : MemoryContextReset(LogicalStreamingContext);
1916 : 363 : }
1917 : :
1918 : : /*
1919 : : * Handle STREAM STOP message.
1920 : : */
1921 : : static void
1922 : 840 : apply_handle_stream_stop(StringInfo s)
1923 : : {
1924 : : ParallelApplyWorkerInfo *winfo;
1925 : : TransApplyAction apply_action;
1926 : :
1927 [ - + ]: 840 : if (!in_streamed_transaction)
1928 [ # # ]: 0 : ereport(ERROR,
1929 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
1930 : : errmsg_internal("STREAM STOP message without STREAM START")));
1931 : :
1932 : 840 : apply_action = get_transaction_apply_action(stream_xid, &winfo);
1933 : :
1934 [ + + + + : 840 : switch (apply_action)
- ]
1935 : : {
1936 : 343 : case TRANS_LEADER_SERIALIZE:
1937 : 343 : stream_stop_internal(stream_xid);
1938 : 343 : break;
1939 : :
1940 : 239 : case TRANS_LEADER_SEND_TO_PARALLEL:
1941 : : Assert(winfo);
1942 : :
1943 : : /*
1944 : : * Lock before sending the STREAM_STOP message so that the leader
1945 : : * can hold the lock first and the parallel apply worker will wait
1946 : : * for leader to release the lock. See Locking Considerations atop
1947 : : * applyparallelworker.c.
1948 : : */
1949 : 239 : pa_lock_stream(winfo->shared->xid, AccessExclusiveLock);
1950 : :
1951 [ + - ]: 239 : if (pa_send_data(winfo, s->len, s->data))
1952 : : {
1953 : 239 : pa_set_stream_apply_worker(NULL);
1954 : 239 : break;
1955 : : }
1956 : :
1957 : : /*
1958 : : * Switch to serialize mode when we are not able to send the
1959 : : * change to parallel apply worker.
1960 : : */
1961 : 0 : pa_switch_to_partial_serialize(winfo, true);
1962 : :
1963 : : pg_fallthrough;
1964 : 15 : case TRANS_LEADER_PARTIAL_SERIALIZE:
1965 : 15 : stream_write_change(LOGICAL_REP_MSG_STREAM_STOP, s);
1966 : 15 : stream_stop_internal(stream_xid);
1967 : 15 : pa_set_stream_apply_worker(NULL);
1968 : 15 : break;
1969 : :
1970 : 243 : case TRANS_PARALLEL_APPLY:
1971 [ + + ]: 243 : elog(DEBUG1, "applied %u changes in the streaming chunk",
1972 : : parallel_stream_nchanges);
1973 : :
1974 : : /*
1975 : : * By the time parallel apply worker is processing the changes in
1976 : : * the current streaming block, the leader apply worker may have
1977 : : * sent multiple streaming blocks. This can lead to parallel apply
1978 : : * worker start waiting even when there are more chunk of streams
1979 : : * in the queue. So, try to lock only if there is no message left
1980 : : * in the queue. See Locking Considerations atop
1981 : : * applyparallelworker.c.
1982 : : *
1983 : : * Note that here we have a race condition where we can start
1984 : : * waiting even when there are pending streaming chunks. This can
1985 : : * happen if the leader sends another streaming block and acquires
1986 : : * the stream lock again after the parallel apply worker checks
1987 : : * that there is no pending streaming block and before it actually
1988 : : * starts waiting on a lock. We can handle this case by not
1989 : : * allowing the leader to increment the stream block count during
1990 : : * the time parallel apply worker acquires the lock but it is not
1991 : : * clear whether that is worth the complexity.
1992 : : *
1993 : : * Now, if this missed chunk contains rollback to savepoint, then
1994 : : * there is a risk of deadlock which probably shouldn't happen
1995 : : * after restart.
1996 : : */
1997 : 243 : pa_decr_and_wait_stream_block();
1998 : 241 : break;
1999 : :
2000 : 0 : default:
2001 [ # # ]: 0 : elog(ERROR, "unexpected apply action: %d", (int) apply_action);
2002 : : break;
2003 : : }
2004 : :
2005 : 838 : in_streamed_transaction = false;
2006 : 838 : stream_xid = InvalidTransactionId;
2007 : :
2008 : : /*
2009 : : * The parallel apply worker could be in a transaction in which case we
2010 : : * need to report the state as STATE_IDLEINTRANSACTION.
2011 : : */
2012 [ + + ]: 838 : if (IsTransactionOrTransactionBlock())
2013 : 241 : pgstat_report_activity(STATE_IDLEINTRANSACTION, NULL);
2014 : : else
2015 : 597 : pgstat_report_activity(STATE_IDLE, NULL);
2016 : :
2017 : 838 : reset_apply_remote_context();
2018 : 838 : }
2019 : :
2020 : : /*
2021 : : * Helper function to handle STREAM ABORT message when the transaction was
2022 : : * serialized to file.
2023 : : */
2024 : : static void
2025 : 14 : stream_abort_internal(TransactionId xid, TransactionId subxid)
2026 : : {
2027 : : /*
2028 : : * If the two XIDs are the same, it's in fact abort of toplevel xact, so
2029 : : * just delete the files with serialized info.
2030 : : */
2031 [ + + ]: 14 : if (xid == subxid)
2032 : 1 : stream_cleanup_files(MyLogicalRepWorker->subid, xid);
2033 : : else
2034 : : {
2035 : : /*
2036 : : * OK, so it's a subxact. We need to read the subxact file for the
2037 : : * toplevel transaction, determine the offset tracked for the subxact,
2038 : : * and truncate the file with changes. We also remove the subxacts
2039 : : * with higher offsets (or rather higher XIDs).
2040 : : *
2041 : : * We intentionally scan the array from the tail, because we're likely
2042 : : * aborting a change for the most recent subtransactions.
2043 : : *
2044 : : * We can't use the binary search here as subxact XIDs won't
2045 : : * necessarily arrive in sorted order, consider the case where we have
2046 : : * released the savepoint for multiple subtransactions and then
2047 : : * performed rollback to savepoint for one of the earlier
2048 : : * sub-transaction.
2049 : : */
2050 : : int64 i;
2051 : : int64 subidx;
2052 : : BufFile *fd;
2053 : 13 : bool found = false;
2054 : : char path[MAXPGPATH];
2055 : :
2056 : 13 : subidx = -1;
2057 : 13 : begin_replication_step();
2058 : 13 : subxact_info_read(MyLogicalRepWorker->subid, xid);
2059 : :
2060 [ + + ]: 15 : for (i = subxact_data.nsubxacts; i > 0; i--)
2061 : : {
2062 [ + + ]: 11 : if (subxact_data.subxacts[i - 1].xid == subxid)
2063 : : {
2064 : 9 : subidx = (i - 1);
2065 : 9 : found = true;
2066 : 9 : break;
2067 : : }
2068 : : }
2069 : :
2070 : : /*
2071 : : * If it's an empty sub-transaction then we will not find the subxid
2072 : : * here so just cleanup the subxact info and return.
2073 : : */
2074 [ + + ]: 13 : if (!found)
2075 : : {
2076 : : /* Cleanup the subxact info */
2077 : 4 : cleanup_subxact_info();
2078 : 4 : end_replication_step();
2079 : 4 : CommitTransactionCommand();
2080 : 4 : return;
2081 : : }
2082 : :
2083 : : /* open the changes file */
2084 : 9 : changes_filename(path, MyLogicalRepWorker->subid, xid);
2085 : 9 : fd = BufFileOpenFileSet(MyLogicalRepWorker->stream_fileset, path,
2086 : : O_RDWR, false);
2087 : :
2088 : : /* OK, truncate the file at the right offset */
2089 : 9 : BufFileTruncateFileSet(fd, subxact_data.subxacts[subidx].fileno,
2090 : 9 : subxact_data.subxacts[subidx].offset);
2091 : 9 : BufFileClose(fd);
2092 : :
2093 : : /* discard the subxacts added later */
2094 : 9 : subxact_data.nsubxacts = subidx;
2095 : :
2096 : : /* write the updated subxact list */
2097 : 9 : subxact_info_write(MyLogicalRepWorker->subid, xid);
2098 : :
2099 : 9 : end_replication_step();
2100 : 9 : CommitTransactionCommand();
2101 : : }
2102 : : }
2103 : :
2104 : : /*
2105 : : * Handle STREAM ABORT message.
2106 : : */
2107 : : static void
2108 : 38 : apply_handle_stream_abort(StringInfo s)
2109 : : {
2110 : : TransactionId xid;
2111 : : TransactionId subxid;
2112 : : LogicalRepStreamAbortData abort_data;
2113 : : ParallelApplyWorkerInfo *winfo;
2114 : : TransApplyAction apply_action;
2115 : :
2116 : : /* Save the message before it is consumed. */
2117 : 38 : StringInfoData original_msg = *s;
2118 : : bool toplevel_xact;
2119 : :
2120 [ - + ]: 38 : if (in_streamed_transaction)
2121 [ # # ]: 0 : ereport(ERROR,
2122 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
2123 : : errmsg_internal("STREAM ABORT message without STREAM STOP")));
2124 : :
2125 : : /* We receive abort information only when we can apply in parallel. */
2126 : 38 : logicalrep_read_stream_abort(s, &abort_data,
2127 : 38 : MyLogicalRepWorker->parallel_apply);
2128 : :
2129 : 38 : xid = abort_data.xid;
2130 : 38 : subxid = abort_data.subxid;
2131 : 38 : toplevel_xact = (xid == subxid);
2132 : :
2133 : : /*
2134 : : * Record the xid of the (sub)transaction being aborted, so that the error
2135 : : * context names whatever failed. Note this is the top-level xid itself
2136 : : * when a top-level transaction aborts, and a subxid only when a
2137 : : * subtransaction rolls back. See set_remote_transaction_info().
2138 : : */
2139 : 38 : set_remote_transaction_info(subxid, abort_data.abort_lsn);
2140 : :
2141 : 38 : apply_action = get_transaction_apply_action(xid, &winfo);
2142 : :
2143 [ + + + + : 38 : switch (apply_action)
- ]
2144 : : {
2145 : 14 : case TRANS_LEADER_APPLY:
2146 : :
2147 : : /*
2148 : : * We are in the leader apply worker and the transaction has been
2149 : : * serialized to file.
2150 : : */
2151 : 14 : stream_abort_internal(xid, subxid);
2152 : :
2153 [ - + ]: 14 : elog(DEBUG1, "finished processing the STREAM ABORT command");
2154 : 14 : break;
2155 : :
2156 : 10 : case TRANS_LEADER_SEND_TO_PARALLEL:
2157 : : Assert(winfo);
2158 : :
2159 : : /*
2160 : : * For the case of aborting the subtransaction, we increment the
2161 : : * number of streaming blocks and take the lock again before
2162 : : * sending the STREAM_ABORT to ensure that the parallel apply
2163 : : * worker will wait on the lock for the next set of changes after
2164 : : * processing the STREAM_ABORT message if it is not already
2165 : : * waiting for STREAM_STOP message.
2166 : : *
2167 : : * It is important to perform this locking before sending the
2168 : : * STREAM_ABORT message so that the leader can hold the lock first
2169 : : * and the parallel apply worker will wait for the leader to
2170 : : * release the lock. This is the same as what we do in
2171 : : * apply_handle_stream_stop. See Locking Considerations atop
2172 : : * applyparallelworker.c.
2173 : : */
2174 [ + + ]: 10 : if (!toplevel_xact)
2175 : : {
2176 : 9 : pa_unlock_stream(xid, AccessExclusiveLock);
2177 : 9 : pg_atomic_add_fetch_u32(&winfo->shared->pending_stream_count, 1);
2178 : 9 : pa_lock_stream(xid, AccessExclusiveLock);
2179 : : }
2180 : :
2181 [ + - ]: 10 : if (pa_send_data(winfo, s->len, s->data))
2182 : : {
2183 : : /*
2184 : : * Unlike STREAM_COMMIT and STREAM_PREPARE, we don't need to
2185 : : * wait here for the parallel apply worker to finish as that
2186 : : * is not required to maintain the commit order and won't have
2187 : : * the risk of failures due to transaction dependencies and
2188 : : * deadlocks. However, it is possible that before the parallel
2189 : : * worker finishes and we clear the worker info, the xid
2190 : : * wraparound happens on the upstream and a new transaction
2191 : : * with the same xid can appear and that can lead to duplicate
2192 : : * entries in ParallelApplyTxnHash. Yet another problem could
2193 : : * be that we may have serialized the changes in partial
2194 : : * serialize mode and the file containing xact changes may
2195 : : * already exist, and after xid wraparound trying to create
2196 : : * the file for the same xid can lead to an error. To avoid
2197 : : * these problems, we decide to wait for the aborts to finish.
2198 : : *
2199 : : * Note, it is okay to not update the flush location position
2200 : : * for aborts as in worst case that means such a transaction
2201 : : * won't be sent again after restart.
2202 : : */
2203 [ + + ]: 10 : if (toplevel_xact)
2204 : 1 : pa_xact_finish(winfo, InvalidXLogRecPtr);
2205 : :
2206 : 10 : break;
2207 : : }
2208 : :
2209 : : /*
2210 : : * Switch to serialize mode when we are not able to send the
2211 : : * change to parallel apply worker.
2212 : : */
2213 : 0 : pa_switch_to_partial_serialize(winfo, true);
2214 : :
2215 : : pg_fallthrough;
2216 : 2 : case TRANS_LEADER_PARTIAL_SERIALIZE:
2217 : : Assert(winfo);
2218 : :
2219 : : /*
2220 : : * Parallel apply worker might have applied some changes, so write
2221 : : * the STREAM_ABORT message so that it can rollback the
2222 : : * subtransaction if needed.
2223 : : */
2224 : 2 : stream_open_and_write_change(xid, LOGICAL_REP_MSG_STREAM_ABORT,
2225 : : &original_msg);
2226 : :
2227 [ + + ]: 2 : if (toplevel_xact)
2228 : : {
2229 : 1 : pa_set_fileset_state(winfo->shared, FS_SERIALIZE_DONE);
2230 : 1 : pa_xact_finish(winfo, InvalidXLogRecPtr);
2231 : : }
2232 : 2 : break;
2233 : :
2234 : 12 : case TRANS_PARALLEL_APPLY:
2235 : :
2236 : : /*
2237 : : * If the parallel apply worker is applying spooled messages then
2238 : : * close the file before aborting.
2239 : : */
2240 [ + + + + ]: 12 : if (toplevel_xact && stream_fd)
2241 : 1 : stream_close_file();
2242 : :
2243 : 12 : pa_stream_abort(&abort_data);
2244 : :
2245 : : /*
2246 : : * We need to wait after processing rollback to savepoint for the
2247 : : * next set of changes.
2248 : : *
2249 : : * We have a race condition here due to which we can start waiting
2250 : : * here when there are more chunk of streams in the queue. See
2251 : : * apply_handle_stream_stop.
2252 : : */
2253 [ + + ]: 12 : if (!toplevel_xact)
2254 : 10 : pa_decr_and_wait_stream_block();
2255 : :
2256 [ + + ]: 12 : elog(DEBUG1, "finished processing the STREAM ABORT command");
2257 : 12 : break;
2258 : :
2259 : 0 : default:
2260 [ # # ]: 0 : elog(ERROR, "unexpected apply action: %d", (int) apply_action);
2261 : : break;
2262 : : }
2263 : :
2264 : 38 : reset_apply_remote_context();
2265 : 38 : }
2266 : :
2267 : : /*
2268 : : * Ensure that the passed location is fileset's end.
2269 : : */
2270 : : static void
2271 : 4 : ensure_last_message(FileSet *stream_fileset, TransactionId xid, int fileno,
2272 : : pgoff_t offset)
2273 : : {
2274 : : char path[MAXPGPATH];
2275 : : BufFile *fd;
2276 : : int last_fileno;
2277 : : pgoff_t last_offset;
2278 : :
2279 : : Assert(!IsTransactionState());
2280 : :
2281 : 4 : begin_replication_step();
2282 : :
2283 : 4 : changes_filename(path, MyLogicalRepWorker->subid, xid);
2284 : :
2285 : 4 : fd = BufFileOpenFileSet(stream_fileset, path, O_RDONLY, false);
2286 : :
2287 : 4 : BufFileSeek(fd, 0, 0, SEEK_END);
2288 : 4 : BufFileTell(fd, &last_fileno, &last_offset);
2289 : :
2290 : 4 : BufFileClose(fd);
2291 : :
2292 : 4 : end_replication_step();
2293 : :
2294 [ + - - + ]: 4 : if (last_fileno != fileno || last_offset != offset)
2295 [ # # ]: 0 : elog(ERROR, "unexpected message left in streaming transaction's changes file \"%s\"",
2296 : : path);
2297 : 4 : }
2298 : :
2299 : : /*
2300 : : * Common spoolfile processing.
2301 : : */
2302 : : void
2303 : 31 : apply_spooled_messages(FileSet *stream_fileset, TransactionId xid,
2304 : : XLogRecPtr lsn)
2305 : : {
2306 : : int nchanges;
2307 : : char path[MAXPGPATH];
2308 : 31 : char *buffer = NULL;
2309 : : MemoryContext oldcxt;
2310 : : ResourceOwner oldowner;
2311 : : int fileno;
2312 : : pgoff_t offset;
2313 : :
2314 [ + + ]: 31 : if (!am_parallel_apply_worker())
2315 : 27 : maybe_start_skipping_changes(lsn);
2316 : :
2317 : : /* Make sure we have an open transaction */
2318 : 31 : begin_replication_step();
2319 : :
2320 : : /*
2321 : : * Allocate file handle and memory required to process all the messages in
2322 : : * TopTransactionContext to avoid them getting reset after each message is
2323 : : * processed.
2324 : : */
2325 : 31 : oldcxt = MemoryContextSwitchTo(TopTransactionContext);
2326 : :
2327 : : /* Open the spool file for the committed/prepared transaction */
2328 : 31 : changes_filename(path, MyLogicalRepWorker->subid, xid);
2329 [ - + ]: 31 : elog(DEBUG1, "replaying changes from file \"%s\"", path);
2330 : :
2331 : : /*
2332 : : * Make sure the file is owned by the toplevel transaction so that the
2333 : : * file will not be accidentally closed when aborting a subtransaction.
2334 : : */
2335 : 31 : oldowner = CurrentResourceOwner;
2336 : 31 : CurrentResourceOwner = TopTransactionResourceOwner;
2337 : :
2338 : 31 : stream_fd = BufFileOpenFileSet(stream_fileset, path, O_RDONLY, false);
2339 : :
2340 : 31 : CurrentResourceOwner = oldowner;
2341 : :
2342 : 31 : buffer = palloc(BLCKSZ);
2343 : :
2344 : 31 : MemoryContextSwitchTo(oldcxt);
2345 : :
2346 : : /*
2347 : : * Make sure the handle apply_dispatch methods are aware we're in a remote
2348 : : * transaction.
2349 : : */
2350 : 31 : in_remote_transaction = true;
2351 : 31 : pgstat_report_activity(STATE_RUNNING, NULL);
2352 : :
2353 : 31 : end_replication_step();
2354 : :
2355 : : /*
2356 : : * Read the entries one by one and pass them through the same logic as in
2357 : : * apply_dispatch.
2358 : : */
2359 : 31 : nchanges = 0;
2360 : : while (true)
2361 : 88470 : {
2362 : : StringInfoData s2;
2363 : : size_t nbytes;
2364 : : int len;
2365 : :
2366 [ - + ]: 88501 : CHECK_FOR_INTERRUPTS();
2367 : :
2368 : : /* read length of the on-disk record */
2369 : 88501 : nbytes = BufFileReadMaybeEOF(stream_fd, &len, sizeof(len), true);
2370 : :
2371 : : /* have we reached end of the file? */
2372 [ + + ]: 88501 : if (nbytes == 0)
2373 : 26 : break;
2374 : :
2375 : : /* do we have a correct length? */
2376 [ - + ]: 88475 : if (len <= 0)
2377 [ # # ]: 0 : elog(ERROR, "incorrect length %d in streaming transaction's changes file \"%s\"",
2378 : : len, path);
2379 : :
2380 : : /* make sure we have sufficiently large buffer */
2381 : 88475 : buffer = repalloc(buffer, len);
2382 : :
2383 : : /* and finally read the data into the buffer */
2384 : 88475 : BufFileReadExact(stream_fd, buffer, len);
2385 : :
2386 : 88475 : BufFileTell(stream_fd, &fileno, &offset);
2387 : :
2388 : : /* init a stringinfo using the buffer and call apply_dispatch */
2389 : 88475 : initReadOnlyStringInfo(&s2, buffer, len);
2390 : :
2391 : : /* Ensure we are reading the data into our memory context. */
2392 : 88475 : oldcxt = MemoryContextSwitchTo(ApplyMessageContext);
2393 : :
2394 : 88475 : apply_dispatch(&s2);
2395 : :
2396 : 88474 : MemoryContextReset(ApplyMessageContext);
2397 : :
2398 : 88474 : MemoryContextSwitchTo(oldcxt);
2399 : :
2400 : 88474 : nchanges++;
2401 : :
2402 : : /*
2403 : : * It is possible the file has been closed because we have processed
2404 : : * the transaction end message like stream_commit in which case that
2405 : : * must be the last message.
2406 : : */
2407 [ + + ]: 88474 : if (!stream_fd)
2408 : : {
2409 : 4 : ensure_last_message(stream_fileset, xid, fileno, offset);
2410 : 4 : break;
2411 : : }
2412 : :
2413 [ + + ]: 88470 : if (nchanges % 1000 == 0)
2414 [ - + ]: 84 : elog(DEBUG1, "replayed %d changes from file \"%s\"",
2415 : : nchanges, path);
2416 : : }
2417 : :
2418 [ + + ]: 30 : if (stream_fd)
2419 : 26 : stream_close_file();
2420 : :
2421 [ - + ]: 30 : elog(DEBUG1, "replayed %d (all) changes from file \"%s\"",
2422 : : nchanges, path);
2423 : :
2424 : 30 : return;
2425 : : }
2426 : :
2427 : : /*
2428 : : * Handle STREAM COMMIT message.
2429 : : */
2430 : : static void
2431 : 61 : apply_handle_stream_commit(StringInfo s)
2432 : : {
2433 : : TransactionId xid;
2434 : : LogicalRepCommitData commit_data;
2435 : : ParallelApplyWorkerInfo *winfo;
2436 : : TransApplyAction apply_action;
2437 : :
2438 : : /* Save the message before it is consumed. */
2439 : 61 : StringInfoData original_msg = *s;
2440 : :
2441 [ - + ]: 61 : if (in_streamed_transaction)
2442 [ # # ]: 0 : ereport(ERROR,
2443 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
2444 : : errmsg_internal("STREAM COMMIT message without STREAM STOP")));
2445 : :
2446 : 61 : xid = logicalrep_read_stream_commit(s, &commit_data);
2447 : 61 : set_remote_transaction_info(xid, commit_data.commit_lsn);
2448 : :
2449 : 61 : apply_action = get_transaction_apply_action(xid, &winfo);
2450 : :
2451 [ + + + + : 61 : switch (apply_action)
- ]
2452 : : {
2453 : 22 : case TRANS_LEADER_APPLY:
2454 : :
2455 : : /*
2456 : : * The transaction has been serialized to file, so replay all the
2457 : : * spooled operations.
2458 : : */
2459 : 22 : apply_spooled_messages(MyLogicalRepWorker->stream_fileset, xid,
2460 : : commit_data.commit_lsn);
2461 : :
2462 : 21 : apply_handle_commit_internal(&commit_data);
2463 : :
2464 : : /* Unlink the files with serialized changes and subxact info. */
2465 : 21 : stream_cleanup_files(MyLogicalRepWorker->subid, xid);
2466 : :
2467 [ - + ]: 21 : elog(DEBUG1, "finished processing the STREAM COMMIT command");
2468 : 21 : break;
2469 : :
2470 : 18 : case TRANS_LEADER_SEND_TO_PARALLEL:
2471 : : Assert(winfo);
2472 : :
2473 [ + - ]: 18 : if (pa_send_data(winfo, s->len, s->data))
2474 : : {
2475 : : /* Finish processing the streaming transaction. */
2476 : 18 : pa_xact_finish(winfo, commit_data.end_lsn);
2477 : 17 : break;
2478 : : }
2479 : :
2480 : : /*
2481 : : * Switch to serialize mode when we are not able to send the
2482 : : * change to parallel apply worker.
2483 : : */
2484 : 0 : pa_switch_to_partial_serialize(winfo, true);
2485 : :
2486 : : pg_fallthrough;
2487 : 2 : case TRANS_LEADER_PARTIAL_SERIALIZE:
2488 : : Assert(winfo);
2489 : :
2490 : 2 : stream_open_and_write_change(xid, LOGICAL_REP_MSG_STREAM_COMMIT,
2491 : : &original_msg);
2492 : :
2493 : 2 : pa_set_fileset_state(winfo->shared, FS_SERIALIZE_DONE);
2494 : :
2495 : : /* Finish processing the streaming transaction. */
2496 : 2 : pa_xact_finish(winfo, commit_data.end_lsn);
2497 : 2 : break;
2498 : :
2499 : 19 : case TRANS_PARALLEL_APPLY:
2500 : :
2501 : : /*
2502 : : * If the parallel apply worker is applying spooled messages then
2503 : : * close the file before committing.
2504 : : */
2505 [ + + ]: 19 : if (stream_fd)
2506 : 2 : stream_close_file();
2507 : :
2508 : 19 : apply_handle_commit_internal(&commit_data);
2509 : :
2510 : 19 : MyParallelShared->last_commit_end = XactLastCommitEnd;
2511 : :
2512 : : /*
2513 : : * It is important to set the transaction state as finished before
2514 : : * releasing the lock. See pa_wait_for_xact_finish.
2515 : : */
2516 : 19 : pa_set_xact_state(MyParallelShared, PARALLEL_TRANS_FINISHED);
2517 : 19 : pa_unlock_transaction(xid, AccessExclusiveLock);
2518 : :
2519 : 19 : pa_reset_subtrans();
2520 : :
2521 [ + + ]: 19 : elog(DEBUG1, "finished processing the STREAM COMMIT command");
2522 : 19 : break;
2523 : :
2524 : 0 : default:
2525 [ # # ]: 0 : elog(ERROR, "unexpected apply action: %d", (int) apply_action);
2526 : : break;
2527 : : }
2528 : :
2529 : : /*
2530 : : * Process any tables that are being synchronized in parallel, as well as
2531 : : * any newly added tables or sequences.
2532 : : */
2533 : 59 : ProcessSyncingRelations(commit_data.end_lsn);
2534 : :
2535 : 59 : pgstat_report_activity(STATE_IDLE, NULL);
2536 : :
2537 : 59 : reset_apply_remote_context();
2538 : 59 : }
2539 : :
2540 : : /*
2541 : : * Helper function for apply_handle_commit and apply_handle_stream_commit.
2542 : : */
2543 : : static void
2544 : 517 : apply_handle_commit_internal(LogicalRepCommitData *commit_data)
2545 : : {
2546 [ + + ]: 517 : if (is_skipping_changes())
2547 : : {
2548 : 2 : stop_skipping_changes();
2549 : :
2550 : : /*
2551 : : * Start a new transaction to clear the subskiplsn, if not started
2552 : : * yet.
2553 : : */
2554 [ + + ]: 2 : if (!IsTransactionState())
2555 : 1 : StartTransactionCommand();
2556 : : }
2557 : :
2558 [ + - ]: 517 : if (IsTransactionState())
2559 : : {
2560 : : /*
2561 : : * The transaction is either non-empty or skipped, so we clear the
2562 : : * subskiplsn.
2563 : : */
2564 : 517 : clear_subscription_skip_lsn(commit_data->commit_lsn);
2565 : :
2566 : : /*
2567 : : * Update origin state so we can restart streaming from correct
2568 : : * position in case of crash.
2569 : : */
2570 : 517 : replorigin_xact_state.origin_lsn = commit_data->end_lsn;
2571 : 517 : replorigin_xact_state.origin_timestamp = commit_data->committime;
2572 : :
2573 : 517 : CommitTransactionCommand();
2574 : :
2575 [ + + ]: 517 : if (IsTransactionBlock())
2576 : : {
2577 : 4 : EndTransactionBlock(false);
2578 : 4 : CommitTransactionCommand();
2579 : : }
2580 : :
2581 : 517 : pgstat_report_stat(false);
2582 : :
2583 : 517 : store_flush_position(commit_data->end_lsn, XactLastCommitEnd);
2584 : : }
2585 : : else
2586 : : {
2587 : : /* Process any invalidation messages that might have accumulated. */
2588 : 0 : AcceptInvalidationMessages();
2589 : 0 : maybe_reread_subscription();
2590 : : }
2591 : :
2592 : 517 : in_remote_transaction = false;
2593 : 517 : }
2594 : :
2595 : : /*
2596 : : * Handle RELATION message.
2597 : : *
2598 : : * Note we don't do validation against local schema here. The validation
2599 : : * against local schema is postponed until first change for given relation
2600 : : * comes as we only care about it when applying changes for it anyway and we
2601 : : * do less locking this way.
2602 : : */
2603 : : static void
2604 : 534 : apply_handle_relation(StringInfo s)
2605 : : {
2606 : : LogicalRepRelation *rel;
2607 : :
2608 [ + + ]: 534 : if (handle_streamed_transaction(LOGICAL_REP_MSG_RELATION, s))
2609 : 36 : return;
2610 : :
2611 : 498 : rel = logicalrep_read_rel(s);
2612 : 498 : logicalrep_relmap_update(rel);
2613 : :
2614 : : /* Also reset all entries in the partition map that refer to remoterel. */
2615 : 498 : logicalrep_partmap_reset_relmap(rel);
2616 : : }
2617 : :
2618 : : /*
2619 : : * Handle TYPE message.
2620 : : *
2621 : : * This implementation pays no attention to TYPE messages; we expect the user
2622 : : * to have set things up so that the incoming data is acceptable to the input
2623 : : * functions for the locally subscribed tables. Hence, we just read and
2624 : : * discard the message.
2625 : : */
2626 : : static void
2627 : 18 : apply_handle_type(StringInfo s)
2628 : : {
2629 : : LogicalRepTyp typ;
2630 : :
2631 [ - + ]: 18 : if (handle_streamed_transaction(LOGICAL_REP_MSG_TYPE, s))
2632 : 0 : return;
2633 : :
2634 : 18 : logicalrep_read_typ(s, &typ);
2635 : : }
2636 : :
2637 : : /*
2638 : : * Check that we (the subscription owner) have sufficient privileges on the
2639 : : * target relation to perform the given operation.
2640 : : */
2641 : : static void
2642 : 241220 : TargetPrivilegesCheck(Relation rel, AclMode mode)
2643 : : {
2644 : : Oid relid;
2645 : : AclResult aclresult;
2646 : :
2647 : 241220 : relid = RelationGetRelid(rel);
2648 : 241220 : aclresult = pg_class_aclcheck(relid, GetUserId(), mode);
2649 [ + + ]: 241220 : if (aclresult != ACLCHECK_OK)
2650 : 11 : aclcheck_error(aclresult,
2651 : 11 : get_relkind_objtype(rel->rd_rel->relkind),
2652 : 11 : get_rel_name(relid));
2653 : :
2654 : : /*
2655 : : * We lack the infrastructure to honor RLS policies. It might be possible
2656 : : * to add such infrastructure here, but tablesync workers lack it, too, so
2657 : : * we don't bother. RLS does not ordinarily apply to TRUNCATE commands,
2658 : : * but it seems dangerous to replicate a TRUNCATE and then refuse to
2659 : : * replicate subsequent INSERTs, so we forbid all commands the same.
2660 : : */
2661 [ + + ]: 241209 : if (check_enable_rls(relid, InvalidOid, false) == RLS_ENABLED)
2662 [ + - ]: 4 : ereport(ERROR,
2663 : : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
2664 : : errmsg("user \"%s\" cannot replicate into relation with row-level security enabled: \"%s\"",
2665 : : GetUserNameFromId(GetUserId(), true),
2666 : : RelationGetRelationName(rel))));
2667 : 241205 : }
2668 : :
2669 : : /*
2670 : : * Handle INSERT message.
2671 : : */
2672 : :
2673 : : static void
2674 : 206715 : apply_handle_insert(StringInfo s)
2675 : : {
2676 : : LogicalRepRelMapEntry *rel;
2677 : : LogicalRepTupleData newtup;
2678 : : LogicalRepRelId relid;
2679 : : UserContext ucxt;
2680 : : ApplyExecutionData *edata;
2681 : : EState *estate;
2682 : : TupleTableSlot *remoteslot;
2683 : : MemoryContext oldctx;
2684 : : bool run_as_owner;
2685 : :
2686 : : /*
2687 : : * Quick return if we are skipping data modification changes or handling
2688 : : * streamed transactions.
2689 : : */
2690 [ + + + + ]: 403429 : if (is_skipping_changes() ||
2691 : 196714 : handle_streamed_transaction(LOGICAL_REP_MSG_INSERT, s))
2692 : 110057 : return;
2693 : :
2694 : 96706 : begin_replication_step();
2695 : :
2696 : 96704 : relid = logicalrep_read_insert(s, &newtup);
2697 : 96704 : rel = logicalrep_rel_open(relid, RowExclusiveLock);
2698 [ + + ]: 96691 : if (!should_apply_changes_for_rel(rel))
2699 : : {
2700 : : /*
2701 : : * The relation can't become interesting in the middle of the
2702 : : * transaction so it's safe to unlock it.
2703 : : */
2704 : 48 : logicalrep_rel_close(rel, RowExclusiveLock);
2705 : 48 : end_replication_step();
2706 : 48 : return;
2707 : : }
2708 : :
2709 : : /*
2710 : : * Make sure that any user-supplied code runs as the table owner, unless
2711 : : * the user has opted out of that behavior.
2712 : : */
2713 : 96643 : run_as_owner = MySubscription->runasowner;
2714 [ + + ]: 96643 : if (!run_as_owner)
2715 : 96633 : SwitchToUntrustedUser(rel->localrel->rd_rel->relowner, &ucxt);
2716 : :
2717 : : /* Set relation for error callback */
2718 : 96643 : remote_ctx.rel = rel;
2719 : :
2720 : : /* Initialize the executor state. */
2721 : 96643 : edata = create_edata_for_relation(rel);
2722 : 96643 : estate = edata->estate;
2723 : 96643 : remoteslot = ExecInitExtraTupleSlot(estate,
2724 : 96643 : RelationGetDescr(rel->localrel),
2725 : : &TTSOpsVirtual);
2726 : :
2727 : : /* Process and store remote tuple in the slot */
2728 [ - + ]: 96643 : oldctx = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
2729 : 96643 : slot_store_data(remoteslot, rel, &newtup);
2730 : 96643 : slot_fill_defaults(rel, estate, remoteslot);
2731 : 96643 : MemoryContextSwitchTo(oldctx);
2732 : :
2733 : : /* For a partitioned table, insert the tuple into a partition. */
2734 [ + + ]: 96643 : if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2735 : 81 : apply_handle_tuple_routing(edata,
2736 : : remoteslot, NULL, CMD_INSERT);
2737 : : else
2738 : : {
2739 : 96562 : ResultRelInfo *relinfo = edata->targetRelInfo;
2740 : :
2741 : 96562 : ExecOpenIndices(relinfo, false);
2742 : 96562 : apply_handle_insert_internal(edata, relinfo, remoteslot);
2743 : 96544 : ExecCloseIndices(relinfo);
2744 : : }
2745 : :
2746 : 96588 : finish_edata(edata);
2747 : :
2748 : : /* Reset relation for error callback */
2749 : 96588 : remote_ctx.rel = NULL;
2750 : :
2751 [ + + ]: 96588 : if (!run_as_owner)
2752 : 96583 : RestoreUserContext(&ucxt);
2753 : :
2754 : 96588 : logicalrep_rel_close(rel, NoLock);
2755 : :
2756 : 96588 : end_replication_step();
2757 : : }
2758 : :
2759 : : /*
2760 : : * Workhorse for apply_handle_insert()
2761 : : * relinfo is for the relation we're actually inserting into
2762 : : * (could be a child partition of edata->targetRelInfo)
2763 : : */
2764 : : static void
2765 : 96644 : apply_handle_insert_internal(ApplyExecutionData *edata,
2766 : : ResultRelInfo *relinfo,
2767 : : TupleTableSlot *remoteslot)
2768 : : {
2769 : 96644 : EState *estate = edata->estate;
2770 : :
2771 : : /* Caller should have opened indexes already. */
2772 : : Assert(relinfo->ri_IndexRelationDescs != NULL ||
2773 : : !relinfo->ri_RelationDesc->rd_rel->relhasindex ||
2774 : : RelationGetIndexList(relinfo->ri_RelationDesc) == NIL);
2775 : :
2776 : : /* Caller will not have done this bit. */
2777 : : Assert(relinfo->ri_onConflictArbiterIndexes == NIL);
2778 : 96644 : InitConflictIndexes(relinfo);
2779 : :
2780 : : /* Do the insert. */
2781 : 96644 : TargetPrivilegesCheck(relinfo->ri_RelationDesc, ACL_INSERT);
2782 : 96635 : ExecSimpleRelationInsert(relinfo, estate, remoteslot);
2783 : 96589 : }
2784 : :
2785 : : /*
2786 : : * Check if the logical replication relation is updatable and throw
2787 : : * appropriate error if it isn't.
2788 : : */
2789 : : static void
2790 : 72321 : check_relation_updatable(LogicalRepRelMapEntry *rel)
2791 : : {
2792 : : /*
2793 : : * For partitioned tables, we only need to care if the target partition is
2794 : : * updatable (aka has PK or RI defined for it).
2795 : : */
2796 [ + + ]: 72321 : if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2797 : 30 : return;
2798 : :
2799 : : /* Updatable, no error. */
2800 [ + - ]: 72291 : if (rel->updatable)
2801 : 72291 : return;
2802 : :
2803 : : /*
2804 : : * We are in error mode so it's fine this is somewhat slow. It's better to
2805 : : * give user correct error.
2806 : : */
2807 [ # # ]: 0 : if (OidIsValid(GetRelationIdentityOrPK(rel->localrel)))
2808 : : {
2809 [ # # ]: 0 : ereport(ERROR,
2810 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2811 : : errmsg("publisher did not send replica identity column "
2812 : : "expected by the logical replication target relation \"%s.%s\"",
2813 : : rel->remoterel.nspname, rel->remoterel.relname)));
2814 : : }
2815 : :
2816 [ # # ]: 0 : ereport(ERROR,
2817 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
2818 : : errmsg("logical replication target relation \"%s.%s\" has "
2819 : : "neither REPLICA IDENTITY index nor PRIMARY "
2820 : : "KEY and published relation does not have "
2821 : : "REPLICA IDENTITY FULL",
2822 : : rel->remoterel.nspname, rel->remoterel.relname)));
2823 : : }
2824 : :
2825 : : /*
2826 : : * Handle UPDATE message.
2827 : : *
2828 : : * TODO: FDW support
2829 : : */
2830 : : static void
2831 : 66188 : apply_handle_update(StringInfo s)
2832 : : {
2833 : : LogicalRepRelMapEntry *rel;
2834 : : LogicalRepRelId relid;
2835 : : UserContext ucxt;
2836 : : ApplyExecutionData *edata;
2837 : : EState *estate;
2838 : : LogicalRepTupleData oldtup;
2839 : : LogicalRepTupleData newtup;
2840 : : bool has_oldtup;
2841 : : TupleTableSlot *remoteslot;
2842 : : RTEPermissionInfo *target_perminfo;
2843 : : MemoryContext oldctx;
2844 : : bool run_as_owner;
2845 : :
2846 : : /*
2847 : : * Quick return if we are skipping data modification changes or handling
2848 : : * streamed transactions.
2849 : : */
2850 [ + + + + ]: 132373 : if (is_skipping_changes() ||
2851 : 66185 : handle_streamed_transaction(LOGICAL_REP_MSG_UPDATE, s))
2852 : 34223 : return;
2853 : :
2854 : 31965 : begin_replication_step();
2855 : :
2856 : 31964 : relid = logicalrep_read_update(s, &has_oldtup, &oldtup,
2857 : : &newtup);
2858 : 31964 : rel = logicalrep_rel_open(relid, RowExclusiveLock);
2859 [ - + ]: 31964 : if (!should_apply_changes_for_rel(rel))
2860 : : {
2861 : : /*
2862 : : * The relation can't become interesting in the middle of the
2863 : : * transaction so it's safe to unlock it.
2864 : : */
2865 : 0 : logicalrep_rel_close(rel, RowExclusiveLock);
2866 : 0 : end_replication_step();
2867 : 0 : return;
2868 : : }
2869 : :
2870 : : /* Set relation for error callback */
2871 : 31964 : remote_ctx.rel = rel;
2872 : :
2873 : : /* Check if we can do the update. */
2874 : 31964 : check_relation_updatable(rel);
2875 : :
2876 : : /*
2877 : : * Make sure that any user-supplied code runs as the table owner, unless
2878 : : * the user has opted out of that behavior.
2879 : : */
2880 : 31964 : run_as_owner = MySubscription->runasowner;
2881 [ + + ]: 31964 : if (!run_as_owner)
2882 : 31960 : SwitchToUntrustedUser(rel->localrel->rd_rel->relowner, &ucxt);
2883 : :
2884 : : /* Initialize the executor state. */
2885 : 31963 : edata = create_edata_for_relation(rel);
2886 : 31963 : estate = edata->estate;
2887 : 31963 : remoteslot = ExecInitExtraTupleSlot(estate,
2888 : 31963 : RelationGetDescr(rel->localrel),
2889 : : &TTSOpsVirtual);
2890 : :
2891 : : /*
2892 : : * Populate updatedCols so that per-column triggers can fire, and so
2893 : : * executor can correctly pass down indexUnchanged hint. This could
2894 : : * include more columns than were actually changed on the publisher
2895 : : * because the logical replication protocol doesn't contain that
2896 : : * information. But it would for example exclude columns that only exist
2897 : : * on the subscriber, since we are not touching those.
2898 : : */
2899 : 31963 : target_perminfo = list_nth(estate->es_rteperminfos, 0);
2900 [ + + ]: 159412 : for (int i = 0; i < remoteslot->tts_tupleDescriptor->natts; i++)
2901 : : {
2902 : 127449 : CompactAttribute *att = TupleDescCompactAttr(remoteslot->tts_tupleDescriptor, i);
2903 : 127449 : int remoteattnum = rel->attrmap->attnums[i];
2904 : :
2905 [ + + + + ]: 127449 : if (!att->attisdropped && remoteattnum >= 0)
2906 : : {
2907 [ - + ]: 68932 : if (remoteattnum >= newtup.ncols)
2908 [ # # ]: 0 : ereport(ERROR,
2909 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
2910 : : errmsg_plural("logical replication column %d not found in tuple: only %d column received",
2911 : : "logical replication column %d not found in tuple: only %d columns received",
2912 : : newtup.ncols,
2913 : : remoteattnum + 1, newtup.ncols)));
2914 : :
2915 [ + - ]: 68932 : if (newtup.colstatus[remoteattnum] != LOGICALREP_COLUMN_UNCHANGED)
2916 : 68932 : target_perminfo->updatedCols =
2917 : 68932 : bms_add_member(target_perminfo->updatedCols,
2918 : : i + 1 - FirstLowInvalidHeapAttributeNumber);
2919 : : }
2920 : : }
2921 : :
2922 : : /* Build the search tuple. */
2923 [ - + ]: 31963 : oldctx = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
2924 : 31963 : slot_store_data(remoteslot, rel,
2925 [ + + ]: 31963 : has_oldtup ? &oldtup : &newtup);
2926 : 31963 : MemoryContextSwitchTo(oldctx);
2927 : :
2928 : : /* For a partitioned table, apply update to correct partition. */
2929 [ + + ]: 31963 : if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
2930 : 13 : apply_handle_tuple_routing(edata,
2931 : : remoteslot, &newtup, CMD_UPDATE);
2932 : : else
2933 : 31950 : apply_handle_update_internal(edata, edata->targetRelInfo,
2934 : : remoteslot, &newtup, rel->localindexoid);
2935 : :
2936 : 31954 : finish_edata(edata);
2937 : :
2938 : : /* Reset relation for error callback */
2939 : 31954 : remote_ctx.rel = NULL;
2940 : :
2941 [ + + ]: 31954 : if (!run_as_owner)
2942 : 31952 : RestoreUserContext(&ucxt);
2943 : :
2944 : 31954 : logicalrep_rel_close(rel, NoLock);
2945 : :
2946 : 31954 : end_replication_step();
2947 : : }
2948 : :
2949 : : /*
2950 : : * Workhorse for apply_handle_update()
2951 : : * relinfo is for the relation we're actually updating in
2952 : : * (could be a child partition of edata->targetRelInfo)
2953 : : */
2954 : : static void
2955 : 31950 : apply_handle_update_internal(ApplyExecutionData *edata,
2956 : : ResultRelInfo *relinfo,
2957 : : TupleTableSlot *remoteslot,
2958 : : LogicalRepTupleData *newtup,
2959 : : Oid localindexoid)
2960 : : {
2961 : 31950 : EState *estate = edata->estate;
2962 : 31950 : LogicalRepRelMapEntry *relmapentry = edata->targetRel;
2963 : 31950 : Relation localrel = relinfo->ri_RelationDesc;
2964 : : EPQState epqstate;
2965 : 31950 : TupleTableSlot *localslot = NULL;
2966 : 31950 : ConflictTupleInfo conflicttuple = {0};
2967 : : bool found;
2968 : : MemoryContext oldctx;
2969 : :
2970 : 31950 : EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1, NIL);
2971 : 31950 : ExecOpenIndices(relinfo, false);
2972 : :
2973 : 31950 : found = FindReplTupleInLocalRel(edata, localrel,
2974 : : &relmapentry->remoterel,
2975 : : localindexoid,
2976 : : remoteslot, &localslot);
2977 : :
2978 : : /*
2979 : : * Tuple found.
2980 : : *
2981 : : * Note this will fail if there are other conflicting unique indexes.
2982 : : */
2983 [ + + ]: 31944 : if (found)
2984 : : {
2985 : : /*
2986 : : * Report the conflict if the tuple was modified by a different
2987 : : * origin.
2988 : : */
2989 [ + + ]: 31921 : if (GetTupleTransactionInfo(localslot, &conflicttuple.xmin,
2990 : 2 : &conflicttuple.origin, &conflicttuple.ts) &&
2991 [ + - ]: 2 : conflicttuple.origin != replorigin_xact_state.origin)
2992 : : {
2993 : : TupleTableSlot *newslot;
2994 : :
2995 : : /* Store the new tuple for conflict reporting */
2996 : 2 : newslot = table_slot_create(localrel, &estate->es_tupleTable);
2997 : 2 : slot_store_data(newslot, relmapentry, newtup);
2998 : :
2999 : 2 : conflicttuple.slot = localslot;
3000 : :
3001 : 2 : ReportApplyConflict(estate, relinfo, LOG, CT_UPDATE_ORIGIN_DIFFERS,
3002 : : remoteslot, newslot,
3003 : : list_make1(&conflicttuple));
3004 : : }
3005 : :
3006 : : /* Process and store remote tuple in the slot */
3007 [ + - ]: 31921 : oldctx = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
3008 : 31921 : slot_modify_data(remoteslot, localslot, relmapentry, newtup);
3009 : 31921 : MemoryContextSwitchTo(oldctx);
3010 : :
3011 : 31921 : EvalPlanQualSetSlot(&epqstate, remoteslot);
3012 : :
3013 : 31921 : InitConflictIndexes(relinfo);
3014 : :
3015 : : /* Do the actual update. */
3016 : 31921 : TargetPrivilegesCheck(relinfo->ri_RelationDesc, ACL_UPDATE);
3017 : 31921 : ExecSimpleRelationUpdate(relinfo, estate, &epqstate, localslot,
3018 : : remoteslot);
3019 : : }
3020 : : else
3021 : : {
3022 : : ConflictType type;
3023 : 23 : TupleTableSlot *newslot = localslot;
3024 : :
3025 : : /*
3026 : : * Detecting whether the tuple was recently deleted or never existed
3027 : : * is crucial to avoid misleading the user during conflict handling.
3028 : : */
3029 [ + + ]: 23 : if (FindDeletedTupleInLocalRel(localrel, localindexoid, remoteslot,
3030 : : &conflicttuple.xmin,
3031 : : &conflicttuple.origin,
3032 : 3 : &conflicttuple.ts) &&
3033 [ + - ]: 3 : conflicttuple.origin != replorigin_xact_state.origin)
3034 : 3 : type = CT_UPDATE_DELETED;
3035 : : else
3036 : 20 : type = CT_UPDATE_MISSING;
3037 : :
3038 : : /* Store the new tuple for conflict reporting */
3039 : 23 : slot_store_data(newslot, relmapentry, newtup);
3040 : :
3041 : : /*
3042 : : * The tuple to be updated could not be found or was deleted. Do
3043 : : * nothing except for emitting a log message.
3044 : : */
3045 : 23 : ReportApplyConflict(estate, relinfo, LOG, type, remoteslot, newslot,
3046 : : list_make1(&conflicttuple));
3047 : : }
3048 : :
3049 : : /* Cleanup. */
3050 : 31941 : ExecCloseIndices(relinfo);
3051 : 31941 : EvalPlanQualEnd(&epqstate);
3052 : 31941 : }
3053 : :
3054 : : /*
3055 : : * Handle DELETE message.
3056 : : *
3057 : : * TODO: FDW support
3058 : : */
3059 : : static void
3060 : 81942 : apply_handle_delete(StringInfo s)
3061 : : {
3062 : : LogicalRepRelMapEntry *rel;
3063 : : LogicalRepTupleData oldtup;
3064 : : LogicalRepRelId relid;
3065 : : UserContext ucxt;
3066 : : ApplyExecutionData *edata;
3067 : : EState *estate;
3068 : : TupleTableSlot *remoteslot;
3069 : : MemoryContext oldctx;
3070 : : bool run_as_owner;
3071 : :
3072 : : /*
3073 : : * Quick return if we are skipping data modification changes or handling
3074 : : * streamed transactions.
3075 : : */
3076 [ + - + + ]: 163884 : if (is_skipping_changes() ||
3077 : 81942 : handle_streamed_transaction(LOGICAL_REP_MSG_DELETE, s))
3078 : 41615 : return;
3079 : :
3080 : 40327 : begin_replication_step();
3081 : :
3082 : 40327 : relid = logicalrep_read_delete(s, &oldtup);
3083 : 40327 : rel = logicalrep_rel_open(relid, RowExclusiveLock);
3084 [ - + ]: 40327 : if (!should_apply_changes_for_rel(rel))
3085 : : {
3086 : : /*
3087 : : * The relation can't become interesting in the middle of the
3088 : : * transaction so it's safe to unlock it.
3089 : : */
3090 : 0 : logicalrep_rel_close(rel, RowExclusiveLock);
3091 : 0 : end_replication_step();
3092 : 0 : return;
3093 : : }
3094 : :
3095 : : /* Set relation for error callback */
3096 : 40327 : remote_ctx.rel = rel;
3097 : :
3098 : : /* Check if we can do the delete. */
3099 : 40327 : check_relation_updatable(rel);
3100 : :
3101 : : /*
3102 : : * Make sure that any user-supplied code runs as the table owner, unless
3103 : : * the user has opted out of that behavior.
3104 : : */
3105 : 40327 : run_as_owner = MySubscription->runasowner;
3106 [ + + ]: 40327 : if (!run_as_owner)
3107 : 40325 : SwitchToUntrustedUser(rel->localrel->rd_rel->relowner, &ucxt);
3108 : :
3109 : : /* Initialize the executor state. */
3110 : 40327 : edata = create_edata_for_relation(rel);
3111 : 40327 : estate = edata->estate;
3112 : 40327 : remoteslot = ExecInitExtraTupleSlot(estate,
3113 : 40327 : RelationGetDescr(rel->localrel),
3114 : : &TTSOpsVirtual);
3115 : :
3116 : : /* Build the search tuple. */
3117 [ - + ]: 40327 : oldctx = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
3118 : 40327 : slot_store_data(remoteslot, rel, &oldtup);
3119 : 40327 : MemoryContextSwitchTo(oldctx);
3120 : :
3121 : : /* For a partitioned table, apply delete to correct partition. */
3122 [ + + ]: 40327 : if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
3123 : 17 : apply_handle_tuple_routing(edata,
3124 : : remoteslot, NULL, CMD_DELETE);
3125 : : else
3126 : : {
3127 : 40310 : ResultRelInfo *relinfo = edata->targetRelInfo;
3128 : :
3129 : 40310 : ExecOpenIndices(relinfo, false);
3130 : 40310 : apply_handle_delete_internal(edata, relinfo,
3131 : : remoteslot, rel->localindexoid);
3132 : 40310 : ExecCloseIndices(relinfo);
3133 : : }
3134 : :
3135 : 40327 : finish_edata(edata);
3136 : :
3137 : : /* Reset relation for error callback */
3138 : 40327 : remote_ctx.rel = NULL;
3139 : :
3140 [ + + ]: 40327 : if (!run_as_owner)
3141 : 40325 : RestoreUserContext(&ucxt);
3142 : :
3143 : 40327 : logicalrep_rel_close(rel, NoLock);
3144 : :
3145 : 40327 : end_replication_step();
3146 : : }
3147 : :
3148 : : /*
3149 : : * Workhorse for apply_handle_delete()
3150 : : * relinfo is for the relation we're actually deleting from
3151 : : * (could be a child partition of edata->targetRelInfo)
3152 : : */
3153 : : static void
3154 : 40327 : apply_handle_delete_internal(ApplyExecutionData *edata,
3155 : : ResultRelInfo *relinfo,
3156 : : TupleTableSlot *remoteslot,
3157 : : Oid localindexoid)
3158 : : {
3159 : 40327 : EState *estate = edata->estate;
3160 : 40327 : Relation localrel = relinfo->ri_RelationDesc;
3161 : 40327 : LogicalRepRelation *remoterel = &edata->targetRel->remoterel;
3162 : : EPQState epqstate;
3163 : : TupleTableSlot *localslot;
3164 : 40327 : ConflictTupleInfo conflicttuple = {0};
3165 : : bool found;
3166 : :
3167 : 40327 : EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1, NIL);
3168 : :
3169 : : /* Caller should have opened indexes already. */
3170 : : Assert(relinfo->ri_IndexRelationDescs != NULL ||
3171 : : !localrel->rd_rel->relhasindex ||
3172 : : RelationGetIndexList(localrel) == NIL);
3173 : :
3174 : 40327 : found = FindReplTupleInLocalRel(edata, localrel, remoterel, localindexoid,
3175 : : remoteslot, &localslot);
3176 : :
3177 : : /* If found delete it. */
3178 [ + + ]: 40327 : if (found)
3179 : : {
3180 : : /*
3181 : : * Report the conflict if the tuple was modified by a different
3182 : : * origin.
3183 : : */
3184 [ + + ]: 40318 : if (GetTupleTransactionInfo(localslot, &conflicttuple.xmin,
3185 : 6 : &conflicttuple.origin, &conflicttuple.ts) &&
3186 [ + + ]: 6 : conflicttuple.origin != replorigin_xact_state.origin)
3187 : : {
3188 : 5 : conflicttuple.slot = localslot;
3189 : 5 : ReportApplyConflict(estate, relinfo, LOG, CT_DELETE_ORIGIN_DIFFERS,
3190 : : remoteslot, NULL,
3191 : : list_make1(&conflicttuple));
3192 : : }
3193 : :
3194 : 40318 : EvalPlanQualSetSlot(&epqstate, localslot);
3195 : :
3196 : : /* Do the actual delete. */
3197 : 40318 : TargetPrivilegesCheck(relinfo->ri_RelationDesc, ACL_DELETE);
3198 : 40318 : ExecSimpleRelationDelete(relinfo, estate, &epqstate, localslot);
3199 : : }
3200 : : else
3201 : : {
3202 : : /*
3203 : : * The tuple to be deleted could not be found. Do nothing except for
3204 : : * emitting a log message.
3205 : : */
3206 : 9 : ReportApplyConflict(estate, relinfo, LOG, CT_DELETE_MISSING,
3207 : : remoteslot, NULL, list_make1(&conflicttuple));
3208 : : }
3209 : :
3210 : : /* Cleanup. */
3211 : 40327 : EvalPlanQualEnd(&epqstate);
3212 : 40327 : }
3213 : :
3214 : : /*
3215 : : * Try to find a tuple received from the publication side (in 'remoteslot') in
3216 : : * the corresponding local relation using either replica identity index,
3217 : : * primary key, index or if needed, sequential scan.
3218 : : *
3219 : : * Local tuple, if found, is returned in '*localslot'.
3220 : : */
3221 : : static bool
3222 : 72290 : FindReplTupleInLocalRel(ApplyExecutionData *edata, Relation localrel,
3223 : : LogicalRepRelation *remoterel,
3224 : : Oid localidxoid,
3225 : : TupleTableSlot *remoteslot,
3226 : : TupleTableSlot **localslot)
3227 : : {
3228 : 72290 : EState *estate = edata->estate;
3229 : : bool found;
3230 : :
3231 : : /*
3232 : : * Regardless of the top-level operation, we're performing a read here, so
3233 : : * check for SELECT privileges.
3234 : : */
3235 : 72290 : TargetPrivilegesCheck(localrel, ACL_SELECT);
3236 : :
3237 : 72284 : *localslot = table_slot_create(localrel, &estate->es_tupleTable);
3238 : :
3239 : : Assert(OidIsValid(localidxoid) ||
3240 : : (remoterel->replident == REPLICA_IDENTITY_FULL));
3241 : :
3242 [ + + ]: 72284 : if (OidIsValid(localidxoid))
3243 : : {
3244 : : #ifdef USE_ASSERT_CHECKING
3245 : : Relation idxrel = index_open(localidxoid, AccessShareLock);
3246 : :
3247 : : /* Index must be PK, RI, or usable for REPLICA IDENTITY FULL tables */
3248 : : Assert(GetRelationIdentityOrPK(localrel) == localidxoid ||
3249 : : (remoterel->replident == REPLICA_IDENTITY_FULL &&
3250 : : IsIndexUsableForReplicaIdentityFull(idxrel,
3251 : : edata->targetRel->attrmap)));
3252 : : index_close(idxrel, AccessShareLock);
3253 : : #endif
3254 : :
3255 : 72130 : found = RelationFindReplTupleByIndex(localrel, localidxoid,
3256 : : LockTupleExclusive,
3257 : : remoteslot, *localslot);
3258 : : }
3259 : : else
3260 : 154 : found = RelationFindReplTupleSeq(localrel, LockTupleExclusive,
3261 : : remoteslot, *localslot);
3262 : :
3263 : 72284 : return found;
3264 : : }
3265 : :
3266 : : /*
3267 : : * Determine whether the index can reliably locate the deleted tuple in the
3268 : : * local relation.
3269 : : *
3270 : : * An index may exclude deleted tuples if it was re-indexed or re-created during
3271 : : * change application. Therefore, an index is considered usable only if the
3272 : : * conflict detection slot.xmin (conflict_detection_xmin) is greater than the
3273 : : * index tuple's xmin. This ensures that any tuples deleted prior to the index
3274 : : * creation or re-indexing are not relevant for conflict detection in the
3275 : : * current apply worker.
3276 : : *
3277 : : * Note that indexes may also be excluded if they were modified by other DDL
3278 : : * operations, such as ALTER INDEX. However, this is acceptable, as the
3279 : : * likelihood of such DDL changes coinciding with the need to scan dead
3280 : : * tuples for the update_deleted is low.
3281 : : */
3282 : : static bool
3283 : 1 : IsIndexUsableForFindingDeletedTuple(Oid localindexoid,
3284 : : TransactionId conflict_detection_xmin)
3285 : : {
3286 : : HeapTuple index_tuple;
3287 : : TransactionId index_xmin;
3288 : :
3289 : 1 : index_tuple = SearchSysCache1(INDEXRELID, ObjectIdGetDatum(localindexoid));
3290 : :
3291 [ - + ]: 1 : if (!HeapTupleIsValid(index_tuple)) /* should not happen */
3292 [ # # ]: 0 : elog(ERROR, "cache lookup failed for index %u", localindexoid);
3293 : :
3294 : : /*
3295 : : * No need to check for a frozen transaction ID, as
3296 : : * TransactionIdPrecedes() manages it internally, treating it as falling
3297 : : * behind the conflict_detection_xmin.
3298 : : */
3299 : 1 : index_xmin = HeapTupleHeaderGetXmin(index_tuple->t_data);
3300 : :
3301 : 1 : ReleaseSysCache(index_tuple);
3302 : :
3303 : 1 : return TransactionIdPrecedes(index_xmin, conflict_detection_xmin);
3304 : : }
3305 : :
3306 : : /*
3307 : : * Attempts to locate a deleted tuple in the local relation that matches the
3308 : : * values of the tuple received from the publication side (in 'remoteslot').
3309 : : * The search is performed using either the replica identity index, primary
3310 : : * key, other available index, or a sequential scan if necessary.
3311 : : *
3312 : : * Returns true if the deleted tuple is found. If found, the transaction ID,
3313 : : * origin, and commit timestamp of the deletion are stored in '*delete_xid',
3314 : : * '*delete_origin', and '*delete_time' respectively.
3315 : : */
3316 : : static bool
3317 : 25 : FindDeletedTupleInLocalRel(Relation localrel, Oid localidxoid,
3318 : : TupleTableSlot *remoteslot,
3319 : : TransactionId *delete_xid, ReplOriginId *delete_origin,
3320 : : TimestampTz *delete_time)
3321 : : {
3322 : : TransactionId oldestxmin;
3323 : :
3324 : : /*
3325 : : * Return false if either dead tuples are not retained or commit timestamp
3326 : : * data is not available.
3327 : : */
3328 [ + + - + ]: 25 : if (!MySubscription->retaindeadtuples || !track_commit_timestamp)
3329 : 22 : return false;
3330 : :
3331 : : /*
3332 : : * For conflict detection, we use the leader worker's
3333 : : * oldest_nonremovable_xid value instead of invoking
3334 : : * GetOldestNonRemovableTransactionId() or using the conflict detection
3335 : : * slot's xmin. The oldest_nonremovable_xid acts as a threshold to
3336 : : * identify tuples that were recently deleted. These deleted tuples are no
3337 : : * longer visible to concurrent transactions. However, if a remote update
3338 : : * matches such a tuple, we log an update_deleted conflict.
3339 : : *
3340 : : * While GetOldestNonRemovableTransactionId() and slot.xmin may return
3341 : : * transaction IDs older than oldest_nonremovable_xid, for our current
3342 : : * purpose, it is acceptable to treat tuples deleted by transactions prior
3343 : : * to oldest_nonremovable_xid as update_missing conflicts.
3344 : : */
3345 [ + - ]: 3 : if (am_leader_apply_worker())
3346 : : {
3347 : 3 : oldestxmin = MyLogicalRepWorker->oldest_nonremovable_xid;
3348 : : }
3349 : : else
3350 : : {
3351 : : LogicalRepWorker *leader;
3352 : :
3353 : : /*
3354 : : * Obtain the information from the leader apply worker as only the
3355 : : * leader manages oldest_nonremovable_xid (see
3356 : : * maybe_advance_nonremovable_xid() for details).
3357 : : */
3358 : 0 : LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
3359 : 0 : leader = logicalrep_worker_find(WORKERTYPE_APPLY,
3360 : 0 : MyLogicalRepWorker->subid, InvalidOid,
3361 : : false);
3362 [ # # ]: 0 : if (!leader)
3363 : : {
3364 [ # # ]: 0 : ereport(ERROR,
3365 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
3366 : : errmsg("could not detect conflict as the leader apply worker has exited")));
3367 : : }
3368 : :
3369 : 0 : SpinLockAcquire(&leader->relmutex);
3370 : 0 : oldestxmin = leader->oldest_nonremovable_xid;
3371 : 0 : SpinLockRelease(&leader->relmutex);
3372 : 0 : LWLockRelease(LogicalRepWorkerLock);
3373 : : }
3374 : :
3375 : : /*
3376 : : * Return false if the leader apply worker has stopped retaining
3377 : : * information for detecting conflicts. This implies that update_deleted
3378 : : * can no longer be reliably detected.
3379 : : */
3380 [ - + ]: 3 : if (!TransactionIdIsValid(oldestxmin))
3381 : 0 : return false;
3382 : :
3383 [ + + + - ]: 4 : if (OidIsValid(localidxoid) &&
3384 : 1 : IsIndexUsableForFindingDeletedTuple(localidxoid, oldestxmin))
3385 : 1 : return RelationFindDeletedTupleInfoByIndex(localrel, localidxoid,
3386 : : remoteslot, oldestxmin,
3387 : : delete_xid, delete_origin,
3388 : : delete_time);
3389 : : else
3390 : 2 : return RelationFindDeletedTupleInfoSeq(localrel, remoteslot,
3391 : : oldestxmin, delete_xid,
3392 : : delete_origin, delete_time);
3393 : : }
3394 : :
3395 : : /*
3396 : : * This handles insert, update, delete on a partitioned table.
3397 : : */
3398 : : static void
3399 : 111 : apply_handle_tuple_routing(ApplyExecutionData *edata,
3400 : : TupleTableSlot *remoteslot,
3401 : : LogicalRepTupleData *newtup,
3402 : : CmdType operation)
3403 : : {
3404 : 111 : EState *estate = edata->estate;
3405 : 111 : LogicalRepRelMapEntry *relmapentry = edata->targetRel;
3406 : 111 : ResultRelInfo *relinfo = edata->targetRelInfo;
3407 : 111 : Relation parentrel = relinfo->ri_RelationDesc;
3408 : : ModifyTableState *mtstate;
3409 : : PartitionTupleRouting *proute;
3410 : : ResultRelInfo *partrelinfo;
3411 : : Relation partrel;
3412 : : TupleTableSlot *remoteslot_part;
3413 : : TupleConversionMap *map;
3414 : : MemoryContext oldctx;
3415 : 111 : LogicalRepRelMapEntry *part_entry = NULL;
3416 : 111 : AttrMap *attrmap = NULL;
3417 : :
3418 : : /* ModifyTableState is needed for ExecFindPartition(). */
3419 : 111 : edata->mtstate = mtstate = makeNode(ModifyTableState);
3420 : 111 : mtstate->ps.plan = NULL;
3421 : 111 : mtstate->ps.state = estate;
3422 : 111 : mtstate->operation = operation;
3423 : 111 : mtstate->resultRelInfo = relinfo;
3424 : :
3425 : : /* ... as is PartitionTupleRouting. */
3426 : 111 : edata->proute = proute = ExecSetupPartitionTupleRouting(estate, parentrel);
3427 : :
3428 : : /*
3429 : : * Find the partition to which the "search tuple" belongs.
3430 : : */
3431 : : Assert(remoteslot != NULL);
3432 [ + - ]: 111 : oldctx = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
3433 : 111 : partrelinfo = ExecFindPartition(mtstate, relinfo, proute,
3434 : : remoteslot, estate);
3435 : : Assert(partrelinfo != NULL);
3436 : 111 : partrel = partrelinfo->ri_RelationDesc;
3437 : :
3438 : : /*
3439 : : * Check for supported relkind. We need this since partitions might be of
3440 : : * unsupported relkinds; and the set of partitions can change, so checking
3441 : : * at CREATE/ALTER SUBSCRIPTION would be insufficient.
3442 : : */
3443 : 111 : CheckSubscriptionRelkind(partrel->rd_rel->relkind,
3444 : 111 : relmapentry->remoterel.relkind,
3445 : 111 : get_namespace_name(RelationGetNamespace(partrel)),
3446 : 111 : RelationGetRelationName(partrel));
3447 : :
3448 : : /*
3449 : : * To perform any of the operations below, the tuple must match the
3450 : : * partition's rowtype. Convert if needed or just copy, using a dedicated
3451 : : * slot to store the tuple in any case.
3452 : : */
3453 : 111 : remoteslot_part = partrelinfo->ri_PartitionTupleSlot;
3454 [ + + ]: 111 : if (remoteslot_part == NULL)
3455 : 78 : remoteslot_part = table_slot_create(partrel, &estate->es_tupleTable);
3456 : 111 : map = ExecGetRootToChildMap(partrelinfo, estate);
3457 [ + + ]: 111 : if (map != NULL)
3458 : : {
3459 : 33 : attrmap = map->attrMap;
3460 : 33 : remoteslot_part = execute_attr_map_slot(attrmap, remoteslot,
3461 : : remoteslot_part);
3462 : : }
3463 : : else
3464 : : {
3465 : 78 : remoteslot_part = ExecCopySlot(remoteslot_part, remoteslot);
3466 : 78 : slot_getallattrs(remoteslot_part);
3467 : : }
3468 : 111 : MemoryContextSwitchTo(oldctx);
3469 : :
3470 : : /* Check if we can do the update or delete on the leaf partition. */
3471 [ + + + + ]: 111 : if (operation == CMD_UPDATE || operation == CMD_DELETE)
3472 : : {
3473 : 30 : part_entry = logicalrep_partition_open(relmapentry, partrel,
3474 : : attrmap);
3475 : 30 : check_relation_updatable(part_entry);
3476 : : }
3477 : :
3478 [ + + + - ]: 111 : switch (operation)
3479 : : {
3480 : 81 : case CMD_INSERT:
3481 : 81 : apply_handle_insert_internal(edata, partrelinfo,
3482 : : remoteslot_part);
3483 : 44 : break;
3484 : :
3485 : 17 : case CMD_DELETE:
3486 : 17 : apply_handle_delete_internal(edata, partrelinfo,
3487 : : remoteslot_part,
3488 : : part_entry->localindexoid);
3489 : 17 : break;
3490 : :
3491 : 13 : case CMD_UPDATE:
3492 : :
3493 : : /*
3494 : : * For UPDATE, depending on whether or not the updated tuple
3495 : : * satisfies the partition's constraint, perform a simple UPDATE
3496 : : * of the partition or move the updated tuple into a different
3497 : : * suitable partition.
3498 : : */
3499 : : {
3500 : : TupleTableSlot *localslot;
3501 : : ResultRelInfo *partrelinfo_new;
3502 : : Relation partrel_new;
3503 : : bool found;
3504 : : EPQState epqstate;
3505 : 13 : ConflictTupleInfo conflicttuple = {0};
3506 : :
3507 : : /* Get the matching local tuple from the partition. */
3508 : 13 : found = FindReplTupleInLocalRel(edata, partrel,
3509 : : &part_entry->remoterel,
3510 : : part_entry->localindexoid,
3511 : : remoteslot_part, &localslot);
3512 [ + + ]: 13 : if (!found)
3513 : : {
3514 : : ConflictType type;
3515 : 2 : TupleTableSlot *newslot = localslot;
3516 : :
3517 : : /*
3518 : : * Detecting whether the tuple was recently deleted or
3519 : : * never existed is crucial to avoid misleading the user
3520 : : * during conflict handling.
3521 : : */
3522 [ - + ]: 2 : if (FindDeletedTupleInLocalRel(partrel,
3523 : : part_entry->localindexoid,
3524 : : remoteslot_part,
3525 : : &conflicttuple.xmin,
3526 : : &conflicttuple.origin,
3527 : 0 : &conflicttuple.ts) &&
3528 [ # # ]: 0 : conflicttuple.origin != replorigin_xact_state.origin)
3529 : 0 : type = CT_UPDATE_DELETED;
3530 : : else
3531 : 2 : type = CT_UPDATE_MISSING;
3532 : :
3533 : : /* Store the new tuple for conflict reporting */
3534 : 2 : slot_store_data(newslot, part_entry, newtup);
3535 : :
3536 : : /*
3537 : : * The tuple to be updated could not be found or was
3538 : : * deleted. Do nothing except for emitting a log message.
3539 : : */
3540 : 2 : ReportApplyConflict(estate, partrelinfo, LOG,
3541 : : type, remoteslot_part, newslot,
3542 : : list_make1(&conflicttuple));
3543 : :
3544 : 2 : return;
3545 : : }
3546 : :
3547 : : /*
3548 : : * Report the conflict if the tuple was modified by a
3549 : : * different origin.
3550 : : */
3551 [ + + ]: 11 : if (GetTupleTransactionInfo(localslot, &conflicttuple.xmin,
3552 : : &conflicttuple.origin,
3553 : 1 : &conflicttuple.ts) &&
3554 [ + - ]: 1 : conflicttuple.origin != replorigin_xact_state.origin)
3555 : : {
3556 : : TupleTableSlot *newslot;
3557 : :
3558 : : /* Store the new tuple for conflict reporting */
3559 : 1 : newslot = table_slot_create(partrel, &estate->es_tupleTable);
3560 : 1 : slot_store_data(newslot, part_entry, newtup);
3561 : :
3562 : 1 : conflicttuple.slot = localslot;
3563 : :
3564 : 1 : ReportApplyConflict(estate, partrelinfo, LOG, CT_UPDATE_ORIGIN_DIFFERS,
3565 : : remoteslot_part, newslot,
3566 : : list_make1(&conflicttuple));
3567 : : }
3568 : :
3569 : : /*
3570 : : * Apply the update to the local tuple, putting the result in
3571 : : * remoteslot_part.
3572 : : */
3573 [ + - ]: 11 : oldctx = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
3574 : 11 : slot_modify_data(remoteslot_part, localslot, part_entry,
3575 : : newtup);
3576 : 11 : MemoryContextSwitchTo(oldctx);
3577 : :
3578 : 11 : EvalPlanQualInit(&epqstate, estate, NULL, NIL, -1, NIL);
3579 : :
3580 : : /*
3581 : : * Does the updated tuple still satisfy the current
3582 : : * partition's constraint?
3583 : : */
3584 [ + - + + ]: 22 : if (!partrel->rd_rel->relispartition ||
3585 : 11 : ExecPartitionCheck(partrelinfo, remoteslot_part, estate,
3586 : : false))
3587 : : {
3588 : : /*
3589 : : * Yes, so simply UPDATE the partition. We don't call
3590 : : * apply_handle_update_internal() here, which would
3591 : : * normally do the following work, to avoid repeating some
3592 : : * work already done above to find the local tuple in the
3593 : : * partition.
3594 : : */
3595 : 10 : InitConflictIndexes(partrelinfo);
3596 : :
3597 : 10 : EvalPlanQualSetSlot(&epqstate, remoteslot_part);
3598 : 10 : TargetPrivilegesCheck(partrelinfo->ri_RelationDesc,
3599 : : ACL_UPDATE);
3600 : 10 : ExecSimpleRelationUpdate(partrelinfo, estate, &epqstate,
3601 : : localslot, remoteslot_part);
3602 : : }
3603 : : else
3604 : : {
3605 : : /* Move the tuple into the new partition. */
3606 : :
3607 : : /*
3608 : : * New partition will be found using tuple routing, which
3609 : : * can only occur via the parent table. We might need to
3610 : : * convert the tuple to the parent's rowtype. Note that
3611 : : * this is the tuple found in the partition, not the
3612 : : * original search tuple received by this function.
3613 : : */
3614 [ + - ]: 1 : if (map)
3615 : : {
3616 : : TupleConversionMap *PartitionToRootMap =
3617 : 1 : convert_tuples_by_name(RelationGetDescr(partrel),
3618 : : RelationGetDescr(parentrel));
3619 : :
3620 : : remoteslot =
3621 : 1 : execute_attr_map_slot(PartitionToRootMap->attrMap,
3622 : : remoteslot_part, remoteslot);
3623 : : }
3624 : : else
3625 : : {
3626 : 0 : remoteslot = ExecCopySlot(remoteslot, remoteslot_part);
3627 : 0 : slot_getallattrs(remoteslot);
3628 : : }
3629 : :
3630 : : /* Find the new partition. */
3631 [ + - ]: 1 : oldctx = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
3632 : 1 : partrelinfo_new = ExecFindPartition(mtstate, relinfo,
3633 : : proute, remoteslot,
3634 : : estate);
3635 : 1 : MemoryContextSwitchTo(oldctx);
3636 : : Assert(partrelinfo_new != partrelinfo);
3637 : 1 : partrel_new = partrelinfo_new->ri_RelationDesc;
3638 : :
3639 : : /* Check that new partition also has supported relkind. */
3640 : 1 : CheckSubscriptionRelkind(partrel_new->rd_rel->relkind,
3641 : 1 : relmapentry->remoterel.relkind,
3642 : 1 : get_namespace_name(RelationGetNamespace(partrel_new)),
3643 : 1 : RelationGetRelationName(partrel_new));
3644 : :
3645 : : /* DELETE old tuple found in the old partition. */
3646 : 1 : EvalPlanQualSetSlot(&epqstate, localslot);
3647 : 1 : TargetPrivilegesCheck(partrelinfo->ri_RelationDesc, ACL_DELETE);
3648 : 1 : ExecSimpleRelationDelete(partrelinfo, estate, &epqstate, localslot);
3649 : :
3650 : : /* INSERT new tuple into the new partition. */
3651 : :
3652 : : /*
3653 : : * Convert the replacement tuple to match the destination
3654 : : * partition rowtype.
3655 : : */
3656 [ + - ]: 1 : oldctx = MemoryContextSwitchTo(GetPerTupleMemoryContext(estate));
3657 : 1 : remoteslot_part = partrelinfo_new->ri_PartitionTupleSlot;
3658 [ + - ]: 1 : if (remoteslot_part == NULL)
3659 : 1 : remoteslot_part = table_slot_create(partrel_new,
3660 : : &estate->es_tupleTable);
3661 : 1 : map = ExecGetRootToChildMap(partrelinfo_new, estate);
3662 [ - + ]: 1 : if (map != NULL)
3663 : : {
3664 : 0 : remoteslot_part = execute_attr_map_slot(map->attrMap,
3665 : : remoteslot,
3666 : : remoteslot_part);
3667 : : }
3668 : : else
3669 : : {
3670 : 1 : remoteslot_part = ExecCopySlot(remoteslot_part,
3671 : : remoteslot);
3672 : 1 : slot_getallattrs(remoteslot);
3673 : : }
3674 : 1 : MemoryContextSwitchTo(oldctx);
3675 : 1 : apply_handle_insert_internal(edata, partrelinfo_new,
3676 : : remoteslot_part);
3677 : : }
3678 : :
3679 : 11 : EvalPlanQualEnd(&epqstate);
3680 : : }
3681 : 11 : break;
3682 : :
3683 : 0 : default:
3684 [ # # ]: 0 : elog(ERROR, "unrecognized CmdType: %d", (int) operation);
3685 : : break;
3686 : : }
3687 : : }
3688 : :
3689 : : /*
3690 : : * Handle TRUNCATE message.
3691 : : *
3692 : : * TODO: FDW support
3693 : : */
3694 : : static void
3695 : 20 : apply_handle_truncate(StringInfo s)
3696 : : {
3697 : 20 : bool cascade = false;
3698 : 20 : bool restart_seqs = false;
3699 : 20 : List *remote_relids = NIL;
3700 : 20 : List *remote_rels = NIL;
3701 : 20 : List *rels = NIL;
3702 : 20 : List *part_rels = NIL;
3703 : 20 : List *relids = NIL;
3704 : 20 : List *relids_logged = NIL;
3705 : : ListCell *lc;
3706 : 20 : LOCKMODE lockmode = AccessExclusiveLock;
3707 : :
3708 : : /*
3709 : : * Quick return if we are skipping data modification changes or handling
3710 : : * streamed transactions.
3711 : : */
3712 [ + - - + ]: 40 : if (is_skipping_changes() ||
3713 : 20 : handle_streamed_transaction(LOGICAL_REP_MSG_TRUNCATE, s))
3714 : 0 : return;
3715 : :
3716 : 20 : begin_replication_step();
3717 : :
3718 : 20 : remote_relids = logicalrep_read_truncate(s, &cascade, &restart_seqs);
3719 : :
3720 [ + - + + : 49 : foreach(lc, remote_relids)
+ + ]
3721 : : {
3722 : 29 : LogicalRepRelId relid = lfirst_oid(lc);
3723 : : LogicalRepRelMapEntry *rel;
3724 : :
3725 : 29 : rel = logicalrep_rel_open(relid, lockmode);
3726 [ - + ]: 29 : if (!should_apply_changes_for_rel(rel))
3727 : : {
3728 : : /*
3729 : : * The relation can't become interesting in the middle of the
3730 : : * transaction so it's safe to unlock it.
3731 : : */
3732 : 0 : logicalrep_rel_close(rel, lockmode);
3733 : 0 : continue;
3734 : : }
3735 : :
3736 : 29 : remote_rels = lappend(remote_rels, rel);
3737 : 29 : TargetPrivilegesCheck(rel->localrel, ACL_TRUNCATE);
3738 : 29 : rels = lappend(rels, rel->localrel);
3739 : 29 : relids = lappend_oid(relids, rel->localreloid);
3740 [ + + - + : 29 : if (RelationIsLogicallyLogged(rel->localrel))
+ - - + -
- - - + -
+ - ]
3741 : 1 : relids_logged = lappend_oid(relids_logged, rel->localreloid);
3742 : :
3743 : : /*
3744 : : * Truncate partitions if we got a message to truncate a partitioned
3745 : : * table.
3746 : : */
3747 [ + + ]: 29 : if (rel->localrel->rd_rel->relkind == RELKIND_PARTITIONED_TABLE)
3748 : : {
3749 : : ListCell *child;
3750 : 4 : List *children = find_all_inheritors(rel->localreloid,
3751 : : lockmode,
3752 : : NULL);
3753 : :
3754 [ + - + + : 15 : foreach(child, children)
+ + ]
3755 : : {
3756 : 11 : Oid childrelid = lfirst_oid(child);
3757 : : Relation childrel;
3758 : :
3759 [ + + ]: 11 : if (list_member_oid(relids, childrelid))
3760 : 4 : continue;
3761 : :
3762 : : /* find_all_inheritors already got lock */
3763 : 7 : childrel = table_open(childrelid, NoLock);
3764 : :
3765 : : /*
3766 : : * Ignore temp tables of other backends. See similar code in
3767 : : * ExecuteTruncate().
3768 : : */
3769 [ - + - - ]: 7 : if (RELATION_IS_OTHER_TEMP(childrel))
3770 : : {
3771 : 0 : table_close(childrel, lockmode);
3772 : 0 : continue;
3773 : : }
3774 : :
3775 : 7 : TargetPrivilegesCheck(childrel, ACL_TRUNCATE);
3776 : 7 : rels = lappend(rels, childrel);
3777 : 7 : part_rels = lappend(part_rels, childrel);
3778 : 7 : relids = lappend_oid(relids, childrelid);
3779 : : /* Log this relation only if needed for logical decoding */
3780 [ + - - + : 7 : if (RelationIsLogicallyLogged(childrel))
- - - - -
- - - - -
- - ]
3781 : 0 : relids_logged = lappend_oid(relids_logged, childrelid);
3782 : : }
3783 : : }
3784 : : }
3785 : :
3786 : : /*
3787 : : * Even if we used CASCADE on the upstream primary we explicitly default
3788 : : * to replaying changes without further cascading. This might be later
3789 : : * changeable with a user specified option.
3790 : : *
3791 : : * MySubscription->runasowner tells us whether we want to execute
3792 : : * replication actions as the subscription owner; the last argument to
3793 : : * TruncateGuts tells it whether we want to switch to the table owner.
3794 : : * Those are exactly opposite conditions.
3795 : : */
3796 : 20 : ExecuteTruncateGuts(rels,
3797 : : relids,
3798 : : relids_logged,
3799 : : DROP_RESTRICT,
3800 : : restart_seqs,
3801 : 20 : !MySubscription->runasowner);
3802 [ + - + + : 49 : foreach(lc, remote_rels)
+ + ]
3803 : : {
3804 : 29 : LogicalRepRelMapEntry *rel = lfirst(lc);
3805 : :
3806 : 29 : logicalrep_rel_close(rel, NoLock);
3807 : : }
3808 [ + + + + : 27 : foreach(lc, part_rels)
+ + ]
3809 : : {
3810 : 7 : Relation rel = lfirst(lc);
3811 : :
3812 : 7 : table_close(rel, NoLock);
3813 : : }
3814 : :
3815 : 20 : end_replication_step();
3816 : : }
3817 : :
3818 : :
3819 : : /*
3820 : : * Logical replication protocol message dispatcher.
3821 : : */
3822 : : void
3823 : 358313 : apply_dispatch(StringInfo s)
3824 : : {
3825 : 358313 : LogicalRepMsgType action = pq_getmsgbyte(s);
3826 : : LogicalRepMsgType saved_command;
3827 : :
3828 : : /*
3829 : : * Set the current command being applied. Since this function can be
3830 : : * called recursively when applying spooled changes, save the current
3831 : : * command.
3832 : : */
3833 : 358313 : saved_command = remote_ctx.command;
3834 : 358313 : remote_ctx.command = action;
3835 : :
3836 [ + + + + : 358313 : switch (action)
+ + + + +
- + + + +
+ + + + +
- ]
3837 : : {
3838 : 557 : case LOGICAL_REP_MSG_BEGIN:
3839 : 557 : apply_handle_begin(s);
3840 : 557 : break;
3841 : :
3842 : 477 : case LOGICAL_REP_MSG_COMMIT:
3843 : 477 : apply_handle_commit(s);
3844 : 477 : break;
3845 : :
3846 : 206715 : case LOGICAL_REP_MSG_INSERT:
3847 : 206715 : apply_handle_insert(s);
3848 : 206645 : break;
3849 : :
3850 : 66188 : case LOGICAL_REP_MSG_UPDATE:
3851 : 66188 : apply_handle_update(s);
3852 : 66177 : break;
3853 : :
3854 : 81942 : case LOGICAL_REP_MSG_DELETE:
3855 : 81942 : apply_handle_delete(s);
3856 : 81942 : break;
3857 : :
3858 : 20 : case LOGICAL_REP_MSG_TRUNCATE:
3859 : 20 : apply_handle_truncate(s);
3860 : 20 : break;
3861 : :
3862 : 534 : case LOGICAL_REP_MSG_RELATION:
3863 : 534 : apply_handle_relation(s);
3864 : 534 : break;
3865 : :
3866 : 18 : case LOGICAL_REP_MSG_TYPE:
3867 : 18 : apply_handle_type(s);
3868 : 18 : break;
3869 : :
3870 : 7 : case LOGICAL_REP_MSG_ORIGIN:
3871 : 7 : apply_handle_origin(s);
3872 : 7 : break;
3873 : :
3874 : 0 : case LOGICAL_REP_MSG_MESSAGE:
3875 : :
3876 : : /*
3877 : : * Logical replication does not use generic logical messages yet.
3878 : : * Although, it could be used by other applications that use this
3879 : : * output plugin.
3880 : : */
3881 : 0 : break;
3882 : :
3883 : 841 : case LOGICAL_REP_MSG_STREAM_START:
3884 : 841 : apply_handle_stream_start(s);
3885 : 841 : break;
3886 : :
3887 : 840 : case LOGICAL_REP_MSG_STREAM_STOP:
3888 : 840 : apply_handle_stream_stop(s);
3889 : 838 : break;
3890 : :
3891 : 38 : case LOGICAL_REP_MSG_STREAM_ABORT:
3892 : 38 : apply_handle_stream_abort(s);
3893 : 38 : break;
3894 : :
3895 : 61 : case LOGICAL_REP_MSG_STREAM_COMMIT:
3896 : 61 : apply_handle_stream_commit(s);
3897 : 59 : break;
3898 : :
3899 : 17 : case LOGICAL_REP_MSG_BEGIN_PREPARE:
3900 : 17 : apply_handle_begin_prepare(s);
3901 : 17 : break;
3902 : :
3903 : 16 : case LOGICAL_REP_MSG_PREPARE:
3904 : 16 : apply_handle_prepare(s);
3905 : 15 : break;
3906 : :
3907 : 22 : case LOGICAL_REP_MSG_COMMIT_PREPARED:
3908 : 22 : apply_handle_commit_prepared(s);
3909 : 22 : break;
3910 : :
3911 : 5 : case LOGICAL_REP_MSG_ROLLBACK_PREPARED:
3912 : 5 : apply_handle_rollback_prepared(s);
3913 : 5 : break;
3914 : :
3915 : 15 : case LOGICAL_REP_MSG_STREAM_PREPARE:
3916 : 15 : apply_handle_stream_prepare(s);
3917 : 13 : break;
3918 : :
3919 : 0 : default:
3920 [ # # ]: 0 : ereport(ERROR,
3921 : : (errcode(ERRCODE_PROTOCOL_VIOLATION),
3922 : : errmsg("invalid logical replication message type \"??? (%d)\"", action)));
3923 : : }
3924 : :
3925 : : /* Reset the current command */
3926 : 358225 : remote_ctx.command = saved_command;
3927 : 358225 : }
3928 : :
3929 : : /*
3930 : : * Figure out which write/flush positions to report to the walsender process.
3931 : : *
3932 : : * We can't simply report back the last LSN the walsender sent us because the
3933 : : * local transaction might not yet be flushed to disk locally. Instead we
3934 : : * build a list that associates local with remote LSNs for every commit. When
3935 : : * reporting back the flush position to the sender we iterate that list and
3936 : : * check which entries on it are already locally flushed. Those we can report
3937 : : * as having been flushed.
3938 : : *
3939 : : * The have_pending_txes is true if there are outstanding transactions that
3940 : : * need to be flushed.
3941 : : */
3942 : : static void
3943 : 30982 : get_flush_position(XLogRecPtr *write, XLogRecPtr *flush,
3944 : : bool *have_pending_txes)
3945 : : {
3946 : : dlist_mutable_iter iter;
3947 : 30982 : XLogRecPtr local_flush = GetFlushRecPtr(NULL);
3948 : :
3949 : 30982 : *write = InvalidXLogRecPtr;
3950 : 30982 : *flush = InvalidXLogRecPtr;
3951 : :
3952 [ + - + + ]: 31529 : dlist_foreach_modify(iter, &lsn_mapping)
3953 : : {
3954 : 2950 : FlushPosition *pos =
3955 : : dlist_container(FlushPosition, node, iter.cur);
3956 : :
3957 : 2950 : *write = pos->remote_end;
3958 : :
3959 [ + + ]: 2950 : if (pos->local_end <= local_flush)
3960 : : {
3961 : 547 : *flush = pos->remote_end;
3962 : 547 : dlist_delete(iter.cur);
3963 : 547 : pfree(pos);
3964 : : }
3965 : : else
3966 : : {
3967 : : /*
3968 : : * Don't want to uselessly iterate over the rest of the list which
3969 : : * could potentially be long. Instead get the last element and
3970 : : * grab the write position from there.
3971 : : */
3972 : 2403 : pos = dlist_tail_element(FlushPosition, node,
3973 : : &lsn_mapping);
3974 : 2403 : *write = pos->remote_end;
3975 : 2403 : *have_pending_txes = true;
3976 : 2403 : return;
3977 : : }
3978 : : }
3979 : :
3980 : 28579 : *have_pending_txes = !dlist_is_empty(&lsn_mapping);
3981 : : }
3982 : :
3983 : : /*
3984 : : * Store current remote/local lsn pair in the tracking list.
3985 : : */
3986 : : void
3987 : 587 : store_flush_position(XLogRecPtr remote_lsn, XLogRecPtr local_lsn)
3988 : : {
3989 : : FlushPosition *flushpos;
3990 : :
3991 : : /*
3992 : : * Skip for parallel apply workers, because the lsn_mapping is maintained
3993 : : * by the leader apply worker.
3994 : : */
3995 [ + + ]: 587 : if (am_parallel_apply_worker())
3996 : 19 : return;
3997 : :
3998 : : /* Need to do this in permanent context */
3999 : 568 : MemoryContextSwitchTo(ApplyContext);
4000 : :
4001 : : /* Track commit lsn */
4002 : 568 : flushpos = palloc_object(FlushPosition);
4003 : 568 : flushpos->local_end = local_lsn;
4004 : 568 : flushpos->remote_end = remote_lsn;
4005 : :
4006 : 568 : dlist_push_tail(&lsn_mapping, &flushpos->node);
4007 : 568 : MemoryContextSwitchTo(ApplyMessageContext);
4008 : : }
4009 : :
4010 : :
4011 : : /* Update statistics of the worker. */
4012 : : static void
4013 : 214126 : UpdateWorkerStats(XLogRecPtr last_lsn, TimestampTz send_time, bool reply)
4014 : : {
4015 : 214126 : MyLogicalRepWorker->last_lsn = last_lsn;
4016 : 214126 : MyLogicalRepWorker->last_send_time = send_time;
4017 : 214126 : MyLogicalRepWorker->last_recv_time = GetCurrentTimestamp();
4018 [ + + ]: 214126 : if (reply)
4019 : : {
4020 : 1924 : MyLogicalRepWorker->reply_lsn = last_lsn;
4021 : 1924 : MyLogicalRepWorker->reply_time = send_time;
4022 : : }
4023 : 214126 : }
4024 : :
4025 : : /*
4026 : : * Apply main loop.
4027 : : */
4028 : : static void
4029 : 477 : LogicalRepApplyLoop(XLogRecPtr last_received)
4030 : : {
4031 : 477 : TimestampTz last_recv_timestamp = GetCurrentTimestamp();
4032 : 477 : bool ping_sent = false;
4033 : : TimeLineID tli;
4034 : : ErrorContextCallback errcallback;
4035 : 477 : RetainDeadTuplesData rdt_data = {0};
4036 : :
4037 : : /*
4038 : : * Init the ApplyMessageContext which we clean up after each replication
4039 : : * protocol message.
4040 : : */
4041 : 477 : ApplyMessageContext = AllocSetContextCreate(ApplyContext,
4042 : : "ApplyMessageContext",
4043 : : ALLOCSET_DEFAULT_SIZES);
4044 : :
4045 : : /*
4046 : : * This memory context is used for per-stream data when the streaming mode
4047 : : * is enabled. This context is reset on each stream stop.
4048 : : */
4049 : 477 : LogicalStreamingContext = AllocSetContextCreate(ApplyContext,
4050 : : "LogicalStreamingContext",
4051 : : ALLOCSET_DEFAULT_SIZES);
4052 : :
4053 : : /* mark as idle, before starting to loop */
4054 : 477 : pgstat_report_activity(STATE_IDLE, NULL);
4055 : :
4056 : : /*
4057 : : * Push apply error context callback. Fields will be filled while applying
4058 : : * a change.
4059 : : */
4060 : 477 : errcallback.callback = apply_error_callback;
4061 : 477 : errcallback.previous = error_context_stack;
4062 : 477 : error_context_stack = &errcallback;
4063 : 477 : apply_error_context_stack = error_context_stack;
4064 : :
4065 : : /* This outer loop iterates once per wait. */
4066 : : for (;;)
4067 : 28225 : {
4068 : 28702 : pgsocket fd = PGINVALID_SOCKET;
4069 : : int rc;
4070 : : int len;
4071 : 28702 : char *buf = NULL;
4072 : 28702 : bool endofstream = false;
4073 : : long wait_time;
4074 : :
4075 [ - + ]: 28702 : CHECK_FOR_INTERRUPTS();
4076 : :
4077 : 28702 : MemoryContextSwitchTo(ApplyMessageContext);
4078 : :
4079 : 28702 : len = walrcv_receive(LogRepWorkerWalRcvConn, &buf, &fd);
4080 : :
4081 [ + + ]: 28682 : if (len != 0)
4082 : : {
4083 : : /* Loop to process all available data (without blocking). */
4084 : : for (;;)
4085 : : {
4086 [ - + ]: 241385 : CHECK_FOR_INTERRUPTS();
4087 : :
4088 [ + + ]: 241385 : if (len == 0)
4089 : : {
4090 : 27244 : break;
4091 : : }
4092 [ + + ]: 214141 : else if (len < 0)
4093 : : {
4094 [ + - ]: 14 : ereport(LOG,
4095 : : (errmsg("data stream from publisher has ended")));
4096 : 14 : endofstream = true;
4097 : 14 : break;
4098 : : }
4099 : : else
4100 : : {
4101 : : int c;
4102 : : StringInfoData s;
4103 : :
4104 [ - + ]: 214127 : if (ConfigReloadPending)
4105 : : {
4106 : 0 : ConfigReloadPending = false;
4107 : 0 : ProcessConfigFile(PGC_SIGHUP);
4108 : : }
4109 : :
4110 : : /* Reset timeout. */
4111 : 214127 : last_recv_timestamp = GetCurrentTimestamp();
4112 : 214127 : ping_sent = false;
4113 : :
4114 : 214127 : rdt_data.last_recv_time = last_recv_timestamp;
4115 : :
4116 : : /* Ensure we are reading the data into our memory context. */
4117 : 214127 : MemoryContextSwitchTo(ApplyMessageContext);
4118 : :
4119 : 214127 : initReadOnlyStringInfo(&s, buf, len);
4120 : :
4121 : 214127 : c = pq_getmsgbyte(&s);
4122 : :
4123 [ + + ]: 214127 : if (c == PqReplMsg_WALData)
4124 : : {
4125 : : XLogRecPtr start_lsn;
4126 : : XLogRecPtr end_lsn;
4127 : : TimestampTz send_time;
4128 : :
4129 : 205810 : start_lsn = pq_getmsgint64(&s);
4130 : 205810 : end_lsn = pq_getmsgint64(&s);
4131 : 205810 : send_time = pq_getmsgint64(&s);
4132 : :
4133 [ + + ]: 205810 : if (last_received < start_lsn)
4134 : 167656 : last_received = start_lsn;
4135 : :
4136 [ - + ]: 205810 : if (last_received < end_lsn)
4137 : 0 : last_received = end_lsn;
4138 : :
4139 : 205810 : UpdateWorkerStats(last_received, send_time, false);
4140 : :
4141 : 205810 : apply_dispatch(&s);
4142 : :
4143 : 205726 : maybe_advance_nonremovable_xid(&rdt_data, false);
4144 : : }
4145 [ + + ]: 8317 : else if (c == PqReplMsg_Keepalive)
4146 : : {
4147 : : XLogRecPtr end_lsn;
4148 : : TimestampTz timestamp;
4149 : : bool reply_requested;
4150 : :
4151 : 1925 : end_lsn = pq_getmsgint64(&s);
4152 : 1925 : timestamp = pq_getmsgint64(&s);
4153 : 1925 : reply_requested = pq_getmsgbyte(&s);
4154 : :
4155 [ + + ]: 1925 : if (last_received < end_lsn)
4156 : 1087 : last_received = end_lsn;
4157 : :
4158 : 1925 : send_feedback(last_received, reply_requested, false);
4159 : :
4160 : 1924 : maybe_advance_nonremovable_xid(&rdt_data, false);
4161 : :
4162 : 1924 : UpdateWorkerStats(last_received, timestamp, true);
4163 : : }
4164 [ + - ]: 6392 : else if (c == PqReplMsg_PrimaryStatusUpdate)
4165 : : {
4166 : 6392 : rdt_data.remote_lsn = pq_getmsgint64(&s);
4167 : 6392 : rdt_data.remote_oldestxid = FullTransactionIdFromU64((uint64) pq_getmsgint64(&s));
4168 : 6392 : rdt_data.remote_nextxid = FullTransactionIdFromU64((uint64) pq_getmsgint64(&s));
4169 : 6392 : rdt_data.reply_time = pq_getmsgint64(&s);
4170 : :
4171 : : /*
4172 : : * This should never happen, see
4173 : : * ProcessStandbyPSRequestMessage. But if it happens
4174 : : * due to a bug, we don't want to proceed as it can
4175 : : * incorrectly advance oldest_nonremovable_xid.
4176 : : */
4177 [ - + ]: 6392 : if (!XLogRecPtrIsValid(rdt_data.remote_lsn))
4178 [ # # ]: 0 : elog(ERROR, "cannot get the latest WAL position from the publisher");
4179 : :
4180 : 6392 : maybe_advance_nonremovable_xid(&rdt_data, true);
4181 : :
4182 : 6392 : UpdateWorkerStats(last_received, rdt_data.reply_time, false);
4183 : : }
4184 : : /* other message types are purposefully ignored */
4185 : :
4186 : 214042 : MemoryContextReset(ApplyMessageContext);
4187 : : }
4188 : :
4189 : 214042 : len = walrcv_receive(LogRepWorkerWalRcvConn, &buf, &fd);
4190 : : }
4191 : : }
4192 : :
4193 : : /* confirm all writes so far */
4194 : 28596 : send_feedback(last_received, false, false);
4195 : :
4196 : : /* Reset the timestamp if no message was received */
4197 : 28596 : rdt_data.last_recv_time = 0;
4198 : :
4199 : 28596 : maybe_advance_nonremovable_xid(&rdt_data, false);
4200 : :
4201 [ + + + + ]: 28595 : if (!in_remote_transaction && !in_streamed_transaction)
4202 : : {
4203 : : /*
4204 : : * If we didn't get any transactions for a while there might be
4205 : : * unconsumed invalidation messages in the queue, consume them
4206 : : * now.
4207 : : */
4208 : 7830 : AcceptInvalidationMessages();
4209 : 7830 : maybe_reread_subscription();
4210 : :
4211 : : /*
4212 : : * Process any relations that are being synchronized in parallel
4213 : : * and any newly added tables or sequences.
4214 : : */
4215 : 7785 : ProcessSyncingRelations(last_received);
4216 : : }
4217 : :
4218 : : /* Cleanup the memory. */
4219 : 28343 : MemoryContextReset(ApplyMessageContext);
4220 : 28343 : MemoryContextSwitchTo(TopMemoryContext);
4221 : :
4222 : : /* Check if we need to exit the streaming loop. */
4223 [ + + ]: 28343 : if (endofstream)
4224 : 14 : break;
4225 : :
4226 : : /*
4227 : : * Wait for more data or latch. If we have unflushed transactions,
4228 : : * wake up after WalWriterDelay to see if they've been flushed yet (in
4229 : : * which case we should send a feedback message). Otherwise, there's
4230 : : * no particular urgency about waking up unless we get data or a
4231 : : * signal.
4232 : : */
4233 [ + + ]: 28329 : if (!dlist_is_empty(&lsn_mapping))
4234 : 1912 : wait_time = WalWriterDelay;
4235 : : else
4236 : 26417 : wait_time = NAPTIME_PER_CYCLE;
4237 : :
4238 : : /*
4239 : : * Ensure to wake up when it's possible to advance the non-removable
4240 : : * transaction ID, or when the retention duration may have exceeded
4241 : : * max_retention_duration.
4242 : : */
4243 [ + + ]: 28329 : if (MySubscription->retentionactive)
4244 : : {
4245 [ + + ]: 4884 : if (rdt_data.phase == RDT_GET_CANDIDATE_XID &&
4246 [ + - ]: 176 : rdt_data.xid_advance_interval)
4247 : 176 : wait_time = Min(wait_time, rdt_data.xid_advance_interval);
4248 [ + + ]: 4708 : else if (MySubscription->maxretention > 0)
4249 : 1 : wait_time = Min(wait_time, MySubscription->maxretention);
4250 : : }
4251 : :
4252 : 28329 : rc = WaitLatchOrSocket(MyLatch,
4253 : : WL_SOCKET_READABLE | WL_LATCH_SET |
4254 : : WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
4255 : : fd, wait_time,
4256 : : WAIT_EVENT_LOGICAL_APPLY_MAIN);
4257 : :
4258 [ + + ]: 28329 : if (rc & WL_LATCH_SET)
4259 : : {
4260 : 813 : ResetLatch(MyLatch);
4261 [ + + ]: 813 : CHECK_FOR_INTERRUPTS();
4262 : : }
4263 : :
4264 [ + + ]: 28225 : if (ConfigReloadPending)
4265 : : {
4266 : 12 : ConfigReloadPending = false;
4267 : 12 : ProcessConfigFile(PGC_SIGHUP);
4268 : : }
4269 : :
4270 [ + + ]: 28225 : if (rc & WL_TIMEOUT)
4271 : : {
4272 : : /*
4273 : : * We didn't receive anything new. If we haven't heard anything
4274 : : * from the server for more than wal_receiver_timeout / 2, ping
4275 : : * the server. Also, if it's been longer than
4276 : : * wal_receiver_status_interval since the last update we sent,
4277 : : * send a status update to the primary anyway, to report any
4278 : : * progress in applying WAL.
4279 : : */
4280 : 447 : bool requestReply = false;
4281 : :
4282 : : /*
4283 : : * Check if time since last receive from primary has reached the
4284 : : * configured limit.
4285 : : */
4286 [ + - ]: 447 : if (wal_receiver_timeout > 0)
4287 : : {
4288 : 447 : TimestampTz now = GetCurrentTimestamp();
4289 : : TimestampTz timeout;
4290 : :
4291 : 447 : timeout =
4292 : 447 : TimestampTzPlusMilliseconds(last_recv_timestamp,
4293 : : wal_receiver_timeout);
4294 : :
4295 [ - + ]: 447 : if (now >= timeout)
4296 [ # # ]: 0 : ereport(ERROR,
4297 : : (errcode(ERRCODE_CONNECTION_FAILURE),
4298 : : errmsg("terminating logical replication worker due to timeout")));
4299 : :
4300 : : /* Check to see if it's time for a ping. */
4301 [ + - ]: 447 : if (!ping_sent)
4302 : : {
4303 : 447 : timeout = TimestampTzPlusMilliseconds(last_recv_timestamp,
4304 : : (wal_receiver_timeout / 2));
4305 [ - + ]: 447 : if (now >= timeout)
4306 : : {
4307 : 0 : requestReply = true;
4308 : 0 : ping_sent = true;
4309 : : }
4310 : : }
4311 : : }
4312 : :
4313 : 447 : send_feedback(last_received, requestReply, requestReply);
4314 : :
4315 : 447 : maybe_advance_nonremovable_xid(&rdt_data, false);
4316 : :
4317 : : /*
4318 : : * Force reporting to ensure long idle periods don't lead to
4319 : : * arbitrarily delayed stats. Stats can only be reported outside
4320 : : * of (implicit or explicit) transactions. That shouldn't lead to
4321 : : * stats being delayed for long, because transactions are either
4322 : : * sent as a whole on commit or streamed. Streamed transactions
4323 : : * are spilled to disk and applied on commit.
4324 : : */
4325 [ + - ]: 447 : if (!IsTransactionState())
4326 : 447 : pgstat_report_stat(true);
4327 : : }
4328 : : }
4329 : :
4330 : : /* Pop the error context stack */
4331 : 14 : error_context_stack = errcallback.previous;
4332 : 14 : apply_error_context_stack = error_context_stack;
4333 : :
4334 : : /* All done */
4335 : 14 : walrcv_endstreaming(LogRepWorkerWalRcvConn, &tli);
4336 : 0 : }
4337 : :
4338 : : /*
4339 : : * Send a Standby Status Update message to server.
4340 : : *
4341 : : * 'recvpos' is the latest LSN we've received data to, force is set if we need
4342 : : * to send a response to avoid timeouts.
4343 : : */
4344 : : static void
4345 : 30968 : send_feedback(XLogRecPtr recvpos, bool force, bool requestReply)
4346 : : {
4347 : : static StringInfo reply_message = NULL;
4348 : : static TimestampTz send_time = 0;
4349 : :
4350 : : static XLogRecPtr last_recvpos = InvalidXLogRecPtr;
4351 : : static XLogRecPtr last_writepos = InvalidXLogRecPtr;
4352 : :
4353 : : XLogRecPtr writepos;
4354 : : XLogRecPtr flushpos;
4355 : : TimestampTz now;
4356 : : bool have_pending_txes;
4357 : :
4358 : : /*
4359 : : * If the user doesn't want status to be reported to the publisher, be
4360 : : * sure to exit before doing anything at all.
4361 : : */
4362 [ + + - + ]: 30968 : if (!force && wal_receiver_status_interval <= 0)
4363 : 12927 : return;
4364 : :
4365 : : /* It's legal to not pass a recvpos */
4366 [ - + ]: 30968 : if (recvpos < last_recvpos)
4367 : 0 : recvpos = last_recvpos;
4368 : :
4369 : 30968 : get_flush_position(&writepos, &flushpos, &have_pending_txes);
4370 : :
4371 : : /*
4372 : : * No outstanding transactions to flush, we can report the latest received
4373 : : * position. This is important for synchronous replication.
4374 : : */
4375 [ + + ]: 30968 : if (!have_pending_txes)
4376 : 28568 : flushpos = writepos = recvpos;
4377 : :
4378 [ - + ]: 30968 : if (writepos < last_writepos)
4379 : 0 : writepos = last_writepos;
4380 : :
4381 [ + + ]: 30968 : if (flushpos < last_flushpos)
4382 : 2339 : flushpos = last_flushpos;
4383 : :
4384 : 30968 : now = GetCurrentTimestamp();
4385 : :
4386 : : /* if we've already reported everything we're good */
4387 [ + + ]: 30968 : if (!force &&
4388 [ + + ]: 30965 : writepos == last_writepos &&
4389 [ + + ]: 13242 : flushpos == last_flushpos &&
4390 [ + + ]: 13021 : !TimestampDifferenceExceeds(send_time, now,
4391 : : wal_receiver_status_interval * 1000))
4392 : 12927 : return;
4393 : 18041 : send_time = now;
4394 : :
4395 [ + + ]: 18041 : if (!reply_message)
4396 : : {
4397 : 477 : MemoryContext oldctx = MemoryContextSwitchTo(ApplyContext);
4398 : :
4399 : 477 : reply_message = makeStringInfo();
4400 : 477 : MemoryContextSwitchTo(oldctx);
4401 : : }
4402 : : else
4403 : 17564 : resetStringInfo(reply_message);
4404 : :
4405 : 18041 : pq_sendbyte(reply_message, PqReplMsg_StandbyStatusUpdate);
4406 : 18041 : pq_sendint64(reply_message, recvpos); /* write */
4407 : 18041 : pq_sendint64(reply_message, flushpos); /* flush */
4408 : 18041 : pq_sendint64(reply_message, writepos); /* apply */
4409 : 18041 : pq_sendint64(reply_message, now); /* sendTime */
4410 : 18041 : pq_sendbyte(reply_message, requestReply); /* replyRequested */
4411 : :
4412 [ + + ]: 18041 : elog(DEBUG2, "sending feedback (force %d) to recv %X/%08X, write %X/%08X, flush %X/%08X",
4413 : : force,
4414 : : LSN_FORMAT_ARGS(recvpos),
4415 : : LSN_FORMAT_ARGS(writepos),
4416 : : LSN_FORMAT_ARGS(flushpos));
4417 : :
4418 : 18041 : walrcv_send(LogRepWorkerWalRcvConn,
4419 : : reply_message->data, reply_message->len);
4420 : :
4421 [ + + ]: 18040 : if (recvpos > last_recvpos)
4422 : 17721 : last_recvpos = recvpos;
4423 [ + + ]: 18040 : if (writepos > last_writepos)
4424 : 17725 : last_writepos = writepos;
4425 [ + + ]: 18040 : if (flushpos > last_flushpos)
4426 : 17557 : last_flushpos = flushpos;
4427 : : }
4428 : :
4429 : : /*
4430 : : * Attempt to advance the non-removable transaction ID.
4431 : : *
4432 : : * See comments atop worker.c for details.
4433 : : */
4434 : : static void
4435 : 243085 : maybe_advance_nonremovable_xid(RetainDeadTuplesData *rdt_data,
4436 : : bool status_received)
4437 : : {
4438 [ + + ]: 243085 : if (!can_advance_nonremovable_xid(rdt_data))
4439 : 231535 : return;
4440 : :
4441 : 11550 : process_rdt_phase_transition(rdt_data, status_received);
4442 : : }
4443 : :
4444 : : /*
4445 : : * Preliminary check to determine if advancing the non-removable transaction ID
4446 : : * is allowed.
4447 : : */
4448 : : static bool
4449 : 243085 : can_advance_nonremovable_xid(RetainDeadTuplesData *rdt_data)
4450 : : {
4451 : : /*
4452 : : * It is sufficient to manage non-removable transaction ID for a
4453 : : * subscription by the main apply worker to detect update_deleted reliably
4454 : : * even for table sync or parallel apply workers.
4455 : : */
4456 [ + + ]: 243085 : if (!am_leader_apply_worker())
4457 : 378 : return false;
4458 : :
4459 : : /* No need to advance if retaining dead tuples is not required */
4460 [ + + ]: 242707 : if (!MySubscription->retaindeadtuples)
4461 : 231157 : return false;
4462 : :
4463 : 11550 : return true;
4464 : : }
4465 : :
4466 : : /*
4467 : : * Process phase transitions during the non-removable transaction ID
4468 : : * advancement. See comments atop worker.c for details of the transition.
4469 : : */
4470 : : static void
4471 : 18040 : process_rdt_phase_transition(RetainDeadTuplesData *rdt_data,
4472 : : bool status_received)
4473 : : {
4474 [ + + + + : 18040 : switch (rdt_data->phase)
+ + - ]
4475 : : {
4476 : 452 : case RDT_GET_CANDIDATE_XID:
4477 : 452 : get_candidate_xid(rdt_data);
4478 : 452 : break;
4479 : 6393 : case RDT_REQUEST_PUBLISHER_STATUS:
4480 : 6393 : request_publisher_status(rdt_data);
4481 : 6393 : break;
4482 : 11088 : case RDT_WAIT_FOR_PUBLISHER_STATUS:
4483 : 11088 : wait_for_publisher_status(rdt_data, status_received);
4484 : 11088 : break;
4485 : 105 : case RDT_WAIT_FOR_LOCAL_FLUSH:
4486 : 105 : wait_for_local_flush(rdt_data);
4487 : 105 : break;
4488 : 1 : case RDT_STOP_CONFLICT_INFO_RETENTION:
4489 : 1 : stop_conflict_info_retention(rdt_data);
4490 : 1 : break;
4491 : 1 : case RDT_RESUME_CONFLICT_INFO_RETENTION:
4492 : 1 : resume_conflict_info_retention(rdt_data);
4493 : 0 : break;
4494 : : }
4495 : 18039 : }
4496 : :
4497 : : /*
4498 : : * Workhorse for the RDT_GET_CANDIDATE_XID phase.
4499 : : */
4500 : : static void
4501 : 452 : get_candidate_xid(RetainDeadTuplesData *rdt_data)
4502 : : {
4503 : : TransactionId oldest_running_xid;
4504 : : TimestampTz now;
4505 : :
4506 : : /*
4507 : : * Use last_recv_time when applying changes in the loop to avoid
4508 : : * unnecessary system time retrieval. If last_recv_time is not available,
4509 : : * obtain the current timestamp.
4510 : : */
4511 [ + + ]: 452 : now = rdt_data->last_recv_time ? rdt_data->last_recv_time : GetCurrentTimestamp();
4512 : :
4513 : : /*
4514 : : * Compute the candidate_xid and request the publisher status at most once
4515 : : * per xid_advance_interval. Refer to adjust_xid_advance_interval() for
4516 : : * details on how this value is dynamically adjusted. This is to avoid
4517 : : * using CPU and network resources without making much progress.
4518 : : */
4519 [ + + ]: 452 : if (!TimestampDifferenceExceeds(rdt_data->candidate_xid_time, now,
4520 : : rdt_data->xid_advance_interval))
4521 : 345 : return;
4522 : :
4523 : : /*
4524 : : * Immediately update the timer, even if the function returns later
4525 : : * without setting candidate_xid due to inactivity on the subscriber. This
4526 : : * avoids frequent calls to GetOldestActiveTransactionId.
4527 : : */
4528 : 107 : rdt_data->candidate_xid_time = now;
4529 : :
4530 : : /*
4531 : : * Consider transactions in the current database, as only dead tuples from
4532 : : * this database are required for conflict detection.
4533 : : */
4534 : 107 : oldest_running_xid = GetOldestActiveTransactionId(false, false);
4535 : :
4536 : : /*
4537 : : * Oldest active transaction ID (oldest_running_xid) can't be behind any
4538 : : * of its previously computed value.
4539 : : */
4540 : : Assert(TransactionIdPrecedesOrEquals(MyLogicalRepWorker->oldest_nonremovable_xid,
4541 : : oldest_running_xid));
4542 : :
4543 : : /* Return if the oldest_nonremovable_xid cannot be advanced */
4544 [ + + ]: 107 : if (TransactionIdEquals(MyLogicalRepWorker->oldest_nonremovable_xid,
4545 : : oldest_running_xid))
4546 : : {
4547 : 56 : adjust_xid_advance_interval(rdt_data, false);
4548 : 56 : return;
4549 : : }
4550 : :
4551 : 51 : adjust_xid_advance_interval(rdt_data, true);
4552 : :
4553 : 51 : rdt_data->candidate_xid = oldest_running_xid;
4554 : 51 : rdt_data->phase = RDT_REQUEST_PUBLISHER_STATUS;
4555 : :
4556 : : /* process the next phase */
4557 : 51 : process_rdt_phase_transition(rdt_data, false);
4558 : : }
4559 : :
4560 : : /*
4561 : : * Workhorse for the RDT_REQUEST_PUBLISHER_STATUS phase.
4562 : : */
4563 : : static void
4564 : 6393 : request_publisher_status(RetainDeadTuplesData *rdt_data)
4565 : : {
4566 : : static StringInfo request_message = NULL;
4567 : :
4568 [ + + ]: 6393 : if (!request_message)
4569 : : {
4570 : 12 : MemoryContext oldctx = MemoryContextSwitchTo(ApplyContext);
4571 : :
4572 : 12 : request_message = makeStringInfo();
4573 : 12 : MemoryContextSwitchTo(oldctx);
4574 : : }
4575 : : else
4576 : 6381 : resetStringInfo(request_message);
4577 : :
4578 : : /*
4579 : : * Send the current time to update the remote walsender's latest reply
4580 : : * message received time.
4581 : : */
4582 : 6393 : pq_sendbyte(request_message, PqReplMsg_PrimaryStatusRequest);
4583 : 6393 : pq_sendint64(request_message, GetCurrentTimestamp());
4584 : :
4585 [ + + ]: 6393 : elog(DEBUG2, "sending publisher status request message");
4586 : :
4587 : : /* Send a request for the publisher status */
4588 : 6393 : walrcv_send(LogRepWorkerWalRcvConn,
4589 : : request_message->data, request_message->len);
4590 : :
4591 : 6393 : rdt_data->phase = RDT_WAIT_FOR_PUBLISHER_STATUS;
4592 : :
4593 : : /*
4594 : : * Skip calling maybe_advance_nonremovable_xid() since further transition
4595 : : * is possible only once we receive the publisher status message.
4596 : : */
4597 : 6393 : }
4598 : :
4599 : : /*
4600 : : * Workhorse for the RDT_WAIT_FOR_PUBLISHER_STATUS phase.
4601 : : */
4602 : : static void
4603 : 11088 : wait_for_publisher_status(RetainDeadTuplesData *rdt_data,
4604 : : bool status_received)
4605 : : {
4606 : : /*
4607 : : * Return if we have requested but not yet received the publisher status.
4608 : : */
4609 [ + + ]: 11088 : if (!status_received)
4610 : 4696 : return;
4611 : :
4612 : : /*
4613 : : * We don't need to maintain oldest_nonremovable_xid if we decide to stop
4614 : : * retaining conflict information for this worker.
4615 : : */
4616 [ - + ]: 6392 : if (should_stop_conflict_info_retention(rdt_data))
4617 : : {
4618 : 0 : rdt_data->phase = RDT_STOP_CONFLICT_INFO_RETENTION;
4619 : 0 : return;
4620 : : }
4621 : :
4622 [ + + ]: 6392 : if (!FullTransactionIdIsValid(rdt_data->remote_wait_for))
4623 : 50 : rdt_data->remote_wait_for = rdt_data->remote_nextxid;
4624 : :
4625 : : /*
4626 : : * Check if all remote concurrent transactions that were active at the
4627 : : * first status request have now completed. If completed, proceed to the
4628 : : * next phase; otherwise, continue checking the publisher status until
4629 : : * these transactions finish.
4630 : : *
4631 : : * It's possible that transactions in the commit phase during the last
4632 : : * cycle have now finished committing, but remote_oldestxid remains older
4633 : : * than remote_wait_for. This can happen if some old transaction came in
4634 : : * the commit phase when we requested status in this cycle. We do not
4635 : : * handle this case explicitly as it's rare and the benefit doesn't
4636 : : * justify the required complexity. Tracking would require either caching
4637 : : * all xids at the publisher or sending them to subscribers. The condition
4638 : : * will resolve naturally once the remaining transactions are finished.
4639 : : *
4640 : : * Directly advancing the non-removable transaction ID is possible if
4641 : : * there are no activities on the publisher since the last advancement
4642 : : * cycle. However, it requires maintaining two fields, last_remote_nextxid
4643 : : * and last_remote_lsn, within the structure for comparison with the
4644 : : * current cycle's values. Considering the minimal cost of continuing in
4645 : : * RDT_WAIT_FOR_LOCAL_FLUSH without awaiting changes, we opted not to
4646 : : * advance the transaction ID here.
4647 : : */
4648 [ + + ]: 6392 : if (FullTransactionIdPrecedesOrEquals(rdt_data->remote_wait_for,
4649 : : rdt_data->remote_oldestxid))
4650 : 50 : rdt_data->phase = RDT_WAIT_FOR_LOCAL_FLUSH;
4651 : : else
4652 : 6342 : rdt_data->phase = RDT_REQUEST_PUBLISHER_STATUS;
4653 : :
4654 : : /* process the next phase */
4655 : 6392 : process_rdt_phase_transition(rdt_data, false);
4656 : : }
4657 : :
4658 : : /*
4659 : : * Workhorse for the RDT_WAIT_FOR_LOCAL_FLUSH phase.
4660 : : */
4661 : : static void
4662 : 105 : wait_for_local_flush(RetainDeadTuplesData *rdt_data)
4663 : : {
4664 : : Assert(XLogRecPtrIsValid(rdt_data->remote_lsn) &&
4665 : : TransactionIdIsValid(rdt_data->candidate_xid));
4666 : :
4667 : : /*
4668 : : * We expect the publisher and subscriber clocks to be in sync using time
4669 : : * sync service like NTP. Otherwise, we will advance this worker's
4670 : : * oldest_nonremovable_xid prematurely, leading to the removal of rows
4671 : : * required to detect update_deleted reliably. This check primarily
4672 : : * addresses scenarios where the publisher's clock falls behind; if the
4673 : : * publisher's clock is ahead, subsequent transactions will naturally bear
4674 : : * later commit timestamps, conforming to the design outlined atop
4675 : : * worker.c.
4676 : : *
4677 : : * XXX Consider waiting for the publisher's clock to catch up with the
4678 : : * subscriber's before proceeding to the next phase.
4679 : : */
4680 [ - + ]: 105 : if (TimestampDifferenceExceeds(rdt_data->reply_time,
4681 : : rdt_data->candidate_xid_time, 0))
4682 [ # # ]: 0 : ereport(ERROR,
4683 : : errmsg_internal("oldest_nonremovable_xid transaction ID could be advanced prematurely"),
4684 : : errdetail_internal("The clock on the publisher is behind that of the subscriber."));
4685 : :
4686 : : /*
4687 : : * Do not attempt to advance the non-removable transaction ID when table
4688 : : * sync is in progress. During this time, changes from a single
4689 : : * transaction may be applied by multiple table sync workers corresponding
4690 : : * to the target tables. So, it's necessary for all table sync workers to
4691 : : * apply and flush the corresponding changes before advancing the
4692 : : * transaction ID, otherwise, dead tuples that are still needed for
4693 : : * conflict detection in table sync workers could be removed prematurely.
4694 : : * However, confirming the apply and flush progress across all table sync
4695 : : * workers is complex and not worth the effort, so we simply return if not
4696 : : * all tables are in the READY state.
4697 : : *
4698 : : * Advancing the transaction ID is necessary even when no tables are
4699 : : * currently subscribed, to avoid retaining dead tuples unnecessarily.
4700 : : * While it might seem safe to skip all phases and directly assign
4701 : : * candidate_xid to oldest_nonremovable_xid during the
4702 : : * RDT_GET_CANDIDATE_XID phase in such cases, this is unsafe. If users
4703 : : * concurrently add tables to the subscription, the apply worker may not
4704 : : * process invalidations in time. Consequently,
4705 : : * HasSubscriptionTablesCached() might miss the new tables, leading to
4706 : : * premature advancement of oldest_nonremovable_xid.
4707 : : *
4708 : : * Performing the check during RDT_WAIT_FOR_LOCAL_FLUSH is safe, as
4709 : : * invalidations are guaranteed to be processed before applying changes
4710 : : * from newly added tables while waiting for the local flush to reach
4711 : : * remote_lsn.
4712 : : *
4713 : : * Additionally, even if we check for subscription tables during
4714 : : * RDT_GET_CANDIDATE_XID, they might be dropped before reaching
4715 : : * RDT_WAIT_FOR_LOCAL_FLUSH. Therefore, it's still necessary to verify
4716 : : * subscription tables at this stage to prevent unnecessary tuple
4717 : : * retention.
4718 : : */
4719 [ + + + + ]: 105 : if (HasSubscriptionTablesCached() && !AllTablesyncsReady())
4720 : : {
4721 : : TimestampTz now;
4722 : :
4723 : 10 : now = rdt_data->last_recv_time
4724 [ + + ]: 5 : ? rdt_data->last_recv_time : GetCurrentTimestamp();
4725 : :
4726 : : /*
4727 : : * Record the time spent waiting for table sync, it is needed for the
4728 : : * timeout check in should_stop_conflict_info_retention().
4729 : : */
4730 : 5 : rdt_data->table_sync_wait_time =
4731 : 5 : TimestampDifferenceMilliseconds(rdt_data->candidate_xid_time, now);
4732 : :
4733 : 5 : return;
4734 : : }
4735 : :
4736 : : /*
4737 : : * We don't need to maintain oldest_nonremovable_xid if we decide to stop
4738 : : * retaining conflict information for this worker.
4739 : : */
4740 [ + + ]: 100 : if (should_stop_conflict_info_retention(rdt_data))
4741 : : {
4742 : 1 : rdt_data->phase = RDT_STOP_CONFLICT_INFO_RETENTION;
4743 : 1 : return;
4744 : : }
4745 : :
4746 : : /*
4747 : : * Update and check the remote flush position if we are applying changes
4748 : : * in a loop. This is done at most once per WalWriterDelay to avoid
4749 : : * performing costly operations in get_flush_position() too frequently
4750 : : * during change application.
4751 : : */
4752 [ + + + + : 129 : if (last_flushpos < rdt_data->remote_lsn && rdt_data->last_recv_time &&
+ + ]
4753 : 30 : TimestampDifferenceExceeds(rdt_data->flushpos_update_time,
4754 : : rdt_data->last_recv_time, WalWriterDelay))
4755 : : {
4756 : : XLogRecPtr writepos;
4757 : : XLogRecPtr flushpos;
4758 : : bool have_pending_txes;
4759 : :
4760 : : /* Fetch the latest remote flush position */
4761 : 14 : get_flush_position(&writepos, &flushpos, &have_pending_txes);
4762 : :
4763 [ - + ]: 14 : if (flushpos > last_flushpos)
4764 : 0 : last_flushpos = flushpos;
4765 : :
4766 : 14 : rdt_data->flushpos_update_time = rdt_data->last_recv_time;
4767 : : }
4768 : :
4769 : : /* Return to wait for the changes to be applied */
4770 [ + + ]: 99 : if (last_flushpos < rdt_data->remote_lsn)
4771 : 51 : return;
4772 : :
4773 : : /*
4774 : : * Reaching this point implies should_stop_conflict_info_retention()
4775 : : * returned false earlier, meaning that the most recent duration for
4776 : : * advancing the non-removable transaction ID is within the
4777 : : * max_retention_duration or max_retention_duration is set to 0.
4778 : : *
4779 : : * Therefore, if conflict info retention was previously stopped due to a
4780 : : * timeout, it is now safe to resume retention.
4781 : : */
4782 [ + + ]: 48 : if (!MySubscription->retentionactive)
4783 : : {
4784 : 1 : rdt_data->phase = RDT_RESUME_CONFLICT_INFO_RETENTION;
4785 : 1 : return;
4786 : : }
4787 : :
4788 : : /*
4789 : : * Reaching here means the remote WAL position has been received, and all
4790 : : * transactions up to that position on the publisher have been applied and
4791 : : * flushed locally. So, we can advance the non-removable transaction ID.
4792 : : */
4793 : 47 : SpinLockAcquire(&MyLogicalRepWorker->relmutex);
4794 : 47 : MyLogicalRepWorker->oldest_nonremovable_xid = rdt_data->candidate_xid;
4795 : 47 : SpinLockRelease(&MyLogicalRepWorker->relmutex);
4796 : :
4797 [ + + ]: 47 : elog(DEBUG2, "confirmed flush up to remote lsn %X/%08X: new oldest_nonremovable_xid %u",
4798 : : LSN_FORMAT_ARGS(rdt_data->remote_lsn),
4799 : : rdt_data->candidate_xid);
4800 : :
4801 : : /* Notify launcher to update the xmin of the conflict slot */
4802 : 47 : ApplyLauncherWakeup();
4803 : :
4804 : 47 : reset_retention_data_fields(rdt_data);
4805 : :
4806 : : /* process the next phase */
4807 : 47 : process_rdt_phase_transition(rdt_data, false);
4808 : : }
4809 : :
4810 : : /*
4811 : : * Check whether conflict information retention should be stopped due to
4812 : : * exceeding the maximum wait time (max_retention_duration).
4813 : : *
4814 : : * If retention should be stopped, return true. Otherwise, return false.
4815 : : */
4816 : : static bool
4817 : 6492 : should_stop_conflict_info_retention(RetainDeadTuplesData *rdt_data)
4818 : : {
4819 : : TimestampTz now;
4820 : :
4821 : : Assert(TransactionIdIsValid(rdt_data->candidate_xid));
4822 : : Assert(rdt_data->phase == RDT_WAIT_FOR_PUBLISHER_STATUS ||
4823 : : rdt_data->phase == RDT_WAIT_FOR_LOCAL_FLUSH);
4824 : :
4825 [ + + ]: 6492 : if (!MySubscription->maxretention)
4826 : 6491 : return false;
4827 : :
4828 : : /*
4829 : : * Use last_recv_time when applying changes in the loop to avoid
4830 : : * unnecessary system time retrieval. If last_recv_time is not available,
4831 : : * obtain the current timestamp.
4832 : : */
4833 [ - + ]: 1 : now = rdt_data->last_recv_time ? rdt_data->last_recv_time : GetCurrentTimestamp();
4834 : :
4835 : : /*
4836 : : * Return early if the wait time has not exceeded the configured maximum
4837 : : * (max_retention_duration). Time spent waiting for table synchronization
4838 : : * is excluded from this calculation, as it occurs infrequently.
4839 : : */
4840 [ - + ]: 1 : if (!TimestampDifferenceExceeds(rdt_data->candidate_xid_time, now,
4841 : 1 : MySubscription->maxretention +
4842 : 1 : rdt_data->table_sync_wait_time))
4843 : 0 : return false;
4844 : :
4845 : 1 : return true;
4846 : : }
4847 : :
4848 : : /*
4849 : : * Workhorse for the RDT_STOP_CONFLICT_INFO_RETENTION phase.
4850 : : */
4851 : : static void
4852 : 1 : stop_conflict_info_retention(RetainDeadTuplesData *rdt_data)
4853 : : {
4854 : : /* Stop retention if not yet */
4855 [ + - ]: 1 : if (MySubscription->retentionactive)
4856 : : {
4857 : : /*
4858 : : * If the retention status cannot be updated (e.g., due to active
4859 : : * transaction), skip further processing to avoid inconsistent
4860 : : * retention behavior.
4861 : : */
4862 [ - + ]: 1 : if (!update_retention_status(false))
4863 : 0 : return;
4864 : :
4865 : 1 : SpinLockAcquire(&MyLogicalRepWorker->relmutex);
4866 : 1 : MyLogicalRepWorker->oldest_nonremovable_xid = InvalidTransactionId;
4867 : 1 : SpinLockRelease(&MyLogicalRepWorker->relmutex);
4868 : :
4869 [ + - ]: 1 : ereport(LOG,
4870 : : errmsg("logical replication worker for subscription \"%s\" has stopped retaining the information for detecting conflicts",
4871 : : MySubscription->name),
4872 : : errdetail("Retention is stopped because the apply process has not caught up with the publisher within the configured max_retention_duration."));
4873 : : }
4874 : :
4875 : : Assert(!TransactionIdIsValid(MyLogicalRepWorker->oldest_nonremovable_xid));
4876 : :
4877 : : /*
4878 : : * If retention has been stopped, reset to the initial phase to retry
4879 : : * resuming retention. This reset is required to recalculate the current
4880 : : * wait time and resume retention if the time falls within
4881 : : * max_retention_duration.
4882 : : */
4883 : 1 : reset_retention_data_fields(rdt_data);
4884 : : }
4885 : :
4886 : : /*
4887 : : * Workhorse for the RDT_RESUME_CONFLICT_INFO_RETENTION phase.
4888 : : */
4889 : : static void
4890 : 1 : resume_conflict_info_retention(RetainDeadTuplesData *rdt_data)
4891 : : {
4892 : : /* We can't resume retention without updating retention status. */
4893 [ - + ]: 1 : if (!update_retention_status(true))
4894 : 0 : return;
4895 : :
4896 [ + - - + ]: 1 : ereport(LOG,
4897 : : errmsg("logical replication worker for subscription \"%s\" will resume retaining the information for detecting conflicts",
4898 : : MySubscription->name),
4899 : : MySubscription->maxretention
4900 : : ? errdetail("Retention is re-enabled because the apply process has caught up with the publisher within the configured max_retention_duration.")
4901 : : : errdetail("Retention is re-enabled because max_retention_duration has been set to unlimited."));
4902 : :
4903 : : /*
4904 : : * Restart the worker to let the launcher initialize
4905 : : * oldest_nonremovable_xid at startup.
4906 : : *
4907 : : * While it's technically possible to derive this value on-the-fly using
4908 : : * the conflict detection slot's xmin, doing so risks a race condition:
4909 : : * the launcher might clean slot.xmin just after retention resumes. This
4910 : : * would make oldest_nonremovable_xid unreliable, especially during xid
4911 : : * wraparound.
4912 : : *
4913 : : * Although this can be prevented by introducing heavy weight locking, the
4914 : : * complexity it will bring doesn't seem worthwhile given how rarely
4915 : : * retention is resumed.
4916 : : */
4917 : 1 : apply_worker_exit();
4918 : : }
4919 : :
4920 : : /*
4921 : : * Updates pg_subscription.subretentionactive to the given value within a
4922 : : * new transaction.
4923 : : *
4924 : : * If already inside an active transaction, skips the update and returns
4925 : : * false.
4926 : : *
4927 : : * Returns true if the update is successfully performed.
4928 : : */
4929 : : static bool
4930 : 2 : update_retention_status(bool active)
4931 : : {
4932 : : /*
4933 : : * Do not update the catalog during an active transaction. The transaction
4934 : : * may be started during change application, leading to a possible
4935 : : * rollback of catalog updates if the application fails subsequently.
4936 : : */
4937 [ - + ]: 2 : if (IsTransactionState())
4938 : 0 : return false;
4939 : :
4940 : 2 : StartTransactionCommand();
4941 : :
4942 : : /*
4943 : : * Updating pg_subscription might involve TOAST table access, so ensure we
4944 : : * have a valid snapshot.
4945 : : */
4946 : 2 : PushActiveSnapshot(GetTransactionSnapshot());
4947 : :
4948 : : /* Update pg_subscription.subretentionactive */
4949 : 2 : UpdateDeadTupleRetentionStatus(MySubscription->oid, active);
4950 : :
4951 : 2 : PopActiveSnapshot();
4952 : 2 : CommitTransactionCommand();
4953 : :
4954 : : /* Notify launcher to update the conflict slot */
4955 : 2 : ApplyLauncherWakeup();
4956 : :
4957 : 2 : MySubscription->retentionactive = active;
4958 : :
4959 : 2 : return true;
4960 : : }
4961 : :
4962 : : /*
4963 : : * Reset all data fields of RetainDeadTuplesData except those used to
4964 : : * determine the timing for the next round of transaction ID advancement. We
4965 : : * can even use flushpos_update_time in the next round to decide whether to get
4966 : : * the latest flush position.
4967 : : */
4968 : : static void
4969 : 48 : reset_retention_data_fields(RetainDeadTuplesData *rdt_data)
4970 : : {
4971 : 48 : rdt_data->phase = RDT_GET_CANDIDATE_XID;
4972 : 48 : rdt_data->remote_lsn = InvalidXLogRecPtr;
4973 : 48 : rdt_data->remote_oldestxid = InvalidFullTransactionId;
4974 : 48 : rdt_data->remote_nextxid = InvalidFullTransactionId;
4975 : 48 : rdt_data->reply_time = 0;
4976 : 48 : rdt_data->remote_wait_for = InvalidFullTransactionId;
4977 : 48 : rdt_data->candidate_xid = InvalidTransactionId;
4978 : 48 : rdt_data->table_sync_wait_time = 0;
4979 : 48 : }
4980 : :
4981 : : /*
4982 : : * Adjust the interval for advancing non-removable transaction IDs.
4983 : : *
4984 : : * If there is no activity on the node or retention has been stopped, we
4985 : : * progressively double the interval used to advance non-removable transaction
4986 : : * ID. This helps conserve CPU and network resources when there's little benefit
4987 : : * to frequent updates.
4988 : : *
4989 : : * The interval is capped by the lowest of the following:
4990 : : * - wal_receiver_status_interval (if set and retention is active),
4991 : : * - a default maximum of 3 minutes,
4992 : : * - max_retention_duration (if retention is active).
4993 : : *
4994 : : * This ensures the interval never exceeds the retention boundary, even if other
4995 : : * limits are higher. Once activity resumes on the node and the retention is
4996 : : * active, the interval is reset to lesser of 100ms and max_retention_duration,
4997 : : * allowing timely advancement of non-removable transaction ID.
4998 : : *
4999 : : * XXX The use of wal_receiver_status_interval is a bit arbitrary so we can
5000 : : * consider the other interval or a separate GUC if the need arises.
5001 : : */
5002 : : static void
5003 : 107 : adjust_xid_advance_interval(RetainDeadTuplesData *rdt_data, bool new_xid_found)
5004 : : {
5005 [ + + + + ]: 107 : if (rdt_data->xid_advance_interval && !new_xid_found)
5006 : 51 : {
5007 : 51 : int max_interval = wal_receiver_status_interval
5008 : 102 : ? wal_receiver_status_interval * 1000
5009 [ + - ]: 51 : : MAX_XID_ADVANCE_INTERVAL;
5010 : :
5011 : : /*
5012 : : * No new transaction ID has been assigned since the last check, so
5013 : : * double the interval, but not beyond the maximum allowable value.
5014 : : */
5015 : 51 : rdt_data->xid_advance_interval = Min(rdt_data->xid_advance_interval * 2,
5016 : : max_interval);
5017 : : }
5018 [ + + ]: 56 : else if (rdt_data->xid_advance_interval &&
5019 [ + + ]: 43 : !MySubscription->retentionactive)
5020 : : {
5021 : : /*
5022 : : * Retention has been stopped, so double the interval-capped at a
5023 : : * maximum of 3 minutes. The wal_receiver_status_interval is
5024 : : * intentionally not used as an upper bound, since the likelihood of
5025 : : * retention resuming is lower than that of general activity resuming.
5026 : : */
5027 : 1 : rdt_data->xid_advance_interval = Min(rdt_data->xid_advance_interval * 2,
5028 : : MAX_XID_ADVANCE_INTERVAL);
5029 : : }
5030 : : else
5031 : : {
5032 : : /*
5033 : : * A new transaction ID was found or the interval is not yet
5034 : : * initialized, so set the interval to the minimum value.
5035 : : */
5036 : 55 : rdt_data->xid_advance_interval = MIN_XID_ADVANCE_INTERVAL;
5037 : : }
5038 : :
5039 : : /*
5040 : : * Ensure the wait time remains within the maximum retention time limit
5041 : : * when retention is active. Skip this cap when maxretention is zero,
5042 : : * which means unlimited retention (no timeout).
5043 : : */
5044 [ + + - + ]: 107 : if (MySubscription->retentionactive && MySubscription->maxretention > 0)
5045 : 0 : rdt_data->xid_advance_interval = Min(rdt_data->xid_advance_interval,
5046 : : MySubscription->maxretention);
5047 : 107 : }
5048 : :
5049 : : /*
5050 : : * Exit routine for apply workers due to subscription parameter changes.
5051 : : */
5052 : : static void
5053 : 49 : apply_worker_exit(void)
5054 : : {
5055 [ - + ]: 49 : if (am_parallel_apply_worker())
5056 : : {
5057 : : /*
5058 : : * Don't stop the parallel apply worker as the leader will detect the
5059 : : * subscription parameter change and restart logical replication later
5060 : : * anyway. This also prevents the leader from reporting errors when
5061 : : * trying to communicate with a stopped parallel apply worker, which
5062 : : * would accidentally disable subscriptions if disable_on_error was
5063 : : * set.
5064 : : */
5065 : 0 : return;
5066 : : }
5067 : :
5068 : : /*
5069 : : * Reset the last-start time for this apply worker so that the launcher
5070 : : * will restart it without waiting for wal_retrieve_retry_interval if the
5071 : : * subscription is still active, and so that we won't leak that hash table
5072 : : * entry if it isn't.
5073 : : */
5074 [ + - ]: 49 : if (am_leader_apply_worker())
5075 : 49 : ApplyLauncherForgetWorkerStartTime(MyLogicalRepWorker->subid);
5076 : :
5077 : 49 : proc_exit(0);
5078 : : }
5079 : :
5080 : : /*
5081 : : * Reread subscription info if needed.
5082 : : *
5083 : : * For significant changes, we react by exiting the current process; a new
5084 : : * one will be launched afterwards if needed.
5085 : : */
5086 : : void
5087 : 8953 : maybe_reread_subscription(void)
5088 : : {
5089 : : Subscription *newsub;
5090 : : char *old_conninfo;
5091 : : char *new_conninfo;
5092 : 8953 : bool started_tx = false;
5093 : :
5094 : : /* When cache state is valid there is nothing to do here. */
5095 [ + + ]: 8953 : if (MySubscriptionValid)
5096 : 8856 : return;
5097 : :
5098 : : /* This function might be called inside or outside of transaction. */
5099 [ + + ]: 97 : if (!IsTransactionState())
5100 : : {
5101 : 92 : StartTransactionCommand();
5102 : 92 : started_tx = true;
5103 : : }
5104 : :
5105 : 97 : newsub = GetSubscription(MyLogicalRepWorker->subid, true);
5106 : :
5107 [ + - ]: 97 : if (newsub)
5108 : : {
5109 : 97 : MemoryContextSetParent(newsub->cxt, ApplyContext);
5110 : : }
5111 : : else
5112 : : {
5113 : : /*
5114 : : * Exit if the subscription was removed. This normally should not
5115 : : * happen as the worker gets killed during DROP SUBSCRIPTION.
5116 : : */
5117 [ # # ]: 0 : ereport(LOG,
5118 : : (errmsg("logical replication worker for subscription \"%s\" will stop because the subscription was removed",
5119 : : MySubscription->name)));
5120 : :
5121 : : /* Ensure we remove no-longer-useful entry for worker's start time */
5122 [ # # ]: 0 : if (am_leader_apply_worker())
5123 : 0 : ApplyLauncherForgetWorkerStartTime(MyLogicalRepWorker->subid);
5124 : :
5125 : 0 : proc_exit(0);
5126 : : }
5127 : :
5128 : : /* Exit if the subscription was disabled. */
5129 [ + + ]: 97 : if (!newsub->enabled)
5130 : : {
5131 [ + - ]: 14 : ereport(LOG,
5132 : : (errmsg("logical replication worker for subscription \"%s\" will stop because the subscription was disabled",
5133 : : MySubscription->name)));
5134 : :
5135 : 14 : apply_worker_exit();
5136 : : }
5137 : :
5138 : : /*
5139 : : * May raise error, so build conninfo after checking that the subscription
5140 : : * is enabled. Allocated in transaction context; must be copied to
5141 : : * ApplyContext when we set MySubscriptionConninfo.
5142 : : */
5143 : 83 : new_conninfo = SubscriptionConninfo(newsub);
5144 : :
5145 : : /* !slotname should never happen when enabled is true. */
5146 : : Assert(newsub->slotname);
5147 : :
5148 : : /* two-phase cannot be altered while the worker is running */
5149 : : Assert(newsub->twophasestate == MySubscription->twophasestate);
5150 : :
5151 : : /*
5152 : : * Exit if any parameter that affects the remote connection was changed.
5153 : : * The launcher will start a new worker but note that the parallel apply
5154 : : * worker won't restart if the streaming option's value is changed from
5155 : : * 'parallel' to any other value or the server decides not to stream the
5156 : : * in-progress transaction.
5157 : : */
5158 [ + + ]: 83 : if (strcmp(new_conninfo, MySubscriptionConninfo) != 0 ||
5159 [ + + ]: 78 : strcmp(newsub->name, MySubscription->name) != 0 ||
5160 [ + - ]: 77 : strcmp(newsub->slotname, MySubscription->slotname) != 0 ||
5161 [ + + ]: 77 : newsub->binary != MySubscription->binary ||
5162 [ + + ]: 71 : newsub->stream != MySubscription->stream ||
5163 [ + - ]: 66 : newsub->passwordrequired != MySubscription->passwordrequired ||
5164 [ + + ]: 66 : strcmp(newsub->origin, MySubscription->origin) != 0 ||
5165 [ + + ]: 64 : newsub->owner != MySubscription->owner ||
5166 [ + + ]: 63 : !equal(newsub->publications, MySubscription->publications))
5167 : : {
5168 [ - + ]: 30 : if (am_parallel_apply_worker())
5169 [ # # ]: 0 : ereport(LOG,
5170 : : (errmsg("logical replication parallel apply worker for subscription \"%s\" will stop because of a parameter change",
5171 : : MySubscription->name)));
5172 : : else
5173 [ + - ]: 30 : ereport(LOG,
5174 : : (errmsg("logical replication worker for subscription \"%s\" will restart because of a parameter change",
5175 : : MySubscription->name)));
5176 : :
5177 : 30 : apply_worker_exit();
5178 : : }
5179 : :
5180 : : /*
5181 : : * Exit if the subscription owner's superuser privileges have been
5182 : : * revoked.
5183 : : */
5184 [ + + + + ]: 53 : if (!newsub->ownersuperuser && MySubscription->ownersuperuser)
5185 : : {
5186 [ - + ]: 4 : if (am_parallel_apply_worker())
5187 [ # # ]: 0 : ereport(LOG,
5188 : : errmsg("logical replication parallel apply worker for subscription \"%s\" will stop because the subscription owner's superuser privileges have been revoked",
5189 : : MySubscription->name));
5190 : : else
5191 [ + - ]: 4 : ereport(LOG,
5192 : : errmsg("logical replication worker for subscription \"%s\" will restart because the subscription owner's superuser privileges have been revoked",
5193 : : MySubscription->name));
5194 : :
5195 : 4 : apply_worker_exit();
5196 : : }
5197 : :
5198 : : /* Check for other changes that should never happen too. */
5199 [ - + ]: 49 : if (newsub->dbid != MySubscription->dbid)
5200 : : {
5201 [ # # ]: 0 : elog(ERROR, "subscription %u changed unexpectedly",
5202 : : MyLogicalRepWorker->subid);
5203 : : }
5204 : :
5205 : : /* Clean old subscription info and switch to new one. */
5206 : 49 : MemoryContextDelete(MySubscription->cxt);
5207 : 49 : MySubscription = newsub;
5208 : :
5209 : : /* copy to ApplyContext and update MySubscriptionConninfo */
5210 : 49 : old_conninfo = MySubscriptionConninfo;
5211 : 49 : MySubscriptionConninfo = MemoryContextStrdup(ApplyContext, new_conninfo);
5212 : 49 : pfree(old_conninfo);
5213 : :
5214 : : /* Change synchronous commit according to the user's wishes */
5215 : 49 : SetConfigOption("synchronous_commit", MySubscription->synccommit,
5216 : : PGC_BACKEND, PGC_S_OVERRIDE);
5217 : :
5218 : : /* Change wal_receiver_timeout according to the user's wishes */
5219 : 49 : set_wal_receiver_timeout();
5220 : :
5221 [ + + ]: 49 : if (started_tx)
5222 : 47 : CommitTransactionCommand();
5223 : :
5224 : 49 : MySubscriptionValid = true;
5225 : : }
5226 : :
5227 : : /*
5228 : : * Change wal_receiver_timeout to MySubscription->walrcvtimeout.
5229 : : */
5230 : : static void
5231 : 623 : set_wal_receiver_timeout(void)
5232 : : {
5233 : : bool parsed;
5234 : : int val;
5235 : 623 : int prev_timeout = wal_receiver_timeout;
5236 : :
5237 : : /*
5238 : : * Set the wal_receiver_timeout GUC to MySubscription->walrcvtimeout,
5239 : : * which comes from the subscription's wal_receiver_timeout option. If the
5240 : : * value is -1, reset the GUC to its default, meaning it will inherit from
5241 : : * the server config, command line, or role/database settings.
5242 : : */
5243 : 623 : parsed = parse_int(MySubscription->walrcvtimeout, &val, 0, NULL);
5244 [ + - + - ]: 623 : if (parsed && val == -1)
5245 : 623 : SetConfigOption("wal_receiver_timeout", NULL,
5246 : : PGC_BACKEND, PGC_S_SESSION);
5247 : : else
5248 : 0 : SetConfigOption("wal_receiver_timeout", MySubscription->walrcvtimeout,
5249 : : PGC_BACKEND, PGC_S_SESSION);
5250 : :
5251 : : /*
5252 : : * Log the wal_receiver_timeout setting (in milliseconds) as a debug
5253 : : * message when it changes, to verify it was set correctly.
5254 : : */
5255 [ - + ]: 623 : if (prev_timeout != wal_receiver_timeout)
5256 [ # # ]: 0 : elog(DEBUG1, "logical replication worker for subscription \"%s\" wal_receiver_timeout: %d ms",
5257 : : MySubscription->name, wal_receiver_timeout);
5258 : 623 : }
5259 : :
5260 : : /*
5261 : : * Callback from subscription syscache invalidation. Also needed for server or
5262 : : * user mapping invalidation, which can change the connection information for
5263 : : * subscriptions that connect using a server object.
5264 : : */
5265 : : static void
5266 : 103 : subscription_change_cb(Datum arg, SysCacheIdentifier cacheid, uint32 hashvalue)
5267 : : {
5268 : 103 : MySubscriptionValid = false;
5269 : 103 : }
5270 : :
5271 : : /*
5272 : : * subxact_info_write
5273 : : * Store information about subxacts for a toplevel transaction.
5274 : : *
5275 : : * For each subxact we store offset of its first change in the main file.
5276 : : * The file is always over-written as a whole.
5277 : : *
5278 : : * XXX We should only store subxacts that were not aborted yet.
5279 : : */
5280 : : static void
5281 : 372 : subxact_info_write(Oid subid, TransactionId xid)
5282 : : {
5283 : : char path[MAXPGPATH];
5284 : : Size len;
5285 : : BufFile *fd;
5286 : :
5287 : : Assert(TransactionIdIsValid(xid));
5288 : :
5289 : : /* construct the subxact filename */
5290 : 372 : subxact_filename(path, subid, xid);
5291 : :
5292 : : /* Delete the subxacts file, if exists. */
5293 [ + + ]: 372 : if (subxact_data.nsubxacts == 0)
5294 : : {
5295 : 290 : cleanup_subxact_info();
5296 : 290 : BufFileDeleteFileSet(MyLogicalRepWorker->stream_fileset, path, true);
5297 : :
5298 : 290 : return;
5299 : : }
5300 : :
5301 : : /*
5302 : : * Create the subxact file if it not already created, otherwise open the
5303 : : * existing file.
5304 : : */
5305 : 82 : fd = BufFileOpenFileSet(MyLogicalRepWorker->stream_fileset, path, O_RDWR,
5306 : : true);
5307 [ + + ]: 82 : if (fd == NULL)
5308 : 8 : fd = BufFileCreateFileSet(MyLogicalRepWorker->stream_fileset, path);
5309 : :
5310 : 82 : len = sizeof(SubXactInfo) * subxact_data.nsubxacts;
5311 : :
5312 : : /* Write the subxact count and subxact info */
5313 : 82 : BufFileWrite(fd, &subxact_data.nsubxacts, sizeof(subxact_data.nsubxacts));
5314 : 82 : BufFileWrite(fd, subxact_data.subxacts, len);
5315 : :
5316 : 82 : BufFileClose(fd);
5317 : :
5318 : : /* free the memory allocated for subxact info */
5319 : 82 : cleanup_subxact_info();
5320 : : }
5321 : :
5322 : : /*
5323 : : * subxact_info_read
5324 : : * Restore information about subxacts of a streamed transaction.
5325 : : *
5326 : : * Read information about subxacts into the structure subxact_data that can be
5327 : : * used later.
5328 : : */
5329 : : static void
5330 : 344 : subxact_info_read(Oid subid, TransactionId xid)
5331 : : {
5332 : : char path[MAXPGPATH];
5333 : : Size len;
5334 : : BufFile *fd;
5335 : : MemoryContext oldctx;
5336 : :
5337 : : Assert(!subxact_data.subxacts);
5338 : : Assert(subxact_data.nsubxacts == 0);
5339 : : Assert(subxact_data.nsubxacts_max == 0);
5340 : :
5341 : : /*
5342 : : * If the subxact file doesn't exist that means we don't have any subxact
5343 : : * info.
5344 : : */
5345 : 344 : subxact_filename(path, subid, xid);
5346 : 344 : fd = BufFileOpenFileSet(MyLogicalRepWorker->stream_fileset, path, O_RDONLY,
5347 : : true);
5348 [ + + ]: 344 : if (fd == NULL)
5349 : 265 : return;
5350 : :
5351 : : /* read number of subxact items */
5352 : 79 : BufFileReadExact(fd, &subxact_data.nsubxacts, sizeof(subxact_data.nsubxacts));
5353 : :
5354 : 79 : len = sizeof(SubXactInfo) * subxact_data.nsubxacts;
5355 : :
5356 : : /* we keep the maximum as a power of 2 */
5357 : 79 : subxact_data.nsubxacts_max = 1 << pg_ceil_log2_32(subxact_data.nsubxacts);
5358 : :
5359 : : /*
5360 : : * Allocate subxact information in the logical streaming context. We need
5361 : : * this information during the complete stream so that we can add the sub
5362 : : * transaction info to this. On stream stop we will flush this information
5363 : : * to the subxact file and reset the logical streaming context.
5364 : : */
5365 : 79 : oldctx = MemoryContextSwitchTo(LogicalStreamingContext);
5366 : 79 : subxact_data.subxacts = palloc_array(SubXactInfo,
5367 : : subxact_data.nsubxacts_max);
5368 : 79 : MemoryContextSwitchTo(oldctx);
5369 : :
5370 [ + - ]: 79 : if (len > 0)
5371 : 79 : BufFileReadExact(fd, subxact_data.subxacts, len);
5372 : :
5373 : 79 : BufFileClose(fd);
5374 : : }
5375 : :
5376 : : /*
5377 : : * subxact_info_add
5378 : : * Add information about a subxact (offset in the main file).
5379 : : */
5380 : : static void
5381 : 102513 : subxact_info_add(TransactionId xid)
5382 : : {
5383 : 102513 : SubXactInfo *subxacts = subxact_data.subxacts;
5384 : : int64 i;
5385 : :
5386 : : /* We must have a valid top level stream xid and a stream fd. */
5387 : : Assert(TransactionIdIsValid(stream_xid));
5388 : : Assert(stream_fd != NULL);
5389 : :
5390 : : /*
5391 : : * If the XID matches the toplevel transaction, we don't want to add it.
5392 : : */
5393 [ + + ]: 102513 : if (stream_xid == xid)
5394 : 92389 : return;
5395 : :
5396 : : /*
5397 : : * In most cases we're checking the same subxact as we've already seen in
5398 : : * the last call, so make sure to ignore it (this change comes later).
5399 : : */
5400 [ + + ]: 10124 : if (subxact_data.subxact_last == xid)
5401 : 10048 : return;
5402 : :
5403 : : /* OK, remember we're processing this XID. */
5404 : 76 : subxact_data.subxact_last = xid;
5405 : :
5406 : : /*
5407 : : * Check if the transaction is already present in the array of subxact. We
5408 : : * intentionally scan the array from the tail, because we're likely adding
5409 : : * a change for the most recent subtransactions.
5410 : : *
5411 : : * XXX Can we rely on the subxact XIDs arriving in sorted order? That
5412 : : * would allow us to use binary search here.
5413 : : */
5414 [ + + ]: 95 : for (i = subxact_data.nsubxacts; i > 0; i--)
5415 : : {
5416 : : /* found, so we're done */
5417 [ + + ]: 76 : if (subxacts[i - 1].xid == xid)
5418 : 57 : return;
5419 : : }
5420 : :
5421 : : /* This is a new subxact, so we need to add it to the array. */
5422 [ + + ]: 19 : if (subxact_data.nsubxacts == 0)
5423 : : {
5424 : : MemoryContext oldctx;
5425 : :
5426 : 8 : subxact_data.nsubxacts_max = 128;
5427 : :
5428 : : /*
5429 : : * Allocate this memory for subxacts in per-stream context, see
5430 : : * subxact_info_read.
5431 : : */
5432 : 8 : oldctx = MemoryContextSwitchTo(LogicalStreamingContext);
5433 : 8 : subxacts = palloc_array(SubXactInfo, subxact_data.nsubxacts_max);
5434 : 8 : MemoryContextSwitchTo(oldctx);
5435 : : }
5436 [ + + ]: 11 : else if (subxact_data.nsubxacts == subxact_data.nsubxacts_max)
5437 : : {
5438 : 10 : subxact_data.nsubxacts_max *= 2;
5439 : 10 : subxacts = repalloc_array(subxacts, SubXactInfo,
5440 : : subxact_data.nsubxacts_max);
5441 : : }
5442 : :
5443 : 19 : subxacts[subxact_data.nsubxacts].xid = xid;
5444 : :
5445 : : /*
5446 : : * Get the current offset of the stream file and store it as offset of
5447 : : * this subxact.
5448 : : */
5449 : 19 : BufFileTell(stream_fd,
5450 : 19 : &subxacts[subxact_data.nsubxacts].fileno,
5451 : 19 : &subxacts[subxact_data.nsubxacts].offset);
5452 : :
5453 : 19 : subxact_data.nsubxacts++;
5454 : 19 : subxact_data.subxacts = subxacts;
5455 : : }
5456 : :
5457 : : /* format filename for file containing the info about subxacts */
5458 : : static inline void
5459 : 747 : subxact_filename(char *path, Oid subid, TransactionId xid)
5460 : : {
5461 : 747 : snprintf(path, MAXPGPATH, "%u-%u.subxacts", subid, xid);
5462 : 747 : }
5463 : :
5464 : : /* format filename for file containing serialized changes */
5465 : : static inline void
5466 : 438 : changes_filename(char *path, Oid subid, TransactionId xid)
5467 : : {
5468 : 438 : snprintf(path, MAXPGPATH, "%u-%u.changes", subid, xid);
5469 : 438 : }
5470 : :
5471 : : /*
5472 : : * stream_cleanup_files
5473 : : * Cleanup files for a subscription / toplevel transaction.
5474 : : *
5475 : : * Remove files with serialized changes and subxact info for a particular
5476 : : * toplevel transaction. Each subscription has a separate set of files
5477 : : * for any toplevel transaction.
5478 : : */
5479 : : void
5480 : 31 : stream_cleanup_files(Oid subid, TransactionId xid)
5481 : : {
5482 : : char path[MAXPGPATH];
5483 : :
5484 : : /* Delete the changes file. */
5485 : 31 : changes_filename(path, subid, xid);
5486 : 31 : BufFileDeleteFileSet(MyLogicalRepWorker->stream_fileset, path, false);
5487 : :
5488 : : /* Delete the subxact file, if it exists. */
5489 : 31 : subxact_filename(path, subid, xid);
5490 : 31 : BufFileDeleteFileSet(MyLogicalRepWorker->stream_fileset, path, true);
5491 : 31 : }
5492 : :
5493 : : /*
5494 : : * stream_open_file
5495 : : * Open a file that we'll use to serialize changes for a toplevel
5496 : : * transaction.
5497 : : *
5498 : : * Open a file for streamed changes from a toplevel transaction identified
5499 : : * by stream_xid (global variable). If it's the first chunk of streamed
5500 : : * changes for this transaction, create the buffile, otherwise open the
5501 : : * previously created file.
5502 : : */
5503 : : static void
5504 : 363 : stream_open_file(Oid subid, TransactionId xid, bool first_segment)
5505 : : {
5506 : : char path[MAXPGPATH];
5507 : : MemoryContext oldcxt;
5508 : :
5509 : : Assert(OidIsValid(subid));
5510 : : Assert(TransactionIdIsValid(xid));
5511 : : Assert(stream_fd == NULL);
5512 : :
5513 : :
5514 : 363 : changes_filename(path, subid, xid);
5515 [ - + ]: 363 : elog(DEBUG1, "opening file \"%s\" for streamed changes", path);
5516 : :
5517 : : /*
5518 : : * Create/open the buffiles under the logical streaming context so that we
5519 : : * have those files until stream stop.
5520 : : */
5521 : 363 : oldcxt = MemoryContextSwitchTo(LogicalStreamingContext);
5522 : :
5523 : : /*
5524 : : * If this is the first streamed segment, create the changes file.
5525 : : * Otherwise, just open the file for writing, in append mode.
5526 : : */
5527 [ + + ]: 363 : if (first_segment)
5528 : 32 : stream_fd = BufFileCreateFileSet(MyLogicalRepWorker->stream_fileset,
5529 : : path);
5530 : : else
5531 : : {
5532 : : /*
5533 : : * Open the file and seek to the end of the file because we always
5534 : : * append the changes file.
5535 : : */
5536 : 331 : stream_fd = BufFileOpenFileSet(MyLogicalRepWorker->stream_fileset,
5537 : : path, O_RDWR, false);
5538 : 331 : BufFileSeek(stream_fd, 0, 0, SEEK_END);
5539 : : }
5540 : :
5541 : 363 : MemoryContextSwitchTo(oldcxt);
5542 : 363 : }
5543 : :
5544 : : /*
5545 : : * stream_close_file
5546 : : * Close the currently open file with streamed changes.
5547 : : */
5548 : : static void
5549 : 393 : stream_close_file(void)
5550 : : {
5551 : : Assert(stream_fd != NULL);
5552 : :
5553 : 393 : BufFileClose(stream_fd);
5554 : :
5555 : 393 : stream_fd = NULL;
5556 : 393 : }
5557 : :
5558 : : /*
5559 : : * stream_write_change
5560 : : * Serialize a change to a file for the current toplevel transaction.
5561 : : *
5562 : : * The change is serialized in a simple format, with length (not including
5563 : : * the length), action code (identifying the message type) and message
5564 : : * contents (without the subxact TransactionId value).
5565 : : */
5566 : : static void
5567 : 107554 : stream_write_change(char action, StringInfo s)
5568 : : {
5569 : : int len;
5570 : :
5571 : : Assert(stream_fd != NULL);
5572 : :
5573 : : /* total on-disk size, including the action type character */
5574 : 107554 : len = (s->len - s->cursor) + sizeof(char);
5575 : :
5576 : : /* first write the size */
5577 : 107554 : BufFileWrite(stream_fd, &len, sizeof(len));
5578 : :
5579 : : /* then the action */
5580 : 107554 : BufFileWrite(stream_fd, &action, sizeof(action));
5581 : :
5582 : : /* and finally the remaining part of the buffer (after the XID) */
5583 : 107554 : len = (s->len - s->cursor);
5584 : :
5585 : 107554 : BufFileWrite(stream_fd, &s->data[s->cursor], len);
5586 : 107554 : }
5587 : :
5588 : : /*
5589 : : * stream_open_and_write_change
5590 : : * Serialize a message to a file for the given transaction.
5591 : : *
5592 : : * This function is similar to stream_write_change except that it will open the
5593 : : * target file if not already before writing the message and close the file at
5594 : : * the end.
5595 : : */
5596 : : static void
5597 : 5 : stream_open_and_write_change(TransactionId xid, char action, StringInfo s)
5598 : : {
5599 : : Assert(!in_streamed_transaction);
5600 : :
5601 [ + - ]: 5 : if (!stream_fd)
5602 : 5 : stream_start_internal(xid, false);
5603 : :
5604 : 5 : stream_write_change(action, s);
5605 : 5 : stream_stop_internal(xid);
5606 : 5 : }
5607 : :
5608 : : /*
5609 : : * Sets streaming options including replication slot name and origin start
5610 : : * position. Workers need these options for logical replication.
5611 : : */
5612 : : void
5613 : 477 : set_stream_options(WalRcvStreamOptions *options,
5614 : : char *slotname,
5615 : : XLogRecPtr *origin_startpos)
5616 : : {
5617 : : int server_version;
5618 : :
5619 : 477 : options->logical = true;
5620 : 477 : options->startpoint = *origin_startpos;
5621 : 477 : options->slotname = slotname;
5622 : :
5623 : 477 : server_version = walrcv_server_version(LogRepWorkerWalRcvConn);
5624 : 477 : options->proto.logical.proto_version =
5625 [ - + - - : 477 : server_version >= 160000 ? LOGICALREP_PROTO_STREAM_PARALLEL_VERSION_NUM :
- - ]
5626 : : server_version >= 150000 ? LOGICALREP_PROTO_TWOPHASE_VERSION_NUM :
5627 : : server_version >= 140000 ? LOGICALREP_PROTO_STREAM_VERSION_NUM :
5628 : : LOGICALREP_PROTO_VERSION_NUM;
5629 : :
5630 : 477 : options->proto.logical.publication_names = MySubscription->publications;
5631 : 477 : options->proto.logical.binary = MySubscription->binary;
5632 : :
5633 : : /*
5634 : : * Assign the appropriate option value for streaming option according to
5635 : : * the 'streaming' mode and the publisher's ability to support that mode.
5636 : : */
5637 [ + - ]: 477 : if (server_version >= 160000 &&
5638 [ + + ]: 477 : MySubscription->stream == LOGICALREP_STREAM_PARALLEL)
5639 : : {
5640 : 443 : options->proto.logical.streaming_str = "parallel";
5641 : 443 : MyLogicalRepWorker->parallel_apply = true;
5642 : : }
5643 [ + - ]: 34 : else if (server_version >= 140000 &&
5644 [ + + ]: 34 : MySubscription->stream != LOGICALREP_STREAM_OFF)
5645 : : {
5646 : 26 : options->proto.logical.streaming_str = "on";
5647 : 26 : MyLogicalRepWorker->parallel_apply = false;
5648 : : }
5649 : : else
5650 : : {
5651 : 8 : options->proto.logical.streaming_str = NULL;
5652 : 8 : MyLogicalRepWorker->parallel_apply = false;
5653 : : }
5654 : :
5655 : 477 : options->proto.logical.twophase = false;
5656 : 477 : options->proto.logical.origin = pstrdup(MySubscription->origin);
5657 : 477 : }
5658 : :
5659 : : /*
5660 : : * Cleanup the memory for subxacts and reset the related variables.
5661 : : */
5662 : : static inline void
5663 : 376 : cleanup_subxact_info(void)
5664 : : {
5665 [ + + ]: 376 : if (subxact_data.subxacts)
5666 : 87 : pfree(subxact_data.subxacts);
5667 : :
5668 : 376 : subxact_data.subxacts = NULL;
5669 : 376 : subxact_data.subxact_last = InvalidTransactionId;
5670 : 376 : subxact_data.nsubxacts = 0;
5671 : 376 : subxact_data.nsubxacts_max = 0;
5672 : 376 : }
5673 : :
5674 : : /*
5675 : : * Common function to run the apply loop with error handling. Disable the
5676 : : * subscription, if necessary.
5677 : : *
5678 : : * Note that we don't handle FATAL errors which are probably because
5679 : : * of system resource error and are not repeatable.
5680 : : */
5681 : : void
5682 : 477 : start_apply(XLogRecPtr origin_startpos)
5683 : : {
5684 [ + + ]: 477 : PG_TRY();
5685 : : {
5686 : 477 : LogicalRepApplyLoop(origin_startpos);
5687 : : }
5688 : 117 : PG_CATCH();
5689 : : {
5690 : : /*
5691 : : * Reset the origin state to prevent the advancement of origin
5692 : : * progress if we fail to apply. Otherwise, this will result in
5693 : : * transaction loss as that transaction won't be sent again by the
5694 : : * server.
5695 : : */
5696 : 117 : replorigin_xact_clear(true);
5697 : :
5698 [ + + ]: 117 : if (MySubscription->disableonerr)
5699 : 3 : DisableSubscriptionAndExit();
5700 : : else
5701 : : {
5702 : : /*
5703 : : * Report the worker failed while applying changes. Abort the
5704 : : * current transaction so that the stats message is sent in an
5705 : : * idle state.
5706 : : */
5707 : 114 : AbortOutOfAnyTransaction();
5708 : 114 : pgstat_report_subscription_error(MySubscription->oid);
5709 : :
5710 : 114 : PG_RE_THROW();
5711 : : }
5712 : : }
5713 [ # # ]: 0 : PG_END_TRY();
5714 : 0 : }
5715 : :
5716 : : /*
5717 : : * Runs the leader apply worker.
5718 : : *
5719 : : * It sets up replication origin, streaming options and then starts streaming.
5720 : : */
5721 : : static void
5722 : 332 : run_apply_worker(void)
5723 : : {
5724 : : char originname[NAMEDATALEN];
5725 : 332 : XLogRecPtr origin_startpos = InvalidXLogRecPtr;
5726 : 332 : char *slotname = NULL;
5727 : : WalRcvStreamOptions options;
5728 : : ReplOriginId originid;
5729 : : TimeLineID startpointTLI;
5730 : : char *err;
5731 : : bool must_use_password;
5732 : :
5733 : 332 : slotname = MySubscription->slotname;
5734 : :
5735 : : /*
5736 : : * This shouldn't happen if the subscription is enabled, but guard against
5737 : : * DDL bugs or manual catalog changes. (libpqwalreceiver will crash if
5738 : : * slot is NULL.)
5739 : : */
5740 [ - + ]: 332 : if (!slotname)
5741 [ # # ]: 0 : ereport(ERROR,
5742 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
5743 : : errmsg("subscription has no replication slot set")));
5744 : :
5745 : : /* Setup replication origin tracking. */
5746 : 332 : ReplicationOriginNameForLogicalRep(MySubscription->oid, InvalidOid,
5747 : : originname, sizeof(originname));
5748 : 332 : StartTransactionCommand();
5749 : 332 : originid = replorigin_by_name(originname, true);
5750 [ - + ]: 332 : if (!OidIsValid(originid))
5751 : 0 : originid = replorigin_create(originname);
5752 : 332 : replorigin_session_setup(originid, 0);
5753 : 331 : replorigin_xact_state.origin = originid;
5754 : 331 : origin_startpos = replorigin_session_get_progress(false);
5755 : 331 : CommitTransactionCommand();
5756 : :
5757 : : /* Is the use of a password mandatory? */
5758 [ + + ]: 633 : must_use_password = MySubscription->passwordrequired &&
5759 [ + + ]: 302 : !MySubscription->ownersuperuser;
5760 : :
5761 : 331 : LogRepWorkerWalRcvConn = walrcv_connect(MySubscriptionConninfo, true,
5762 : : true, must_use_password,
5763 : : MySubscription->name, &err);
5764 : :
5765 [ + + ]: 320 : if (LogRepWorkerWalRcvConn == NULL)
5766 [ + - ]: 44 : ereport(ERROR,
5767 : : (errcode(ERRCODE_CONNECTION_FAILURE),
5768 : : errmsg("apply worker for subscription \"%s\" could not connect to the publisher: %s",
5769 : : MySubscription->name, err)));
5770 : :
5771 : : /*
5772 : : * We don't really use the output identify_system for anything but it does
5773 : : * some initializations on the upstream so let's still call it.
5774 : : */
5775 : 276 : (void) walrcv_identify_system(LogRepWorkerWalRcvConn, &startpointTLI, NULL);
5776 : :
5777 : : /*
5778 : : * If retain_dead_tuples is enabled, verify that the publisher is
5779 : : * suitable, that is, it runs a version that supports the feature and is
5780 : : * not in recovery. This is the authoritative check. Although the same
5781 : : * validation is performed opportunistically at DDL time, the publisher's
5782 : : * version or recovery status may have changed since then, for example
5783 : : * after a failover.
5784 : : */
5785 [ + + ]: 276 : if (MySubscription->retaindeadtuples)
5786 : : {
5787 : 13 : StartTransactionCommand();
5788 : 13 : CheckPubDeadTupleRetention(LogRepWorkerWalRcvConn);
5789 : 13 : CommitTransactionCommand();
5790 : : }
5791 : :
5792 : 276 : set_apply_error_context_origin(originname);
5793 : :
5794 : 276 : set_stream_options(&options, slotname, &origin_startpos);
5795 : :
5796 : : /*
5797 : : * Even when the two_phase mode is requested by the user, it remains as
5798 : : * the tri-state PENDING until all tablesyncs have reached READY state.
5799 : : * Only then, can it become ENABLED.
5800 : : *
5801 : : * Note: If the subscription has no tables then leave the state as
5802 : : * PENDING, which allows ALTER SUBSCRIPTION ... REFRESH PUBLICATION to
5803 : : * work.
5804 : : */
5805 [ + + + + ]: 292 : if (MySubscription->twophasestate == LOGICALREP_TWOPHASE_STATE_PENDING &&
5806 : 16 : AllTablesyncsReady())
5807 : : {
5808 : : /* Start streaming with two_phase enabled */
5809 : 9 : options.proto.logical.twophase = true;
5810 : 9 : walrcv_startstreaming(LogRepWorkerWalRcvConn, &options);
5811 : :
5812 : 9 : StartTransactionCommand();
5813 : :
5814 : : /*
5815 : : * Updating pg_subscription might involve TOAST table access, so
5816 : : * ensure we have a valid snapshot.
5817 : : */
5818 : 9 : PushActiveSnapshot(GetTransactionSnapshot());
5819 : :
5820 : 9 : UpdateTwoPhaseState(MySubscription->oid, LOGICALREP_TWOPHASE_STATE_ENABLED);
5821 : 9 : MySubscription->twophasestate = LOGICALREP_TWOPHASE_STATE_ENABLED;
5822 : 9 : PopActiveSnapshot();
5823 : 9 : CommitTransactionCommand();
5824 : : }
5825 : : else
5826 : : {
5827 : 267 : walrcv_startstreaming(LogRepWorkerWalRcvConn, &options);
5828 : : }
5829 : :
5830 [ + + + + : 276 : ereport(DEBUG1,
+ - + - ]
5831 : : (errmsg_internal("logical replication apply worker for subscription \"%s\" two_phase is %s",
5832 : : MySubscription->name,
5833 : : MySubscription->twophasestate == LOGICALREP_TWOPHASE_STATE_DISABLED ? "DISABLED" :
5834 : : MySubscription->twophasestate == LOGICALREP_TWOPHASE_STATE_PENDING ? "PENDING" :
5835 : : MySubscription->twophasestate == LOGICALREP_TWOPHASE_STATE_ENABLED ? "ENABLED" :
5836 : : "?")));
5837 : :
5838 : : /* Run the main loop. */
5839 : 276 : start_apply(origin_startpos);
5840 : 0 : }
5841 : :
5842 : : /*
5843 : : * Common initialization for leader apply worker, parallel apply worker,
5844 : : * tablesync worker and sequencesync worker.
5845 : : *
5846 : : * Initialize the database connection, in-memory subscription and necessary
5847 : : * config options.
5848 : : */
5849 : : void
5850 : 651 : InitializeLogRepWorker(void)
5851 : : {
5852 : : /* Run as replica session replication role. */
5853 : 651 : SetConfigOption("session_replication_role", "replica",
5854 : : PGC_SUSET, PGC_S_OVERRIDE);
5855 : :
5856 : : /* Connect to our database. */
5857 : 651 : BackgroundWorkerInitializeConnectionByOid(MyLogicalRepWorker->dbid,
5858 : 651 : MyLogicalRepWorker->userid,
5859 : : 0);
5860 : :
5861 : : /*
5862 : : * Set always-secure search path, so malicious users can't redirect user
5863 : : * code (e.g. pg_index.indexprs).
5864 : : */
5865 : 645 : SetConfigOption("search_path", "", PGC_SUSET, PGC_S_OVERRIDE);
5866 : :
5867 : : /*
5868 : : * Ignore default_transaction_read_only for logical replication workers,
5869 : : * as they need to be able to modify subscriber-side state regardless of
5870 : : * that setting.
5871 : : */
5872 : 645 : SetConfigOption("default_transaction_read_only", "off", PGC_SUSET,
5873 : : PGC_S_OVERRIDE);
5874 : :
5875 : 645 : ApplyContext = AllocSetContextCreate(TopMemoryContext,
5876 : : "ApplyContext",
5877 : : ALLOCSET_DEFAULT_SIZES);
5878 : :
5879 : 645 : StartTransactionCommand();
5880 : :
5881 : : /*
5882 : : * Lock the subscription to prevent it from being concurrently dropped,
5883 : : * then re-verify its existence. After the initialization, the worker will
5884 : : * be terminated gracefully if the subscription is dropped.
5885 : : */
5886 : 645 : LockSharedObject(SubscriptionRelationId, MyLogicalRepWorker->subid, 0,
5887 : : AccessShareLock);
5888 : :
5889 : 644 : MySubscription = GetSubscription(MyLogicalRepWorker->subid, true);
5890 : :
5891 [ + + ]: 644 : if (MySubscription)
5892 : : {
5893 : 574 : MemoryContextSetParent(MySubscription->cxt, ApplyContext);
5894 : : }
5895 : : else
5896 : : {
5897 [ + - ]: 70 : ereport(LOG,
5898 : : (errmsg("logical replication worker for subscription %u will not start because the subscription was removed during startup",
5899 : : MyLogicalRepWorker->subid)));
5900 : :
5901 : : /* Ensure we remove no-longer-useful entry for worker's start time */
5902 [ + - ]: 70 : if (am_leader_apply_worker())
5903 : 70 : ApplyLauncherForgetWorkerStartTime(MyLogicalRepWorker->subid);
5904 : :
5905 : 70 : proc_exit(0);
5906 : : }
5907 : :
5908 [ - + ]: 574 : if (!MySubscription->enabled)
5909 : : {
5910 [ # # ]: 0 : ereport(LOG,
5911 : : (errmsg("logical replication worker for subscription \"%s\" will not start because the subscription was disabled during startup",
5912 : : MySubscription->name)));
5913 : :
5914 : 0 : apply_worker_exit();
5915 : : }
5916 : :
5917 : : /*
5918 : : * May raise error for server-based subscriptions, so build conninfo after
5919 : : * checking that the subscription is enabled. Build in transaction context
5920 : : * and copy to ApplyContext.
5921 : : */
5922 : 574 : MySubscriptionConninfo =
5923 : 574 : MemoryContextStrdup(ApplyContext,
5924 : 574 : SubscriptionConninfo(MySubscription));
5925 : :
5926 : 574 : MySubscriptionValid = true;
5927 : :
5928 : : /*
5929 : : * Restart the worker if retain_dead_tuples was enabled during startup.
5930 : : *
5931 : : * At this point, the replication slot used for conflict detection might
5932 : : * not exist yet, or could be dropped soon if the launcher perceives
5933 : : * retain_dead_tuples as disabled. To avoid unnecessary tracking of
5934 : : * oldest_nonremovable_xid when the slot is absent or at risk of being
5935 : : * dropped, a restart is initiated.
5936 : : *
5937 : : * The oldest_nonremovable_xid should be initialized only when the
5938 : : * subscription's retention is active before launching the worker. See
5939 : : * logicalrep_worker_launch.
5940 : : */
5941 [ + + ]: 574 : if (am_leader_apply_worker() &&
5942 [ + + ]: 332 : MySubscription->retaindeadtuples &&
5943 [ + - ]: 18 : MySubscription->retentionactive &&
5944 [ - + ]: 18 : !TransactionIdIsValid(MyLogicalRepWorker->oldest_nonremovable_xid))
5945 : : {
5946 [ # # ]: 0 : ereport(LOG,
5947 : : errmsg("logical replication worker for subscription \"%s\" will restart because the option %s was enabled during startup",
5948 : : MySubscription->name, "retain_dead_tuples"));
5949 : :
5950 : 0 : apply_worker_exit();
5951 : : }
5952 : :
5953 : : /* Setup synchronous commit according to the user's wishes */
5954 : 574 : SetConfigOption("synchronous_commit", MySubscription->synccommit,
5955 : : PGC_BACKEND, PGC_S_OVERRIDE);
5956 : :
5957 : : /* Change wal_receiver_timeout according to the user's wishes */
5958 : 574 : set_wal_receiver_timeout();
5959 : :
5960 : : /*
5961 : : * Keep us informed about subscription or role changes. Note that the
5962 : : * role's superuser privilege can be revoked.
5963 : : */
5964 : 574 : CacheRegisterSyscacheCallback(SUBSCRIPTIONOID,
5965 : : subscription_change_cb,
5966 : : (Datum) 0);
5967 : : /* Changes to foreign servers may affect subscriptions using SERVER. */
5968 : 574 : CacheRegisterSyscacheCallback(FOREIGNSERVEROID,
5969 : : subscription_change_cb,
5970 : : (Datum) 0);
5971 : : /* Changes to user mappings may affect subscriptions using SERVER. */
5972 : 574 : CacheRegisterSyscacheCallback(USERMAPPINGOID,
5973 : : subscription_change_cb,
5974 : : (Datum) 0);
5975 : :
5976 : : /*
5977 : : * Changes to FDW connection_function may affect subscriptions using
5978 : : * SERVER.
5979 : : */
5980 : 574 : CacheRegisterSyscacheCallback(FOREIGNDATAWRAPPEROID,
5981 : : subscription_change_cb,
5982 : : (Datum) 0);
5983 : :
5984 : 574 : CacheRegisterSyscacheCallback(AUTHOID,
5985 : : subscription_change_cb,
5986 : : (Datum) 0);
5987 : :
5988 [ + + ]: 574 : if (am_tablesync_worker())
5989 [ + - ]: 215 : ereport(LOG,
5990 : : errmsg("logical replication table synchronization worker for subscription \"%s\", table \"%s\" has started",
5991 : : MySubscription->name,
5992 : : get_rel_name(MyLogicalRepWorker->relid)));
5993 [ + + ]: 359 : else if (am_sequencesync_worker())
5994 [ + - ]: 15 : ereport(LOG,
5995 : : errmsg("logical replication sequence synchronization worker for subscription \"%s\" has started",
5996 : : MySubscription->name));
5997 : : else
5998 [ + - ]: 344 : ereport(LOG,
5999 : : errmsg("logical replication apply worker for subscription \"%s\" has started",
6000 : : MySubscription->name));
6001 : :
6002 : 574 : CommitTransactionCommand();
6003 : :
6004 : : /*
6005 : : * Register a callback to reset the origin state before aborting any
6006 : : * pending transaction during shutdown (see ShutdownPostgres()). This will
6007 : : * avoid origin advancement for an incomplete transaction which could
6008 : : * otherwise lead to its loss as such a transaction won't be sent by the
6009 : : * server again.
6010 : : *
6011 : : * Note that even a LOG or DEBUG statement placed after setting the origin
6012 : : * state may process a shutdown signal before committing the current apply
6013 : : * operation. So, it is important to register such a callback here.
6014 : : *
6015 : : * Register this callback here to ensure that all types of logical
6016 : : * replication workers that set up origins and apply remote transactions
6017 : : * are protected.
6018 : : */
6019 : 574 : before_shmem_exit(on_exit_clear_xact_state, (Datum) 0);
6020 : 574 : }
6021 : :
6022 : : /*
6023 : : * Callback on exit to clear transaction-level replication origin state.
6024 : : */
6025 : : static void
6026 : 574 : on_exit_clear_xact_state(int code, Datum arg)
6027 : : {
6028 : 574 : replorigin_xact_clear(true);
6029 : 574 : }
6030 : :
6031 : : /*
6032 : : * Common function to setup the leader apply, tablesync and sequencesync worker.
6033 : : */
6034 : : void
6035 : 639 : SetupApplyOrSyncWorker(int worker_slot)
6036 : : {
6037 : : /* Attach to slot */
6038 : 639 : logicalrep_worker_attach(worker_slot);
6039 : :
6040 : : Assert(am_tablesync_worker() || am_sequencesync_worker() || am_leader_apply_worker());
6041 : :
6042 : : /* Setup signal handling */
6043 : 639 : pqsignal(SIGHUP, SignalHandlerForConfigReload);
6044 : 639 : BackgroundWorkerUnblockSignals();
6045 : :
6046 : : /*
6047 : : * We don't currently need any ResourceOwner in a walreceiver process, but
6048 : : * if we did, we could call CreateAuxProcessResourceOwner here.
6049 : : */
6050 : :
6051 : : /* Initialise stats to a sanish value */
6052 [ + + ]: 639 : if (am_sequencesync_worker())
6053 : : {
6054 : 15 : MyLogicalRepWorker->last_send_time =
6055 : 15 : MyLogicalRepWorker->last_recv_time =
6056 : 15 : MyLogicalRepWorker->reply_time = 0;
6057 : : }
6058 : : else
6059 : : {
6060 : 624 : MyLogicalRepWorker->last_send_time =
6061 : 624 : MyLogicalRepWorker->last_recv_time =
6062 : 624 : MyLogicalRepWorker->reply_time = GetCurrentTimestamp();
6063 : : }
6064 : :
6065 : : /* Load the libpq-specific functions */
6066 : 639 : load_file("libpqwalreceiver", false);
6067 : :
6068 : 639 : InitializeLogRepWorker();
6069 : :
6070 : : /*
6071 : : * Setup callback for syscache so that we know when something changes in
6072 : : * the subscription relation state.
6073 : : */
6074 : 562 : CacheRegisterSyscacheCallback(SUBSCRIPTIONRELMAP,
6075 : : InvalidateSyncingRelStates,
6076 : : (Datum) 0);
6077 : 562 : }
6078 : :
6079 : : /* Logical Replication Apply worker entry point */
6080 : : void
6081 : 409 : ApplyWorkerMain(Datum main_arg)
6082 : : {
6083 : 409 : int worker_slot = DatumGetInt32(main_arg);
6084 : :
6085 : 409 : InitializingApplyWorker = true;
6086 : :
6087 : 409 : SetupApplyOrSyncWorker(worker_slot);
6088 : :
6089 : 332 : InitializingApplyWorker = false;
6090 : :
6091 : 332 : run_apply_worker();
6092 : :
6093 : 0 : proc_exit(0);
6094 : : }
6095 : :
6096 : : /*
6097 : : * After error recovery, disable the subscription in a new transaction
6098 : : * and exit cleanly.
6099 : : */
6100 : : void
6101 : 4 : DisableSubscriptionAndExit(void)
6102 : : {
6103 : : /*
6104 : : * Emit the error message, and recover from the error state to an idle
6105 : : * state
6106 : : */
6107 : 4 : HOLD_INTERRUPTS();
6108 : :
6109 : 4 : EmitErrorReport();
6110 : 4 : AbortOutOfAnyTransaction();
6111 : 4 : FlushErrorState();
6112 : :
6113 : 4 : RESUME_INTERRUPTS();
6114 : :
6115 : : /*
6116 : : * Report the worker failed during sequence synchronization, table
6117 : : * synchronization, or apply.
6118 : : */
6119 : 4 : pgstat_report_subscription_error(MyLogicalRepWorker->subid);
6120 : :
6121 : : /* Disable the subscription */
6122 : 4 : StartTransactionCommand();
6123 : :
6124 : : /*
6125 : : * Updating pg_subscription might involve TOAST table access, so ensure we
6126 : : * have a valid snapshot.
6127 : : */
6128 : 4 : PushActiveSnapshot(GetTransactionSnapshot());
6129 : :
6130 : 4 : DisableSubscription(MySubscription->oid);
6131 : 4 : PopActiveSnapshot();
6132 : 4 : CommitTransactionCommand();
6133 : :
6134 : : /* Ensure we remove no-longer-useful entry for worker's start time */
6135 [ + + ]: 4 : if (am_leader_apply_worker())
6136 : 3 : ApplyLauncherForgetWorkerStartTime(MyLogicalRepWorker->subid);
6137 : :
6138 : : /* Notify the subscription has been disabled and exit */
6139 [ + - ]: 4 : ereport(LOG,
6140 : : errmsg("subscription \"%s\" has been disabled because of an error",
6141 : : MySubscription->name));
6142 : :
6143 : : /*
6144 : : * Skip the track_commit_timestamp check when disabling the worker due to
6145 : : * an error, as verifying commit timestamps is unnecessary in this
6146 : : * context.
6147 : : */
6148 : 4 : CheckSubDeadTupleRetention(false, true, WARNING,
6149 : 4 : MySubscription->retaindeadtuples,
6150 : 4 : MySubscription->retentionactive, false);
6151 : :
6152 : 4 : proc_exit(0);
6153 : : }
6154 : :
6155 : : /*
6156 : : * Is current process a logical replication worker?
6157 : : */
6158 : : bool
6159 : 2815 : IsLogicalWorker(void)
6160 : : {
6161 : 2815 : return MyLogicalRepWorker != NULL;
6162 : : }
6163 : :
6164 : : /*
6165 : : * Is current process a logical replication parallel apply worker?
6166 : : */
6167 : : bool
6168 : 2035 : IsLogicalParallelApplyWorker(void)
6169 : : {
6170 [ + + + - ]: 2035 : return IsLogicalWorker() && am_parallel_apply_worker();
6171 : : }
6172 : :
6173 : : /*
6174 : : * Start skipping changes of the transaction if the given LSN matches the
6175 : : * LSN specified by subscription's skiplsn.
6176 : : */
6177 : : static void
6178 : 601 : maybe_start_skipping_changes(XLogRecPtr finish_lsn)
6179 : : {
6180 : : Assert(!is_skipping_changes());
6181 : : Assert(!in_remote_transaction);
6182 : : Assert(!in_streamed_transaction);
6183 : :
6184 : : /*
6185 : : * Quick return if it's not requested to skip this transaction. This
6186 : : * function is called for every remote transaction and we assume that
6187 : : * skipping the transaction is not used often.
6188 : : */
6189 [ + + - + : 601 : if (likely(!XLogRecPtrIsValid(MySubscription->skiplsn) ||
+ + ]
6190 : : MySubscription->skiplsn != finish_lsn))
6191 : 598 : return;
6192 : :
6193 : : /* Start skipping all changes of this transaction */
6194 : 3 : skip_xact_finish_lsn = finish_lsn;
6195 : :
6196 [ + - ]: 3 : ereport(LOG,
6197 : : errmsg("logical replication starts skipping transaction at LSN %X/%08X",
6198 : : LSN_FORMAT_ARGS(skip_xact_finish_lsn)));
6199 : : }
6200 : :
6201 : : /*
6202 : : * Stop skipping changes by resetting skip_xact_finish_lsn if enabled.
6203 : : */
6204 : : static void
6205 : 30 : stop_skipping_changes(void)
6206 : : {
6207 [ + + ]: 30 : if (!is_skipping_changes())
6208 : 27 : return;
6209 : :
6210 [ + - ]: 3 : ereport(LOG,
6211 : : errmsg("logical replication completed skipping transaction at LSN %X/%08X",
6212 : : LSN_FORMAT_ARGS(skip_xact_finish_lsn)));
6213 : :
6214 : : /* Stop skipping changes */
6215 : 3 : skip_xact_finish_lsn = InvalidXLogRecPtr;
6216 : : }
6217 : :
6218 : : /*
6219 : : * Clear subskiplsn of pg_subscription catalog.
6220 : : *
6221 : : * finish_lsn is the transaction's finish LSN that is used to check if the
6222 : : * subskiplsn matches it. If not matched, we raise a warning when clearing the
6223 : : * subskiplsn in order to inform users for cases e.g., where the user mistakenly
6224 : : * specified the wrong subskiplsn.
6225 : : */
6226 : : static void
6227 : 572 : clear_subscription_skip_lsn(XLogRecPtr finish_lsn)
6228 : : {
6229 : : Relation rel;
6230 : : Form_pg_subscription subform;
6231 : : HeapTuple tup;
6232 : 572 : XLogRecPtr myskiplsn = MySubscription->skiplsn;
6233 : 572 : bool started_tx = false;
6234 : :
6235 [ + + - + ]: 572 : if (likely(!XLogRecPtrIsValid(myskiplsn)) || am_parallel_apply_worker())
6236 : 569 : return;
6237 : :
6238 [ + + ]: 3 : if (!IsTransactionState())
6239 : : {
6240 : 1 : StartTransactionCommand();
6241 : 1 : started_tx = true;
6242 : : }
6243 : :
6244 : : /*
6245 : : * Updating pg_subscription might involve TOAST table access, so ensure we
6246 : : * have a valid snapshot.
6247 : : */
6248 : 3 : PushActiveSnapshot(GetTransactionSnapshot());
6249 : :
6250 : : /*
6251 : : * Protect subskiplsn of pg_subscription from being concurrently updated
6252 : : * while clearing it.
6253 : : */
6254 : 3 : LockSharedObject(SubscriptionRelationId, MySubscription->oid, 0,
6255 : : AccessShareLock);
6256 : :
6257 : 3 : rel = table_open(SubscriptionRelationId, RowExclusiveLock);
6258 : :
6259 : : /* Fetch the existing tuple. */
6260 : 3 : tup = SearchSysCacheCopy1(SUBSCRIPTIONOID,
6261 : : ObjectIdGetDatum(MySubscription->oid));
6262 : :
6263 [ - + ]: 3 : if (!HeapTupleIsValid(tup))
6264 [ # # ]: 0 : elog(ERROR, "subscription \"%s\" does not exist", MySubscription->name);
6265 : :
6266 : 3 : subform = (Form_pg_subscription) GETSTRUCT(tup);
6267 : :
6268 : : /*
6269 : : * Clear the subskiplsn. If the user has already changed subskiplsn before
6270 : : * clearing it we don't update the catalog and the replication origin
6271 : : * state won't get advanced. So in the worst case, if the server crashes
6272 : : * before sending an acknowledgment of the flush position the transaction
6273 : : * will be sent again and the user needs to set subskiplsn again. We can
6274 : : * reduce the possibility by logging a replication origin WAL record to
6275 : : * advance the origin LSN instead but there is no way to advance the
6276 : : * origin timestamp and it doesn't seem to be worth doing anything about
6277 : : * it since it's a very rare case.
6278 : : */
6279 [ + - ]: 3 : if (subform->subskiplsn == myskiplsn)
6280 : : {
6281 : : bool nulls[Natts_pg_subscription];
6282 : : bool replaces[Natts_pg_subscription];
6283 : : Datum values[Natts_pg_subscription];
6284 : :
6285 : 3 : memset(values, 0, sizeof(values));
6286 : 3 : memset(nulls, false, sizeof(nulls));
6287 : 3 : memset(replaces, false, sizeof(replaces));
6288 : :
6289 : : /* reset subskiplsn */
6290 : 3 : values[Anum_pg_subscription_subskiplsn - 1] = LSNGetDatum(InvalidXLogRecPtr);
6291 : 3 : replaces[Anum_pg_subscription_subskiplsn - 1] = true;
6292 : :
6293 : 3 : tup = heap_modify_tuple(tup, RelationGetDescr(rel), values, nulls,
6294 : : replaces);
6295 : 3 : CatalogTupleUpdate(rel, &tup->t_self, tup);
6296 : :
6297 [ - + ]: 3 : if (myskiplsn != finish_lsn)
6298 [ # # ]: 0 : ereport(WARNING,
6299 : : errmsg("skip-LSN of subscription \"%s\" cleared", MySubscription->name),
6300 : : errdetail("Remote transaction's finish WAL location (LSN) %X/%08X did not match skip-LSN %X/%08X.",
6301 : : LSN_FORMAT_ARGS(finish_lsn),
6302 : : LSN_FORMAT_ARGS(myskiplsn)));
6303 : : }
6304 : :
6305 : 3 : heap_freetuple(tup);
6306 : 3 : table_close(rel, NoLock);
6307 : :
6308 : 3 : PopActiveSnapshot();
6309 : :
6310 [ + + ]: 3 : if (started_tx)
6311 : 1 : CommitTransactionCommand();
6312 : : }
6313 : :
6314 : : /* Error callback to give more context info about the change being applied */
6315 : : void
6316 : 7288 : apply_error_callback(void *arg)
6317 : : {
6318 : 7288 : ApplyRemoteCtx *ctx = &remote_ctx;
6319 : :
6320 [ + + ]: 7288 : if (ctx->command == 0)
6321 : 6843 : return;
6322 : :
6323 : : Assert(ctx->origin_name);
6324 : :
6325 [ + + ]: 445 : if (ctx->rel == NULL)
6326 : : {
6327 [ - + ]: 334 : if (!TransactionIdIsValid(ctx->remote_xid))
6328 : 0 : errcontext("processing remote data for replication origin \"%s\" during message type \"%s\"",
6329 : : ctx->origin_name,
6330 : : logicalrep_message_type(ctx->command));
6331 [ + + ]: 334 : else if (!XLogRecPtrIsValid(ctx->finish_lsn))
6332 : 261 : errcontext("processing remote data for replication origin \"%s\" during message type \"%s\" in transaction %u",
6333 : : ctx->origin_name,
6334 : : logicalrep_message_type(ctx->command),
6335 : : ctx->remote_xid);
6336 : : else
6337 : 146 : errcontext("processing remote data for replication origin \"%s\" during message type \"%s\" in transaction %u, finished at %X/%08X",
6338 : : ctx->origin_name,
6339 : : logicalrep_message_type(ctx->command),
6340 : : ctx->remote_xid,
6341 : 73 : LSN_FORMAT_ARGS(ctx->finish_lsn));
6342 : : }
6343 : : else
6344 : : {
6345 [ + - ]: 111 : if (ctx->remote_attnum < 0)
6346 : : {
6347 [ + + ]: 111 : if (!XLogRecPtrIsValid(ctx->finish_lsn))
6348 : 4 : errcontext("processing remote data for replication origin \"%s\" during message type \"%s\" for replication target relation \"%s.%s\" in transaction %u",
6349 : : ctx->origin_name,
6350 : : logicalrep_message_type(ctx->command),
6351 : 2 : ctx->rel->remoterel.nspname,
6352 : 2 : ctx->rel->remoterel.relname,
6353 : : ctx->remote_xid);
6354 : : else
6355 : 218 : errcontext("processing remote data for replication origin \"%s\" during message type \"%s\" for replication target relation \"%s.%s\" in transaction %u, finished at %X/%08X",
6356 : : ctx->origin_name,
6357 : : logicalrep_message_type(ctx->command),
6358 : 109 : ctx->rel->remoterel.nspname,
6359 : 109 : ctx->rel->remoterel.relname,
6360 : : ctx->remote_xid,
6361 : 109 : LSN_FORMAT_ARGS(ctx->finish_lsn));
6362 : : }
6363 : : else
6364 : : {
6365 [ # # ]: 0 : if (!XLogRecPtrIsValid(ctx->finish_lsn))
6366 : 0 : errcontext("processing remote data for replication origin \"%s\" during message type \"%s\" for replication target relation \"%s.%s\" column \"%s\" in transaction %u",
6367 : : ctx->origin_name,
6368 : : logicalrep_message_type(ctx->command),
6369 : 0 : ctx->rel->remoterel.nspname,
6370 : 0 : ctx->rel->remoterel.relname,
6371 : 0 : ctx->rel->remoterel.attnames[ctx->remote_attnum],
6372 : : ctx->remote_xid);
6373 : : else
6374 : 0 : errcontext("processing remote data for replication origin \"%s\" during message type \"%s\" for replication target relation \"%s.%s\" column \"%s\" in transaction %u, finished at %X/%08X",
6375 : : ctx->origin_name,
6376 : : logicalrep_message_type(ctx->command),
6377 : 0 : ctx->rel->remoterel.nspname,
6378 : 0 : ctx->rel->remoterel.relname,
6379 : 0 : ctx->rel->remoterel.attnames[ctx->remote_attnum],
6380 : : ctx->remote_xid,
6381 : 0 : LSN_FORMAT_ARGS(ctx->finish_lsn));
6382 : : }
6383 : : }
6384 : : }
6385 : :
6386 : : /*
6387 : : * Set information identifying the remote transaction currently being
6388 : : * applied, kept for the duration of that transaction.
6389 : : *
6390 : : * This must be called for every message type that begins or resumes applying
6391 : : * a remote transaction's changes (BEGIN, BEGIN PREPARE, STREAM START, STREAM
6392 : : * COMMIT, STREAM PREPARE), since interleaved transactions (possible only for
6393 : : * streaming) would otherwise leave stale values from whichever transaction
6394 : : * last called this.
6395 : : *
6396 : : * Callers normally pass the top-level transaction's xid. The exception is a
6397 : : * STREAM ABORT, which passes the xid of the (sub)transaction being aborted so
6398 : : * that the error context names whatever failed; that is a subxid only when a
6399 : : * subtransaction rolls back, and the top-level xid otherwise. Nothing else
6400 : : * observes a subxid recorded this way, because no change is applied between a
6401 : : * STREAM ABORT and the STREAM START or STREAM COMMIT/PREPARE that follows it,
6402 : : * and each of those calls this again with the transaction's own values.
6403 : : */
6404 : : static inline void
6405 : 3023 : set_remote_transaction_info(TransactionId xid, XLogRecPtr lsn)
6406 : : {
6407 : 3023 : remote_ctx.remote_xid = xid;
6408 : 3023 : remote_ctx.finish_lsn = lsn;
6409 : 3023 : }
6410 : :
6411 : : /* Reset all information of the remote transaction context */
6412 : : static inline void
6413 : 1467 : reset_apply_remote_context(void)
6414 : : {
6415 : 1467 : remote_ctx.command = 0;
6416 : 1467 : remote_ctx.rel = NULL;
6417 : 1467 : remote_ctx.remote_attnum = -1;
6418 : 1467 : set_remote_transaction_info(InvalidTransactionId, InvalidXLogRecPtr);
6419 : 1467 : }
6420 : :
6421 : : /*
6422 : : * Request wakeup of the workers for the given subscription OID
6423 : : * at commit of the current transaction.
6424 : : *
6425 : : * This is used to ensure that the workers process assorted changes
6426 : : * as soon as possible.
6427 : : */
6428 : : void
6429 : 395 : LogicalRepWorkersWakeupAtCommit(Oid subid)
6430 : : {
6431 : : MemoryContext oldcxt;
6432 : :
6433 : 395 : oldcxt = MemoryContextSwitchTo(TopTransactionContext);
6434 : 395 : on_commit_wakeup_workers_subids =
6435 : 395 : list_append_unique_oid(on_commit_wakeup_workers_subids, subid);
6436 : 395 : MemoryContextSwitchTo(oldcxt);
6437 : 395 : }
6438 : :
6439 : : /*
6440 : : * Wake up the workers of any subscriptions that were changed in this xact.
6441 : : */
6442 : : void
6443 : 668037 : AtEOXact_LogicalRepWorkers(bool isCommit)
6444 : : {
6445 [ + + + + ]: 668037 : if (isCommit && on_commit_wakeup_workers_subids != NIL)
6446 : : {
6447 : : ListCell *lc;
6448 : :
6449 : 381 : LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
6450 [ + - + + : 762 : foreach(lc, on_commit_wakeup_workers_subids)
+ + ]
6451 : : {
6452 : 381 : Oid subid = lfirst_oid(lc);
6453 : : List *workers;
6454 : : ListCell *lc2;
6455 : :
6456 : 381 : workers = logicalrep_workers_find(subid, true, false);
6457 [ + + + + : 462 : foreach(lc2, workers)
+ + ]
6458 : : {
6459 : 81 : LogicalRepWorker *worker = (LogicalRepWorker *) lfirst(lc2);
6460 : :
6461 : 81 : logicalrep_worker_wakeup_ptr(worker);
6462 : : }
6463 : : }
6464 : 381 : LWLockRelease(LogicalRepWorkerLock);
6465 : : }
6466 : :
6467 : : /* The List storage will be reclaimed automatically in xact cleanup. */
6468 : 668037 : on_commit_wakeup_workers_subids = NIL;
6469 : 668037 : }
6470 : :
6471 : : /*
6472 : : * Allocate the origin name in long-lived context for error context message.
6473 : : */
6474 : : void
6475 : 489 : set_apply_error_context_origin(char *originname)
6476 : : {
6477 : 489 : remote_ctx.origin_name = MemoryContextStrdup(ApplyContext, originname);
6478 : 489 : }
6479 : :
6480 : : /*
6481 : : * Return the action to be taken for the given transaction. See
6482 : : * TransApplyAction for information on each of the actions.
6483 : : *
6484 : : * *winfo is assigned to the destination parallel worker info when the leader
6485 : : * apply worker has to pass all the transaction's changes to the parallel
6486 : : * apply worker.
6487 : : */
6488 : : static TransApplyAction
6489 : 347208 : get_transaction_apply_action(TransactionId xid, ParallelApplyWorkerInfo **winfo)
6490 : : {
6491 : 347208 : *winfo = NULL;
6492 : :
6493 [ + + ]: 347208 : if (am_parallel_apply_worker())
6494 : : {
6495 : 69069 : return TRANS_PARALLEL_APPLY;
6496 : : }
6497 : :
6498 : : /*
6499 : : * If we are processing this transaction using a parallel apply worker
6500 : : * then either we send the changes to the parallel worker or if the worker
6501 : : * is busy then serialize the changes to the file which will later be
6502 : : * processed by the parallel worker.
6503 : : */
6504 : 278139 : *winfo = pa_find_worker(xid);
6505 : :
6506 [ + + + + ]: 278139 : if (*winfo && (*winfo)->serialize_changes)
6507 : : {
6508 : 5037 : return TRANS_LEADER_PARTIAL_SERIALIZE;
6509 : : }
6510 [ + + ]: 273102 : else if (*winfo)
6511 : : {
6512 : 68904 : return TRANS_LEADER_SEND_TO_PARALLEL;
6513 : : }
6514 : :
6515 : : /*
6516 : : * If there is no parallel worker involved to process this transaction
6517 : : * then we either directly apply the change or serialize it to a file
6518 : : * which will later be applied when the transaction finish message is
6519 : : * processed.
6520 : : */
6521 [ + + ]: 204198 : else if (in_streamed_transaction)
6522 : : {
6523 : 103199 : return TRANS_LEADER_SERIALIZE;
6524 : : }
6525 : : else
6526 : : {
6527 : 100999 : return TRANS_LEADER_APPLY;
6528 : : }
6529 : : }
|