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