-
Notifications
You must be signed in to change notification settings - Fork 15
/
spock_create_subscriber.c
1775 lines (1492 loc) · 45.3 KB
/
spock_create_subscriber.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* -------------------------------------------------------------------------
*
* spock_create_subscriber.c
* Initialize a new spock subscriber from a physical base backup
*
* Copyright (c) 2022-2023, pgEdge, Inc.
* Portions Copyright (c) 1996-2021, PostgreSQL Global Development Group
* Portions Copyright (c) 1994, The Regents of the University of California
*
* -------------------------------------------------------------------------
*/
/* dirent.h on port/win32_msvc expects MAX_PATH to be defined */
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#include <dirent.h>
#include <fcntl.h>
#include <locale.h>
#include <signal.h>
#include <time.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.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 "miscadmin.h"
#include "access/timeline.h"
#include "access/xlog_internal.h"
#include "catalog/pg_control.h"
#include "spock_fe.h"
#define MAX_APPLY_DELAY 86400
typedef struct RemoteInfo {
Oid nodeid;
char *node_name;
char *sysid;
char *dbname;
char *replication_sets;
} RemoteInfo;
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;
/* defined as static so that die() can close them */
static PGconn *subscriber_conn = NULL;
static PGconn *provider_conn = NULL;
static void signal_handler(int sig);
static void usage(void);
static void die(const char *fmt,...)
pg_attribute_printf(1, 2);
static void print_msg(VerbosityLevelEnum level, const char *fmt,...)
pg_attribute_printf(2, 3);
static int run_pg_ctl(const char *arg);
static void run_basebackup(const char *provider_connstr, const char *data_dir,
const char *extra_basebackup_args);
static void wait_postmaster_connection(const char *connstr);
static void wait_primary_connection(const char *connstr);
static void wait_postmaster_shutdown(void);
static char *validate_replication_set_input(char *replication_sets);
static void remove_unwanted_data(PGconn *conn);
static void initialize_replication_origin(PGconn *conn, char *origin_name, char *remote_lsn);
static char *create_restore_point(PGconn *conn, char *restore_point_name);
static char *initialize_replication_slot(PGconn *conn, char *dbname,
char *provider_node_name, char *subscription_name,
bool drop_slot_if_exists);
static void spock_subscribe(PGconn *conn, char *subscriber_name,
char *subscriber_dsn,
char *provider_connstr,
char *replication_sets,
int apply_delay,
bool force_text_transfer);
static RemoteInfo *get_remote_info(PGconn* conn);
static bool extension_exists(PGconn *conn, const char *extname);
static void install_extension(PGconn *conn, const char *extname);
static void initialize_data_dir(char *data_dir, char *connstr,
char *postgresql_conf, char *pg_hba_conf,
char *extra_basebackup_args);
static bool check_data_dir(char *data_dir, RemoteInfo *remoteinfo);
static char *read_sysid(const char *data_dir);
static void WriteRecoveryConf(PQExpBuffer contents);
static void CopyConfFile(char *fromfile, char *tofile, bool append);
static char *get_connstr_dbname(char *connstr);
static char *get_connstr(char *connstr, char *dbname);
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 is_pg_dir(const char *path);
static void copy_file(char *fromfile, char *tofile, bool append);
static char *find_other_exec_or_die(const char *argv0, const char *target);
static bool postmaster_is_alive(pid_t pid);
static long get_pgpid(void);
static char **get_database_list(char *databases, int *n_databases);
static char *generate_restore_point_name(void);
static PGconn *
connectdb(const 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;
char *remote_lsn;
bool stop = false;
bool drop_slot_if_exists = false;
int optindex;
char *subscriber_name = NULL;
char *base_sub_connstr = NULL;
char *base_prov_connstr = NULL;
char *replication_sets = NULL;
char *databases = NULL;
char *postgresql_conf = NULL,
*pg_hba_conf = NULL,
*recovery_conf = NULL;
int apply_delay = 0;
bool force_text_transfer = false;
char **slot_names;
char *sub_connstr;
char *prov_connstr;
char **database_list = { NULL };
int n_databases = 1;
int dbnum;
bool use_existing_data_dir = false;
int pg_ctl_ret,
logfd;
char *restore_point_name = NULL;
char *extra_basebackup_args = NULL;
static struct option long_options[] = {
{"subscriber-name", required_argument, NULL, 'n'},
{"pgdata", required_argument, NULL, 'D'},
{"provider-dsn", required_argument, NULL, 1},
{"subscriber-dsn", required_argument, NULL, 2},
{"replication-sets", required_argument, NULL, 3},
{"postgresql-conf", required_argument, NULL, 4},
{"hba-conf", required_argument, NULL, 5},
{"recovery-conf", required_argument, NULL, 6},
{"stop", no_argument, NULL, 's'},
{"drop-slot-if-exists", no_argument, NULL, 7},
{"apply-delay", required_argument, NULL, 8},
{"databases", required_argument, NULL, 9},
{"extra-basebackup-args", required_argument, NULL, 10},
{"text-types", no_argument, NULL, 11},
{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:n:sv", long_options, &optindex)) != -1)
{
switch (c)
{
case 'D':
data_dir = pg_strdup(optarg);
break;
case 'n':
subscriber_name = pg_strdup(optarg);
break;
case 1:
base_prov_connstr = pg_strdup(optarg);
break;
case 2:
base_sub_connstr = pg_strdup(optarg);
break;
case 3:
replication_sets = validate_replication_set_input(pg_strdup(optarg));
break;
case 4:
{
postgresql_conf = pg_strdup(optarg);
if (postgresql_conf != NULL && !file_exists(postgresql_conf))
die(_("The specified postgresql.conf file does not exist."));
break;
}
case 5:
{
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 6:
{
recovery_conf = pg_strdup(optarg);
if (recovery_conf != NULL && !file_exists(recovery_conf))
die(_("The specified recovery configuration file does not exist."));
break;
}
case 'v':
verbosity++;
break;
case 's':
stop = true;
break;
case 7:
drop_slot_if_exists = true;
break;
case 8:
apply_delay = atoi(optarg);
break;
case 9:
databases = pg_strdup(optarg);
break;
case 10:
extra_basebackup_args = pg_strdup(optarg);
break;
case 11:
force_text_transfer = 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 (subscriber_name == NULL)
{
fprintf(stderr, _("No subscriber name specified\n"));
fprintf(stderr, _("Try \"%s --help\" for more information.\n"), progname);
exit(1);
}
if (!base_prov_connstr || !strlen(base_prov_connstr))
die(_("Provider connection string must be specified.\n"));
if (!base_sub_connstr || !strlen(base_sub_connstr))
die(_("Subscriber connection string must be specified.\n"));
if (apply_delay < 0)
die(_("Apply delay cannot be negative.\n"));
if (apply_delay > MAX_APPLY_DELAY)
die(_("Apply delay cannot be more than %d.\n"), MAX_APPLY_DELAY);
if (!replication_sets || !strlen(replication_sets))
replication_sets = "default,default_insert_only,ddl_sql";
/* Init random numbers used for slot suffixes, etc */
srand(time(NULL));
/* Parse database list or connection string. */
if (databases != NULL)
{
database_list = get_database_list(databases, &n_databases);
}
else
{
char *dbname = get_connstr_dbname(base_prov_connstr);
if (!dbname)
die(_("Either provider connection string must contain database "
"name or --databases option must be specified.\n"));
n_databases = 1;
database_list = palloc(n_databases * sizeof(char *));
database_list[0] = dbname;
}
slot_names = palloc(n_databases * sizeof(char *));
/*
* Check connection strings for validity before doing anything
* expensive.
*/
for (dbnum = 0; dbnum < n_databases; dbnum++)
{
char *db = database_list[dbnum];
prov_connstr = get_connstr(base_prov_connstr, db);
if (!prov_connstr || !strlen(prov_connstr))
die(_("Provider connection string is not valid.\n"));
sub_connstr = get_connstr(base_sub_connstr, db);
if (!sub_connstr || !strlen(sub_connstr))
die(_("Subscriber connection string is not valid.\n"));
}
/*
* Create log file where new postgres instance will log to while being
* initialized.
*/
logfd = open("spock_create_subscriber_postgres.log", O_CREAT | O_RDWR,
S_IRUSR | S_IWUSR);
if (logfd == -1)
{
die(_("Creating spock_create_subscriber_postgres.log failed: %s"),
strerror(errno));
}
/* Safe to close() unchecked, we didn't write */
(void) close(logfd);
/* Let's start the real work... */
print_msg(VERBOSITY_NORMAL, _("%s: starting ...\n"), progname);
for (dbnum = 0; dbnum < n_databases; dbnum++)
{
char *db = database_list[dbnum];
prov_connstr = get_connstr(base_prov_connstr, db);
if (!prov_connstr || !strlen(prov_connstr))
die(_("Provider connection string is not valid.\n"));
/* Read the remote server indetification. */
print_msg(VERBOSITY_NORMAL,
_("Getting information for database %s ...\n"), db);
provider_conn = connectdb(prov_connstr);
remote_info = get_remote_info(provider_conn);
/* only need to do this piece once */
if (dbnum == 0)
{
use_existing_data_dir = check_data_dir(data_dir, remote_info);
if (use_existing_data_dir &&
strcmp(remote_info->sysid, read_sysid(data_dir)) != 0)
die(_("Subscriber data directory is not basebackup of remote node.\n"));
}
/*
* Create replication slots on remote node.
*/
print_msg(VERBOSITY_NORMAL,
_("Creating replication slot in database %s ...\n"), db);
slot_names[dbnum] = initialize_replication_slot(provider_conn,
remote_info->dbname,
remote_info->node_name,
subscriber_name,
drop_slot_if_exists);
PQfinish(provider_conn);
provider_conn = NULL;
}
/*
* Create basebackup or use existing one
*/
prov_connstr = get_connstr(base_prov_connstr, database_list[0]);
sub_connstr = get_connstr(base_sub_connstr, database_list[0]);
initialize_data_dir(data_dir,
use_existing_data_dir ? NULL : prov_connstr,
postgresql_conf, pg_hba_conf,
extra_basebackup_args);
snprintf(pid_file, MAXPGPATH, "%s/postmaster.pid", data_dir);
restore_point_name = generate_restore_point_name();
print_msg(VERBOSITY_NORMAL, _("Creating restore point \"%s\" on remote node ...\n"),
restore_point_name);
provider_conn = connectdb(prov_connstr);
remote_lsn = create_restore_point(provider_conn, restore_point_name);
PQfinish(provider_conn);
provider_conn = NULL;
/*
* Get subscriber db to consistent state (for lsn after slot creation).
*/
print_msg(VERBOSITY_NORMAL,
_("Bringing subscriber node to the restore point ...\n"));
if (recovery_conf)
{
CopyConfFile(recovery_conf, "postgresql.auto.conf", true);
}
else
{
appendPQExpBuffer(recoveryconfcontents, "primary_conninfo = '%s'\n",
escape_single_quotes_ascii(prov_connstr));
}
appendPQExpBuffer(recoveryconfcontents, "recovery_target_name = '%s'\n", restore_point_name);
appendPQExpBuffer(recoveryconfcontents, "recovery_target_inclusive = true\n");
appendPQExpBuffer(recoveryconfcontents, "recovery_target_action = promote\n");
WriteRecoveryConf(recoveryconfcontents);
free(restore_point_name);
restore_point_name = NULL;
/*
* Start subscriber node with spock disabled, and wait until it starts
* accepting connections which means it has caught up to the restore point.
*/
pg_ctl_ret = run_pg_ctl("start -l \"spock_create_subscriber_postgres.log\" -o \"-c shared_preload_libraries=''\"");
if (pg_ctl_ret != 0)
die(_("Postgres startup for restore point catchup failed with %d. See spock_create_subscriber_postgres.log."), pg_ctl_ret);
wait_primary_connection(sub_connstr);
/*
* Clean any per-node data that were copied by pg_basebackup.
*/
print_msg(VERBOSITY_VERBOSE,
_("Removing old spock configuration ...\n"));
for (dbnum = 0; dbnum < n_databases; dbnum++)
{
char *db = database_list[dbnum];
sub_connstr = get_connstr(base_sub_connstr, db);
if (!sub_connstr || !strlen(sub_connstr))
die(_("Subscriber connection string is not valid.\n"));
subscriber_conn = connectdb(sub_connstr);
remove_unwanted_data(subscriber_conn);
PQfinish(subscriber_conn);
subscriber_conn = NULL;
}
/* Stop Postgres so we can reset system id and start it with spock loaded. */
pg_ctl_ret = run_pg_ctl("stop");
if (pg_ctl_ret != 0)
die(_("Postgres stop after restore point catchup failed with %d. See spock_create_subscriber_postgres.log."), pg_ctl_ret);
wait_postmaster_shutdown();
/*
* Start the node again, now with spock active so that we can start the
* logical replication. This is final start, so don't log to to special log
* file anymore.
*/
print_msg(VERBOSITY_NORMAL,
_("Initializing spock on the subscriber node:\n"));
pg_ctl_ret = run_pg_ctl("start");
if (pg_ctl_ret != 0)
die(_("Postgres restart with spock enabled failed with %d."), pg_ctl_ret);
wait_postmaster_connection(base_sub_connstr);
for (dbnum = 0; dbnum < n_databases; dbnum++)
{
char *db = database_list[dbnum];
sub_connstr = get_connstr(base_sub_connstr, db);
prov_connstr = get_connstr(base_prov_connstr, db);
subscriber_conn = connectdb(sub_connstr);
/* Create the extension. */
print_msg(VERBOSITY_VERBOSE,
_("Creating spock extension for database %s...\n"), db);
if (PQserverVersion(subscriber_conn) < 90500)
install_extension(subscriber_conn, "spock_origin");
install_extension(subscriber_conn, "spock");
/*
* Create the identifier which is setup with the position to which we
* already caught up using physical replication.
*/
print_msg(VERBOSITY_VERBOSE,
_("Creating replication origin for database %s...\n"), db);
initialize_replication_origin(subscriber_conn, slot_names[dbnum], remote_lsn);
/*
* And finally add the node to the cluster.
*/
print_msg(VERBOSITY_NORMAL, _("Creating subscriber %s for database %s...\n"),
subscriber_name, db);
print_msg(VERBOSITY_VERBOSE, _("Replication sets: %s\n"), replication_sets);
spock_subscribe(subscriber_conn, subscriber_name, sub_connstr,
prov_connstr, replication_sets, apply_delay,
force_text_transfer);
PQfinish(subscriber_conn);
subscriber_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 subscriber node ...\n"));
pg_ctl_ret = run_pg_ctl("stop");
if (pg_ctl_ret != 0)
die(_("Stopping postgres after successful subscribtion failed with %d."), pg_ctl_ret);
wait_postmaster_shutdown();
}
print_msg(VERBOSITY_NORMAL, _("All done\n"));
return 0;
}
/*
* Print help.
*/
static void
usage(void)
{
printf(_("%s create new spock subscriber from basebackup of provider.\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\n"));
printf(_(" pg_basebackup -X stream command\n"));
printf(_(" --databases optional list of databases to replicate\n"));
printf(_(" -n, --subscriber-name=NAME name of the newly created subscriber\n"));
printf(_(" --subscriber-dsn=CONNSTR connection string to the newly created subscriber\n"));
printf(_(" --provider-dsn=CONNSTR connection string to the provider\n"));
printf(_(" --replication-sets=SETS comma separated list of replication set names\n"));
printf(_(" --apply-delay=DELAY apply delay in seconds (by default 0)\n"));
printf(_(" --drop-slot-if-exists drop replication slot of conflicting name\n"));
printf(_(" -s, --stop stop the server once the initialization is done\n"));
printf(_(" -v increase logging verbosity\n"));
printf(_(" --extra-basebackup-args additional arguments to pass to pg_basebackup.\n"));
printf(_(" Safe options: -T, -c, --xlogdir/--waldir\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 configuration\n"));
}
/*
* Print error and exit.
*/
static void
die(const char *fmt,...)
{
va_list argptr;
va_start(argptr, fmt);
vfprintf(stderr, fmt, argptr);
va_end(argptr);
if (subscriber_conn)
PQfinish(subscriber_conn);
if (provider_conn)
PQfinish(provider_conn);
if (get_pgpid())
{
if (!run_pg_ctl("stop -s"))
{
fprintf(stderr, _("WARNING: postgres seems to be running, but could not be stopped\n"));
}
}
exit(1);
}
/*
* Print message to stdout and flush
*/
static void
print_msg(VerbosityLevelEnum level, const char *fmt,...)
{
if (verbosity >= level)
{
va_list argptr;
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");
appendPQExpBuffer(cmd, "%s %s -D \"%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);
return -1;
}
/*
* Run pg_basebackup to create the copy of the origin node.
*/
static void
run_basebackup(const char *provider_connstr, const char *data_dir,
const char *extra_basebackup_args)
{
int ret;
PQExpBuffer cmd = createPQExpBuffer();
char *exec_path = find_other_exec_or_die(argv0, "pg_basebackup");
appendPQExpBuffer(cmd, "%s -D \"%s\" -d \"%s\" -X s -P", exec_path, data_dir, provider_connstr);
/* Run pg_basebackup in verbose mode if we are running in verbose mode. */
if (verbosity >= VERBOSITY_VERBOSE)
appendPQExpBuffer(cmd, " -v");
if (extra_basebackup_args != NULL)
appendPQExpBuffer(cmd, "%s", extra_basebackup_args);
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);
}
/*
* 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,
char *extra_basebackup_args)
{
if (connstr)
{
print_msg(VERBOSITY_NORMAL,
_("Creating base backup of the remote node...\n"));
run_basebackup(connstr, data_dir, extra_basebackup_args);
}
if (postgresql_conf)
CopyConfFile(postgresql_conf, "postgresql.conf", false);
if (pg_hba_conf)
CopyConfFile(pg_hba_conf, "pg_hba.conf", false);
}
/*
* 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 (!is_pg_dir(data_dir))
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
*/
static char *
initialize_replication_slot(PGconn *conn, char *dbname,
char *provider_node_name, char *subscription_name,
bool drop_slot_if_exists)
{
PQExpBufferData query;
char *slot_name;
PGresult *res;
/* Generate the slot name. */
initPQExpBuffer(&query);
printfPQExpBuffer(&query,
"SELECT spock.spock_gen_slot_name(%s, %s, %s)",
PQescapeLiteral(conn, dbname, strlen(dbname)),
PQescapeLiteral(conn, provider_node_name,
strlen(provider_node_name)),
PQescapeLiteral(conn, subscription_name,
strlen(subscription_name)));
res = PQexec(conn, query.data);
if (PQresultStatus(res) != PGRES_TUPLES_OK)
die(_("Could generate slot name: %s"), PQerrorMessage(conn));
slot_name = pstrdup(PQgetvalue(res, 0, 0));
PQclear(res);
resetPQExpBuffer(&query);
/* Check if the current slot exists. */
printfPQExpBuffer(&query,
"SELECT 1 FROM pg_catalog.pg_replication_slots WHERE slot_name = %s",
PQescapeLiteral(conn, slot_name, strlen(slot_name)));
res = PQexec(conn, query.data);
if (PQresultStatus(res) != PGRES_TUPLES_OK)
die(_("Could not fetch existing slot information: %s"), PQerrorMessage(conn));
/* Drop the existing slot when asked for it or error if it already exists. */
if (PQntuples(res) > 0)
{
PQclear(res);
resetPQExpBuffer(&query);
if (!drop_slot_if_exists)
die(_("Slot %s already exists, drop it or use --drop-slot-if-exists to drop it automatically.\n"),
slot_name);
print_msg(VERBOSITY_VERBOSE,
_("Droping existing slot %s ...\n"), slot_name);
printfPQExpBuffer(&query,
"SELECT pg_catalog.pg_drop_replication_slot(%s)",
PQescapeLiteral(conn, slot_name, strlen(slot_name)));
res = PQexec(conn, query.data);
if (PQresultStatus(res) != PGRES_TUPLES_OK)
die(_("Could not drop existing slot %s: %s"), slot_name,
PQerrorMessage(conn));
}
PQclear(res);
resetPQExpBuffer(&query);
/* And finally, create the slot. */
appendPQExpBuffer(&query, "SELECT pg_create_logical_replication_slot(%s, '%s');",
PQescapeLiteral(conn, slot_name, strlen(slot_name)),
"spock_output");
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);
termPQExpBuffer(&query);
return slot_name;
}
/*
* Read replication info about remote connection
*
* TODO: unify with spock_remote_node_info in spock_rpc
*/
static RemoteInfo *
get_remote_info(PGconn* conn)
{
RemoteInfo *ri = (RemoteInfo *)pg_malloc0(sizeof(RemoteInfo));
PGresult *res;
if (!extension_exists(conn, "spock"))
die(_("The remote node is not configured as a spock provider.\n"));
res = PQexec(conn, "SELECT node_id, node_name, sysid, dbname, replication_sets FROM spock.node_info()");
if (PQresultStatus(res) != PGRES_TUPLES_OK)
die(_("could not fetch remote node info: %s\n"), PQerrorMessage(conn));
/* No nodes found? */
if (PQntuples(res) == 0)
die(_("The remote database is not configured as a spock node.\n"));
if (PQntuples(res) > 1)
die(_("The remote database has multiple nodes configured. That is not supported with current version of spock.\n"));
#define atooid(x) ((Oid) strtoul((x), NULL, 10))
ri->nodeid = atooid(PQgetvalue(res, 0, 0));
ri->node_name = pstrdup(PQgetvalue(res, 0, 1));
ri->sysid = pstrdup(PQgetvalue(res, 0, 2));
ri->dbname = pstrdup(PQgetvalue(res, 0, 3));
ri->replication_sets = pstrdup(PQgetvalue(res, 0, 4));
PQclear(res);
return ri;
}
/*
* Check if extension exists.
*/
static bool
extension_exists(PGconn *conn, const char *extname)
{
PQExpBuffer query = createPQExpBuffer();
PGresult *res;
bool ret;
printfPQExpBuffer(query, "SELECT 1 FROM pg_catalog.pg_extension WHERE extname = %s;",
PQescapeLiteral(conn, extname, strlen(extname)));
res = PQexec(conn, query->data);
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
PQclear(res);
die(_("Could not read extension info: %s\n"), PQerrorMessage(conn));
}
ret = PQntuples(res) == 1;
PQclear(res);
destroyPQExpBuffer(query);
return ret;
}
/*
* Create extension.
*/
static void
install_extension(PGconn *conn, const char *extname)
{
PQExpBuffer query = createPQExpBuffer();
PGresult *res;
printfPQExpBuffer(query, "CREATE EXTENSION IF NOT EXISTS %s;",
PQescapeIdentifier(conn, extname, strlen(extname)));
res = PQexec(conn, query->data);
if (PQresultStatus(res) != PGRES_COMMAND_OK)
{
PQclear(res);
die(_("Could not install %s extension: %s\n"), extname, PQerrorMessage(conn));
}
PQclear(res);
destroyPQExpBuffer(query);
}
/*
* Clean all the data that was copied from remote node but we don't
* want it here (currently shared security labels and replication identifiers).
*/
static void
remove_unwanted_data(PGconn *conn)
{
PGresult *res;
/*
* Remove replication identifiers (9.4 will get them removed by dropping
* the extension later as we emulate them there).
*/
if (PQserverVersion(conn) >= 90500)
{
res = PQexec(conn, "SELECT pg_replication_origin_drop(external_id) FROM pg_replication_origin_status;");
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
PQclear(res);
die(_("Could not remove existing replication origins: %s\n"), PQerrorMessage(conn));
}
PQclear(res);
}
res = PQexec(conn, "DROP EXTENSION spock CASCADE;");
if (PQresultStatus(res) != PGRES_COMMAND_OK)
{
die(_("Could not clean the spock extension, status %s: %s\n"),
PQresStatus(PQresultStatus(res)), PQresultErrorMessage(res));
}
PQclear(res);
}
/*
* Initialize new remote identifier to specific position.
*/
static void
initialize_replication_origin(PGconn *conn, char *origin_name, char *remote_lsn)
{
PGresult *res;
PQExpBuffer query = createPQExpBuffer();
if (PQserverVersion(conn) >= 90500)
{
printfPQExpBuffer(query, "SELECT pg_replication_origin_create(%s)",
PQescapeLiteral(conn, origin_name, strlen(origin_name)));