-
Notifications
You must be signed in to change notification settings - Fork 9
/
bdr_init_copy.c
2095 lines (1775 loc) · 54.9 KB
/
bdr_init_copy.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_copy.c
* Initialize a new bdr node from a physical base backup
*
* Copyright (C) 2012-2015, PostgreSQL Global Development Group
*
* IDENTIFICATION
* bdr_conflict_logging.c
*
* -------------------------------------------------------------------------
*/
#include <dirent.h>
#include <fcntl.h>
#include <locale.h>
#include <signal.h>
#include <time.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <unistd.h>
/* Note the order is important for debian here. */
#if !defined(pg_attribute_printf)
/* GCC and XLC support format attributes */
#if defined(__GNUC__) || defined(__IBMC__)
#define pg_attribute_format_arg(a) __attribute__((format_arg(a)))
#define pg_attribute_printf(f,a) __attribute__((format(PG_PRINTF_ATTRIBUTE, f, a)))
#else
#define pg_attribute_format_arg(a)
#define pg_attribute_printf(f,a)
#endif
#endif
#include "libpq-fe.h"
#include "postgres_fe.h"
#include "pqexpbuffer.h"
#include "getopt_long.h"
#include "port.h"
#include "miscadmin.h"
#include "access/xlog_internal.h"
#include "catalog/pg_control.h"
#include "bdr_internal.h"
#define LLOGCDIR "pg_logical/checkpoints"
typedef struct RemoteInfo {
uint64 sysid;
TimeLineID tlid;
int version;
int numdbs;
Oid *dboids;
char **dbnames;
char **replication_sets;
} RemoteInfo;
typedef struct NodeInfo {
uint64 remote_sysid;
TimeLineID remote_tlid;
uint64 local_sysid;
TimeLineID local_tlid;
} NodeInfo;
typedef enum {
VERBOSITY_NORMAL,
VERBOSITY_VERBOSE,
VERBOSITY_DEBUG
} VerbosityLevelEnum;
static char *argv0 = NULL;
static const char *progname;
static char *data_dir = NULL;
static char pid_file[MAXPGPATH];
static time_t start_time;
static VerbosityLevelEnum verbosity = VERBOSITY_NORMAL;
static char *log_file_name = "bdr_init_copy_postgres.log";
/* defined as static so that die() can close them */
static PGconn *local_conn = NULL;
static PGconn *remote_conn = NULL;
/* static so print_msg etc can easily use it */
static char *node_name = NULL;
static void signal_handler(int sig);
static void usage(void);
static void BDR_NORETURN finish_die();
static void BDR_NORETURN die(const char *fmt,...)
__attribute__((format(PG_PRINTF_ATTRIBUTE, 1, 2)));
static void print_msg(VerbosityLevelEnum level, const char *fmt,...)
__attribute__((format(PG_PRINTF_ATTRIBUTE, 2, 3)));
static int BDR_WARN_UNUSED run_pg_ctl(const char *arg);
static void run_basebackup(const char *remote_connstr, const char *data_dir);
static void wait_postmaster_connection(const char *connstr);
static void wait_for_end_recovery(const char *connstr);
static void wait_postmaster_shutdown(void);
static char *validate_replication_set_input(char *replication_sets);
static void initialize_node_entry(PGconn **conn, NodeInfo *ni, char *node_name,
Oid dboid, char *remote_connstr, char *local_connstr);
static void remove_unwanted_files(void);
static void remove_unwanted_data(PGconn *conn);
static void reset_bdr_sequence_cache(PGconn *conn);
static void initialize_replication_identifier(PGconn *conn, NodeInfo *ni, Oid dboid, char *remote_lsn);
static char *create_restore_point(PGconn *conn, char *restore_point_name);
static void initialize_replication_slot(PGconn *conn, NodeInfo *ni, Oid dboid);
static void bdr_node_start(PGconn *conn, char *node_name, char *remote_connstr,
char *local_connstr, char *replication_sets,
int apply_delay);
static RemoteInfo *get_remote_info(char* connstr);
static void initialize_data_dir(char *data_dir, char *connstr,
char *postgresql_conf, char *pg_hba_conf);
static bool check_data_dir(char *data_dir, RemoteInfo *remoteinfo);
static uint64 GenerateSystemIdentifier(void);
static uint64 read_sysid(const char *data_dir);
static void set_sysid(uint64 sysid);
static void WriteRecoveryConf(PQExpBuffer contents);
static void CopyConfFile(char *fromfile, char *tofile);
char *get_connstr(char *connstr, char *dbname, char *dbhost, char *dbport, char *dbuser);
static char *PQconninfoParamsToConnstr(const char *const * keywords, const char *const * values);
static void appendPQExpBufferConnstrValue(PQExpBuffer buf, const char *str);
static bool file_exists(const char *path);
static bool path_file_exists(const char *path, const char *filename);
static void copy_file(char *fromfile, char *tofile);
static char *find_other_exec_or_die(const char *argv0, const char *target, const char *versionstr);
static bool postmaster_is_alive(pid_t pid);
static long get_pgpid(void);
static PGconn *
connectdb(char *connstr)
{
PGconn *conn;
conn = PQconnectdb(connstr);
if (PQstatus(conn) != CONNECTION_OK)
die(_("Connection to database failed: %s, connection string was: %s\n"), PQerrorMessage(conn), connstr);
return conn;
}
void signal_handler(int sig)
{
if (sig == SIGINT)
{
die(_("\nCanceling...\n"));
}
}
int
main(int argc, char **argv)
{
int i;
int c;
PQExpBuffer recoveryconfcontents = createPQExpBuffer();
RemoteInfo *remote_info;
NodeInfo node_info;
char restore_point_name[NAMEDATALEN];
char *remote_lsn;
bool stop = false;
int optindex;
char *local_connstr = NULL;
char *local_dbhost = NULL,
*local_dbport = NULL,
*local_dbuser = NULL;
char *remote_connstr = NULL;
char *remote_dbhost = NULL,
*remote_dbport = NULL,
*remote_dbuser = NULL;
char *postgresql_conf = NULL,
*pg_hba_conf = NULL,
*recovery_conf = NULL;
char *replication_sets = NULL;
bool use_existing_data_dir;
int pg_ctl_ret,
logfd;
int apply_delay = 0;
#define PG_CTL_CMD_BUF_SIZE 1000
char pg_ctl_cmd_buf[PG_CTL_CMD_BUF_SIZE];
static struct option long_options[] = {
{"apply-delay", required_argument, NULL, 'y'},
{"node-name", required_argument, NULL, 'n'},
{"pgdata", required_argument, NULL, 'D'},
{"remote-dbname", required_argument, NULL, 'd'},
{"remote-host", required_argument, NULL, 'h'},
{"remote-port", required_argument, NULL, 'p'},
{"remote-user", required_argument, NULL, 'U'},
{"local-dbname", required_argument, NULL, 2},
{"local-host", required_argument, NULL, 3},
{"local-port", required_argument, NULL, 4},
{"local-user", required_argument, NULL, 5},
{"log-file", required_argument, NULL, 'l'},
{"postgresql-conf", required_argument, NULL, 6},
{"hba-conf", required_argument, NULL, 7},
{"recovery-conf", required_argument, NULL, 8},
{"stop", no_argument, NULL, 's'},
{"replication-sets", required_argument, NULL, 9},
{NULL, 0, NULL, 0}
};
argv0 = argv[0];
progname = get_progname(argv[0]);
start_time = time(NULL);
signal(SIGINT, signal_handler);
/* check for --help */
if (argc > 1)
{
for (i = 1; i < argc; i++)
{
if (strcmp(argv[i], "--help") == 0 || strcmp(argv[i], "-?") == 0)
{
usage();
exit(0);
}
}
}
/* Option parsing and validation */
while ((c = getopt_long(argc, argv, "D:d:h:l:n:p:sU:vy:", long_options, &optindex)) != -1)
{
switch (c)
{
case 'D':
data_dir = pg_strdup(optarg);
break;
case 'd':
remote_connstr = pg_strdup(optarg);
break;
case 'h':
remote_dbhost = pg_strdup(optarg);
break;
case 'l':
if (strchr(optarg, '\'') != NULL)
die(_("log file name may not contain a single quote character"));
log_file_name = pg_strdup(optarg);
break;
case 'n':
node_name = pg_strdup(optarg);
break;
case 'p':
remote_dbport = pg_strdup(optarg);
break;
case 'U':
remote_dbuser = pg_strdup(optarg);
break;
case 'v':
verbosity++;
break;
case 'y':
{
char *endptr = NULL;
apply_delay = strtol(optarg, &endptr, 10);
if (*endptr != '\0')
die(_("could not parse '%s' as an integer for apply_delay"), optarg);
break;
}
case 2:
local_connstr = pg_strdup(optarg);
break;
case 3:
local_dbhost = pg_strdup(optarg);
break;
case 4:
local_dbport = pg_strdup(optarg);
break;
case 5:
local_dbuser = pg_strdup(optarg);
break;
case 6:
{
postgresql_conf = pg_strdup(optarg);
if (postgresql_conf != NULL && !file_exists(postgresql_conf))
die(_("The specified postgresql.conf file does not exist."));
break;
}
case 7:
{
pg_hba_conf = pg_strdup(optarg);
if (pg_hba_conf != NULL && !file_exists(pg_hba_conf))
die(_("The specified pg_hba.conf file does not exist."));
break;
}
case 8:
{
recovery_conf = pg_strdup(optarg);
if (recovery_conf != NULL && !file_exists(recovery_conf))
die(_("The specified recovery.conf file does not exist."));
break;
}
case 9:
replication_sets = validate_replication_set_input(optarg);
break;
case 's':
stop = true;
break;
default:
fprintf(stderr, _("Unknown option\n"));
fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
exit(1);
}
}
/*
* Sanity checks
*/
if (data_dir == NULL)
{
fprintf(stderr, _("No data directory specified\n"));
fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
exit(1);
}
else if (node_name == NULL)
{
fprintf(stderr, _("No node name specified\n"));
fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
exit(1);
}
remote_connstr = get_connstr(remote_connstr, NULL, remote_dbhost,
remote_dbport, remote_dbuser);
local_connstr = get_connstr(local_connstr, NULL, local_dbhost,
local_dbport, local_dbuser);
if (!remote_connstr || !strlen(remote_connstr))
die(_("Remote connection must be specified.\n"));
if (!local_connstr || !strlen(local_connstr))
die(_("Local connection must be specified.\n"));
logfd = open(log_file_name, O_CREAT | O_RDWR | O_TRUNC,
S_IRUSR | S_IWUSR);
if (logfd == -1)
{
die(_("Creating log file '%s' failed: %s"),
log_file_name, strerror(errno));
}
/* Safe to close() unchecked, we didn't write */
(void) close(logfd);
print_msg(VERBOSITY_NORMAL, _("%s: starting ...\n"), progname);
/* Read the remote server identification. */
print_msg(VERBOSITY_NORMAL,
_("Getting remote server identification ...\n"));
remote_info = get_remote_info(remote_connstr);
/* If there are no BDR enabled dbs, just bail. */
if (remote_info->numdbs < 1)
die(_("Remote node does not have any BDR enabled databases.\n"));
/*
* Check if we either detected symmetric rep sets on the remote node
* or user provided replication sets on command line.
*/
if (remote_info->replication_sets == NULL && replication_sets == NULL)
die(_("Replication sets parameter is required when adding node to cluster with asymetric replication sets.\n"));
use_existing_data_dir = check_data_dir(data_dir, remote_info);
if (use_existing_data_dir &&
remote_info->sysid != read_sysid(data_dir))
die(_("Local data directory is not basebackup of remote node.\n"));
print_msg(VERBOSITY_NORMAL,
_("Detected %d BDR database(s) on remote server\n"),
remote_info->numdbs);
/*
* Start the cloning process
*/
node_info.remote_sysid = remote_info->sysid;
node_info.remote_tlid = remote_info->tlid;
/*
* Once the physical replication reaches the restore point, it will
* bump the timeline by one.
*/
node_info.local_tlid = remote_info->tlid + 1;
/* Generate new identifier for local node. */
node_info.local_sysid = GenerateSystemIdentifier();
print_msg(VERBOSITY_VERBOSE,
_("Generated new local system identifier: "UINT64_FORMAT"\n"),
node_info.local_sysid);
print_msg(VERBOSITY_NORMAL,
_("Updating BDR configuration on the remote node:\n"));
/*
* Initialize remote node.
*
* The remote might have multiple BDR-enabled DBs, so we
* need to perform setup for each one.
*/
for (i = 0; i < remote_info->numdbs; i++)
{
char *dbname = remote_info->dbnames[i];
char *db_local_connstr = get_connstr(local_connstr, dbname,
NULL, NULL, NULL);
char *db_remote_connstr = get_connstr(remote_connstr, dbname,
NULL, NULL, NULL);
remote_conn = connectdb(db_remote_connstr);
/*
* Create replication slots on remote node.
*/
print_msg(VERBOSITY_NORMAL,
_(" %s: creating replication slot ...\n"), dbname);
initialize_replication_slot(remote_conn, &node_info,
remote_info->dboids[i]);
/*
* Create node entry for future local node.
*/
print_msg(VERBOSITY_NORMAL,
_(" %s: creating node entry for local node ...\n"), dbname);
initialize_node_entry(&remote_conn, &node_info, node_name,
remote_info->dboids[i],
db_remote_connstr, db_local_connstr);
/* Don't hold connection since the next step might take long time. */
PQfinish(remote_conn);
remote_conn = NULL;
}
/*
* Create basebackup or use existing one
*/
initialize_data_dir(data_dir,
use_existing_data_dir ? NULL : remote_connstr,
postgresql_conf, pg_hba_conf);
snprintf(pid_file, MAXPGPATH, "%s/postmaster.pid", data_dir);
/*
* Create restore point to which we will catchup via physical replication.
*/
remote_conn = connectdb(remote_connstr);
print_msg(VERBOSITY_NORMAL, _("Creating restore point on remote node ...\n"));
snprintf(restore_point_name, NAMEDATALEN,
"bdr_"UINT64_FORMAT, node_info.local_sysid);
remote_lsn = create_restore_point(remote_conn, restore_point_name);
PQfinish(remote_conn);
remote_conn = NULL;
/*
* Get local db to consistent state (for lsn after slot creation).
*/
print_msg(VERBOSITY_NORMAL,
_("Bringing local node to the restore point ...\n"));
if (!path_file_exists(data_dir, "recovery.conf"))
{
appendPQExpBuffer(recoveryconfcontents, "standby_mode = 'on'\n");
appendPQExpBuffer(recoveryconfcontents, "primary_conninfo = '%s'\n",
escape_single_quotes_ascii(remote_connstr));
}
else
printf(_("updating recovery target in existing recovery.conf\n"));
appendPQExpBuffer(recoveryconfcontents, "recovery_target_name = '%s'\n", restore_point_name);
appendPQExpBuffer(recoveryconfcontents, "recovery_target_inclusive = true\n");
if (PG_VERSION_NUM/100 == 904)
{
appendPQExpBuffer(recoveryconfcontents, "pause_at_recovery_target = off");
}
else if (PG_VERSION_NUM >= 90600)
{
appendPQExpBuffer(recoveryconfcontents, "recovery_target_action = promote");
}
else
{
die(_("Only 9.4bdr and 9.6 are supported"));
}
WriteRecoveryConf(recoveryconfcontents);
/*
* Start local node with BDR disabled, and wait until it starts accepting
* connections which means it has caught up to the restore point.
*
* Note that pg_ctl won't return nonzero if postmaster starts then
* immediately exits due to issues like port conflicts. We'll detect that
* in wait_postmaster_connection().
*/
snprintf(&pg_ctl_cmd_buf[0], PG_CTL_CMD_BUF_SIZE,
"start -l \'%s\' -o \"-c shared_preload_libraries=''\"",
log_file_name);
pg_ctl_ret = run_pg_ctl(pg_ctl_cmd_buf);
if (pg_ctl_ret != 0)
die(_("postgres startup for restore point catchup failed with %d. See '%s'."), pg_ctl_ret, log_file_name);
wait_postmaster_connection(local_connstr);
/*
* The postmaster is in standby mode and has caught up. Now we have to
* promote it so we can perform read/write transactions and wait for
* it to notice that it has been promoted.
*
* When pg_is_in_recovery() no longer returns true, we're ready.
*/
wait_for_end_recovery(local_connstr);
/*
* Clean any per-node data that were copied by pg_basebackup.
*/
for (i = 0; i < remote_info->numdbs; i++)
{
char *dbname = remote_info->dbnames[i];
char *db_connstr = get_connstr(local_connstr, dbname,
NULL, NULL, NULL);
local_conn = connectdb(db_connstr);
remove_unwanted_data(local_conn);
PQfinish(local_conn);
local_conn = NULL;
}
/* Stop Postgres so we can reset system id and start it with BDR loaded. */
pg_ctl_ret = run_pg_ctl("stop");
if (pg_ctl_ret != 0)
die(_("postgres stop after restore point catchup failed with %d. See '%s'."), pg_ctl_ret, log_file_name);
wait_postmaster_shutdown();
/*
* Individualize the local node by changing the system identifier.
*
* We can't rely on the timeline ID alone, even though it's incremented
* on promotion of the copy, because we can't make sure it's globally
* unique. If node A is copied to node B, then node A is copied to node C,
* both nodes B and C will have the same tlid.
*
* For 9.6 this means using a patched pg_resetxlog since the stock one
* doesn't know how to alter the sysid.
*/
set_sysid(node_info.local_sysid);
/*
* Start the node again, now with BDR active so that we can join the node
* to the BDR cluster. This is final start, so don't log to to special log
* file anymore.
*/
print_msg(VERBOSITY_NORMAL,
_("Initializing BDR on the local node:\n"));
snprintf(&pg_ctl_cmd_buf[0], PG_CTL_CMD_BUF_SIZE,
"start -l '%s'", log_file_name);
pg_ctl_ret = run_pg_ctl(pg_ctl_cmd_buf);
if (pg_ctl_ret != 0)
die(_("postgres restart with bdr enabled failed with %d. See '%s'."), pg_ctl_ret, log_file_name);
wait_postmaster_connection(local_connstr);
for (i = 0; i < remote_info->numdbs; i++)
{
char *dbname = remote_info->dbnames[i];
char *db_local_connstr = get_connstr(local_connstr, dbname,
NULL, NULL, NULL);
char *db_remote_connstr = get_connstr(remote_connstr, dbname,
NULL, NULL, NULL);
if (replication_sets == NULL)
replication_sets = remote_info->replication_sets[i];
local_conn = connectdb(db_local_connstr);
/*
* Clean the sequence amdata cache which was copied from the remote
* server verbatim but isn't valid on the new node and would cause
* duplicate values being returned by the sequence on both servers.
*/
reset_bdr_sequence_cache(local_conn);
/*
* Create the identifier which is setup with the position to which we
* already caught up using physical replication.
*/
print_msg(VERBOSITY_VERBOSE,
_(" %s: creating replication identifier ...\n"), dbname);
initialize_replication_identifier(local_conn, &node_info,
remote_info->dboids[i], remote_lsn);
/*
* And finally add the node to the cluster.
*/
print_msg(VERBOSITY_NORMAL,
_(" %s: adding the database to BDR cluster ...\n"), dbname);
print_msg(VERBOSITY_VERBOSE,
_(" %s: replication sets: %s"), dbname, replication_sets);
bdr_node_start(local_conn, node_name, db_remote_connstr,
db_local_connstr, replication_sets, apply_delay);
PQfinish(local_conn);
local_conn = NULL;
}
/* If user does not want the node to be running at the end, stop it. */
if (stop)
{
print_msg(VERBOSITY_NORMAL, _("Stopping the local node ...\n"));
pg_ctl_ret = run_pg_ctl("stop");
if (pg_ctl_ret != 0)
die(_("Stopping postgres after successful join failed with %d. See '%s'."), pg_ctl_ret, log_file_name);
wait_postmaster_shutdown();
}
print_msg(VERBOSITY_NORMAL, _("All done\n"));
return 0;
}
/*
* Print help.
*/
static void
usage(void)
{
printf(_("%s initializes new BDR node from existing BDR instance.\n\n"), progname);
printf(_("Usage:\n"));
printf(_(" %s [OPTION]...\n"), progname);
printf(_("\nGeneral options:\n"));
printf(_(" -D, --pgdata=DIRECTORY data directory to be used for new node,\n"));
printf(_(" can be either empty/non-existing directory,\n"));
printf(_(" or directory populated using pg_basebackup -X stream\n"));
printf(_(" command\n"));
printf(_(" -l, --log-file log file name, default bdr_init_copy_postgres.log"));
printf(_(" -n, --node-name=NAME name of the newly created node\n"));
printf(_(" --replication-sets=SETS comma separated list of replication set names to use\n"));
printf(_(" -s, --stop stop the server once the initialization is done\n"));
printf(_(" -v increase logging verbosity\n"));
printf(_("\nConfiguration files override:\n"));
printf(_(" --hba-conf path to the new pg_hba.conf\n"));
printf(_(" --postgresql-conf path to the new postgresql.conf\n"));
printf(_(" --recovery-conf path to the template recovery.conf\n"));
printf(_("\nConnection options:\n"));
printf(_(" -d, --remote-dbname=CONNSTR\n"));
printf(_(" dbname or connection string for remote node\n"));
printf(_(" -h, --remote-host=HOSTNAME\n"));
printf(_(" server host or socket directory for remote node\n"));
printf(_(" -p, --remote-port=PORT server port number for remote node\n"));
printf(_(" -U, --remote-user=NAME connect as specified database user to the remote node\n"));
printf(_(" --local-dbname=CONNSTR dbname or connection string for local node\n"));
printf(_(" --local-host=HOSTNAME server host or socket directory for local node\n"));
printf(_(" --local-port=PORT server port number for local node. Must match\n"));
printf(_(" postgresql.conf, does not set port server is"));
printf(_(" started with."));
printf(_(" --local-user=NAME connect as specified database user to the local node\n"));
printf(_("\nDebug options:\n"));
printf(_(" --apply-delay artificially delay replication for this node\n"));
}
static void
finish_die()
{
if (local_conn)
PQfinish(local_conn);
if (remote_conn)
PQfinish(remote_conn);
if (get_pgpid())
{
if (!run_pg_ctl("stop -s"))
{
fprintf(stderr, _("WARNING: postgres seems to be running, but could not be stopped"));
}
}
exit(1);
}
/*
* Print error and exit.
*/
static void
die(const char *fmt,...)
{
va_list argptr;
if (node_name != NULL)
fprintf(stdout, "[%s] ", node_name);
va_start(argptr, fmt);
vfprintf(stderr, fmt, argptr);
va_end(argptr);
finish_die();
}
/*
* Print message to stdout and flush
*/
static void
print_msg(VerbosityLevelEnum level, const char *fmt,...)
{
if (verbosity >= level)
{
va_list argptr;
if (node_name != NULL)
fprintf(stdout, "[%s] ", node_name);
va_start(argptr, fmt);
vfprintf(stdout, fmt, argptr);
va_end(argptr);
fflush(stdout);
}
}
/*
* Start pg_ctl with given argument(s) - used to start/stop postgres
*
* Returns the exit code reported by pg_ctl. If pg_ctl exits due to a
* signal this call will die and not return.
*/
static int
run_pg_ctl(const char *arg)
{
int ret;
PQExpBuffer cmd = createPQExpBuffer();
char *exec_path = find_other_exec_or_die(argv0, "pg_ctl", NULL);
appendPQExpBuffer(cmd, "%s %s -D \"%s\" -s", exec_path, arg, data_dir);
/* Run pg_ctl in silent mode unless we run in debug mode. */
if (verbosity < VERBOSITY_DEBUG)
appendPQExpBuffer(cmd, " -s");
print_msg(VERBOSITY_DEBUG, _("Running pg_ctl: %s.\n"), cmd->data);
ret = system(cmd->data);
destroyPQExpBuffer(cmd);
if (WIFEXITED(ret))
return WEXITSTATUS(ret);
else if (WIFSIGNALED(ret))
die(_("pg_ctl exited with signal %d"), WTERMSIG(ret));
else
die(_("pg_ctl exited for an unknown reason (system() returned %d)"), ret);
}
/*
* Run pg_basebackup to create the copy of the origin node.
*/
static void
run_basebackup(const char *remote_connstr, const char *data_dir)
{
int ret;
PQExpBuffer cmd = createPQExpBuffer();
char *exec_path = find_other_exec_or_die(argv0, "pg_basebackup", NULL);
appendPQExpBuffer(cmd, "%s -D \"%s\" -d \"%s\" -X s -P", exec_path, data_dir, remote_connstr);
/* Run pg_basebackup in verbose mode if we are running in verbose mode. */
if (verbosity >= VERBOSITY_VERBOSE)
appendPQExpBuffer(cmd, " -v");
print_msg(VERBOSITY_DEBUG, _("Running pg_basebackup: %s.\n"), cmd->data);
ret = system(cmd->data);
destroyPQExpBuffer(cmd);
if (WIFEXITED(ret) && WEXITSTATUS(ret) == 0)
return;
if (WIFEXITED(ret))
die(_("pg_basebackup failed with exit status %d, cannot continue.\n"), WEXITSTATUS(ret));
else if (WIFSIGNALED(ret))
die(_("pg_basebackup exited with signal %d, cannot continue"), WTERMSIG(ret));
else
die(_("pg_basebackup exited for an unknown reason (system() returned %d)"), ret);
}
/*
* Set system identifier to system id we used for registering the slots.
*/
static void
set_sysid(uint64 sysid)
{
int ret;
PQExpBuffer cmd = createPQExpBuffer();
char *exec_path, *cmdname;
if (PG_VERSION_NUM/100 == 904)
{
exec_path = find_other_exec_or_die(argv0, "pg_resetxlog", "pg_resetxlog (PostgreSQL) " PG_VERSION "\n");
cmdname = "pg_resetxlog";
}
else
{
exec_path = find_other_exec_or_die(argv0, "bdr_resetxlog", "bdr_resetxlog (PostgreSQL) " PG_VERSION "\n");
cmdname = "bdr_resetxlog";
}
appendPQExpBuffer(cmd, "%s \"-s "UINT64_FORMAT"\" \"%s\"", exec_path, sysid, data_dir);
print_msg(VERBOSITY_DEBUG, _("Running %s: %s.\n"), cmdname, cmd->data);
ret = system(cmd->data);
destroyPQExpBuffer(cmd);
if (WIFEXITED(ret) && WEXITSTATUS(ret) == 0)
return;
if (WIFEXITED(ret))
die(_("%s failed with exit status %d, cannot continue.\n"), cmdname, WEXITSTATUS(ret));
else if (WIFSIGNALED(ret))
die(_("%s exited with signal %d, cannot continue"), cmdname, WTERMSIG(ret));
else
die(_("%s exited for an unknown reason (system() returned %d)"), cmdname, ret);
}
/*
* Cleans everything that was replicated via basebackup but we don't want it.
*/
static void
remove_unwanted_files(void)
{
/*
* 9.4's pg_basebackup copies pg_logical/checkpoints; 9.6 does
* not since there's no such thing on 9.6.
*/
if (PG_VERSION_NUM/100 == 904)
{
DIR *lldir;
struct dirent *llde;
PQExpBuffer llpath = createPQExpBuffer();
PQExpBuffer filename = createPQExpBuffer();
printfPQExpBuffer(llpath, "%s/%s", data_dir, LLOGCDIR);
print_msg(VERBOSITY_DEBUG, _("Removing data from \"%s\" directory.\n"),
llpath->data);
/*
* Remove stray logical replication checkpoints
*/
lldir = opendir(llpath->data);
if (lldir == NULL)
{
die(_("Could not open directory \"%s\": %s\n"),
llpath->data, strerror(errno));
}
while (errno = 0, (llde = readdir(lldir)) != NULL)
{
size_t len = strlen(llde->d_name);
if (len > 5 && !strcmp(llde->d_name + len - 5, ".ckpt"))
{
printfPQExpBuffer(filename, "%s/%s", llpath->data, llde->d_name);
if (unlink(filename->data) != 0)
{
die(_("Could not unlink checkpoint file \"%s\": %s\n"),
filename->data, strerror(errno));
}
}
}
destroyPQExpBuffer(llpath);
destroyPQExpBuffer(filename);
if (errno)
{
die(_("Could not read directory \"%s\": %s\n"),
LLOGCDIR, strerror(errno));
}
if (closedir(lldir))
{
die(_("Could not close directory \"%s\": %s\n"),
LLOGCDIR, strerror(errno));
}
}
}
/*
* Init the datadir
*
* This function can either ensure provided datadir is a postgres datadir,
* or create it using pg_basebackup.
*
* In any case, new postresql.conf and pg_hba.conf will be copied to the
* datadir if they are provided.
*/
static void
initialize_data_dir(char *data_dir, char *connstr,
char *postgresql_conf, char *pg_hba_conf)
{
if (connstr)
{
print_msg(VERBOSITY_NORMAL,
_("Creating base backup of the remote node...\n"));
run_basebackup(connstr, data_dir);
}
remove_unwanted_files();
if (postgresql_conf)
CopyConfFile(postgresql_conf, "postgresql.conf");
if (pg_hba_conf)
CopyConfFile(pg_hba_conf, "pg_hba.conf");
}
/*
* This function checks if provided datadir is clone of the remote node
* described by the remote info, or if it's emtpy directory that can be used
* as new datadir.
*/
static bool
check_data_dir(char *data_dir, RemoteInfo *remoteinfo)
{
/* Run basebackup as needed. */
switch (pg_check_dir(data_dir))
{
case 0: /* Does not exist */
case 1: /* Exists, empty */
return false;
case 2:
case 3: /* Exists, not empty */
case 4:
{
if (!path_file_exists(data_dir, "PG_VERSION"))
die(_("Directory \"%s\" exists but is not valid postgres data directory.\n"),
data_dir);
return true;
}
case -1: /* Access problem */
die(_("Could not access directory \"%s\": %s.\n"),
data_dir, strerror(errno));
}
/* Unreachable */
die(_("Unexpected result from pg_check_dir() call"));
return false;
}
/*
* Initialize replication slots
*
* Get connection configs from bdr and use the info
* to register replication slots for future use.
*/
static void
initialize_replication_slot(PGconn *conn, NodeInfo *ni, Oid dboid)
{
NameData slotname;
PQExpBuffer query = createPQExpBuffer();
PGresult *res;
BDRNodeId node;
/* dboids are the same, because we just cloned... */
node.sysid = ni->local_sysid;
node.timeline = ni->local_tlid;
node.dboid = dboid;
bdr_slot_name(&slotname, &node, dboid);
appendPQExpBuffer(query, "SELECT pg_create_logical_replication_slot(%s, '%s');",
PQescapeLiteral(conn, NameStr(slotname), NAMEDATALEN), "bdr");
res = PQexec(conn, query->data);
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
die(_("Could not create replication slot, status %s: %s\n"),
PQresStatus(PQresultStatus(res)), PQresultErrorMessage(res));
}
PQclear(res);
destroyPQExpBuffer(query);
}
/*
* Read replication info about remote connection
*/
static RemoteInfo *
get_remote_info(char* remote_connstr)
{
RemoteInfo *ri = (RemoteInfo *)pg_malloc0(sizeof(RemoteInfo));