forked from pgEdge/spock
-
Notifications
You must be signed in to change notification settings - Fork 0
/
spock_sync.c
2257 lines (1878 loc) · 58.5 KB
/
spock_sync.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*-------------------------------------------------------------------------
*
* spock_sync.c
* table synchronization functions
*
* Copyright (c) 2022-2023, pgEdge, Inc.
* Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, The Regents of the University of California
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <unistd.h>
#ifdef WIN32
#include <process.h>
#else
#include <sys/wait.h>
#endif
#include "libpq-fe.h"
#include "miscadmin.h"
#include "access/genam.h"
#include "access/hash.h"
#include "access/heapam.h"
#include "access/skey.h"
#include "access/stratnum.h"
#include "access/xact.h"
#include "catalog/indexing.h"
#include "catalog/namespace.h"
#include "commands/dbcommands.h"
#include "commands/tablecmds.h"
#include "lib/stringinfo.h"
#include "utils/memutils.h"
#include "nodes/makefuncs.h"
#include "nodes/parsenodes.h"
#include "pgstat.h"
#include "replication/origin.h"
#include "storage/fd.h"
#include "storage/ipc.h"
#include "storage/proc.h"
#include "tcop/utility.h"
#include "utils/builtins.h"
#include "utils/fmgroids.h"
#include "utils/guc.h"
#include "utils/pg_lsn.h"
#include "utils/rel.h"
#include "utils/resowner.h"
#include "spock_relcache.h"
#include "spock_repset.h"
#include "spock_rpc.h"
#include "spock_sync.h"
#include "spock_worker.h"
#include "spock.h"
#define CATALOG_LOCAL_SYNC_STATUS "local_sync_status"
#define PGDUMP_BINARY "pg_dump"
#define PGRESTORE_BINARY "pg_restore"
#define Natts_local_sync_state 6
#define Anum_sync_kind 1
#define Anum_sync_subid 2
#define Anum_sync_nspname 3
#define Anum_sync_relname 4
#define Anum_sync_status 5
#define Anum_sync_statuslsn 6
PGDLLEXPORT void spock_sync_main(Datum main_arg);
static SpockSyncWorker *MySyncWorker = NULL;
#ifdef WIN32
static int exec_cmd_win32(const char *cmd, char *cmdargv[]);
#endif
/*
* Run a command and wait for it to exit, then return its exit code
* in the same format as waitpid() including on Windows.
*
* Does not elog(ERROR).
*
* 'cmd' must be a full relative or absolute path to the executable to
* start. The PATH is not searched.
*
* Preserves each argument in cmdargv as a discrete argument to the child
* process. The first entry in cmdargv is passed as the child process's
* argv[0], so the first "real" argument begins at index 1.
*
* Uses the current environment and working directory.
*
* Note that if we elog(ERROR) or elog(FATAL) here we won't kill the
* child proc.
*/
static int
exec_cmd(const char *cmd, char *cmdargv[])
{
pid_t pid;
int stat;
/* Fire off execv in child */
fflush(stdout);
fflush(stderr);
#ifndef WIN32
if ((pid = fork()) == 0)
{
if (execv(cmd, cmdargv) < 0)
{
ereport(ERROR,
(errmsg("could not execute \"%s\": %m", cmd)));
/* We're already in the child process here, can't return */
exit(1);
}
}
if (waitpid(pid, &stat, 0) != pid)
stat = -1;
#else
stat = exec_cmd_win32(cmd, cmdargv);
#endif
return stat;
}
static void
get_pg_executable(char *cmdname, char *cmdbuf)
{
uint32 version;
if (find_other_exec_version(my_exec_path, cmdname, &version, cmdbuf))
elog(ERROR, "spock subscriber init failed to find %s relative to binary %s",
cmdname, my_exec_path);
if (version / 100 != PG_VERSION_NUM / 100)
elog(ERROR, "spock subscriber init found %s with wrong major version %d.%d, expected %d.%d",
cmdname, version / 100 / 100, version / 100 % 100,
PG_VERSION_NUM / 100 / 100, PG_VERSION_NUM / 100 % 100);
}
static void
dump_structure(SpockSubscription *sub, const char *destfile,
const char *snapshot)
{
char *dsn;
char *err_msg;
char pg_dump[MAXPGPATH];
char *cmdargv[20];
int cmdargc = 0;
bool has_spk_origin;
bool has_snowflake;
StringInfoData s;
dsn = spk_get_connstr((char *) sub->origin_if->dsn, NULL, NULL, &err_msg);
if (dsn == NULL)
elog(ERROR, "invalid connection string \"%s\": %s",
sub->origin_if->dsn, err_msg);
get_pg_executable(PGDUMP_BINARY, pg_dump);
cmdargv[cmdargc++] = pg_dump;
/* custom format */
cmdargv[cmdargc++] = "-Fc";
/* schema only */
cmdargv[cmdargc++] = "-s";
/* snapshot */
initStringInfo(&s);
appendStringInfo(&s, "--snapshot=%s", snapshot);
cmdargv[cmdargc++] = pstrdup(s.data);
resetStringInfo(&s);
/* Dumping database, filter out our extension. */
appendStringInfo(&s, "--exclude-schema=%s", EXTENSION_NAME);
cmdargv[cmdargc++] = pstrdup(s.data);
resetStringInfo(&s);
/* Skip the spock_origin and snowflake if it exists locally. */
StartTransactionCommand();
has_spk_origin = OidIsValid(LookupExplicitNamespace("spock_origin",
true));
has_snowflake = OidIsValid(LookupExplicitNamespace("snowflake",
true));
CommitTransactionCommand();
if (has_spk_origin)
{
appendStringInfo(&s, "--exclude-schema=%s", "spock_origin");
cmdargv[cmdargc++] = pstrdup(s.data);
resetStringInfo(&s);
}
if (has_snowflake)
{
appendStringInfo(&s, "--exclude-schema=%s", "snowflake");
cmdargv[cmdargc++] = pstrdup(s.data);
resetStringInfo(&s);
}
/* destination file */
appendStringInfo(&s, "--file=%s", destfile);
cmdargv[cmdargc++] = pstrdup(s.data);
resetStringInfo(&s);
/* connection string */
appendStringInfo(&s, "--dbname=%s", dsn);
cmdargv[cmdargc++] = pstrdup(s.data);
resetStringInfo(&s);
free(dsn);
cmdargv[cmdargc++] = NULL;
if (exec_cmd(pg_dump, cmdargv) != 0)
ereport(ERROR,
(errcode_for_file_access(),
errmsg("could not execute pg_dump (\"%s\"): %m",
pg_dump)));
}
static void
restore_structure(SpockSubscription *sub, const char *srcfile,
const char *section)
{
char *dsn;
char *err_msg;
char pg_restore[MAXPGPATH];
char *cmdargv[20];
int cmdargc = 0;
StringInfoData s;
dsn = spk_get_connstr((char *) sub->target_if->dsn, NULL,
"-cspock.subscription_schema_restore=true",
&err_msg);
if (dsn == NULL)
elog(ERROR, "invalid connection string \"%s\": %s",
sub->target_if->dsn, err_msg);
get_pg_executable(PGRESTORE_BINARY, pg_restore);
cmdargv[cmdargc++] = pg_restore;
/* section */
if (section)
{
initStringInfo(&s);
appendStringInfo(&s, "--section=%s", section);
cmdargv[cmdargc++] = pstrdup(s.data);
resetStringInfo(&s);
}
/* stop execution on any error */
cmdargv[cmdargc++] = "--exit-on-error";
/* apply everything in single tx */
cmdargv[cmdargc++] = "-1";
/* connection string */
initStringInfo(&s);
appendStringInfo(&s, "--dbname=%s", dsn);
cmdargv[cmdargc++] = pstrdup(s.data);
free(dsn);
/* source file */
cmdargv[cmdargc++] = pstrdup(srcfile);
cmdargv[cmdargc++] = NULL;
if (exec_cmd(pg_restore, cmdargv) != 0)
ereport(ERROR,
(errcode_for_file_access(),
errmsg("could not execute pg_restore (\"%s\"): %m",
pg_restore)));
}
/*
* Create slot and get the exported snapshot.
*
* This will try to recreate slot if already exists and not active.
*
* The reported LSN is the confirmed flush LSN at the point the slot reached
* consistency and exported its snapshot.
*/
static char *
ensure_replication_slot_snapshot(PGconn *sql_conn, PGconn *repl_conn,
char *slot_name, bool use_failover_slot,
XLogRecPtr *lsn)
{
PGresult *res;
StringInfoData query;
char *snapshot;
retry:
initStringInfo(&query);
appendStringInfo(&query, "CREATE_REPLICATION_SLOT \"%s\" LOGICAL %s%s",
slot_name, "spock_output",
use_failover_slot ? " FAILOVER" : "");
res = PQexec(repl_conn, query.data);
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
const char *sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
/*
* If our slot already exist but is not used, it's leftover from
* previous unsucessful attempt to synchronize table, try dropping
* it and recreating.
*/
if (sqlstate &&
strcmp(sqlstate, "42710" /*ERRCODE_DUPLICATE_OBJECT*/) == 0 &&
!spock_remote_slot_active(sql_conn, slot_name))
{
pfree(query.data);
PQclear(res);
spock_drop_remote_slot(sql_conn, slot_name);
goto retry;
}
elog(ERROR, "could not create replication slot on provider: %s\n",
PQresultErrorMessage(res));
}
*lsn = DatumGetLSN(DirectFunctionCall1Coll(pg_lsn_in, InvalidOid,
CStringGetDatum(PQgetvalue(res, 0, 1))));
snapshot = pstrdup(PQgetvalue(res, 0, 2));
PQclear(res);
return snapshot;
}
/*
* Get or create replication origin for a given slot.
*/
static RepOriginId
ensure_replication_origin(char *slot_name)
{
RepOriginId origin = replorigin_by_name(slot_name, true);
if (origin == InvalidRepOriginId)
origin = replorigin_create(slot_name);
return origin;
}
/*
* Transaction management for COPY.
*/
static void
start_copy_origin_tx(PGconn *conn, const char *snapshot)
{
PGresult *res;
char *s;
const char *setup_query =
"BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY;\n"
"SET DATESTYLE = ISO;\n"
"SET INTERVALSTYLE = POSTGRES;\n"
"SET extra_float_digits TO 3;\n"
"SET statement_timeout = 0;\n"
"SET lock_timeout = 0;\n";
StringInfoData query;
initStringInfo(&query);
appendStringInfoString(&query, setup_query);
if (snapshot)
{
s = PQescapeLiteral(conn, snapshot, strlen(snapshot));
appendStringInfo(&query, "SET TRANSACTION SNAPSHOT %s;\n", s);
}
res = PQexec(conn, query.data);
if (PQresultStatus(res) != PGRES_COMMAND_OK)
elog(ERROR, "BEGIN on origin node failed: %s",
PQresultErrorMessage(res));
PQclear(res);
}
static void
start_copy_target_tx(PGconn *conn, const char *origin_name)
{
PGresult *res;
char *s;
const char *setup_query =
"BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED;\n"
"SET session_replication_role = 'replica';\n"
"SET DATESTYLE = ISO;\n"
"SET INTERVALSTYLE = POSTGRES;\n"
"SET extra_float_digits TO 3;\n"
"SET statement_timeout = 0;\n"
"SET lock_timeout = 0;\n";
StringInfoData query;
initStringInfo(&query);
/*
* Set correct origin if target db supports it.
* We must do this before starting the transaction otherwise the status
* code bellow would get much more complicated.
*/
if (PQserverVersion(conn) >= 90500)
{
s = PQescapeLiteral(conn, origin_name, strlen(origin_name));
appendStringInfo(&query,
"SELECT pg_catalog.pg_replication_origin_session_setup(%s);\n",
s);
PQfreemem(s);
}
appendStringInfoString(&query, setup_query);
res = PQexec(conn, query.data);
if (PQresultStatus(res) != PGRES_COMMAND_OK)
elog(ERROR, "BEGIN on target node failed: %s",
PQresultErrorMessage(res));
PQclear(res);
}
static void
finish_copy_origin_tx(PGconn *conn)
{
PGresult *res;
/* Close the transaction and connection on origin node. */
res = PQexec(conn, "ROLLBACK");
if (PQresultStatus(res) != PGRES_COMMAND_OK)
elog(WARNING, "ROLLBACK on origin node failed: %s",
PQresultErrorMessage(res));
PQclear(res);
PQfinish(conn);
}
static void
finish_copy_target_tx(PGconn *conn)
{
PGresult *res;
/* Close the transaction and connection on target node. */
res = PQexec(conn, "COMMIT");
if (PQresultStatus(res) != PGRES_COMMAND_OK)
elog(ERROR, "COMMIT on target node failed: %s",
PQresultErrorMessage(res));
PQclear(res);
/*
* Resetting the origin explicitly before the backend exits will help
* prevent races with other accesses to the same replication origin.
*/
if (PQserverVersion(conn) >= 90500)
{
res = PQexec(conn, "SELECT pg_catalog.pg_replication_origin_session_reset();\n");
if (PQresultStatus(res) != PGRES_TUPLES_OK)
elog(WARNING, "Resetting session origin on target node failed: %s",
PQresultErrorMessage(res));
PQclear(res);
}
PQfinish(conn);
}
static int
physatt_in_attmap(SpockRelation *rel, int attid)
{
AttrNumber i;
for (i = 0; i < rel->natts; i++)
if (rel->attmap[i] == attid)
return i;
return -1;
}
/*
* Create list of columns for COPY based on logical relation mapping.
*/
static List *
make_copy_attnamelist(SpockRelation *rel)
{
List *attnamelist = NIL;
TupleDesc desc = RelationGetDescr(rel->rel);
int attnum;
for (attnum = 0; attnum < desc->natts; attnum++)
{
int remoteattnum = physatt_in_attmap(rel, attnum);
/* Skip dropped attributes. */
if (TupleDescAttr(desc,attnum)->attisdropped)
continue;
if (remoteattnum < 0)
continue;
attnamelist = lappend(attnamelist,
makeString(rel->attnames[remoteattnum]));
}
return attnamelist;
}
/*
* COPY single table over wire.
*/
static void
copy_table_data(PGconn *origin_conn, PGconn *target_conn,
SpockRemoteRel *remoterel, List *replication_sets)
{
SpockRelation *rel;
PGresult *res;
int bytes;
char *copybuf;
List *attnamelist;
ListCell *lc;
bool first;
StringInfoData query;
StringInfoData attlist;
MemoryContext curctx = CurrentMemoryContext,
oldctx;
/* Build the relation map. */
StartTransactionCommand();
oldctx = MemoryContextSwitchTo(curctx);
spock_relation_cache_updater(remoterel);
rel = spock_relation_open(remoterel->relid, AccessShareLock);
attnamelist = make_copy_attnamelist(rel);
initStringInfo(&attlist);
first = true;
foreach (lc, attnamelist)
{
char *attname = strVal(lfirst(lc));
if (first)
first = false;
else
appendStringInfoString(&attlist, ",");
appendStringInfoString(&attlist,
PQescapeIdentifier(origin_conn, attname,
strlen(attname)));
}
MemoryContextSwitchTo(oldctx);
spock_relation_close(rel, AccessShareLock);
CommitTransactionCommand();
/* Build COPY TO query. */
initStringInfo(&query);
appendStringInfoString(&query, "COPY ");
/*
* If the table is row-filtered we need to run query over the table
* to execute the filter.
*/
if (remoterel->hasRowFilter)
{
StringInfoData relname;
StringInfoData repsetarr;
initStringInfo(&relname);
appendStringInfo(&relname, "%s.%s",
PQescapeIdentifier(origin_conn, remoterel->nspname,
strlen(remoterel->nspname)),
PQescapeIdentifier(origin_conn, remoterel->relname,
strlen(remoterel->relname)));
initStringInfo(&repsetarr);
first = true;
foreach (lc, replication_sets)
{
char *repset_name = lfirst(lc);
if (first)
first = false;
else
appendStringInfoChar(&repsetarr, ',');
appendStringInfo(&repsetarr, "%s",
PQescapeLiteral(origin_conn, repset_name,
strlen(repset_name)));
}
appendStringInfo(&query,
"(SELECT %s FROM spock.table_data_filtered(NULL::%s, %s::regclass, ARRAY[%s])) ",
list_length(attnamelist) ? attlist.data : "*",
relname.data,
PQescapeLiteral(origin_conn, relname.data, relname.len),
repsetarr.data);
}
else
{
if (remoterel->relkind == RELKIND_PARTITIONED_TABLE)
{
/* use COPY(SELECT...) for partitioned tables. */
appendStringInfo(&query, "(SELECT %s FROM %s.%s) ",
list_length(attnamelist) ? attlist.data : "*",
PQescapeIdentifier(origin_conn, remoterel->nspname,
strlen(remoterel->nspname)),
PQescapeIdentifier(origin_conn, remoterel->relname,
strlen(remoterel->relname)));
}
else
{
/* Otherwise just copy the table. */
appendStringInfo(&query, "%s.%s ",
PQescapeIdentifier(origin_conn, remoterel->nspname,
strlen(remoterel->nspname)),
PQescapeIdentifier(origin_conn, remoterel->relname,
strlen(remoterel->relname)));
if (list_length(attnamelist))
appendStringInfo(&query, "(%s) ", attlist.data);
}
}
appendStringInfoString(&query, "TO stdout");
/* Execute COPY TO. */
res = PQexec(origin_conn, query.data);
if (PQresultStatus(res) != PGRES_COPY_OUT)
{
ereport(ERROR,
(errmsg("table copy failed"),
errdetail("Query '%s': %s", query.data,
PQerrorMessage(origin_conn))));
}
/* Build COPY FROM query. */
resetStringInfo(&query);
appendStringInfo(&query, "COPY %s.%s ",
PQescapeIdentifier(origin_conn, remoterel->nspname,
strlen(remoterel->nspname)),
PQescapeIdentifier(origin_conn, remoterel->relname,
strlen(remoterel->relname)));
if (list_length(attnamelist))
appendStringInfo(&query, "(%s) ", attlist.data);
appendStringInfoString(&query, "FROM stdin");
/* Execute COPY FROM. */
res = PQexec(target_conn, query.data);
if (PQresultStatus(res) != PGRES_COPY_IN)
{
ereport(ERROR,
(errmsg("table copy failed"),
errdetail("Query '%s': %s", query.data,
PQerrorMessage(origin_conn))));
}
while ((bytes = PQgetCopyData(origin_conn, ©buf, false)) > 0)
{
if (PQputCopyData(target_conn, copybuf, bytes) != 1)
{
ereport(ERROR,
(errmsg("writing to target table failed"),
errdetail("destination connection reported: %s",
PQerrorMessage(target_conn))));
}
PQfreemem(copybuf);
CHECK_FOR_INTERRUPTS();
}
if (bytes != -1)
{
ereport(ERROR,
(errmsg("reading from origin table failed"),
errdetail("source connection returned %d: %s",
bytes, PQerrorMessage(origin_conn))));
}
/* Send local finish */
if (PQputCopyEnd(target_conn, NULL) != 1)
{
ereport(ERROR,
(errmsg("sending copy-completion to destination connection failed"),
errdetail("destination connection reported: %s",
PQerrorMessage(target_conn))));
}
PQclear(res);
elog(INFO, "finished synchronization of data for table %s.%s",
remoterel->nspname, remoterel->relname);
}
/*
* Copy data from origin node to target node.
*
* Creates new connection to origin and target.
*/
static void
copy_tables_data(char *sub_name, const char *origin_dsn,
const char *target_dsn, const char *origin_snapshot,
List *tables, List *replication_sets,
const char *origin_name)
{
PGconn *origin_conn;
PGconn *target_conn;
ListCell *lc;
/* Connect to origin node. */
origin_conn = spock_connect(origin_dsn, sub_name, "copy");
start_copy_origin_tx(origin_conn, origin_snapshot);
/* Connect to target node. */
target_conn = spock_connect(target_dsn, sub_name, "copy");
start_copy_target_tx(target_conn, origin_name);
/* Copy every table. */
foreach (lc, tables)
{
RangeVar *rv = lfirst(lc);
SpockRemoteRel *remoterel;
remoterel = spock_get_remote_repset_table(origin_conn, rv,
replication_sets);
/*
* In case of table partitioning, we synchronize the partitioned
* (parent) table and skip the partitions. Other tables are synchronized
* normally.
*/
if (!remoterel->ispartition)
copy_table_data(origin_conn, target_conn, remoterel, replication_sets);
CHECK_FOR_INTERRUPTS();
}
/* Finish the transactions and disconnect. */
finish_copy_origin_tx(origin_conn);
finish_copy_target_tx(target_conn);
}
/*
* Copy data from origin node to target node.
*
* Creates new connection to origin and target.
*
* This is basically same as the copy_tables_data, but it can't be easily
* merged to single function because we need to get list of tables here after
* the transaction is bound to a snapshot.
*/
static List *
copy_replication_sets_data(char *sub_name, const char *origin_dsn,
const char *target_dsn,
const char *origin_snapshot,
List *replication_sets, const char *origin_name)
{
PGconn *origin_conn;
PGconn *target_conn;
List *tables;
ListCell *lc;
/* Connect to origin node. */
origin_conn = spock_connect(origin_dsn, sub_name, "copy");
start_copy_origin_tx(origin_conn, origin_snapshot);
/* Get tables to copy from origin node. */
tables = spock_get_remote_repset_tables(origin_conn,
replication_sets);
/* Connect to target node. */
target_conn = spock_connect(target_dsn, sub_name, "copy");
start_copy_target_tx(target_conn, origin_name);
/* Copy every table. */
foreach (lc, tables)
{
SpockRemoteRel *remoterel = lfirst(lc);
/*
* In case of table partitioning, we synchronize the partitioned
* (parent) table and skip the partitions. Other tables are synchronized
* normally.
*/
if (!remoterel->ispartition)
copy_table_data(origin_conn, target_conn, remoterel, replication_sets);
CHECK_FOR_INTERRUPTS();
}
/* Finish the transactions and disconnect. */
finish_copy_origin_tx(origin_conn);
finish_copy_target_tx(target_conn);
return tables;
}
static void
spock_sync_worker_cleanup(SpockSubscription *sub)
{
PGconn *origin_conn;
/* Drop the slot on the remote side. */
origin_conn = spock_connect(sub->origin_if->dsn, sub->name,
"cleanup");
/* Wait for slot to be free. */
while (!got_SIGTERM)
{
int rc;
if (!spock_remote_slot_active(origin_conn, sub->slot_name))
break;
rc = WaitLatch(&MyProc->procLatch,
WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
1000L);
ResetLatch(&MyProc->procLatch);
/* emergency bailout if postmaster has died */
if (rc & WL_POSTMASTER_DEATH)
proc_exit(1);
}
spock_drop_remote_slot(origin_conn, sub->slot_name);
PQfinish(origin_conn);
/* Drop the origin tracking locally. */
if (replorigin_session_origin != InvalidRepOriginId)
{
replorigin_session_reset();
#if PG_VERSION_NUM >= 140000
replorigin_drop_by_name(sub->slot_name, true, true);
#else
replorigin_drop(replorigin_session_origin, true);
#endif
replorigin_session_origin = InvalidRepOriginId;
}
}
static void
spock_sync_worker_cleanup_error_cb(int code, Datum arg)
{
SpockSubscription *sub = (SpockSubscription *) DatumGetPointer(arg);
spock_sync_worker_cleanup(sub);
}
static void
spock_sync_tmpfile_cleanup_cb(int code, Datum arg)
{
const char *tmpfile = DatumGetCString(arg);
if (unlink(tmpfile) != 0 && errno != ENOENT)
elog(WARNING, "Failed to clean up spock temporary dump file \"%s\" on exit/error: %m",
tmpfile);
}
void
spock_sync_subscription(SpockSubscription *sub)
{
SpockSyncStatus *sync;
XLogRecPtr lsn;
char status;
MemoryContext myctx,
oldctx;
/* We need our own context for keeping things between transactions. */
myctx = AllocSetContextCreate(CurrentMemoryContext,
"spock_sync_subscription cxt",
ALLOCSET_DEFAULT_SIZES);
StartTransactionCommand();
oldctx = MemoryContextSwitchTo(myctx);
sync = get_subscription_sync_status(sub->id, false);
MemoryContextSwitchTo(oldctx);
CommitTransactionCommand();
status = sync->status;
switch (status)
{
/* Already synced, nothing to do except cleanup. */
case SYNC_STATUS_READY:
MemoryContextDelete(myctx);
return;
/* We can recover from crashes during these. */
case SYNC_STATUS_INIT:
case SYNC_STATUS_CATCHUP:
break;
default:
elog(ERROR,
"subscriber %s initialization failed during nonrecoverable step (%c), please try the setup again",
sub->name, status);
break;
}
if (status == SYNC_STATUS_INIT)
{
PGconn *origin_conn;
PGconn *origin_conn_repl;
RepOriginId originid;
char *snapshot;
bool use_failover_slot;
elog(INFO, "initializing subscriber %s", sub->name);
origin_conn = spock_connect(sub->origin_if->dsn,
sub->name, "snap");
/* 2QPG9.6 and 2QPG11 support failover slots */
use_failover_slot =
spock_remote_function_exists(origin_conn, "pg_catalog",
"pg_create_logical_replication_slot",
-1,
"failover");
origin_conn_repl = spock_connect_replica(sub->origin_if->dsn,
sub->name, "snap");
snapshot = ensure_replication_slot_snapshot(origin_conn,
origin_conn_repl,
sub->slot_name,
use_failover_slot, &lsn);
PQfinish(origin_conn);
PG_ENSURE_ERROR_CLEANUP(spock_sync_worker_cleanup_error_cb,
PointerGetDatum(sub));
{
char tmpfile[MAXPGPATH];
snprintf(tmpfile, MAXPGPATH, "%s/spock-%d.dump",
spock_temp_directory, MyProcPid);
canonicalize_path(tmpfile);
PG_ENSURE_ERROR_CLEANUP_SUFFIX(spock_sync_tmpfile_cleanup_cb,
CStringGetDatum(tmpfile), _suf);
{
Relation replorigin_rel;
StartTransactionCommand();
originid = ensure_replication_origin(sub->slot_name);
elog(DEBUG3, "advancing origin with oid %u for forwarded row to %X/%X during subscription sync",
originid,
(uint32)(XactLastCommitEnd>>32), (uint32)XactLastCommitEnd);
replorigin_rel = table_open(ReplicationOriginRelationId, RowExclusiveLock);
replorigin_advance(originid, lsn, XactLastCommitEnd, true,
true);
table_close(replorigin_rel, RowExclusiveLock);
CommitTransactionCommand();
if (SyncKindStructure(sync->kind))
{
elog(INFO, "synchronizing structure");
status = SYNC_STATUS_STRUCTURE;
StartTransactionCommand();
set_subscription_sync_status(sub->id, status);
CommitTransactionCommand();
/* Dump structure to temp storage. */
dump_structure(sub, tmpfile, snapshot);
/* Restore base pre-data structure (types, tables, etc). */
restore_structure(sub, tmpfile, "pre-data");
}
/* Copy data. */
if (SyncKindData(sync->kind))
{
List *tables;
ListCell *lc;
elog(INFO, "synchronizing data");
status = SYNC_STATUS_DATA;
StartTransactionCommand();
set_subscription_sync_status(sub->id, status);
CommitTransactionCommand();
tables = copy_replication_sets_data(sub->name,
sub->origin_if->dsn,
sub->target_if->dsn,
snapshot,
sub->replication_sets,
sub->slot_name);