PostgreSQL Source Code  git master
tablesync.c
Go to the documentation of this file.
1 /*-------------------------------------------------------------------------
2  * tablesync.c
3  * PostgreSQL logical replication: initial table data synchronization
4  *
5  * Copyright (c) 2012-2021, 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 main 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"
100 #include "catalog/pg_type.h"
101 #include "commands/copy.h"
102 #include "miscadmin.h"
103 #include "parser/parse_relation.h"
104 #include "pgstat.h"
107 #include "replication/walreceiver.h"
109 #include "replication/slot.h"
110 #include "replication/origin.h"
111 #include "storage/ipc.h"
112 #include "storage/lmgr.h"
113 #include "utils/builtins.h"
114 #include "utils/lsyscache.h"
115 #include "utils/memutils.h"
116 #include "utils/snapmgr.h"
117 
118 static bool table_states_valid = false;
119 
121 
122 /*
123  * Exit routine for synchronization worker.
124  */
125 static void
127 finish_sync_worker(void)
128 {
129  /*
130  * Commit any outstanding transaction. This is the usual case, unless
131  * there was nothing to do for the table.
132  */
133  if (IsTransactionState())
134  {
136  pgstat_report_stat(false);
137  }
138 
139  /* And flush all writes. */
141 
143  ereport(LOG,
144  (errmsg("logical replication table synchronization worker for subscription \"%s\", table \"%s\" has finished",
148 
149  /* Find the main apply worker and signal it. */
151 
152  /* Stop gracefully */
153  proc_exit(0);
154 }
155 
156 /*
157  * Wait until the relation sync state is set in the catalog to the expected
158  * one; return true when it happens.
159  *
160  * Returns false if the table sync worker or the table itself have
161  * disappeared, or the table state has been reset.
162  *
163  * Currently, this is used in the apply worker when transitioning from
164  * CATCHUP state to SYNCDONE.
165  */
166 static bool
167 wait_for_relation_state_change(Oid relid, char expected_state)
168 {
169  char state;
170 
171  for (;;)
172  {
173  LogicalRepWorker *worker;
174  XLogRecPtr statelsn;
175 
177 
180  relid, &statelsn);
181 
182  if (state == SUBREL_STATE_UNKNOWN)
183  break;
184 
185  if (state == expected_state)
186  return true;
187 
188  /* Check if the sync worker is still running and bail if not. */
189  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
191  false);
192  LWLockRelease(LogicalRepWorkerLock);
193  if (!worker)
194  break;
195 
196  (void) WaitLatch(MyLatch,
199 
201  }
202 
203  return false;
204 }
205 
206 /*
207  * Wait until the apply worker changes the state of our synchronization
208  * worker to the expected one.
209  *
210  * Used when transitioning from SYNCWAIT state to CATCHUP.
211  *
212  * Returns false if the apply worker has disappeared.
213  */
214 static bool
215 wait_for_worker_state_change(char expected_state)
216 {
217  int rc;
218 
219  for (;;)
220  {
221  LogicalRepWorker *worker;
222 
224 
225  /*
226  * Done if already in correct state. (We assume this fetch is atomic
227  * enough to not give a misleading answer if we do it with no lock.)
228  */
229  if (MyLogicalRepWorker->relstate == expected_state)
230  return true;
231 
232  /*
233  * Bail out if the apply worker has died, else signal it we're
234  * waiting.
235  */
236  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
238  InvalidOid, false);
239  if (worker && worker->proc)
241  LWLockRelease(LogicalRepWorkerLock);
242  if (!worker)
243  break;
244 
245  /*
246  * Wait. We expect to get a latch signal back from the apply worker,
247  * but use a timeout in case it dies without sending one.
248  */
249  rc = WaitLatch(MyLatch,
252 
253  if (rc & WL_LATCH_SET)
255  }
256 
257  return false;
258 }
259 
260 /*
261  * Callback from syscache invalidation.
262  */
263 void
265 {
266  table_states_valid = false;
267 }
268 
269 /*
270  * Handle table synchronization cooperation from the synchronization
271  * worker.
272  *
273  * If the sync worker is in CATCHUP state and reached (or passed) the
274  * predetermined synchronization point in the WAL stream, mark the table as
275  * SYNCDONE and finish.
276  */
277 static void
279 {
281 
282  if (MyLogicalRepWorker->relstate == SUBREL_STATE_CATCHUP &&
283  current_lsn >= MyLogicalRepWorker->relstate_lsn)
284  {
285  TimeLineID tli;
286  char syncslotname[NAMEDATALEN] = {0};
287 
288  MyLogicalRepWorker->relstate = SUBREL_STATE_SYNCDONE;
289  MyLogicalRepWorker->relstate_lsn = current_lsn;
290 
292 
293  /*
294  * UpdateSubscriptionRelState must be called within a transaction.
295  * That transaction will be ended within the finish_sync_worker().
296  */
297  if (!IsTransactionState())
299 
304 
305  /* End wal streaming so wrconn can be re-used to drop the slot. */
307 
308  /*
309  * Cleanup the tablesync slot.
310  *
311  * This has to be done after updating the state because otherwise if
312  * there is an error while doing the database operations we won't be
313  * able to rollback dropped slot.
314  */
317  syncslotname,
318  sizeof(syncslotname));
319 
320  /*
321  * It is important to give an error if we are unable to drop the slot,
322  * otherwise, it won't be dropped till the corresponding subscription
323  * is dropped. So passing missing_ok = false.
324  */
325  ReplicationSlotDropAtPubNode(wrconn, syncslotname, false);
326 
327  finish_sync_worker();
328  }
329  else
331 }
332 
333 /*
334  * Handle table synchronization cooperation from the apply worker.
335  *
336  * Walk over all subscription tables that are individually tracked by the
337  * apply process (currently, all that have state other than
338  * SUBREL_STATE_READY) and manage synchronization for them.
339  *
340  * If there are tables that need synchronizing and are not being synchronized
341  * yet, start sync workers for them (if there are free slots for sync
342  * workers). To prevent starting the sync worker for the same relation at a
343  * high frequency after a failure, we store its last start time with each sync
344  * state info. We start the sync worker for the same relation after waiting
345  * at least wal_retrieve_retry_interval.
346  *
347  * For tables that are being synchronized already, check if sync workers
348  * either need action from the apply worker or have finished. This is the
349  * SYNCWAIT to CATCHUP transition.
350  *
351  * If the synchronization position is reached (SYNCDONE), then the table can
352  * be marked as READY and is no longer tracked.
353  */
354 static void
356 {
357  struct tablesync_start_time_mapping
358  {
359  Oid relid;
360  TimestampTz last_start_time;
361  };
362  static List *table_states = NIL;
363  static HTAB *last_start_times = NULL;
364  ListCell *lc;
365  bool started_tx = false;
366 
368 
369  /* We need up-to-date sync state info for subscription tables here. */
370  if (!table_states_valid)
371  {
372  MemoryContext oldctx;
373  List *rstates;
374  ListCell *lc;
375  SubscriptionRelState *rstate;
376 
377  /* Clean the old list. */
378  list_free_deep(table_states);
379  table_states = NIL;
380 
382  started_tx = true;
383 
384  /* Fetch all non-ready tables. */
386 
387  /* Allocate the tracking info in a permanent memory context. */
389  foreach(lc, rstates)
390  {
391  rstate = palloc(sizeof(SubscriptionRelState));
392  memcpy(rstate, lfirst(lc), sizeof(SubscriptionRelState));
393  table_states = lappend(table_states, rstate);
394  }
395  MemoryContextSwitchTo(oldctx);
396 
397  table_states_valid = true;
398  }
399 
400  /*
401  * Prepare a hash table for tracking last start times of workers, to avoid
402  * immediate restarts. We don't need it if there are no tables that need
403  * syncing.
404  */
405  if (table_states && !last_start_times)
406  {
407  HASHCTL ctl;
408 
409  ctl.keysize = sizeof(Oid);
410  ctl.entrysize = sizeof(struct tablesync_start_time_mapping);
411  last_start_times = hash_create("Logical replication table sync worker start times",
412  256, &ctl, HASH_ELEM | HASH_BLOBS);
413  }
414 
415  /*
416  * Clean up the hash table when we're done with all tables (just to
417  * release the bit of memory).
418  */
419  else if (!table_states && last_start_times)
420  {
421  hash_destroy(last_start_times);
422  last_start_times = NULL;
423  }
424 
425  /*
426  * Process all tables that are being synchronized.
427  */
428  foreach(lc, table_states)
429  {
431 
432  if (rstate->state == SUBREL_STATE_SYNCDONE)
433  {
434  /*
435  * Apply has caught up to the position where the table sync has
436  * finished. Mark the table as ready so that the apply will just
437  * continue to replicate it normally.
438  */
439  if (current_lsn >= rstate->lsn)
440  {
441  char originname[NAMEDATALEN];
442 
443  rstate->state = SUBREL_STATE_READY;
444  rstate->lsn = current_lsn;
445  if (!started_tx)
446  {
448  started_tx = true;
449  }
450 
451  /*
452  * Remove the tablesync origin tracking if exists.
453  *
454  * The normal case origin drop is done here instead of in the
455  * process_syncing_tables_for_sync function because we don't
456  * allow to drop the origin till the process owning the origin
457  * is alive.
458  *
459  * There is a chance that the user is concurrently performing
460  * refresh for the subscription where we remove the table
461  * state and its origin and by this time the origin might be
462  * already removed. So passing missing_ok = true.
463  */
465  rstate->relid,
466  originname,
467  sizeof(originname));
468  replorigin_drop_by_name(originname, true, false);
469 
470  /*
471  * Update the state to READY only after the origin cleanup.
472  */
474  rstate->relid, rstate->state,
475  rstate->lsn);
476  }
477  }
478  else
479  {
480  LogicalRepWorker *syncworker;
481 
482  /*
483  * Look for a sync worker for this relation.
484  */
485  LWLockAcquire(LogicalRepWorkerLock, LW_SHARED);
486 
488  rstate->relid, false);
489 
490  if (syncworker)
491  {
492  /* Found one, update our copy of its state */
493  SpinLockAcquire(&syncworker->relmutex);
494  rstate->state = syncworker->relstate;
495  rstate->lsn = syncworker->relstate_lsn;
496  if (rstate->state == SUBREL_STATE_SYNCWAIT)
497  {
498  /*
499  * Sync worker is waiting for apply. Tell sync worker it
500  * can catchup now.
501  */
502  syncworker->relstate = SUBREL_STATE_CATCHUP;
503  syncworker->relstate_lsn =
504  Max(syncworker->relstate_lsn, current_lsn);
505  }
506  SpinLockRelease(&syncworker->relmutex);
507 
508  /* If we told worker to catch up, wait for it. */
509  if (rstate->state == SUBREL_STATE_SYNCWAIT)
510  {
511  /* Signal the sync worker, as it may be waiting for us. */
512  if (syncworker->proc)
513  logicalrep_worker_wakeup_ptr(syncworker);
514 
515  /* Now safe to release the LWLock */
516  LWLockRelease(LogicalRepWorkerLock);
517 
518  /*
519  * Enter busy loop and wait for synchronization worker to
520  * reach expected state (or die trying).
521  */
522  if (!started_tx)
523  {
525  started_tx = true;
526  }
527 
529  SUBREL_STATE_SYNCDONE);
530  }
531  else
532  LWLockRelease(LogicalRepWorkerLock);
533  }
534  else
535  {
536  /*
537  * If there is no sync worker for this table yet, count
538  * running sync workers for this subscription, while we have
539  * the lock.
540  */
541  int nsyncworkers =
543 
544  /* Now safe to release the LWLock */
545  LWLockRelease(LogicalRepWorkerLock);
546 
547  /*
548  * If there are free sync worker slot(s), start a new sync
549  * worker for the table.
550  */
551  if (nsyncworkers < max_sync_workers_per_subscription)
552  {
554  struct tablesync_start_time_mapping *hentry;
555  bool found;
556 
557  hentry = hash_search(last_start_times, &rstate->relid,
558  HASH_ENTER, &found);
559 
560  if (!found ||
561  TimestampDifferenceExceeds(hentry->last_start_time, now,
563  {
568  rstate->relid);
569  hentry->last_start_time = now;
570  }
571  }
572  }
573  }
574  }
575 
576  if (started_tx)
577  {
579  pgstat_report_stat(false);
580  }
581 }
582 
583 /*
584  * Process possible state change(s) of tables that are being synchronized.
585  */
586 void
588 {
589  if (am_tablesync_worker())
590  process_syncing_tables_for_sync(current_lsn);
591  else
593 }
594 
595 /*
596  * Create list of columns for COPY based on logical relation mapping.
597  */
598 static List *
600 {
601  List *attnamelist = NIL;
602  int i;
603 
604  for (i = 0; i < rel->remoterel.natts; i++)
605  {
606  attnamelist = lappend(attnamelist,
607  makeString(rel->remoterel.attnames[i]));
608  }
609 
610 
611  return attnamelist;
612 }
613 
614 /*
615  * Data source callback for the COPY FROM, which reads from the remote
616  * connection and passes the data back to our local COPY.
617  */
618 static int
619 copy_read_data(void *outbuf, int minread, int maxread)
620 {
621  int bytesread = 0;
622  int avail;
623 
624  /* If there are some leftover data from previous read, use it. */
625  avail = copybuf->len - copybuf->cursor;
626  if (avail)
627  {
628  if (avail > maxread)
629  avail = maxread;
630  memcpy(outbuf, &copybuf->data[copybuf->cursor], avail);
631  copybuf->cursor += avail;
632  maxread -= avail;
633  bytesread += avail;
634  }
635 
636  while (maxread > 0 && bytesread < minread)
637  {
639  int len;
640  char *buf = NULL;
641 
642  for (;;)
643  {
644  /* Try read the data. */
645  len = walrcv_receive(wrconn, &buf, &fd);
646 
648 
649  if (len == 0)
650  break;
651  else if (len < 0)
652  return bytesread;
653  else
654  {
655  /* Process the data */
656  copybuf->data = buf;
657  copybuf->len = len;
658  copybuf->cursor = 0;
659 
660  avail = copybuf->len - copybuf->cursor;
661  if (avail > maxread)
662  avail = maxread;
663  memcpy(outbuf, &copybuf->data[copybuf->cursor], avail);
664  outbuf = (void *) ((char *) outbuf + avail);
665  copybuf->cursor += avail;
666  maxread -= avail;
667  bytesread += avail;
668  }
669 
670  if (maxread <= 0 || bytesread >= minread)
671  return bytesread;
672  }
673 
674  /*
675  * Wait for more data or latch.
676  */
677  (void) WaitLatchOrSocket(MyLatch,
680  fd, 1000L, WAIT_EVENT_LOGICAL_SYNC_DATA);
681 
683  }
684 
685  return bytesread;
686 }
687 
688 
689 /*
690  * Get information about remote relation in similar fashion the RELATION
691  * message provides during replication.
692  */
693 static void
694 fetch_remote_table_info(char *nspname, char *relname,
695  LogicalRepRelation *lrel)
696 {
697  WalRcvExecResult *res;
698  StringInfoData cmd;
699  TupleTableSlot *slot;
700  Oid tableRow[] = {OIDOID, CHAROID, CHAROID};
701  Oid attrRow[] = {TEXTOID, OIDOID, BOOLOID};
702  bool isnull;
703  int natt;
704 
705  lrel->nspname = nspname;
706  lrel->relname = relname;
707 
708  /* First fetch Oid and replica identity. */
709  initStringInfo(&cmd);
710  appendStringInfo(&cmd, "SELECT c.oid, c.relreplident, c.relkind"
711  " FROM pg_catalog.pg_class c"
712  " INNER JOIN pg_catalog.pg_namespace n"
713  " ON (c.relnamespace = n.oid)"
714  " WHERE n.nspname = %s"
715  " AND c.relname = %s",
716  quote_literal_cstr(nspname),
717  quote_literal_cstr(relname));
718  res = walrcv_exec(wrconn, cmd.data, lengthof(tableRow), tableRow);
719 
720  if (res->status != WALRCV_OK_TUPLES)
721  ereport(ERROR,
722  (errmsg("could not fetch table info for table \"%s.%s\" from publisher: %s",
723  nspname, relname, res->err)));
724 
726  if (!tuplestore_gettupleslot(res->tuplestore, true, false, slot))
727  ereport(ERROR,
728  (errmsg("table \"%s.%s\" not found on publisher",
729  nspname, relname)));
730 
731  lrel->remoteid = DatumGetObjectId(slot_getattr(slot, 1, &isnull));
732  Assert(!isnull);
733  lrel->replident = DatumGetChar(slot_getattr(slot, 2, &isnull));
734  Assert(!isnull);
735  lrel->relkind = DatumGetChar(slot_getattr(slot, 3, &isnull));
736  Assert(!isnull);
737 
739  walrcv_clear_result(res);
740 
741  /* Now fetch columns. */
742  resetStringInfo(&cmd);
743  appendStringInfo(&cmd,
744  "SELECT a.attname,"
745  " a.atttypid,"
746  " a.attnum = ANY(i.indkey)"
747  " FROM pg_catalog.pg_attribute a"
748  " LEFT JOIN pg_catalog.pg_index i"
749  " ON (i.indexrelid = pg_get_replica_identity_index(%u))"
750  " WHERE a.attnum > 0::pg_catalog.int2"
751  " AND NOT a.attisdropped %s"
752  " AND a.attrelid = %u"
753  " ORDER BY a.attnum",
754  lrel->remoteid,
755  (walrcv_server_version(wrconn) >= 120000 ? "AND a.attgenerated = ''" : ""),
756  lrel->remoteid);
757  res = walrcv_exec(wrconn, cmd.data, lengthof(attrRow), attrRow);
758 
759  if (res->status != WALRCV_OK_TUPLES)
760  ereport(ERROR,
761  (errmsg("could not fetch table info for table \"%s.%s\": %s",
762  nspname, relname, res->err)));
763 
764  /* We don't know the number of rows coming, so allocate enough space. */
765  lrel->attnames = palloc0(MaxTupleAttributeNumber * sizeof(char *));
766  lrel->atttyps = palloc0(MaxTupleAttributeNumber * sizeof(Oid));
767  lrel->attkeys = NULL;
768 
769  natt = 0;
771  while (tuplestore_gettupleslot(res->tuplestore, true, false, slot))
772  {
773  lrel->attnames[natt] =
774  TextDatumGetCString(slot_getattr(slot, 1, &isnull));
775  Assert(!isnull);
776  lrel->atttyps[natt] = DatumGetObjectId(slot_getattr(slot, 2, &isnull));
777  Assert(!isnull);
778  if (DatumGetBool(slot_getattr(slot, 3, &isnull)))
779  lrel->attkeys = bms_add_member(lrel->attkeys, natt);
780 
781  /* Should never happen. */
782  if (++natt >= MaxTupleAttributeNumber)
783  elog(ERROR, "too many columns in remote table \"%s.%s\"",
784  nspname, relname);
785 
786  ExecClearTuple(slot);
787  }
789 
790  lrel->natts = natt;
791 
792  walrcv_clear_result(res);
793  pfree(cmd.data);
794 }
795 
796 /*
797  * Copy existing data of a table from publisher.
798  *
799  * Caller is responsible for locking the local relation.
800  */
801 static void
803 {
804  LogicalRepRelMapEntry *relmapentry;
805  LogicalRepRelation lrel;
806  WalRcvExecResult *res;
807  StringInfoData cmd;
808  CopyFromState cstate;
809  List *attnamelist;
810  ParseState *pstate;
811 
812  /* Get the publisher relation info. */
814  RelationGetRelationName(rel), &lrel);
815 
816  /* Put the relation into relmap. */
818 
819  /* Map the publisher relation to local one. */
820  relmapentry = logicalrep_rel_open(lrel.remoteid, NoLock);
821  Assert(rel == relmapentry->localrel);
822 
823  /* Start copy on the publisher. */
824  initStringInfo(&cmd);
825  if (lrel.relkind == RELKIND_RELATION)
826  appendStringInfo(&cmd, "COPY %s TO STDOUT",
828  else
829  {
830  /*
831  * For non-tables, we need to do COPY (SELECT ...), but we can't just
832  * do SELECT * because we need to not copy generated columns.
833  */
834  appendStringInfoString(&cmd, "COPY (SELECT ");
835  for (int i = 0; i < lrel.natts; i++)
836  {
838  if (i < lrel.natts - 1)
839  appendStringInfoString(&cmd, ", ");
840  }
841  appendStringInfo(&cmd, " FROM %s) TO STDOUT",
843  }
844  res = walrcv_exec(wrconn, cmd.data, 0, NULL);
845  pfree(cmd.data);
846  if (res->status != WALRCV_OK_COPY_OUT)
847  ereport(ERROR,
848  (errmsg("could not start initial contents copy for table \"%s.%s\": %s",
849  lrel.nspname, lrel.relname, res->err)));
850  walrcv_clear_result(res);
851 
852  copybuf = makeStringInfo();
853 
854  pstate = make_parsestate(NULL);
856  NULL, false, false);
857 
858  attnamelist = make_copy_attnamelist(relmapentry);
859  cstate = BeginCopyFrom(pstate, rel, NULL, NULL, false, copy_read_data, attnamelist, NIL);
860 
861  /* Do the copy */
862  (void) CopyFrom(cstate);
863 
864  logicalrep_rel_close(relmapentry, NoLock);
865 }
866 
867 /*
868  * Determine the tablesync slot name.
869  *
870  * The name must not exceed NAMEDATALEN - 1 because of remote node constraints
871  * on slot name length. We append system_identifier to avoid slot_name
872  * collision with subscriptions in other clusters. With the current scheme
873  * pg_%u_sync_%u_UINT64_FORMAT (3 + 10 + 6 + 10 + 20 + '\0'), the maximum
874  * length of slot_name will be 50.
875  *
876  * The returned slot name is stored in the supplied buffer (syncslotname) with
877  * the given size.
878  *
879  * Note: We don't use the subscription slot name as part of tablesync slot name
880  * because we are responsible for cleaning up these slots and it could become
881  * impossible to recalculate what name to cleanup if the subscription slot name
882  * had changed.
883  */
884 void
886  char *syncslotname, int szslot)
887 {
888  snprintf(syncslotname, szslot, "pg_%u_sync_%u_" UINT64_FORMAT, suboid,
889  relid, GetSystemIdentifier());
890 }
891 
892 /*
893  * Form the origin name for tablesync.
894  *
895  * Return the name in the supplied buffer.
896  */
897 void
899  char *originname, int szorgname)
900 {
901  snprintf(originname, szorgname, "pg_%u_%u", suboid, relid);
902 }
903 
904 /*
905  * Start syncing the table in the sync worker.
906  *
907  * If nothing needs to be done to sync the table, we exit the worker without
908  * any further action.
909  *
910  * The returned slot name is palloc'ed in current memory context.
911  */
912 char *
914 {
915  char *slotname;
916  char *err;
917  char relstate;
918  XLogRecPtr relstate_lsn;
919  Relation rel;
920  WalRcvExecResult *res;
921  char originname[NAMEDATALEN];
922  RepOriginId originid;
923 
924  /* Check the state of the table synchronization. */
928  &relstate_lsn);
930 
932  MyLogicalRepWorker->relstate = relstate;
933  MyLogicalRepWorker->relstate_lsn = relstate_lsn;
935 
936  /*
937  * If synchronization is already done or no longer necessary, exit now
938  * that we've updated shared memory state.
939  */
940  switch (relstate)
941  {
942  case SUBREL_STATE_SYNCDONE:
943  case SUBREL_STATE_READY:
944  case SUBREL_STATE_UNKNOWN:
945  finish_sync_worker(); /* doesn't return */
946  }
947 
948  /* Calculate the name of the tablesync slot. */
949  slotname = (char *) palloc(NAMEDATALEN);
952  slotname,
953  NAMEDATALEN);
954 
955  /*
956  * Here we use the slot name instead of the subscription name as the
957  * application_name, so that it is different from the main apply worker,
958  * so that synchronous replication can distinguish them.
959  */
960  wrconn = walrcv_connect(MySubscription->conninfo, true, slotname, &err);
961  if (wrconn == NULL)
962  ereport(ERROR,
963  (errmsg("could not connect to the publisher: %s", err)));
964 
965  Assert(MyLogicalRepWorker->relstate == SUBREL_STATE_INIT ||
966  MyLogicalRepWorker->relstate == SUBREL_STATE_DATASYNC ||
967  MyLogicalRepWorker->relstate == SUBREL_STATE_FINISHEDCOPY);
968 
969  /* Assign the origin tracking record name. */
972  originname,
973  sizeof(originname));
974 
975  if (MyLogicalRepWorker->relstate == SUBREL_STATE_DATASYNC)
976  {
977  /*
978  * We have previously errored out before finishing the copy so the
979  * replication slot might exist. We want to remove the slot if it
980  * already exists and proceed.
981  *
982  * XXX We could also instead try to drop the slot, last time we failed
983  * but for that, we might need to clean up the copy state as it might
984  * be in the middle of fetching the rows. Also, if there is a network
985  * breakdown then it wouldn't have succeeded so trying it next time
986  * seems like a better bet.
987  */
988  ReplicationSlotDropAtPubNode(wrconn, slotname, true);
989  }
990  else if (MyLogicalRepWorker->relstate == SUBREL_STATE_FINISHEDCOPY)
991  {
992  /*
993  * The COPY phase was previously done, but tablesync then crashed
994  * before it was able to finish normally.
995  */
997 
998  /*
999  * The origin tracking name must already exist. It was created first
1000  * time this tablesync was launched.
1001  */
1002  originid = replorigin_by_name(originname, false);
1003  replorigin_session_setup(originid);
1004  replorigin_session_origin = originid;
1005  *origin_startpos = replorigin_session_get_progress(false);
1006 
1008 
1009  goto copy_table_done;
1010  }
1011 
1013  MyLogicalRepWorker->relstate = SUBREL_STATE_DATASYNC;
1016 
1017  /* Update the state and make it visible to others. */
1024  pgstat_report_stat(false);
1025 
1027 
1028  /*
1029  * Use a standard write lock here. It might be better to disallow access
1030  * to the table while it's being synchronized. But we don't want to block
1031  * the main apply process from working and it has to open the relation in
1032  * RowExclusiveLock when remapping remote relation id to local one.
1033  */
1035 
1036  /*
1037  * Start a transaction in the remote node in REPEATABLE READ mode. This
1038  * ensures that both the replication slot we create (see below) and the
1039  * COPY are consistent with each other.
1040  */
1041  res = walrcv_exec(wrconn,
1042  "BEGIN READ ONLY ISOLATION LEVEL REPEATABLE READ",
1043  0, NULL);
1044  if (res->status != WALRCV_OK_COMMAND)
1045  ereport(ERROR,
1046  (errmsg("table copy could not start transaction on publisher"),
1047  errdetail("The error was: %s", res->err)));
1048  walrcv_clear_result(res);
1049 
1050  /*
1051  * Create a new permanent logical decoding slot. This slot will be used
1052  * for the catchup phase after COPY is done, so tell it to use the
1053  * snapshot to make the final data consistent.
1054  */
1055  walrcv_create_slot(wrconn, slotname, false /* permanent */ ,
1056  CRS_USE_SNAPSHOT, origin_startpos);
1057 
1058  /*
1059  * Setup replication origin tracking. The purpose of doing this before the
1060  * copy is to avoid doing the copy again due to any error in setting up
1061  * origin tracking.
1062  */
1063  originid = replorigin_by_name(originname, true);
1064  if (!OidIsValid(originid))
1065  {
1066  /*
1067  * Origin tracking does not exist, so create it now.
1068  *
1069  * Then advance to the LSN got from walrcv_create_slot. This is WAL
1070  * logged for the purpose of recovery. Locks are to prevent the
1071  * replication origin from vanishing while advancing.
1072  */
1073  originid = replorigin_create(originname);
1074 
1075  LockRelationOid(ReplicationOriginRelationId, RowExclusiveLock);
1076  replorigin_advance(originid, *origin_startpos, InvalidXLogRecPtr,
1077  true /* go backward */ , true /* WAL log */ );
1078  UnlockRelationOid(ReplicationOriginRelationId, RowExclusiveLock);
1079 
1080  replorigin_session_setup(originid);
1081  replorigin_session_origin = originid;
1082  }
1083  else
1084  {
1085  ereport(ERROR,
1087  errmsg("replication origin \"%s\" already exists",
1088  originname)));
1089  }
1090 
1091  /* Now do the initial data copy */
1093  copy_table(rel);
1095 
1096  res = walrcv_exec(wrconn, "COMMIT", 0, NULL);
1097  if (res->status != WALRCV_OK_COMMAND)
1098  ereport(ERROR,
1099  (errmsg("table copy could not finish transaction on publisher"),
1100  errdetail("The error was: %s", res->err)));
1101  walrcv_clear_result(res);
1102 
1103  table_close(rel, NoLock);
1104 
1105  /* Make the copy visible. */
1107 
1108  /*
1109  * Update the persisted state to indicate the COPY phase is done; make it
1110  * visible to others.
1111  */
1114  SUBREL_STATE_FINISHEDCOPY,
1116 
1118 
1119 copy_table_done:
1120 
1121  elog(DEBUG1,
1122  "LogicalRepSyncTableStart: '%s' origin_startpos lsn %X/%X",
1123  originname, LSN_FORMAT_ARGS(*origin_startpos));
1124 
1125  /*
1126  * We are done with the initial data synchronization, update the state.
1127  */
1129  MyLogicalRepWorker->relstate = SUBREL_STATE_SYNCWAIT;
1130  MyLogicalRepWorker->relstate_lsn = *origin_startpos;
1132 
1133  /*
1134  * Finally, wait until the main apply worker tells us to catch up and then
1135  * return to let LogicalRepApplyLoop do it.
1136  */
1137  wait_for_worker_state_change(SUBREL_STATE_CATCHUP);
1138  return slotname;
1139 }
Subscription * MySubscription
Definition: worker.c:161
Value * makeString(char *str)
Definition: value.c:53
#define NIL
Definition: pg_list.h:65
void hash_destroy(HTAB *hashp)
Definition: dynahash.c:862
WalReceiverConn * wrconn
Definition: worker.c:159
#define InvalidXLogRecPtr
Definition: xlogdefs.h:28
#define walrcv_endstreaming(conn, next_tli)
Definition: walreceiver.h:415
#define DEBUG1
Definition: elog.h:25
void table_close(Relation relation, LOCKMODE lockmode)
Definition: table.c:167
char * quote_literal_cstr(const char *rawstr)
Definition: quote.c:102
uint32 TimeLineID
Definition: xlogdefs.h:59
#define HASH_ELEM
Definition: hsearch.h:95
#define WL_TIMEOUT
Definition: latch.h:128
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:10994
static TupleTableSlot * ExecClearTuple(TupleTableSlot *slot)
Definition: tuptable.h:425
#define MaxTupleAttributeNumber
Definition: htup_details.h:33
void ReplicationSlotDropAtPubNode(WalReceiverConn *wrconn, char *slotname, bool missing_ok)
void process_syncing_tables(XLogRecPtr current_lsn)
Definition: tablesync.c:587
TupleTableSlot * MakeSingleTupleTableSlot(TupleDesc tupdesc, const TupleTableSlotOps *tts_ops)
Definition: execTuples.c:1208
void UnlockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:199
TimestampTz GetCurrentTimestamp(void)
Definition: timestamp.c:1578
void logicalrep_worker_wakeup(Oid subid, Oid relid)
Definition: launcher.c:539
int64 TimestampTz
Definition: timestamp.h:39
static void process_syncing_tables_for_apply(XLogRecPtr current_lsn)
Definition: tablesync.c:355
void replorigin_drop_by_name(char *name, bool missing_ok, bool nowait)
Definition: origin.c:414
uint64 CopyFrom(CopyFromState cstate)
Definition: copyfrom.c:524
#define DatumGetObjectId(X)
Definition: postgres.h:500
void CommitTransactionCommand(void)
Definition: xact.c:2939
StringInfo makeStringInfo(void)
Definition: stringinfo.c:41
#define walrcv_receive(conn, buffer, wait_fd)
Definition: walreceiver.h:417
#define walrcv_server_version(conn)
Definition: walreceiver.h:409
static MemoryContext MemoryContextSwitchTo(MemoryContext context)
Definition: palloc.h:109
#define AccessShareLock
Definition: lockdefs.h:36
uint16 RepOriginId
Definition: xlogdefs.h:65
Size entrysize
Definition: hsearch.h:76
static void copy_table(Relation rel)
Definition: tablesync.c:802
void proc_exit(int code)
Definition: ipc.c:104
XLogRecPtr replorigin_session_get_progress(bool flush)
Definition: origin.c:1203
int errcode(int sqlerrcode)
Definition: elog.c:694
static bool wait_for_relation_state_change(Oid relid, char expected_state)
Definition: tablesync.c:167
void logicalrep_rel_close(LogicalRepRelMapEntry *rel, LOCKMODE lockmode)
Definition: relation.c:447
#define WL_SOCKET_READABLE
Definition: latch.h:126
void PopActiveSnapshot(void)
Definition: snapmgr.c:759
void replorigin_advance(RepOriginId node, XLogRecPtr remote_commit, XLogRecPtr local_commit, bool go_backward, bool wal_log)
Definition: origin.c:872
void pgstat_report_stat(bool disconnect)
Definition: pgstat.c:870
#define lengthof(array)
Definition: c.h:734
void * hash_search(HTAB *hashp, const void *keyPtr, HASHACTION action, bool *foundPtr)
Definition: dynahash.c:954
void replorigin_session_setup(RepOriginId node)
Definition: origin.c:1068
#define LOG
Definition: elog.h:26
NameData relname
Definition: pg_class.h:38
unsigned int Oid
Definition: postgres_ext.h:31
static bool table_states_valid
Definition: tablesync.c:118
char * LogicalRepSyncTableStart(XLogRecPtr *origin_startpos)
Definition: tablesync.c:913
#define walrcv_create_slot(conn, slotname, temporary, snapshot_action, lsn)
Definition: walreceiver.h:421
bool TimestampDifferenceExceeds(TimestampTz start_time, TimestampTz stop_time, int msec)
Definition: timestamp.c:1709
Snapshot GetTransactionSnapshot(void)
Definition: snapmgr.c:250
#define OidIsValid(objectId)
Definition: c.h:710
void list_free_deep(List *list)
Definition: list.c:1405
Bitmapset * attkeys
Definition: logicalproto.h:98
void XLogFlush(XLogRecPtr record)
Definition: xlog.c:2850
static int fd(const char *x, int i)
Definition: preproc-init.c:105
RepOriginId replorigin_by_name(char *roname, bool missing_ok)
Definition: origin.c:209
void ResetLatch(Latch *latch)
Definition: latch.c:660
int WaitLatch(Latch *latch, int wakeEvents, long timeout, uint32 wait_event_info)
Definition: latch.c:452
LogicalRepRelId remoteid
Definition: logicalproto.h:90
XLogRecPtr relstate_lsn
ParseNamespaceItem * addRangeTableEntryForRelation(ParseState *pstate, Relation rel, int lockmode, Alias *alias, bool inh, bool inFromCl)
ParseState * make_parsestate(ParseState *parentParseState)
Definition: parse_node.c:44
void LWLockRelease(LWLock *lock)
Definition: lwlock.c:1808
#define NAMEDATALEN
void logicalrep_worker_wakeup_ptr(LogicalRepWorker *worker)
Definition: launcher.c:559
void logicalrep_relmap_update(LogicalRepRelation *remoterel)
Definition: relation.c:171
#define SpinLockAcquire(lock)
Definition: spin.h:62
Definition: dynahash.c:219
#define LSN_FORMAT_ARGS(lsn)
Definition: xlogdefs.h:43
static void walrcv_clear_result(WalRcvExecResult *walres)
Definition: walreceiver.h:431
void pfree(void *pointer)
Definition: mcxt.c:1057
void appendStringInfo(StringInfo str, const char *fmt,...)
Definition: stringinfo.c:91
TupleDesc tupledesc
Definition: walreceiver.h:216
LogicalRepWorker * MyLogicalRepWorker
Definition: launcher.c:57
#define ERROR
Definition: elog.h:45
LogicalRepRelation remoterel
int max_sync_workers_per_subscription
Definition: launcher.c:55
static bool am_tablesync_worker(void)
void appendStringInfoString(StringInfo str, const char *s)
Definition: stringinfo.c:176
char * get_namespace_name(Oid nspid)
Definition: lsyscache.c:3316
#define NoLock
Definition: lockdefs.h:34
static char * buf
Definition: pg_test_fsync.c:68
void PushActiveSnapshot(Snapshot snap)
Definition: snapmgr.c:680
void ExecDropSingleTupleTableSlot(TupleTableSlot *slot)
Definition: execTuples.c:1224
#define RowExclusiveLock
Definition: lockdefs.h:38
int errdetail(const char *fmt,...)
Definition: elog.c:1038
#define DatumGetBool(X)
Definition: postgres.h:393
#define RelationGetRelationName(relation)
Definition: rel.h:491
HTAB * hash_create(const char *tabname, long nelem, const HASHCTL *info, int flags)
Definition: dynahash.c:349
void resetStringInfo(StringInfo str)
Definition: stringinfo.c:75
int WaitLatchOrSocket(Latch *latch, int wakeEvents, pgsocket sock, long timeout, uint32 wait_event_info)
Definition: latch.c:500
unsigned int uint32
Definition: c.h:441
int pgsocket
Definition: port.h:31
RepOriginId replorigin_create(char *roname)
Definition: origin.c:240
LogicalRepRelMapEntry * logicalrep_rel_open(LogicalRepRelId remoteid, LOCKMODE lockmode)
Definition: relation.c:272
void InvalidateCatalogSnapshot(void)
Definition: snapmgr.c:456
List * lappend(List *list, void *datum)
Definition: list.c:336
void initStringInfo(StringInfo str)
Definition: stringinfo.c:59
char * quote_qualified_identifier(const char *qualifier, const char *ident)
Definition: ruleutils.c:11078
int wal_retrieve_retry_interval
Definition: xlog.c:111
#define SpinLockRelease(lock)
Definition: spin.h:64
#define HASH_BLOBS
Definition: hsearch.h:97
#define TextDatumGetCString(d)
Definition: builtins.h:83
static void pg_attribute_noreturn()
Definition: tablesync.c:126
void * palloc0(Size size)
Definition: mcxt.c:981
char GetSubscriptionRelState(Oid subid, Oid relid, XLogRecPtr *sublsn)
uintptr_t Datum
Definition: postgres.h:367
void CommandCounterIncrement(void)
Definition: xact.c:1021
#define PGINVALID_SOCKET
Definition: port.h:33
#define DatumGetChar(X)
Definition: postgres.h:409
void UpdateSubscriptionRelState(Oid subid, Oid relid, char state, XLogRecPtr sublsn)
Size keysize
Definition: hsearch.h:75
StringInfo copybuf
Definition: tablesync.c:120
static void fetch_remote_table_info(char *nspname, char *relname, LogicalRepRelation *lrel)
Definition: tablesync.c:694
int logicalrep_sync_worker_count(Oid subid)
Definition: launcher.c:665
#define InvalidOid
Definition: postgres_ext.h:36
static Datum slot_getattr(TupleTableSlot *slot, int attnum, bool *isnull)
Definition: tuptable.h:381
#define ereport(elevel,...)
Definition: elog.h:155
XLogRecPtr GetXLogWriteRecPtr(void)
Definition: xlog.c:11631
#define Max(x, y)
Definition: c.h:980
CopyFromState BeginCopyFrom(ParseState *pstate, Relation rel, Node *whereClause, const char *filename, bool is_program, copy_data_source_cb data_source_cb, List *attnamelist, List *options)
Definition: copyfrom.c:1174
bool tuplestore_gettupleslot(Tuplestorestate *state, bool forward, bool copy, TupleTableSlot *slot)
Definition: tuplestore.c:1078
Tuplestorestate * tuplestore
Definition: walreceiver.h:215
void logicalrep_worker_launch(Oid dbid, Oid subid, const char *subname, Oid userid, Oid relid)
Definition: launcher.c:272
uint64 XLogRecPtr
Definition: xlogdefs.h:21
#define Assert(condition)
Definition: c.h:804
#define lfirst(lc)
Definition: pg_list.h:169
WalRcvExecStatus status
Definition: walreceiver.h:212
RepOriginId replorigin_session_origin
Definition: origin.c:154
Definition: regguts.h:317
LogicalRepWorker * logicalrep_worker_find(Oid subid, Oid relid, bool only_running)
Definition: launcher.c:221
void StartTransactionCommand(void)
Definition: xact.c:2838
bool LWLockAcquire(LWLock *lock, LWLockMode mode)
Definition: lwlock.c:1206
bool IsTransactionState(void)
Definition: xact.c:371
void ReplicationOriginNameForTablesync(Oid suboid, Oid relid, char *originname, int szorgname)
Definition: tablesync.c:898
Bitmapset * bms_add_member(Bitmapset *a, int x)
Definition: bitmapset.c:736
static void process_syncing_tables_for_sync(XLogRecPtr current_lsn)
Definition: tablesync.c:278
uint64 GetSystemIdentifier(void)
Definition: xlog.c:4931
void * palloc(Size size)
Definition: mcxt.c:950
int errmsg(const char *fmt,...)
Definition: elog.c:905
#define elog(elevel,...)
Definition: elog.h:227
int i
void * arg
struct Latch * MyLatch
Definition: globals.c:55
static int copy_read_data(void *outbuf, int minread, int maxread)
Definition: tablesync.c:619
#define CHECK_FOR_INTERRUPTS()
Definition: miscadmin.h:100
void LockRelationOid(Oid relid, LOCKMODE lockmode)
Definition: lmgr.c:108
Relation table_open(Oid relationId, LOCKMODE lockmode)
Definition: table.c:39
static List * make_copy_attnamelist(LogicalRepRelMapEntry *rel)
Definition: tablesync.c:599
#define ERRCODE_DUPLICATE_OBJECT
Definition: streamutil.c:32
Definition: pg_list.h:50
List * GetSubscriptionNotReadyRelations(Oid subid)
char * get_rel_name(Oid relid)
Definition: lsyscache.c:1899
#define snprintf
Definition: port.h:216
#define WL_LATCH_SET
Definition: latch.h:125
static bool wait_for_worker_state_change(char expected_state)
Definition: tablesync.c:215
#define UINT64_FORMAT
Definition: c.h:484
const TupleTableSlotOps TTSOpsMinimalTuple
Definition: execTuples.c:85
Datum now(PG_FUNCTION_ARGS)
Definition: timestamp.c:1542
#define WL_EXIT_ON_PM_DEATH
Definition: latch.h:130
#define walrcv_exec(conn, exec, nRetTypes, retTypes)
Definition: walreceiver.h:425
void invalidate_syncing_table_states(Datum arg, int cacheid, uint32 hashvalue)
Definition: tablesync.c:264
void ReplicationSlotNameForTablesync(Oid suboid, Oid relid, char *syncslotname, int szslot)
Definition: tablesync.c:885
MemoryContext CacheMemoryContext
Definition: mcxt.c:47
#define RelationGetNamespace(relation)
Definition: rel.h:498
#define walrcv_connect(conninfo, logical, appname, err)
Definition: walreceiver.h:399