-
Notifications
You must be signed in to change notification settings - Fork 4.4k
/
pg_basebackup.c
2771 lines (2480 loc) · 78 KB
/
pg_basebackup.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
/*-------------------------------------------------------------------------
*
* pg_basebackup.c - receive a base backup using streaming replication protocol
*
* Author: Magnus Hagander <magnus@hagander.net>
*
* Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
*
* IDENTIFICATION
* src/bin/pg_basebackup/pg_basebackup.c
*-------------------------------------------------------------------------
*/
#include "postgres_fe.h"
#include <unistd.h>
#include <dirent.h>
#include <limits.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <signal.h>
#include <time.h>
#ifdef HAVE_LIBZ
#include <zlib.h>
#endif
#include "access/xlog_internal.h"
#include "backup/basebackup.h"
#include "bbstreamer.h"
#include "common/compression.h"
#include "common/file_perm.h"
#include "common/file_utils.h"
#include "common/logging.h"
#include "fe_utils/option_utils.h"
#include "fe_utils/recovery_gen.h"
#include "getopt_long.h"
#include "receivelog.h"
#include "streamutil.h"
#define ERRCODE_DATA_CORRUPTED "XX001"
typedef struct TablespaceListCell
{
struct TablespaceListCell *next;
char old_dir[MAXPGPATH];
char new_dir[MAXPGPATH];
} TablespaceListCell;
typedef struct TablespaceList
{
TablespaceListCell *head;
TablespaceListCell *tail;
} TablespaceList;
typedef struct ArchiveStreamState
{
int tablespacenum;
pg_compress_specification *compress;
bbstreamer *streamer;
bbstreamer *manifest_inject_streamer;
PQExpBuffer manifest_buffer;
char manifest_filename[MAXPGPATH];
FILE *manifest_file;
} ArchiveStreamState;
typedef struct WriteTarState
{
int tablespacenum;
bbstreamer *streamer;
} WriteTarState;
typedef struct WriteManifestState
{
char filename[MAXPGPATH];
FILE *file;
} WriteManifestState;
typedef void (*WriteDataCallback) (size_t nbytes, char *buf,
void *callback_data);
/*
* pg_xlog has been renamed to pg_wal in version 10. This version number
* should be compared with PQserverVersion().
*/
#define MINIMUM_VERSION_FOR_PG_WAL 100000
/*
* Temporary replication slots are supported from version 10.
*/
#define MINIMUM_VERSION_FOR_TEMP_SLOTS 100000
/*
* Backup manifests are supported from version 13.
*/
#define MINIMUM_VERSION_FOR_MANIFESTS 130000
/*
* Before v15, tar files received from the server will be improperly
* terminated.
*/
#define MINIMUM_VERSION_FOR_TERMINATED_TARFILE 150000
/*
* Different ways to include WAL
*/
typedef enum
{
NO_WAL,
FETCH_WAL,
STREAM_WAL
} IncludeWal;
/*
* Different places to perform compression
*/
typedef enum
{
COMPRESS_LOCATION_UNSPECIFIED,
COMPRESS_LOCATION_CLIENT,
COMPRESS_LOCATION_SERVER
} CompressionLocation;
/* Global options */
static char *basedir = NULL;
static TablespaceList tablespace_dirs = {NULL, NULL};
static char *xlog_dir = NULL;
static char format = '\0'; /* p(lain)/t(ar) */
static char *label = "pg_basebackup base backup";
static bool noclean = false;
static bool checksum_failure = false;
static bool showprogress = false;
static bool estimatesize = true;
static int verbose = 0;
static IncludeWal includewal = STREAM_WAL;
static bool fastcheckpoint = false;
static bool writerecoveryconf = false;
static bool do_sync = true;
static int standby_message_timeout = 10 * 1000; /* 10 sec = default */
static pg_time_t last_progress_report = 0;
static int32 maxrate = 0; /* no limit by default */
static char *replication_slot = NULL;
static bool temp_replication_slot = true;
static char *backup_target = NULL;
static bool create_slot = false;
static bool no_slot = false;
static bool verify_checksums = true;
static bool manifest = true;
static bool manifest_force_encode = false;
static char *manifest_checksums = NULL;
static DataDirSyncMethod sync_method = DATA_DIR_SYNC_METHOD_FSYNC;
static bool success = false;
static bool made_new_pgdata = false;
static bool found_existing_pgdata = false;
static bool made_new_xlogdir = false;
static bool found_existing_xlogdir = false;
static bool made_tablespace_dirs = false;
static bool found_tablespace_dirs = false;
/* Progress indicators */
static uint64 totalsize_kb;
static uint64 totaldone;
static int tablespacecount;
static char *progress_filename = NULL;
/* Pipe to communicate with background wal receiver process */
#ifndef WIN32
static int bgpipe[2] = {-1, -1};
#endif
/* Handle to child process */
static pid_t bgchild = -1;
static bool in_log_streamer = false;
/* Flag to indicate if child process exited unexpectedly */
static volatile sig_atomic_t bgchild_exited = false;
/* End position for xlog streaming, empty string if unknown yet */
static XLogRecPtr xlogendptr;
#ifndef WIN32
static int has_xlogendptr = 0;
#else
static volatile LONG has_xlogendptr = 0;
#endif
/* Contents of configuration file to be generated */
static PQExpBuffer recoveryconfcontents = NULL;
/* Function headers */
static void usage(void);
static void verify_dir_is_empty_or_create(char *dirname, bool *created, bool *found);
static void progress_update_filename(const char *filename);
static void progress_report(int tablespacenum, bool force, bool finished);
static bbstreamer *CreateBackupStreamer(char *archive_name, char *spclocation,
bbstreamer **manifest_inject_streamer_p,
bool is_recovery_guc_supported,
bool expect_unterminated_tarfile,
pg_compress_specification *compress);
static void ReceiveArchiveStreamChunk(size_t r, char *copybuf,
void *callback_data);
static char GetCopyDataByte(size_t r, char *copybuf, size_t *cursor);
static char *GetCopyDataString(size_t r, char *copybuf, size_t *cursor);
static uint64 GetCopyDataUInt64(size_t r, char *copybuf, size_t *cursor);
static void GetCopyDataEnd(size_t r, char *copybuf, size_t cursor);
static void ReportCopyDataParseError(size_t r, char *copybuf);
static void ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
bool tablespacenum, pg_compress_specification *compress);
static void ReceiveTarCopyChunk(size_t r, char *copybuf, void *callback_data);
static void ReceiveBackupManifest(PGconn *conn);
static void ReceiveBackupManifestChunk(size_t r, char *copybuf,
void *callback_data);
static void ReceiveBackupManifestInMemory(PGconn *conn, PQExpBuffer buf);
static void ReceiveBackupManifestInMemoryChunk(size_t r, char *copybuf,
void *callback_data);
static void BaseBackup(char *compression_algorithm, char *compression_detail,
CompressionLocation compressloc,
pg_compress_specification *client_compress);
static bool reached_end_position(XLogRecPtr segendpos, uint32 timeline,
bool segment_finished);
static const char *get_tablespace_mapping(const char *dir);
static void tablespace_list_append(const char *arg);
static void
cleanup_directories_atexit(void)
{
if (success || in_log_streamer)
return;
if (!noclean && !checksum_failure)
{
if (made_new_pgdata)
{
pg_log_info("removing data directory \"%s\"", basedir);
if (!rmtree(basedir, true))
pg_log_error("failed to remove data directory");
}
else if (found_existing_pgdata)
{
pg_log_info("removing contents of data directory \"%s\"", basedir);
if (!rmtree(basedir, false))
pg_log_error("failed to remove contents of data directory");
}
if (made_new_xlogdir)
{
pg_log_info("removing WAL directory \"%s\"", xlog_dir);
if (!rmtree(xlog_dir, true))
pg_log_error("failed to remove WAL directory");
}
else if (found_existing_xlogdir)
{
pg_log_info("removing contents of WAL directory \"%s\"", xlog_dir);
if (!rmtree(xlog_dir, false))
pg_log_error("failed to remove contents of WAL directory");
}
}
else
{
if ((made_new_pgdata || found_existing_pgdata) && !checksum_failure)
pg_log_info("data directory \"%s\" not removed at user's request", basedir);
if (made_new_xlogdir || found_existing_xlogdir)
pg_log_info("WAL directory \"%s\" not removed at user's request", xlog_dir);
}
if ((made_tablespace_dirs || found_tablespace_dirs) && !checksum_failure)
pg_log_info("changes to tablespace directories will not be undone");
}
static void
disconnect_atexit(void)
{
if (conn != NULL)
PQfinish(conn);
}
#ifndef WIN32
/*
* If the bgchild exits prematurely and raises a SIGCHLD signal, we can abort
* processing rather than wait until the backup has finished and error out at
* that time. On Windows, we use a background thread which can communicate
* without the need for a signal handler.
*/
static void
sigchld_handler(SIGNAL_ARGS)
{
bgchild_exited = true;
}
/*
* On windows, our background thread dies along with the process. But on
* Unix, if we have started a subprocess, we want to kill it off so it
* doesn't remain running trying to stream data.
*/
static void
kill_bgchild_atexit(void)
{
if (bgchild > 0 && !bgchild_exited)
kill(bgchild, SIGTERM);
}
#endif
/*
* Split argument into old_dir and new_dir and append to tablespace mapping
* list.
*/
static void
tablespace_list_append(const char *arg)
{
TablespaceListCell *cell = (TablespaceListCell *) pg_malloc0(sizeof(TablespaceListCell));
char *dst;
char *dst_ptr;
const char *arg_ptr;
dst_ptr = dst = cell->old_dir;
for (arg_ptr = arg; *arg_ptr; arg_ptr++)
{
if (dst_ptr - dst >= MAXPGPATH)
pg_fatal("directory name too long");
if (*arg_ptr == '\\' && *(arg_ptr + 1) == '=')
; /* skip backslash escaping = */
else if (*arg_ptr == '=' && (arg_ptr == arg || *(arg_ptr - 1) != '\\'))
{
if (*cell->new_dir)
pg_fatal("multiple \"=\" signs in tablespace mapping");
else
dst = dst_ptr = cell->new_dir;
}
else
*dst_ptr++ = *arg_ptr;
}
if (!*cell->old_dir || !*cell->new_dir)
pg_fatal("invalid tablespace mapping format \"%s\", must be \"OLDDIR=NEWDIR\"", arg);
/*
* All tablespaces are created with absolute directories, so specifying a
* non-absolute path here would just never match, possibly confusing
* users. Since we don't know whether the remote side is Windows or not,
* and it might be different than the local side, permit any path that
* could be absolute under either set of rules.
*
* (There is little practical risk of confusion here, because someone
* running entirely on Linux isn't likely to have a relative path that
* begins with a backslash or something that looks like a drive
* specification. If they do, and they also incorrectly believe that a
* relative path is acceptable here, we'll silently fail to warn them of
* their mistake, and the -T option will just not get applied, same as if
* they'd specified -T for a nonexistent tablespace.)
*/
if (!is_nonwindows_absolute_path(cell->old_dir) &&
!is_windows_absolute_path(cell->old_dir))
pg_fatal("old directory is not an absolute path in tablespace mapping: %s",
cell->old_dir);
if (!is_absolute_path(cell->new_dir))
pg_fatal("new directory is not an absolute path in tablespace mapping: %s",
cell->new_dir);
/*
* Comparisons done with these values should involve similarly
* canonicalized path values. This is particularly sensitive on Windows
* where path values may not necessarily use Unix slashes.
*/
canonicalize_path(cell->old_dir);
canonicalize_path(cell->new_dir);
if (tablespace_dirs.tail)
tablespace_dirs.tail->next = cell;
else
tablespace_dirs.head = cell;
tablespace_dirs.tail = cell;
}
static void
usage(void)
{
printf(_("%s takes a base backup of a running PostgreSQL server.\n\n"),
progname);
printf(_("Usage:\n"));
printf(_(" %s [OPTION]...\n"), progname);
printf(_("\nOptions controlling the output:\n"));
printf(_(" -D, --pgdata=DIRECTORY receive base backup into directory\n"));
printf(_(" -F, --format=p|t output format (plain (default), tar)\n"));
printf(_(" -r, --max-rate=RATE maximum transfer rate to transfer data directory\n"
" (in kB/s, or use suffix \"k\" or \"M\")\n"));
printf(_(" -R, --write-recovery-conf\n"
" write configuration for replication\n"));
printf(_(" -t, --target=TARGET[:DETAIL]\n"
" backup target (if other than client)\n"));
printf(_(" -T, --tablespace-mapping=OLDDIR=NEWDIR\n"
" relocate tablespace in OLDDIR to NEWDIR\n"));
printf(_(" --waldir=WALDIR location for the write-ahead log directory\n"));
printf(_(" -X, --wal-method=none|fetch|stream\n"
" include required WAL files with specified method\n"));
printf(_(" -z, --gzip compress tar output\n"));
printf(_(" -Z, --compress=[{client|server}-]METHOD[:DETAIL]\n"
" compress on client or server as specified\n"));
printf(_(" -Z, --compress=none do not compress tar output\n"));
printf(_("\nGeneral options:\n"));
printf(_(" -c, --checkpoint=fast|spread\n"
" set fast or spread checkpointing\n"));
printf(_(" -C, --create-slot create replication slot\n"));
printf(_(" -l, --label=LABEL set backup label\n"));
printf(_(" -n, --no-clean do not clean up after errors\n"));
printf(_(" -N, --no-sync do not wait for changes to be written safely to disk\n"));
printf(_(" -P, --progress show progress information\n"));
printf(_(" -S, --slot=SLOTNAME replication slot to use\n"));
printf(_(" -v, --verbose output verbose messages\n"));
printf(_(" -V, --version output version information, then exit\n"));
printf(_(" --manifest-checksums=SHA{224,256,384,512}|CRC32C|NONE\n"
" use algorithm for manifest checksums\n"));
printf(_(" --manifest-force-encode\n"
" hex encode all file names in manifest\n"));
printf(_(" --no-estimate-size do not estimate backup size in server side\n"));
printf(_(" --no-manifest suppress generation of backup manifest\n"));
printf(_(" --no-slot prevent creation of temporary replication slot\n"));
printf(_(" --no-verify-checksums\n"
" do not verify checksums\n"));
printf(_(" --sync-method=METHOD\n"
" set method for syncing files to disk\n"));
printf(_(" -?, --help show this help, then exit\n"));
printf(_("\nConnection options:\n"));
printf(_(" -d, --dbname=CONNSTR connection string\n"));
printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
printf(_(" -p, --port=PORT database server port number\n"));
printf(_(" -s, --status-interval=INTERVAL\n"
" time between status packets sent to server (in seconds)\n"));
printf(_(" -U, --username=NAME connect as specified database user\n"));
printf(_(" -w, --no-password never prompt for password\n"));
printf(_(" -W, --password force password prompt (should happen automatically)\n"));
printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
}
/*
* Called in the background process every time data is received.
* On Unix, we check to see if there is any data on our pipe
* (which would mean we have a stop position), and if it is, check if
* it is time to stop.
* On Windows, we are in a single process, so we can just check if it's
* time to stop.
*/
static bool
reached_end_position(XLogRecPtr segendpos, uint32 timeline,
bool segment_finished)
{
if (!has_xlogendptr)
{
#ifndef WIN32
fd_set fds;
struct timeval tv = {0};
int r;
/*
* Don't have the end pointer yet - check our pipe to see if it has
* been sent yet.
*/
FD_ZERO(&fds);
FD_SET(bgpipe[0], &fds);
r = select(bgpipe[0] + 1, &fds, NULL, NULL, &tv);
if (r == 1)
{
char xlogend[64] = {0};
uint32 hi,
lo;
r = read(bgpipe[0], xlogend, sizeof(xlogend) - 1);
if (r < 0)
pg_fatal("could not read from ready pipe: %m");
if (sscanf(xlogend, "%X/%X", &hi, &lo) != 2)
pg_fatal("could not parse write-ahead log location \"%s\"",
xlogend);
xlogendptr = ((uint64) hi) << 32 | lo;
has_xlogendptr = 1;
/*
* Fall through to check if we've reached the point further
* already.
*/
}
else
{
/*
* No data received on the pipe means we don't know the end
* position yet - so just say it's not time to stop yet.
*/
return false;
}
#else
/*
* On win32, has_xlogendptr is set by the main thread, so if it's not
* set here, we just go back and wait until it shows up.
*/
return false;
#endif
}
/*
* At this point we have an end pointer, so compare it to the current
* position to figure out if it's time to stop.
*/
if (segendpos >= xlogendptr)
return true;
/*
* Have end pointer, but haven't reached it yet - so tell the caller to
* keep streaming.
*/
return false;
}
typedef struct
{
PGconn *bgconn;
XLogRecPtr startptr;
char xlog[MAXPGPATH]; /* directory or tarfile depending on mode */
char *sysidentifier;
int timeline;
pg_compress_algorithm wal_compress_algorithm;
int wal_compress_level;
} logstreamer_param;
static int
LogStreamerMain(logstreamer_param *param)
{
StreamCtl stream = {0};
in_log_streamer = true;
stream.startpos = param->startptr;
stream.timeline = param->timeline;
stream.sysidentifier = param->sysidentifier;
stream.stream_stop = reached_end_position;
#ifndef WIN32
stream.stop_socket = bgpipe[0];
#else
stream.stop_socket = PGINVALID_SOCKET;
#endif
stream.standby_message_timeout = standby_message_timeout;
stream.synchronous = false;
/* fsync happens at the end of pg_basebackup for all data */
stream.do_sync = false;
stream.mark_done = true;
stream.partial_suffix = NULL;
stream.replication_slot = replication_slot;
if (format == 'p')
stream.walmethod = CreateWalDirectoryMethod(param->xlog,
PG_COMPRESSION_NONE, 0,
stream.do_sync);
else
stream.walmethod = CreateWalTarMethod(param->xlog,
param->wal_compress_algorithm,
param->wal_compress_level,
stream.do_sync);
if (!ReceiveXlogStream(param->bgconn, &stream))
{
/*
* Any errors will already have been reported in the function process,
* but we need to tell the parent that we didn't shutdown in a nice
* way.
*/
#ifdef WIN32
/*
* In order to signal the main thread of an ungraceful exit we set the
* same flag that we use on Unix to signal SIGCHLD.
*/
bgchild_exited = true;
#endif
return 1;
}
if (!stream.walmethod->ops->finish(stream.walmethod))
{
pg_log_error("could not finish writing WAL files: %m");
#ifdef WIN32
bgchild_exited = true;
#endif
return 1;
}
PQfinish(param->bgconn);
stream.walmethod->ops->free(stream.walmethod);
return 0;
}
/*
* Initiate background process for receiving xlog during the backup.
* The background stream will use its own database connection so we can
* stream the logfile in parallel with the backups.
*/
static void
StartLogStreamer(char *startpos, uint32 timeline, char *sysidentifier,
pg_compress_algorithm wal_compress_algorithm,
int wal_compress_level)
{
logstreamer_param *param;
uint32 hi,
lo;
char statusdir[MAXPGPATH];
param = pg_malloc0(sizeof(logstreamer_param));
param->timeline = timeline;
param->sysidentifier = sysidentifier;
param->wal_compress_algorithm = wal_compress_algorithm;
param->wal_compress_level = wal_compress_level;
/* Convert the starting position */
if (sscanf(startpos, "%X/%X", &hi, &lo) != 2)
pg_fatal("could not parse write-ahead log location \"%s\"",
startpos);
param->startptr = ((uint64) hi) << 32 | lo;
/* Round off to even segment position */
param->startptr -= XLogSegmentOffset(param->startptr, WalSegSz);
#ifndef WIN32
/* Create our background pipe */
if (pipe(bgpipe) < 0)
pg_fatal("could not create pipe for background process: %m");
#endif
/* Get a second connection */
param->bgconn = GetConnection();
if (!param->bgconn)
/* Error message already written in GetConnection() */
exit(1);
/* In post-10 cluster, pg_xlog has been renamed to pg_wal */
snprintf(param->xlog, sizeof(param->xlog), "%s/%s",
basedir,
PQserverVersion(conn) < MINIMUM_VERSION_FOR_PG_WAL ?
"pg_xlog" : "pg_wal");
/* Temporary replication slots are only supported in 10 and newer */
if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_TEMP_SLOTS)
temp_replication_slot = false;
/*
* Create replication slot if requested
*/
if (temp_replication_slot && !replication_slot)
replication_slot = psprintf("pg_basebackup_%d", (int) PQbackendPID(param->bgconn));
if (temp_replication_slot || create_slot)
{
if (!CreateReplicationSlot(param->bgconn, replication_slot, NULL,
temp_replication_slot, true, true, false, false))
exit(1);
if (verbose)
{
if (temp_replication_slot)
pg_log_info("created temporary replication slot \"%s\"",
replication_slot);
else
pg_log_info("created replication slot \"%s\"",
replication_slot);
}
}
if (format == 'p')
{
/*
* Create pg_wal/archive_status or pg_xlog/archive_status (and thus
* pg_wal or pg_xlog) depending on the target server so we can write
* to basedir/pg_wal or basedir/pg_xlog as the directory entry in the
* tar file may arrive later.
*/
snprintf(statusdir, sizeof(statusdir), "%s/%s/archive_status",
basedir,
PQserverVersion(conn) < MINIMUM_VERSION_FOR_PG_WAL ?
"pg_xlog" : "pg_wal");
if (pg_mkdir_p(statusdir, pg_dir_create_mode) != 0 && errno != EEXIST)
pg_fatal("could not create directory \"%s\": %m", statusdir);
}
/*
* Start a child process and tell it to start streaming. On Unix, this is
* a fork(). On Windows, we create a thread.
*/
#ifndef WIN32
bgchild = fork();
if (bgchild == 0)
{
/* in child process */
exit(LogStreamerMain(param));
}
else if (bgchild < 0)
pg_fatal("could not create background process: %m");
/*
* Else we are in the parent process and all is well.
*/
atexit(kill_bgchild_atexit);
#else /* WIN32 */
bgchild = _beginthreadex(NULL, 0, (void *) LogStreamerMain, param, 0, NULL);
if (bgchild == 0)
pg_fatal("could not create background thread: %m");
#endif
}
/*
* Verify that the given directory exists and is empty. If it does not
* exist, it is created. If it exists but is not empty, an error will
* be given and the process ended.
*/
static void
verify_dir_is_empty_or_create(char *dirname, bool *created, bool *found)
{
switch (pg_check_dir(dirname))
{
case 0:
/*
* Does not exist, so create
*/
if (pg_mkdir_p(dirname, pg_dir_create_mode) == -1)
pg_fatal("could not create directory \"%s\": %m", dirname);
if (created)
*created = true;
return;
case 1:
/*
* Exists, empty
*/
if (found)
*found = true;
return;
case 2:
case 3:
case 4:
/*
* Exists, not empty
*/
pg_fatal("directory \"%s\" exists but is not empty", dirname);
case -1:
/*
* Access problem
*/
pg_fatal("could not access directory \"%s\": %m", dirname);
}
}
/*
* Callback to update our notion of the current filename.
*
* No other code should modify progress_filename!
*/
static void
progress_update_filename(const char *filename)
{
/* We needn't maintain this variable if not doing verbose reports. */
if (showprogress && verbose)
{
free(progress_filename);
if (filename)
progress_filename = pg_strdup(filename);
else
progress_filename = NULL;
}
}
/*
* Print a progress report based on the global variables. If verbose output
* is enabled, also print the current file name.
*
* Progress report is written at maximum once per second, unless the force
* parameter is set to true.
*
* If finished is set to true, this is the last progress report. The cursor
* is moved to the next line.
*/
static void
progress_report(int tablespacenum, bool force, bool finished)
{
int percent;
char totaldone_str[32];
char totalsize_str[32];
pg_time_t now;
if (!showprogress)
return;
now = time(NULL);
if (now == last_progress_report && !force && !finished)
return; /* Max once per second */
last_progress_report = now;
percent = totalsize_kb ? (int) ((totaldone / 1024) * 100 / totalsize_kb) : 0;
/*
* Avoid overflowing past 100% or the full size. This may make the total
* size number change as we approach the end of the backup (the estimate
* will always be wrong if WAL is included), but that's better than having
* the done column be bigger than the total.
*/
if (percent > 100)
percent = 100;
if (totaldone / 1024 > totalsize_kb)
totalsize_kb = totaldone / 1024;
snprintf(totaldone_str, sizeof(totaldone_str), UINT64_FORMAT,
totaldone / 1024);
snprintf(totalsize_str, sizeof(totalsize_str), UINT64_FORMAT, totalsize_kb);
#define VERBOSE_FILENAME_LENGTH 35
if (verbose)
{
if (!progress_filename)
/*
* No filename given, so clear the status line (used for last
* call)
*/
fprintf(stderr,
ngettext("%*s/%s kB (100%%), %d/%d tablespace %*s",
"%*s/%s kB (100%%), %d/%d tablespaces %*s",
tablespacecount),
(int) strlen(totalsize_str),
totaldone_str, totalsize_str,
tablespacenum, tablespacecount,
VERBOSE_FILENAME_LENGTH + 5, "");
else
{
bool truncate = (strlen(progress_filename) > VERBOSE_FILENAME_LENGTH);
fprintf(stderr,
ngettext("%*s/%s kB (%d%%), %d/%d tablespace (%s%-*.*s)",
"%*s/%s kB (%d%%), %d/%d tablespaces (%s%-*.*s)",
tablespacecount),
(int) strlen(totalsize_str),
totaldone_str, totalsize_str, percent,
tablespacenum, tablespacecount,
/* Prefix with "..." if we do leading truncation */
truncate ? "..." : "",
truncate ? VERBOSE_FILENAME_LENGTH - 3 : VERBOSE_FILENAME_LENGTH,
truncate ? VERBOSE_FILENAME_LENGTH - 3 : VERBOSE_FILENAME_LENGTH,
/* Truncate filename at beginning if it's too long */
truncate ? progress_filename + strlen(progress_filename) - VERBOSE_FILENAME_LENGTH + 3 : progress_filename);
}
}
else
fprintf(stderr,
ngettext("%*s/%s kB (%d%%), %d/%d tablespace",
"%*s/%s kB (%d%%), %d/%d tablespaces",
tablespacecount),
(int) strlen(totalsize_str),
totaldone_str, totalsize_str, percent,
tablespacenum, tablespacecount);
/*
* Stay on the same line if reporting to a terminal and we're not done
* yet.
*/
fputc((!finished && isatty(fileno(stderr))) ? '\r' : '\n', stderr);
}
static int32
parse_max_rate(char *src)
{
double result;
char *after_num;
char *suffix = NULL;
errno = 0;
result = strtod(src, &after_num);
if (src == after_num)
pg_fatal("transfer rate \"%s\" is not a valid value", src);
if (errno != 0)
pg_fatal("invalid transfer rate \"%s\": %m", src);
if (result <= 0)
{
/*
* Reject obviously wrong values here.
*/
pg_fatal("transfer rate must be greater than zero");
}
/*
* Evaluate suffix, after skipping over possible whitespace. Lack of
* suffix means kilobytes.
*/
while (*after_num != '\0' && isspace((unsigned char) *after_num))
after_num++;
if (*after_num != '\0')
{
suffix = after_num;
if (*after_num == 'k')
{
/* kilobyte is the expected unit. */
after_num++;
}
else if (*after_num == 'M')
{
after_num++;
result *= 1024.0;
}
}
/* The rest can only consist of white space. */
while (*after_num != '\0' && isspace((unsigned char) *after_num))
after_num++;
if (*after_num != '\0')
pg_fatal("invalid --max-rate unit: \"%s\"", suffix);
/* Valid integer? */
if ((uint64) result != (uint64) ((uint32) result))
pg_fatal("transfer rate \"%s\" exceeds integer range", src);
/*
* The range is checked on the server side too, but avoid the server
* connection if a nonsensical value was passed.
*/
if (result < MAX_RATE_LOWER || result > MAX_RATE_UPPER)
pg_fatal("transfer rate \"%s\" is out of range", src);
return (int32) result;
}
/*
* Basic parsing of a value specified for -Z/--compress.
*
* We're not concerned here with understanding exactly what behavior the
* user wants, but we do need to know whether the user is requesting client
* or server side compression or leaving it unspecified, and we need to
* separate the name of the compression algorithm from the detail string.
*
* For instance, if the user writes --compress client-lz4:6, we want to
* separate that into (a) client-side compression, (b) algorithm "lz4",
* and (c) detail "6". Note, however, that all the client/server prefix is
* optional, and so is the detail. The algorithm name is required, unless
* the whole string is an integer, in which case we assume "gzip" as the
* algorithm and use the integer as the detail.
*
* We're not concerned with validation at this stage, so if the user writes
* --compress client-turkey:sandwich, the requested algorithm is "turkey"
* and the detail string is "sandwich". We'll sort out whether that's legal
* at a later stage.
*/
static void
backup_parse_compress_options(char *option, char **algorithm, char **detail,
CompressionLocation *locationres)
{
/*
* Strip off any "client-" or "server-" prefix, calculating the location.
*/
if (strncmp(option, "server-", 7) == 0)
{
*locationres = COMPRESS_LOCATION_SERVER;
option += 7;
}
else if (strncmp(option, "client-", 7) == 0)
{
*locationres = COMPRESS_LOCATION_CLIENT;
option += 7;
}
else
*locationres = COMPRESS_LOCATION_UNSPECIFIED;
/* fallback to the common parsing for the algorithm and detail */
parse_compress_options(option, algorithm, detail);
}
/*
* Read a stream of COPY data and invoke the provided callback for each
* chunk.
*/
static void
ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
void *callback_data)
{
PGresult *res;
/* Get the COPY data stream. */
res = PQgetResult(conn);
if (PQresultStatus(res) != PGRES_COPY_OUT)
pg_fatal("could not get COPY data stream: %s",
PQerrorMessage(conn));
PQclear(res);