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