forked from fdr/repmgr
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrepmgr.c
2014 lines (1781 loc) · 59.7 KB
/
repmgr.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
/*
* repmgr.c - Command interpreter for the repmgr
* Copyright (C) 2ndQuadrant, 2010-2011
*
* This module is a command-line utility to easily setup a cluster of
* hot standby servers for an HA environment
*
* Commands implemented are.
* MASTER REGISTER
* STANDBY REGISTER, STANDBY CLONE, STANDBY FOLLOW, STANDBY PROMOTE
* WITNESS CREATE
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "repmgr.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include "log.h"
#include "config.h"
#include "check_dir.h"
#include "strutil.h"
#define RECOVERY_FILE "recovery.conf"
#define RECOVERY_DONE_FILE "recovery.done"
#define NO_ACTION 0 /* Not a real action, just to initialize */
#define MASTER_REGISTER 1
#define STANDBY_REGISTER 2
#define STANDBY_CLONE 3
#define STANDBY_PROMOTE 4
#define STANDBY_FOLLOW 5
#define WITNESS_CREATE 6
static bool create_recovery_file(const char *data_dir, char *master_conninfo);
static int test_ssh_connection(char *host, char *remote_user);
static int copy_remote_files(char *host, char *remote_user, char *remote_path,
char *local_path, bool is_directory);
static bool check_parameters_for_action(const int action);
static bool create_schema(PGconn *conn);
static bool copy_configuration(PGconn *masterconn, PGconn *witnessconn);
static void do_master_register(void);
static void do_standby_register(void);
static void do_standby_clone(void);
static void do_standby_promote(void);
static void do_standby_follow(void);
static void do_witness_create(void);
static void usage(void);
static void help(const char *progname);
/* Global variables */
static const char *progname;
static const char *keywords[6];
static const char *values[6];
char repmgr_schema[MAXLEN];
bool need_a_node = true;
/* XXX This should be mapped into a command line option */
bool require_password = false;
/* Initialization of runtime options */
t_runtime_options runtime_options = { "", "", "", "", "", "", DEFAULT_WAL_KEEP_SEGMENTS, false, false, false, "" };
t_configuration_options options = { "", -1, "", MANUAL_FAILOVER, -1, "", "", "", "", "" };
static char *server_mode = NULL;
static char *server_cmd = NULL;
int
main(int argc, char **argv)
{
static struct option long_options[] =
{
{"dbname", required_argument, NULL, 'd'},
{"host", required_argument, NULL, 'h'},
{"port", required_argument, NULL, 'p'},
{"username", required_argument, NULL, 'U'},
{"dest-dir", required_argument, NULL, 'D'},
{"local-port", required_argument, NULL, 'l'},
{"config-file", required_argument, NULL, 'f'},
{"remote-user", required_argument, NULL, 'R'},
{"wal-keep-segments", required_argument, NULL, 'w'},
{"force", no_argument, NULL, 'F'},
{"ignore-rsync-warning", no_argument, NULL, 'I'},
{"verbose", no_argument, NULL, 'v'},
{NULL, 0, NULL, 0}
};
int optindex;
int c;
int action = NO_ACTION;
progname = get_progname(argv[0]);
if (argc > 1)
{
if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
{
help(progname);
exit(SUCCESS);
}
if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
{
printf("%s (PostgreSQL) " PG_VERSION "\n", progname);
exit(SUCCESS);
}
}
while ((c = getopt_long(argc, argv, "d:h:p:U:D:l:f:R:w:F:I:v", long_options,
&optindex)) != -1)
{
switch (c)
{
case 'd':
strncpy(runtime_options.dbname, optarg, MAXLEN);
break;
case 'h':
strncpy(runtime_options.host, optarg, MAXLEN);
break;
case 'p':
if (atoi(optarg) > 0)
strncpy(runtime_options.masterport, optarg, MAXLEN);
break;
case 'U':
strncpy(runtime_options.username, optarg, MAXLEN);
break;
case 'D':
strncpy(runtime_options.dest_dir, optarg, MAXFILENAME);
break;
case 'l':
if (atoi(optarg) > 0)
strncpy(runtime_options.localport, optarg, MAXLEN);
break;
case 'f':
strncpy(runtime_options.config_file, optarg, MAXLEN);
break;
case 'R':
strncpy(runtime_options.remote_user, optarg, MAXLEN);
break;
case 'w':
if (atoi(optarg) > 0)
strncpy(runtime_options.wal_keep_segments, optarg, MAXLEN);
break;
case 'F':
runtime_options.force = true;
break;
case 'I':
runtime_options.ignore_rsync_warn = true;
break;
case 'v':
runtime_options.verbose = true;
break;
default:
usage();
exit(ERR_BAD_CONFIG);
}
}
/*
* Now we need to obtain the action, this comes in one of these forms:
* MASTER REGISTER |
* STANDBY {REGISTER | CLONE [node] | PROMOTE | FOLLOW [node]} |
* WITNESS CREATE
*
* the node part is optional, if we receive it then we shouldn't
* have received a -h option
*/
if (optind < argc)
{
server_mode = argv[optind++];
if (strcasecmp(server_mode, "STANDBY") != 0 && strcasecmp(server_mode, "MASTER") != 0 &&
strcasecmp(server_mode, "WITNESS") != 0)
{
usage();
exit(ERR_BAD_CONFIG);
}
}
if (optind < argc)
{
server_cmd = argv[optind++];
/* check posibilities for all server modes */
if (strcasecmp(server_mode, "MASTER") == 0)
{
if (strcasecmp(server_cmd, "REGISTER") == 0)
action = MASTER_REGISTER;
}
else if (strcasecmp(server_mode, "STANDBY") == 0)
{
if (strcasecmp(server_cmd, "REGISTER") == 0)
action = STANDBY_REGISTER;
else if (strcasecmp(server_cmd, "CLONE") == 0)
action = STANDBY_CLONE;
else if (strcasecmp(server_cmd, "PROMOTE") == 0)
action = STANDBY_PROMOTE;
else if (strcasecmp(server_cmd, "FOLLOW") == 0)
action = STANDBY_FOLLOW;
}
else if (strcasecmp(server_mode, "WITNESS") == 0)
if (strcasecmp(server_cmd, "CREATE") == 0)
action = WITNESS_CREATE;
}
if (action == NO_ACTION)
{
usage();
exit(ERR_BAD_CONFIG);
}
/* For some actions we still can receive a last argument */
if (action == STANDBY_CLONE)
{
if (optind < argc)
{
if (runtime_options.host[0])
{
log_err(_("Conflicting parameters: you can't use -h while providing a node separately.\n"));
usage();
exit(ERR_BAD_CONFIG);
}
strncpy(runtime_options.host, argv[optind++], MAXLEN);
}
}
switch (optind < argc)
{
case 0:
break;
default:
log_err(_("%s: too many command-line arguments (first extra is \"%s\")\n"),
progname, argv[optind + 1]);
usage();
exit(ERR_BAD_CONFIG);
}
if (!check_parameters_for_action(action))
exit(ERR_BAD_CONFIG);
if (!runtime_options.dbname[0])
{
if (getenv("PGDATABASE"))
strncpy(runtime_options.dbname, getenv("PGDATABASE"), MAXLEN);
else if (getenv("PGUSER"))
strncpy(runtime_options.dbname, getenv("PGUSER"), MAXLEN);
else
strncpy(runtime_options.dbname, DEFAULT_DBNAME, MAXLEN);
}
/* Read the configuration file, normally repmgr.conf */
if (!runtime_options.config_file[0])
strncpy(runtime_options.config_file, DEFAULT_CONFIG_FILE, MAXLEN);
if (runtime_options.verbose)
printf(_("Opening configuration file: %s\n"), runtime_options.config_file);
/*
* XXX Do not read config files for action where it is not required (clone
* for example).
*/
parse_config(runtime_options.config_file, &options);
keywords[2] = "user";
values[2] = (runtime_options.username[0]) ? runtime_options.username : NULL;
keywords[3] = "dbname";
values[3] = runtime_options.dbname;
keywords[4] = "application_name";
values[4] = (char *) progname;
keywords[5] = NULL;
values[5] = NULL;
/*
* Initialize the logger. If verbose command line parameter was
* input, make sure that the log level is at least INFO. This
* is mainly useful for STANDBY CLONE. That doesn't require a
* configuration file where a logging level might be specified
* at, but it often requires detailed logging to troubleshoot
* problems.
*/
logger_init(progname, options.loglevel, options.logfacility);
if (runtime_options.verbose)
logger_min_verbose(LOG_INFO);
/*
* Node configuration information is not needed for all actions,
* with STANDBY CLONE being the main exception.
*/
if (need_a_node)
{
if (options.node == -1)
{
log_err(_("Node information is missing. "
"Check the configuration file.\n"));
exit(ERR_BAD_CONFIG);
}
}
/* Prepare the repmgr schema variable */
snprintf(repmgr_schema, MAXLEN, "%s%s", DEFAULT_REPMGR_SCHEMA_PREFIX, options.cluster_name);
switch (action)
{
case MASTER_REGISTER:
do_master_register();
break;
case STANDBY_REGISTER:
do_standby_register();
break;
case STANDBY_CLONE:
do_standby_clone();
break;
case STANDBY_PROMOTE:
do_standby_promote();
break;
case STANDBY_FOLLOW:
do_standby_follow();
break;
case WITNESS_CREATE:
do_witness_create();
break;
default:
usage();
exit(ERR_BAD_CONFIG);
}
logger_shutdown();
return 0;
}
static void
do_master_register(void)
{
PGconn *conn;
PGresult *res;
char sqlquery[QUERY_STR_LEN];
bool schema_exists = false;
char schema_quoted[MAXLEN];
char master_version[MAXVERSIONSTR];
conn = establishDBConnection(options.conninfo, true);
/* master should be v9 or better */
log_info(_("%s connecting to master database\n"), progname);
pg_version(conn, master_version);
if (strcmp(master_version, "") == 0)
{
PQfinish(conn);
log_err( _("%s needs master to be PostgreSQL 9.0 or better\n"), progname);
return;
}
/* Check we are a master */
log_info(_("%s connected to master, checking its state\n"), progname);
if (is_standby(conn))
{
log_err(_("%s needs master to be PostgreSQL 9.0 or better\n"), progname);
PQfinish(conn);
exit(ERR_BAD_CONFIG);
}
/* Assemble a quoted schema name
* XXX This is not currently used due to a merge conflict, but
* probably should be */
if (false)
{
char *identifier = PQescapeIdentifier(conn, repmgr_schema,
strlen(repmgr_schema));
maxlen_snprintf(schema_quoted, "%s", identifier);
PQfreemem(identifier);
}
/* Check if there is a schema for this cluster */
sqlquery_snprintf(sqlquery,
"SELECT 1 FROM pg_namespace "
"WHERE nspname = '%s'", repmgr_schema);
log_debug(_("master register: %s\n"), sqlquery);
res = PQexec(conn, sqlquery);
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
log_err(_("Can't get info about schemas: %s\n"), PQerrorMessage(conn));
PQclear(res);
PQfinish(conn);
exit(ERR_BAD_CONFIG);
}
if (PQntuples(res) > 0) /* schema exists */
{
if (!runtime_options.force) /* and we are not forcing so error */
{
log_notice(_("Schema %s already exists.\n"), repmgr_schema);
PQclear(res);
PQfinish(conn);
exit(ERR_BAD_CONFIG);
}
schema_exists = true;
}
PQclear(res);
if (!schema_exists)
{
log_info(_("master register: creating database objects inside the %s schema\n"), repmgr_schema);
/* ok, create the schema */
if (!create_schema(conn))
return;
}
else
{
PGconn *master_conn;
int id;
/* Ensure there isn't any other master already registered */
master_conn = getMasterConnection(conn, repmgr_schema, options.node,
options.cluster_name, &id,NULL);
if (master_conn != NULL)
{
PQfinish(master_conn);
log_warning(_("There is a master already in cluster %s\n"), options.cluster_name);
exit(ERR_BAD_CONFIG);
}
}
/* Now register the master */
if (runtime_options.force)
{
sqlquery_snprintf(sqlquery, "DELETE FROM %s.repl_nodes "
" WHERE id = %d",
repmgr_schema, options.node);
log_debug(_("master register: %s\n"), sqlquery);
if (!PQexec(conn, sqlquery))
{
log_warning(_("Cannot delete node details, %s\n"),
PQerrorMessage(conn));
PQfinish(conn);
exit(ERR_BAD_CONFIG);
}
}
sqlquery_snprintf(sqlquery, "INSERT INTO %s.repl_nodes (id, cluster, conninfo, priority) "
"VALUES (%d, '%s', '%s', %d)",
repmgr_schema, options.node, options.cluster_name, options.conninfo, options.priority);
log_debug(_("master register: %s\n"), sqlquery);
if (!PQexec(conn, sqlquery))
{
log_warning(_("Cannot insert node details, %s\n"),
PQerrorMessage(conn));
PQfinish(conn);
exit(ERR_BAD_CONFIG);
}
PQfinish(conn);
log_notice(_("Master node correctly registered for cluster %s with id %d (conninfo: %s)\n"),
options.cluster_name, options.node, options.conninfo);
return;
}
static void
do_standby_register(void)
{
PGconn *conn;
PGconn *master_conn;
int master_id;
PGresult *res;
char sqlquery[QUERY_STR_LEN];
char schema_quoted[MAXLEN];
char master_version[MAXVERSIONSTR];
char standby_version[MAXVERSIONSTR];
/* XXX: A lot of copied code from do_master_register! Refactor */
log_info(_("%s connecting to standby database\n"), progname);
conn = establishDBConnection(options.conninfo, true);
/* should be v9 or better */
log_info(_("%s connected to standby, checking its state\n"), progname);
pg_version(conn, standby_version);
if (strcmp(standby_version, "") == 0)
{
PQfinish(conn);
log_err(_("%s needs standby to be PostgreSQL 9.0 or better\n"), progname);
exit(ERR_BAD_CONFIG);
}
/* Check we are a standby */
if (!is_standby(conn))
{
log_err(_("repmgr: This node should be a standby (%s)\n"), options.conninfo);
PQfinish(conn);
exit(ERR_BAD_CONFIG);
}
/* Assemble a quoted schema name
* XXX This is not currently used due to a merge conflict, but
* probably should be */
if (false)
{
char *identifier = PQescapeIdentifier(conn, repmgr_schema,
strlen(repmgr_schema));
maxlen_snprintf(schema_quoted, "%s", identifier);
PQfreemem(identifier);
}
/* Check if there is a schema for this cluster */
sqlquery_snprintf(sqlquery, "SELECT 1 FROM pg_namespace WHERE nspname = '%s'", repmgr_schema);
log_debug(_("standby register: %s\n"), sqlquery);
res = PQexec(conn, sqlquery);
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
log_err(_("Can't get info about tablespaces: %s\n"), PQerrorMessage(conn));
PQclear(res);
PQfinish(conn);
exit(ERR_BAD_CONFIG);
}
if (PQntuples(res) == 0)
{
/* schema doesn't exist */
log_err(_("Schema %s doesn't exists.\n"), repmgr_schema);
PQclear(res);
PQfinish(conn);
exit(ERR_BAD_CONFIG);
}
PQclear(res);
/* check if there is a master in this cluster */
log_info(_("%s connecting to master database\n"), progname);
master_conn = getMasterConnection(conn, repmgr_schema, options.node, options.cluster_name,
&master_id, NULL);
if (!master_conn)
{
log_err(_("A master must be defined before configuring a slave\n"));
exit(ERR_BAD_CONFIG);
}
/* master should be v9 or better */
log_info(_("%s connected to master, checking its state\n"), progname);
pg_version(master_conn, master_version);
if (strcmp(master_version, "") == 0)
{
PQfinish(conn);
PQfinish(master_conn);
log_err(_("%s needs master to be PostgreSQL 9.0 or better\n"), progname);
exit(ERR_BAD_CONFIG);
}
/* master and standby version should match */
if (strcmp(master_version, standby_version) != 0)
{
PQfinish(conn);
PQfinish(master_conn);
log_err(_("%s needs versions of both master (%s) and standby (%s) to match.\n"),
progname, master_version, standby_version);
exit(ERR_BAD_CONFIG);
}
/* Now register the standby */
log_info(_("%s registering the standby\n"), progname);
if (runtime_options.force)
{
sqlquery_snprintf(sqlquery, "DELETE FROM %s.repl_nodes "
" WHERE id = %d",
repmgr_schema, options.node);
log_debug(_("standby register: %s\n"), sqlquery);
if (!PQexec(master_conn, sqlquery))
{
log_err(_("Cannot delete node details, %s\n"),
PQerrorMessage(master_conn));
PQfinish(master_conn);
PQfinish(conn);
exit(ERR_BAD_CONFIG);
}
}
sqlquery_snprintf(sqlquery, "INSERT INTO %s.repl_nodes(id, cluster, conninfo, priority) "
"VALUES (%d, '%s', '%s', %d)",
repmgr_schema, options.node, options.cluster_name, options.conninfo, options.priority);
log_debug(_("standby register: %s\n"), sqlquery);
if (!PQexec(master_conn, sqlquery))
{
log_err(_("Cannot insert node details, %s\n"),
PQerrorMessage(master_conn));
PQfinish(master_conn);
PQfinish(conn);
exit(ERR_BAD_CONFIG);
}
log_info(_("%s registering the standby complete\n"), progname);
PQfinish(master_conn);
PQfinish(conn);
log_notice(_("Standby node correctly registered for cluster %s with id %d (conninfo: %s)\n"),
options.cluster_name, options.node, options.conninfo);
return;
}
static void
do_standby_clone(void)
{
PGconn *conn;
PGresult *res;
char sqlquery[QUERY_STR_LEN];
int r = 0;
int i;
bool flag_success = false;
bool test_mode = false;
char tblspc_dir[MAXFILENAME];
char master_data_directory[MAXFILENAME];
char local_data_directory[MAXFILENAME];
char master_xlog_directory[MAXFILENAME];
char local_xlog_directory[MAXFILENAME];
char master_stats_temp_directory[MAXFILENAME];
char local_stats_temp_directory[MAXFILENAME];
char master_control_file[MAXFILENAME];
char local_control_file[MAXFILENAME];
char master_config_file[MAXFILENAME];
char local_config_file[MAXFILENAME];
char master_hba_file[MAXFILENAME];
char local_hba_file[MAXFILENAME];
char master_ident_file[MAXFILENAME];
char local_ident_file[MAXFILENAME];
char *first_wal_segment = NULL;
const char *last_wal_segment = NULL;
char master_version[MAXVERSIONSTR];
/*
* if dest_dir has been provided, we copy everything in the same path
* if dest_dir is set and the master have tablespace, repmgr will stop
* because it is more complex to remap the path for the tablespaces and it
* does not look useful at the moment
*/
if (runtime_options.dest_dir[0])
{
test_mode = true;
log_notice(_("%s Destination directory %s provided, try to clone everything in it.\n"), progname, runtime_options.dest_dir);
}
/* Connection parameters for master only */
keywords[0] = "host";
values[0] = runtime_options.host;
keywords[1] = "port";
values[1] = runtime_options.masterport;
/* We need to connect to check configuration and start a backup */
log_info(_("%s connecting to master database\n"), progname);
conn = establishDBConnectionByParams(keywords,values,true);
/* primary should be v9 or better */
log_info(_("%s connected to master, checking its state\n"), progname);
pg_version(conn, master_version);
if (strcmp(master_version, "") == 0)
{
PQfinish(conn);
log_err(_("%s needs master to be PostgreSQL 9.0 or better\n"), progname);
exit(ERR_BAD_CONFIG);
}
/* Check we are cloning a primary node */
if (is_standby(conn))
{
PQfinish(conn);
log_err(_("\nThe command should clone a primary node\n"));
exit(ERR_BAD_CONFIG);
}
/* And check if it is well configured */
if (!guc_setted(conn, "wal_level", "=", "hot_standby"))
{
PQfinish(conn);
log_err(_("%s needs parameter 'wal_level' to be set to 'hot_standby'\n"), progname);
exit(ERR_BAD_CONFIG);
}
if (!guc_setted(conn, "wal_keep_segments", ">=", runtime_options.wal_keep_segments))
{
PQfinish(conn);
log_err(_("%s needs parameter 'wal_keep_segments' to be set to %s or greater (see the '-w' option or edit the postgresql.conf of the PostgreSQL master.)\n"), progname, runtime_options.wal_keep_segments);
exit(ERR_BAD_CONFIG);
}
if (!guc_setted(conn, "archive_mode", "=", "on"))
{
PQfinish(conn);
log_err(_("%s needs parameter 'archive_mode' to be set to 'on'\n"), progname);
exit(ERR_BAD_CONFIG);
}
/*
* Check if the tablespace locations exists and that we can write to
* them.
*/
sqlquery_snprintf(sqlquery,
"SELECT spclocation "
" FROM pg_tablespace "
"WHERE spcname NOT IN ('pg_default', 'pg_global')");
log_debug(_("standby clone: %s\n"), sqlquery);
res = PQexec(conn, sqlquery);
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
log_err(_("Can't get info about tablespaces: %s\n"), PQerrorMessage(conn));
PQclear(res);
PQfinish(conn);
exit(ERR_BAD_CONFIG);
}
for (i = 0; i < PQntuples(res); i++)
{
if (test_mode)
{
log_err("Can't clone in test mode when master have tablespace\n");
PQclear(res);
PQfinish(conn);
exit(ERR_BAD_CONFIG);
}
strncpy(tblspc_dir, PQgetvalue(res, i, 0), MAXFILENAME);
/*
* Check this directory could be used for tablespace
* this will create the directory a bit too early
* XXX build an array of tablespace to create later in the backup
*/
if (!create_pgdir(tblspc_dir, runtime_options.force))
{
PQclear(res);
PQfinish(conn);
exit(ERR_BAD_CONFIG);
}
}
r = test_ssh_connection(runtime_options.host, runtime_options.remote_user);
if (r != 0)
{
log_err(_("%s: Aborting, remote host %s is not reachable.\n"), progname, runtime_options.host);
goto stop_backup;
}
log_notice(_("Starting backup...\n"));
/* Get the data directory full path and the configuration files location */
sqlquery_snprintf(sqlquery,
"SELECT name, setting "
" FROM pg_settings "
" WHERE name IN ('data_directory', 'config_file', 'hba_file', 'ident_file', 'stats_temp_directory')");
log_debug(_("standby clone: %s\n"), sqlquery);
res = PQexec(conn, sqlquery);
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
log_err(_("Can't get info about data directory and configuration files: %s\n"), PQerrorMessage(conn));
PQclear(res);
PQfinish(conn);
exit(ERR_BAD_CONFIG);
}
for (i = 0; i < PQntuples(res); i++)
{
if (strcmp(PQgetvalue(res, i, 0), "data_directory") == 0)
strncpy(master_data_directory, PQgetvalue(res, i, 1), MAXFILENAME);
else if (strcmp(PQgetvalue(res, i, 0), "config_file") == 0)
strncpy(master_config_file, PQgetvalue(res, i, 1), MAXFILENAME);
else if (strcmp(PQgetvalue(res, i, 0), "hba_file") == 0)
strncpy(master_hba_file, PQgetvalue(res, i, 1), MAXFILENAME);
else if (strcmp(PQgetvalue(res, i, 0), "ident_file") == 0)
strncpy(master_ident_file, PQgetvalue(res, i, 1), MAXFILENAME);
else if (strcmp(PQgetvalue(res, i, 0), "stats_temp_directory") == 0)
strncpy(master_stats_temp_directory, PQgetvalue(res, i, 1), MAXFILENAME);
else
log_warning(_("unknown parameter: %s\n"), PQgetvalue(res, i, 0));
}
PQclear(res);
log_info(_("Succesfully connected to primary. Current installation size is %s\n"), get_cluster_size(conn));
/*
* XXX master_xlog_directory should be discovered from master configuration
* but it is not possible via SQL. We need to use a command via ssh
*/
maxlen_snprintf(master_xlog_directory, "%s/pg_xlog", master_data_directory);
if (test_mode)
{
strncpy(local_data_directory, runtime_options.dest_dir, MAXFILENAME);
strncpy(local_config_file, runtime_options.dest_dir, MAXFILENAME);
strncpy(local_hba_file, runtime_options.dest_dir, MAXFILENAME);
strncpy(local_ident_file, runtime_options.dest_dir, MAXFILENAME);
maxlen_snprintf(local_stats_temp_directory, "%s/pg_stat_tmp", runtime_options.dest_dir);
maxlen_snprintf(local_xlog_directory, "%s/pg_xlog", runtime_options.dest_dir);
}
else
{
strncpy(local_data_directory, master_data_directory, MAXFILENAME);
strncpy(local_config_file, master_config_file, MAXFILENAME);
strncpy(local_hba_file, master_hba_file, MAXFILENAME);
strncpy(local_ident_file, master_ident_file, MAXFILENAME);
strncpy(local_stats_temp_directory, master_stats_temp_directory, MAXFILENAME);
strncpy(local_xlog_directory, master_xlog_directory, MAXFILENAME);
}
r = test_ssh_connection(runtime_options.host, runtime_options.remote_user);
if (r != 0)
{
log_err(_("%s: Aborting, remote host %s is not reachable.\n"), progname, runtime_options.host);
goto stop_backup;
}
log_notice(_("Starting backup...\n"));
/*
* inform the master we will start a backup and get the first XLog filename
* so we can say to the user we need those files
*/
sqlquery_snprintf(
sqlquery,
"SELECT pg_xlogfile_name(pg_start_backup('repmgr_standby_clone_%ld'))",
time(NULL));
log_debug(_("standby clone: %s\n"), sqlquery);
res = PQexec(conn, sqlquery);
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
log_err(_("Can't start backup: %s\n"), PQerrorMessage(conn));
PQclear(res);
PQfinish(conn);
exit(ERR_BAD_CONFIG);
}
if (runtime_options.verbose)
{
char *first_wal_seg_pq = PQgetvalue(res, 0, 0);
size_t buf_sz = strlen(first_wal_seg_pq);
first_wal_segment = malloc(buf_sz + 1);
xsnprintf(first_wal_segment, buf_sz + 1, "%s", first_wal_seg_pq);
}
PQclear(res);
/* Check the directory could be used as a PGDATA dir */
if (!create_pgdir(local_data_directory, runtime_options.force))
{
log_err(_("%s: couldn't use directory %s ...\nUse --force option to force\n"),
progname, local_data_directory);
goto stop_backup;
}
/*
* 1) first move global/pg_control
*
* 2) then move data_directory ommiting the files we have already moved and
* pg_xlog content
*
* 3) finally We need to backup configuration files (that could be on other
* directories, debian like systems likes to do that), so look at
* config_file, hba_file and ident_file but we can omit
* external_pid_file ;)
*
* On error we need to return but before that execute pg_stop_backup()
*/
/* need to create the global sub directory */
maxlen_snprintf(master_control_file, "%s/global/pg_control", master_data_directory);
maxlen_snprintf(local_control_file, "%s/global", local_data_directory);
log_info(_("standby clone: master control file '%s'\n"), master_control_file);
if (!create_directory(local_control_file))
{
log_err(_("%s: couldn't create directory %s ...\n"),
progname, local_control_file);
goto stop_backup;
}
log_info(_("standby clone: master control file '%s'\n"), master_control_file);
r = copy_remote_files(runtime_options.host, runtime_options.remote_user,
master_control_file, local_control_file,
false);
if (r != 0)
{
log_warning(_("standby clone: failed copying master control file '%s'\n"), master_control_file);
goto stop_backup;
}
log_info(_("standby clone: master data directory '%s'\n"), master_data_directory);
r = copy_remote_files(runtime_options.host, runtime_options.remote_user,
master_data_directory, local_data_directory,
true);
if (r != 0)
{
log_warning(_("standby clone: failed copying master data directory '%s'\n"), master_data_directory);
goto stop_backup;
}
/*
* Copy tablespace locations, i'm doing this separately because i couldn't
* find and appropiate rsync option but besides we could someday make all
* these rsync happen concurrently
* XXX We may not do that if we are in test_mode but it does not hurt too much
* (except if a tablespace is created during the test)
*/
sqlquery_snprintf(sqlquery,
"SELECT spclocation "
" FROM pg_tablespace "
" WHERE spcname NOT IN ('pg_default', 'pg_global')");
log_debug(_("standby clone: %s\n"), sqlquery);
res = PQexec(conn, sqlquery);
if (PQresultStatus(res) != PGRES_TUPLES_OK)
{
log_err(_("Can't get info about tablespaces: %s\n"), PQerrorMessage(conn));
PQclear(res);
goto stop_backup;
}
for (i = 0; i < PQntuples(res); i++)
{
strncpy(tblspc_dir, PQgetvalue(res, i, 0), MAXFILENAME);
log_info(_("standby clone: master tablespace '%s'\n"), tblspc_dir);
r = copy_remote_files(runtime_options.host, runtime_options.remote_user,
tblspc_dir, tblspc_dir,
true);
if (r != 0)
{
log_warning(_("standby clone: failed copying tablespace directory '%s'\n"), tblspc_dir);
goto stop_backup;
}
}
log_info(_("standby clone: master config file '%s'\n"), master_config_file);
r = copy_remote_files(runtime_options.host, runtime_options.remote_user,
master_config_file, local_config_file,
false);
if (r != 0)
{
log_warning(_("standby clone: failed copying master config file '%s'\n"), master_config_file);
goto stop_backup;
}
log_info(_("standby clone: master hba file '%s'\n"), master_hba_file);
r = copy_remote_files(runtime_options.host, runtime_options.remote_user,
master_hba_file, local_hba_file,
false);
if (r != 0)
{
log_warning(_("standby clone: failed copying master hba file '%s'\n"), master_hba_file);
goto stop_backup;
}
log_info(_("standby clone: master ident file '%s'\n"), master_ident_file);
r = copy_remote_files(runtime_options.host, runtime_options.remote_user,
master_ident_file, local_ident_file,
false);
if (r != 0)
{
log_warning(_("standby clone: failed copying master ident file '%s'\n"), master_ident_file);
goto stop_backup;
}
/* we success so far, flag that to allow a better HINT */
flag_success = true;
stop_backup:
/*
* Inform the master that we have finished the backup.
*
* Don't have this one exit if it fails, so that a more informative
* error message will also appear about the backup not being stopped.
*/
log_info(_("%s connecting to master database to stop backup\n"), progname);
conn=establishDBConnectionByParams(keywords,values,false);
log_notice(_("Finishing backup...\n"));
sqlquery_snprintf(sqlquery, "SELECT pg_xlogfile_name(pg_stop_backup())");
log_debug(_("standby clone: %s\n"), sqlquery);
res = PQexec(conn, sqlquery);
if (PQresultStatus(res) != PGRES_TUPLES_OK)