forked from 2ndQuadrant/bdr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbdr_init_replica.c
1234 lines (1068 loc) · 37.2 KB
/
bdr_init_replica.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
/* -------------------------------------------------------------------------
*
* bdr_init_replica.c
* Populate a new bdr node from the data in an existing node
*
* Use dump and restore, then bdr catchup mode, to bring up a new
* bdr node into a bdr group. Allows a new blank database to be
* introduced into an existing, already-working bdr group.
*
* Copyright (C) 2012-2015, PostgreSQL Global Development Group
*
* IDENTIFICATION
* bdr_init_replica.c
*
* -------------------------------------------------------------------------
*/
#include "postgres.h"
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include "bdr.h"
#include "fmgr.h"
#include "funcapi.h"
#include "libpq-fe.h"
#include "miscadmin.h"
#include "libpq/pqformat.h"
#include "access/heapam.h"
#include "access/xact.h"
#include "catalog/pg_type.h"
#include "executor/spi.h"
#include "replication/replication_identifier.h"
#include "replication/walreceiver.h"
#include "postmaster/bgworker.h"
#include "postmaster/bgwriter.h"
#include "storage/ipc.h"
#include "storage/latch.h"
#include "storage/lwlock.h"
#include "storage/proc.h"
#include "storage/shmem.h"
#include "utils/builtins.h"
#include "utils/memutils.h"
#include "utils/pg_lsn.h"
#include "utils/syscache.h"
char *bdr_temp_dump_directory = NULL;
static void bdr_init_exec_dump_restore(BDRNodeInfo *node,
char *snapshot);
static void bdr_catchup_to_lsn(remote_node_info *ri, XLogRecPtr target_lsn);
static XLogRecPtr
bdr_get_remote_lsn(PGconn *conn)
{
XLogRecPtr lsn;
PGresult *res;
res = PQexec(conn, "SELECT pg_current_xlog_insert_location()");
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
elog(ERROR, "Unable to get remote LSN: status %s: %s\n",
PQresStatus(PQresultStatus(res)), PQresultErrorMessage(res));
}
Assert(PQntuples(res) == 1);
Assert(!PQgetisnull(res, 0, 0));
lsn = DatumGetLSN(DirectFunctionCall1Coll(pg_lsn_in, InvalidOid,
CStringGetDatum(PQgetvalue(res, 0, 0))));
PQclear(res);
return lsn;
}
static void
bdr_get_remote_ext_version(PGconn *pgconn, char **default_version,
char **installed_version)
{
PGresult *res;
const char *q_bdr_installed =
"SELECT default_version, installed_version "
"FROM pg_catalog.pg_available_extensions WHERE name = 'bdr';";
res = PQexec(pgconn, q_bdr_installed);
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
elog(ERROR, "Unable to get remote bdr extension version; query %s failed with %s: %s\n",
q_bdr_installed, PQresStatus(PQresultStatus(res)), PQresultErrorMessage(res));
}
if (PQntuples(res) == 1)
{
/*
* bdr ext is known to Pg, check install state.
*/
*default_version = pstrdup(PQgetvalue(res, 0, 0));
*installed_version = pstrdup(PQgetvalue(res, 0, 0));
}
else if (PQntuples(res) == 0)
{
/* bdr ext is not known to Pg at all */
*default_version = NULL;
*installed_version = NULL;
}
else
{
Assert(false); /* Should not get >1 tuples */
}
PQclear(res);
}
/*
* Make sure the bdr extension is installed on the other end. If it's a known
* extension but not present in the current DB error out and tell the user to
* activate BDR then try again.
*/
void
bdr_ensure_ext_installed(PGconn *pgconn)
{
char *default_version = NULL;
char *installed_version = NULL;
bdr_get_remote_ext_version(pgconn, &default_version, &installed_version);
if (default_version == NULL || strcmp(default_version, "") == 0)
{
ereport(ERROR,
(errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("Remote PostgreSQL install for bdr connection does not have bdr extension installed"),
errdetail("no entry with name 'bdr' in pg_available_extensions."),
errhint("You need to install the BDR extension on the remote end")));
}
if (installed_version == NULL || strcmp(installed_version, "") == 0)
{
ereport(ERROR,
(errcode(ERRCODE_CONFIG_FILE_ERROR),
errmsg("Remote database for BDR connection does not have the bdr extension active"),
errdetail("installed_version for entry 'bdr' in pg_available_extensions is blank"),
errhint("Run 'CREATE EXTENSION bdr;'")));
}
pfree(default_version);
pfree(installed_version);
}
static void
bdr_init_replica_cleanup_tmpdir(int errcode, Datum tmpdir)
{
struct stat st;
const char* dir = DatumGetCString(tmpdir);
if (stat(dir, &st) == 0)
if (!rmtree(dir, true))
elog(WARNING, "Failed to clean up bdr dump temporary directory %s on exit/error", dir);
}
/*
* Use a script to copy the contents of a remote node using pg_dump and apply
* it to the local node. Runs during node join creation to bring up a new
* logical replica from an existing node. The remote dump is taken from the
* start position of a slot on the remote end to ensure that we never replay
* changes included in the dump and never miss changes.
*/
static void
bdr_init_exec_dump_restore(BDRNodeInfo *node,
char *snapshot)
{
#ifndef WIN32
pid_t pid;
char *bindir;
char *tmpdir;
char bdr_init_replica_script_path[MAXPGPATH];
char bdr_dump_path[MAXPGPATH];
char bdr_restore_path[MAXPGPATH];
StringInfoData path;
StringInfoData origin_dsn;
StringInfoData local_dsn;
int saved_errno;
uint32 bin_version;
initStringInfo(&path);
initStringInfo(&origin_dsn);
initStringInfo(&local_dsn);
bindir = pstrdup(my_exec_path);
get_parent_directory(bindir);
if (bdr_find_other_exec(my_exec_path, BDR_INIT_REPLICA_CMD,
&bin_version,
&bdr_init_replica_script_path[0]) < 0)
{
elog(ERROR, "bdr node init failed to find " BDR_INIT_REPLICA_CMD
" relative to binary %s",
my_exec_path);
}
if (bin_version / 100 != PG_VERSION_NUM / 100)
{
elog(ERROR, "bdr node init found " BDR_INIT_REPLICA_CMD
" with wrong major version %d.%d, expected %d.%d",
bin_version / 100 / 100, bin_version / 100 % 100,
PG_VERSION_NUM / 100 / 100, PG_VERSION_NUM / 100 % 100);
}
if (bdr_find_other_exec(my_exec_path, BDR_DUMP_CMD,
&bin_version,
&bdr_dump_path[0]) < 0)
{
elog(ERROR, "bdr node init failed to find " BDR_DUMP_CMD
" relative to binary %s",
my_exec_path);
}
if (bin_version / 100 != PG_VERSION_NUM / 100)
{
elog(ERROR, "bdr node init found " BDR_DUMP_CMD
" with wrong major version %d.%d, expected %d.%d",
bin_version / 100 / 100, bin_version / 100 % 100,
PG_VERSION_NUM / 100 / 100, PG_VERSION_NUM / 100 % 100);
}
if (bdr_find_other_exec(my_exec_path, BDR_RESTORE_CMD,
&bin_version,
&bdr_restore_path[0]) < 0)
{
elog(ERROR, "bdr node init failed to find " BDR_RESTORE_CMD
" relative to binary %s",
my_exec_path);
}
if (bin_version / 100 != PG_VERSION_NUM / 100)
{
elog(ERROR, "bdr node init found " BDR_RESTORE_CMD
" with wrong major version %d.%d, expected %d.%d",
bin_version / 100 / 100, bin_version / 100 % 100,
PG_VERSION_NUM / 100 / 100, PG_VERSION_NUM / 100 % 100);
}
appendStringInfoString(&origin_dsn, bdr_default_apply_connection_options);
appendStringInfoChar(&origin_dsn, ' ');
appendStringInfoString(&origin_dsn, bdr_extra_apply_connection_options);
appendStringInfoChar(&origin_dsn, ' ');
appendStringInfoString(&origin_dsn, node->init_from_dsn);
appendStringInfo(&origin_dsn,
" fallback_application_name='"BDR_LOCALID_FORMAT": init_replica dump'",
BDR_LOCALID_FORMAT_ARGS);
appendStringInfo(&local_dsn,
"%s fallback_application_name='"BDR_LOCALID_FORMAT": init_replica restore'",
node->local_dsn, BDR_LOCALID_FORMAT_ARGS);
/*
* Suppress replication of changes applied via pg_restore back to
* the local node.
*
* TODO: This should PQconninfoParse, modify the options keyword or add
* it, and reconstruct the string using the functions from pg_dumpall
* (also to be used for init_copy). Simply appending the options
* instead is a bit dodgy.
*/
appendStringInfoString(&local_dsn,
" options='-c bdr.do_not_replicate=on "
" -c bdr.permit_unsafe_ddl_commands=on"
" -c bdr.skip_ddl_replication=on"
" -c bdr.skip_ddl_locking=on"
" -c session_replication_role=replica'");
tmpdir = palloc(strlen(bdr_temp_dump_directory)+32);
sprintf(tmpdir, "%s/postgres-bdr-%s.%d", bdr_temp_dump_directory,
snapshot, getpid());
if (mkdir(tmpdir, 0700))
{
saved_errno = errno;
if (saved_errno == EEXIST)
{
/*
* Target is an existing dir that somehow wasn't cleaned up or
* something more sinister. We'll just die here, and let the
* postmaster relaunch us and retry the whole operation.
*/
elog(ERROR, "bdr init_replica: Temporary dump directory %s exists: %s",
tmpdir, strerror(saved_errno));
}
else
{
elog(ERROR, "bdr init_replica: Failed to create temp directory: %s",
strerror(saved_errno));
}
}
pid = fork();
if (pid < 0)
elog(FATAL, "can't fork to create initial replica");
else if (pid == 0)
{
int n = 0;
char *const argv[] = {
bdr_init_replica_script_path,
"--snapshot", snapshot,
"--source", origin_dsn.data,
"--target", local_dsn.data,
"--tmp-directory", tmpdir,
"--pg-dump-path", bdr_dump_path,
"--pg-restore-path", bdr_restore_path,
NULL
};
ereport(LOG,
(errmsg("Creating replica with: %s --snapshot %s --source \"%s\" --target \"%s\" --tmp-directory \"%s\", --pg-dump-path \"%s\", --pg-restore-path \"%s\"",
bdr_init_replica_script_path, snapshot,
node->init_from_dsn, node->local_dsn, tmpdir,
bdr_dump_path, bdr_restore_path)));
n = execv(bdr_init_replica_script_path, argv);
if (n < 0)
_exit(n);
}
else
{
pid_t res;
int exitstatus = 0;
elog(DEBUG3, "Waiting for %s pid %d",
bdr_init_replica_script_path, pid);
PG_ENSURE_ERROR_CLEANUP(bdr_init_replica_cleanup_tmpdir,
CStringGetDatum(tmpdir));
{
do
{
res = waitpid(pid, &exitstatus, WNOHANG);
if (res < 0)
{
if (errno == EINTR || errno == EAGAIN)
continue;
elog(FATAL, "bdr_exec_init_replica: error calling waitpid");
}
else if (res == pid)
break;
pg_usleep(10 * 1000);
CHECK_FOR_INTERRUPTS();
}
while (1);
elog(DEBUG3, "%s exited with waitpid return status %d",
bdr_init_replica_script_path, exitstatus);
if (exitstatus != 0)
{
if (WIFEXITED(exitstatus))
elog(FATAL, "bdr: %s exited with exit code %d",
bdr_init_replica_script_path, WEXITSTATUS(exitstatus));
if (WIFSIGNALED(exitstatus))
elog(FATAL, "bdr: %s exited due to signal %d",
bdr_init_replica_script_path, WTERMSIG(exitstatus));
elog(FATAL, "bdr: %s exited for an unknown reason with waitpid return %d",
bdr_init_replica_script_path, exitstatus);
}
}
PG_END_ENSURE_ERROR_CLEANUP(bdr_init_replica_cleanup_tmpdir,
PointerGetDatum(tmpdir));
bdr_init_replica_cleanup_tmpdir(0, CStringGetDatum(tmpdir));
}
pfree(tmpdir);
#else
/*
* On Windows we should be using CreateProcessEx instead of fork() and
* exec(). We should add an abstraction for this to port/ eventually,
* so this code doesn't have to care about the platform.
*
* TODO
*/
ereport(ERROR,
(errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
errmsg("init_replica isn't supported on Windows yet")));
#endif
}
/*
* BDR state synchronization.
*/
static void
bdr_sync_nodes(PGconn *remote_conn, BDRNodeInfo *local_node)
{
PGconn *local_conn;
local_conn = bdr_connect_nonrepl(local_node->local_dsn, "init");
PG_ENSURE_ERROR_CLEANUP(bdr_cleanup_conn_close,
PointerGetDatum(&local_conn));
{
StringInfoData query;
PGresult *res;
char sysid_str[33];
const char *const setup_query =
"BEGIN TRANSACTION ISOLATION LEVEL READ COMMITTED;\n"
"SET LOCAL search_path = bdr, pg_catalog;\n"
"SET LOCAL bdr.permit_unsafe_ddl_commands = on;\n"
"SET LOCAL bdr.skip_ddl_replication = on;\n"
"SET LOCAL bdr.skip_ddl_locking = on;\n"
"LOCK TABLE bdr.bdr_nodes IN EXCLUSIVE MODE;\n"
"LOCK TABLE bdr.bdr_connections IN EXCLUSIVE MODE;\n";
/* Setup the environment. */
res = PQexec(remote_conn, setup_query);
if (PQresultStatus(res) != PGRES_COMMAND_OK)
elog(ERROR, "BEGIN or table locking on remote failed: %s",
PQresultErrorMessage(res));
PQclear(res);
res = PQexec(local_conn, setup_query);
if (PQresultStatus(res) != PGRES_COMMAND_OK)
elog(ERROR, "BEGIN or table locking on local failed: %s",
PQresultErrorMessage(res));
PQclear(res);
/* Copy remote bdr_nodes entries to the local node. */
bdr_copytable(remote_conn, local_conn,
"COPY (SELECT * FROM bdr.bdr_nodes) TO stdout",
"COPY bdr.bdr_nodes FROM stdin");
/* Copy the local entry to remote node. */
initStringInfo(&query);
/* No need to quote as everything is numbers. */
snprintf(sysid_str, sizeof(sysid_str), UINT64_FORMAT, local_node->id.sysid);
sysid_str[sizeof(sysid_str)-1] = '\0';
appendStringInfo(&query,
"COPY (SELECT * FROM bdr.bdr_nodes WHERE "
"node_sysid = '%s' AND node_timeline = '%u' "
"AND node_dboid = '%u') TO stdout",
sysid_str, local_node->id.timeline, local_node->id.dboid);
bdr_copytable(local_conn, remote_conn,
query.data, "COPY bdr.bdr_nodes FROM stdin");
/*
* Copy remote connections to the local node.
*
* Adding local connection to remote node is handled separately
* because it triggers the connect-back process on the remote node(s).
*/
bdr_copytable(remote_conn, local_conn,
"COPY (SELECT * FROM bdr.bdr_connections) TO stdout",
"COPY bdr.bdr_connections FROM stdin");
/* Save changes. */
res = PQexec(remote_conn, "COMMIT");
if (PQresultStatus(res) != PGRES_COMMAND_OK)
elog(ERROR, "COMMIT on remote failed: %s",
PQresultErrorMessage(res));
PQclear(res);
res = PQexec(local_conn, "COMMIT");
if (PQresultStatus(res) != PGRES_COMMAND_OK)
elog(ERROR, "COMMIT on remote failed: %s",
PQresultErrorMessage(res));
PQclear(res);
}
PG_END_ENSURE_ERROR_CLEANUP(bdr_cleanup_conn_close,
PointerGetDatum(&local_conn));
PQfinish(local_conn);
}
static void
bdr_insert_remote_conninfo(PGconn *conn, BdrConnectionConfig *myconfig)
{
#define INTERNAL_NODE_JOIN_NPARAMS 6
PGresult *res;
Oid types[INTERNAL_NODE_JOIN_NPARAMS] = { TEXTOID, OIDOID, OIDOID, TEXTOID, INT4OID, TEXTARRAYOID };
const char *values[INTERNAL_NODE_JOIN_NPARAMS];
StringInfoData replicationsets;
/* Needs to fit max length of UINT64_FORMAT */
char sysid_str[33];
char tlid_str[33];
char mydatabaseid_str[33];
char apply_delay[33];
initStringInfo(&replicationsets);
stringify_my_node_identity(sysid_str, sizeof(sysid_str),
tlid_str, sizeof(tlid_str),
mydatabaseid_str, sizeof(mydatabaseid_str));
values[0] = &sysid_str[0];
values[1] = &tlid_str[0];
values[2] = &mydatabaseid_str[0];
values[3] = myconfig->dsn;
snprintf(&apply_delay[0], 33, "%d", myconfig->apply_delay);
values[4] = &apply_delay[0];
/*
* Replication sets are stored as a quoted identifier list. To turn
* it into an array literal we can just wrap some brackets around it.
*/
appendStringInfo(&replicationsets, "{%s}", myconfig->replication_sets);
values[5] = replicationsets.data;
res = PQexecParams(conn,
"SELECT bdr.internal_node_join($1,$2,$3,$4,$5,$6);",
INTERNAL_NODE_JOIN_NPARAMS,
types, &values[0], NULL, NULL, 0);
/*
* bdr.internal_node_join() must correctly handle unique violations.
* Otherwise init that resumes after slot creation, when we're waiting
* for inbound slots, will fail.
*/
if (PQresultStatus(res) != PGRES_TUPLES_OK)
elog(ERROR, "unable to update remote bdr.bdr_connections: %s",
PQerrorMessage(conn));
#undef INTERNAL_NODE_JOIN_NPARAMS
}
/*
* Find all connections other than our own using the copy of
* bdr.bdr_connections that we acquired from the remote server during
* apply. Apply workers won't be started yet, we're just making the
* slots.
*
* If the slot already exists from a prior attempt we'll leave it
* alone. It'll be advanced when we start replaying from it anyway,
* and it's guaranteed to retain more than the WAL we need.
*/
static void
bdr_init_make_other_slots()
{
List *configs;
ListCell *lc;
MemoryContext old_context;
Assert(!IsTransactionState());
StartTransactionCommand();
old_context = MemoryContextSwitchTo(TopMemoryContext);
configs = bdr_read_connection_configs();
MemoryContextSwitchTo(old_context);
CommitTransactionCommand();
foreach(lc, configs)
{
BdrConnectionConfig *cfg = lfirst(lc);
PGconn *conn;
NameData slot_name;
uint64 sysid;
TimeLineID timeline;
Oid dboid;
RepNodeId replication_identifier;
char *snapshot;
if (cfg->sysid == GetSystemIdentifier() &&
cfg->timeline == ThisTimeLineID &&
cfg->dboid == MyDatabaseId)
{
/* Don't make a slot pointing to ourselves */
continue;
bdr_free_connection_config(cfg);
}
conn = bdr_establish_connection_and_slot(cfg->dsn, "mkslot", &slot_name,
&sysid, &timeline, &dboid, &replication_identifier,
&snapshot);
/* Ensure the slot points to the node the conn info says it should */
if (cfg->sysid != sysid ||
cfg->timeline != timeline ||
cfg->dboid != dboid)
{
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("System identification mismatch between connection and slot"),
errdetail("Connection for "BDR_LOCALID_FORMAT" resulted in slot on node "BDR_LOCALID_FORMAT" instead of expected node",
cfg->sysid, cfg->timeline, cfg->dboid, EMPTY_REPLICATION_NAME,
sysid, timeline, dboid, EMPTY_REPLICATION_NAME)));
}
/* We don't require the snapshot IDs here */
if (snapshot != NULL)
pfree(snapshot);
/* No replication for now, just close the connection */
PQfinish(conn);
elog(DEBUG2, "Ensured existence of slot %s on "BDR_LOCALID_FORMAT,
NameStr(slot_name), cfg->sysid, cfg->timeline, cfg->dboid,
EMPTY_REPLICATION_NAME);
bdr_free_connection_config(cfg);
}
list_free(configs);
}
/*
* For each outbound connection in bdr.bdr_connections we should have a local
* replication slot created by a remote node using our connection info.
*
* Wait until all such entries are created and active, then return.
*/
static void
bdr_init_wait_for_slot_creation()
{
List *configs;
ListCell *lc;
ListCell *next,
*prev;
elog(INFO, "waiting for all inbound slots to be established");
/*
* Determine the list of expected slot identifiers. These are
* inbound slots, so they're our db oid + the remote's bdr ident.
*/
StartTransactionCommand();
configs = bdr_read_connection_configs();
/* Cleanup the config list from the ones we are not insterested in. */
prev = NULL;
for (lc = list_head(configs); lc; lc = next)
{
BdrConnectionConfig *cfg = lfirst(lc);
/* We might delete the cell so advance it now. */
next = lnext(lc);
/*
* We won't see an inbound slot from our own node.
*/
if (cfg->sysid == GetSystemIdentifier() &&
cfg->timeline == ThisTimeLineID &&
cfg->dboid == MyDatabaseId)
{
configs = list_delete_cell(configs, lc, prev);
break;
}
else
prev = lc;
}
/*
* Wait for each slot to reach consistent point.
*
* This works by checking for BDR_WORKER_WALSENDER in the worker array.
* The reason for checking this way is that the worker structure for
* BDR_WORKER_WALSENDER is setup from startup_cb which is called after the
* consistent point was reached.
*/
while (true)
{
int found = 0;
int slotoff;
foreach(lc, configs)
{
BdrConnectionConfig *cfg = lfirst(lc);
if (cfg->sysid == GetSystemIdentifier() &&
cfg->timeline == ThisTimeLineID &&
cfg->dboid == MyDatabaseId)
{
/* We won't see an inbound slot from our own node */
continue;
}
LWLockAcquire(BdrWorkerCtl->lock, LW_EXCLUSIVE);
for (slotoff = 0; slotoff < bdr_max_workers; slotoff++)
{
BdrWorker *w = &BdrWorkerCtl->slots[slotoff];
if (w->worker_type != BDR_WORKER_WALSENDER)
continue;
if (cfg->sysid == w->data.walsnd.remote_sysid &&
cfg->timeline == w->data.walsnd.remote_timeline &&
cfg->dboid == w->data.walsnd.remote_dboid &&
w->worker_proc &&
w->worker_proc->databaseId == MyDatabaseId)
found ++;
}
LWLockRelease(BdrWorkerCtl->lock);
}
if (found == list_length(configs))
break;
elog(DEBUG2, "found %u of %u expected slots, sleeping",
(uint32)found, (uint32)list_length(configs));
pg_usleep(100000);
}
CommitTransactionCommand();
elog(INFO, "all inbound slots established");
}
/*
* TODO DYNCONF perform_pointless_transaction
*
* This is temporary code to be removed when the full part/join protocol is
* introduced, at which point WAL messages should handle this. See comments on
* call site.
*/
static void
perform_pointless_transaction(PGconn *conn, BDRNodeInfo *node)
{
PGresult *res;
res = PQexec(conn, "CREATE TEMP TABLE bdr_init(a int) ON COMMIT DROP");
Assert(PQresultStatus(res) == PGRES_COMMAND_OK);
PQclear(res);
}
/*
* Initialize the database, from a remote node if necessary.
*/
void
bdr_init_replica(BDRNodeInfo *local_node)
{
char status;
PGconn *nonrepl_init_conn;
StringInfoData dsn;
BdrConnectionConfig *local_conn_config;
initStringInfo(&dsn);
status = local_node->status;
Assert(status != 'r');
elog(DEBUG2, "bdr_init_replica");
/*
* The local SPI transaction we're about to perform must do any writes as a
* local transaction, not as a changeset application from a remote node.
* That allows rows to be replicated to other nodes. So no replication_origin_id
* may be set.
*/
Assert(replication_origin_id == InvalidRepNodeId);
/*
* Before starting workers we must determine if we need to copy initial
* state from a remote node. This is necessary unless we are the first node
* created or we've already completed init. If we'd already completed init
* we would've exited above.
*/
if (local_node->init_from_dsn == NULL)
{
if (status != 'b')
{
/*
* Even though there's no init_replica worker, the local bdr.bdr_nodes table
* has an entry for our (sysid,dbname) and it isn't status=r (checked above),
* this should never happen
*/
ereport(ERROR, (errmsg("bdr.bdr_nodes row with "BDR_LOCALID_FORMAT" exists and has status=%c, "
"but has init_from_dsn set to NULL",
GetSystemIdentifier(), ThisTimeLineID, MyDatabaseId, EMPTY_REPLICATION_NAME, status)));
}
/*
* No connections have init_replica=t, so there's no remote copy to do.
* We still have to ensure that bdr.bdr_nodes.status is 'r' for this
* node so that slot creation is permitted.
*
* XXX: is this actually a good idea?
*/
elog(DEBUG2, "init_replica: Marking as root/standalone node");
bdr_nodes_set_local_status('r');
return;
}
local_conn_config = bdr_get_connection_config(
local_node->id.sysid,
local_node->id.timeline,
local_node->id.dboid,
true);
if (!local_conn_config)
elog(ERROR, "cannot find local BDR connection configurations");
elog(DEBUG1, "init_replica init from remote %s",
local_node->init_from_dsn);
nonrepl_init_conn =
bdr_connect_nonrepl(local_node->init_from_dsn, "init");
PG_ENSURE_ERROR_CLEANUP(bdr_cleanup_conn_close,
PointerGetDatum(&nonrepl_init_conn));
{
bdr_ensure_ext_installed(nonrepl_init_conn);
switch (status)
{
case 'b':
elog(DEBUG2, "initializing from clean state");
break;
case 'r':
elog(ERROR, "unexpected state");
case 'c':
/*
* We were in catchup mode when we died. We need to resume catchup
* mode up to the expected LSN before switching over.
*
* To do that all we need to do is fall through without doing any
* slot re-creation, dump/apply, etc, and pick up where we do
* catchup.
*
* We won't know what the original catchup target point is, but we
* can just catch up to whatever xlog position the server is
* currently at, it's guaranteed to be later than the target
* position.
*/
elog(DEBUG2, "dump applied, need to continue catchup");
break;
case 'o':
elog(DEBUG2, "dump applied and catchup completed, need to continue slot creation");
break;
case 'i':
/*
* A previous init attempt seems to have failed.
* Clean up, then fall through to start setup
* again.
*
* We can't just re-use the slot and replication
* identifier that were created last time (if
* they were), because we have no way of getting
* the slot's exported snapshot after
* CREATE_REPLICATION_SLOT.
*
* We could drop and re-create the slot, but...
*
* We also have no way to undo a failed
* pg_restore, so if that phase fails it's
* necessary to do manual cleanup, dropping and
* re-creating the db.
*
* To avoid that We need to be able to run
* pg_restore --clean, and that needs a way to
* exclude the bdr schema, the bdr extension,
* and their dependencies like plpgsql and
* btree_gist. (TODO patch pg_restore for that)
*/
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("previous init failed, manual cleanup is required"),
errdetail("Found bdr.bdr_nodes entry for "BDR_LOCALID_FORMAT" with state=i in remote bdr.bdr_nodes", BDR_LOCALID_FORMAT_ARGS),
errhint("Remove all replication identifiers and slots corresponding to this node from the init target node then drop and recreate this database and try again")));
break;
default:
elog(ERROR, "unreachable %c", status); /* Unhandled case */
break;
}
if (status == 'b')
{
char *init_snapshot = NULL;
PGconn *init_repl_conn = NULL;
NameData slot_name;
uint64 remote_sysid;
TimeLineID remote_timeline;
Oid remote_dboid;
RepNodeId repnodeid;
elog(INFO, "initializing node");
/*
* We're starting from scratch or have cleaned up a previous failed
* attempt.
*/
status = 'i';
bdr_nodes_set_local_status(status);
/*
* Now establish our slot on the target node, so we can replay
* changes from that node. It'll be used in catchup mode.
*/
init_repl_conn = bdr_establish_connection_and_slot(
local_node->init_from_dsn,
"init", &slot_name,
&remote_sysid, &remote_timeline, &remote_dboid,
&repnodeid, &init_snapshot);
elog(INFO, "connected to target node "BDR_LOCALID_FORMAT
" with snapshot %s",
remote_sysid, remote_timeline, remote_dboid,
EMPTY_REPLICATION_NAME, init_snapshot);
/*
* Take the remote dump and apply it. This will give us a local
* copy of bdr_connections to work from. It's guaranteed that
* everything after this dump will be accessible via the catchup
* mode slot created earlier.
*/
bdr_init_exec_dump_restore(local_node, init_snapshot);
/*
* TODO DYNCONF copy replication identifier state
*
* Should copy the target node's pg_catalog.pg_replication_identifier
* state for each node to the local node, using the same snapshot
* we used to take the dump from the remote. Doing this ensures
* that when we create slots to the target nodes they'll begin
* replay from a position that's exactly consistent with what's
* in the dump.
*
* We'll still need catchup mode because there's no guarantee our
* newly created slots will force all WAL we'd need to be retained
* on each node. The target might be behind. So we should catchup
* replay until the replication identifier positions received from
* catchup are >= the creation positions of the slots we made.
*
* (We don't need to do this if we instead send a replay confirmation
* request and wait for a reply from each node.)
*/
PQfinish(init_repl_conn);
pfree(init_snapshot);
/*
* Copy the state (bdr_nodes and bdr_connections) over from the
* init node to our node.
*/
elog(DEBUG1, "syncing bdr_nodes and bdr_connections");
bdr_sync_nodes(nonrepl_init_conn, local_node);
status = 'c';
bdr_nodes_set_local_status(status);
elog(DEBUG1, "dump and apply finished, preparing for catchup replay");
}
Assert(status != 'b');
if (status == 'c')
{
XLogRecPtr min_remote_lsn;
remote_node_info ri;
/*
* Launch outbound connections to all other nodes. It doesn't
* matter that their slot horizons are after the dump was taken on
* the origin node, so we could never replay all the data we need
* if we switched to replaying from these slots now. We'll be
* advancing them in catchup mode until they overtake their current
* position before switching to replaying from them directly.
*/
bdr_init_make_other_slots();
/*
* Enter catchup mode and wait until we've replayed up to the LSN
* the remote was at when we started catchup.
*
* TODO: It's possible that this step can lose transactions that
* were committed on a 3rd party node before we made our slot on it
* but not replicated to the init target node until after we exit
* catchup mode. If we acquire the DDL lock during join we can know
* that can't happen, so we should do that.
*/
elog(DEBUG3, "getting LSN to replay to in catchup mode");
min_remote_lsn = bdr_get_remote_lsn(nonrepl_init_conn);
/*
* Catchup cannot complete if there isn't at least one remote transaction
* to replay. So we perform a dummy transaction on the target node.
*
* XXX This is a hack. What we really *should* be doing is asking
* the target node to send a catchup confirmation wal message, then
* wait until all its current peers (we aren' one yet) reply with
* confirmation. Then we should be replaying until we get
* confirmation of this from the init target node, rather than
* replaying to some specific LSN. The full part/join
* protocol should take care of this.
*/
elog(DEBUG3, "forcing a new transaction on the target node");
perform_pointless_transaction(nonrepl_init_conn, local_node);
bdr_get_remote_nodeinfo_internal(nonrepl_init_conn, &ri);