Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * pg_basebackup.c - receive a base backup using streaming replication protocol
4 : : *
5 : : * Author: Magnus Hagander <magnus@hagander.net>
6 : : *
7 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
8 : : *
9 : : * IDENTIFICATION
10 : : * src/bin/pg_basebackup/pg_basebackup.c
11 : : *-------------------------------------------------------------------------
12 : : */
13 : :
14 : : #include "postgres_fe.h"
15 : :
16 : : #include <unistd.h>
17 : : #include <dirent.h>
18 : : #include <limits.h>
19 : : #include <sys/select.h>
20 : : #include <sys/stat.h>
21 : : #include <sys/wait.h>
22 : : #include <signal.h>
23 : : #include <time.h>
24 : : #ifdef HAVE_LIBZ
25 : : #include <zlib.h>
26 : : #endif
27 : :
28 : : #include "access/xlog_internal.h"
29 : : #include "astreamer_inject.h"
30 : : #include "backup/basebackup.h"
31 : : #include "common/compression.h"
32 : : #include "common/file_perm.h"
33 : : #include "common/file_utils.h"
34 : : #include "common/logging.h"
35 : : #include "fe_utils/option_utils.h"
36 : : #include "fe_utils/recovery_gen.h"
37 : : #include "getopt_long.h"
38 : : #include "libpq/protocol.h"
39 : : #include "receivelog.h"
40 : : #include "streamutil.h"
41 : :
42 : : #define ERRCODE_DATA_CORRUPTED "XX001"
43 : :
44 : : typedef struct TablespaceListCell
45 : : {
46 : : struct TablespaceListCell *next;
47 : : char old_dir[MAXPGPATH];
48 : : char new_dir[MAXPGPATH];
49 : : } TablespaceListCell;
50 : :
51 : : typedef struct TablespaceList
52 : : {
53 : : TablespaceListCell *head;
54 : : TablespaceListCell *tail;
55 : : } TablespaceList;
56 : :
57 : : typedef struct ArchiveStreamState
58 : : {
59 : : int tablespacenum;
60 : : pg_compress_specification *compress;
61 : : astreamer *streamer;
62 : : astreamer *manifest_inject_streamer;
63 : : PQExpBuffer manifest_buffer;
64 : : char manifest_filename[MAXPGPATH];
65 : : FILE *manifest_file;
66 : : } ArchiveStreamState;
67 : :
68 : : typedef struct WriteTarState
69 : : {
70 : : int tablespacenum;
71 : : astreamer *streamer;
72 : : } WriteTarState;
73 : :
74 : : typedef struct WriteManifestState
75 : : {
76 : : char filename[MAXPGPATH];
77 : : FILE *file;
78 : : } WriteManifestState;
79 : :
80 : : typedef void (*WriteDataCallback) (size_t nbytes, char *buf,
81 : : void *callback_data);
82 : :
83 : : /*
84 : : * pg_xlog has been renamed to pg_wal in version 10. This version number
85 : : * should be compared with PQserverVersion().
86 : : */
87 : : #define MINIMUM_VERSION_FOR_PG_WAL 100000
88 : :
89 : : /*
90 : : * Temporary replication slots are supported from version 10.
91 : : */
92 : : #define MINIMUM_VERSION_FOR_TEMP_SLOTS 100000
93 : :
94 : : /*
95 : : * Backup manifests are supported from version 13.
96 : : */
97 : : #define MINIMUM_VERSION_FOR_MANIFESTS 130000
98 : :
99 : : /*
100 : : * Before v15, tar files received from the server will be improperly
101 : : * terminated.
102 : : */
103 : : #define MINIMUM_VERSION_FOR_TERMINATED_TARFILE 150000
104 : :
105 : : /*
106 : : * pg_wal/summaries exists beginning with version 17.
107 : : */
108 : : #define MINIMUM_VERSION_FOR_WAL_SUMMARIES 170000
109 : :
110 : : /*
111 : : * Different ways to include WAL
112 : : */
113 : : typedef enum
114 : : {
115 : : NO_WAL,
116 : : FETCH_WAL,
117 : : STREAM_WAL,
118 : : } IncludeWal;
119 : :
120 : : /*
121 : : * Different places to perform compression
122 : : */
123 : : typedef enum
124 : : {
125 : : COMPRESS_LOCATION_UNSPECIFIED,
126 : : COMPRESS_LOCATION_CLIENT,
127 : : COMPRESS_LOCATION_SERVER,
128 : : } CompressionLocation;
129 : :
130 : : /* Global options */
131 : : static char *basedir = NULL;
132 : : static TablespaceList tablespace_dirs = {NULL, NULL};
133 : : static char *xlog_dir = NULL;
134 : : static char format = '\0'; /* p(lain)/t(ar) */
135 : : static char *label = "pg_basebackup base backup";
136 : : static bool noclean = false;
137 : : static bool checksum_failure = false;
138 : : static bool showprogress = false;
139 : : static bool estimatesize = true;
140 : : static int verbose = 0;
141 : : static IncludeWal includewal = STREAM_WAL;
142 : : static bool fastcheckpoint = false;
143 : : static bool writerecoveryconf = false;
144 : : static bool do_sync = true;
145 : : static int standby_message_timeout = 10 * 1000; /* 10 sec = default */
146 : : static pg_time_t last_progress_report = 0;
147 : : static int32 maxrate = 0; /* no limit by default */
148 : : static char *replication_slot = NULL;
149 : : static bool temp_replication_slot = true;
150 : : static char *backup_target = NULL;
151 : : static bool create_slot = false;
152 : : static bool no_slot = false;
153 : : static bool verify_checksums = true;
154 : : static bool manifest = true;
155 : : static bool manifest_force_encode = false;
156 : : static char *manifest_checksums = NULL;
157 : : static DataDirSyncMethod sync_method = DATA_DIR_SYNC_METHOD_FSYNC;
158 : :
159 : : static bool success = false;
160 : : static bool made_new_pgdata = false;
161 : : static bool found_existing_pgdata = false;
162 : : static bool made_new_xlogdir = false;
163 : : static bool found_existing_xlogdir = false;
164 : : static bool made_tablespace_dirs = false;
165 : : static bool found_tablespace_dirs = false;
166 : :
167 : : /* Progress indicators */
168 : : static uint64 totalsize_kb;
169 : : static uint64 totaldone;
170 : : static int tablespacecount;
171 : : static char *progress_filename = NULL;
172 : :
173 : : /* Pipe to communicate with background wal receiver process */
174 : : #ifndef WIN32
175 : : static int bgpipe[2] = {-1, -1};
176 : : #endif
177 : :
178 : : /* Handle to child process */
179 : : static pid_t bgchild = -1;
180 : : static bool in_log_streamer = false;
181 : :
182 : : /* Flag to indicate if child process exited unexpectedly */
183 : : static volatile sig_atomic_t bgchild_exited = false;
184 : :
185 : : /* End position for xlog streaming, empty string if unknown yet */
186 : : static XLogRecPtr xlogendptr;
187 : :
188 : : #ifndef WIN32
189 : : static int has_xlogendptr = 0;
190 : : #else
191 : : static volatile LONG has_xlogendptr = 0;
192 : : #endif
193 : :
194 : : /* Contents of configuration file to be generated */
195 : : static PQExpBuffer recoveryconfcontents = NULL;
196 : :
197 : : /* Function headers */
198 : : static void usage(void);
199 : : static void verify_dir_is_empty_or_create(char *dirname, bool *created, bool *found);
200 : : static void progress_update_filename(const char *filename);
201 : : static void progress_report(int tablespacenum, bool force, bool finished);
202 : :
203 : : static astreamer *CreateBackupStreamer(char *archive_name, char *spclocation,
204 : : astreamer **manifest_inject_streamer_p,
205 : : bool is_recovery_guc_supported,
206 : : bool expect_unterminated_tarfile,
207 : : pg_compress_specification *compress);
208 : : static void ReceiveArchiveStreamChunk(size_t r, char *copybuf,
209 : : void *callback_data);
210 : : static char GetCopyDataByte(size_t r, char *copybuf, size_t *cursor);
211 : : static char *GetCopyDataString(size_t r, char *copybuf, size_t *cursor);
212 : : static uint64 GetCopyDataUInt64(size_t r, char *copybuf, size_t *cursor);
213 : : static void GetCopyDataEnd(size_t r, char *copybuf, size_t cursor);
214 : : static void ReportCopyDataParseError(size_t r, char *copybuf);
215 : : static void ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
216 : : bool tablespacenum, pg_compress_specification *compress);
217 : : static void ReceiveTarCopyChunk(size_t r, char *copybuf, void *callback_data);
218 : : static void ReceiveBackupManifest(PGconn *conn);
219 : : static void ReceiveBackupManifestChunk(size_t r, char *copybuf,
220 : : void *callback_data);
221 : : static void ReceiveBackupManifestInMemory(PGconn *conn, PQExpBuffer buf);
222 : : static void ReceiveBackupManifestInMemoryChunk(size_t r, char *copybuf,
223 : : void *callback_data);
224 : : static void BaseBackup(char *compression_algorithm, char *compression_detail,
225 : : CompressionLocation compressloc,
226 : : pg_compress_specification *client_compress,
227 : : char *incremental_manifest);
228 : :
229 : : static bool reached_end_position(XLogRecPtr segendpos, uint32 timeline,
230 : : bool segment_finished);
231 : :
232 : : static const char *get_tablespace_mapping(const char *dir);
233 : : static void tablespace_list_append(const char *arg);
234 : :
235 : :
236 : : static void
3522 peter_e@gmx.net 237 :CBC 382 : cleanup_directories_atexit(void)
238 : : {
239 [ + + + + ]: 382 : if (success || in_log_streamer)
240 : 325 : return;
241 : :
2954 magnus@hagander.net 242 [ + + + + ]: 57 : if (!noclean && !checksum_failure)
243 : : {
3522 peter_e@gmx.net 244 [ + + ]: 53 : if (made_new_pgdata)
245 : : {
2591 peter@eisentraut.org 246 : 19 : pg_log_info("removing data directory \"%s\"", basedir);
3522 peter_e@gmx.net 247 [ - + ]: 19 : if (!rmtree(basedir, true))
2591 peter@eisentraut.org 248 :UBC 0 : pg_log_error("failed to remove data directory");
249 : : }
3522 peter_e@gmx.net 250 [ - + ]:CBC 34 : else if (found_existing_pgdata)
251 : : {
2591 peter@eisentraut.org 252 :UBC 0 : pg_log_info("removing contents of data directory \"%s\"", basedir);
3522 peter_e@gmx.net 253 [ # # ]: 0 : if (!rmtree(basedir, false))
2591 peter@eisentraut.org 254 : 0 : pg_log_error("failed to remove contents of data directory");
255 : : }
256 : :
3522 peter_e@gmx.net 257 [ - + ]:CBC 53 : if (made_new_xlogdir)
258 : : {
2591 peter@eisentraut.org 259 :UBC 0 : pg_log_info("removing WAL directory \"%s\"", xlog_dir);
3522 peter_e@gmx.net 260 [ # # ]: 0 : if (!rmtree(xlog_dir, true))
2591 peter@eisentraut.org 261 : 0 : pg_log_error("failed to remove WAL directory");
262 : : }
3522 peter_e@gmx.net 263 [ - + ]:CBC 53 : else if (found_existing_xlogdir)
264 : : {
2591 peter@eisentraut.org 265 :UBC 0 : pg_log_info("removing contents of WAL directory \"%s\"", xlog_dir);
3522 peter_e@gmx.net 266 [ # # ]: 0 : if (!rmtree(xlog_dir, false))
2591 peter@eisentraut.org 267 : 0 : pg_log_error("failed to remove contents of WAL directory");
268 : : }
269 : : }
270 : : else
271 : : {
2954 magnus@hagander.net 272 [ + + - + :CBC 4 : if ((made_new_pgdata || found_existing_pgdata) && !checksum_failure)
- + ]
2591 peter@eisentraut.org 273 :UBC 0 : pg_log_info("data directory \"%s\" not removed at user's request", basedir);
274 : :
3522 peter_e@gmx.net 275 [ + - - + ]:CBC 4 : if (made_new_xlogdir || found_existing_xlogdir)
2591 peter@eisentraut.org 276 :UBC 0 : pg_log_info("WAL directory \"%s\" not removed at user's request", xlog_dir);
277 : : }
278 : :
2954 magnus@hagander.net 279 [ + - - + :CBC 57 : if ((made_tablespace_dirs || found_tablespace_dirs) && !checksum_failure)
- - ]
2591 peter@eisentraut.org 280 :UBC 0 : pg_log_info("changes to tablespace directories will not be undone");
281 : : }
282 : :
283 : : static void
2684 peter@eisentraut.org 284 :CBC 352 : disconnect_atexit(void)
285 : : {
4468 magnus@hagander.net 286 [ + + ]: 352 : if (conn != NULL)
287 : 175 : PQfinish(conn);
2684 peter@eisentraut.org 288 : 352 : }
289 : :
290 : : #ifndef WIN32
291 : : /*
292 : : * If the bgchild exits prematurely and raises a SIGCHLD signal, we can abort
293 : : * processing rather than wait until the backup has finished and error out at
294 : : * that time. On Windows, we use a background thread which can communicate
295 : : * without the need for a signal handler.
296 : : */
297 : : static void
1532 dgustafsson@postgres 298 : 150 : sigchld_handler(SIGNAL_ARGS)
299 : : {
300 : 150 : bgchild_exited = true;
301 : 150 : }
302 : :
303 : : /*
304 : : * On windows, our background thread dies along with the process. But on
305 : : * Unix, if we have started a subprocess, we want to kill it off so it
306 : : * doesn't remain running trying to stream data.
307 : : */
308 : : static void
2684 peter@eisentraut.org 309 : 152 : kill_bgchild_atexit(void)
310 : : {
1532 dgustafsson@postgres 311 [ + - + + ]: 152 : if (bgchild > 0 && !bgchild_exited)
4468 magnus@hagander.net 312 : 4 : kill(bgchild, SIGTERM);
313 : 152 : }
314 : : #endif
315 : :
316 : : /*
317 : : * Split argument into old_dir and new_dir and append to tablespace mapping
318 : : * list.
319 : : */
320 : : static void
4455 peter_e@gmx.net 321 : 22 : tablespace_list_append(const char *arg)
322 : : {
67 michael@paquier.xyz 323 :GNC 22 : TablespaceListCell *cell = pg_malloc0_object(TablespaceListCell);
324 : : char *dst;
325 : : char *dst_ptr;
326 : : const char *arg_ptr;
327 : :
4455 peter_e@gmx.net 328 :CBC 22 : dst_ptr = dst = cell->old_dir;
329 [ + + ]: 910 : for (arg_ptr = arg; *arg_ptr; arg_ptr++)
330 : : {
331 [ - + ]: 889 : if (dst_ptr - dst >= MAXPGPATH)
1488 tgl@sss.pgh.pa.us 332 :UBC 0 : pg_fatal("directory name too long");
333 : :
4455 peter_e@gmx.net 334 [ + + + - ]:CBC 889 : if (*arg_ptr == '\\' && *(arg_ptr + 1) == '=')
335 : : ; /* skip backslash escaping = */
336 [ + + + + : 887 : else if (*arg_ptr == '=' && (arg_ptr == arg || *(arg_ptr - 1) != '\\'))
+ + ]
337 : : {
338 [ + + ]: 22 : if (*cell->new_dir)
1488 tgl@sss.pgh.pa.us 339 : 1 : pg_fatal("multiple \"=\" signs in tablespace mapping");
340 : : else
4455 peter_e@gmx.net 341 : 21 : dst = dst_ptr = cell->new_dir;
342 : : }
343 : : else
344 : 865 : *dst_ptr++ = *arg_ptr;
345 : : }
346 : :
347 [ + + + + ]: 21 : if (!*cell->old_dir || !*cell->new_dir)
1488 tgl@sss.pgh.pa.us 348 : 3 : pg_fatal("invalid tablespace mapping format \"%s\", must be \"OLDDIR=NEWDIR\"", arg);
349 : :
350 : : /*
351 : : * All tablespaces are created with absolute directories, so specifying a
352 : : * non-absolute path here would just never match, possibly confusing
353 : : * users. Since we don't know whether the remote side is Windows or not,
354 : : * and it might be different than the local side, permit any path that
355 : : * could be absolute under either set of rules.
356 : : *
357 : : * (There is little practical risk of confusion here, because someone
358 : : * running entirely on Linux isn't likely to have a relative path that
359 : : * begins with a backslash or something that looks like a drive
360 : : * specification. If they do, and they also incorrectly believe that a
361 : : * relative path is acceptable here, we'll silently fail to warn them of
362 : : * their mistake, and the -T option will just not get applied, same as if
363 : : * they'd specified -T for a nonexistent tablespace.)
364 : : */
1292 rhaas@postgresql.org 365 [ + + ]: 18 : if (!is_nonwindows_absolute_path(cell->old_dir) &&
366 [ + - + - : 1 : !is_windows_absolute_path(cell->old_dir))
+ - - + -
- - - ]
1488 tgl@sss.pgh.pa.us 367 : 1 : pg_fatal("old directory is not an absolute path in tablespace mapping: %s",
368 : : cell->old_dir);
369 : :
4455 peter_e@gmx.net 370 [ + + ]: 17 : if (!is_absolute_path(cell->new_dir))
1488 tgl@sss.pgh.pa.us 371 : 1 : pg_fatal("new directory is not an absolute path in tablespace mapping: %s",
372 : : cell->new_dir);
373 : :
374 : : /*
375 : : * Comparisons done with these values should involve similarly
376 : : * canonicalized path values. This is particularly sensitive on Windows
377 : : * where path values may not necessarily use Unix slashes.
378 : : */
4025 bruce@momjian.us 379 : 16 : canonicalize_path(cell->old_dir);
380 : 16 : canonicalize_path(cell->new_dir);
381 : :
4455 peter_e@gmx.net 382 [ - + ]: 16 : if (tablespace_dirs.tail)
4455 peter_e@gmx.net 383 :UBC 0 : tablespace_dirs.tail->next = cell;
384 : : else
4455 peter_e@gmx.net 385 :CBC 16 : tablespace_dirs.head = cell;
386 : 16 : tablespace_dirs.tail = cell;
387 : 16 : }
388 : :
389 : :
390 : : static void
5581 magnus@hagander.net 391 : 1 : usage(void)
392 : : {
5480 peter_e@gmx.net 393 : 1 : printf(_("%s takes a base backup of a running PostgreSQL server.\n\n"),
394 : : progname);
5581 magnus@hagander.net 395 : 1 : printf(_("Usage:\n"));
396 : 1 : printf(_(" %s [OPTION]...\n"), progname);
397 : 1 : printf(_("\nOptions controlling the output:\n"));
5026 alvherre@alvh.no-ip. 398 : 1 : printf(_(" -D, --pgdata=DIRECTORY receive base backup into directory\n"));
399 : 1 : printf(_(" -F, --format=p|t output format (plain (default), tar)\n"));
861 michael@paquier.xyz 400 : 1 : printf(_(" -i, --incremental=OLDMANIFEST\n"
401 : : " take incremental backup\n"));
3275 tgl@sss.pgh.pa.us 402 : 1 : printf(_(" -r, --max-rate=RATE maximum transfer rate to transfer data directory\n"
403 : : " (in kB/s, or use suffix \"k\" or \"M\")\n"));
404 : 1 : printf(_(" -R, --write-recovery-conf\n"
405 : : " write configuration for replication\n"));
1485 peter@eisentraut.org 406 : 1 : printf(_(" -t, --target=TARGET[:DETAIL]\n"
407 : : " backup target (if other than client)\n"));
3275 tgl@sss.pgh.pa.us 408 : 1 : printf(_(" -T, --tablespace-mapping=OLDDIR=NEWDIR\n"
409 : : " relocate tablespace in OLDDIR to NEWDIR\n"));
3143 peter_e@gmx.net 410 : 1 : printf(_(" --waldir=WALDIR location for the write-ahead log directory\n"));
3275 tgl@sss.pgh.pa.us 411 : 1 : printf(_(" -X, --wal-method=none|fetch|stream\n"
412 : : " include required WAL files with specified method\n"));
5026 alvherre@alvh.no-ip. 413 : 1 : printf(_(" -z, --gzip compress tar output\n"));
1504 rhaas@postgresql.org 414 : 1 : printf(_(" -Z, --compress=[{client|server}-]METHOD[:DETAIL]\n"
415 : : " compress on client or server as specified\n"));
1520 416 : 1 : printf(_(" -Z, --compress=none do not compress tar output\n"));
5581 magnus@hagander.net 417 : 1 : printf(_("\nGeneral options:\n"));
3275 tgl@sss.pgh.pa.us 418 : 1 : printf(_(" -c, --checkpoint=fast|spread\n"
419 : : " set fast or spread (default) checkpointing\n"));
3143 peter_e@gmx.net 420 : 1 : printf(_(" -C, --create-slot create replication slot\n"));
5026 alvherre@alvh.no-ip. 421 : 1 : printf(_(" -l, --label=LABEL set backup label\n"));
3485 peter_e@gmx.net 422 : 1 : printf(_(" -n, --no-clean do not clean up after errors\n"));
423 : 1 : printf(_(" -N, --no-sync do not wait for changes to be written safely to disk\n"));
5026 alvherre@alvh.no-ip. 424 : 1 : printf(_(" -P, --progress show progress information\n"));
3143 peter_e@gmx.net 425 : 1 : printf(_(" -S, --slot=SLOTNAME replication slot to use\n"));
5026 alvherre@alvh.no-ip. 426 : 1 : printf(_(" -v, --verbose output verbose messages\n"));
427 : 1 : printf(_(" -V, --version output version information, then exit\n"));
2195 peter@eisentraut.org 428 : 1 : printf(_(" --manifest-checksums=SHA{224,256,384,512}|CRC32C|NONE\n"
429 : : " use algorithm for manifest checksums\n"));
430 : 1 : printf(_(" --manifest-force-encode\n"
431 : : " hex encode all file names in manifest\n"));
432 : 1 : printf(_(" --no-estimate-size do not estimate backup size in server side\n"));
433 : 1 : printf(_(" --no-manifest suppress generation of backup manifest\n"));
2906 peter_e@gmx.net 434 : 1 : printf(_(" --no-slot prevent creation of temporary replication slot\n"));
435 : 1 : printf(_(" --no-verify-checksums\n"
436 : : " do not verify checksums\n"));
972 nathan@postgresql.or 437 : 1 : printf(_(" --sync-method=METHOD\n"
438 : : " set method for syncing files to disk\n"));
5026 alvherre@alvh.no-ip. 439 : 1 : printf(_(" -?, --help show this help, then exit\n"));
5581 magnus@hagander.net 440 : 1 : printf(_("\nConnection options:\n"));
4817 heikki.linnakangas@i 441 : 1 : printf(_(" -d, --dbname=CONNSTR connection string\n"));
5026 alvherre@alvh.no-ip. 442 : 1 : printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
443 : 1 : printf(_(" -p, --port=PORT database server port number\n"));
3275 tgl@sss.pgh.pa.us 444 : 1 : printf(_(" -s, --status-interval=INTERVAL\n"
445 : : " time between status packets sent to server (in seconds)\n"));
5026 alvherre@alvh.no-ip. 446 : 1 : printf(_(" -U, --username=NAME connect as specified database user\n"));
447 : 1 : printf(_(" -w, --no-password never prompt for password\n"));
448 : 1 : printf(_(" -W, --password force password prompt (should happen automatically)\n"));
2258 peter@eisentraut.org 449 : 1 : printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
450 : 1 : printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
5581 magnus@hagander.net 451 : 1 : }
452 : :
453 : :
454 : : /*
455 : : * Called in the background process every time data is received.
456 : : * On Unix, we check to see if there is any data on our pipe
457 : : * (which would mean we have a stop position), and if it is, check if
458 : : * it is time to stop.
459 : : * On Windows, we are in a single process, so we can just check if it's
460 : : * time to stop.
461 : : */
462 : : static bool
5026 alvherre@alvh.no-ip. 463 : 3082 : reached_end_position(XLogRecPtr segendpos, uint32 timeline,
464 : : bool segment_finished)
465 : : {
5305 magnus@hagander.net 466 [ + + ]: 3082 : if (!has_xlogendptr)
467 : : {
468 : : #ifndef WIN32
469 : : fd_set fds;
1389 peter@eisentraut.org 470 : 2883 : struct timeval tv = {0};
471 : : int r;
472 : :
473 : : /*
474 : : * Don't have the end pointer yet - check our pipe to see if it has
475 : : * been sent yet.
476 : : */
5305 magnus@hagander.net 477 [ + + ]: 49011 : FD_ZERO(&fds);
478 : 2883 : FD_SET(bgpipe[0], &fds);
479 : :
480 : 2883 : r = select(bgpipe[0] + 1, &fds, NULL, NULL, &tv);
481 [ + + ]: 2883 : if (r == 1)
482 : : {
1389 peter@eisentraut.org 483 : 146 : char xlogend[64] = {0};
484 : : uint32 hi,
485 : : lo;
486 : :
4382 bruce@momjian.us 487 : 146 : r = read(bgpipe[0], xlogend, sizeof(xlogend) - 1);
5305 magnus@hagander.net 488 [ - + ]: 146 : if (r < 0)
1488 tgl@sss.pgh.pa.us 489 :UBC 0 : pg_fatal("could not read from ready pipe: %m");
490 : :
302 alvherre@kurilemu.de 491 [ - + ]:GNC 146 : if (sscanf(xlogend, "%X/%08X", &hi, &lo) != 2)
1488 tgl@sss.pgh.pa.us 492 :UBC 0 : pg_fatal("could not parse write-ahead log location \"%s\"",
493 : : xlogend);
5063 heikki.linnakangas@i 494 :CBC 146 : xlogendptr = ((uint64) hi) << 32 | lo;
5305 magnus@hagander.net 495 : 146 : has_xlogendptr = 1;
496 : :
497 : : /*
498 : : * Fall through to check if we've reached the point further
499 : : * already.
500 : : */
501 : : }
502 : : else
503 : : {
504 : : /*
505 : : * No data received on the pipe means we don't know the end
506 : : * position yet - so just say it's not time to stop yet.
507 : : */
508 : 2737 : return false;
509 : : }
510 : : #else
511 : :
512 : : /*
513 : : * On win32, has_xlogendptr is set by the main thread, so if it's not
514 : : * set here, we just go back and wait until it shows up.
515 : : */
516 : : return false;
517 : : #endif
518 : : }
519 : :
520 : : /*
521 : : * At this point we have an end pointer, so compare it to the current
522 : : * position to figure out if it's time to stop.
523 : : */
5063 heikki.linnakangas@i 524 [ + + ]: 345 : if (segendpos >= xlogendptr)
5305 magnus@hagander.net 525 : 292 : return true;
526 : :
527 : : /*
528 : : * Have end pointer, but haven't reached it yet - so tell the caller to
529 : : * keep streaming.
530 : : */
531 : 53 : return false;
532 : : }
533 : :
534 : : typedef struct
535 : : {
536 : : PGconn *bgconn;
537 : : XLogRecPtr startptr;
538 : : char xlog[MAXPGPATH]; /* directory or tarfile depending on mode */
539 : : char *sysidentifier;
540 : : int timeline;
541 : : pg_compress_algorithm wal_compress_algorithm;
542 : : int wal_compress_level;
543 : : } logstreamer_param;
544 : :
545 : : static int
1504 rhaas@postgresql.org 546 : 148 : LogStreamerMain(logstreamer_param *param)
547 : : {
1389 peter@eisentraut.org 548 : 148 : StreamCtl stream = {0};
549 : :
3522 peter_e@gmx.net 550 : 148 : in_log_streamer = true;
551 : :
3707 magnus@hagander.net 552 : 148 : stream.startpos = param->startptr;
553 : 148 : stream.timeline = param->timeline;
554 : 148 : stream.sysidentifier = param->sysidentifier;
555 : 148 : stream.stream_stop = reached_end_position;
556 : : #ifndef WIN32
3295 tgl@sss.pgh.pa.us 557 : 148 : stream.stop_socket = bgpipe[0];
558 : : #else
559 : : stream.stop_socket = PGINVALID_SOCKET;
560 : : #endif
3707 magnus@hagander.net 561 : 148 : stream.standby_message_timeout = standby_message_timeout;
562 : 148 : stream.synchronous = false;
563 : : /* fsync happens at the end of pg_basebackup for all data */
2435 michael@paquier.xyz 564 : 148 : stream.do_sync = false;
3707 magnus@hagander.net 565 : 148 : stream.mark_done = true;
566 : 148 : stream.partial_suffix = NULL;
3396 567 : 148 : stream.replication_slot = replication_slot;
3481 568 [ + + ]: 148 : if (format == 'p')
1643 michael@paquier.xyz 569 : 134 : stream.walmethod = CreateWalDirectoryMethod(param->xlog,
570 : : PG_COMPRESSION_NONE, 0,
2435 571 : 134 : stream.do_sync);
572 : : else
1544 rhaas@postgresql.org 573 : 14 : stream.walmethod = CreateWalTarMethod(param->xlog,
574 : : param->wal_compress_algorithm,
575 : : param->wal_compress_level,
576 : 14 : stream.do_sync);
577 : :
3707 magnus@hagander.net 578 [ + + ]: 148 : if (!ReceiveXlogStream(param->bgconn, &stream))
579 : : {
580 : : /*
581 : : * Any errors will already have been reported in the function process,
582 : : * but we need to tell the parent that we didn't shutdown in a nice
583 : : * way.
584 : : */
585 : : #ifdef WIN32
586 : : /*
587 : : * In order to signal the main thread of an ungraceful exit we set the
588 : : * same flag that we use on Unix to signal SIGCHLD.
589 : : */
590 : : bgchild_exited = true;
591 : : #endif
5305 592 : 2 : return 1;
593 : : }
594 : :
1324 rhaas@postgresql.org 595 [ - + ]: 146 : if (!stream.walmethod->ops->finish(stream.walmethod))
596 : : {
2591 peter@eisentraut.org 597 :UBC 0 : pg_log_error("could not finish writing WAL files: %m");
598 : : #ifdef WIN32
599 : : bgchild_exited = true;
600 : : #endif
3481 magnus@hagander.net 601 : 0 : return 1;
602 : : }
603 : :
5305 magnus@hagander.net 604 :CBC 146 : PQfinish(param->bgconn);
605 : :
1324 rhaas@postgresql.org 606 : 146 : stream.walmethod->ops->free(stream.walmethod);
607 : :
5305 magnus@hagander.net 608 : 146 : return 0;
609 : : }
610 : :
611 : : /*
612 : : * Initiate background process for receiving xlog during the backup.
613 : : * The background stream will use its own database connection so we can
614 : : * stream the logfile in parallel with the backups.
615 : : */
616 : : static void
1504 rhaas@postgresql.org 617 : 153 : StartLogStreamer(char *startpos, uint32 timeline, char *sysidentifier,
618 : : pg_compress_algorithm wal_compress_algorithm,
619 : : int wal_compress_level)
620 : : {
621 : : logstreamer_param *param;
622 : : uint32 hi,
623 : : lo;
624 : : char statusdir[MAXPGPATH];
625 : :
67 michael@paquier.xyz 626 :GNC 153 : param = pg_malloc0_object(logstreamer_param);
5305 magnus@hagander.net 627 :CBC 153 : param->timeline = timeline;
628 : 153 : param->sysidentifier = sysidentifier;
1484 michael@paquier.xyz 629 : 153 : param->wal_compress_algorithm = wal_compress_algorithm;
1504 rhaas@postgresql.org 630 : 153 : param->wal_compress_level = wal_compress_level;
631 : :
632 : : /* Convert the starting position */
302 alvherre@kurilemu.de 633 [ - + ]:GNC 153 : if (sscanf(startpos, "%X/%08X", &hi, &lo) != 2)
1488 tgl@sss.pgh.pa.us 634 :UBC 0 : pg_fatal("could not parse write-ahead log location \"%s\"",
635 : : startpos);
5063 heikki.linnakangas@i 636 :CBC 153 : param->startptr = ((uint64) hi) << 32 | lo;
637 : : /* Round off to even segment position */
3150 andres@anarazel.de 638 : 153 : param->startptr -= XLogSegmentOffset(param->startptr, WalSegSz);
639 : :
640 : : #ifndef WIN32
641 : : /* Create our background pipe */
5151 andrew@dunslane.net 642 [ - + ]: 153 : if (pipe(bgpipe) < 0)
1488 tgl@sss.pgh.pa.us 643 :UBC 0 : pg_fatal("could not create pipe for background process: %m");
644 : : #endif
645 : :
646 : : /* Get a second connection */
5305 magnus@hagander.net 647 :CBC 153 : param->bgconn = GetConnection();
5091 648 [ - + ]: 153 : if (!param->bgconn)
649 : : /* Error message already written in GetConnection() */
5091 magnus@hagander.net 650 :UBC 0 : exit(1);
651 : :
652 : : /* In post-10 cluster, pg_xlog has been renamed to pg_wal */
3481 magnus@hagander.net 653 [ - + ]:CBC 153 : snprintf(param->xlog, sizeof(param->xlog), "%s/%s",
654 : : basedir,
3484 rhaas@postgresql.org 655 : 153 : PQserverVersion(conn) < MINIMUM_VERSION_FOR_PG_WAL ?
656 : : "pg_xlog" : "pg_wal");
657 : :
658 : : /* Temporary replication slots are only supported in 10 and newer */
3396 magnus@hagander.net 659 [ - + ]: 153 : if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_TEMP_SLOTS)
3143 peter_e@gmx.net 660 :UBC 0 : temp_replication_slot = false;
661 : :
662 : : /*
663 : : * Create replication slot if requested
664 : : */
3143 peter_e@gmx.net 665 [ + + + - ]:CBC 153 : if (temp_replication_slot && !replication_slot)
971 michael@paquier.xyz 666 : 146 : replication_slot = psprintf("pg_basebackup_%u",
667 : 146 : (unsigned int) PQbackendPID(param->bgconn));
3143 peter_e@gmx.net 668 [ + + + + ]: 153 : if (temp_replication_slot || create_slot)
669 : : {
670 [ + + ]: 149 : if (!CreateReplicationSlot(param->bgconn, replication_slot, NULL,
671 : : temp_replication_slot, true, true, false,
672 : : false, false))
2684 peter@eisentraut.org 673 : 1 : exit(1);
674 : :
3143 peter_e@gmx.net 675 [ - + ]: 148 : if (verbose)
676 : : {
3143 peter_e@gmx.net 677 [ # # ]:UBC 0 : if (temp_replication_slot)
2591 peter@eisentraut.org 678 : 0 : pg_log_info("created temporary replication slot \"%s\"",
679 : : replication_slot);
680 : : else
681 : 0 : pg_log_info("created replication slot \"%s\"",
682 : : replication_slot);
683 : : }
684 : : }
685 : :
3481 magnus@hagander.net 686 [ + + ]:CBC 152 : if (format == 'p')
687 : : {
688 : : /*
689 : : * Create pg_wal/archive_status or pg_xlog/archive_status (and thus
690 : : * pg_wal or pg_xlog) depending on the target server so we can write
691 : : * to basedir/pg_wal or basedir/pg_xlog as the directory entry in the
692 : : * tar file may arrive later.
693 : : */
694 [ - + ]: 137 : snprintf(statusdir, sizeof(statusdir), "%s/%s/archive_status",
695 : : basedir,
696 : 137 : PQserverVersion(conn) < MINIMUM_VERSION_FOR_PG_WAL ?
697 : : "pg_xlog" : "pg_wal");
698 : :
2950 sfrost@snowman.net 699 [ - + - - ]: 137 : if (pg_mkdir_p(statusdir, pg_dir_create_mode) != 0 && errno != EEXIST)
1488 tgl@sss.pgh.pa.us 700 :UBC 0 : pg_fatal("could not create directory \"%s\": %m", statusdir);
701 : :
702 : : /*
703 : : * For newer server versions, likewise create pg_wal/summaries
704 : : */
821 michael@paquier.xyz 705 [ + - ]:CBC 137 : if (PQserverVersion(conn) >= MINIMUM_VERSION_FOR_WAL_SUMMARIES)
706 : : {
707 : : char summarydir[MAXPGPATH];
708 : :
867 rhaas@postgresql.org 709 : 137 : snprintf(summarydir, sizeof(summarydir), "%s/%s/summaries",
710 : : basedir, "pg_wal");
711 : :
845 712 [ - + ]: 137 : if (pg_mkdir_p(summarydir, pg_dir_create_mode) != 0 &&
867 rhaas@postgresql.org 713 [ # # ]:UBC 0 : errno != EEXIST)
714 : 0 : pg_fatal("could not create directory \"%s\": %m", summarydir);
715 : : }
716 : : }
717 : :
718 : : /*
719 : : * Start a child process and tell it to start streaming. On Unix, this is
720 : : * a fork(). On Windows, we create a thread.
721 : : */
722 : : #ifndef WIN32
5305 magnus@hagander.net 723 :CBC 152 : bgchild = fork();
724 [ + + ]: 300 : if (bgchild == 0)
725 : : {
726 : : /* in child process */
1400 andres@anarazel.de 727 : 148 : exit(LogStreamerMain(param));
728 : : }
5305 magnus@hagander.net 729 [ - + ]: 152 : else if (bgchild < 0)
1488 tgl@sss.pgh.pa.us 730 :UBC 0 : pg_fatal("could not create background process: %m");
731 : :
732 : : /*
733 : : * Else we are in the parent process and all is well.
734 : : */
2684 peter@eisentraut.org 735 :CBC 152 : atexit(kill_bgchild_atexit);
736 : : #else /* WIN32 */
737 : : bgchild = _beginthreadex(NULL, 0, (void *) LogStreamerMain, param, 0, NULL);
738 : : if (bgchild == 0)
739 : : pg_fatal("could not create background thread: %m");
740 : : #endif
5305 magnus@hagander.net 741 : 152 : }
742 : :
743 : : /*
744 : : * Verify that the given directory exists and is empty. If it does not
745 : : * exist, it is created. If it exists but is not empty, an error will
746 : : * be given and the process ended.
747 : : */
748 : : static void
3522 peter_e@gmx.net 749 : 220 : verify_dir_is_empty_or_create(char *dirname, bool *created, bool *found)
750 : : {
5581 magnus@hagander.net 751 [ + + + - : 220 : switch (pg_check_dir(dirname))
- ]
752 : : {
753 : 205 : case 0:
754 : :
755 : : /*
756 : : * Does not exist, so create
757 : : */
2950 sfrost@snowman.net 758 [ - + ]: 205 : if (pg_mkdir_p(dirname, pg_dir_create_mode) == -1)
1488 tgl@sss.pgh.pa.us 759 :UBC 0 : pg_fatal("could not create directory \"%s\": %m", dirname);
3522 peter_e@gmx.net 760 [ + - ]:CBC 205 : if (created)
761 : 205 : *created = true;
5581 magnus@hagander.net 762 : 205 : return;
763 : 14 : case 1:
764 : :
765 : : /*
766 : : * Exists, empty
767 : : */
3522 peter_e@gmx.net 768 [ + - ]: 14 : if (found)
769 : 14 : *found = true;
5581 magnus@hagander.net 770 : 14 : return;
771 : 1 : case 2:
772 : : case 3:
773 : : case 4:
774 : :
775 : : /*
776 : : * Exists, not empty
777 : : */
1488 tgl@sss.pgh.pa.us 778 : 1 : pg_fatal("directory \"%s\" exists but is not empty", dirname);
5581 magnus@hagander.net 779 :UBC 0 : case -1:
780 : :
781 : : /*
782 : : * Access problem
783 : : */
1488 tgl@sss.pgh.pa.us 784 : 0 : pg_fatal("could not access directory \"%s\": %m", dirname);
785 : : }
786 : : }
787 : :
788 : : /*
789 : : * Callback to update our notion of the current filename.
790 : : *
791 : : * No other code should modify progress_filename!
792 : : */
793 : : static void
1642 rhaas@postgresql.org 794 :CBC 161433 : progress_update_filename(const char *filename)
795 : : {
796 : : /* We needn't maintain this variable if not doing verbose reports. */
1538 tgl@sss.pgh.pa.us 797 [ - + - - ]: 161433 : if (showprogress && verbose)
798 : : {
1419 peter@eisentraut.org 799 :UBC 0 : free(progress_filename);
1538 tgl@sss.pgh.pa.us 800 [ # # ]: 0 : if (filename)
801 : 0 : progress_filename = pg_strdup(filename);
802 : : else
803 : 0 : progress_filename = NULL;
804 : : }
1642 rhaas@postgresql.org 805 :CBC 161433 : }
806 : :
807 : : /*
808 : : * Print a progress report based on the global variables. If verbose output
809 : : * is enabled, also print the current file name.
810 : : *
811 : : * Progress report is written at maximum once per second, unless the force
812 : : * parameter is set to true.
813 : : *
814 : : * If finished is set to true, this is the last progress report. The cursor
815 : : * is moved to the next line.
816 : : */
817 : : static void
818 : 258 : progress_report(int tablespacenum, bool force, bool finished)
819 : : {
820 : : int percent;
821 : : char totaldone_str[32];
822 : : char totalsize_str[32];
823 : : pg_time_t now;
824 : :
4468 magnus@hagander.net 825 [ + - ]: 258 : if (!showprogress)
826 : 258 : return;
827 : :
4468 magnus@hagander.net 828 :UBC 0 : now = time(NULL);
2087 heikki.linnakangas@i 829 [ # # # # : 0 : if (now == last_progress_report && !force && !finished)
# # ]
4382 bruce@momjian.us 830 : 0 : return; /* Max once per second */
831 : :
4468 magnus@hagander.net 832 : 0 : last_progress_report = now;
2436 peter@eisentraut.org 833 [ # # ]: 0 : percent = totalsize_kb ? (int) ((totaldone / 1024) * 100 / totalsize_kb) : 0;
834 : :
835 : : /*
836 : : * Avoid overflowing past 100% or the full size. This may make the total
837 : : * size number change as we approach the end of the backup (the estimate
838 : : * will always be wrong if WAL is included), but that's better than having
839 : : * the done column be bigger than the total.
840 : : */
5574 magnus@hagander.net 841 [ # # ]: 0 : if (percent > 100)
842 : 0 : percent = 100;
2436 peter@eisentraut.org 843 [ # # ]: 0 : if (totaldone / 1024 > totalsize_kb)
844 : 0 : totalsize_kb = totaldone / 1024;
845 : :
1693 846 : 0 : snprintf(totaldone_str, sizeof(totaldone_str), UINT64_FORMAT,
847 : : totaldone / 1024);
848 : 0 : snprintf(totalsize_str, sizeof(totalsize_str), UINT64_FORMAT, totalsize_kb);
849 : :
850 : : #define VERBOSE_FILENAME_LENGTH 35
5581 magnus@hagander.net 851 [ # # ]: 0 : if (verbose)
852 : : {
1642 rhaas@postgresql.org 853 [ # # ]: 0 : if (!progress_filename)
854 : :
855 : : /*
856 : : * No filename given, so clear the status line (used for last
857 : : * call)
858 : : */
5526 magnus@hagander.net 859 : 0 : fprintf(stderr,
4856 860 : 0 : ngettext("%*s/%s kB (100%%), %d/%d tablespace %*s",
861 : : "%*s/%s kB (100%%), %d/%d tablespaces %*s",
862 : : tablespacecount),
863 : 0 : (int) strlen(totalsize_str),
864 : : totaldone_str, totalsize_str,
865 : : tablespacenum, tablespacecount,
866 : : VERBOSE_FILENAME_LENGTH + 5, "");
867 : : else
868 : : {
1642 rhaas@postgresql.org 869 : 0 : bool truncate = (strlen(progress_filename) > VERBOSE_FILENAME_LENGTH);
870 : :
5526 magnus@hagander.net 871 [ # # # # : 0 : fprintf(stderr,
# # # # ]
4856 872 : 0 : ngettext("%*s/%s kB (%d%%), %d/%d tablespace (%s%-*.*s)",
873 : : "%*s/%s kB (%d%%), %d/%d tablespaces (%s%-*.*s)",
874 : : tablespacecount),
875 : 0 : (int) strlen(totalsize_str),
876 : : totaldone_str, totalsize_str, percent,
877 : : tablespacenum, tablespacecount,
878 : : /* Prefix with "..." if we do leading truncation */
879 : : truncate ? "..." : "",
880 : : truncate ? VERBOSE_FILENAME_LENGTH - 3 : VERBOSE_FILENAME_LENGTH,
881 : : truncate ? VERBOSE_FILENAME_LENGTH - 3 : VERBOSE_FILENAME_LENGTH,
882 : : /* Truncate filename at beginning if it's too long */
1642 rhaas@postgresql.org 883 : 0 : truncate ? progress_filename + strlen(progress_filename) - VERBOSE_FILENAME_LENGTH + 3 : progress_filename);
884 : : }
885 : : }
886 : : else
5376 peter_e@gmx.net 887 : 0 : fprintf(stderr,
4856 magnus@hagander.net 888 : 0 : ngettext("%*s/%s kB (%d%%), %d/%d tablespace",
889 : : "%*s/%s kB (%d%%), %d/%d tablespaces",
890 : : tablespacecount),
891 : 0 : (int) strlen(totalsize_str),
892 : : totaldone_str, totalsize_str, percent,
893 : : tablespacenum, tablespacecount);
894 : :
895 : : /*
896 : : * Stay on the same line if reporting to a terminal and we're not done
897 : : * yet.
898 : : */
2086 heikki.linnakangas@i 899 [ # # # # ]: 0 : fputc((!finished && isatty(fileno(stderr))) ? '\r' : '\n', stderr);
900 : : }
901 : :
902 : : static int32
4450 alvherre@alvh.no-ip. 903 :CBC 1 : parse_max_rate(char *src)
904 : : {
905 : : double result;
906 : : char *after_num;
4382 bruce@momjian.us 907 : 1 : char *suffix = NULL;
908 : :
4450 alvherre@alvh.no-ip. 909 : 1 : errno = 0;
910 : 1 : result = strtod(src, &after_num);
911 [ - + ]: 1 : if (src == after_num)
1488 tgl@sss.pgh.pa.us 912 :UBC 0 : pg_fatal("transfer rate \"%s\" is not a valid value", src);
4450 alvherre@alvh.no-ip. 913 [ - + ]:CBC 1 : if (errno != 0)
1488 tgl@sss.pgh.pa.us 914 :UBC 0 : pg_fatal("invalid transfer rate \"%s\": %m", src);
915 : :
4450 alvherre@alvh.no-ip. 916 [ - + ]:CBC 1 : if (result <= 0)
917 : : {
918 : : /*
919 : : * Reject obviously wrong values here.
920 : : */
1488 tgl@sss.pgh.pa.us 921 :UBC 0 : pg_fatal("transfer rate must be greater than zero");
922 : : }
923 : :
924 : : /*
925 : : * Evaluate suffix, after skipping over possible whitespace. Lack of
926 : : * suffix means kilobytes.
927 : : */
4450 alvherre@alvh.no-ip. 928 [ - + - - ]:CBC 1 : while (*after_num != '\0' && isspace((unsigned char) *after_num))
4450 alvherre@alvh.no-ip. 929 :UBC 0 : after_num++;
930 : :
4450 alvherre@alvh.no-ip. 931 [ - + ]:CBC 1 : if (*after_num != '\0')
932 : : {
4450 alvherre@alvh.no-ip. 933 :UBC 0 : suffix = after_num;
934 [ # # ]: 0 : if (*after_num == 'k')
935 : : {
936 : : /* kilobyte is the expected unit. */
937 : 0 : after_num++;
938 : : }
939 [ # # ]: 0 : else if (*after_num == 'M')
940 : : {
941 : 0 : after_num++;
942 : 0 : result *= 1024.0;
943 : : }
944 : : }
945 : :
946 : : /* The rest can only consist of white space. */
4450 alvherre@alvh.no-ip. 947 [ - + - - ]:CBC 1 : while (*after_num != '\0' && isspace((unsigned char) *after_num))
4450 alvherre@alvh.no-ip. 948 :UBC 0 : after_num++;
949 : :
4450 alvherre@alvh.no-ip. 950 [ - + ]:CBC 1 : if (*after_num != '\0')
1488 tgl@sss.pgh.pa.us 951 :UBC 0 : pg_fatal("invalid --max-rate unit: \"%s\"", suffix);
952 : :
953 : : /* Valid integer? */
4450 alvherre@alvh.no-ip. 954 [ - + ]:CBC 1 : if ((uint64) result != (uint64) ((uint32) result))
1488 tgl@sss.pgh.pa.us 955 :UBC 0 : pg_fatal("transfer rate \"%s\" exceeds integer range", src);
956 : :
957 : : /*
958 : : * The range is checked on the server side too, but avoid the server
959 : : * connection if a nonsensical value was passed.
960 : : */
4450 alvherre@alvh.no-ip. 961 [ + - - + ]:CBC 1 : if (result < MAX_RATE_LOWER || result > MAX_RATE_UPPER)
1488 tgl@sss.pgh.pa.us 962 :UBC 0 : pg_fatal("transfer rate \"%s\" is out of range", src);
963 : :
4450 alvherre@alvh.no-ip. 964 :CBC 1 : return (int32) result;
965 : : }
966 : :
967 : : /*
968 : : * Basic parsing of a value specified for -Z/--compress.
969 : : *
970 : : * We're not concerned here with understanding exactly what behavior the
971 : : * user wants, but we do need to know whether the user is requesting client
972 : : * or server side compression or leaving it unspecified, and we need to
973 : : * separate the name of the compression algorithm from the detail string.
974 : : *
975 : : * For instance, if the user writes --compress client-lz4:6, we want to
976 : : * separate that into (a) client-side compression, (b) algorithm "lz4",
977 : : * and (c) detail "6". Note, however, that all the client/server prefix is
978 : : * optional, and so is the detail. The algorithm name is required, unless
979 : : * the whole string is an integer, in which case we assume "gzip" as the
980 : : * algorithm and use the integer as the detail.
981 : : *
982 : : * We're not concerned with validation at this stage, so if the user writes
983 : : * --compress client-turkey:sandwich, the requested algorithm is "turkey"
984 : : * and the detail string is "sandwich". We'll sort out whether that's legal
985 : : * at a later stage.
986 : : */
987 : : static void
1252 michael@paquier.xyz 988 : 39 : backup_parse_compress_options(char *option, char **algorithm, char **detail,
989 : : CompressionLocation *locationres)
990 : : {
991 : : /*
992 : : * Strip off any "client-" or "server-" prefix, calculating the location.
993 : : */
1504 rhaas@postgresql.org 994 [ + + ]: 39 : if (strncmp(option, "server-", 7) == 0)
995 : : {
1562 996 : 19 : *locationres = COMPRESS_LOCATION_SERVER;
1504 997 : 19 : option += 7;
998 : : }
999 [ + + ]: 20 : else if (strncmp(option, "client-", 7) == 0)
1000 : : {
1544 1001 : 6 : *locationres = COMPRESS_LOCATION_CLIENT;
1504 1002 : 6 : option += 7;
1003 : : }
1004 : : else
1562 1005 : 14 : *locationres = COMPRESS_LOCATION_UNSPECIFIED;
1006 : :
1007 : : /* fallback to the common parsing for the algorithm and detail */
1252 michael@paquier.xyz 1008 : 39 : parse_compress_options(option, algorithm, detail);
1565 1009 : 39 : }
1010 : :
1011 : : /*
1012 : : * Read a stream of COPY data and invoke the provided callback for each
1013 : : * chunk.
1014 : : */
1015 : : static void
2343 rhaas@postgresql.org 1016 : 183 : ReceiveCopyData(PGconn *conn, WriteDataCallback callback,
1017 : : void *callback_data)
1018 : : {
1019 : : PGresult *res;
1020 : :
1021 : : /* Get the COPY data stream. */
1022 : 183 : res = PQgetResult(conn);
1023 [ - + ]: 183 : if (PQresultStatus(res) != PGRES_COPY_OUT)
1488 tgl@sss.pgh.pa.us 1024 :UBC 0 : pg_fatal("could not get COPY data stream: %s",
1025 : : PQerrorMessage(conn));
2343 rhaas@postgresql.org 1026 :CBC 183 : PQclear(res);
1027 : :
1028 : : /* Loop over chunks until done. */
1029 : : while (1)
1030 : 406764 : {
1031 : : int r;
1032 : : char *copybuf;
1033 : :
1034 : 406947 : r = PQgetCopyData(conn, ©buf, 0);
1035 [ + + ]: 406947 : if (r == -1)
1036 : : {
1037 : : /* End of chunk. */
1038 : 181 : break;
1039 : : }
1040 [ - + ]: 406766 : else if (r == -2)
1488 tgl@sss.pgh.pa.us 1041 :UBC 0 : pg_fatal("could not read COPY data: %s",
1042 : : PQerrorMessage(conn));
1043 : :
1532 dgustafsson@postgres 1044 [ + + ]:CBC 406766 : if (bgchild_exited)
1488 tgl@sss.pgh.pa.us 1045 : 2 : pg_fatal("background process terminated unexpectedly");
1046 : :
2343 rhaas@postgresql.org 1047 : 406764 : (*callback) (r, copybuf, callback_data);
1048 : :
1049 : 406764 : PQfreemem(copybuf);
1050 : : }
1051 : 181 : }
1052 : :
1053 : : /*
1054 : : * Figure out what to do with an archive received from the server based on
1055 : : * the options selected by the user. We may just write the results directly
1056 : : * to a file, or we might compress first, or we might extract the tar file
1057 : : * and write each member separately. This function doesn't do any of that
1058 : : * directly, but it works out what kind of astreamer we need to create so
1059 : : * that the right stuff happens when, down the road, we actually receive
1060 : : * the data.
1061 : : */
1062 : : static astreamer *
1642 1063 : 205 : CreateBackupStreamer(char *archive_name, char *spclocation,
1064 : : astreamer **manifest_inject_streamer_p,
1065 : : bool is_recovery_guc_supported,
1066 : : bool expect_unterminated_tarfile,
1067 : : pg_compress_specification *compress)
1068 : : {
638 1069 : 205 : astreamer *streamer = NULL;
1070 : 205 : astreamer *manifest_inject_streamer = NULL;
1071 : : bool inject_manifest;
1072 : : bool is_tar,
1073 : : is_compressed_tar;
1074 : : pg_compress_algorithm compressed_tar_algorithm;
1075 : : bool must_parse_archive;
1076 : :
1077 : : /*
1078 : : * Normally, we emit the backup manifest as a separate file, but when
1079 : : * we're writing a tarfile to stdout, we don't have that option, so
1080 : : * include it in the one tarfile we've got.
1081 : : */
1642 1082 [ + + - + : 205 : inject_manifest = (format == 't' && strcmp(basedir, "-") == 0 && manifest);
- - ]
1083 : :
1084 : : /* Check whether it is a tar archive and its compression type */
46 andrew@dunslane.net 1085 :GNC 205 : is_tar = parse_tar_compress_algorithm(archive_name,
1086 : : &compressed_tar_algorithm);
1087 : :
1088 : : /* Is this any kind of compressed tar? */
1089 [ + - ]: 410 : is_compressed_tar = (is_tar &&
1090 [ + + ]: 205 : compressed_tar_algorithm != PG_COMPRESSION_NONE);
1091 : :
1092 : : /*
1093 : : * Injecting the manifest into a compressed tar file would be possible if
1094 : : * we decompressed it, parsed the tarfile, generated a new tarfile, and
1095 : : * recompressed it, but compressing and decompressing multiple times just
1096 : : * to inject the manifest seems inefficient enough that it's probably not
1097 : : * what the user wants. So, instead, reject the request and tell the user
1098 : : * to specify something more reasonable.
1099 : : */
1516 rhaas@postgresql.org 1100 [ - + - - ]:CBC 205 : if (inject_manifest && is_compressed_tar)
1101 : : {
1319 peter@eisentraut.org 1102 :UBC 0 : pg_log_error("cannot inject manifest into a compressed tar file");
1103 : 0 : pg_log_error_hint("Use client-side compression, send the output to a directory rather than standard output, or use %s.",
1104 : : "--no-manifest");
1516 rhaas@postgresql.org 1105 : 0 : exit(1);
1106 : : }
1107 : :
1108 : : /*
1109 : : * We have to parse the archive if (1) we're suppose to extract it, or if
1110 : : * (2) we need to inject backup_manifest or recovery configuration into
1111 : : * it. However, we only know how to parse tar archives.
1112 : : */
1642 rhaas@postgresql.org 1113 [ + + + - :CBC 228 : must_parse_archive = (format == 'p' || inject_manifest ||
+ + ]
1454 tgl@sss.pgh.pa.us 1114 [ - + ]: 23 : (spclocation == NULL && writerecoveryconf));
1115 : :
1116 : : /* At present, we only know how to parse tar archives. */
46 andrew@dunslane.net 1117 [ + + - + ]:GNC 205 : if (must_parse_archive && !is_tar)
1118 : : {
1319 peter@eisentraut.org 1119 :UBC 0 : pg_log_error("cannot parse archive \"%s\"", archive_name);
1488 tgl@sss.pgh.pa.us 1120 : 0 : pg_log_error_detail("Only tar archives can be parsed.");
1562 rhaas@postgresql.org 1121 [ # # ]: 0 : if (format == 'p')
1488 tgl@sss.pgh.pa.us 1122 : 0 : pg_log_error_detail("Plain format requires pg_basebackup to parse the archive.");
1562 rhaas@postgresql.org 1123 [ # # ]: 0 : if (inject_manifest)
1488 tgl@sss.pgh.pa.us 1124 : 0 : pg_log_error_detail("Using - as the output directory requires pg_basebackup to parse the archive.");
1562 rhaas@postgresql.org 1125 [ # # ]: 0 : if (writerecoveryconf)
1488 tgl@sss.pgh.pa.us 1126 : 0 : pg_log_error_detail("The -R option requires pg_basebackup to parse the archive.");
1562 rhaas@postgresql.org 1127 : 0 : exit(1);
1128 : : }
1129 : :
1642 rhaas@postgresql.org 1130 [ + + ]:CBC 205 : if (format == 'p')
1131 : : {
1132 : : const char *directory;
1133 : :
1134 : : /*
1135 : : * In plain format, we must extract the archive. The data for the main
1136 : : * tablespace will be written to the base directory, and the data for
1137 : : * other tablespaces will be written to the directory where they're
1138 : : * located on the server, after applying any user-specified tablespace
1139 : : * mappings.
1140 : : *
1141 : : * In the case of an in-place tablespace, spclocation will be a
1142 : : * relative path. We just convert it to an absolute path by prepending
1143 : : * basedir.
1144 : : */
1113 1145 [ + + ]: 179 : if (spclocation == NULL)
1146 : 149 : directory = basedir;
1147 [ + + ]: 30 : else if (!is_absolute_path(spclocation))
1148 : 14 : directory = psprintf("%s/%s", basedir, spclocation);
1149 : : else
1150 : 16 : directory = get_tablespace_mapping(spclocation);
638 1151 : 179 : streamer = astreamer_extractor_new(directory,
1152 : : get_tablespace_mapping,
1153 : : progress_update_filename);
1154 : : }
1155 : : else
1156 : : {
1157 : : FILE *archive_file;
1158 : : char archive_filename[MAXPGPATH];
1159 : :
1160 : : /*
1161 : : * In tar format, we just write the archive without extracting it.
1162 : : * Normally, we write it to the archive name provided by the caller,
1163 : : * but when the base directory is "-" that means we need to write to
1164 : : * standard output.
1165 : : */
1642 1166 [ - + ]: 26 : if (strcmp(basedir, "-") == 0)
1167 : : {
1642 rhaas@postgresql.org 1168 :UBC 0 : snprintf(archive_filename, sizeof(archive_filename), "-");
1169 : 0 : archive_file = stdout;
1170 : : }
1171 : : else
1172 : : {
1642 rhaas@postgresql.org 1173 :CBC 26 : snprintf(archive_filename, sizeof(archive_filename),
1174 : : "%s/%s", basedir, archive_name);
1175 : 26 : archive_file = NULL;
1176 : : }
1177 : :
1484 michael@paquier.xyz 1178 [ + + ]: 26 : if (compress->algorithm == PG_COMPRESSION_NONE)
638 rhaas@postgresql.org 1179 : 17 : streamer = astreamer_plain_writer_new(archive_filename,
1180 : : archive_file);
1484 michael@paquier.xyz 1181 [ + + ]: 9 : else if (compress->algorithm == PG_COMPRESSION_GZIP)
1182 : : {
1642 rhaas@postgresql.org 1183 : 4 : strlcat(archive_filename, ".gz", sizeof(archive_filename));
638 1184 : 4 : streamer = astreamer_gzip_writer_new(archive_filename,
1185 : : archive_file, compress);
1186 : : }
1484 michael@paquier.xyz 1187 [ + + ]: 5 : else if (compress->algorithm == PG_COMPRESSION_LZ4)
1188 : : {
1544 rhaas@postgresql.org 1189 : 2 : strlcat(archive_filename, ".lz4", sizeof(archive_filename));
638 1190 : 2 : streamer = astreamer_plain_writer_new(archive_filename,
1191 : : archive_file);
1192 : 2 : streamer = astreamer_lz4_compressor_new(streamer, compress);
1193 : : }
1484 michael@paquier.xyz 1194 [ + - ]: 3 : else if (compress->algorithm == PG_COMPRESSION_ZSTD)
1195 : : {
1520 rhaas@postgresql.org 1196 : 3 : strlcat(archive_filename, ".zst", sizeof(archive_filename));
638 1197 : 3 : streamer = astreamer_plain_writer_new(archive_filename,
1198 : : archive_file);
1199 : 3 : streamer = astreamer_zstd_compressor_new(streamer, compress);
1200 : : }
1201 : : else
1202 : : {
1565 michael@paquier.xyz 1203 :UBC 0 : Assert(false); /* not reachable */
1204 : : }
1205 : :
1206 : : /*
1207 : : * If we need to parse the archive for whatever reason, then we'll
1208 : : * also need to re-archive, because, if the output format is tar, the
1209 : : * only point of parsing the archive is to be able to inject stuff
1210 : : * into it.
1211 : : */
1642 rhaas@postgresql.org 1212 [ - + ]:CBC 26 : if (must_parse_archive)
638 rhaas@postgresql.org 1213 :UBC 0 : streamer = astreamer_tar_archiver_new(streamer);
1538 tgl@sss.pgh.pa.us 1214 :CBC 26 : progress_update_filename(archive_filename);
1215 : : }
1216 : :
1217 : : /*
1218 : : * If we're supposed to inject the backup manifest into the results, it
1219 : : * should be done here, so that the file content can be injected directly,
1220 : : * without worrying about the details of the tar format.
1221 : : */
1642 rhaas@postgresql.org 1222 [ - + ]: 205 : if (inject_manifest)
1642 rhaas@postgresql.org 1223 :UBC 0 : manifest_inject_streamer = streamer;
1224 : :
1225 : : /*
1226 : : * If this is the main tablespace and we're supposed to write recovery
1227 : : * information, arrange to do that.
1228 : : */
1642 rhaas@postgresql.org 1229 [ + + + + ]:CBC 205 : if (spclocation == NULL && writerecoveryconf)
1230 : : {
1231 [ - + ]: 4 : Assert(must_parse_archive);
638 1232 : 4 : streamer = astreamer_recovery_injector_new(streamer,
1233 : : is_recovery_guc_supported,
1234 : : recoveryconfcontents);
1235 : : }
1236 : :
1237 : : /*
1238 : : * If we're doing anything that involves understanding the contents of the
1239 : : * archive, we'll need to parse it. If not, we can skip parsing it, but
1240 : : * old versions of the server send improperly terminated tarfiles, so if
1241 : : * we're talking to such a server we'll need to add the terminator here.
1242 : : */
1642 1243 [ + + ]: 205 : if (must_parse_archive)
638 1244 : 179 : streamer = astreamer_tar_parser_new(streamer);
1638 1245 [ - + ]: 26 : else if (expect_unterminated_tarfile)
638 rhaas@postgresql.org 1246 :UBC 0 : streamer = astreamer_tar_terminator_new(streamer);
1247 : :
1248 : : /*
1249 : : * If the user has requested a server compressed archive along with
1250 : : * archive extraction at client then we need to decompress it.
1251 : : */
46 andrew@dunslane.net 1252 [ + + + + ]:GNC 205 : if (format == 'p' && is_compressed_tar)
1253 : : {
1254 [ + + ]: 4 : if (compressed_tar_algorithm == PG_COMPRESSION_GZIP)
638 rhaas@postgresql.org 1255 :CBC 1 : streamer = astreamer_gzip_decompressor_new(streamer);
46 andrew@dunslane.net 1256 [ + + ]:GNC 3 : else if (compressed_tar_algorithm == PG_COMPRESSION_LZ4)
638 rhaas@postgresql.org 1257 :CBC 1 : streamer = astreamer_lz4_decompressor_new(streamer);
46 andrew@dunslane.net 1258 [ + - ]:GNC 2 : else if (compressed_tar_algorithm == PG_COMPRESSION_ZSTD)
638 rhaas@postgresql.org 1259 :CBC 2 : streamer = astreamer_zstd_decompressor_new(streamer);
1260 : : }
1261 : :
1262 : : /* Return the results. */
1642 1263 : 205 : *manifest_inject_streamer_p = manifest_inject_streamer;
1264 : 205 : return streamer;
1265 : : }
1266 : :
1267 : : /*
1268 : : * Receive all of the archives the server wants to send - and the backup
1269 : : * manifest if present - as a single COPY stream.
1270 : : */
1271 : : static void
1484 michael@paquier.xyz 1272 : 183 : ReceiveArchiveStream(PGconn *conn, pg_compress_specification *compress)
1273 : : {
1274 : : ArchiveStreamState state;
1275 : :
1276 : : /* Set up initial state. */
1568 rhaas@postgresql.org 1277 : 183 : memset(&state, 0, sizeof(state));
1278 : 183 : state.tablespacenum = -1;
1504 1279 : 183 : state.compress = compress;
1280 : :
1281 : : /* All the real work happens in ReceiveArchiveStreamChunk. */
1568 1282 : 183 : ReceiveCopyData(conn, ReceiveArchiveStreamChunk, &state);
1283 : :
1284 : : /* If we wrote the backup manifest to a file, close the file. */
1285 [ + + ]: 181 : if (state.manifest_file !=NULL)
1286 : : {
1287 : 168 : fclose(state.manifest_file);
1288 : 168 : state.manifest_file = NULL;
1289 : : }
1290 : :
1291 : : /*
1292 : : * If we buffered the backup manifest in order to inject it into the
1293 : : * output tarfile, do that now.
1294 : : */
1295 [ - + ]: 181 : if (state.manifest_inject_streamer != NULL &&
1568 rhaas@postgresql.org 1296 [ # # ]:UBC 0 : state.manifest_buffer != NULL)
1297 : : {
638 1298 : 0 : astreamer_inject_file(state.manifest_inject_streamer,
1299 : : "backup_manifest",
1300 : 0 : state.manifest_buffer->data,
1301 : 0 : state.manifest_buffer->len);
1568 1302 : 0 : destroyPQExpBuffer(state.manifest_buffer);
1303 : 0 : state.manifest_buffer = NULL;
1304 : : }
1305 : :
1306 : : /* If there's still an archive in progress, end processing. */
1568 rhaas@postgresql.org 1307 [ + + ]:CBC 181 : if (state.streamer != NULL)
1308 : : {
638 1309 : 170 : astreamer_finalize(state.streamer);
1310 : 170 : astreamer_free(state.streamer);
1568 1311 : 170 : state.streamer = NULL;
1312 : : }
1313 : 181 : }
1314 : :
1315 : : /*
1316 : : * Receive one chunk of data sent by the server as part of a single COPY
1317 : : * stream that includes all archives and the manifest.
1318 : : */
1319 : : static void
1320 : 406764 : ReceiveArchiveStreamChunk(size_t r, char *copybuf, void *callback_data)
1321 : : {
1322 : 406764 : ArchiveStreamState *state = callback_data;
1323 : 406764 : size_t cursor = 0;
1324 : :
1325 : : /* Each CopyData message begins with a type byte. */
1326 [ + + + + : 406764 : switch (GetCopyDataByte(r, copybuf, &cursor))
- ]
1327 : : {
272 nathan@postgresql.or 1328 :GNC 222 : case PqBackupMsg_NewArchive:
1329 : : {
1330 : : /* New archive. */
1331 : : char *archive_name;
1332 : : char *spclocation;
1333 : :
1334 : : /*
1335 : : * We force a progress report at the end of each tablespace. A
1336 : : * new tablespace starts when the previous one ends, except in
1337 : : * the case of the very first one.
1338 : : */
1568 rhaas@postgresql.org 1339 [ + + ]:CBC 222 : if (++state->tablespacenum > 0)
1340 : 39 : progress_report(state->tablespacenum, true, false);
1341 : :
1342 : : /* Sanity check. */
1343 [ + - ]: 222 : if (state->manifest_buffer != NULL ||
1344 [ - + ]: 222 : state->manifest_file !=NULL)
1319 peter@eisentraut.org 1345 :UBC 0 : pg_fatal("archives must precede manifest");
1346 : :
1347 : : /* Parse the rest of the CopyData message. */
1568 rhaas@postgresql.org 1348 :CBC 222 : archive_name = GetCopyDataString(r, copybuf, &cursor);
1349 : 222 : spclocation = GetCopyDataString(r, copybuf, &cursor);
1350 : 222 : GetCopyDataEnd(r, copybuf, cursor);
1351 : :
1352 : : /*
1353 : : * Basic sanity checks on the archive name: it shouldn't be
1354 : : * empty, it shouldn't start with a dot, and it shouldn't
1355 : : * contain a path separator.
1356 : : */
1357 [ + - + - ]: 222 : if (archive_name[0] == '\0' || archive_name[0] == '.' ||
1358 [ + - ]: 222 : strchr(archive_name, '/') != NULL ||
1359 [ - + ]: 222 : strchr(archive_name, '\\') != NULL)
1488 tgl@sss.pgh.pa.us 1360 :UBC 0 : pg_fatal("invalid archive name: \"%s\"",
1361 : : archive_name);
1362 : :
1363 : : /*
1364 : : * An empty spclocation is treated as NULL. We expect this
1365 : : * case to occur for the data directory itself, but not for
1366 : : * any archives that correspond to tablespaces.
1367 : : */
1568 rhaas@postgresql.org 1368 [ + + ]:CBC 222 : if (spclocation[0] == '\0')
1369 : 183 : spclocation = NULL;
1370 : :
1371 : : /* End processing of any prior archive. */
1372 [ + + ]: 222 : if (state->streamer != NULL)
1373 : : {
638 1374 : 33 : astreamer_finalize(state->streamer);
1375 : 33 : astreamer_free(state->streamer);
1568 1376 : 33 : state->streamer = NULL;
1377 : : }
1378 : :
1379 : : /*
1380 : : * Create an appropriate backup streamer, unless a backup
1381 : : * target was specified. In that case, it's up to the server
1382 : : * to put the backup wherever it needs to go.
1383 : : */
1631 1384 [ + + ]: 222 : if (backup_target == NULL)
1385 : : {
1386 : : /*
1387 : : * We know that recovery GUCs are supported, because this
1388 : : * protocol can only be used on v15+.
1389 : : */
1390 : 205 : state->streamer =
1391 : 205 : CreateBackupStreamer(archive_name,
1392 : : spclocation,
1393 : : &state->manifest_inject_streamer,
1394 : : true, false,
1395 : : state->compress);
1396 : : }
1568 1397 : 222 : break;
1398 : : }
1399 : :
272 nathan@postgresql.or 1400 :GNC 406144 : case PqMsg_CopyData:
1401 : : {
1402 : : /* Archive or manifest data. */
1568 rhaas@postgresql.org 1403 [ - + ]:CBC 406144 : if (state->manifest_buffer != NULL)
1404 : : {
1405 : : /* Manifest data, buffer in memory. */
1568 rhaas@postgresql.org 1406 :UBC 0 : appendPQExpBuffer(state->manifest_buffer, copybuf + 1,
1407 : : r - 1);
1408 : : }
1568 rhaas@postgresql.org 1409 [ + + ]:CBC 406144 : else if (state->manifest_file !=NULL)
1410 : : {
1411 : : /* Manifest data, write to disk. */
1412 [ - + ]: 883 : if (fwrite(copybuf + 1, r - 1, 1,
1413 : : state->manifest_file) != 1)
1414 : : {
1415 : : /*
1416 : : * If fwrite() didn't set errno, assume that the
1417 : : * problem is that we're out of disk space.
1418 : : */
1568 rhaas@postgresql.org 1419 [ # # ]:UBC 0 : if (errno == 0)
1420 : 0 : errno = ENOSPC;
1488 tgl@sss.pgh.pa.us 1421 : 0 : pg_fatal("could not write to file \"%s\": %m",
1422 : : state->manifest_filename);
1423 : : }
1424 : : }
1568 rhaas@postgresql.org 1425 [ + - ]:CBC 405261 : else if (state->streamer != NULL)
1426 : : {
1427 : : /* Archive data. */
638 1428 : 405261 : astreamer_content(state->streamer, NULL, copybuf + 1,
1429 : 405261 : r - 1, ASTREAMER_UNKNOWN);
1430 : : }
1431 : : else
1488 tgl@sss.pgh.pa.us 1432 :UBC 0 : pg_fatal("unexpected payload data");
1568 rhaas@postgresql.org 1433 :CBC 406144 : break;
1434 : : }
1435 : :
272 nathan@postgresql.or 1436 :GNC 219 : case PqBackupMsg_ProgressReport:
1437 : : {
1438 : : /*
1439 : : * Progress report.
1440 : : *
1441 : : * The remainder of the message is expected to be an 8-byte
1442 : : * count of bytes completed.
1443 : : */
1568 rhaas@postgresql.org 1444 :CBC 219 : totaldone = GetCopyDataUInt64(r, copybuf, &cursor);
1445 : 219 : GetCopyDataEnd(r, copybuf, cursor);
1446 : :
1447 : : /*
1448 : : * The server shouldn't send progress report messages too
1449 : : * often, so we force an update each time we receive one.
1450 : : */
1451 : 219 : progress_report(state->tablespacenum, true, false);
1452 : 219 : break;
1453 : : }
1454 : :
272 nathan@postgresql.or 1455 :GNC 179 : case PqBackupMsg_Manifest:
1456 : : {
1457 : : /*
1458 : : * Manifest data will be sent next. This message is not
1459 : : * expected to have any further payload data.
1460 : : */
1568 rhaas@postgresql.org 1461 :CBC 179 : GetCopyDataEnd(r, copybuf, cursor);
1462 : :
1463 : : /*
1464 : : * If a backup target was specified, figuring out where to put
1465 : : * the manifest is the server's problem. Otherwise, we need to
1466 : : * deal with it.
1467 : : */
1631 1468 [ + + ]: 179 : if (backup_target == NULL)
1469 : : {
1470 : : /*
1471 : : * If we're supposed inject the manifest into the archive,
1472 : : * we prepare to buffer it in memory; otherwise, we
1473 : : * prepare to write it to a temporary file.
1474 : : */
1475 [ - + ]: 168 : if (state->manifest_inject_streamer != NULL)
1631 rhaas@postgresql.org 1476 :UBC 0 : state->manifest_buffer = createPQExpBuffer();
1477 : : else
1478 : : {
1631 rhaas@postgresql.org 1479 :CBC 168 : snprintf(state->manifest_filename,
1480 : : sizeof(state->manifest_filename),
1481 : : "%s/backup_manifest.tmp", basedir);
1482 : 168 : state->manifest_file =
1483 : 168 : fopen(state->manifest_filename, "wb");
1484 [ - + ]: 168 : if (state->manifest_file == NULL)
1488 tgl@sss.pgh.pa.us 1485 :UBC 0 : pg_fatal("could not create file \"%s\": %m",
1486 : : state->manifest_filename);
1487 : : }
1488 : : }
1568 rhaas@postgresql.org 1489 :CBC 179 : break;
1490 : : }
1491 : :
1568 rhaas@postgresql.org 1492 :UBC 0 : default:
1493 : 0 : ReportCopyDataParseError(r, copybuf);
1494 : 0 : break;
1495 : : }
1568 rhaas@postgresql.org 1496 :CBC 406764 : }
1497 : :
1498 : : /*
1499 : : * Get a single byte from a CopyData message.
1500 : : *
1501 : : * Bail out if none remain.
1502 : : */
1503 : : static char
1504 : 406764 : GetCopyDataByte(size_t r, char *copybuf, size_t *cursor)
1505 : : {
1506 [ - + ]: 406764 : if (*cursor >= r)
1568 rhaas@postgresql.org 1507 :UBC 0 : ReportCopyDataParseError(r, copybuf);
1508 : :
1568 rhaas@postgresql.org 1509 :CBC 406764 : return copybuf[(*cursor)++];
1510 : : }
1511 : :
1512 : : /*
1513 : : * Get a NUL-terminated string from a CopyData message.
1514 : : *
1515 : : * Bail out if the terminating NUL cannot be found.
1516 : : */
1517 : : static char *
1518 : 444 : GetCopyDataString(size_t r, char *copybuf, size_t *cursor)
1519 : : {
1520 : 444 : size_t startpos = *cursor;
1521 : 444 : size_t endpos = startpos;
1522 : :
1523 : : while (1)
1524 : : {
1525 [ - + ]: 3075 : if (endpos >= r)
1568 rhaas@postgresql.org 1526 :UBC 0 : ReportCopyDataParseError(r, copybuf);
1568 rhaas@postgresql.org 1527 [ + + ]:CBC 3075 : if (copybuf[endpos] == '\0')
1528 : 444 : break;
1529 : 2631 : ++endpos;
1530 : : }
1531 : :
1532 : 444 : *cursor = endpos + 1;
1533 : 444 : return ©buf[startpos];
1534 : : }
1535 : :
1536 : : /*
1537 : : * Get an unsigned 64-bit integer from a CopyData message.
1538 : : *
1539 : : * Bail out if there are not at least 8 bytes remaining.
1540 : : */
1541 : : static uint64
1542 : 219 : GetCopyDataUInt64(size_t r, char *copybuf, size_t *cursor)
1543 : : {
1544 : : uint64 result;
1545 : :
1546 [ - + ]: 219 : if (*cursor + sizeof(uint64) > r)
1568 rhaas@postgresql.org 1547 :UBC 0 : ReportCopyDataParseError(r, copybuf);
1568 rhaas@postgresql.org 1548 :CBC 219 : memcpy(&result, ©buf[*cursor], sizeof(uint64));
1549 : 219 : *cursor += sizeof(uint64);
1550 : 219 : return pg_ntoh64(result);
1551 : : }
1552 : :
1553 : : /*
1554 : : * Bail out if we didn't parse the whole message.
1555 : : */
1556 : : static void
1557 : 620 : GetCopyDataEnd(size_t r, char *copybuf, size_t cursor)
1558 : : {
1559 [ - + ]: 620 : if (r != cursor)
1568 rhaas@postgresql.org 1560 :UBC 0 : ReportCopyDataParseError(r, copybuf);
1568 rhaas@postgresql.org 1561 :CBC 620 : }
1562 : :
1563 : : /*
1564 : : * Report failure to parse a CopyData message from the server. Then exit.
1565 : : *
1566 : : * As a debugging aid, we try to give some hint about what kind of message
1567 : : * provoked the failure. Perhaps this is not detailed enough, but it's not
1568 : : * clear that it's worth expending any more code on what should be a
1569 : : * can't-happen case.
1570 : : */
1571 : : static void
1568 rhaas@postgresql.org 1572 :UBC 0 : ReportCopyDataParseError(size_t r, char *copybuf)
1573 : : {
1574 [ # # ]: 0 : if (r == 0)
1488 tgl@sss.pgh.pa.us 1575 : 0 : pg_fatal("empty COPY message");
1576 : : else
1577 : 0 : pg_fatal("malformed COPY message of type %d, length %zu",
1578 : : copybuf[0], r);
1579 : : }
1580 : :
1581 : : /*
1582 : : * Receive raw tar data from the server, and stream it to the appropriate
1583 : : * location. If we're writing a single tarfile to standard output, also
1584 : : * receive the backup manifest and inject it into that tarfile.
1585 : : */
1586 : : static void
1642 rhaas@postgresql.org 1587 : 0 : ReceiveTarFile(PGconn *conn, char *archive_name, char *spclocation,
1588 : : bool tablespacenum, pg_compress_specification *compress)
1589 : : {
1590 : : WriteTarState state;
1591 : : astreamer *manifest_inject_streamer;
1592 : : bool is_recovery_guc_supported;
1593 : : bool expect_unterminated_tarfile;
1594 : :
1595 : : /* Pass all COPY data through to the backup streamer. */
1596 : 0 : memset(&state, 0, sizeof(state));
1597 : 0 : is_recovery_guc_supported =
1598 : 0 : PQserverVersion(conn) >= MINIMUM_VERSION_FOR_RECOVERY_GUC;
1638 1599 : 0 : expect_unterminated_tarfile =
1600 : 0 : PQserverVersion(conn) < MINIMUM_VERSION_FOR_TERMINATED_TARFILE;
1642 1601 : 0 : state.streamer = CreateBackupStreamer(archive_name, spclocation,
1602 : : &manifest_inject_streamer,
1603 : : is_recovery_guc_supported,
1604 : : expect_unterminated_tarfile,
1605 : : compress);
1606 : 0 : state.tablespacenum = tablespacenum;
1607 : 0 : ReceiveCopyData(conn, ReceiveTarCopyChunk, &state);
1538 tgl@sss.pgh.pa.us 1608 : 0 : progress_update_filename(NULL);
1609 : :
1610 : : /*
1611 : : * The decision as to whether we need to inject the backup manifest into
1612 : : * the output at this stage is made by CreateBackupStreamer; if that is
1613 : : * needed, manifest_inject_streamer will be non-NULL; otherwise, it will
1614 : : * be NULL.
1615 : : */
1642 rhaas@postgresql.org 1616 [ # # ]: 0 : if (manifest_inject_streamer != NULL)
1617 : : {
1618 : : PQExpBufferData buf;
1619 : :
1620 : : /* Slurp the entire backup manifest into a buffer. */
2223 1621 : 0 : initPQExpBuffer(&buf);
1622 : 0 : ReceiveBackupManifestInMemory(conn, &buf);
1623 [ # # ]: 0 : if (PQExpBufferDataBroken(buf))
1488 tgl@sss.pgh.pa.us 1624 : 0 : pg_fatal("out of memory");
1625 : :
1626 : : /* Inject it into the output tarfile. */
638 rhaas@postgresql.org 1627 : 0 : astreamer_inject_file(manifest_inject_streamer, "backup_manifest",
1628 : 0 : buf.data, buf.len);
1629 : :
1630 : : /* Free memory. */
1642 1631 : 0 : termPQExpBuffer(&buf);
1632 : : }
1633 : :
1634 : : /* Cleanup. */
638 1635 : 0 : astreamer_finalize(state.streamer);
1636 : 0 : astreamer_free(state.streamer);
1637 : :
1642 1638 : 0 : progress_report(tablespacenum, true, false);
1639 : :
1640 : : /*
1641 : : * Do not sync the resulting tar file yet, all files are synced once at
1642 : : * the end.
1643 : : */
2343 1644 : 0 : }
1645 : :
1646 : : /*
1647 : : * Receive one chunk of tar-format data from the server.
1648 : : */
1649 : : static void
1650 : 0 : ReceiveTarCopyChunk(size_t r, char *copybuf, void *callback_data)
1651 : : {
1652 : 0 : WriteTarState *state = callback_data;
1653 : :
638 1654 : 0 : astreamer_content(state->streamer, NULL, copybuf, r, ASTREAMER_UNKNOWN);
1655 : :
2343 1656 : 0 : totaldone += r;
1642 1657 : 0 : progress_report(state->tablespacenum, false, false);
5581 magnus@hagander.net 1658 : 0 : }
1659 : :
1660 : :
1661 : : /*
1662 : : * Retrieve tablespace path, either relocated or original depending on whether
1663 : : * -T was passed or not.
1664 : : */
1665 : : static const char *
4455 peter_e@gmx.net 1666 :CBC 49 : get_tablespace_mapping(const char *dir)
1667 : : {
1668 : : TablespaceListCell *cell;
1669 : : char canon_dir[MAXPGPATH];
1670 : :
1671 : : /* Canonicalize path for comparison consistency */
3107 1672 : 49 : strlcpy(canon_dir, dir, sizeof(canon_dir));
1673 : 49 : canonicalize_path(canon_dir);
1674 : :
4455 1675 [ + + ]: 49 : for (cell = tablespace_dirs.head; cell; cell = cell->next)
3107 1676 [ + - ]: 48 : if (strcmp(canon_dir, cell->old_dir) == 0)
4455 1677 : 48 : return cell->new_dir;
1678 : :
1679 : 1 : return dir;
1680 : : }
1681 : :
1682 : : /*
1683 : : * Receive the backup manifest file and write it out to a file.
1684 : : */
1685 : : static void
2223 rhaas@postgresql.org 1686 :UBC 0 : ReceiveBackupManifest(PGconn *conn)
1687 : : {
1688 : : WriteManifestState state;
1689 : :
1690 : 0 : snprintf(state.filename, sizeof(state.filename),
1691 : : "%s/backup_manifest.tmp", basedir);
1692 : 0 : state.file = fopen(state.filename, "wb");
1693 [ # # ]: 0 : if (state.file == NULL)
1488 tgl@sss.pgh.pa.us 1694 : 0 : pg_fatal("could not create file \"%s\": %m", state.filename);
1695 : :
2223 rhaas@postgresql.org 1696 : 0 : ReceiveCopyData(conn, ReceiveBackupManifestChunk, &state);
1697 : :
1698 : 0 : fclose(state.file);
1699 : 0 : }
1700 : :
1701 : : /*
1702 : : * Receive one chunk of the backup manifest file and write it out to a file.
1703 : : */
1704 : : static void
1705 : 0 : ReceiveBackupManifestChunk(size_t r, char *copybuf, void *callback_data)
1706 : : {
1707 : 0 : WriteManifestState *state = callback_data;
1708 : :
2146 alvherre@alvh.no-ip. 1709 : 0 : errno = 0;
2223 rhaas@postgresql.org 1710 [ # # ]: 0 : if (fwrite(copybuf, r, 1, state->file) != 1)
1711 : : {
1712 : : /* if write didn't set errno, assume problem is no disk space */
2146 alvherre@alvh.no-ip. 1713 [ # # ]: 0 : if (errno == 0)
1714 : 0 : errno = ENOSPC;
1488 tgl@sss.pgh.pa.us 1715 : 0 : pg_fatal("could not write to file \"%s\": %m", state->filename);
1716 : : }
2223 rhaas@postgresql.org 1717 : 0 : }
1718 : :
1719 : : /*
1720 : : * Receive the backup manifest file and write it out to a file.
1721 : : */
1722 : : static void
1723 : 0 : ReceiveBackupManifestInMemory(PGconn *conn, PQExpBuffer buf)
1724 : : {
1725 : 0 : ReceiveCopyData(conn, ReceiveBackupManifestInMemoryChunk, buf);
1726 : 0 : }
1727 : :
1728 : : /*
1729 : : * Receive one chunk of the backup manifest file and write it out to a file.
1730 : : */
1731 : : static void
1732 : 0 : ReceiveBackupManifestInMemoryChunk(size_t r, char *copybuf,
1733 : : void *callback_data)
1734 : : {
1735 : 0 : PQExpBuffer buf = callback_data;
1736 : :
1737 : 0 : appendPQExpBuffer(buf, copybuf, r);
1738 : 0 : }
1739 : :
1740 : : static void
1504 rhaas@postgresql.org 1741 :CBC 204 : BaseBackup(char *compression_algorithm, char *compression_detail,
1742 : : CompressionLocation compressloc,
1743 : : pg_compress_specification *client_compress,
1744 : : char *incremental_manifest)
1745 : : {
1746 : : PGresult *res;
1747 : : char *sysidentifier;
1748 : : TimeLineID latesttli;
1749 : : TimeLineID starttli;
1750 : : char *basebkp;
1751 : : int i;
1752 : : char xlogstart[64];
1389 peter@eisentraut.org 1753 : 204 : char xlogend[64] = {0};
1754 : : int minServerMajor,
1755 : : maxServerMajor;
1756 : : int serverVersion,
1757 : : serverMajor;
1758 : : int writing_to_stdout;
1673 rhaas@postgresql.org 1759 : 204 : bool use_new_option_syntax = false;
1760 : : PQExpBufferData buf;
1761 : :
3484 1762 [ - + ]: 204 : Assert(conn != NULL);
1673 1763 : 204 : initPQExpBuffer(&buf);
1764 : :
1765 : : /*
1766 : : * Check server version. BASE_BACKUP command was introduced in 9.1, so we
1767 : : * can't work with servers older than 9.1.
1768 : : */
4792 heikki.linnakangas@i 1769 : 204 : minServerMajor = 901;
1770 : 204 : maxServerMajor = PG_VERSION_NUM / 100;
3484 rhaas@postgresql.org 1771 : 204 : serverVersion = PQserverVersion(conn);
1772 : 204 : serverMajor = serverVersion / 100;
4792 heikki.linnakangas@i 1773 [ + - - + ]: 204 : if (serverMajor < minServerMajor || serverMajor > maxServerMajor)
1774 : : {
4792 heikki.linnakangas@i 1775 :UBC 0 : const char *serverver = PQparameterStatus(conn, "server_version");
1776 : :
1488 tgl@sss.pgh.pa.us 1777 [ # # ]: 0 : pg_fatal("incompatible server version %s",
1778 : : serverver ? serverver : "'unknown'");
1779 : : }
1673 rhaas@postgresql.org 1780 [ + - ]:CBC 204 : if (serverMajor >= 1500)
1781 : 204 : use_new_option_syntax = true;
1782 : :
1783 : : /*
1784 : : * If WAL streaming was requested, also check that the server is new
1785 : : * enough for that.
1786 : : */
3403 magnus@hagander.net 1787 [ + + - + ]: 204 : if (includewal == STREAM_WAL && !CheckServerVersionForStreaming(conn))
1788 : : {
1789 : : /*
1790 : : * Error message already written in CheckServerVersionForStreaming(),
1791 : : * but add a hint about using -X none.
1792 : : */
1319 peter@eisentraut.org 1793 :UBC 0 : pg_log_error_hint("Use -X none or -X fetch to disable log streaming.");
2684 1794 : 0 : exit(1);
1795 : : }
1796 : :
1797 : : /*
1798 : : * Build contents of configuration file if requested.
1799 : : *
1800 : : * Note that we don't use the dbname from key-value pair in conn as that
1801 : : * would have been filled by the default dbname (dbname=replication) in
1802 : : * case the user didn't specify the one. The dbname written in the config
1803 : : * file as part of primary_conninfo would be used by slotsync worker which
1804 : : * doesn't use a replication connection so the default won't work for it.
1805 : : */
4868 magnus@hagander.net 1806 [ + + ]:CBC 204 : if (writerecoveryconf)
775 akapila@postgresql.o 1807 : 4 : recoveryconfcontents = GenerateRecoveryConfig(conn,
1808 : : replication_slot,
1809 : : GetDbnameFromConnectionOptions(connection_string));
1810 : :
1811 : : /*
1812 : : * Run IDENTIFY_SYSTEM so we can get the timeline
1813 : : */
4234 andres@anarazel.de 1814 [ - + ]: 204 : if (!RunIdentifySystem(conn, &sysidentifier, &latesttli, NULL, NULL))
2684 peter@eisentraut.org 1815 :UBC 0 : exit(1);
1816 : :
1817 : : /*
1818 : : * If the user wants an incremental backup, we must upload the manifest
1819 : : * for the previous backup upon which it is to be based.
1820 : : */
867 rhaas@postgresql.org 1821 [ + + ]:CBC 204 : if (incremental_manifest != NULL)
1822 : : {
1823 : : int fd;
1824 : : char mbuf[65536];
1825 : : int nbytes;
1826 : :
1827 : : /* Reject if server is too old. */
1828 [ - + ]: 13 : if (serverVersion < MINIMUM_VERSION_FOR_WAL_SUMMARIES)
867 rhaas@postgresql.org 1829 :UBC 0 : pg_fatal("server does not support incremental backup");
1830 : :
1831 : : /* Open the file. */
867 rhaas@postgresql.org 1832 :CBC 13 : fd = open(incremental_manifest, O_RDONLY | PG_BINARY, 0);
1833 [ - + ]: 13 : if (fd < 0)
867 rhaas@postgresql.org 1834 :UBC 0 : pg_fatal("could not open file \"%s\": %m", incremental_manifest);
1835 : :
1836 : : /* Tell the server what we want to do. */
867 rhaas@postgresql.org 1837 [ - + ]:CBC 13 : if (PQsendQuery(conn, "UPLOAD_MANIFEST") == 0)
867 rhaas@postgresql.org 1838 :UBC 0 : pg_fatal("could not send replication command \"%s\": %s",
1839 : : "UPLOAD_MANIFEST", PQerrorMessage(conn));
867 rhaas@postgresql.org 1840 :CBC 13 : res = PQgetResult(conn);
1841 [ - + ]: 13 : if (PQresultStatus(res) != PGRES_COPY_IN)
1842 : : {
867 rhaas@postgresql.org 1843 [ # # ]:UBC 0 : if (PQresultStatus(res) == PGRES_FATAL_ERROR)
1844 : 0 : pg_fatal("could not upload manifest: %s",
1845 : : PQerrorMessage(conn));
1846 : : else
1847 : 0 : pg_fatal("could not upload manifest: unexpected status %s",
1848 : : PQresStatus(PQresultStatus(res)));
1849 : : }
1850 : :
1851 : : /* Loop, reading from the file and sending the data to the server. */
867 rhaas@postgresql.org 1852 [ + + ]:CBC 53 : while ((nbytes = read(fd, mbuf, sizeof mbuf)) > 0)
1853 : : {
1854 [ - + ]: 40 : if (PQputCopyData(conn, mbuf, nbytes) < 0)
867 rhaas@postgresql.org 1855 :UBC 0 : pg_fatal("could not send COPY data: %s",
1856 : : PQerrorMessage(conn));
1857 : : }
1858 : :
1859 : : /* Bail out if we exited the loop due to an error. */
867 rhaas@postgresql.org 1860 [ - + ]:CBC 13 : if (nbytes < 0)
867 rhaas@postgresql.org 1861 :UBC 0 : pg_fatal("could not read file \"%s\": %m", incremental_manifest);
1862 : :
1863 : : /* End the COPY operation. */
867 rhaas@postgresql.org 1864 [ - + ]:CBC 13 : if (PQputCopyEnd(conn, NULL) < 0)
867 rhaas@postgresql.org 1865 :UBC 0 : pg_fatal("could not send end-of-COPY: %s",
1866 : : PQerrorMessage(conn));
1867 : :
1868 : : /* See whether the server is happy with what we sent. */
867 rhaas@postgresql.org 1869 :CBC 13 : res = PQgetResult(conn);
1870 [ + + ]: 13 : if (PQresultStatus(res) == PGRES_FATAL_ERROR)
1871 : 1 : pg_fatal("could not upload manifest: %s",
1872 : : PQerrorMessage(conn));
1873 [ - + ]: 12 : else if (PQresultStatus(res) != PGRES_COMMAND_OK)
867 rhaas@postgresql.org 1874 :UBC 0 : pg_fatal("could not upload manifest: unexpected status %s",
1875 : : PQresStatus(PQresultStatus(res)));
1876 : :
1877 : : /* Consume ReadyForQuery message from server. */
867 rhaas@postgresql.org 1878 :CBC 12 : res = PQgetResult(conn);
1879 [ - + ]: 12 : if (res != NULL)
867 rhaas@postgresql.org 1880 :UBC 0 : pg_fatal("unexpected extra result while sending manifest");
1881 : :
1882 : : /* Add INCREMENTAL option to BASE_BACKUP command. */
867 rhaas@postgresql.org 1883 :CBC 12 : AppendPlainCommandOption(&buf, use_new_option_syntax, "INCREMENTAL");
1884 : : }
1885 : :
1886 : : /*
1887 : : * Continue building up the options list for the BASE_BACKUP command.
1888 : : */
1673 1889 : 203 : AppendStringCommandOption(&buf, use_new_option_syntax, "LABEL", label);
1890 [ + - ]: 203 : if (estimatesize)
1891 : 203 : AppendPlainCommandOption(&buf, use_new_option_syntax, "PROGRESS");
1892 [ + + ]: 203 : if (includewal == FETCH_WAL)
1893 : 26 : AppendPlainCommandOption(&buf, use_new_option_syntax, "WAL");
1894 [ + + ]: 203 : if (fastcheckpoint)
1895 : : {
1896 [ + - ]: 193 : if (use_new_option_syntax)
1897 : 193 : AppendStringCommandOption(&buf, use_new_option_syntax,
1898 : : "CHECKPOINT", "fast");
1899 : : else
1673 rhaas@postgresql.org 1900 :UBC 0 : AppendPlainCommandOption(&buf, use_new_option_syntax, "FAST");
1901 : : }
1673 rhaas@postgresql.org 1902 [ + + ]:CBC 203 : if (includewal != NO_WAL)
1903 : : {
1904 [ + - ]: 193 : if (use_new_option_syntax)
1905 : 193 : AppendIntegerCommandOption(&buf, use_new_option_syntax, "WAIT", 0);
1906 : : else
1673 rhaas@postgresql.org 1907 :UBC 0 : AppendPlainCommandOption(&buf, use_new_option_syntax, "NOWAIT");
1908 : : }
4450 alvherre@alvh.no-ip. 1909 [ + + ]:CBC 203 : if (maxrate > 0)
1673 rhaas@postgresql.org 1910 : 1 : AppendIntegerCommandOption(&buf, use_new_option_syntax, "MAX_RATE",
1911 : : maxrate);
1912 [ + + ]: 203 : if (format == 't')
1913 : 24 : AppendPlainCommandOption(&buf, use_new_option_syntax, "TABLESPACE_MAP");
1914 [ + + ]: 203 : if (!verify_checksums)
1915 : : {
1916 [ + - ]: 1 : if (use_new_option_syntax)
1917 : 1 : AppendIntegerCommandOption(&buf, use_new_option_syntax,
1918 : : "VERIFY_CHECKSUMS", 0);
1919 : : else
1673 rhaas@postgresql.org 1920 :UBC 0 : AppendPlainCommandOption(&buf, use_new_option_syntax,
1921 : : "NOVERIFY_CHECKSUMS");
1922 : : }
1923 : :
2223 rhaas@postgresql.org 1924 [ + + ]:CBC 203 : if (manifest)
1925 : : {
1673 1926 : 202 : AppendStringCommandOption(&buf, use_new_option_syntax, "MANIFEST",
1631 1927 [ + + ]: 202 : manifest_force_encode ? "force-encode" : "yes");
2223 1928 [ + + ]: 202 : if (manifest_checksums != NULL)
1673 1929 : 14 : AppendStringCommandOption(&buf, use_new_option_syntax,
1930 : : "MANIFEST_CHECKSUMS", manifest_checksums);
1931 : : }
1932 : :
1631 1933 [ + + ]: 203 : if (backup_target != NULL)
1934 : : {
1935 : : char *colon;
1936 : :
1937 [ - + ]: 16 : if (serverMajor < 1500)
1488 tgl@sss.pgh.pa.us 1938 :UBC 0 : pg_fatal("backup targets are not supported by this server version");
1939 : :
1559 rhaas@postgresql.org 1940 [ - + ]:CBC 16 : if (writerecoveryconf)
1488 tgl@sss.pgh.pa.us 1941 :UBC 0 : pg_fatal("recovery configuration cannot be written when a backup target is used");
1942 : :
1631 rhaas@postgresql.org 1943 :CBC 16 : AppendPlainCommandOption(&buf, use_new_option_syntax, "TABLESPACE_MAP");
1944 : :
1945 [ + + ]: 16 : if ((colon = strchr(backup_target, ':')) == NULL)
1946 : : {
1947 : 6 : AppendStringCommandOption(&buf, use_new_option_syntax,
1948 : : "TARGET", backup_target);
1949 : : }
1950 : : else
1951 : : {
1952 : : char *target;
1953 : :
1954 : 10 : target = pnstrdup(backup_target, colon - backup_target);
1955 : 10 : AppendStringCommandOption(&buf, use_new_option_syntax,
1956 : : "TARGET", target);
1957 : 10 : AppendStringCommandOption(&buf, use_new_option_syntax,
1958 : : "TARGET_DETAIL", colon + 1);
1959 : : }
1960 : : }
1961 [ + - ]: 187 : else if (serverMajor >= 1500)
1568 1962 : 187 : AppendStringCommandOption(&buf, use_new_option_syntax,
1963 : : "TARGET", "client");
1964 : :
1562 1965 [ + + ]: 203 : if (compressloc == COMPRESS_LOCATION_SERVER)
1966 : : {
1967 [ - + ]: 30 : if (!use_new_option_syntax)
1488 tgl@sss.pgh.pa.us 1968 :UBC 0 : pg_fatal("server does not support server-side compression");
1562 rhaas@postgresql.org 1969 :CBC 30 : AppendStringCommandOption(&buf, use_new_option_syntax,
1970 : : "COMPRESSION", compression_algorithm);
1504 1971 [ + + ]: 30 : if (compression_detail != NULL)
1972 : 15 : AppendStringCommandOption(&buf, use_new_option_syntax,
1973 : : "COMPRESSION_DETAIL",
1974 : : compression_detail);
1975 : : }
1976 : :
3355 magnus@hagander.net 1977 [ - + ]: 203 : if (verbose)
2591 peter@eisentraut.org 1978 :UBC 0 : pg_log_info("initiating base backup, waiting for checkpoint to complete");
1979 : :
3355 magnus@hagander.net 1980 [ - + - - ]:CBC 203 : if (showprogress && !verbose)
1981 : : {
1319 peter@eisentraut.org 1982 :UBC 0 : fprintf(stderr, _("waiting for checkpoint"));
3077 peter_e@gmx.net 1983 [ # # ]: 0 : if (isatty(fileno(stderr)))
1984 : 0 : fprintf(stderr, "\r");
1985 : : else
1986 : 0 : fprintf(stderr, "\n");
1987 : : }
1988 : :
1673 rhaas@postgresql.org 1989 [ + - + - ]:CBC 203 : if (use_new_option_syntax && buf.len > 0)
1990 : 203 : basebkp = psprintf("BASE_BACKUP (%s)", buf.data);
1991 : : else
1673 rhaas@postgresql.org 1992 :UBC 0 : basebkp = psprintf("BASE_BACKUP %s", buf.data);
1993 : :
1994 : : /* OK, try to start the backup. */
4450 alvherre@alvh.no-ip. 1995 [ - + ]:CBC 203 : if (PQsendQuery(conn, basebkp) == 0)
1488 tgl@sss.pgh.pa.us 1996 :UBC 0 : pg_fatal("could not send replication command \"%s\": %s",
1997 : : "BASE_BACKUP", PQerrorMessage(conn));
1998 : :
1999 : : /*
2000 : : * Get the starting WAL location
2001 : : */
5581 magnus@hagander.net 2002 :CBC 203 : res = PQgetResult(conn);
2003 [ + + ]: 203 : if (PQresultStatus(res) != PGRES_TUPLES_OK)
1488 tgl@sss.pgh.pa.us 2004 : 18 : pg_fatal("could not initiate base backup: %s",
2005 : : PQerrorMessage(conn));
4792 heikki.linnakangas@i 2006 [ - + ]: 185 : if (PQntuples(res) != 1)
1488 tgl@sss.pgh.pa.us 2007 :UBC 0 : pg_fatal("server returned unexpected response to BASE_BACKUP command; got %d rows and %d fields, expected %d rows and %d fields",
2008 : : PQntuples(res), PQnfields(res), 1, 2);
2009 : :
4460 tgl@sss.pgh.pa.us 2010 :CBC 185 : strlcpy(xlogstart, PQgetvalue(res, 0, 0), sizeof(xlogstart));
2011 : :
3355 magnus@hagander.net 2012 [ - + ]: 185 : if (verbose)
2591 peter@eisentraut.org 2013 :UBC 0 : pg_log_info("checkpoint completed");
2014 : :
2015 : : /*
2016 : : * 9.3 and later sends the TLI of the starting point. With older servers,
2017 : : * assume it's the same as the latest timeline reported by
2018 : : * IDENTIFY_SYSTEM.
2019 : : */
4792 heikki.linnakangas@i 2020 [ + - ]:CBC 185 : if (PQnfields(res) >= 2)
2021 : 185 : starttli = atoi(PQgetvalue(res, 0, 1));
2022 : : else
4792 heikki.linnakangas@i 2023 :UBC 0 : starttli = latesttli;
5570 magnus@hagander.net 2024 :CBC 185 : PQclear(res);
2025 : :
3403 2026 [ - + - - ]: 185 : if (verbose && includewal != NO_WAL)
2591 peter@eisentraut.org 2027 :UBC 0 : pg_log_info("write-ahead log start point: %s on timeline %u",
2028 : : xlogstart, starttli);
2029 : :
2030 : : /*
2031 : : * Get the header
2032 : : */
5570 magnus@hagander.net 2033 :CBC 185 : res = PQgetResult(conn);
2034 [ - + ]: 185 : if (PQresultStatus(res) != PGRES_TUPLES_OK)
1488 tgl@sss.pgh.pa.us 2035 :UBC 0 : pg_fatal("could not get backup header: %s",
2036 : : PQerrorMessage(conn));
5581 magnus@hagander.net 2037 [ - + ]:CBC 185 : if (PQntuples(res) < 1)
1488 tgl@sss.pgh.pa.us 2038 :UBC 0 : pg_fatal("no data returned from server");
2039 : :
2040 : : /*
2041 : : * Sum up the total size, for progress reporting
2042 : : */
2436 peter@eisentraut.org 2043 :CBC 185 : totalsize_kb = totaldone = 0;
5581 magnus@hagander.net 2044 : 185 : tablespacecount = PQntuples(res);
2045 [ + + ]: 408 : for (i = 0; i < PQntuples(res); i++)
2046 : : {
633 peter@eisentraut.org 2047 : 224 : totalsize_kb += atoll(PQgetvalue(res, i, 2));
2048 : :
2049 : : /*
2050 : : * Verify tablespace directories are empty. Don't bother with the
2051 : : * first once since it can be relocated, and it will be checked before
2052 : : * we do anything anyway.
2053 : : *
2054 : : * Note that this is skipped for tar format backups and backups that
2055 : : * the server is storing to a target location, since in that case we
2056 : : * won't be storing anything into these directories and thus should
2057 : : * not create them.
2058 : : */
1631 rhaas@postgresql.org 2059 [ + + + + : 224 : if (backup_target == NULL && format == 'p' && !PQgetisnull(res, i, 1))
+ + ]
2060 : : {
1113 2061 : 31 : char *path = PQgetvalue(res, i, 1);
2062 : :
2063 [ + + ]: 31 : if (is_absolute_path(path))
2064 : 17 : path = unconstify(char *, get_tablespace_mapping(path));
2065 : : else
2066 : : {
2067 : : /* This is an in-place tablespace, so prepend basedir. */
2068 : 14 : path = psprintf("%s/%s", basedir, path);
2069 : : }
2070 : :
3522 peter_e@gmx.net 2071 : 31 : verify_dir_is_empty_or_create(path, &made_tablespace_dirs, &found_tablespace_dirs);
2072 : : }
2073 : : }
2074 : :
2075 : : /*
2076 : : * When writing to stdout, require a single tablespace
2077 : : */
1631 rhaas@postgresql.org 2078 [ + + + - ]: 207 : writing_to_stdout = format == 't' && basedir != NULL &&
2079 [ - + ]: 23 : strcmp(basedir, "-") == 0;
2223 2080 [ - + - - ]: 184 : if (writing_to_stdout && PQntuples(res) > 1)
1488 tgl@sss.pgh.pa.us 2081 :UBC 0 : pg_fatal("can only write single tablespace to stdout, database has %d",
2082 : : PQntuples(res));
2083 : :
2084 : : /*
2085 : : * If we're streaming WAL, start the streaming session before we start
2086 : : * receiving the actual data chunks.
2087 : : */
3403 magnus@hagander.net 2088 [ + + ]:CBC 184 : if (includewal == STREAM_WAL)
2089 : : {
2090 : : pg_compress_algorithm wal_compress_algorithm;
2091 : : int wal_compress_level;
2092 : :
5305 2093 [ - + ]: 153 : if (verbose)
2591 peter@eisentraut.org 2094 :UBC 0 : pg_log_info("starting background WAL receiver");
2095 : :
1484 michael@paquier.xyz 2096 [ + + ]:CBC 153 : if (client_compress->algorithm == PG_COMPRESSION_GZIP)
2097 : : {
2098 : 3 : wal_compress_algorithm = PG_COMPRESSION_GZIP;
1329 2099 : 3 : wal_compress_level = client_compress->level;
2100 : : }
2101 : : else
2102 : : {
1484 2103 : 150 : wal_compress_algorithm = PG_COMPRESSION_NONE;
1504 rhaas@postgresql.org 2104 : 150 : wal_compress_level = 0;
2105 : : }
2106 : :
2107 : 153 : StartLogStreamer(xlogstart, starttli, sysidentifier,
2108 : : wal_compress_algorithm,
2109 : : wal_compress_level);
2110 : : }
2111 : :
1568 2112 [ + - ]: 183 : if (serverMajor >= 1500)
2113 : : {
2114 : : /* Receive a single tar stream with everything. */
1504 2115 : 183 : ReceiveArchiveStream(conn, client_compress);
2116 : : }
2117 : : else
2118 : : {
2119 : : /* Receive a tar file for each tablespace in turn */
1568 rhaas@postgresql.org 2120 [ # # ]:UBC 0 : for (i = 0; i < PQntuples(res); i++)
2121 : : {
2122 : : char archive_name[MAXPGPATH];
2123 : : char *spclocation;
2124 : :
2125 : : /*
2126 : : * If we write the data out to a tar file, it will be named
2127 : : * base.tar if it's the main data directory or <tablespaceoid>.tar
2128 : : * if it's for another tablespace. CreateBackupStreamer() will
2129 : : * arrange to add an extension to the archive name if
2130 : : * pg_basebackup is performing compression, depending on the
2131 : : * compression type.
2132 : : */
2133 [ # # ]: 0 : if (PQgetisnull(res, i, 0))
2134 : : {
2135 : 0 : strlcpy(archive_name, "base.tar", sizeof(archive_name));
2136 : 0 : spclocation = NULL;
2137 : : }
2138 : : else
2139 : : {
2140 : 0 : snprintf(archive_name, sizeof(archive_name),
2141 : : "%s.tar", PQgetvalue(res, i, 0));
2142 : 0 : spclocation = PQgetvalue(res, i, 1);
2143 : : }
2144 : :
1504 2145 : 0 : ReceiveTarFile(conn, archive_name, spclocation, i,
2146 : : client_compress);
2147 : : }
2148 : :
2149 : : /*
2150 : : * Now receive backup manifest, if appropriate.
2151 : : *
2152 : : * If we're writing a tarfile to stdout, ReceiveTarFile will have
2153 : : * already processed the backup manifest and included it in the output
2154 : : * tarfile. Such a configuration doesn't allow for writing multiple
2155 : : * files.
2156 : : *
2157 : : * If we're talking to an older server, it won't send a backup
2158 : : * manifest, so don't try to receive one.
2159 : : */
1568 2160 [ # # # # ]: 0 : if (!writing_to_stdout && manifest)
2161 : 0 : ReceiveBackupManifest(conn);
2162 : : }
2163 : :
5581 magnus@hagander.net 2164 [ - + ]:CBC 181 : if (showprogress)
2165 : : {
1538 tgl@sss.pgh.pa.us 2166 :UBC 0 : progress_update_filename(NULL);
1642 rhaas@postgresql.org 2167 : 0 : progress_report(PQntuples(res), true, true);
2168 : : }
2169 : :
5581 magnus@hagander.net 2170 :CBC 181 : PQclear(res);
2171 : :
2172 : : /*
2173 : : * Get the stop position
2174 : : */
5570 2175 : 181 : res = PQgetResult(conn);
2176 [ + + ]: 181 : if (PQresultStatus(res) != PGRES_TUPLES_OK)
1488 tgl@sss.pgh.pa.us 2177 : 1 : pg_fatal("backup failed: %s",
2178 : : PQerrorMessage(conn));
5570 magnus@hagander.net 2179 [ - + ]: 180 : if (PQntuples(res) != 1)
1488 tgl@sss.pgh.pa.us 2180 :UBC 0 : pg_fatal("no write-ahead log end position returned from server");
4460 tgl@sss.pgh.pa.us 2181 :CBC 180 : strlcpy(xlogend, PQgetvalue(res, 0, 0), sizeof(xlogend));
3403 magnus@hagander.net 2182 [ - + - - ]: 180 : if (verbose && includewal != NO_WAL)
2591 peter@eisentraut.org 2183 :UBC 0 : pg_log_info("write-ahead log end point: %s", xlogend);
5570 magnus@hagander.net 2184 :CBC 180 : PQclear(res);
2185 : :
5581 2186 : 180 : res = PQgetResult(conn);
2187 [ + + ]: 180 : if (PQresultStatus(res) != PGRES_COMMAND_OK)
2188 : : {
2954 2189 : 3 : const char *sqlstate = PQresultErrorField(res, PG_DIAG_SQLSTATE);
2190 : :
2191 [ + - ]: 3 : if (sqlstate &&
2192 [ + - ]: 3 : strcmp(sqlstate, ERRCODE_DATA_CORRUPTED) == 0)
2193 : : {
2591 peter@eisentraut.org 2194 : 3 : pg_log_error("checksum error occurred");
2954 magnus@hagander.net 2195 : 3 : checksum_failure = true;
2196 : : }
2197 : : else
2198 : : {
2591 peter@eisentraut.org 2199 :UBC 0 : pg_log_error("final receive failed: %s",
2200 : : PQerrorMessage(conn));
2201 : : }
2684 peter@eisentraut.org 2202 :CBC 3 : exit(1);
2203 : : }
2204 : :
5305 magnus@hagander.net 2205 [ + + ]: 177 : if (bgchild > 0)
2206 : : {
2207 : : #ifndef WIN32
2208 : : int status;
2209 : : pid_t r;
2210 : : #else
2211 : : DWORD status;
2212 : :
2213 : : /*
2214 : : * get a pointer sized version of bgchild to avoid warnings about
2215 : : * casting to a different size on WIN64.
2216 : : */
2217 : : intptr_t bgchild_handle = bgchild;
2218 : : uint32 hi,
2219 : : lo;
2220 : : #endif
2221 : :
2222 [ - + ]: 146 : if (verbose)
2591 peter@eisentraut.org 2223 :UBC 0 : pg_log_info("waiting for background process to finish streaming ...");
2224 : :
2225 : : #ifndef WIN32
5151 andrew@dunslane.net 2226 [ - + ]:CBC 146 : if (write(bgpipe[1], xlogend, strlen(xlogend)) != strlen(xlogend))
1488 tgl@sss.pgh.pa.us 2227 :UBC 0 : pg_fatal("could not send command to background pipe: %m");
2228 : :
2229 : : /* Just wait for the background process to exit */
5305 magnus@hagander.net 2230 :CBC 146 : r = waitpid(bgchild, &status, 0);
2697 tgl@sss.pgh.pa.us 2231 [ - + ]: 146 : if (r == (pid_t) -1)
1488 tgl@sss.pgh.pa.us 2232 :UBC 0 : pg_fatal("could not wait for child process: %m");
5305 magnus@hagander.net 2233 [ - + ]:CBC 146 : if (r != bgchild)
1488 tgl@sss.pgh.pa.us 2234 :UBC 0 : pg_fatal("child %d died, expected %d", (int) r, (int) bgchild);
2697 tgl@sss.pgh.pa.us 2235 [ - + ]:CBC 146 : if (status != 0)
1488 tgl@sss.pgh.pa.us 2236 :UBC 0 : pg_fatal("%s", wait_result_to_str(status));
2237 : : /* Exited normally, we're happy! */
2238 : : #else /* WIN32 */
2239 : :
2240 : : /*
2241 : : * On Windows, since we are in the same process, we can just store the
2242 : : * value directly in the variable, and then set the flag that says
2243 : : * it's there.
2244 : : */
2245 : : if (sscanf(xlogend, "%X/%08X", &hi, &lo) != 2)
2246 : : pg_fatal("could not parse write-ahead log location \"%s\"",
2247 : : xlogend);
2248 : : xlogendptr = ((uint64) hi) << 32 | lo;
2249 : : InterlockedIncrement(&has_xlogendptr);
2250 : :
2251 : : /* First wait for the thread to exit */
2252 : : if (WaitForSingleObjectEx((HANDLE) bgchild_handle, INFINITE, FALSE) !=
2253 : : WAIT_OBJECT_0)
2254 : : {
2255 : : _dosmaperr(GetLastError());
2256 : : pg_fatal("could not wait for child thread: %m");
2257 : : }
2258 : : if (GetExitCodeThread((HANDLE) bgchild_handle, &status) == 0)
2259 : : {
2260 : : _dosmaperr(GetLastError());
2261 : : pg_fatal("could not get child thread exit status: %m");
2262 : : }
2263 : : if (status != 0)
2264 : : pg_fatal("child thread exited with error %u",
2265 : : (unsigned int) status);
2266 : : /* Exited normally, we're happy */
2267 : : #endif
2268 : : }
2269 : :
2270 : : /* Free the configuration file contents */
4868 magnus@hagander.net 2271 :CBC 177 : destroyPQExpBuffer(recoveryconfcontents);
2272 : :
2273 : : /*
2274 : : * End of copy data. Final result is already checked inside the loop.
2275 : : */
5219 2276 : 177 : PQclear(res);
5581 2277 : 177 : PQfinish(conn);
2684 peter@eisentraut.org 2278 : 177 : conn = NULL;
2279 : :
2280 : : /*
2281 : : * Make data persistent on disk once backup is completed. For tar format
2282 : : * sync the parent directory and all its contents as each tar file was not
2283 : : * synced after being completed. In plain format, all the data of the
2284 : : * base directory is synced, taking into account all the tablespaces.
2285 : : * Errors are not considered fatal.
2286 : : *
2287 : : * If, however, there's a backup target, we're not writing anything
2288 : : * locally, so in that case we skip this step.
2289 : : */
1631 rhaas@postgresql.org 2290 [ - + - - ]: 177 : if (do_sync && backup_target == NULL)
2291 : : {
2837 michael@paquier.xyz 2292 [ # # ]:UBC 0 : if (verbose)
2591 peter@eisentraut.org 2293 : 0 : pg_log_info("syncing data to disk ...");
3505 peter_e@gmx.net 2294 [ # # ]: 0 : if (format == 't')
2295 : : {
2296 [ # # ]: 0 : if (strcmp(basedir, "-") != 0)
972 nathan@postgresql.or 2297 : 0 : (void) sync_dir_recurse(basedir, sync_method);
2298 : : }
2299 : : else
2300 : : {
406 2301 : 0 : (void) sync_pgdata(basedir, serverVersion, sync_method, true);
2302 : : }
2303 : : }
2304 : :
2305 : : /*
2306 : : * After synchronizing data to disk, perform a durable rename of
2307 : : * backup_manifest.tmp to backup_manifest, if we wrote such a file. This
2308 : : * way, a failure or system crash before we reach this point will leave us
2309 : : * without a backup_manifest file, decreasing the chances that a directory
2310 : : * we leave behind will be mistaken for a valid backup.
2311 : : */
1631 rhaas@postgresql.org 2312 [ + - + + :CBC 177 : if (!writing_to_stdout && manifest && backup_target == NULL)
+ + ]
2313 : : {
2314 : : char tmp_filename[MAXPGPATH];
2315 : : char filename[MAXPGPATH];
2316 : :
2223 2317 [ - + ]: 165 : if (verbose)
2223 rhaas@postgresql.org 2318 :UBC 0 : pg_log_info("renaming backup_manifest.tmp to backup_manifest");
2319 : :
2223 rhaas@postgresql.org 2320 :CBC 165 : snprintf(tmp_filename, MAXPGPATH, "%s/backup_manifest.tmp", basedir);
2321 : 165 : snprintf(filename, MAXPGPATH, "%s/backup_manifest", basedir);
2322 : :
1563 andres@anarazel.de 2323 [ - + ]: 165 : if (do_sync)
2324 : : {
2325 : : /* durable_rename emits its own log message in case of failure */
1563 andres@anarazel.de 2326 [ # # ]:UBC 0 : if (durable_rename(tmp_filename, filename) != 0)
2327 : 0 : exit(1);
2328 : : }
2329 : : else
2330 : : {
1563 andres@anarazel.de 2331 [ - + ]:CBC 165 : if (rename(tmp_filename, filename) != 0)
1488 tgl@sss.pgh.pa.us 2332 :UBC 0 : pg_fatal("could not rename file \"%s\" to \"%s\": %m",
2333 : : tmp_filename, filename);
2334 : : }
2335 : : }
2336 : :
5581 magnus@hagander.net 2337 [ - + ]:CBC 177 : if (verbose)
2591 peter@eisentraut.org 2338 :UBC 0 : pg_log_info("base backup completed");
5581 magnus@hagander.net 2339 :CBC 177 : }
2340 : :
2341 : :
2342 : : int
2343 : 236 : main(int argc, char **argv)
2344 : : {
2345 : : static struct option long_options[] = {
2346 : : {"help", no_argument, NULL, '?'},
2347 : : {"version", no_argument, NULL, 'V'},
2348 : : {"pgdata", required_argument, NULL, 'D'},
2349 : : {"format", required_argument, NULL, 'F'},
2350 : : {"incremental", required_argument, NULL, 'i'},
2351 : : {"checkpoint", required_argument, NULL, 'c'},
2352 : : {"create-slot", no_argument, NULL, 'C'},
2353 : : {"max-rate", required_argument, NULL, 'r'},
2354 : : {"write-recovery-conf", no_argument, NULL, 'R'},
2355 : : {"slot", required_argument, NULL, 'S'},
2356 : : {"target", required_argument, NULL, 't'},
2357 : : {"tablespace-mapping", required_argument, NULL, 'T'},
2358 : : {"wal-method", required_argument, NULL, 'X'},
2359 : : {"gzip", no_argument, NULL, 'z'},
2360 : : {"compress", required_argument, NULL, 'Z'},
2361 : : {"label", required_argument, NULL, 'l'},
2362 : : {"no-clean", no_argument, NULL, 'n'},
2363 : : {"no-sync", no_argument, NULL, 'N'},
2364 : : {"dbname", required_argument, NULL, 'd'},
2365 : : {"host", required_argument, NULL, 'h'},
2366 : : {"port", required_argument, NULL, 'p'},
2367 : : {"username", required_argument, NULL, 'U'},
2368 : : {"no-password", no_argument, NULL, 'w'},
2369 : : {"password", no_argument, NULL, 'W'},
2370 : : {"status-interval", required_argument, NULL, 's'},
2371 : : {"verbose", no_argument, NULL, 'v'},
2372 : : {"progress", no_argument, NULL, 'P'},
2373 : : {"waldir", required_argument, NULL, 1},
2374 : : {"no-slot", no_argument, NULL, 2},
2375 : : {"no-verify-checksums", no_argument, NULL, 3},
2376 : : {"no-estimate-size", no_argument, NULL, 4},
2377 : : {"no-manifest", no_argument, NULL, 5},
2378 : : {"manifest-force-encode", no_argument, NULL, 6},
2379 : : {"manifest-checksums", required_argument, NULL, 7},
2380 : : {"sync-method", required_argument, NULL, 8},
2381 : : {NULL, 0, NULL, 0}
2382 : : };
2383 : : int c;
2384 : :
2385 : : int option_index;
1504 rhaas@postgresql.org 2386 : 236 : char *compression_algorithm = "none";
2387 : 236 : char *compression_detail = NULL;
867 2388 : 236 : char *incremental_manifest = NULL;
1454 tgl@sss.pgh.pa.us 2389 : 236 : CompressionLocation compressloc = COMPRESS_LOCATION_UNSPECIFIED;
2390 : : pg_compress_specification client_compress;
2391 : :
2591 peter@eisentraut.org 2392 : 236 : pg_logging_init(argv[0]);
5581 magnus@hagander.net 2393 : 236 : progname = get_progname(argv[0]);
2394 : 236 : set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_basebackup"));
2395 : :
2396 [ + + ]: 236 : if (argc > 1)
2397 : : {
2398 [ + + - + ]: 235 : if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
2399 : : {
2400 : 1 : usage();
2401 : 1 : exit(0);
2402 : : }
2403 [ + - ]: 234 : else if (strcmp(argv[1], "-V") == 0
2404 [ + + ]: 234 : || strcmp(argv[1], "--version") == 0)
2405 : : {
2406 : 1 : puts("pg_basebackup (PostgreSQL) " PG_VERSION);
2407 : 1 : exit(0);
2408 : : }
2409 : : }
2410 : :
3522 peter_e@gmx.net 2411 : 234 : atexit(cleanup_directories_atexit);
2412 : :
867 rhaas@postgresql.org 2413 : 1257 : while ((c = getopt_long(argc, argv, "c:Cd:D:F:h:i:l:nNp:Pr:Rs:S:t:T:U:vwWX:zZ:",
5581 magnus@hagander.net 2414 [ + + ]: 1257 : long_options, &option_index)) != -1)
2415 : : {
2416 [ + + + + : 1030 : switch (c)
+ + + - +
+ + - + +
- + + + +
- - - + +
+ + + + -
+ + + -
+ ]
2417 : : {
1240 peter@eisentraut.org 2418 : 210 : case 'c':
2419 [ + - ]: 210 : if (pg_strcasecmp(optarg, "fast") == 0)
2420 : 210 : fastcheckpoint = true;
1240 peter@eisentraut.org 2421 [ # # ]:UBC 0 : else if (pg_strcasecmp(optarg, "spread") == 0)
2422 : 0 : fastcheckpoint = false;
2423 : : else
2424 : 0 : pg_fatal("invalid checkpoint argument \"%s\", must be \"fast\" or \"spread\"",
2425 : : optarg);
1240 peter@eisentraut.org 2426 :CBC 210 : break;
3143 peter_e@gmx.net 2427 : 5 : case 'C':
2428 : 5 : create_slot = true;
2429 : 5 : break;
1240 peter@eisentraut.org 2430 : 3 : case 'd':
2431 : 3 : connection_string = pg_strdup(optarg);
2432 : 3 : break;
5581 magnus@hagander.net 2433 : 213 : case 'D':
4963 tgl@sss.pgh.pa.us 2434 : 213 : basedir = pg_strdup(optarg);
5581 magnus@hagander.net 2435 : 213 : break;
2436 : 39 : case 'F':
2437 [ + - + + ]: 39 : if (strcmp(optarg, "p") == 0 || strcmp(optarg, "plain") == 0)
2438 : 14 : format = 'p';
2439 [ + + + - ]: 25 : else if (strcmp(optarg, "t") == 0 || strcmp(optarg, "tar") == 0)
2440 : 25 : format = 't';
2441 : : else
1488 tgl@sss.pgh.pa.us 2442 :UBC 0 : pg_fatal("invalid output format \"%s\", must be \"plain\" or \"tar\"",
2443 : : optarg);
5581 magnus@hagander.net 2444 :CBC 39 : break;
1240 peter@eisentraut.org 2445 : 82 : case 'h':
2446 : 82 : dbhost = pg_strdup(optarg);
2447 : 82 : break;
867 rhaas@postgresql.org 2448 : 13 : case 'i':
2449 : 13 : incremental_manifest = pg_strdup(optarg);
2450 : 13 : break;
1240 peter@eisentraut.org 2451 :UBC 0 : case 'l':
2452 : 0 : label = pg_strdup(optarg);
2453 : 0 : break;
1240 peter@eisentraut.org 2454 :CBC 1 : case 'n':
2455 : 1 : noclean = true;
2456 : 1 : break;
2457 : 210 : case 'N':
2458 : 210 : do_sync = false;
2459 : 210 : break;
2460 : 82 : case 'p':
2461 : 82 : dbport = pg_strdup(optarg);
2462 : 82 : break;
1240 peter@eisentraut.org 2463 :UBC 0 : case 'P':
2464 : 0 : showprogress = true;
2465 : 0 : break;
4450 alvherre@alvh.no-ip. 2466 :CBC 1 : case 'r':
2467 : 1 : maxrate = parse_max_rate(optarg);
2468 : 1 : break;
4868 magnus@hagander.net 2469 : 4 : case 'R':
2470 : 4 : writerecoveryconf = true;
2471 : 4 : break;
1240 peter@eisentraut.org 2472 :UBC 0 : case 's':
2473 [ # # ]: 0 : if (!option_parse_int(optarg, "-s/--status-interval", 0,
2474 : : INT_MAX / 1000,
2475 : : &standby_message_timeout))
2476 : 0 : exit(1);
2477 : 0 : standby_message_timeout *= 1000;
2478 : 0 : break;
3941 peter_e@gmx.net 2479 :CBC 8 : case 'S':
2480 : :
2481 : : /*
2482 : : * When specifying replication slot name, use a permanent
2483 : : * slot.
2484 : : */
2485 : 8 : replication_slot = pg_strdup(optarg);
3396 magnus@hagander.net 2486 : 8 : temp_replication_slot = false;
2487 : 8 : break;
1631 rhaas@postgresql.org 2488 : 21 : case 't':
2489 : 21 : backup_target = pg_strdup(optarg);
2490 : 21 : break;
4455 peter_e@gmx.net 2491 : 22 : case 'T':
2492 : 22 : tablespace_list_append(optarg);
2493 : 16 : break;
1240 peter@eisentraut.org 2494 : 7 : case 'U':
2495 : 7 : dbuser = pg_strdup(optarg);
2496 : 7 : break;
1240 peter@eisentraut.org 2497 :UBC 0 : case 'v':
2498 : 0 : verbose++;
2499 : 0 : break;
2500 : 0 : case 'w':
2501 : 0 : dbgetpassword = -1;
2502 : 0 : break;
2503 : 0 : case 'W':
2504 : 0 : dbgetpassword = 1;
2505 : 0 : break;
5077 magnus@hagander.net 2506 :CBC 48 : case 'X':
3408 2507 [ + - ]: 48 : if (strcmp(optarg, "n") == 0 ||
2508 [ + + ]: 48 : strcmp(optarg, "none") == 0)
2509 : : {
3403 2510 : 13 : includewal = NO_WAL;
2511 : : }
3408 2512 [ + - ]: 35 : else if (strcmp(optarg, "f") == 0 ||
3275 bruce@momjian.us 2513 [ + + ]: 35 : strcmp(optarg, "fetch") == 0)
2514 : : {
3403 magnus@hagander.net 2515 : 26 : includewal = FETCH_WAL;
2516 : : }
5305 2517 [ + - ]: 9 : else if (strcmp(optarg, "s") == 0 ||
2518 [ + - ]: 9 : strcmp(optarg, "stream") == 0)
2519 : : {
3403 2520 : 9 : includewal = STREAM_WAL;
2521 : : }
2522 : : else
1488 tgl@sss.pgh.pa.us 2523 :UBC 0 : pg_fatal("invalid wal-method option \"%s\", must be \"fetch\", \"stream\", or \"none\"",
2524 : : optarg);
5574 magnus@hagander.net 2525 :CBC 48 : break;
5454 peter_e@gmx.net 2526 : 1 : case 'z':
1504 rhaas@postgresql.org 2527 : 1 : compression_algorithm = "gzip";
2528 : 1 : compression_detail = NULL;
1562 2529 : 1 : compressloc = COMPRESS_LOCATION_UNSPECIFIED;
5454 peter_e@gmx.net 2530 : 1 : break;
5581 magnus@hagander.net 2531 : 39 : case 'Z':
1252 michael@paquier.xyz 2532 : 39 : backup_parse_compress_options(optarg, &compression_algorithm,
2533 : : &compression_detail, &compressloc);
5581 magnus@hagander.net 2534 : 39 : break;
1240 peter@eisentraut.org 2535 : 1 : case 1:
2536 : 1 : xlog_dir = pg_strdup(optarg);
5581 magnus@hagander.net 2537 : 1 : break;
1240 peter@eisentraut.org 2538 : 2 : case 2:
2539 : 2 : no_slot = true;
5581 magnus@hagander.net 2540 : 2 : break;
2906 peter_e@gmx.net 2541 : 1 : case 3:
2954 magnus@hagander.net 2542 : 1 : verify_checksums = false;
2543 : 1 : break;
2238 fujii@postgresql.org 2544 :UBC 0 : case 4:
2545 : 0 : estimatesize = false;
2546 : 0 : break;
2223 rhaas@postgresql.org 2547 :CBC 1 : case 5:
2548 : 1 : manifest = false;
2549 : 1 : break;
2550 : 1 : case 6:
2551 : 1 : manifest_force_encode = true;
2552 : 1 : break;
2553 : 14 : case 7:
2554 : 14 : manifest_checksums = pg_strdup(optarg);
2555 : 14 : break;
972 nathan@postgresql.or 2556 :UBC 0 : case 8:
2557 [ # # ]: 0 : if (!parse_sync_method(optarg, &sync_method))
2558 : 0 : exit(1);
2559 : 0 : break;
5581 magnus@hagander.net 2560 :CBC 1 : default:
2561 : : /* getopt_long already emitted a complaint */
1488 tgl@sss.pgh.pa.us 2562 : 1 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
5581 magnus@hagander.net 2563 : 1 : exit(1);
2564 : : }
2565 : : }
2566 : :
2567 : : /*
2568 : : * Any non-option arguments?
2569 : : */
2570 [ - + ]: 227 : if (optind < argc)
2571 : : {
2591 peter@eisentraut.org 2572 :UBC 0 : pg_log_error("too many command-line arguments (first is \"%s\")",
2573 : : argv[optind]);
1488 tgl@sss.pgh.pa.us 2574 : 0 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
5581 magnus@hagander.net 2575 : 0 : exit(1);
2576 : : }
2577 : :
2578 : : /*
2579 : : * Setting the backup target to 'client' is equivalent to leaving out the
2580 : : * option. This logic allows us to assume elsewhere that the backup is
2581 : : * being stored locally if and only if backup_target == NULL.
2582 : : */
1631 rhaas@postgresql.org 2583 [ + + - + ]:CBC 227 : if (backup_target != NULL && strcmp(backup_target, "client") == 0)
2584 : : {
1631 rhaas@postgresql.org 2585 :UBC 0 : pg_free(backup_target);
2586 : 0 : backup_target = NULL;
2587 : : }
2588 : :
2589 : : /*
2590 : : * Can't use --format with --target. Without --target, default format is
2591 : : * tar.
2592 : : */
1631 rhaas@postgresql.org 2593 [ + + + + ]:CBC 227 : if (backup_target != NULL && format != '\0')
2594 : : {
2595 : 1 : pg_log_error("cannot specify both format and backup target");
1488 tgl@sss.pgh.pa.us 2596 : 1 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
1631 rhaas@postgresql.org 2597 : 1 : exit(1);
2598 : : }
2599 [ + + ]: 226 : if (format == '\0')
2600 : 194 : format = 'p';
2601 : :
2602 : : /*
2603 : : * Either directory or backup target should be specified, but not both
2604 : : */
2605 [ + + + + ]: 226 : if (basedir == NULL && backup_target == NULL)
2606 : : {
2607 : 1 : pg_log_error("must specify output directory or backup target");
1488 tgl@sss.pgh.pa.us 2608 : 1 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
1631 rhaas@postgresql.org 2609 : 1 : exit(1);
2610 : : }
2611 [ + + + + ]: 225 : if (basedir != NULL && backup_target != NULL)
2612 : : {
2613 : 2 : pg_log_error("cannot specify both output directory and backup target");
1488 tgl@sss.pgh.pa.us 2614 : 2 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
5581 magnus@hagander.net 2615 : 2 : exit(1);
2616 : : }
2617 : :
2618 : : /*
2619 : : * If the user has not specified where to perform backup compression,
2620 : : * default to the client, unless the user specified --target, in which
2621 : : * case the server is the only choice.
2622 : : */
1504 rhaas@postgresql.org 2623 [ + + ]: 223 : if (compressloc == COMPRESS_LOCATION_UNSPECIFIED)
2624 : : {
1631 2625 [ + + ]: 198 : if (backup_target == NULL)
1562 2626 : 185 : compressloc = COMPRESS_LOCATION_CLIENT;
2627 : : else
2628 : 13 : compressloc = COMPRESS_LOCATION_SERVER;
2629 : : }
2630 : :
2631 : : /*
2632 : : * If any compression that we're doing is happening on the client side, we
2633 : : * must try to parse the compression algorithm and detail, but if it's all
2634 : : * on the server side, then we're just going to pass through whatever was
2635 : : * requested and let the server decide what to do.
2636 : : */
1504 2637 [ + + ]: 223 : if (compressloc == COMPRESS_LOCATION_CLIENT)
2638 : : {
2639 : : pg_compress_algorithm alg;
2640 : : char *error_detail;
2641 : :
1484 michael@paquier.xyz 2642 [ + + ]: 191 : if (!parse_compress_algorithm(compression_algorithm, &alg))
1319 peter@eisentraut.org 2643 : 2 : pg_fatal("unrecognized compression algorithm: \"%s\"",
2644 : : compression_algorithm);
2645 : :
1484 michael@paquier.xyz 2646 : 189 : parse_compress_specification(alg, compression_detail, &client_compress);
2647 : 189 : error_detail = validate_compress_specification(&client_compress);
1504 rhaas@postgresql.org 2648 [ + + ]: 189 : if (error_detail != NULL)
1488 tgl@sss.pgh.pa.us 2649 : 10 : pg_fatal("invalid compression specification: %s",
2650 : : error_detail);
2651 : : }
2652 : : else
2653 : : {
1504 rhaas@postgresql.org 2654 [ - + ]: 32 : Assert(compressloc == COMPRESS_LOCATION_SERVER);
1484 michael@paquier.xyz 2655 : 32 : client_compress.algorithm = PG_COMPRESSION_NONE;
1504 rhaas@postgresql.org 2656 : 32 : client_compress.options = 0;
2657 : : }
2658 : :
2659 : : /*
2660 : : * Can't perform client-side compression if the backup is not being sent
2661 : : * to the client.
2662 : : */
1562 2663 [ + + - + ]: 211 : if (backup_target != NULL && compressloc == COMPRESS_LOCATION_CLIENT)
2664 : : {
1562 rhaas@postgresql.org 2665 :UBC 0 : pg_log_error("client-side compression is not possible when a backup target is specified");
1488 tgl@sss.pgh.pa.us 2666 : 0 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
1562 rhaas@postgresql.org 2667 : 0 : exit(1);
2668 : : }
2669 : :
2670 : : /*
2671 : : * Client-side compression doesn't make sense unless tar format is in use.
2672 : : */
1504 rhaas@postgresql.org 2673 [ + + + + ]:CBC 211 : if (format == 'p' && compressloc == COMPRESS_LOCATION_CLIENT &&
1484 michael@paquier.xyz 2674 [ - + ]: 155 : client_compress.algorithm != PG_COMPRESSION_NONE)
2675 : : {
1562 rhaas@postgresql.org 2676 :UBC 0 : pg_log_error("only tar mode backups can be compressed");
1488 tgl@sss.pgh.pa.us 2677 : 0 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
5581 magnus@hagander.net 2678 : 0 : exit(1);
2679 : : }
2680 : :
2681 : : /*
2682 : : * Sanity checks for WAL method.
2683 : : */
1631 rhaas@postgresql.org 2684 [ + + + + ]:CBC 211 : if (backup_target != NULL && includewal == STREAM_WAL)
2685 : : {
2686 : 2 : pg_log_error("WAL cannot be streamed when a backup target is specified");
1488 tgl@sss.pgh.pa.us 2687 : 2 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
1631 rhaas@postgresql.org 2688 : 2 : exit(1);
2689 : : }
3403 magnus@hagander.net 2690 [ + + + + : 209 : if (format == 't' && includewal == STREAM_WAL && strcmp(basedir, "-") == 0)
- + ]
2691 : : {
2591 peter@eisentraut.org 2692 :UBC 0 : pg_log_error("cannot stream write-ahead logs in tar mode to stdout");
1488 tgl@sss.pgh.pa.us 2693 : 0 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
3422 fujii@postgresql.org 2694 : 0 : exit(1);
2695 : : }
2696 : :
3396 magnus@hagander.net 2697 [ + + + + ]:CBC 209 : if (replication_slot && includewal != STREAM_WAL)
2698 : : {
2591 peter@eisentraut.org 2699 : 1 : pg_log_error("replication slots can only be used with WAL streaming");
1488 tgl@sss.pgh.pa.us 2700 : 1 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
3941 peter_e@gmx.net 2701 : 1 : exit(1);
2702 : : }
2703 : :
2704 : : /*
2705 : : * Sanity checks for replication slot options.
2706 : : */
3396 magnus@hagander.net 2707 [ + + ]: 208 : if (no_slot)
2708 : : {
2709 [ + + ]: 2 : if (replication_slot)
2710 : : {
2591 peter@eisentraut.org 2711 : 1 : pg_log_error("--no-slot cannot be used with slot name");
1488 tgl@sss.pgh.pa.us 2712 : 1 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
3396 magnus@hagander.net 2713 : 1 : exit(1);
2714 : : }
2715 : 1 : temp_replication_slot = false;
2716 : : }
2717 : :
3143 peter_e@gmx.net 2718 [ + + ]: 207 : if (create_slot)
2719 : : {
2720 [ + + ]: 4 : if (!replication_slot)
2721 : : {
2591 peter@eisentraut.org 2722 : 1 : pg_log_error("%s needs a slot to be specified using --slot",
2723 : : "--create-slot");
1488 tgl@sss.pgh.pa.us 2724 : 1 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
3143 peter_e@gmx.net 2725 : 1 : exit(1);
2726 : : }
2727 : :
2728 [ - + ]: 3 : if (no_slot)
2729 : : {
2150 peter@eisentraut.org 2730 :UBC 0 : pg_log_error("%s and %s are incompatible options",
2731 : : "--create-slot", "--no-slot");
1488 tgl@sss.pgh.pa.us 2732 : 0 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
3143 peter_e@gmx.net 2733 : 0 : exit(1);
2734 : : }
2735 : : }
2736 : :
2737 : : /*
2738 : : * Sanity checks on WAL directory.
2739 : : */
3170 peter_e@gmx.net 2740 [ + + ]:CBC 206 : if (xlog_dir)
2741 : : {
1631 rhaas@postgresql.org 2742 [ - + ]: 1 : if (backup_target != NULL)
2743 : : {
1631 rhaas@postgresql.org 2744 :UBC 0 : pg_log_error("WAL directory location cannot be specified along with a backup target");
1488 tgl@sss.pgh.pa.us 2745 : 0 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
1631 rhaas@postgresql.org 2746 : 0 : exit(1);
2747 : : }
4542 fujii@postgresql.org 2748 [ - + ]:CBC 1 : if (format != 'p')
2749 : : {
2591 peter@eisentraut.org 2750 :UBC 0 : pg_log_error("WAL directory location can only be specified in plain mode");
1488 tgl@sss.pgh.pa.us 2751 : 0 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
4542 fujii@postgresql.org 2752 : 0 : exit(1);
2753 : : }
2754 : :
2755 : : /* clean up xlog directory name, check it's absolute */
4542 fujii@postgresql.org 2756 :CBC 1 : canonicalize_path(xlog_dir);
2757 [ - + ]: 1 : if (!is_absolute_path(xlog_dir))
2758 : : {
2591 peter@eisentraut.org 2759 :UBC 0 : pg_log_error("WAL directory location must be an absolute path");
1488 tgl@sss.pgh.pa.us 2760 : 0 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
4542 fujii@postgresql.org 2761 : 0 : exit(1);
2762 : : }
2763 : : }
2764 : :
2765 : : /*
2766 : : * Sanity checks for progress reporting options.
2767 : : */
2238 fujii@postgresql.org 2768 [ - + - - ]:CBC 206 : if (showprogress && !estimatesize)
2769 : : {
2150 peter@eisentraut.org 2770 :UBC 0 : pg_log_error("%s and %s are incompatible options",
2771 : : "--progress", "--no-estimate-size");
1488 tgl@sss.pgh.pa.us 2772 : 0 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2238 fujii@postgresql.org 2773 : 0 : exit(1);
2774 : : }
2775 : :
2776 : : /*
2777 : : * Sanity checks for backup manifest options.
2778 : : */
2223 rhaas@postgresql.org 2779 [ + + - + ]:CBC 206 : if (!manifest && manifest_checksums != NULL)
2780 : : {
2150 peter@eisentraut.org 2781 :UBC 0 : pg_log_error("%s and %s are incompatible options",
2782 : : "--no-manifest", "--manifest-checksums");
1488 tgl@sss.pgh.pa.us 2783 : 0 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2223 rhaas@postgresql.org 2784 : 0 : exit(1);
2785 : : }
2786 : :
2223 rhaas@postgresql.org 2787 [ + + - + ]:CBC 206 : if (!manifest && manifest_force_encode)
2788 : : {
2150 peter@eisentraut.org 2789 :UBC 0 : pg_log_error("%s and %s are incompatible options",
2790 : : "--no-manifest", "--manifest-force-encode");
1488 tgl@sss.pgh.pa.us 2791 : 0 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
2223 rhaas@postgresql.org 2792 : 0 : exit(1);
2793 : : }
2794 : :
2795 : : /* connection in replication mode to server */
3484 rhaas@postgresql.org 2796 :CBC 206 : conn = GetConnection();
2797 [ + + ]: 206 : if (!conn)
2798 : : {
2799 : : /* Error message already written in GetConnection() */
2800 : 2 : exit(1);
2801 : : }
2684 peter@eisentraut.org 2802 : 204 : atexit(disconnect_atexit);
2803 : :
2804 : : #ifndef WIN32
2805 : :
2806 : : /*
2807 : : * Trap SIGCHLD to be able to handle the WAL stream process exiting. There
2808 : : * is no SIGCHLD on Windows, there we rely on the background thread
2809 : : * setting the signal variable on unexpected but graceful exit. If the WAL
2810 : : * stream thread crashes on Windows it will bring down the entire process
2811 : : * as it's a thread, so there is nothing to catch should that happen. A
2812 : : * crash on UNIX will be caught by the signal handler.
2813 : : */
1532 dgustafsson@postgres 2814 : 204 : pqsignal(SIGCHLD, sigchld_handler);
2815 : : #endif
2816 : :
2817 : : /*
2818 : : * Set umask so that directories/files are created with the same
2819 : : * permissions as directories/files in the source data directory.
2820 : : *
2821 : : * pg_mode_mask is set to owner-only by default and then updated in
2822 : : * GetConnection() where we get the mode from the server-side with
2823 : : * RetrieveDataDirCreatePerm() and then call SetDataDirectoryCreatePerm().
2824 : : */
2950 sfrost@snowman.net 2825 : 204 : umask(pg_mode_mask);
2826 : :
2827 : : /* Backup manifests are supported in 13 and newer versions */
2210 michael@paquier.xyz 2828 [ - + ]: 204 : if (PQserverVersion(conn) < MINIMUM_VERSION_FOR_MANIFESTS)
2210 michael@paquier.xyz 2829 :UBC 0 : manifest = false;
2830 : :
2831 : : /*
2832 : : * If an output directory was specified, verify that it exists, or create
2833 : : * it. Note that for a tar backup, an output directory of "-" means we are
2834 : : * writing to stdout, so do nothing in that case.
2835 : : */
1631 rhaas@postgresql.org 2836 [ + + + + :CBC 204 : if (basedir != NULL && (format == 'p' || strcmp(basedir, "-") != 0))
+ - ]
2950 sfrost@snowman.net 2837 : 188 : verify_dir_is_empty_or_create(basedir, &made_new_pgdata, &found_existing_pgdata);
2838 : :
2839 : : /* determine remote server's xlog segment size */
3150 andres@anarazel.de 2840 [ - + ]: 204 : if (!RetrieveWalSegSize(conn))
2684 peter@eisentraut.org 2841 :UBC 0 : exit(1);
2842 : :
2843 : : /* Create pg_wal symlink, if required */
3170 peter_e@gmx.net 2844 [ + + ]:CBC 204 : if (xlog_dir)
2845 : : {
2846 : : char *linkloc;
2847 : :
3522 2848 : 1 : verify_dir_is_empty_or_create(xlog_dir, &made_new_xlogdir, &found_existing_xlogdir);
2849 : :
2850 : : /*
2851 : : * Form name of the place where the symlink must go. pg_xlog has been
2852 : : * renamed to pg_wal in post-10 clusters.
2853 : : */
3484 rhaas@postgresql.org 2854 [ - + ]: 1 : linkloc = psprintf("%s/%s", basedir,
3240 tgl@sss.pgh.pa.us 2855 : 1 : PQserverVersion(conn) < MINIMUM_VERSION_FOR_PG_WAL ?
2856 : : "pg_xlog" : "pg_wal");
2857 : :
4542 fujii@postgresql.org 2858 [ - + ]: 1 : if (symlink(xlog_dir, linkloc) != 0)
1488 tgl@sss.pgh.pa.us 2859 :UBC 0 : pg_fatal("could not create symbolic link \"%s\": %m", linkloc);
4542 fujii@postgresql.org 2860 :CBC 1 : free(linkloc);
2861 : : }
2862 : :
1504 rhaas@postgresql.org 2863 : 204 : BaseBackup(compression_algorithm, compression_detail, compressloc,
2864 : : &client_compress, incremental_manifest);
2865 : :
3522 peter_e@gmx.net 2866 : 177 : success = true;
5581 magnus@hagander.net 2867 : 177 : return 0;
2868 : : }
|