Line data Source code
1 : /*-------------------------------------------------------------------------
2 : * tablesync.c
3 : * PostgreSQL logical replication: initial table data synchronization
4 : *
5 : * Copyright (c) 2012-2025, PostgreSQL Global Development Group
6 : *
7 : * IDENTIFICATION
8 : * src/backend/replication/logical/tablesync.c
9 : *
10 : * NOTES
11 : * This file contains code for initial table data synchronization for
12 : * logical replication.
13 : *
14 : * The initial data synchronization is done separately for each table,
15 : * in a separate apply worker that only fetches the initial snapshot data
16 : * from the publisher and then synchronizes the position in the stream with
17 : * the leader apply worker.
18 : *
19 : * There are several reasons for doing the synchronization this way:
20 : * - It allows us to parallelize the initial data synchronization
21 : * which lowers the time needed for it to happen.
22 : * - The initial synchronization does not have to hold the xid and LSN
23 : * for the time it takes to copy data of all tables, causing less
24 : * bloat and lower disk consumption compared to doing the
25 : * synchronization in a single process for the whole database.
26 : * - It allows us to synchronize any tables added after the initial
27 : * synchronization has finished.
28 : *
29 : * The stream position synchronization works in multiple steps:
30 : * - Apply worker requests a tablesync worker to start, setting the new
31 : * table state to INIT.
32 : * - Tablesync worker starts; changes table state from INIT to DATASYNC while
33 : * copying.
34 : * - Tablesync worker does initial table copy; there is a FINISHEDCOPY (sync
35 : * worker specific) state to indicate when the copy phase has completed, so
36 : * if the worker crashes with this (non-memory) state then the copy will not
37 : * be re-attempted.
38 : * - Tablesync worker then sets table state to SYNCWAIT; waits for state change.
39 : * - Apply worker periodically checks for tables in SYNCWAIT state. When
40 : * any appear, it sets the table state to CATCHUP and starts loop-waiting
41 : * until either the table state is set to SYNCDONE or the sync worker
42 : * exits.
43 : * - After the sync worker has seen the state change to CATCHUP, it will
44 : * read the stream and apply changes (acting like an apply worker) until
45 : * it catches up to the specified stream position. Then it sets the
46 : * state to SYNCDONE. There might be zero changes applied between
47 : * CATCHUP and SYNCDONE, because the sync worker might be ahead of the
48 : * apply worker.
49 : * - Once the state is set to SYNCDONE, the apply will continue tracking
50 : * the table until it reaches the SYNCDONE stream position, at which
51 : * point it sets state to READY and stops tracking. Again, there might
52 : * be zero changes in between.
53 : *
54 : * So the state progression is always: INIT -> DATASYNC -> FINISHEDCOPY
55 : * -> SYNCWAIT -> CATCHUP -> SYNCDONE -> READY.
56 : *
57 : * The catalog pg_subscription_rel is used to keep information about
58 : * subscribed tables and their state. The catalog holds all states
59 : * except SYNCWAIT and CATCHUP which are only in shared memory.
60 : *
61 : * Example flows look like this:
62 : * - Apply is in front:
63 : * sync:8
64 : * -> set in catalog FINISHEDCOPY
65 : * -> set in memory SYNCWAIT
66 : * apply:10
67 : * -> set in memory CATCHUP
68 : * -> enter wait-loop
69 : * sync:10
70 : * -> set in catalog SYNCDONE
71 : * -> exit
72 : * apply:10
73 : * -> exit wait-loop
74 : * -> continue rep
75 : * apply:11
76 : * -> set in catalog READY
77 : *
78 : * - Sync is in front:
79 : * sync:10
80 : * -> set in catalog FINISHEDCOPY
81 : * -> set in memory SYNCWAIT
82 : * apply:8
83 : * -> set in memory CATCHUP
84 : * -> continue per-table filtering
85 : * sync:10
86 : * -> set in catalog SYNCDONE
87 : * -> exit
88 : * apply:10
89 : * -> set in catalog READY
90 : * -> stop per-table filtering
91 : * -> continue rep
92 : *-------------------------------------------------------------------------
93 : */
94 :
95 : #include "postgres.h"
96 :
97 : #include "access/table.h"
98 : #include "access/xact.h"
99 : #include "catalog/indexing.h"
100 : #include "catalog/pg_subscription_rel.h"
101 : #include "catalog/pg_type.h"
102 : #include "commands/copy.h"
103 : #include "miscadmin.h"
104 : #include "nodes/makefuncs.h"
105 : #include "parser/parse_relation.h"
106 : #include "pgstat.h"
107 : #include "replication/logicallauncher.h"
108 : #include "replication/logicalrelation.h"
109 : #include "replication/logicalworker.h"
110 : #include "replication/origin.h"
111 : #include "replication/slot.h"
112 : #include "replication/walreceiver.h"
113 : #include "replication/worker_internal.h"
114 : #include "storage/ipc.h"
115 : #include "storage/lmgr.h"
116 : #include "utils/acl.h"
117 : #include "utils/array.h"
118 : #include "utils/builtins.h"
119 : #include "utils/lsyscache.h"
120 : #include "utils/memutils.h"
121 : #include "utils/rls.h"
122 : #include "utils/snapmgr.h"
123 : #include "utils/syscache.h"
124 : #include "utils/usercontext.h"
125 :
126 : typedef enum
127 : {
128 : SYNC_TABLE_STATE_NEEDS_REBUILD,
129 : SYNC_TABLE_STATE_REBUILD_STARTED,
130 : SYNC_TABLE_STATE_VALID,
131 : } SyncingTablesState;
132 :
133 : static SyncingTablesState table_states_validity = SYNC_TABLE_STATE_NEEDS_REBUILD;
134 : static List *table_states_not_ready = NIL;
135 : static bool FetchTableStates(bool *started_tx);
136 :
137 : static StringInfo copybuf = NULL;
138 :
139 : /*
140 : * Exit routine for synchronization worker.
141 : */
142 : pg_noreturn static void
143 354 : finish_sync_worker(void)
144 : {
145 : /*
146 : * Commit any outstanding transaction. This is the usual case, unless
147 : * there was nothing to do for the table.
148 : */
149 354 : if (IsTransactionState())
150 : {
151 354 : CommitTransactionCommand();
152 354 : pgstat_report_stat(true);
153 : }
154 :
155 : /* And flush all writes. */
156 354 : XLogFlush(GetXLogWriteRecPtr());
157 :
158 354 : StartTransactionCommand();
159 354 : ereport(LOG,
160 : (errmsg("logical replication table synchronization worker for subscription \"%s\", table \"%s\" has finished",
161 : MySubscription->name,
162 : get_rel_name(MyLogicalRepWorker->relid))));
163 354 : CommitTransactionCommand();
164 :
165 : /* Find the leader apply worker and signal it. */
166 354 : logicalrep_worker_wakeup(MyLogicalRepWorker->subid, InvalidOid);
167 :
168 : /* Stop gracefully */
169 354 : proc_exit(0);
170 : }
171 :
172 : /*
173 : * Wait until the relation sync state is set in the catalog to the expected
174 : * one; return true when it happens.
175 : *
176 : * Returns false if the table sync worker or the table itself have
177 : * disappeared, or the table state has been reset.
178 : *
179 : * Currently, this is used in the apply worker when transitioning from
180 : * CATCHUP state to SYNCDONE.
181 : */
182 : static bool
183 704 : wait_for_relation_state_change(Oid relid, char expected_state)
184 : {
185 : char state;
186 :
187 : for (;;)
188 354 : {
189 : LogicalRepWorker *worker;
190 : XLogRecPtr statelsn;
191 :
192 704 : CHECK_FOR_INTERRUPTS();
193 :
194 704 : InvalidateCatalogSnapshot();
195 704 : state = GetSubscriptionRelState(MyLogicalRepWorker->subid,
196 : relid, &statelsn);
197 :
198 704 : if (state == SUBREL_STATE_UNKNOWN)
199 0 : break;
200 :
201 704 : if (state == expected_state)
202 350 : return true;
203 :
204 : /* Check if the sync worker is still running and bail if not. */
205 354 : LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
206 354 : worker = logicalrep_worker_find(MyLogicalRepWorker->subid, relid,
207 : false);
208 354 : LWLockRelease(LogicalRepWorkerLock);
209 354 : if (!worker)
210 0 : break;
211 :
212 354 : (void) WaitLatch(MyLatch,
213 : WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
214 : 1000L, WAIT_EVENT_LOGICAL_SYNC_STATE_CHANGE);
215 :
216 354 : ResetLatch(MyLatch);
217 : }
218 :
219 0 : return false;
220 : }
221 :
222 : /*
223 : * Wait until the apply worker changes the state of our synchronization
224 : * worker to the expected one.
225 : *
226 : * Used when transitioning from SYNCWAIT state to CATCHUP.
227 : *
228 : * Returns false if the apply worker has disappeared.
229 : */
230 : static bool
231 710 : wait_for_worker_state_change(char expected_state)
232 : {
233 : int rc;
234 :
235 : for (;;)
236 356 : {
237 : LogicalRepWorker *worker;
238 :
239 710 : CHECK_FOR_INTERRUPTS();
240 :
241 : /*
242 : * Done if already in correct state. (We assume this fetch is atomic
243 : * enough to not give a misleading answer if we do it with no lock.)
244 : */
245 710 : if (MyLogicalRepWorker->relstate == expected_state)
246 354 : return true;
247 :
248 : /*
249 : * Bail out if the apply worker has died, else signal it we're
250 : * waiting.
251 : */
252 356 : LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
253 356 : worker = logicalrep_worker_find(MyLogicalRepWorker->subid,
254 : InvalidOid, false);
255 356 : if (worker && worker->proc)
256 356 : logicalrep_worker_wakeup_ptr(worker);
257 356 : LWLockRelease(LogicalRepWorkerLock);
258 356 : if (!worker)
259 0 : break;
260 :
261 : /*
262 : * Wait. We expect to get a latch signal back from the apply worker,
263 : * but use a timeout in case it dies without sending one.
264 : */
265 356 : rc = WaitLatch(MyLatch,
266 : WL_LATCH_SET | WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
267 : 1000L, WAIT_EVENT_LOGICAL_SYNC_STATE_CHANGE);
268 :
269 356 : if (rc & WL_LATCH_SET)
270 356 : ResetLatch(MyLatch);
271 : }
272 :
273 0 : return false;
274 : }
275 :
276 : /*
277 : * Callback from syscache invalidation.
278 : */
279 : void
280 3300 : invalidate_syncing_table_states(Datum arg, int cacheid, uint32 hashvalue)
281 : {
282 3300 : table_states_validity = SYNC_TABLE_STATE_NEEDS_REBUILD;
283 3300 : }
284 :
285 : /*
286 : * Handle table synchronization cooperation from the synchronization
287 : * worker.
288 : *
289 : * If the sync worker is in CATCHUP state and reached (or passed) the
290 : * predetermined synchronization point in the WAL stream, mark the table as
291 : * SYNCDONE and finish.
292 : */
293 : static void
294 378 : process_syncing_tables_for_sync(XLogRecPtr current_lsn)
295 : {
296 378 : SpinLockAcquire(&MyLogicalRepWorker->relmutex);
297 :
298 378 : if (MyLogicalRepWorker->relstate == SUBREL_STATE_CATCHUP &&
299 378 : current_lsn >= MyLogicalRepWorker->relstate_lsn)
300 : {
301 : TimeLineID tli;
302 354 : char syncslotname[NAMEDATALEN] = {0};
303 354 : char originname[NAMEDATALEN] = {0};
304 :
305 354 : MyLogicalRepWorker->relstate = SUBREL_STATE_SYNCDONE;
306 354 : MyLogicalRepWorker->relstate_lsn = current_lsn;
307 :
308 354 : SpinLockRelease(&MyLogicalRepWorker->relmutex);
309 :
310 : /*
311 : * UpdateSubscriptionRelState must be called within a transaction.
312 : */
313 354 : if (!IsTransactionState())
314 354 : StartTransactionCommand();
315 :
316 354 : UpdateSubscriptionRelState(MyLogicalRepWorker->subid,
317 354 : MyLogicalRepWorker->relid,
318 354 : MyLogicalRepWorker->relstate,
319 354 : MyLogicalRepWorker->relstate_lsn);
320 :
321 : /*
322 : * End streaming so that LogRepWorkerWalRcvConn can be used to drop
323 : * the slot.
324 : */
325 354 : walrcv_endstreaming(LogRepWorkerWalRcvConn, &tli);
326 :
327 : /*
328 : * Cleanup the tablesync slot.
329 : *
330 : * This has to be done after updating the state because otherwise if
331 : * there is an error while doing the database operations we won't be
332 : * able to rollback dropped slot.
333 : */
334 354 : ReplicationSlotNameForTablesync(MyLogicalRepWorker->subid,
335 354 : MyLogicalRepWorker->relid,
336 : syncslotname,
337 : sizeof(syncslotname));
338 :
339 : /*
340 : * It is important to give an error if we are unable to drop the slot,
341 : * otherwise, it won't be dropped till the corresponding subscription
342 : * is dropped. So passing missing_ok = false.
343 : */
344 354 : ReplicationSlotDropAtPubNode(LogRepWorkerWalRcvConn, syncslotname, false);
345 :
346 354 : CommitTransactionCommand();
347 354 : pgstat_report_stat(false);
348 :
349 : /*
350 : * Start a new transaction to clean up the tablesync origin tracking.
351 : * This transaction will be ended within the finish_sync_worker().
352 : * Now, even, if we fail to remove this here, the apply worker will
353 : * ensure to clean it up afterward.
354 : *
355 : * We need to do this after the table state is set to SYNCDONE.
356 : * Otherwise, if an error occurs while performing the database
357 : * operation, the worker will be restarted and the in-memory state of
358 : * replication progress (remote_lsn) won't be rolled-back which would
359 : * have been cleared before restart. So, the restarted worker will use
360 : * invalid replication progress state resulting in replay of
361 : * transactions that have already been applied.
362 : */
363 354 : StartTransactionCommand();
364 :
365 354 : ReplicationOriginNameForLogicalRep(MyLogicalRepWorker->subid,
366 354 : MyLogicalRepWorker->relid,
367 : originname,
368 : sizeof(originname));
369 :
370 : /*
371 : * Resetting the origin session removes the ownership of the slot.
372 : * This is needed to allow the origin to be dropped.
373 : */
374 354 : replorigin_session_reset();
375 354 : replorigin_session_origin = InvalidRepOriginId;
376 354 : replorigin_session_origin_lsn = InvalidXLogRecPtr;
377 354 : replorigin_session_origin_timestamp = 0;
378 :
379 : /*
380 : * Drop the tablesync's origin tracking if exists.
381 : *
382 : * There is a chance that the user is concurrently performing refresh
383 : * for the subscription where we remove the table state and its origin
384 : * or the apply worker would have removed this origin. So passing
385 : * missing_ok = true.
386 : */
387 354 : replorigin_drop_by_name(originname, true, false);
388 :
389 354 : finish_sync_worker();
390 : }
391 : else
392 24 : SpinLockRelease(&MyLogicalRepWorker->relmutex);
393 24 : }
394 :
395 : /*
396 : * Handle table synchronization cooperation from the apply worker.
397 : *
398 : * Walk over all subscription tables that are individually tracked by the
399 : * apply process (currently, all that have state other than
400 : * SUBREL_STATE_READY) and manage synchronization for them.
401 : *
402 : * If there are tables that need synchronizing and are not being synchronized
403 : * yet, start sync workers for them (if there are free slots for sync
404 : * workers). To prevent starting the sync worker for the same relation at a
405 : * high frequency after a failure, we store its last start time with each sync
406 : * state info. We start the sync worker for the same relation after waiting
407 : * at least wal_retrieve_retry_interval.
408 : *
409 : * For tables that are being synchronized already, check if sync workers
410 : * either need action from the apply worker or have finished. This is the
411 : * SYNCWAIT to CATCHUP transition.
412 : *
413 : * If the synchronization position is reached (SYNCDONE), then the table can
414 : * be marked as READY and is no longer tracked.
415 : */
416 : static void
417 30350 : process_syncing_tables_for_apply(XLogRecPtr current_lsn)
418 : {
419 : struct tablesync_start_time_mapping
420 : {
421 : Oid relid;
422 : TimestampTz last_start_time;
423 : };
424 : static HTAB *last_start_times = NULL;
425 : ListCell *lc;
426 30350 : bool started_tx = false;
427 30350 : bool should_exit = false;
428 :
429 : Assert(!IsTransactionState());
430 :
431 : /* We need up-to-date sync state info for subscription tables here. */
432 30350 : FetchTableStates(&started_tx);
433 :
434 : /*
435 : * Prepare a hash table for tracking last start times of workers, to avoid
436 : * immediate restarts. We don't need it if there are no tables that need
437 : * syncing.
438 : */
439 30350 : if (table_states_not_ready != NIL && !last_start_times)
440 224 : {
441 : HASHCTL ctl;
442 :
443 224 : ctl.keysize = sizeof(Oid);
444 224 : ctl.entrysize = sizeof(struct tablesync_start_time_mapping);
445 224 : last_start_times = hash_create("Logical replication table sync worker start times",
446 : 256, &ctl, HASH_ELEM | HASH_BLOBS);
447 : }
448 :
449 : /*
450 : * Clean up the hash table when we're done with all tables (just to
451 : * release the bit of memory).
452 : */
453 30126 : else if (table_states_not_ready == NIL && last_start_times)
454 : {
455 170 : hash_destroy(last_start_times);
456 170 : last_start_times = NULL;
457 : }
458 :
459 : /*
460 : * Process all tables that are being synchronized.
461 : */
462 33132 : foreach(lc, table_states_not_ready)
463 : {
464 2782 : SubscriptionRelState *rstate = (SubscriptionRelState *) lfirst(lc);
465 :
466 2782 : if (rstate->state == SUBREL_STATE_SYNCDONE)
467 : {
468 : /*
469 : * Apply has caught up to the position where the table sync has
470 : * finished. Mark the table as ready so that the apply will just
471 : * continue to replicate it normally.
472 : */
473 350 : if (current_lsn >= rstate->lsn)
474 : {
475 : char originname[NAMEDATALEN];
476 :
477 350 : rstate->state = SUBREL_STATE_READY;
478 350 : rstate->lsn = current_lsn;
479 350 : if (!started_tx)
480 : {
481 12 : StartTransactionCommand();
482 12 : started_tx = true;
483 : }
484 :
485 : /*
486 : * Remove the tablesync origin tracking if exists.
487 : *
488 : * There is a chance that the user is concurrently performing
489 : * refresh for the subscription where we remove the table
490 : * state and its origin or the tablesync worker would have
491 : * already removed this origin. We can't rely on tablesync
492 : * worker to remove the origin tracking as if there is any
493 : * error while dropping we won't restart it to drop the
494 : * origin. So passing missing_ok = true.
495 : */
496 350 : ReplicationOriginNameForLogicalRep(MyLogicalRepWorker->subid,
497 : rstate->relid,
498 : originname,
499 : sizeof(originname));
500 350 : replorigin_drop_by_name(originname, true, false);
501 :
502 : /*
503 : * Update the state to READY only after the origin cleanup.
504 : */
505 350 : UpdateSubscriptionRelState(MyLogicalRepWorker->subid,
506 350 : rstate->relid, rstate->state,
507 : rstate->lsn);
508 : }
509 : }
510 : else
511 : {
512 : LogicalRepWorker *syncworker;
513 :
514 : /*
515 : * Look for a sync worker for this relation.
516 : */
517 2432 : LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
518 :
519 2432 : syncworker = logicalrep_worker_find(MyLogicalRepWorker->subid,
520 : rstate->relid, false);
521 :
522 2432 : if (syncworker)
523 : {
524 : /* Found one, update our copy of its state */
525 1132 : SpinLockAcquire(&syncworker->relmutex);
526 1132 : rstate->state = syncworker->relstate;
527 1132 : rstate->lsn = syncworker->relstate_lsn;
528 1132 : if (rstate->state == SUBREL_STATE_SYNCWAIT)
529 : {
530 : /*
531 : * Sync worker is waiting for apply. Tell sync worker it
532 : * can catchup now.
533 : */
534 350 : syncworker->relstate = SUBREL_STATE_CATCHUP;
535 350 : syncworker->relstate_lsn =
536 350 : Max(syncworker->relstate_lsn, current_lsn);
537 : }
538 1132 : SpinLockRelease(&syncworker->relmutex);
539 :
540 : /* If we told worker to catch up, wait for it. */
541 1132 : if (rstate->state == SUBREL_STATE_SYNCWAIT)
542 : {
543 : /* Signal the sync worker, as it may be waiting for us. */
544 350 : if (syncworker->proc)
545 350 : logicalrep_worker_wakeup_ptr(syncworker);
546 :
547 : /* Now safe to release the LWLock */
548 350 : LWLockRelease(LogicalRepWorkerLock);
549 :
550 350 : if (started_tx)
551 : {
552 : /*
553 : * We must commit the existing transaction to release
554 : * the existing locks before entering a busy loop.
555 : * This is required to avoid any undetected deadlocks
556 : * due to any existing lock as deadlock detector won't
557 : * be able to detect the waits on the latch.
558 : */
559 350 : CommitTransactionCommand();
560 350 : pgstat_report_stat(false);
561 : }
562 :
563 : /*
564 : * Enter busy loop and wait for synchronization worker to
565 : * reach expected state (or die trying).
566 : */
567 350 : StartTransactionCommand();
568 350 : started_tx = true;
569 :
570 350 : wait_for_relation_state_change(rstate->relid,
571 : SUBREL_STATE_SYNCDONE);
572 : }
573 : else
574 782 : LWLockRelease(LogicalRepWorkerLock);
575 : }
576 : else
577 : {
578 : /*
579 : * If there is no sync worker for this table yet, count
580 : * running sync workers for this subscription, while we have
581 : * the lock.
582 : */
583 : int nsyncworkers =
584 1300 : logicalrep_sync_worker_count(MyLogicalRepWorker->subid);
585 :
586 : /* Now safe to release the LWLock */
587 1300 : LWLockRelease(LogicalRepWorkerLock);
588 :
589 : /*
590 : * If there are free sync worker slot(s), start a new sync
591 : * worker for the table.
592 : */
593 1300 : if (nsyncworkers < max_sync_workers_per_subscription)
594 : {
595 394 : TimestampTz now = GetCurrentTimestamp();
596 : struct tablesync_start_time_mapping *hentry;
597 : bool found;
598 :
599 394 : hentry = hash_search(last_start_times, &rstate->relid,
600 : HASH_ENTER, &found);
601 :
602 426 : if (!found ||
603 32 : TimestampDifferenceExceeds(hentry->last_start_time, now,
604 : wal_retrieve_retry_interval))
605 : {
606 372 : logicalrep_worker_launch(WORKERTYPE_TABLESYNC,
607 372 : MyLogicalRepWorker->dbid,
608 372 : MySubscription->oid,
609 372 : MySubscription->name,
610 372 : MyLogicalRepWorker->userid,
611 : rstate->relid,
612 : DSM_HANDLE_INVALID);
613 372 : hentry->last_start_time = now;
614 : }
615 : }
616 : }
617 : }
618 : }
619 :
620 30350 : if (started_tx)
621 : {
622 : /*
623 : * Even when the two_phase mode is requested by the user, it remains
624 : * as 'pending' until all tablesyncs have reached READY state.
625 : *
626 : * When this happens, we restart the apply worker and (if the
627 : * conditions are still ok) then the two_phase tri-state will become
628 : * 'enabled' at that time.
629 : *
630 : * Note: If the subscription has no tables then leave the state as
631 : * PENDING, which allows ALTER SUBSCRIPTION ... REFRESH PUBLICATION to
632 : * work.
633 : */
634 1558 : if (MySubscription->twophasestate == LOGICALREP_TWOPHASE_STATE_PENDING)
635 : {
636 54 : CommandCounterIncrement(); /* make updates visible */
637 54 : if (AllTablesyncsReady())
638 : {
639 12 : ereport(LOG,
640 : (errmsg("logical replication apply worker for subscription \"%s\" will restart so that two_phase can be enabled",
641 : MySubscription->name)));
642 12 : should_exit = true;
643 : }
644 : }
645 :
646 1558 : CommitTransactionCommand();
647 1558 : pgstat_report_stat(true);
648 : }
649 :
650 30350 : if (should_exit)
651 : {
652 : /*
653 : * Reset the last-start time for this worker so that the launcher will
654 : * restart it without waiting for wal_retrieve_retry_interval.
655 : */
656 12 : ApplyLauncherForgetWorkerStartTime(MySubscription->oid);
657 :
658 12 : proc_exit(0);
659 : }
660 30338 : }
661 :
662 : /*
663 : * Process possible state change(s) of tables that are being synchronized.
664 : */
665 : void
666 30772 : process_syncing_tables(XLogRecPtr current_lsn)
667 : {
668 30772 : switch (MyLogicalRepWorker->type)
669 : {
670 44 : case WORKERTYPE_PARALLEL_APPLY:
671 :
672 : /*
673 : * Skip for parallel apply workers because they only operate on
674 : * tables that are in a READY state. See pa_can_start() and
675 : * should_apply_changes_for_rel().
676 : */
677 44 : break;
678 :
679 378 : case WORKERTYPE_TABLESYNC:
680 378 : process_syncing_tables_for_sync(current_lsn);
681 24 : break;
682 :
683 30350 : case WORKERTYPE_APPLY:
684 30350 : process_syncing_tables_for_apply(current_lsn);
685 30338 : break;
686 :
687 0 : case WORKERTYPE_UNKNOWN:
688 : /* Should never happen. */
689 0 : elog(ERROR, "Unknown worker type");
690 : }
691 30406 : }
692 :
693 : /*
694 : * Create list of columns for COPY based on logical relation mapping.
695 : */
696 : static List *
697 372 : make_copy_attnamelist(LogicalRepRelMapEntry *rel)
698 : {
699 372 : List *attnamelist = NIL;
700 : int i;
701 :
702 992 : for (i = 0; i < rel->remoterel.natts; i++)
703 : {
704 620 : attnamelist = lappend(attnamelist,
705 620 : makeString(rel->remoterel.attnames[i]));
706 : }
707 :
708 :
709 372 : return attnamelist;
710 : }
711 :
712 : /*
713 : * Data source callback for the COPY FROM, which reads from the remote
714 : * connection and passes the data back to our local COPY.
715 : */
716 : static int
717 27994 : copy_read_data(void *outbuf, int minread, int maxread)
718 : {
719 27994 : int bytesread = 0;
720 : int avail;
721 :
722 : /* If there are some leftover data from previous read, use it. */
723 27994 : avail = copybuf->len - copybuf->cursor;
724 27994 : if (avail)
725 : {
726 0 : if (avail > maxread)
727 0 : avail = maxread;
728 0 : memcpy(outbuf, ©buf->data[copybuf->cursor], avail);
729 0 : copybuf->cursor += avail;
730 0 : maxread -= avail;
731 0 : bytesread += avail;
732 : }
733 :
734 27996 : while (maxread > 0 && bytesread < minread)
735 : {
736 27996 : pgsocket fd = PGINVALID_SOCKET;
737 : int len;
738 27996 : char *buf = NULL;
739 :
740 : for (;;)
741 : {
742 : /* Try read the data. */
743 27996 : len = walrcv_receive(LogRepWorkerWalRcvConn, &buf, &fd);
744 :
745 27996 : CHECK_FOR_INTERRUPTS();
746 :
747 27996 : if (len == 0)
748 2 : break;
749 27994 : else if (len < 0)
750 27994 : return bytesread;
751 : else
752 : {
753 : /* Process the data */
754 27626 : copybuf->data = buf;
755 27626 : copybuf->len = len;
756 27626 : copybuf->cursor = 0;
757 :
758 27626 : avail = copybuf->len - copybuf->cursor;
759 27626 : if (avail > maxread)
760 0 : avail = maxread;
761 27626 : memcpy(outbuf, ©buf->data[copybuf->cursor], avail);
762 27626 : outbuf = (char *) outbuf + avail;
763 27626 : copybuf->cursor += avail;
764 27626 : maxread -= avail;
765 27626 : bytesread += avail;
766 : }
767 :
768 27626 : if (maxread <= 0 || bytesread >= minread)
769 27626 : return bytesread;
770 : }
771 :
772 : /*
773 : * Wait for more data or latch.
774 : */
775 2 : (void) WaitLatchOrSocket(MyLatch,
776 : WL_SOCKET_READABLE | WL_LATCH_SET |
777 : WL_TIMEOUT | WL_EXIT_ON_PM_DEATH,
778 : fd, 1000L, WAIT_EVENT_LOGICAL_SYNC_DATA);
779 :
780 2 : ResetLatch(MyLatch);
781 : }
782 :
783 0 : return bytesread;
784 : }
785 :
786 :
787 : /*
788 : * Get information about remote relation in similar fashion the RELATION
789 : * message provides during replication.
790 : *
791 : * This function also returns (a) the relation qualifications to be used in
792 : * the COPY command, and (b) whether the remote relation has published any
793 : * generated column.
794 : */
795 : static void
796 374 : fetch_remote_table_info(char *nspname, char *relname, LogicalRepRelation *lrel,
797 : List **qual, bool *gencol_published)
798 : {
799 : WalRcvExecResult *res;
800 : StringInfoData cmd;
801 : TupleTableSlot *slot;
802 374 : Oid tableRow[] = {OIDOID, CHAROID, CHAROID};
803 374 : Oid attrRow[] = {INT2OID, TEXTOID, OIDOID, BOOLOID, BOOLOID};
804 374 : Oid qualRow[] = {TEXTOID};
805 : bool isnull;
806 : int natt;
807 374 : StringInfo pub_names = NULL;
808 374 : Bitmapset *included_cols = NULL;
809 374 : int server_version = walrcv_server_version(LogRepWorkerWalRcvConn);
810 :
811 374 : lrel->nspname = nspname;
812 374 : lrel->relname = relname;
813 :
814 : /* First fetch Oid and replica identity. */
815 374 : initStringInfo(&cmd);
816 374 : appendStringInfo(&cmd, "SELECT c.oid, c.relreplident, c.relkind"
817 : " FROM pg_catalog.pg_class c"
818 : " INNER JOIN pg_catalog.pg_namespace n"
819 : " ON (c.relnamespace = n.oid)"
820 : " WHERE n.nspname = %s"
821 : " AND c.relname = %s",
822 : quote_literal_cstr(nspname),
823 : quote_literal_cstr(relname));
824 374 : res = walrcv_exec(LogRepWorkerWalRcvConn, cmd.data,
825 : lengthof(tableRow), tableRow);
826 :
827 374 : if (res->status != WALRCV_OK_TUPLES)
828 0 : ereport(ERROR,
829 : (errcode(ERRCODE_CONNECTION_FAILURE),
830 : errmsg("could not fetch table info for table \"%s.%s\" from publisher: %s",
831 : nspname, relname, res->err)));
832 :
833 374 : slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
834 374 : if (!tuplestore_gettupleslot(res->tuplestore, true, false, slot))
835 0 : ereport(ERROR,
836 : (errcode(ERRCODE_UNDEFINED_OBJECT),
837 : errmsg("table \"%s.%s\" not found on publisher",
838 : nspname, relname)));
839 :
840 374 : lrel->remoteid = DatumGetObjectId(slot_getattr(slot, 1, &isnull));
841 : Assert(!isnull);
842 374 : lrel->replident = DatumGetChar(slot_getattr(slot, 2, &isnull));
843 : Assert(!isnull);
844 374 : lrel->relkind = DatumGetChar(slot_getattr(slot, 3, &isnull));
845 : Assert(!isnull);
846 :
847 374 : ExecDropSingleTupleTableSlot(slot);
848 374 : walrcv_clear_result(res);
849 :
850 :
851 : /*
852 : * Get column lists for each relation.
853 : *
854 : * We need to do this before fetching info about column names and types,
855 : * so that we can skip columns that should not be replicated.
856 : */
857 374 : if (server_version >= 150000)
858 : {
859 : WalRcvExecResult *pubres;
860 : TupleTableSlot *tslot;
861 374 : Oid attrsRow[] = {INT2VECTOROID};
862 :
863 : /* Build the pub_names comma-separated string. */
864 374 : pub_names = makeStringInfo();
865 374 : GetPublicationsStr(MySubscription->publications, pub_names, true);
866 :
867 : /*
868 : * Fetch info about column lists for the relation (from all the
869 : * publications).
870 : */
871 374 : resetStringInfo(&cmd);
872 374 : appendStringInfo(&cmd,
873 : "SELECT DISTINCT"
874 : " (CASE WHEN (array_length(gpt.attrs, 1) = c.relnatts)"
875 : " THEN NULL ELSE gpt.attrs END)"
876 : " FROM pg_publication p,"
877 : " LATERAL pg_get_publication_tables(p.pubname) gpt,"
878 : " pg_class c"
879 : " WHERE gpt.relid = %u AND c.oid = gpt.relid"
880 : " AND p.pubname IN ( %s )",
881 : lrel->remoteid,
882 : pub_names->data);
883 :
884 374 : pubres = walrcv_exec(LogRepWorkerWalRcvConn, cmd.data,
885 : lengthof(attrsRow), attrsRow);
886 :
887 374 : if (pubres->status != WALRCV_OK_TUPLES)
888 0 : ereport(ERROR,
889 : (errcode(ERRCODE_CONNECTION_FAILURE),
890 : errmsg("could not fetch column list info for table \"%s.%s\" from publisher: %s",
891 : nspname, relname, pubres->err)));
892 :
893 : /*
894 : * We don't support the case where the column list is different for
895 : * the same table when combining publications. See comments atop
896 : * fetch_table_list. So there should be only one row returned.
897 : * Although we already checked this when creating the subscription, we
898 : * still need to check here in case the column list was changed after
899 : * creating the subscription and before the sync worker is started.
900 : */
901 374 : if (tuplestore_tuple_count(pubres->tuplestore) > 1)
902 0 : ereport(ERROR,
903 : errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
904 : errmsg("cannot use different column lists for table \"%s.%s\" in different publications",
905 : nspname, relname));
906 :
907 : /*
908 : * Get the column list and build a single bitmap with the attnums.
909 : *
910 : * If we find a NULL value, it means all the columns should be
911 : * replicated.
912 : */
913 374 : tslot = MakeSingleTupleTableSlot(pubres->tupledesc, &TTSOpsMinimalTuple);
914 374 : if (tuplestore_gettupleslot(pubres->tuplestore, true, false, tslot))
915 : {
916 374 : Datum cfval = slot_getattr(tslot, 1, &isnull);
917 :
918 374 : if (!isnull)
919 : {
920 : ArrayType *arr;
921 : int nelems;
922 : int16 *elems;
923 :
924 44 : arr = DatumGetArrayTypeP(cfval);
925 44 : nelems = ARR_DIMS(arr)[0];
926 44 : elems = (int16 *) ARR_DATA_PTR(arr);
927 :
928 118 : for (natt = 0; natt < nelems; natt++)
929 74 : included_cols = bms_add_member(included_cols, elems[natt]);
930 : }
931 :
932 374 : ExecClearTuple(tslot);
933 : }
934 374 : ExecDropSingleTupleTableSlot(tslot);
935 :
936 374 : walrcv_clear_result(pubres);
937 : }
938 :
939 : /*
940 : * Now fetch column names and types.
941 : */
942 374 : resetStringInfo(&cmd);
943 374 : appendStringInfo(&cmd,
944 : "SELECT a.attnum,"
945 : " a.attname,"
946 : " a.atttypid,"
947 : " a.attnum = ANY(i.indkey)");
948 :
949 : /* Generated columns can be replicated since version 18. */
950 374 : if (server_version >= 180000)
951 374 : appendStringInfo(&cmd, ", a.attgenerated != ''");
952 :
953 748 : appendStringInfo(&cmd,
954 : " FROM pg_catalog.pg_attribute a"
955 : " LEFT JOIN pg_catalog.pg_index i"
956 : " ON (i.indexrelid = pg_get_replica_identity_index(%u))"
957 : " WHERE a.attnum > 0::pg_catalog.int2"
958 : " AND NOT a.attisdropped %s"
959 : " AND a.attrelid = %u"
960 : " ORDER BY a.attnum",
961 : lrel->remoteid,
962 374 : (server_version >= 120000 && server_version < 180000 ?
963 : "AND a.attgenerated = ''" : ""),
964 : lrel->remoteid);
965 374 : res = walrcv_exec(LogRepWorkerWalRcvConn, cmd.data,
966 : server_version >= 180000 ? lengthof(attrRow) : lengthof(attrRow) - 1, attrRow);
967 :
968 374 : if (res->status != WALRCV_OK_TUPLES)
969 0 : ereport(ERROR,
970 : (errcode(ERRCODE_CONNECTION_FAILURE),
971 : errmsg("could not fetch table info for table \"%s.%s\" from publisher: %s",
972 : nspname, relname, res->err)));
973 :
974 : /* We don't know the number of rows coming, so allocate enough space. */
975 374 : lrel->attnames = palloc0(MaxTupleAttributeNumber * sizeof(char *));
976 374 : lrel->atttyps = palloc0(MaxTupleAttributeNumber * sizeof(Oid));
977 374 : lrel->attkeys = NULL;
978 :
979 : /*
980 : * Store the columns as a list of names. Ignore those that are not
981 : * present in the column list, if there is one.
982 : */
983 374 : natt = 0;
984 374 : slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
985 1062 : while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
986 : {
987 : char *rel_colname;
988 : AttrNumber attnum;
989 :
990 688 : attnum = DatumGetInt16(slot_getattr(slot, 1, &isnull));
991 : Assert(!isnull);
992 :
993 : /* If the column is not in the column list, skip it. */
994 688 : if (included_cols != NULL && !bms_is_member(attnum, included_cols))
995 : {
996 62 : ExecClearTuple(slot);
997 62 : continue;
998 : }
999 :
1000 626 : rel_colname = TextDatumGetCString(slot_getattr(slot, 2, &isnull));
1001 : Assert(!isnull);
1002 :
1003 626 : lrel->attnames[natt] = rel_colname;
1004 626 : lrel->atttyps[natt] = DatumGetObjectId(slot_getattr(slot, 3, &isnull));
1005 : Assert(!isnull);
1006 :
1007 626 : if (DatumGetBool(slot_getattr(slot, 4, &isnull)))
1008 210 : lrel->attkeys = bms_add_member(lrel->attkeys, natt);
1009 :
1010 : /* Remember if the remote table has published any generated column. */
1011 626 : if (server_version >= 180000 && !(*gencol_published))
1012 : {
1013 626 : *gencol_published = DatumGetBool(slot_getattr(slot, 5, &isnull));
1014 : Assert(!isnull);
1015 : }
1016 :
1017 : /* Should never happen. */
1018 626 : if (++natt >= MaxTupleAttributeNumber)
1019 0 : elog(ERROR, "too many columns in remote table \"%s.%s\"",
1020 : nspname, relname);
1021 :
1022 626 : ExecClearTuple(slot);
1023 : }
1024 374 : ExecDropSingleTupleTableSlot(slot);
1025 :
1026 374 : lrel->natts = natt;
1027 :
1028 374 : walrcv_clear_result(res);
1029 :
1030 : /*
1031 : * Get relation's row filter expressions. DISTINCT avoids the same
1032 : * expression of a table in multiple publications from being included
1033 : * multiple times in the final expression.
1034 : *
1035 : * We need to copy the row even if it matches just one of the
1036 : * publications, so we later combine all the quals with OR.
1037 : *
1038 : * For initial synchronization, row filtering can be ignored in following
1039 : * cases:
1040 : *
1041 : * 1) one of the subscribed publications for the table hasn't specified
1042 : * any row filter
1043 : *
1044 : * 2) one of the subscribed publications has puballtables set to true
1045 : *
1046 : * 3) one of the subscribed publications is declared as TABLES IN SCHEMA
1047 : * that includes this relation
1048 : */
1049 374 : if (server_version >= 150000)
1050 : {
1051 : /* Reuse the already-built pub_names. */
1052 : Assert(pub_names != NULL);
1053 :
1054 : /* Check for row filters. */
1055 374 : resetStringInfo(&cmd);
1056 374 : appendStringInfo(&cmd,
1057 : "SELECT DISTINCT pg_get_expr(gpt.qual, gpt.relid)"
1058 : " FROM pg_publication p,"
1059 : " LATERAL pg_get_publication_tables(p.pubname) gpt"
1060 : " WHERE gpt.relid = %u"
1061 : " AND p.pubname IN ( %s )",
1062 : lrel->remoteid,
1063 : pub_names->data);
1064 :
1065 374 : res = walrcv_exec(LogRepWorkerWalRcvConn, cmd.data, 1, qualRow);
1066 :
1067 374 : if (res->status != WALRCV_OK_TUPLES)
1068 0 : ereport(ERROR,
1069 : (errmsg("could not fetch table WHERE clause info for table \"%s.%s\" from publisher: %s",
1070 : nspname, relname, res->err)));
1071 :
1072 : /*
1073 : * Multiple row filter expressions for the same table will be combined
1074 : * by COPY using OR. If any of the filter expressions for this table
1075 : * are null, it means the whole table will be copied. In this case it
1076 : * is not necessary to construct a unified row filter expression at
1077 : * all.
1078 : */
1079 374 : slot = MakeSingleTupleTableSlot(res->tupledesc, &TTSOpsMinimalTuple);
1080 404 : while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
1081 : {
1082 382 : Datum rf = slot_getattr(slot, 1, &isnull);
1083 :
1084 382 : if (!isnull)
1085 30 : *qual = lappend(*qual, makeString(TextDatumGetCString(rf)));
1086 : else
1087 : {
1088 : /* Ignore filters and cleanup as necessary. */
1089 352 : if (*qual)
1090 : {
1091 6 : list_free_deep(*qual);
1092 6 : *qual = NIL;
1093 : }
1094 352 : break;
1095 : }
1096 :
1097 30 : ExecClearTuple(slot);
1098 : }
1099 374 : ExecDropSingleTupleTableSlot(slot);
1100 :
1101 374 : walrcv_clear_result(res);
1102 374 : destroyStringInfo(pub_names);
1103 : }
1104 :
1105 374 : pfree(cmd.data);
1106 374 : }
1107 :
1108 : /*
1109 : * Copy existing data of a table from publisher.
1110 : *
1111 : * Caller is responsible for locking the local relation.
1112 : */
1113 : static void
1114 374 : copy_table(Relation rel)
1115 : {
1116 : LogicalRepRelMapEntry *relmapentry;
1117 : LogicalRepRelation lrel;
1118 374 : List *qual = NIL;
1119 : WalRcvExecResult *res;
1120 : StringInfoData cmd;
1121 : CopyFromState cstate;
1122 : List *attnamelist;
1123 : ParseState *pstate;
1124 374 : List *options = NIL;
1125 374 : bool gencol_published = false;
1126 :
1127 : /* Get the publisher relation info. */
1128 374 : fetch_remote_table_info(get_namespace_name(RelationGetNamespace(rel)),
1129 374 : RelationGetRelationName(rel), &lrel, &qual,
1130 : &gencol_published);
1131 :
1132 : /* Put the relation into relmap. */
1133 374 : logicalrep_relmap_update(&lrel);
1134 :
1135 : /* Map the publisher relation to local one. */
1136 374 : relmapentry = logicalrep_rel_open(lrel.remoteid, NoLock);
1137 : Assert(rel == relmapentry->localrel);
1138 :
1139 : /* Start copy on the publisher. */
1140 372 : initStringInfo(&cmd);
1141 :
1142 : /* Regular table with no row filter or generated columns */
1143 372 : if (lrel.relkind == RELKIND_RELATION && qual == NIL && !gencol_published)
1144 : {
1145 316 : appendStringInfo(&cmd, "COPY %s",
1146 316 : quote_qualified_identifier(lrel.nspname, lrel.relname));
1147 :
1148 : /* If the table has columns, then specify the columns */
1149 316 : if (lrel.natts)
1150 : {
1151 314 : appendStringInfoString(&cmd, " (");
1152 :
1153 : /*
1154 : * XXX Do we need to list the columns in all cases? Maybe we're
1155 : * replicating all columns?
1156 : */
1157 850 : for (int i = 0; i < lrel.natts; i++)
1158 : {
1159 536 : if (i > 0)
1160 222 : appendStringInfoString(&cmd, ", ");
1161 :
1162 536 : appendStringInfoString(&cmd, quote_identifier(lrel.attnames[i]));
1163 : }
1164 :
1165 314 : appendStringInfoChar(&cmd, ')');
1166 : }
1167 :
1168 316 : appendStringInfoString(&cmd, " TO STDOUT");
1169 : }
1170 : else
1171 : {
1172 : /*
1173 : * For non-tables and tables with row filters, we need to do COPY
1174 : * (SELECT ...), but we can't just do SELECT * because we may need to
1175 : * copy only subset of columns including generated columns. For tables
1176 : * with any row filters, build a SELECT query with OR'ed row filters
1177 : * for COPY.
1178 : *
1179 : * We also need to use this same COPY (SELECT ...) syntax when
1180 : * generated columns are published, because copy of generated columns
1181 : * is not supported by the normal COPY.
1182 : */
1183 56 : appendStringInfoString(&cmd, "COPY (SELECT ");
1184 140 : for (int i = 0; i < lrel.natts; i++)
1185 : {
1186 84 : appendStringInfoString(&cmd, quote_identifier(lrel.attnames[i]));
1187 84 : if (i < lrel.natts - 1)
1188 28 : appendStringInfoString(&cmd, ", ");
1189 : }
1190 :
1191 56 : appendStringInfoString(&cmd, " FROM ");
1192 :
1193 : /*
1194 : * For regular tables, make sure we don't copy data from a child that
1195 : * inherits the named table as those will be copied separately.
1196 : */
1197 56 : if (lrel.relkind == RELKIND_RELATION)
1198 22 : appendStringInfoString(&cmd, "ONLY ");
1199 :
1200 56 : appendStringInfoString(&cmd, quote_qualified_identifier(lrel.nspname, lrel.relname));
1201 : /* list of OR'ed filters */
1202 56 : if (qual != NIL)
1203 : {
1204 : ListCell *lc;
1205 22 : char *q = strVal(linitial(qual));
1206 :
1207 22 : appendStringInfo(&cmd, " WHERE %s", q);
1208 24 : for_each_from(lc, qual, 1)
1209 : {
1210 2 : q = strVal(lfirst(lc));
1211 2 : appendStringInfo(&cmd, " OR %s", q);
1212 : }
1213 22 : list_free_deep(qual);
1214 : }
1215 :
1216 56 : appendStringInfoString(&cmd, ") TO STDOUT");
1217 : }
1218 :
1219 : /*
1220 : * Prior to v16, initial table synchronization will use text format even
1221 : * if the binary option is enabled for a subscription.
1222 : */
1223 372 : if (walrcv_server_version(LogRepWorkerWalRcvConn) >= 160000 &&
1224 372 : MySubscription->binary)
1225 : {
1226 10 : appendStringInfoString(&cmd, " WITH (FORMAT binary)");
1227 10 : options = list_make1(makeDefElem("format",
1228 : (Node *) makeString("binary"), -1));
1229 : }
1230 :
1231 372 : res = walrcv_exec(LogRepWorkerWalRcvConn, cmd.data, 0, NULL);
1232 372 : pfree(cmd.data);
1233 372 : if (res->status != WALRCV_OK_COPY_OUT)
1234 0 : ereport(ERROR,
1235 : (errcode(ERRCODE_CONNECTION_FAILURE),
1236 : errmsg("could not start initial contents copy for table \"%s.%s\": %s",
1237 : lrel.nspname, lrel.relname, res->err)));
1238 372 : walrcv_clear_result(res);
1239 :
1240 372 : copybuf = makeStringInfo();
1241 :
1242 372 : pstate = make_parsestate(NULL);
1243 372 : (void) addRangeTableEntryForRelation(pstate, rel, AccessShareLock,
1244 : NULL, false, false);
1245 :
1246 372 : attnamelist = make_copy_attnamelist(relmapentry);
1247 372 : cstate = BeginCopyFrom(pstate, rel, NULL, NULL, false, copy_read_data, attnamelist, options);
1248 :
1249 : /* Do the copy */
1250 370 : (void) CopyFrom(cstate);
1251 :
1252 354 : logicalrep_rel_close(relmapentry, NoLock);
1253 354 : }
1254 :
1255 : /*
1256 : * Determine the tablesync slot name.
1257 : *
1258 : * The name must not exceed NAMEDATALEN - 1 because of remote node constraints
1259 : * on slot name length. We append system_identifier to avoid slot_name
1260 : * collision with subscriptions in other clusters. With the current scheme
1261 : * pg_%u_sync_%u_UINT64_FORMAT (3 + 10 + 6 + 10 + 20 + '\0'), the maximum
1262 : * length of slot_name will be 50.
1263 : *
1264 : * The returned slot name is stored in the supplied buffer (syncslotname) with
1265 : * the given size.
1266 : *
1267 : * Note: We don't use the subscription slot name as part of tablesync slot name
1268 : * because we are responsible for cleaning up these slots and it could become
1269 : * impossible to recalculate what name to cleanup if the subscription slot name
1270 : * had changed.
1271 : */
1272 : void
1273 740 : ReplicationSlotNameForTablesync(Oid suboid, Oid relid,
1274 : char *syncslotname, Size szslot)
1275 : {
1276 740 : snprintf(syncslotname, szslot, "pg_%u_sync_%u_" UINT64_FORMAT, suboid,
1277 : relid, GetSystemIdentifier());
1278 740 : }
1279 :
1280 : /*
1281 : * Start syncing the table in the sync worker.
1282 : *
1283 : * If nothing needs to be done to sync the table, we exit the worker without
1284 : * any further action.
1285 : *
1286 : * The returned slot name is palloc'ed in current memory context.
1287 : */
1288 : static char *
1289 376 : LogicalRepSyncTableStart(XLogRecPtr *origin_startpos)
1290 : {
1291 : char *slotname;
1292 : char *err;
1293 : char relstate;
1294 : XLogRecPtr relstate_lsn;
1295 : Relation rel;
1296 : AclResult aclresult;
1297 : WalRcvExecResult *res;
1298 : char originname[NAMEDATALEN];
1299 : RepOriginId originid;
1300 : UserContext ucxt;
1301 : bool must_use_password;
1302 : bool run_as_owner;
1303 :
1304 : /* Check the state of the table synchronization. */
1305 376 : StartTransactionCommand();
1306 376 : relstate = GetSubscriptionRelState(MyLogicalRepWorker->subid,
1307 376 : MyLogicalRepWorker->relid,
1308 : &relstate_lsn);
1309 376 : CommitTransactionCommand();
1310 :
1311 : /* Is the use of a password mandatory? */
1312 744 : must_use_password = MySubscription->passwordrequired &&
1313 368 : !MySubscription->ownersuperuser;
1314 :
1315 376 : SpinLockAcquire(&MyLogicalRepWorker->relmutex);
1316 376 : MyLogicalRepWorker->relstate = relstate;
1317 376 : MyLogicalRepWorker->relstate_lsn = relstate_lsn;
1318 376 : SpinLockRelease(&MyLogicalRepWorker->relmutex);
1319 :
1320 : /*
1321 : * If synchronization is already done or no longer necessary, exit now
1322 : * that we've updated shared memory state.
1323 : */
1324 376 : switch (relstate)
1325 : {
1326 0 : case SUBREL_STATE_SYNCDONE:
1327 : case SUBREL_STATE_READY:
1328 : case SUBREL_STATE_UNKNOWN:
1329 0 : finish_sync_worker(); /* doesn't return */
1330 : }
1331 :
1332 : /* Calculate the name of the tablesync slot. */
1333 376 : slotname = (char *) palloc(NAMEDATALEN);
1334 376 : ReplicationSlotNameForTablesync(MySubscription->oid,
1335 376 : MyLogicalRepWorker->relid,
1336 : slotname,
1337 : NAMEDATALEN);
1338 :
1339 : /*
1340 : * Here we use the slot name instead of the subscription name as the
1341 : * application_name, so that it is different from the leader apply worker,
1342 : * so that synchronous replication can distinguish them.
1343 : */
1344 376 : LogRepWorkerWalRcvConn =
1345 376 : walrcv_connect(MySubscription->conninfo, true, true,
1346 : must_use_password,
1347 : slotname, &err);
1348 376 : if (LogRepWorkerWalRcvConn == NULL)
1349 0 : ereport(ERROR,
1350 : (errcode(ERRCODE_CONNECTION_FAILURE),
1351 : errmsg("table synchronization worker for subscription \"%s\" could not connect to the publisher: %s",
1352 : MySubscription->name, err)));
1353 :
1354 : Assert(MyLogicalRepWorker->relstate == SUBREL_STATE_INIT ||
1355 : MyLogicalRepWorker->relstate == SUBREL_STATE_DATASYNC ||
1356 : MyLogicalRepWorker->relstate == SUBREL_STATE_FINISHEDCOPY);
1357 :
1358 : /* Assign the origin tracking record name. */
1359 376 : ReplicationOriginNameForLogicalRep(MySubscription->oid,
1360 376 : MyLogicalRepWorker->relid,
1361 : originname,
1362 : sizeof(originname));
1363 :
1364 376 : if (MyLogicalRepWorker->relstate == SUBREL_STATE_DATASYNC)
1365 : {
1366 : /*
1367 : * We have previously errored out before finishing the copy so the
1368 : * replication slot might exist. We want to remove the slot if it
1369 : * already exists and proceed.
1370 : *
1371 : * XXX We could also instead try to drop the slot, last time we failed
1372 : * but for that, we might need to clean up the copy state as it might
1373 : * be in the middle of fetching the rows. Also, if there is a network
1374 : * breakdown then it wouldn't have succeeded so trying it next time
1375 : * seems like a better bet.
1376 : */
1377 16 : ReplicationSlotDropAtPubNode(LogRepWorkerWalRcvConn, slotname, true);
1378 : }
1379 360 : else if (MyLogicalRepWorker->relstate == SUBREL_STATE_FINISHEDCOPY)
1380 : {
1381 : /*
1382 : * The COPY phase was previously done, but tablesync then crashed
1383 : * before it was able to finish normally.
1384 : */
1385 0 : StartTransactionCommand();
1386 :
1387 : /*
1388 : * The origin tracking name must already exist. It was created first
1389 : * time this tablesync was launched.
1390 : */
1391 0 : originid = replorigin_by_name(originname, false);
1392 0 : replorigin_session_setup(originid, 0);
1393 0 : replorigin_session_origin = originid;
1394 0 : *origin_startpos = replorigin_session_get_progress(false);
1395 :
1396 0 : CommitTransactionCommand();
1397 :
1398 0 : goto copy_table_done;
1399 : }
1400 :
1401 376 : SpinLockAcquire(&MyLogicalRepWorker->relmutex);
1402 376 : MyLogicalRepWorker->relstate = SUBREL_STATE_DATASYNC;
1403 376 : MyLogicalRepWorker->relstate_lsn = InvalidXLogRecPtr;
1404 376 : SpinLockRelease(&MyLogicalRepWorker->relmutex);
1405 :
1406 : /* Update the state and make it visible to others. */
1407 376 : StartTransactionCommand();
1408 376 : UpdateSubscriptionRelState(MyLogicalRepWorker->subid,
1409 376 : MyLogicalRepWorker->relid,
1410 376 : MyLogicalRepWorker->relstate,
1411 376 : MyLogicalRepWorker->relstate_lsn);
1412 374 : CommitTransactionCommand();
1413 374 : pgstat_report_stat(true);
1414 :
1415 374 : StartTransactionCommand();
1416 :
1417 : /*
1418 : * Use a standard write lock here. It might be better to disallow access
1419 : * to the table while it's being synchronized. But we don't want to block
1420 : * the main apply process from working and it has to open the relation in
1421 : * RowExclusiveLock when remapping remote relation id to local one.
1422 : */
1423 374 : rel = table_open(MyLogicalRepWorker->relid, RowExclusiveLock);
1424 :
1425 : /*
1426 : * Start a transaction in the remote node in REPEATABLE READ mode. This
1427 : * ensures that both the replication slot we create (see below) and the
1428 : * COPY are consistent with each other.
1429 : */
1430 374 : res = walrcv_exec(LogRepWorkerWalRcvConn,
1431 : "BEGIN READ ONLY ISOLATION LEVEL REPEATABLE READ",
1432 : 0, NULL);
1433 374 : if (res->status != WALRCV_OK_COMMAND)
1434 0 : ereport(ERROR,
1435 : (errcode(ERRCODE_CONNECTION_FAILURE),
1436 : errmsg("table copy could not start transaction on publisher: %s",
1437 : res->err)));
1438 374 : walrcv_clear_result(res);
1439 :
1440 : /*
1441 : * Create a new permanent logical decoding slot. This slot will be used
1442 : * for the catchup phase after COPY is done, so tell it to use the
1443 : * snapshot to make the final data consistent.
1444 : */
1445 374 : walrcv_create_slot(LogRepWorkerWalRcvConn,
1446 : slotname, false /* permanent */ , false /* two_phase */ ,
1447 : MySubscription->failover,
1448 : CRS_USE_SNAPSHOT, origin_startpos);
1449 :
1450 : /*
1451 : * Setup replication origin tracking. The purpose of doing this before the
1452 : * copy is to avoid doing the copy again due to any error in setting up
1453 : * origin tracking.
1454 : */
1455 374 : originid = replorigin_by_name(originname, true);
1456 374 : if (!OidIsValid(originid))
1457 : {
1458 : /*
1459 : * Origin tracking does not exist, so create it now.
1460 : *
1461 : * Then advance to the LSN got from walrcv_create_slot. This is WAL
1462 : * logged for the purpose of recovery. Locks are to prevent the
1463 : * replication origin from vanishing while advancing.
1464 : */
1465 374 : originid = replorigin_create(originname);
1466 :
1467 374 : LockRelationOid(ReplicationOriginRelationId, RowExclusiveLock);
1468 374 : replorigin_advance(originid, *origin_startpos, InvalidXLogRecPtr,
1469 : true /* go backward */ , true /* WAL log */ );
1470 374 : UnlockRelationOid(ReplicationOriginRelationId, RowExclusiveLock);
1471 :
1472 374 : replorigin_session_setup(originid, 0);
1473 374 : replorigin_session_origin = originid;
1474 : }
1475 : else
1476 : {
1477 0 : ereport(ERROR,
1478 : (errcode(ERRCODE_DUPLICATE_OBJECT),
1479 : errmsg("replication origin \"%s\" already exists",
1480 : originname)));
1481 : }
1482 :
1483 : /*
1484 : * Make sure that the copy command runs as the table owner, unless the
1485 : * user has opted out of that behaviour.
1486 : */
1487 374 : run_as_owner = MySubscription->runasowner;
1488 374 : if (!run_as_owner)
1489 372 : SwitchToUntrustedUser(rel->rd_rel->relowner, &ucxt);
1490 :
1491 : /*
1492 : * Check that our table sync worker has permission to insert into the
1493 : * target table.
1494 : */
1495 374 : aclresult = pg_class_aclcheck(RelationGetRelid(rel), GetUserId(),
1496 : ACL_INSERT);
1497 374 : if (aclresult != ACLCHECK_OK)
1498 0 : aclcheck_error(aclresult,
1499 0 : get_relkind_objtype(rel->rd_rel->relkind),
1500 0 : RelationGetRelationName(rel));
1501 :
1502 : /*
1503 : * COPY FROM does not honor RLS policies. That is not a problem for
1504 : * subscriptions owned by roles with BYPASSRLS privilege (or superuser,
1505 : * who has it implicitly), but other roles should not be able to
1506 : * circumvent RLS. Disallow logical replication into RLS enabled
1507 : * relations for such roles.
1508 : */
1509 374 : if (check_enable_rls(RelationGetRelid(rel), InvalidOid, false) == RLS_ENABLED)
1510 0 : ereport(ERROR,
1511 : (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
1512 : errmsg("user \"%s\" cannot replicate into relation with row-level security enabled: \"%s\"",
1513 : GetUserNameFromId(GetUserId(), true),
1514 : RelationGetRelationName(rel))));
1515 :
1516 : /* Now do the initial data copy */
1517 374 : PushActiveSnapshot(GetTransactionSnapshot());
1518 374 : copy_table(rel);
1519 354 : PopActiveSnapshot();
1520 :
1521 354 : res = walrcv_exec(LogRepWorkerWalRcvConn, "COMMIT", 0, NULL);
1522 354 : if (res->status != WALRCV_OK_COMMAND)
1523 0 : ereport(ERROR,
1524 : (errcode(ERRCODE_CONNECTION_FAILURE),
1525 : errmsg("table copy could not finish transaction on publisher: %s",
1526 : res->err)));
1527 354 : walrcv_clear_result(res);
1528 :
1529 354 : if (!run_as_owner)
1530 352 : RestoreUserContext(&ucxt);
1531 :
1532 354 : table_close(rel, NoLock);
1533 :
1534 : /* Make the copy visible. */
1535 354 : CommandCounterIncrement();
1536 :
1537 : /*
1538 : * Update the persisted state to indicate the COPY phase is done; make it
1539 : * visible to others.
1540 : */
1541 354 : UpdateSubscriptionRelState(MyLogicalRepWorker->subid,
1542 354 : MyLogicalRepWorker->relid,
1543 : SUBREL_STATE_FINISHEDCOPY,
1544 354 : MyLogicalRepWorker->relstate_lsn);
1545 :
1546 354 : CommitTransactionCommand();
1547 :
1548 354 : copy_table_done:
1549 :
1550 354 : elog(DEBUG1,
1551 : "LogicalRepSyncTableStart: '%s' origin_startpos lsn %X/%X",
1552 : originname, LSN_FORMAT_ARGS(*origin_startpos));
1553 :
1554 : /*
1555 : * We are done with the initial data synchronization, update the state.
1556 : */
1557 354 : SpinLockAcquire(&MyLogicalRepWorker->relmutex);
1558 354 : MyLogicalRepWorker->relstate = SUBREL_STATE_SYNCWAIT;
1559 354 : MyLogicalRepWorker->relstate_lsn = *origin_startpos;
1560 354 : SpinLockRelease(&MyLogicalRepWorker->relmutex);
1561 :
1562 : /*
1563 : * Finally, wait until the leader apply worker tells us to catch up and
1564 : * then return to let LogicalRepApplyLoop do it.
1565 : */
1566 354 : wait_for_worker_state_change(SUBREL_STATE_CATCHUP);
1567 354 : return slotname;
1568 : }
1569 :
1570 : /*
1571 : * Common code to fetch the up-to-date sync state info into the static lists.
1572 : *
1573 : * Returns true if subscription has 1 or more tables, else false.
1574 : *
1575 : * Note: If this function started the transaction (indicated by the parameter)
1576 : * then it is the caller's responsibility to commit it.
1577 : */
1578 : static bool
1579 30488 : FetchTableStates(bool *started_tx)
1580 : {
1581 : static bool has_subrels = false;
1582 :
1583 30488 : *started_tx = false;
1584 :
1585 30488 : if (table_states_validity != SYNC_TABLE_STATE_VALID)
1586 : {
1587 : MemoryContext oldctx;
1588 : List *rstates;
1589 : ListCell *lc;
1590 : SubscriptionRelState *rstate;
1591 :
1592 1610 : table_states_validity = SYNC_TABLE_STATE_REBUILD_STARTED;
1593 :
1594 : /* Clean the old lists. */
1595 1610 : list_free_deep(table_states_not_ready);
1596 1610 : table_states_not_ready = NIL;
1597 :
1598 1610 : if (!IsTransactionState())
1599 : {
1600 1576 : StartTransactionCommand();
1601 1576 : *started_tx = true;
1602 : }
1603 :
1604 : /* Fetch all non-ready tables. */
1605 1610 : rstates = GetSubscriptionRelations(MySubscription->oid, true);
1606 :
1607 : /* Allocate the tracking info in a permanent memory context. */
1608 1610 : oldctx = MemoryContextSwitchTo(CacheMemoryContext);
1609 4108 : foreach(lc, rstates)
1610 : {
1611 2498 : rstate = palloc(sizeof(SubscriptionRelState));
1612 2498 : memcpy(rstate, lfirst(lc), sizeof(SubscriptionRelState));
1613 2498 : table_states_not_ready = lappend(table_states_not_ready, rstate);
1614 : }
1615 1610 : MemoryContextSwitchTo(oldctx);
1616 :
1617 : /*
1618 : * Does the subscription have tables?
1619 : *
1620 : * If there were not-READY relations found then we know it does. But
1621 : * if table_states_not_ready was empty we still need to check again to
1622 : * see if there are 0 tables.
1623 : */
1624 2038 : has_subrels = (table_states_not_ready != NIL) ||
1625 428 : HasSubscriptionRelations(MySubscription->oid);
1626 :
1627 : /*
1628 : * If the subscription relation cache has been invalidated since we
1629 : * entered this routine, we still use and return the relations we just
1630 : * finished constructing, to avoid infinite loops, but we leave the
1631 : * table states marked as stale so that we'll rebuild it again on next
1632 : * access. Otherwise, we mark the table states as valid.
1633 : */
1634 1610 : if (table_states_validity == SYNC_TABLE_STATE_REBUILD_STARTED)
1635 1610 : table_states_validity = SYNC_TABLE_STATE_VALID;
1636 : }
1637 :
1638 30488 : return has_subrels;
1639 : }
1640 :
1641 : /*
1642 : * Execute the initial sync with error handling. Disable the subscription,
1643 : * if it's required.
1644 : *
1645 : * Allocate the slot name in long-lived context on return. Note that we don't
1646 : * handle FATAL errors which are probably because of system resource error and
1647 : * are not repeatable.
1648 : */
1649 : static void
1650 376 : start_table_sync(XLogRecPtr *origin_startpos, char **slotname)
1651 : {
1652 376 : char *sync_slotname = NULL;
1653 :
1654 : Assert(am_tablesync_worker());
1655 :
1656 376 : PG_TRY();
1657 : {
1658 : /* Call initial sync. */
1659 376 : sync_slotname = LogicalRepSyncTableStart(origin_startpos);
1660 : }
1661 20 : PG_CATCH();
1662 : {
1663 20 : if (MySubscription->disableonerr)
1664 2 : DisableSubscriptionAndExit();
1665 : else
1666 : {
1667 : /*
1668 : * Report the worker failed during table synchronization. Abort
1669 : * the current transaction so that the stats message is sent in an
1670 : * idle state.
1671 : */
1672 18 : AbortOutOfAnyTransaction();
1673 18 : pgstat_report_subscription_error(MySubscription->oid, false);
1674 :
1675 18 : PG_RE_THROW();
1676 : }
1677 : }
1678 354 : PG_END_TRY();
1679 :
1680 : /* allocate slot name in long-lived context */
1681 354 : *slotname = MemoryContextStrdup(ApplyContext, sync_slotname);
1682 354 : pfree(sync_slotname);
1683 354 : }
1684 :
1685 : /*
1686 : * Runs the tablesync worker.
1687 : *
1688 : * It starts syncing tables. After a successful sync, sets streaming options
1689 : * and starts streaming to catchup with apply worker.
1690 : */
1691 : static void
1692 376 : run_tablesync_worker()
1693 : {
1694 : char originname[NAMEDATALEN];
1695 376 : XLogRecPtr origin_startpos = InvalidXLogRecPtr;
1696 376 : char *slotname = NULL;
1697 : WalRcvStreamOptions options;
1698 :
1699 376 : start_table_sync(&origin_startpos, &slotname);
1700 :
1701 354 : ReplicationOriginNameForLogicalRep(MySubscription->oid,
1702 354 : MyLogicalRepWorker->relid,
1703 : originname,
1704 : sizeof(originname));
1705 :
1706 354 : set_apply_error_context_origin(originname);
1707 :
1708 354 : set_stream_options(&options, slotname, &origin_startpos);
1709 :
1710 354 : walrcv_startstreaming(LogRepWorkerWalRcvConn, &options);
1711 :
1712 : /* Apply the changes till we catchup with the apply worker. */
1713 354 : start_apply(origin_startpos);
1714 0 : }
1715 :
1716 : /* Logical Replication Tablesync worker entry point */
1717 : void
1718 376 : TablesyncWorkerMain(Datum main_arg)
1719 : {
1720 376 : int worker_slot = DatumGetInt32(main_arg);
1721 :
1722 376 : SetupApplyOrSyncWorker(worker_slot);
1723 :
1724 376 : run_tablesync_worker();
1725 :
1726 0 : finish_sync_worker();
1727 : }
1728 :
1729 : /*
1730 : * If the subscription has no tables then return false.
1731 : *
1732 : * Otherwise, are all tablesyncs READY?
1733 : *
1734 : * Note: This function is not suitable to be called from outside of apply or
1735 : * tablesync workers because MySubscription needs to be already initialized.
1736 : */
1737 : bool
1738 138 : AllTablesyncsReady(void)
1739 : {
1740 138 : bool started_tx = false;
1741 138 : bool has_subrels = false;
1742 :
1743 : /* We need up-to-date sync state info for subscription tables here. */
1744 138 : has_subrels = FetchTableStates(&started_tx);
1745 :
1746 138 : if (started_tx)
1747 : {
1748 30 : CommitTransactionCommand();
1749 30 : pgstat_report_stat(true);
1750 : }
1751 :
1752 : /*
1753 : * Return false when there are no tables in subscription or not all tables
1754 : * are in ready state; true otherwise.
1755 : */
1756 138 : return has_subrels && (table_states_not_ready == NIL);
1757 : }
1758 :
1759 : /*
1760 : * Update the two_phase state of the specified subscription in pg_subscription.
1761 : */
1762 : void
1763 18 : UpdateTwoPhaseState(Oid suboid, char new_state)
1764 : {
1765 : Relation rel;
1766 : HeapTuple tup;
1767 : bool nulls[Natts_pg_subscription];
1768 : bool replaces[Natts_pg_subscription];
1769 : Datum values[Natts_pg_subscription];
1770 :
1771 : Assert(new_state == LOGICALREP_TWOPHASE_STATE_DISABLED ||
1772 : new_state == LOGICALREP_TWOPHASE_STATE_PENDING ||
1773 : new_state == LOGICALREP_TWOPHASE_STATE_ENABLED);
1774 :
1775 18 : rel = table_open(SubscriptionRelationId, RowExclusiveLock);
1776 18 : tup = SearchSysCacheCopy1(SUBSCRIPTIONOID, ObjectIdGetDatum(suboid));
1777 18 : if (!HeapTupleIsValid(tup))
1778 0 : elog(ERROR,
1779 : "cache lookup failed for subscription oid %u",
1780 : suboid);
1781 :
1782 : /* Form a new tuple. */
1783 18 : memset(values, 0, sizeof(values));
1784 18 : memset(nulls, false, sizeof(nulls));
1785 18 : memset(replaces, false, sizeof(replaces));
1786 :
1787 : /* And update/set two_phase state */
1788 18 : values[Anum_pg_subscription_subtwophasestate - 1] = CharGetDatum(new_state);
1789 18 : replaces[Anum_pg_subscription_subtwophasestate - 1] = true;
1790 :
1791 18 : tup = heap_modify_tuple(tup, RelationGetDescr(rel),
1792 : values, nulls, replaces);
1793 18 : CatalogTupleUpdate(rel, &tup->t_self, tup);
1794 :
1795 18 : heap_freetuple(tup);
1796 18 : table_close(rel, RowExclusiveLock);
1797 18 : }
|