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