-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathbdr_init_replica.c
1474 lines (1271 loc) · 45.6 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 "bdr_internal.h"
#include "bdr_locks.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/origin.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/snapmgr.h"
#include "utils/syscache.h"
#include "pgstat.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_wal_insert_lsn()");
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;
char *nodename;
initStringInfo(&path);
initStringInfo(&origin_dsn);
initStringInfo(&local_dsn);
nodename = MemoryContextStrdup(TopMemoryContext, bdr_get_my_cached_node_name());
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 / 10000 != PG_VERSION_NUM / 10000)
{
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 / 10000 != PG_VERSION_NUM / 10000)
{
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 / 10000 != PG_VERSION_NUM / 10000)
{
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='%s: init dump'",
nodename);
appendStringInfo(&local_dsn,
"%s fallback_application_name='%s: init restore'",
node->local_dsn, nodename);
pfree(nodename);
nodename = NULL;
/*
* 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);
}
/*
* Insert the bdr.bdr_nodes and bdr.bdr_connections entries for our node in the
* remote peer, if they don't already exist.
*/
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;
BDRNodeId remote, myid;
RepOriginId replication_identifier;
char *snapshot;
bdr_make_my_nodeid(&myid);
if (bdr_nodeid_eq(&cfg->remote_node, &myid))
{
/* 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,
&remote, &replication_identifier, &snapshot);
/* Ensure the slot points to the node the conn info says it should */
if (!bdr_nodeid_eq(&cfg->remote_node, &remote))
{
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("System identification mismatch between connection and slot"),
errdetail("Connection for "BDR_NODEID_FORMAT_WITHNAME" resulted in slot on node "BDR_NODEID_FORMAT_WITHNAME" instead of expected node",
BDR_NODEID_FORMAT_WITHNAME_ARGS(cfg->remote_node),
BDR_NODEID_FORMAT_WITHNAME_ARGS(remote))));
}
/* 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_NODEID_FORMAT_WITHNAME,
NameStr(slot_name), BDR_NODEID_FORMAT_WITHNAME_ARGS(remote));
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;
BDRNodeId myid;
bdr_make_my_nodeid(&myid);
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 (bdr_nodeid_eq(&cfg->remote_node, &myid))
{
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 (bdr_nodeid_eq(&cfg->remote_node, &myid))
{
/* 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 (bdr_nodeid_eq(&cfg->remote_node, &w->data.walsnd.remote_node) &&
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");
}
/*
* Explicitly ttake the DDL lock on a remote peer.
*
* Can run standalone or in an existing tx, doesn't care about tx state.
*
* Does nothing if the remote peer doesn't support explicit DDL lock requests.
*
* ERRORs if the lock attempt fails. Caller should be prepared to retry
* the attempt or the whole operations containing it.
*/
static void
bdr_ddl_lock_remote(PGconn *conn, BDRLockType mode)
{
PGresult *res;
/* Currently only supports BDR_LOCK_DDL mode 'cos I'm lazy */
if (mode != BDR_LOCK_DDL)
elog(ERROR, "remote DDL locking only supports mode = 'ddl'");
res = PQexec(conn,
"DO LANGUAGE plpgsql $$\n"
"BEGIN\n"
" IF EXISTS (SELECT 1 FROM pg_proc WHERE proname = 'acquire_global_lock' AND pronamespace = (SELECT oid FROM pg_namespace WHERE nspname = 'bdr')) THEN\n"
" PERFORM bdr.acquire_global_lock('ddl_lock');\n"
" END IF;\n"
"END; $$;\n");
if (PQresultStatus(res) != PGRES_COMMAND_OK)
{
PQclear(res);
elog(ERROR, "Failed to acquire global DDL lock on remote peer: %s\n", PQerrorMessage(conn));
}
PQclear(res);
}
/*
* While holding the global ddl lock on the remote, update bdr.bdr_nodes
* status to 'r' on the join target. See callsite for more info.
*
* This function can leave a tx open and aborted on failure, but the
* caller is assumed to just close the conn on failure anyway.
*
* Note that we set the global sequence ID from here too.
*
* Since bdr_init_copy creates nodes in state BDR_NODE_STATUS_CATCHUP,
* we'll run this for both logically and physically joined nodes.
*/
static void
bdr_nodes_set_remote_status_ready(PGconn *conn)
{
PGresult *res;
char *values[3];
char local_sysid[32], local_timeline[32], local_dboid[32];
int node_seq_id;
res = PQexec(conn, "BEGIN ISOLATION LEVEL READ COMMITTED;");
if (PQresultStatus(res) != PGRES_COMMAND_OK)
{
PQclear(res);
elog(ERROR, "Failed to start tx on remote peer: %s\n", PQerrorMessage(conn));
}
bdr_ddl_lock_remote(conn, BDR_LOCK_DDL);
/* DDL lock renders this somewhat redundant but you can't be too careful */
res = PQexec(conn, "LOCK TABLE bdr.bdr_nodes IN EXCLUSIVE MODE;");
stringify_my_node_identity(local_sysid, sizeof(local_sysid),
local_timeline, sizeof(local_timeline),
local_dboid, sizeof(local_dboid));
values[0] = &local_sysid[0];
values[1] = &local_timeline[0];
values[2] = &local_dboid[0];
/*
* Update our node status to 'r'eady, and grab the lowest free node
* node_seq_id in the process.
*
* It's safe to claim a node_seq_id from a 'k'illed node because we
* won't be replaying new changes from it once we see that status and
* the ID generator is based on timestamps.
*/
res = PQexecParams(conn,
"UPDATE bdr.bdr_nodes\n"
"SET node_status = "BDR_NODE_STATUS_READY_S",\n"
" node_seq_id = coalesce(\n"
" -- lowest free ID if one has been released (right anti-join)\n"
" (select min(x)\n"
" from\n"
" (select * from bdr.bdr_nodes where node_status not in ("BDR_NODE_STATUS_KILLED_S")) n\n"
" right join generate_series(1, (select max(n2.node_seq_id) from bdr.bdr_nodes n2)) s(x)\n"
" on (n.node_seq_id = x)\n"
" where n.node_seq_id is null),\n"
" -- otherwise next-greatest ID\n"
" (select coalesce(max(node_seq_id),0) + 1 from bdr.bdr_nodes where node_status not in ("BDR_NODE_STATUS_KILLED_S")))\n"
"WHERE (node_sysid, node_timeline, node_dboid) = ($1, $2, $3)\n"
"RETURNING node_seq_id\n",
3, NULL, (const char **)values, NULL, NULL, 0);
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
PQclear(res);
elog(ERROR, "failed to update my bdr.bdr_nodes entry on remote server: %s\n", PQerrorMessage(conn));
}
if (PQntuples(res) != 1)
{
PQclear(res);
elog(ERROR, "failed to update my bdr.bdr_nodes entry on remote server: affected %d rows instead of expected 1", PQntuples(res));
}
Assert(PQnfields(res) == 1);
if (PQgetisnull(res, 0, 0))
{
PQclear(res);
elog(ERROR, "assigned node sequence ID is unexpectedly null");
}
node_seq_id = atoi(PQgetvalue(res, 0,0));
elog(DEBUG1, "BDR node finishing join assigned global seq id %d", node_seq_id);
res = PQexec(conn, "COMMIT;");
if (PQresultStatus(res) != PGRES_COMMAND_OK)
{
PQclear(res);
elog(ERROR, "Failed to start tx on remote peer: %s\n", PQerrorMessage(conn));
}
}
/*
* Idle until our local node status goes 'r'
*/
static void
bdr_wait_for_local_node_ready()
{
BdrNodeStatus status = BDR_NODE_STATUS_NONE;
BDRNodeId myid;
bdr_make_my_nodeid(&myid);
while (status != BDR_NODE_STATUS_READY)
{
int rc;
rc = WaitLatch(&MyProc->procLatch,
WL_LATCH_SET | WL_TIMEOUT | WL_POSTMASTER_DEATH,
1000, PG_WAIT_EXTENSION);
ResetLatch(&MyProc->procLatch);
/* emergency bailout if postmaster has died */
if (rc & WL_POSTMASTER_DEATH)
proc_exit(1);
StartTransactionCommand();
SPI_connect();
PushActiveSnapshot(GetTransactionSnapshot());
status = bdr_nodes_get_local_status(&myid);
PopActiveSnapshot();
SPI_finish();
CommitTransactionCommand();
if (status == BDR_NODE_STATUS_KILLED)
{
ereport(ERROR,
(errcode(ERRCODE_OPERATOR_INTERVENTION),
errmsg("The local node has been parted from the BDR group (status=%c)", status)));
}
};
}
/*
* 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);
}
/*
* Set a standalone node, i.e one that's not initializing from another peer, to
* ready state and assign it a node sequence ID.
*/
static void
bdr_init_standalone_node(BDRNodeInfo *local_node)
{
int seq_id = 1;
Relation rel;
Assert(local_node->init_from_dsn == NULL);
StartTransactionCommand();
rel = heap_open(BdrNodesRelid, ExclusiveLock);
bdr_nodes_set_local_attrs(BDR_NODE_STATUS_READY, BDR_NODE_STATUS_BEGINNING_INIT, &seq_id);
heap_close(rel, ExclusiveLock);
CommitTransactionCommand();
}
/*
* Initialize the database, from a remote node if necessary.
*/
void
bdr_init_replica(BDRNodeInfo *local_node)
{
BdrNodeStatus status;
PGconn *nonrepl_init_conn;
StringInfoData dsn;
BdrConnectionConfig *local_conn_config;
initStringInfo(&dsn);
status = local_node->status;
Assert(status != BDR_NODE_STATUS_READY);
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 replorigin_session_origin
* may be set.
*/
Assert(replorigin_session_origin == InvalidRepOriginId);
/*
* 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 != BDR_NODE_STATUS_BEGINNING_INIT)
{
/*
* 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_NODEID_FORMAT_WITHNAME" exists and has status=%c, but has init_from_dsn set to NULL",
BDR_LOCALID_FORMAT_WITHNAME_ARGS, status)));
}
/*
* No connections have init_replica=t, so there's no remote copy to do,
* but we still have some work to do to bring up the first / a standalone
* node.
*/
bdr_init_standalone_node(local_node);
return;
}
local_conn_config = bdr_get_connection_config(&local_node->id, 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);