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