Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * basebackup.c
4 : : * code for taking a base backup and streaming it to a standby
5 : : *
6 : : * Portions Copyright (c) 2010-2026, PostgreSQL Global Development Group
7 : : *
8 : : * IDENTIFICATION
9 : : * src/backend/backup/basebackup.c
10 : : *
11 : : *-------------------------------------------------------------------------
12 : : */
13 : : #include "postgres.h"
14 : :
15 : : #include <sys/stat.h>
16 : : #include <unistd.h>
17 : : #include <time.h>
18 : :
19 : : #include "access/xlog_internal.h"
20 : : #include "access/xlogbackup.h"
21 : : #include "backup/backup_manifest.h"
22 : : #include "backup/basebackup.h"
23 : : #include "backup/basebackup_incremental.h"
24 : : #include "backup/basebackup_sink.h"
25 : : #include "backup/basebackup_target.h"
26 : : #include "catalog/pg_tablespace_d.h"
27 : : #include "commands/defrem.h"
28 : : #include "common/compression.h"
29 : : #include "common/file_perm.h"
30 : : #include "common/file_utils.h"
31 : : #include "lib/stringinfo.h"
32 : : #include "miscadmin.h"
33 : : #include "nodes/pg_list.h"
34 : : #include "pgstat.h"
35 : : #include "pgtar.h"
36 : : #include "postmaster/syslogger.h"
37 : : #include "postmaster/walsummarizer.h"
38 : : #include "replication/slot.h"
39 : : #include "replication/walsender.h"
40 : : #include "replication/walsender_private.h"
41 : : #include "storage/bufpage.h"
42 : : #include "storage/checksum.h"
43 : : #include "storage/dsm_impl.h"
44 : : #include "storage/ipc.h"
45 : : #include "storage/reinit.h"
46 : : #include "utils/builtins.h"
47 : : #include "utils/guc.h"
48 : : #include "utils/ps_status.h"
49 : : #include "utils/relcache.h"
50 : : #include "utils/resowner.h"
51 : : #include "utils/wait_event.h"
52 : :
53 : : /*
54 : : * How much data do we want to send in one CopyData message? Note that
55 : : * this may also result in reading the underlying files in chunks of this
56 : : * size.
57 : : *
58 : : * NB: The buffer size is required to be a multiple of the system block
59 : : * size, so use that value instead if it's bigger than our preference.
60 : : */
61 : : #define SINK_BUFFER_LENGTH Max(32768, BLCKSZ)
62 : :
63 : : typedef struct
64 : : {
65 : : const char *label;
66 : : bool progress;
67 : : bool fastcheckpoint;
68 : : bool nowait;
69 : : bool includewal;
70 : : bool incremental;
71 : : uint32 maxrate;
72 : : bool sendtblspcmapfile;
73 : : bool send_to_client;
74 : : bool use_copytblspc;
75 : : BaseBackupTargetHandle *target_handle;
76 : : backup_manifest_option manifest;
77 : : pg_compress_algorithm compression;
78 : : pg_compress_specification compression_specification;
79 : : pg_checksum_type manifest_checksum_type;
80 : : } basebackup_options;
81 : :
82 : : #define TAR_NUM_TERMINATION_BLOCKS 2
83 : :
84 : : StaticAssertDecl(TAR_NUM_TERMINATION_BLOCKS * TAR_BLOCK_SIZE <= BLCKSZ,
85 : : "BLCKSZ too small for " CppAsString2(TAR_NUM_TERMINATION_BLOCKS) " tar termination blocks");
86 : :
87 : : static int64 sendTablespace(bbsink *sink, char *path, Oid spcoid, bool sizeonly,
88 : : struct backup_manifest_info *manifest,
89 : : IncrementalBackupInfo *ib);
90 : : static int64 sendDir(bbsink *sink, const char *path, int basepathlen, bool sizeonly,
91 : : List *tablespaces, bool sendtblspclinks,
92 : : backup_manifest_info *manifest, Oid spcoid,
93 : : IncrementalBackupInfo *ib);
94 : : static bool sendFile(bbsink *sink, const char *readfilename, const char *tarfilename,
95 : : struct stat *statbuf, bool missing_ok,
96 : : Oid dboid, Oid spcoid, RelFileNumber relfilenumber,
97 : : unsigned segno,
98 : : backup_manifest_info *manifest,
99 : : unsigned num_incremental_blocks,
100 : : BlockNumber *incremental_blocks,
101 : : unsigned truncation_block_length);
102 : : static off_t read_file_data_into_buffer(bbsink *sink,
103 : : const char *readfilename, int fd,
104 : : off_t offset, size_t length,
105 : : BlockNumber blkno,
106 : : bool verify_checksum,
107 : : int *checksum_failures);
108 : : static void push_to_sink(bbsink *sink, pg_checksum_context *checksum_ctx,
109 : : size_t *bytes_done, void *data, size_t length);
110 : : static bool verify_page_checksum(Page page, XLogRecPtr start_lsn,
111 : : BlockNumber blkno,
112 : : uint16 *expected_checksum);
113 : : static void sendFileWithContent(bbsink *sink, const char *filename,
114 : : const char *content, int len,
115 : : backup_manifest_info *manifest);
116 : : static int64 _tarWriteHeader(bbsink *sink, const char *filename,
117 : : const char *linktarget, struct stat *statbuf,
118 : : bool sizeonly);
119 : : static void _tarWritePadding(bbsink *sink, int len);
120 : : static void convert_link_to_directory(const char *pathbuf, struct stat *statbuf);
121 : : static void perform_base_backup(basebackup_options *opt, bbsink *sink,
122 : : IncrementalBackupInfo *ib);
123 : : static void parse_basebackup_options(List *options, basebackup_options *opt);
124 : : static int compareWalFileNames(const ListCell *a, const ListCell *b);
125 : : static ssize_t basebackup_read_file(int fd, char *buf, size_t nbytes, off_t offset,
126 : : const char *filename, bool partial_read_ok);
127 : :
128 : : /* Was the backup currently in-progress initiated in recovery mode? */
129 : : static bool backup_started_in_recovery = false;
130 : :
131 : : /* Total number of checksum failures during base backup. */
132 : : static long long int total_checksum_failures;
133 : :
134 : : /* Do not verify checksums. */
135 : : static bool noverify_checksums = false;
136 : :
137 : : /*
138 : : * Definition of one element part of an exclusion list, used for paths part
139 : : * of checksum validation or base backups. "name" is the name of the file
140 : : * or path to check for exclusion. If "match_prefix" is true, any items
141 : : * matching the name as prefix are excluded.
142 : : */
143 : : struct exclude_list_item
144 : : {
145 : : const char *name;
146 : : bool match_prefix;
147 : : };
148 : :
149 : : /*
150 : : * The contents of these directories are removed or recreated during server
151 : : * start so they are not included in backups. The directories themselves are
152 : : * kept and included as empty to preserve access permissions.
153 : : *
154 : : * Note: this list should be kept in sync with the filter lists in pg_rewind's
155 : : * filemap.c.
156 : : */
157 : : static const char *const excludeDirContents[] =
158 : : {
159 : : /*
160 : : * Skip temporary statistics files. PG_STAT_TMP_DIR must be skipped
161 : : * because extensions like pg_stat_statements store data there.
162 : : */
163 : : PG_STAT_TMP_DIR,
164 : :
165 : : /*
166 : : * It is generally not useful to backup the contents of this directory
167 : : * even if the intention is to restore to another primary. See backup.sgml
168 : : * for a more detailed description.
169 : : */
170 : : PG_REPLSLOT_DIR,
171 : :
172 : : /* Contents removed on startup, see dsm_cleanup_for_mmap(). */
173 : : PG_DYNSHMEM_DIR,
174 : :
175 : : /* Contents removed on startup, see AsyncShmemInit(). */
176 : : "pg_notify",
177 : :
178 : : /*
179 : : * Old contents are loaded for possible debugging but are not required for
180 : : * normal operation, see SerialInit().
181 : : */
182 : : "pg_serial",
183 : :
184 : : /* Contents removed on startup, see DeleteAllExportedSnapshotFiles(). */
185 : : "pg_snapshots",
186 : :
187 : : /* Contents zeroed on startup, see StartupSUBTRANS(). */
188 : : "pg_subtrans",
189 : :
190 : : /* end of list */
191 : : NULL
192 : : };
193 : :
194 : : /*
195 : : * List of files excluded from backups.
196 : : */
197 : : static const struct exclude_list_item excludeFiles[] =
198 : : {
199 : : /* Skip auto conf temporary file. */
200 : : {PG_AUTOCONF_FILENAME ".tmp", false},
201 : :
202 : : /* Skip current log file temporary file */
203 : : {LOG_METAINFO_DATAFILE_TMP, false},
204 : :
205 : : /*
206 : : * Skip relation cache because it is rebuilt on startup. This includes
207 : : * temporary files.
208 : : */
209 : : {RELCACHE_INIT_FILENAME, true},
210 : :
211 : : /*
212 : : * backup_label and tablespace_map should not exist in a running cluster
213 : : * capable of doing an online backup, but exclude them just in case.
214 : : */
215 : : {BACKUP_LABEL_FILE, false},
216 : : {TABLESPACE_MAP, false},
217 : :
218 : : /*
219 : : * If there's a backup_manifest, it belongs to a backup that was used to
220 : : * start this server. It is *not* correct for this backup. Our
221 : : * backup_manifest is injected into the backup separately if users want
222 : : * it.
223 : : */
224 : : {"backup_manifest", false},
225 : :
226 : : {"postmaster.pid", false},
227 : : {"postmaster.opts", false},
228 : :
229 : : /* end of list */
230 : : {NULL, false}
231 : : };
232 : :
233 : : /*
234 : : * Actually do a base backup for the specified tablespaces.
235 : : *
236 : : * This is split out mainly to avoid complaints about "variable might be
237 : : * clobbered by longjmp" from stupider versions of gcc.
238 : : */
239 : : static void
948 rhaas@postgresql.org 240 :CBC 181 : perform_base_backup(basebackup_options *opt, bbsink *sink,
241 : : IncrementalBackupInfo *ib)
242 : : {
243 : : bbsink_state state;
244 : : XLogRecPtr endptr;
245 : : TimeLineID endtli;
246 : : backup_manifest_info manifest;
247 : : BackupState *backup_state;
248 : : StringInfoData tablespace_map;
249 : :
250 : : /* Initial backup state, insofar as we know it now. */
1723 251 : 181 : state.tablespaces = NIL;
252 : 181 : state.tablespace_num = 0;
253 : 181 : state.bytes_done = 0;
254 : 181 : state.bytes_total = 0;
255 : 181 : state.bytes_total_is_valid = false;
256 : :
257 : : /* we're going to use a BufFile, so we need a ResourceOwner */
655 andres@anarazel.de 258 [ - + ]: 181 : Assert(AuxProcessResourceOwner != NULL);
259 [ + + - + ]: 181 : Assert(CurrentResourceOwner == AuxProcessResourceOwner ||
260 : : CurrentResourceOwner == NULL);
261 : 181 : CurrentResourceOwner = AuxProcessResourceOwner;
262 : :
4972 heikki.linnakangas@i 263 : 181 : backup_started_in_recovery = RecoveryInProgress();
264 : :
2284 rhaas@postgresql.org 265 : 181 : InitializeBackupManifest(&manifest, opt->manifest,
266 : : opt->manifest_checksum_type);
267 : :
3035 magnus@hagander.net 268 : 181 : total_checksum_failures = 0;
269 : :
270 : : /* Allocate backup related variables. */
227 michael@paquier.xyz 271 : 181 : backup_state = palloc0_object(BackupState);
261 drowley@postgresql.o 272 : 181 : initStringInfo(&tablespace_map);
273 : :
1723 rhaas@postgresql.org 274 : 181 : basebackup_progress_wait_checkpoint();
1398 michael@paquier.xyz 275 : 181 : do_pg_backup_start(opt->label, opt->fastcheckpoint, &state.tablespaces,
276 : : backup_state, &tablespace_map);
277 : :
278 : 181 : state.startptr = backup_state->startpoint;
279 : 181 : state.starttli = backup_state->starttli;
280 : :
281 : : /*
282 : : * Once do_pg_backup_start has been called, ensure that any failure causes
283 : : * us to abort the backup so we don't "leak" a backup counter. For this
284 : : * reason, *all* functionality between do_pg_backup_start() and the end of
285 : : * do_pg_backup_stop() should be inside the error cleanup block!
286 : : */
287 : :
2410 rhaas@postgresql.org 288 [ + + ]: 181 : PG_ENSURE_ERROR_CLEANUP(do_pg_abort_backup, BoolGetDatum(false));
289 : : {
290 : : ListCell *lc;
291 : : tablespaceinfo *newti;
292 : :
293 : : /* If this is an incremental backup, execute preparatory steps. */
948 294 [ + + ]: 181 : if (ib != NULL)
295 : 12 : PrepareForIncrementalBackup(ib, backup_state);
296 : :
297 : : /* Add a node for the base directory at the end */
227 michael@paquier.xyz 298 : 181 : newti = palloc0_object(tablespaceinfo);
1389 drowley@postgresql.o 299 : 181 : newti->size = -1;
300 : 181 : state.tablespaces = lappend(state.tablespaces, newti);
301 : :
302 : : /*
303 : : * Calculate the total backup size by summing up the size of each
304 : : * tablespace
305 : : */
2335 fujii@postgresql.org 306 [ + - ]: 181 : if (opt->progress)
307 : : {
1723 rhaas@postgresql.org 308 : 181 : basebackup_progress_estimate_backup_size();
309 : :
310 [ + - + + : 399 : foreach(lc, state.tablespaces)
+ + ]
311 : : {
2335 fujii@postgresql.org 312 : 218 : tablespaceinfo *tmp = (tablespaceinfo *) lfirst(lc);
313 : :
2229 rhaas@postgresql.org 314 [ + + ]: 218 : if (tmp->path == NULL)
1723 315 : 181 : tmp->size = sendDir(sink, ".", 1, true, state.tablespaces,
316 : : true, NULL, InvalidOid, NULL);
317 : : else
318 : 37 : tmp->size = sendTablespace(sink, tmp->path, tmp->oid, true,
319 : : NULL, NULL);
320 : 218 : state.bytes_total += tmp->size;
321 : : }
322 : 181 : state.bytes_total_is_valid = true;
323 : : }
324 : :
325 : : /* notify basebackup sink about start of backup */
326 : 181 : bbsink_begin_backup(sink, &state, SINK_BUFFER_LENGTH);
327 : :
328 : : /* Send off our tablespaces one by one */
329 [ + - + + : 394 : foreach(lc, state.tablespaces)
+ + ]
330 : : {
5674 tgl@sss.pgh.pa.us 331 : 218 : tablespaceinfo *ti = (tablespaceinfo *) lfirst(lc);
332 : :
5295 simon@2ndQuadrant.co 333 [ + + ]: 218 : if (ti->path == NULL)
334 : : {
335 : : struct stat statbuf;
1900 tgl@sss.pgh.pa.us 336 : 181 : bool sendtblspclinks = true;
337 : : char *backup_label;
338 : :
1723 rhaas@postgresql.org 339 : 181 : bbsink_begin_archive(sink, "base.tar");
340 : :
341 : : /* In the main tar, include the backup_label first... */
1398 michael@paquier.xyz 342 : 181 : backup_label = build_backup_content(backup_state, false);
343 : 181 : sendFileWithContent(sink, BACKUP_LABEL_FILE,
344 : : backup_label, -1, &manifest);
345 : 181 : pfree(backup_label);
346 : :
347 : : /* Then the tablespace_map file, if required... */
2229 rhaas@postgresql.org 348 [ + + ]: 181 : if (opt->sendtblspcmapfile)
349 : : {
1398 michael@paquier.xyz 350 : 28 : sendFileWithContent(sink, TABLESPACE_MAP,
261 drowley@postgresql.o 351 : 28 : tablespace_map.data, -1, &manifest);
2229 rhaas@postgresql.org 352 : 28 : sendtblspclinks = false;
353 : : }
354 : :
355 : : /* Then the bulk of the files... */
1723 356 : 181 : sendDir(sink, ".", 1, false, state.tablespaces,
357 : : sendtblspclinks, &manifest, InvalidOid, ib);
358 : :
359 : : /* ... and pg_control after everything else. */
5295 simon@2ndQuadrant.co 360 [ - + ]: 176 : if (lstat(XLOG_CONTROL_FILE, &statbuf) != 0)
5295 simon@2ndQuadrant.co 361 [ # # ]:UBC 0 : ereport(ERROR,
362 : : (errcode_for_file_access(),
363 : : errmsg("could not stat file \"%s\": %m",
364 : : XLOG_CONTROL_FILE)));
1723 rhaas@postgresql.org 365 :CBC 176 : sendFile(sink, XLOG_CONTROL_FILE, XLOG_CONTROL_FILE, &statbuf,
366 : : false, InvalidOid, InvalidOid,
367 : : InvalidRelFileNumber, 0, &manifest, 0, NULL, 0);
368 : : }
369 : : else
370 : : {
1006 371 : 37 : char *archive_name = psprintf("%u.tar", ti->oid);
372 : :
1723 373 : 37 : bbsink_begin_archive(sink, archive_name);
374 : :
948 375 : 37 : sendTablespace(sink, ti->path, ti->oid, false, &manifest, ib);
376 : : }
377 : :
378 : : /*
379 : : * If we're including WAL, and this is the main data directory we
380 : : * don't treat this as the end of the tablespace. Instead, we will
381 : : * include the xlog files below and stop afterwards. This is safe
382 : : * since the main data directory is always sent *last*.
383 : : */
5655 magnus@hagander.net 384 [ + + + + ]: 213 : if (opt->includewal && ti->path == NULL)
385 : : {
1723 rhaas@postgresql.org 386 [ - + ]: 15 : Assert(lnext(state.tablespaces, lc) == NULL);
387 : : }
388 : : else
389 : : {
390 : : /* Properly terminate the tarfile. */
159 peter@eisentraut.org 391 : 198 : memset(sink->bbs_buffer, 0, TAR_NUM_TERMINATION_BLOCKS * TAR_BLOCK_SIZE);
392 : 198 : bbsink_archive_contents(sink, TAR_NUM_TERMINATION_BLOCKS * TAR_BLOCK_SIZE);
393 : :
394 : : /* OK, that's the end of the archive. */
1723 rhaas@postgresql.org 395 : 198 : bbsink_end_archive(sink);
396 : : }
397 : : }
398 : :
399 : 176 : basebackup_progress_wait_wal_archive(&state);
1398 michael@paquier.xyz 400 : 176 : do_pg_backup_stop(backup_state, !opt->nowait);
401 : :
402 : 176 : endptr = backup_state->stoppoint;
403 : 176 : endtli = backup_state->stoptli;
404 : :
405 : : /* Deallocate backup-related variables. */
261 drowley@postgresql.o 406 : 176 : pfree(tablespace_map.data);
1398 michael@paquier.xyz 407 : 176 : pfree(backup_state);
408 : : }
2410 rhaas@postgresql.org 409 [ - + ]: 177 : PG_END_ENSURE_ERROR_CLEANUP(do_pg_abort_backup, BoolGetDatum(false));
410 : :
411 : :
5655 magnus@hagander.net 412 [ + + ]: 176 : if (opt->includewal)
413 : : {
414 : : /*
415 : : * We've left the last tar file "open", so we can now append the
416 : : * required WAL files to it.
417 : : */
418 : : char pathbuf[MAXPGPATH];
419 : : XLogSegNo segno;
420 : : XLogSegNo startsegno;
421 : : XLogSegNo endsegno;
422 : : struct stat statbuf;
4951 heikki.linnakangas@i 423 : 15 : List *historyFileList = NIL;
424 : 15 : List *walFileList = NIL;
425 : : char firstoff[MAXFNAMELEN];
426 : : char lastoff[MAXFNAMELEN];
427 : : DIR *dir;
428 : : struct dirent *de;
429 : : ListCell *lc;
430 : : TimeLineID tli;
431 : :
1723 rhaas@postgresql.org 432 : 15 : basebackup_progress_transfer_wal();
433 : :
434 : : /*
435 : : * I'd rather not worry about timelines here, so scan pg_wal and
436 : : * include all WAL files in the range between 'startptr' and 'endptr',
437 : : * regardless of the timeline the file is stamped with. If there are
438 : : * some spurious WAL files belonging to timelines that don't belong in
439 : : * this server's history, they will be included too. Normally there
440 : : * shouldn't be such files, but if there are, there's little harm in
441 : : * including them.
442 : : */
443 : 15 : XLByteToSeg(state.startptr, startsegno, wal_segment_size);
444 : 15 : XLogFileName(firstoff, state.starttli, startsegno, wal_segment_size);
3231 andres@anarazel.de 445 : 15 : XLByteToPrevSeg(endptr, endsegno, wal_segment_size);
1730 rhaas@postgresql.org 446 : 15 : XLogFileName(lastoff, endtli, endsegno, wal_segment_size);
447 : :
3565 448 : 15 : dir = AllocateDir("pg_wal");
449 [ + + ]: 108 : while ((de = ReadDir(dir, "pg_wal")) != NULL)
450 : : {
451 : : /* Does it look like a WAL segment, and is it in the range? */
4096 heikki.linnakangas@i 452 [ + + ]: 93 : if (IsXLogFileName(de->d_name) &&
4951 453 [ + - ]: 33 : strcmp(de->d_name + 8, firstoff + 8) >= 0 &&
454 [ + + ]: 33 : strcmp(de->d_name + 8, lastoff + 8) <= 0)
455 : : {
456 : 15 : walFileList = lappend(walFileList, pstrdup(de->d_name));
457 : : }
458 : : /* Does it look like a timeline history file? */
4096 459 [ - + ]: 78 : else if (IsTLHistoryFileName(de->d_name))
460 : : {
4951 heikki.linnakangas@i 461 :UBC 0 : historyFileList = lappend(historyFileList, pstrdup(de->d_name));
462 : : }
463 : : }
4951 heikki.linnakangas@i 464 :CBC 15 : FreeDir(dir);
465 : :
466 : : /*
467 : : * Before we go any further, check that none of the WAL segments we
468 : : * need were removed.
469 : : */
1723 rhaas@postgresql.org 470 : 15 : CheckXLogRemoved(startsegno, state.starttli);
471 : :
472 : : /*
473 : : * Sort the WAL filenames. We want to send the files in order from
474 : : * oldest to newest, to reduce the chance that a file is recycled
475 : : * before we get a chance to send it over.
476 : : */
2566 tgl@sss.pgh.pa.us 477 : 15 : list_sort(walFileList, compareWalFileNames);
478 : :
479 : : /*
480 : : * There must be at least one xlog file in the pg_wal directory, since
481 : : * we are doing backup-including-xlog.
482 : : */
483 [ - + ]: 15 : if (walFileList == NIL)
4718 magnus@hagander.net 484 [ # # ]:UBC 0 : ereport(ERROR,
485 : : (errmsg("could not find any WAL files")));
486 : :
487 : : /*
488 : : * Sanity check: the first and last segment should cover startptr and
489 : : * endptr, with no gaps in between.
490 : : */
2566 tgl@sss.pgh.pa.us 491 :CBC 15 : XLogFromFileName((char *) linitial(walFileList),
492 : : &tli, &segno, wal_segment_size);
4951 heikki.linnakangas@i 493 [ - + ]: 15 : if (segno != startsegno)
494 : : {
495 : : char startfname[MAXFNAMELEN];
496 : :
1723 rhaas@postgresql.org 497 :UBC 0 : XLogFileName(startfname, state.starttli, startsegno,
498 : : wal_segment_size);
4951 heikki.linnakangas@i 499 [ # # ]: 0 : ereport(ERROR,
500 : : (errmsg("could not find WAL file \"%s\"", startfname)));
501 : : }
2566 tgl@sss.pgh.pa.us 502 [ + - + + :CBC 30 : foreach(lc, walFileList)
+ + ]
503 : : {
504 : 15 : char *walFileName = (char *) lfirst(lc);
4805 bruce@momjian.us 505 : 15 : XLogSegNo currsegno = segno;
506 : 15 : XLogSegNo nextsegno = segno + 1;
507 : :
2566 tgl@sss.pgh.pa.us 508 : 15 : XLogFromFileName(walFileName, &tli, &segno, wal_segment_size);
4951 heikki.linnakangas@i 509 [ + - - + ]: 15 : if (!(nextsegno == segno || currsegno == segno))
510 : : {
511 : : char nextfname[MAXFNAMELEN];
512 : :
1730 rhaas@postgresql.org 513 :UBC 0 : XLogFileName(nextfname, tli, nextsegno, wal_segment_size);
4951 heikki.linnakangas@i 514 [ # # ]: 0 : ereport(ERROR,
515 : : (errmsg("could not find WAL file \"%s\"", nextfname)));
516 : : }
517 : : }
4951 heikki.linnakangas@i 518 [ - + ]:CBC 15 : if (segno != endsegno)
519 : : {
520 : : char endfname[MAXFNAMELEN];
521 : :
1730 rhaas@postgresql.org 522 :UBC 0 : XLogFileName(endfname, endtli, endsegno, wal_segment_size);
4951 heikki.linnakangas@i 523 [ # # ]: 0 : ereport(ERROR,
524 : : (errmsg("could not find WAL file \"%s\"", endfname)));
525 : : }
526 : :
527 : : /* Ok, we have everything we need. Send the WAL files. */
2566 tgl@sss.pgh.pa.us 528 [ + - + + :CBC 30 : foreach(lc, walFileList)
+ + ]
529 : : {
530 : 15 : char *walFileName = (char *) lfirst(lc);
531 : : int fd;
532 : : ssize_t cnt;
4951 heikki.linnakangas@i 533 : 15 : pgoff_t len = 0;
534 : :
2566 tgl@sss.pgh.pa.us 535 : 15 : snprintf(pathbuf, MAXPGPATH, XLOGDIR "/%s", walFileName);
536 : 15 : XLogFromFileName(walFileName, &tli, &segno, wal_segment_size);
537 : :
2229 rhaas@postgresql.org 538 : 15 : fd = OpenTransientFile(pathbuf, O_RDONLY | PG_BINARY);
539 [ - + ]: 15 : if (fd < 0)
540 : : {
2952 michael@paquier.xyz 541 :UBC 0 : int save_errno = errno;
542 : :
543 : : /*
544 : : * Most likely reason for this is that the file was already
545 : : * removed by a checkpoint, so check for that to get a better
546 : : * error message.
547 : : */
4951 heikki.linnakangas@i 548 : 0 : CheckXLogRemoved(segno, tli);
549 : :
2952 michael@paquier.xyz 550 : 0 : errno = save_errno;
4951 heikki.linnakangas@i 551 [ # # ]: 0 : ereport(ERROR,
552 : : (errcode_for_file_access(),
553 : : errmsg("could not open file \"%s\": %m", pathbuf)));
554 : : }
555 : :
2229 rhaas@postgresql.org 556 [ - + ]:CBC 15 : if (fstat(fd, &statbuf) != 0)
4951 heikki.linnakangas@i 557 [ # # ]:UBC 0 : ereport(ERROR,
558 : : (errcode_for_file_access(),
559 : : errmsg("could not stat file \"%s\": %m",
560 : : pathbuf)));
3231 andres@anarazel.de 561 [ - + ]:CBC 15 : if (statbuf.st_size != wal_segment_size)
562 : : {
4951 heikki.linnakangas@i 563 :UBC 0 : CheckXLogRemoved(segno, tli);
564 [ # # ]: 0 : ereport(ERROR,
565 : : (errcode_for_file_access(),
566 : : errmsg("unexpected WAL file size \"%s\"", walFileName)));
567 : : }
568 : :
569 : : /* send the WAL file itself */
1723 rhaas@postgresql.org 570 :CBC 15 : _tarWriteHeader(sink, pathbuf, NULL, &statbuf, false);
571 : :
572 : 15 : while ((cnt = basebackup_read_file(fd, sink->bbs_buffer,
573 : 7680 : Min(sink->bbs_buffer_length,
574 : : wal_segment_size - len),
2229 575 [ + - ]: 7680 : len, pathbuf, true)) > 0)
576 : : {
4951 heikki.linnakangas@i 577 : 7680 : CheckXLogRemoved(segno, tli);
1723 rhaas@postgresql.org 578 : 7680 : bbsink_archive_contents(sink, cnt);
579 : :
4951 heikki.linnakangas@i 580 : 7680 : len += cnt;
581 : :
3231 andres@anarazel.de 582 [ + + ]: 7680 : if (len == wal_segment_size)
4951 heikki.linnakangas@i 583 : 15 : break;
584 : : }
585 : :
3231 andres@anarazel.de 586 [ - + ]: 15 : if (len != wal_segment_size)
587 : : {
4951 heikki.linnakangas@i 588 :UBC 0 : CheckXLogRemoved(segno, tli);
589 [ # # ]: 0 : ereport(ERROR,
590 : : (errcode_for_file_access(),
591 : : errmsg("unexpected WAL file size \"%s\"", walFileName)));
592 : : }
593 : :
594 : : /*
595 : : * wal_segment_size is a multiple of TAR_BLOCK_SIZE, so no need
596 : : * for padding.
597 : : */
2283 rhaas@postgresql.org 598 [ - + ]:CBC 15 : Assert(wal_segment_size % TAR_BLOCK_SIZE == 0);
599 : :
2229 600 : 15 : CloseTransientFile(fd);
601 : :
602 : : /*
603 : : * Mark file as archived, otherwise files can get archived again
604 : : * after promotion of a new node. This is in line with
605 : : * walreceiver.c always doing an XLogArchiveForceDone() after a
606 : : * complete segment.
607 : : */
2566 tgl@sss.pgh.pa.us 608 : 15 : StatusFilePath(pathbuf, walFileName, ".done");
985 michael@paquier.xyz 609 : 15 : sendFileWithContent(sink, pathbuf, "", -1, &manifest);
610 : : }
611 : :
612 : : /*
613 : : * Send timeline history files too. Only the latest timeline history
614 : : * file is required for recovery, and even that only if there happens
615 : : * to be a timeline switch in the first WAL segment that contains the
616 : : * checkpoint record, or if we're taking a base backup from a standby
617 : : * server and the target timeline changes while the backup is taken.
618 : : * But they are small and highly useful for debugging purposes, so
619 : : * better include them all, always.
620 : : */
4951 heikki.linnakangas@i 621 [ - + - - : 15 : foreach(lc, historyFileList)
- + ]
622 : : {
4805 bruce@momjian.us 623 :UBC 0 : char *fname = lfirst(lc);
624 : :
4951 heikki.linnakangas@i 625 : 0 : snprintf(pathbuf, MAXPGPATH, XLOGDIR "/%s", fname);
626 : :
627 [ # # ]: 0 : if (lstat(pathbuf, &statbuf) != 0)
628 [ # # ]: 0 : ereport(ERROR,
629 : : (errcode_for_file_access(),
630 : : errmsg("could not stat file \"%s\": %m", pathbuf)));
631 : :
1006 rhaas@postgresql.org 632 : 0 : sendFile(sink, pathbuf, pathbuf, &statbuf, false,
633 : : InvalidOid, InvalidOid, InvalidRelFileNumber, 0,
634 : : &manifest, 0, NULL, 0);
635 : :
636 : : /* unconditionally mark file as archived */
4221 andres@anarazel.de 637 : 0 : StatusFilePath(pathbuf, fname, ".done");
985 michael@paquier.xyz 638 : 0 : sendFileWithContent(sink, pathbuf, "", -1, &manifest);
639 : : }
640 : :
641 : : /* Properly terminate the tar file. */
159 peter@eisentraut.org 642 :CBC 15 : memset(sink->bbs_buffer, 0, TAR_NUM_TERMINATION_BLOCKS * TAR_BLOCK_SIZE);
643 : 15 : bbsink_archive_contents(sink, TAR_NUM_TERMINATION_BLOCKS * TAR_BLOCK_SIZE);
644 : :
645 : : /* OK, that's the end of the archive. */
1723 rhaas@postgresql.org 646 : 15 : bbsink_end_archive(sink);
647 : : }
648 : :
649 : 176 : AddWALInfoToBackupManifest(&manifest, state.startptr, state.starttli,
650 : : endptr, endtli);
651 : :
652 : 176 : SendBackupManifest(&manifest, sink);
653 : :
654 : 176 : bbsink_end_backup(sink, endptr, endtli);
655 : :
3035 magnus@hagander.net 656 [ + + ]: 176 : if (total_checksum_failures)
657 : : {
658 [ + + ]: 3 : if (total_checksum_failures > 1)
659 [ + - ]: 2 : ereport(WARNING,
660 : : (errmsg_plural("%lld total checksum verification failure",
661 : : "%lld total checksum verification failures",
662 : : total_checksum_failures,
663 : : total_checksum_failures)));
664 : :
665 [ + - ]: 3 : ereport(ERROR,
666 : : (errcode(ERRCODE_DATA_CORRUPTED),
667 : : errmsg("checksum verification failure during base backup")));
668 : : }
669 : :
670 : : /*
671 : : * Make sure to free the manifest before the resource owners as manifests
672 : : * use cryptohash contexts that may depend on resource owners (like
673 : : * OpenSSL).
674 : : */
2059 michael@paquier.xyz 675 : 173 : FreeBackupManifest(&manifest);
676 : :
677 : : /* clean up the resource owner we created */
655 andres@anarazel.de 678 : 173 : ReleaseAuxProcessResources(true);
5674 tgl@sss.pgh.pa.us 679 : 173 : }
680 : :
681 : : /*
682 : : * list_sort comparison function, to compare log/seg portion of WAL segment
683 : : * filenames, ignoring the timeline portion.
684 : : */
685 : : static int
2566 tgl@sss.pgh.pa.us 686 :UBC 0 : compareWalFileNames(const ListCell *a, const ListCell *b)
687 : : {
688 : 0 : char *fna = (char *) lfirst(a);
689 : 0 : char *fnb = (char *) lfirst(b);
690 : :
4951 heikki.linnakangas@i 691 : 0 : return strcmp(fna + 8, fnb + 8);
692 : : }
693 : :
694 : : /*
695 : : * Parse the base backup options passed down by the parser
696 : : */
697 : : static void
5662 magnus@hagander.net 698 :CBC 198 : parse_basebackup_options(List *options, basebackup_options *opt)
699 : : {
700 : : ListCell *lopt;
701 : 198 : bool o_label = false;
702 : 198 : bool o_progress = false;
1754 rhaas@postgresql.org 703 : 198 : bool o_checkpoint = false;
5645 magnus@hagander.net 704 : 198 : bool o_nowait = false;
5655 705 : 198 : bool o_wal = false;
948 rhaas@postgresql.org 706 : 198 : bool o_incremental = false;
4531 alvherre@alvh.no-ip. 707 : 198 : bool o_maxrate = false;
4092 andrew@dunslane.net 708 : 198 : bool o_tablespace_map = false;
3035 magnus@hagander.net 709 : 198 : bool o_noverify_checksums = false;
2304 rhaas@postgresql.org 710 : 198 : bool o_manifest = false;
711 : 198 : bool o_manifest_checksums = false;
1649 712 : 198 : bool o_target = false;
1712 713 : 198 : bool o_target_detail = false;
1593 714 : 198 : char *target_str = NULL;
715 : 198 : char *target_detail_str = NULL;
1643 716 : 198 : bool o_compression = false;
1585 717 : 198 : bool o_compression_detail = false;
718 : 198 : char *compression_detail_str = NULL;
719 : :
5660 magnus@hagander.net 720 [ + - + - : 2178 : MemSet(opt, 0, sizeof(*opt));
+ - + - +
+ ]
2304 rhaas@postgresql.org 721 : 198 : opt->manifest = MANIFEST_OPTION_NO;
722 : 198 : opt->manifest_checksum_type = CHECKSUM_TYPE_CRC32C;
1565 michael@paquier.xyz 723 : 198 : opt->compression = PG_COMPRESSION_NONE;
724 : 198 : opt->compression_specification.algorithm = PG_COMPRESSION_NONE;
725 : :
5662 magnus@hagander.net 726 [ + - + + : 1488 : foreach(lopt, options)
+ + ]
727 : : {
728 : 1293 : DefElem *defel = (DefElem *) lfirst(lopt);
729 : :
730 [ + + ]: 1293 : if (strcmp(defel->defname, "label") == 0)
731 : : {
732 [ - + ]: 198 : if (o_label)
5662 magnus@hagander.net 733 [ # # ]:UBC 0 : ereport(ERROR,
734 : : (errcode(ERRCODE_SYNTAX_ERROR),
735 : : errmsg("duplicate option \"%s\"", defel->defname)));
1754 rhaas@postgresql.org 736 :CBC 198 : opt->label = defGetString(defel);
5662 magnus@hagander.net 737 : 198 : o_label = true;
738 : : }
739 [ + + ]: 1095 : else if (strcmp(defel->defname, "progress") == 0)
740 : : {
741 [ - + ]: 198 : if (o_progress)
5662 magnus@hagander.net 742 [ # # ]:UBC 0 : ereport(ERROR,
743 : : (errcode(ERRCODE_SYNTAX_ERROR),
744 : : errmsg("duplicate option \"%s\"", defel->defname)));
1754 rhaas@postgresql.org 745 :CBC 198 : opt->progress = defGetBoolean(defel);
5662 magnus@hagander.net 746 : 198 : o_progress = true;
747 : : }
1754 rhaas@postgresql.org 748 [ + + ]: 897 : else if (strcmp(defel->defname, "checkpoint") == 0)
749 : : {
750 : 188 : char *optval = defGetString(defel);
751 : :
752 [ - + ]: 188 : if (o_checkpoint)
5662 magnus@hagander.net 753 [ # # ]:UBC 0 : ereport(ERROR,
754 : : (errcode(ERRCODE_SYNTAX_ERROR),
755 : : errmsg("duplicate option \"%s\"", defel->defname)));
1754 rhaas@postgresql.org 756 [ + - ]:CBC 188 : if (pg_strcasecmp(optval, "fast") == 0)
757 : 188 : opt->fastcheckpoint = true;
1754 rhaas@postgresql.org 758 [ # # ]:UBC 0 : else if (pg_strcasecmp(optval, "spread") == 0)
759 : 0 : opt->fastcheckpoint = false;
760 : : else
761 [ # # ]: 0 : ereport(ERROR,
762 : : (errcode(ERRCODE_SYNTAX_ERROR),
763 : : errmsg("unrecognized checkpoint type: \"%s\"",
764 : : optval)));
1754 rhaas@postgresql.org 765 :CBC 188 : o_checkpoint = true;
766 : : }
767 [ + + ]: 709 : else if (strcmp(defel->defname, "wait") == 0)
768 : : {
5645 magnus@hagander.net 769 [ - + ]: 189 : if (o_nowait)
5645 magnus@hagander.net 770 [ # # ]:UBC 0 : ereport(ERROR,
771 : : (errcode(ERRCODE_SYNTAX_ERROR),
772 : : errmsg("duplicate option \"%s\"", defel->defname)));
1754 rhaas@postgresql.org 773 :CBC 189 : opt->nowait = !defGetBoolean(defel);
5645 magnus@hagander.net 774 : 189 : o_nowait = true;
775 : : }
5655 776 [ + + ]: 520 : else if (strcmp(defel->defname, "wal") == 0)
777 : : {
778 [ - + ]: 19 : if (o_wal)
5655 magnus@hagander.net 779 [ # # ]:UBC 0 : ereport(ERROR,
780 : : (errcode(ERRCODE_SYNTAX_ERROR),
781 : : errmsg("duplicate option \"%s\"", defel->defname)));
1754 rhaas@postgresql.org 782 :CBC 19 : opt->includewal = defGetBoolean(defel);
5655 magnus@hagander.net 783 : 19 : o_wal = true;
784 : : }
948 rhaas@postgresql.org 785 [ + + ]: 501 : else if (strcmp(defel->defname, "incremental") == 0)
786 : : {
787 [ - + ]: 12 : if (o_incremental)
948 rhaas@postgresql.org 788 [ # # ]:UBC 0 : ereport(ERROR,
789 : : (errcode(ERRCODE_SYNTAX_ERROR),
790 : : errmsg("duplicate option \"%s\"", defel->defname)));
948 rhaas@postgresql.org 791 :CBC 12 : opt->incremental = defGetBoolean(defel);
792 [ + - - + ]: 12 : if (opt->incremental && !summarize_wal)
948 rhaas@postgresql.org 793 [ # # ]:UBC 0 : ereport(ERROR,
794 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
795 : : errmsg("incremental backups cannot be taken unless WAL summarization is enabled")));
948 rhaas@postgresql.org 796 :CBC 12 : o_incremental = true;
797 : : }
4531 alvherre@alvh.no-ip. 798 [ + + ]: 489 : else if (strcmp(defel->defname, "max_rate") == 0)
799 : : {
800 : : int64 maxrate;
801 : :
802 [ - + ]: 1 : if (o_maxrate)
4531 alvherre@alvh.no-ip. 803 [ # # ]:UBC 0 : ereport(ERROR,
804 : : (errcode(ERRCODE_SYNTAX_ERROR),
805 : : errmsg("duplicate option \"%s\"", defel->defname)));
806 : :
1754 rhaas@postgresql.org 807 :CBC 1 : maxrate = defGetInt64(defel);
4531 alvherre@alvh.no-ip. 808 [ + - - + ]: 1 : if (maxrate < MAX_RATE_LOWER || maxrate > MAX_RATE_UPPER)
4531 alvherre@alvh.no-ip. 809 [ # # ]:UBC 0 : ereport(ERROR,
810 : : (errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
811 : : errmsg("%" PRId64 " is outside the valid range for parameter \"%s\" (%d .. %d)",
812 : : maxrate, "MAX_RATE", MAX_RATE_LOWER, MAX_RATE_UPPER)));
813 : :
4531 alvherre@alvh.no-ip. 814 :CBC 1 : opt->maxrate = (uint32) maxrate;
815 : 1 : o_maxrate = true;
816 : : }
4092 andrew@dunslane.net 817 [ + + ]: 488 : else if (strcmp(defel->defname, "tablespace_map") == 0)
818 : : {
819 [ - + ]: 34 : if (o_tablespace_map)
4092 andrew@dunslane.net 820 [ # # ]:UBC 0 : ereport(ERROR,
821 : : (errcode(ERRCODE_SYNTAX_ERROR),
822 : : errmsg("duplicate option \"%s\"", defel->defname)));
1754 rhaas@postgresql.org 823 :CBC 34 : opt->sendtblspcmapfile = defGetBoolean(defel);
4092 andrew@dunslane.net 824 : 34 : o_tablespace_map = true;
825 : : }
1754 rhaas@postgresql.org 826 [ + + ]: 454 : else if (strcmp(defel->defname, "verify_checksums") == 0)
827 : : {
3035 magnus@hagander.net 828 [ - + ]: 1 : if (o_noverify_checksums)
3035 magnus@hagander.net 829 [ # # ]:UBC 0 : ereport(ERROR,
830 : : (errcode(ERRCODE_SYNTAX_ERROR),
831 : : errmsg("duplicate option \"%s\"", defel->defname)));
1754 rhaas@postgresql.org 832 :CBC 1 : noverify_checksums = !defGetBoolean(defel);
3035 magnus@hagander.net 833 : 1 : o_noverify_checksums = true;
834 : : }
2304 rhaas@postgresql.org 835 [ + + ]: 453 : else if (strcmp(defel->defname, "manifest") == 0)
836 : : {
1754 837 : 197 : char *optval = defGetString(defel);
838 : : bool manifest_bool;
839 : :
2304 840 [ - + ]: 197 : if (o_manifest)
2304 rhaas@postgresql.org 841 [ # # ]:UBC 0 : ereport(ERROR,
842 : : (errcode(ERRCODE_SYNTAX_ERROR),
843 : : errmsg("duplicate option \"%s\"", defel->defname)));
2304 rhaas@postgresql.org 844 [ + + ]:CBC 197 : if (parse_bool(optval, &manifest_bool))
845 : : {
846 [ + - ]: 196 : if (manifest_bool)
847 : 196 : opt->manifest = MANIFEST_OPTION_YES;
848 : : else
2304 rhaas@postgresql.org 849 :UBC 0 : opt->manifest = MANIFEST_OPTION_NO;
850 : : }
2304 rhaas@postgresql.org 851 [ + - ]:CBC 1 : else if (pg_strcasecmp(optval, "force-encode") == 0)
852 : 1 : opt->manifest = MANIFEST_OPTION_FORCE_ENCODE;
853 : : else
2304 rhaas@postgresql.org 854 [ # # ]:UBC 0 : ereport(ERROR,
855 : : (errcode(ERRCODE_SYNTAX_ERROR),
856 : : errmsg("unrecognized manifest option: \"%s\"",
857 : : optval)));
2304 rhaas@postgresql.org 858 :CBC 197 : o_manifest = true;
859 : : }
860 [ + + ]: 256 : else if (strcmp(defel->defname, "manifest_checksums") == 0)
861 : : {
1754 862 : 14 : char *optval = defGetString(defel);
863 : :
2304 864 [ - + ]: 14 : if (o_manifest_checksums)
2304 rhaas@postgresql.org 865 [ # # ]:UBC 0 : ereport(ERROR,
866 : : (errcode(ERRCODE_SYNTAX_ERROR),
867 : : errmsg("duplicate option \"%s\"", defel->defname)));
2304 rhaas@postgresql.org 868 [ + + ]:CBC 14 : if (!pg_checksum_parse_type(optval,
869 : : &opt->manifest_checksum_type))
870 [ + - ]: 2 : ereport(ERROR,
871 : : (errcode(ERRCODE_SYNTAX_ERROR),
872 : : errmsg("unrecognized checksum algorithm: \"%s\"",
873 : : optval)));
874 : 12 : o_manifest_checksums = true;
875 : : }
1649 876 [ + + ]: 242 : else if (strcmp(defel->defname, "target") == 0)
877 : : {
878 [ - + ]: 196 : if (o_target)
1649 rhaas@postgresql.org 879 [ # # ]:UBC 0 : ereport(ERROR,
880 : : (errcode(ERRCODE_SYNTAX_ERROR),
881 : : errmsg("duplicate option \"%s\"", defel->defname)));
1593 rhaas@postgresql.org 882 :CBC 196 : target_str = defGetString(defel);
1649 883 : 196 : o_target = true;
884 : : }
1712 885 [ + + ]: 46 : else if (strcmp(defel->defname, "target_detail") == 0)
886 : : {
887 : 8 : char *optval = defGetString(defel);
888 : :
889 [ - + ]: 8 : if (o_target_detail)
1712 rhaas@postgresql.org 890 [ # # ]:UBC 0 : ereport(ERROR,
891 : : (errcode(ERRCODE_SYNTAX_ERROR),
892 : : errmsg("duplicate option \"%s\"", defel->defname)));
1593 rhaas@postgresql.org 893 :CBC 8 : target_detail_str = optval;
1712 894 : 8 : o_target_detail = true;
895 : : }
1643 896 [ + + ]: 38 : else if (strcmp(defel->defname, "compression") == 0)
897 : : {
898 : 26 : char *optval = defGetString(defel);
899 : :
900 [ - + ]: 26 : if (o_compression)
1643 rhaas@postgresql.org 901 [ # # ]:UBC 0 : ereport(ERROR,
902 : : (errcode(ERRCODE_SYNTAX_ERROR),
903 : : errmsg("duplicate option \"%s\"", defel->defname)));
1565 michael@paquier.xyz 904 [ + + ]:CBC 26 : if (!parse_compress_algorithm(optval, &opt->compression))
1643 rhaas@postgresql.org 905 [ + - ]: 1 : ereport(ERROR,
906 : : (errcode(ERRCODE_SYNTAX_ERROR),
907 : : errmsg("unrecognized compression algorithm: \"%s\"",
908 : : optval)));
909 : 25 : o_compression = true;
910 : : }
1585 911 [ + - ]: 12 : else if (strcmp(defel->defname, "compression_detail") == 0)
912 : : {
913 [ - + ]: 12 : if (o_compression_detail)
1643 rhaas@postgresql.org 914 [ # # ]:UBC 0 : ereport(ERROR,
915 : : (errcode(ERRCODE_SYNTAX_ERROR),
916 : : errmsg("duplicate option \"%s\"", defel->defname)));
1585 rhaas@postgresql.org 917 :CBC 12 : compression_detail_str = defGetString(defel);
918 : 12 : o_compression_detail = true;
919 : : }
920 : : else
1643 rhaas@postgresql.org 921 [ # # ]:UBC 0 : ereport(ERROR,
922 : : (errcode(ERRCODE_SYNTAX_ERROR),
923 : : errmsg("unrecognized base backup option: \"%s\"",
924 : : defel->defname)));
925 : : }
926 : :
5662 magnus@hagander.net 927 [ - + ]:CBC 195 : if (opt->label == NULL)
5662 magnus@hagander.net 928 :UBC 0 : opt->label = "base backup";
2304 rhaas@postgresql.org 929 [ + + ]:CBC 195 : if (opt->manifest == MANIFEST_OPTION_NO)
930 : : {
931 [ - + ]: 1 : if (o_manifest_checksums)
2304 rhaas@postgresql.org 932 [ # # ]:UBC 0 : ereport(ERROR,
933 : : (errcode(ERRCODE_SYNTAX_ERROR),
934 : : errmsg("manifest checksums require a backup manifest")));
2304 rhaas@postgresql.org 935 :CBC 1 : opt->manifest_checksum_type = CHECKSUM_TYPE_NONE;
936 : : }
937 : :
1593 938 [ - + ]: 195 : if (target_str == NULL)
939 : : {
1593 rhaas@postgresql.org 940 [ # # ]:UBC 0 : if (target_detail_str != NULL)
1712 941 [ # # ]: 0 : ereport(ERROR,
942 : : (errcode(ERRCODE_SYNTAX_ERROR),
943 : : errmsg("target detail cannot be used without target")));
1593 944 : 0 : opt->use_copytblspc = true;
945 : 0 : opt->send_to_client = true;
946 : : }
1593 rhaas@postgresql.org 947 [ + + ]:CBC 195 : else if (strcmp(target_str, "client") == 0)
948 : : {
949 [ - + ]: 181 : if (target_detail_str != NULL)
1712 rhaas@postgresql.org 950 [ # # ]:UBC 0 : ereport(ERROR,
951 : : (errcode(ERRCODE_SYNTAX_ERROR),
952 : : errmsg("target \"%s\" does not accept a target detail",
953 : : target_str)));
1593 rhaas@postgresql.org 954 :CBC 181 : opt->send_to_client = true;
955 : : }
956 : : else
957 : 12 : opt->target_handle =
958 : 14 : BaseBackupGetTargetHandle(target_str, target_detail_str);
959 : :
1585 960 [ + + - + ]: 193 : if (o_compression_detail && !o_compression)
1643 rhaas@postgresql.org 961 [ # # ]:UBC 0 : ereport(ERROR,
962 : : (errcode(ERRCODE_SYNTAX_ERROR),
963 : : errmsg("compression detail cannot be specified unless compression is enabled")));
964 : :
1585 rhaas@postgresql.org 965 [ + + ]:CBC 193 : if (o_compression)
966 : : {
967 : : char *error_detail;
968 : :
1565 michael@paquier.xyz 969 : 23 : parse_compress_specification(opt->compression, compression_detail_str,
970 : : &opt->compression_specification);
971 : : error_detail =
972 : 23 : validate_compress_specification(&opt->compression_specification);
1585 rhaas@postgresql.org 973 [ + + ]: 23 : if (error_detail != NULL)
974 [ + - ]: 9 : ereport(ERROR,
975 : : errcode(ERRCODE_SYNTAX_ERROR),
976 : : errmsg("invalid compression specification: %s",
977 : : error_detail));
978 : : }
5662 magnus@hagander.net 979 : 184 : }
980 : :
981 : :
982 : : /*
983 : : * SendBaseBackup() - send a complete base backup.
984 : : *
985 : : * The function will put the system into backup mode like pg_backup_start()
986 : : * does, so that the backup is consistent even though we read directly from
987 : : * the filesystem, bypassing the buffer cache.
988 : : */
989 : : void
948 rhaas@postgresql.org 990 : 199 : SendBaseBackup(BaseBackupCmd *cmd, IncrementalBackupInfo *ib)
991 : : {
992 : : basebackup_options opt;
993 : : bbsink *sink;
1474 fujii@postgresql.org 994 : 199 : SessionBackupState status = get_backup_status();
995 : :
996 [ + + ]: 199 : if (status == SESSION_BACKUP_RUNNING)
997 [ + - ]: 1 : ereport(ERROR,
998 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
999 : : errmsg("a backup is already in progress in this session")));
1000 : :
5662 magnus@hagander.net 1001 : 198 : parse_basebackup_options(cmd->options, &opt);
1002 : :
5674 1003 : 184 : WalSndSetState(WALSNDSTATE_BACKUP);
1004 : :
5675 1005 [ + - ]: 184 : if (update_process_title)
1006 : : {
1007 : : char activitymsg[50];
1008 : :
1009 : 184 : snprintf(activitymsg, sizeof(activitymsg), "sending backup \"%s\"",
1010 : : opt.label);
2327 peter@eisentraut.org 1011 : 184 : set_ps_display(activitymsg);
1012 : : }
1013 : :
1014 : : /*
1015 : : * If we're asked to perform an incremental backup and the user has not
1016 : : * supplied a manifest, that's an ERROR.
1017 : : *
1018 : : * If we're asked to perform a full backup and the user did supply a
1019 : : * manifest, just ignore it.
1020 : : */
948 rhaas@postgresql.org 1021 [ + + ]: 184 : if (!opt.incremental)
1022 : 172 : ib = NULL;
1023 [ - + ]: 12 : else if (ib == NULL)
948 rhaas@postgresql.org 1024 [ # # ]:UBC 0 : ereport(ERROR,
1025 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1026 : : errmsg("must UPLOAD_MANIFEST before performing an incremental BASE_BACKUP")));
1027 : :
1028 : : /*
1029 : : * If the target is specifically 'client' then set up to stream the backup
1030 : : * to the client; otherwise, it's being sent someplace else and should not
1031 : : * be sent to the client. BaseBackupGetSink has the job of setting up a
1032 : : * sink to send the backup data wherever it needs to go.
1033 : : */
1593 rhaas@postgresql.org 1034 :CBC 184 : sink = bbsink_copystream_new(opt.send_to_client);
1035 [ + + ]: 184 : if (opt.target_handle != NULL)
1036 : 12 : sink = BaseBackupGetSink(opt.target_handle, sink);
1037 : :
1038 : : /* Set up network throttling, if client requested it */
1723 1039 [ + + ]: 181 : if (opt.maxrate > 0)
1040 : 1 : sink = bbsink_throttle_new(sink, opt.maxrate);
1041 : :
1042 : : /* Set up server-side compression, if client requested it */
1565 michael@paquier.xyz 1043 [ + + ]: 181 : if (opt.compression == PG_COMPRESSION_GZIP)
1585 rhaas@postgresql.org 1044 : 2 : sink = bbsink_gzip_new(sink, &opt.compression_specification);
1565 michael@paquier.xyz 1045 [ + + ]: 179 : else if (opt.compression == PG_COMPRESSION_LZ4)
1585 rhaas@postgresql.org 1046 : 3 : sink = bbsink_lz4_new(sink, &opt.compression_specification);
1565 michael@paquier.xyz 1047 [ - + ]: 176 : else if (opt.compression == PG_COMPRESSION_ZSTD)
1585 rhaas@postgresql.org 1048 :UBC 0 : sink = bbsink_zstd_new(sink, &opt.compression_specification);
1049 : :
1050 : : /* Set up progress reporting. */
354 msawada@postgresql.o 1051 :CBC 181 : sink = bbsink_progress_new(sink, opt.progress, opt.incremental);
1052 : :
1053 : : /*
1054 : : * Perform the base backup, but make sure we clean up the bbsink even if
1055 : : * an error occurs.
1056 : : */
1723 rhaas@postgresql.org 1057 [ + + ]: 181 : PG_TRY();
1058 : : {
948 1059 : 181 : perform_base_backup(&opt, sink, ib);
1060 : : }
1723 1061 : 4 : PG_FINALLY();
1062 : : {
1063 : 177 : bbsink_cleanup(sink);
1064 : : }
1065 [ + + ]: 177 : PG_END_TRY();
5651 magnus@hagander.net 1066 : 173 : }
1067 : :
1068 : : /*
1069 : : * Inject a file with given name and content in the output tar stream.
1070 : : *
1071 : : * "len" can optionally be set to an arbitrary length of data sent. If set
1072 : : * to -1, the content sent is treated as a string with strlen() as length.
1073 : : */
1074 : : static void
1723 rhaas@postgresql.org 1075 : 224 : sendFileWithContent(bbsink *sink, const char *filename, const char *content,
1076 : : int len, backup_manifest_info *manifest)
1077 : : {
1078 : : struct stat statbuf;
985 michael@paquier.xyz 1079 : 224 : int bytes_done = 0;
1080 : : pg_checksum_context checksum_ctx;
1081 : :
2061 1082 [ - + ]: 224 : if (pg_checksum_init(&checksum_ctx, manifest->checksum_type) < 0)
2061 michael@paquier.xyz 1083 [ # # ]:UBC 0 : elog(ERROR, "could not initialize checksum of file \"%s\"",
1084 : : filename);
1085 : :
985 michael@paquier.xyz 1086 [ + - ]:CBC 224 : if (len < 0)
1087 : 224 : len = strlen(content);
1088 : :
1089 : : /*
1090 : : * Construct a stat struct for the file we're injecting in the tar.
1091 : : */
1092 : :
1093 : : /* Windows doesn't have the concept of uid and gid */
1094 : : #ifdef WIN32
1095 : : statbuf.st_uid = 0;
1096 : : statbuf.st_gid = 0;
1097 : : #else
5654 heikki.linnakangas@i 1098 : 224 : statbuf.st_uid = geteuid();
1099 : 224 : statbuf.st_gid = getegid();
1100 : : #endif
1101 : 224 : statbuf.st_mtime = time(NULL);
3031 sfrost@snowman.net 1102 : 224 : statbuf.st_mode = pg_file_create_mode;
5654 heikki.linnakangas@i 1103 : 224 : statbuf.st_size = len;
1104 : :
1723 rhaas@postgresql.org 1105 : 224 : _tarWriteHeader(sink, filename, NULL, &statbuf, false);
1106 : :
180 peter@eisentraut.org 1107 [ - + ]: 224 : if (pg_checksum_update(&checksum_ctx, (const uint8 *) content, len) < 0)
1723 rhaas@postgresql.org 1108 [ # # ]:UBC 0 : elog(ERROR, "could not update checksum of file \"%s\"",
1109 : : filename);
1110 : :
1723 rhaas@postgresql.org 1111 [ + + ]:CBC 411 : while (bytes_done < len)
1112 : : {
1113 : 187 : size_t remaining = len - bytes_done;
1114 : 187 : size_t nbytes = Min(sink->bbs_buffer_length, remaining);
1115 : :
1116 : 187 : memcpy(sink->bbs_buffer, content, nbytes);
1117 : 187 : bbsink_archive_contents(sink, nbytes);
1118 : 187 : bytes_done += nbytes;
1321 1119 : 187 : content += nbytes;
1120 : : }
1121 : :
1723 1122 : 224 : _tarWritePadding(sink, len);
1123 : :
1006 1124 : 224 : AddFileToBackupManifest(manifest, InvalidOid, filename, len,
2284 1125 : 224 : (pg_time_t) statbuf.st_mtime, &checksum_ctx);
5654 heikki.linnakangas@i 1126 : 224 : }
1127 : :
1128 : : /*
1129 : : * Include the tablespace directory pointed to by 'path' in the output tar
1130 : : * stream. If 'sizeonly' is true, we just calculate a total length and return
1131 : : * it, without actually sending anything.
1132 : : *
1133 : : * Only used to send auxiliary tablespaces, not PGDATA.
1134 : : */
1135 : : static int64
1006 rhaas@postgresql.org 1136 : 74 : sendTablespace(bbsink *sink, char *path, Oid spcoid, bool sizeonly,
1137 : : backup_manifest_info *manifest, IncrementalBackupInfo *ib)
1138 : : {
1139 : : int64 size;
1140 : : char pathbuf[MAXPGPATH];
1141 : : struct stat statbuf;
1142 : :
1143 : : /*
1144 : : * 'path' points to the tablespace location, but we only want to include
1145 : : * the version directory in it that belongs to us.
1146 : : */
4870 heikki.linnakangas@i 1147 : 74 : snprintf(pathbuf, sizeof(pathbuf), "%s/%s", path,
1148 : : TABLESPACE_VERSION_DIRECTORY);
1149 : :
1150 : : /*
1151 : : * Store a directory entry in the tar file so we get the permissions
1152 : : * right.
1153 : : */
1154 [ - + ]: 74 : if (lstat(pathbuf, &statbuf) != 0)
1155 : : {
4870 heikki.linnakangas@i 1156 [ # # ]:UBC 0 : if (errno != ENOENT)
1157 [ # # ]: 0 : ereport(ERROR,
1158 : : (errcode_for_file_access(),
1159 : : errmsg("could not stat file or directory \"%s\": %m",
1160 : : pathbuf)));
1161 : :
1162 : : /* If the tablespace went away while scanning, it's no error. */
1163 : 0 : return 0;
1164 : : }
1165 : :
1723 rhaas@postgresql.org 1166 :CBC 74 : size = _tarWriteHeader(sink, TABLESPACE_VERSION_DIRECTORY, NULL, &statbuf,
1167 : : sizeonly);
1168 : :
1169 : : /* Send all the files in the tablespace version directory */
1170 : 74 : size += sendDir(sink, pathbuf, strlen(path), sizeonly, NIL, true, manifest,
1171 : : spcoid, ib);
1172 : :
4870 heikki.linnakangas@i 1173 : 74 : return size;
1174 : : }
1175 : :
1176 : : /*
1177 : : * Include all files from the given directory in the output tar stream. If
1178 : : * 'sizeonly' is true, we just calculate a total length and return it, without
1179 : : * actually sending anything.
1180 : : *
1181 : : * Omit any directory in the tablespaces list, to avoid backing up
1182 : : * tablespaces twice when they were created inside PGDATA.
1183 : : *
1184 : : * If sendtblspclinks is true, we need to include symlink
1185 : : * information in the tar file. If not, we can skip that
1186 : : * as it will be sent separately in the tablespace_map file.
1187 : : */
1188 : : static int64
1723 rhaas@postgresql.org 1189 : 6257 : sendDir(bbsink *sink, const char *path, int basepathlen, bool sizeonly,
1190 : : List *tablespaces, bool sendtblspclinks, backup_manifest_info *manifest,
1191 : : Oid spcoid, IncrementalBackupInfo *ib)
1192 : : {
1193 : : DIR *dir;
1194 : : struct dirent *de;
1195 : : char pathbuf[MAXPGPATH * 2];
1196 : : struct stat statbuf;
5675 magnus@hagander.net 1197 : 6257 : int64 size = 0;
1198 : : const char *lastDir; /* Split last dir from parent path. */
984 rhaas@postgresql.org 1199 : 6257 : bool isRelationDir = false; /* Does directory contain relations? */
948 1200 : 6257 : bool isGlobalDir = false;
984 1201 : 6257 : Oid dboid = InvalidOid;
948 1202 : 6257 : BlockNumber *relative_block_numbers = NULL;
1203 : :
1204 : : /*
1205 : : * Since this array is relatively large, avoid putting it on the stack.
1206 : : * But we don't need it at all if this is not an incremental backup.
1207 : : */
1208 [ + + ]: 6257 : if (ib != NULL)
227 michael@paquier.xyz 1209 : 208 : relative_block_numbers = palloc_array(BlockNumber, RELSEG_SIZE);
1210 : :
1211 : : /*
1212 : : * Determine if the current path is a database directory that can contain
1213 : : * relations.
1214 : : *
1215 : : * Start by finding the location of the delimiter between the parent path
1216 : : * and the current path.
1217 : : */
3046 teodor@sigaev.ru 1218 : 6257 : lastDir = last_dir_separator(path);
1219 : :
1220 : : /* Does this path look like a database path (i.e. all digits)? */
1221 [ + + ]: 6257 : if (lastDir != NULL &&
1222 [ + + ]: 5895 : strspn(lastDir + 1, "0123456789") == strlen(lastDir + 1))
1223 : 1158 : {
1224 : : /* Part of path that contains the parent directory. */
3012 tgl@sss.pgh.pa.us 1225 : 1158 : int parentPathLen = lastDir - path;
1226 : :
1227 : : /*
1228 : : * Mark path as a database directory if the parent path is either
1229 : : * $PGDATA/base or a tablespace version path.
1230 : : */
3046 teodor@sigaev.ru 1231 [ + + ]: 1158 : if (strncmp(path, "./base", parentPathLen) == 0 ||
1232 [ + - ]: 52 : (parentPathLen >= (sizeof(TABLESPACE_VERSION_DIRECTORY) - 1) &&
1233 [ + - ]: 52 : strncmp(lastDir - (sizeof(TABLESPACE_VERSION_DIRECTORY) - 1),
1234 : : TABLESPACE_VERSION_DIRECTORY,
1235 : : sizeof(TABLESPACE_VERSION_DIRECTORY) - 1) == 0))
1236 : : {
984 rhaas@postgresql.org 1237 : 1158 : isRelationDir = true;
1238 : 1158 : dboid = atooid(lastDir + 1);
1239 : : }
1240 : : }
1241 [ + + ]: 5099 : else if (strcmp(path, "./global") == 0)
1242 : : {
1243 : 359 : isRelationDir = true;
948 1244 : 359 : isGlobalDir = true;
1245 : : }
1246 : :
5675 magnus@hagander.net 1247 : 6257 : dir = AllocateDir(path);
1248 [ + + ]: 408943 : while ((de = ReadDir(dir, path)) != NULL)
1249 : : {
1250 : : int excludeIdx;
1251 : : bool excludeFound;
984 rhaas@postgresql.org 1252 : 402695 : RelFileNumber relfilenumber = InvalidRelFileNumber;
1253 : 402695 : ForkNumber relForkNum = InvalidForkNumber;
1254 : 402695 : unsigned segno = 0;
1255 : 402695 : bool isRelationFile = false;
1256 : :
1257 : : /* Skip special stuff */
5675 magnus@hagander.net 1258 [ + + + + ]: 402695 : if (strcmp(de->d_name, ".") == 0 || strcmp(de->d_name, "..") == 0)
1259 : 17691 : continue;
1260 : :
1261 : : /* Skip temporary files */
heikki.linnakangas@i 1262 [ + + ]: 390193 : if (strncmp(de->d_name,
1263 : : PG_TEMP_FILE_PREFIX,
1264 : : strlen(PG_TEMP_FILE_PREFIX)) == 0)
1265 : 357 : continue;
1266 : :
1267 : : /* Skip macOS system files */
893 dgustafsson@postgres 1268 [ + + ]: 389836 : if (strcmp(de->d_name, ".DS_Store") == 0)
1269 : 68 : continue;
1270 : :
1271 : : /*
1272 : : * Check if the postmaster has signaled us to exit, and abort with an
1273 : : * error in that case. The error handler further up will call
1274 : : * do_pg_abort_backup() for us. Also check that if the backup was
1275 : : * started while still in recovery, the server wasn't promoted.
1276 : : * do_pg_backup_stop() will check that too, but it's better to stop
1277 : : * the backup early than continue to the end and fail there.
1278 : : */
4972 heikki.linnakangas@i 1279 [ + + ]: 389768 : CHECK_FOR_INTERRUPTS();
1280 [ - + ]: 389764 : if (RecoveryInProgress() != backup_started_in_recovery)
5671 magnus@hagander.net 1281 [ # # ]:UBC 0 : ereport(ERROR,
1282 : : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1283 : : errmsg("the standby was promoted during online backup"),
1284 : : errhint("This means that the backup being taken is corrupt "
1285 : : "and should not be used. "
1286 : : "Try taking another online backup.")));
1287 : :
1288 : : /* Scan for files that should be excluded */
3587 peter_e@gmx.net 1289 :CBC 389764 : excludeFound = false;
2343 michael@paquier.xyz 1290 [ + + ]: 3502480 : for (excludeIdx = 0; excludeFiles[excludeIdx].name != NULL; excludeIdx++)
1291 : : {
1292 : 3114134 : int cmplen = strlen(excludeFiles[excludeIdx].name);
1293 : :
1294 [ + + ]: 3114134 : if (!excludeFiles[excludeIdx].match_prefix)
1295 : 2724502 : cmplen++;
1296 [ + + ]: 3114134 : if (strncmp(de->d_name, excludeFiles[excludeIdx].name, cmplen) == 0)
1297 : : {
3587 peter_e@gmx.net 1298 [ + + ]: 1418 : elog(DEBUG1, "file \"%s\" excluded from backup", de->d_name);
1299 : 1418 : excludeFound = true;
1300 : 1418 : break;
1301 : : }
1302 : : }
1303 : :
1304 [ + + ]: 389764 : if (excludeFound)
5675 magnus@hagander.net 1305 : 1418 : continue;
1306 : :
1307 : : /*
1308 : : * If there could be non-temporary relation files in this directory,
1309 : : * try to parse the filename.
1310 : : */
984 rhaas@postgresql.org 1311 [ + + ]: 388346 : if (isRelationDir)
1312 : : isRelationFile =
1313 : 375798 : parse_filename_for_nontemp_relation(de->d_name,
1314 : : &relfilenumber,
1315 : : &relForkNum, &segno);
1316 : :
1317 : : /* Exclude all forks for unlogged tables except the init fork */
1318 [ + + + + ]: 388346 : if (isRelationFile && relForkNum != INIT_FORKNUM)
1319 : : {
1320 : : char initForkFile[MAXPGPATH];
1321 : :
1322 : : /*
1323 : : * If any other type of fork, check if there is an init fork with
1324 : : * the same RelFileNumber. If so, the file can be excluded.
1325 : : */
1326 : 372753 : snprintf(initForkFile, sizeof(initForkFile), "%s/%u_init",
1327 : : path, relfilenumber);
1328 : :
1329 [ + + ]: 372753 : if (lstat(initForkFile, &statbuf) == 0)
1330 : : {
1331 [ - + ]: 81 : elog(DEBUG2,
1332 : : "unlogged relation file \"%s\" excluded from backup",
1333 : : de->d_name);
1334 : :
1335 : 81 : continue;
1336 : : }
1337 : : }
1338 : :
1339 : : /* Exclude temporary relations */
1340 [ + + + + ]: 388265 : if (OidIsValid(dboid) && looks_like_temp_rel_name(de->d_name))
1341 : : {
3042 teodor@sigaev.ru 1342 [ - + ]: 36 : elog(DEBUG2,
1343 : : "temporary relation file \"%s\" excluded from backup",
1344 : : de->d_name);
1345 : :
1346 : 36 : continue;
1347 : : }
1348 : :
3392 peter_e@gmx.net 1349 : 388229 : snprintf(pathbuf, sizeof(pathbuf), "%s/%s", path, de->d_name);
1350 : :
1351 : : /* Skip pg_control here to back up it last */
474 fujii@postgresql.org 1352 [ + + ]: 388229 : if (strcmp(pathbuf, "./" XLOG_CONTROL_FILE) == 0)
5295 simon@2ndQuadrant.co 1353 : 358 : continue;
1354 : :
5675 magnus@hagander.net 1355 [ - + ]: 387871 : if (lstat(pathbuf, &statbuf) != 0)
1356 : : {
5675 magnus@hagander.net 1357 [ # # ]:UBC 0 : if (errno != ENOENT)
1358 [ # # ]: 0 : ereport(ERROR,
1359 : : (errcode_for_file_access(),
1360 : : errmsg("could not stat file or directory \"%s\": %m",
1361 : : pathbuf)));
1362 : :
1363 : : /* If the file went away while scanning, it's not an error. */
1364 : 0 : continue;
1365 : : }
1366 : :
1367 : : /* Scan for directories whose contents should be excluded */
3587 peter_e@gmx.net 1368 :CBC 387871 : excludeFound = false;
1369 [ + + ]: 3092905 : for (excludeIdx = 0; excludeDirContents[excludeIdx] != NULL; excludeIdx++)
1370 : : {
1371 [ + + ]: 2707547 : if (strcmp(de->d_name, excludeDirContents[excludeIdx]) == 0)
1372 : : {
1373 [ + + ]: 2513 : elog(DEBUG1, "contents of directory \"%s\" excluded from backup", de->d_name);
1747 rhaas@postgresql.org 1374 : 2513 : convert_link_to_directory(pathbuf, &statbuf);
1723 1375 : 2513 : size += _tarWriteHeader(sink, pathbuf + basepathlen + 1, NULL,
1376 : : &statbuf, sizeonly);
3587 peter_e@gmx.net 1377 : 2513 : excludeFound = true;
1378 : 2513 : break;
1379 : : }
1380 : : }
1381 : :
1382 [ + + ]: 387871 : if (excludeFound)
1383 : 2513 : continue;
1384 : :
1385 : : /*
1386 : : * We can skip pg_wal, the WAL segments need to be fetched from the
1387 : : * WAL archive anyway. But include it as an empty directory anyway, so
1388 : : * we get permissions right.
1389 : : */
3565 rhaas@postgresql.org 1390 [ + + ]: 385358 : if (strcmp(pathbuf, "./pg_wal") == 0)
1391 : : {
1392 : : /* If pg_wal is a symlink, write it as a directory anyway */
1747 1393 : 358 : convert_link_to_directory(pathbuf, &statbuf);
1723 1394 : 358 : size += _tarWriteHeader(sink, pathbuf + basepathlen + 1, NULL,
1395 : : &statbuf, sizeonly);
1396 : :
1397 : : /*
1398 : : * Also send archive_status and summaries directories (by
1399 : : * hackishly reusing statbuf from above ...).
1400 : : */
1401 : 358 : size += _tarWriteHeader(sink, "./pg_wal/archive_status", NULL,
1402 : : &statbuf, sizeonly);
948 1403 : 358 : size += _tarWriteHeader(sink, "./pg_wal/summaries", NULL,
1404 : : &statbuf, sizeonly);
1405 : :
3565 1406 : 358 : continue; /* don't recurse into pg_wal */
1407 : : }
1408 : :
1409 : : /* Allow symbolic links in pg_tblspc only */
1449 tmunro@postgresql.or 1410 [ + + + + ]: 385000 : if (strcmp(path, "./pg_tblspc") == 0 && S_ISLNK(statbuf.st_mode))
5675 magnus@hagander.net 1411 : 39 : {
1412 : : char linkpath[MAXPGPATH];
1413 : : ssize_t rllen;
1414 : :
5344 tgl@sss.pgh.pa.us 1415 : 39 : rllen = readlink(pathbuf, linkpath, sizeof(linkpath));
1416 [ - + ]: 39 : if (rllen < 0)
5675 magnus@hagander.net 1417 [ # # ]:UBC 0 : ereport(ERROR,
1418 : : (errcode_for_file_access(),
1419 : : errmsg("could not read symbolic link \"%s\": %m",
1420 : : pathbuf)));
5344 tgl@sss.pgh.pa.us 1421 [ - + ]:CBC 39 : if (rllen >= sizeof(linkpath))
5344 tgl@sss.pgh.pa.us 1422 [ # # ]:UBC 0 : ereport(ERROR,
1423 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
1424 : : errmsg("symbolic link \"%s\" target is too long",
1425 : : pathbuf)));
5344 tgl@sss.pgh.pa.us 1426 :CBC 39 : linkpath[rllen] = '\0';
1427 : :
1723 rhaas@postgresql.org 1428 : 39 : size += _tarWriteHeader(sink, pathbuf + basepathlen + 1, linkpath,
1429 : : &statbuf, sizeonly);
1430 : : }
5675 magnus@hagander.net 1431 [ + + ]: 384961 : else if (S_ISDIR(statbuf.st_mode))
1432 : : {
4582 1433 : 5876 : bool skip_this_dir = false;
1434 : : ListCell *lc;
1435 : :
1436 : : /*
1437 : : * Store a directory entry in the tar file so we can get the
1438 : : * permissions right.
1439 : : */
1723 rhaas@postgresql.org 1440 : 5876 : size += _tarWriteHeader(sink, pathbuf + basepathlen + 1, NULL, &statbuf,
1441 : : sizeonly);
1442 : :
1443 : : /*
1444 : : * Call ourselves recursively for a directory, unless it happens
1445 : : * to be a separate tablespace located within PGDATA.
1446 : : */
4582 magnus@hagander.net 1447 [ + + + + : 12889 : foreach(lc, tablespaces)
+ + ]
1448 : : {
1449 : 7041 : tablespaceinfo *ti = (tablespaceinfo *) lfirst(lc);
1450 : :
1451 : : /*
1452 : : * ti->rpath is the tablespace relative path within PGDATA, or
1453 : : * NULL if the tablespace has been properly located somewhere
1454 : : * else.
1455 : : *
1456 : : * Skip past the leading "./" in pathbuf when comparing.
1457 : : */
1458 [ + + + + ]: 7041 : if (ti->rpath && strcmp(ti->rpath, pathbuf + 2) == 0)
1459 : : {
1460 : 28 : skip_this_dir = true;
1461 : 28 : break;
1462 : : }
1463 : : }
1464 : :
1465 : : /*
1466 : : * skip sending directories inside pg_tblspc, if not required.
1467 : : */
4092 andrew@dunslane.net 1468 [ + + + + ]: 5876 : if (strcmp(pathbuf, "./pg_tblspc") == 0 && !sendtblspclinks)
1469 : 27 : skip_this_dir = true;
1470 : :
4582 magnus@hagander.net 1471 [ + + ]: 5876 : if (!skip_this_dir)
1723 rhaas@postgresql.org 1472 : 5821 : size += sendDir(sink, pathbuf, basepathlen, sizeonly, tablespaces,
1473 : : sendtblspclinks, manifest, spcoid, ib);
1474 : : }
5675 magnus@hagander.net 1475 [ + - ]: 379085 : else if (S_ISREG(statbuf.st_mode))
1476 : : {
4805 bruce@momjian.us 1477 : 379085 : bool sent = false;
948 rhaas@postgresql.org 1478 : 379085 : unsigned num_blocks_required = 0;
1479 : 379085 : unsigned truncation_block_length = 0;
1480 : : char tarfilenamebuf[MAXPGPATH * 2];
1481 : 379085 : char *tarfilename = pathbuf + basepathlen + 1;
1482 : 379085 : FileBackupMethod method = BACK_UP_FILE_FULLY;
1483 : :
1484 [ + + + + ]: 379085 : if (ib != NULL && isRelationFile)
1485 : : {
1486 : : Oid relspcoid;
1487 : : char *lookup_path;
1488 : :
1489 [ + + ]: 12822 : if (OidIsValid(spcoid))
1490 : : {
1491 : 9 : relspcoid = spcoid;
690 michael@paquier.xyz 1492 : 9 : lookup_path = psprintf("%s/%u/%s", PG_TBLSPC_DIR, spcoid,
1493 : : tarfilename);
1494 : : }
1495 : : else
1496 : : {
948 rhaas@postgresql.org 1497 [ + + ]: 12813 : if (isGlobalDir)
1498 : 672 : relspcoid = GLOBALTABLESPACE_OID;
1499 : : else
1500 : 12141 : relspcoid = DEFAULTTABLESPACE_OID;
1501 : 12813 : lookup_path = pstrdup(tarfilename);
1502 : : }
1503 : :
1504 : 12822 : method = GetFileBackupMethod(ib, lookup_path, dboid, relspcoid,
1505 : : relfilenumber, relForkNum,
1506 : 12822 : segno, statbuf.st_size,
1507 : : &num_blocks_required,
1508 : : relative_block_numbers,
1509 : : &truncation_block_length);
1510 [ + + ]: 12822 : if (method == BACK_UP_FILE_INCREMENTALLY)
1511 : : {
1512 : 8462 : statbuf.st_size =
1513 : 8462 : GetIncrementalFileSize(num_blocks_required);
1514 : 8462 : snprintf(tarfilenamebuf, sizeof(tarfilenamebuf),
1515 : : "%s/INCREMENTAL.%s",
1516 : 8462 : path + basepathlen + 1,
1517 : 8462 : de->d_name);
1518 : 8462 : tarfilename = tarfilenamebuf;
1519 : : }
1520 : :
1521 : 12822 : pfree(lookup_path);
1522 : : }
1523 : :
5675 magnus@hagander.net 1524 [ + + ]: 379085 : if (!sizeonly)
948 rhaas@postgresql.org 1525 [ + + ]: 187024 : sent = sendFile(sink, pathbuf, tarfilename, &statbuf,
1526 : : true, dboid, spcoid,
1527 : : relfilenumber, segno, manifest,
1528 : : num_blocks_required,
1529 : : method == BACK_UP_FILE_INCREMENTALLY ? relative_block_numbers : NULL,
1530 : : truncation_block_length);
1531 : :
4964 heikki.linnakangas@i 1532 [ + + + - ]: 379084 : if (sent || sizeonly)
1533 : : {
1534 : : /* Add size. */
2283 rhaas@postgresql.org 1535 : 379084 : size += statbuf.st_size;
1536 : :
1537 : : /* Pad to a multiple of the tar block size. */
1538 : 379084 : size += tarPaddingBytesRequired(statbuf.st_size);
1539 : :
1540 : : /* Size of the header for the file. */
1541 : 379084 : size += TAR_BLOCK_SIZE;
1542 : : }
1543 : : }
1544 : : else
5675 magnus@hagander.net 1545 [ # # ]:UBC 0 : ereport(WARNING,
1546 : : (errmsg("skipping special file \"%s\"", pathbuf)));
1547 : : }
1548 : :
948 rhaas@postgresql.org 1549 [ + + ]:CBC 6248 : if (relative_block_numbers != NULL)
1550 : 208 : pfree(relative_block_numbers);
1551 : :
5675 magnus@hagander.net 1552 : 6248 : FreeDir(dir);
1553 : 6248 : return size;
1554 : : }
1555 : :
1556 : : /*
1557 : : * Given the member, write the TAR header & send the file.
1558 : : *
1559 : : * If 'missing_ok' is true, will not throw an error if the file is not found.
1560 : : *
1561 : : * If dboid is anything other than InvalidOid then any checksum failures
1562 : : * detected will get reported to the cumulative stats system.
1563 : : *
1564 : : * If the file is to be sent incrementally, then num_incremental_blocks
1565 : : * should be the number of blocks to be sent, and incremental_blocks
1566 : : * an array of block numbers relative to the start of the current segment.
1567 : : * If the whole file is to be sent, then incremental_blocks should be NULL,
1568 : : * and num_incremental_blocks can have any value, as it will be ignored.
1569 : : *
1570 : : * Returns true if the file was successfully sent, false if 'missing_ok',
1571 : : * and the file did not exist.
1572 : : */
1573 : : static bool
1723 rhaas@postgresql.org 1574 : 187200 : sendFile(bbsink *sink, const char *readfilename, const char *tarfilename,
1575 : : struct stat *statbuf, bool missing_ok, Oid dboid, Oid spcoid,
1576 : : RelFileNumber relfilenumber, unsigned segno,
1577 : : backup_manifest_info *manifest, unsigned num_incremental_blocks,
1578 : : BlockNumber *incremental_blocks, unsigned truncation_block_length)
1579 : : {
1580 : : int fd;
3035 magnus@hagander.net 1581 : 187200 : BlockNumber blkno = 0;
1582 : 187200 : int checksum_failures = 0;
1583 : : off_t cnt;
1026 rhaas@postgresql.org 1584 : 187200 : pgoff_t bytes_done = 0;
3035 magnus@hagander.net 1585 : 187200 : bool verify_checksum = false;
1586 : : pg_checksum_context checksum_ctx;
948 rhaas@postgresql.org 1587 : 187200 : int ibindex = 0;
1588 : :
2061 michael@paquier.xyz 1589 [ - + ]: 187200 : if (pg_checksum_init(&checksum_ctx, manifest->checksum_type) < 0)
2061 michael@paquier.xyz 1590 [ # # ]:UBC 0 : elog(ERROR, "could not initialize checksum of file \"%s\"",
1591 : : readfilename);
1592 : :
2229 rhaas@postgresql.org 1593 :CBC 187200 : fd = OpenTransientFile(readfilename, O_RDONLY | PG_BINARY);
1594 [ - + ]: 187200 : if (fd < 0)
1595 : : {
4964 heikki.linnakangas@i 1596 [ # # # # ]:UBC 0 : if (errno == ENOENT && missing_ok)
1597 : 0 : return false;
5675 magnus@hagander.net 1598 [ # # ]: 0 : ereport(ERROR,
1599 : : (errcode_for_file_access(),
1600 : : errmsg("could not open file \"%s\": %m", readfilename)));
1601 : : }
1602 : :
1723 rhaas@postgresql.org 1603 :CBC 187200 : _tarWriteHeader(sink, tarfilename, NULL, statbuf, false);
1604 : :
1605 : : /*
1606 : : * Checksums are verified in multiples of BLCKSZ, so the buffer length
1607 : : * should be a multiple of the block size as well.
1608 : : */
1026 1609 [ - + ]: 187199 : Assert((sink->bbs_buffer_length % BLCKSZ) == 0);
1610 : :
1611 : : /*
1612 : : * If we weren't told not to verify checksums, and if checksums are
1613 : : * enabled for this cluster, and if this is a relation file, then verify
1614 : : * the checksum. We cannot at this point check if checksums are enabled
1615 : : * or disabled as that might change, thus we check at each point where we
1616 : : * could be validating a checksum.
1617 : : */
113 dgustafsson@postgres 1618 [ + + + + ]: 187199 : if (!noverify_checksums && RelFileNumberIsValid(relfilenumber))
984 rhaas@postgresql.org 1619 : 182872 : verify_checksum = true;
1620 : :
1621 : : /*
1622 : : * If we're sending an incremental file, write the file header.
1623 : : */
948 1624 [ + + ]: 187199 : if (incremental_blocks != NULL)
1625 : : {
1626 : 8462 : unsigned magic = INCREMENTAL_MAGIC;
1627 : 8462 : size_t header_bytes_done = 0;
1628 : : char padding[BLCKSZ];
1629 : : size_t paddinglen;
1630 : :
1631 : : /* Emit header data. */
1632 : 8462 : push_to_sink(sink, &checksum_ctx, &header_bytes_done,
1633 : : &magic, sizeof(magic));
1634 : 8462 : push_to_sink(sink, &checksum_ctx, &header_bytes_done,
1635 : : &num_incremental_blocks, sizeof(num_incremental_blocks));
1636 : 8462 : push_to_sink(sink, &checksum_ctx, &header_bytes_done,
1637 : : &truncation_block_length, sizeof(truncation_block_length));
1638 : 8462 : push_to_sink(sink, &checksum_ctx, &header_bytes_done,
1639 : : incremental_blocks,
1640 : : sizeof(BlockNumber) * num_incremental_blocks);
1641 : :
1642 : : /*
1643 : : * Add padding to align header to a multiple of BLCKSZ, but only if
1644 : : * the incremental file has some blocks, and the alignment is actually
1645 : : * needed (i.e. header is not already a multiple of BLCKSZ). If there
1646 : : * are no blocks we don't want to make the file unnecessarily large,
1647 : : * as that might make some filesystem optimizations impossible.
1648 : : */
832 tomas.vondra@postgre 1649 [ + + + - ]: 8462 : if ((num_incremental_blocks > 0) && (header_bytes_done % BLCKSZ != 0))
1650 : : {
841 1651 : 27 : paddinglen = (BLCKSZ - (header_bytes_done % BLCKSZ));
1652 : :
1653 : 27 : memset(padding, 0, paddinglen);
1654 : 27 : bytes_done += paddinglen;
1655 : :
1656 : 27 : push_to_sink(sink, &checksum_ctx, &header_bytes_done,
1657 : : padding, paddinglen);
1658 : : }
1659 : :
1660 : : /* Flush out any data still in the buffer so it's again empty. */
948 rhaas@postgresql.org 1661 [ + - ]: 8462 : if (header_bytes_done > 0)
1662 : : {
1663 : 8462 : bbsink_archive_contents(sink, header_bytes_done);
1664 [ - + ]: 8462 : if (pg_checksum_update(&checksum_ctx,
1665 : 8462 : (uint8 *) sink->bbs_buffer,
1666 : : header_bytes_done) < 0)
948 rhaas@postgresql.org 1667 [ # # ]:UBC 0 : elog(ERROR, "could not update checksum of base backup");
1668 : : }
1669 : :
1670 : : /* Update our notion of file position. */
948 rhaas@postgresql.org 1671 :CBC 8462 : bytes_done += sizeof(magic);
1672 : 8462 : bytes_done += sizeof(num_incremental_blocks);
1673 : 8462 : bytes_done += sizeof(truncation_block_length);
1674 : 8462 : bytes_done += sizeof(BlockNumber) * num_incremental_blocks;
1675 : : }
1676 : :
1677 : : /*
1678 : : * Loop until we read the amount of data the caller told us to expect. The
1679 : : * file could be longer, if it was extended while we were sending it, but
1680 : : * for a base backup we can ignore such extended data. It will be restored
1681 : : * from WAL.
1682 : : */
1683 : : while (1)
1684 : : {
1685 : : /*
1686 : : * Determine whether we've read all the data that we need, and if not,
1687 : : * read some more.
1688 : : */
1689 [ + + ]: 398680 : if (incremental_blocks == NULL)
1690 : : {
1691 : 390179 : size_t remaining = statbuf->st_size - bytes_done;
1692 : :
1693 : : /*
1694 : : * If we've read the required number of bytes, then it's time to
1695 : : * stop.
1696 : : */
1697 [ + + ]: 390179 : if (bytes_done >= statbuf->st_size)
1698 : 178737 : break;
1699 : :
1700 : : /*
1701 : : * Read as many bytes as will fit in the buffer, or however many
1702 : : * are left to read, whichever is less.
1703 : : */
1704 : 211442 : cnt = read_file_data_into_buffer(sink, readfilename, fd,
1705 : : bytes_done, remaining,
1706 : 211442 : blkno + segno * RELSEG_SIZE,
1707 : : verify_checksum,
1708 : : &checksum_failures);
1709 : : }
1710 : : else
1711 : : {
1712 : : BlockNumber relative_blkno;
1713 : :
1714 : : /*
1715 : : * If we've read all the blocks, then it's time to stop.
1716 : : */
1717 [ + + ]: 8501 : if (ibindex >= num_incremental_blocks)
1718 : 8462 : break;
1719 : :
1720 : : /*
1721 : : * Read just one block, whichever one is the next that we're
1722 : : * supposed to include.
1723 : : */
1724 : 39 : relative_blkno = incremental_blocks[ibindex++];
1725 : 39 : cnt = read_file_data_into_buffer(sink, readfilename, fd,
1726 : 39 : relative_blkno * BLCKSZ,
1727 : : BLCKSZ,
1728 : 39 : relative_blkno + segno * RELSEG_SIZE,
1729 : : verify_checksum,
1730 : : &checksum_failures);
1731 : :
1732 : : /*
1733 : : * If we get a partial read, that must mean that the relation is
1734 : : * being truncated. Ultimately, it should be truncated to a
1735 : : * multiple of BLCKSZ, since this path should only be reached for
1736 : : * relation files, but we might transiently observe an
1737 : : * intermediate value.
1738 : : *
1739 : : * It should be fine to treat this just as if the entire block had
1740 : : * been truncated away - i.e. fill this and all later blocks with
1741 : : * zeroes. WAL replay will fix things up.
1742 : : */
1743 [ - + ]: 39 : if (cnt < BLCKSZ)
948 rhaas@postgresql.org 1744 :UBC 0 : break;
1745 : : }
1746 : :
1747 : : /*
1748 : : * If the amount of data we were able to read was not a multiple of
1749 : : * BLCKSZ, we cannot verify checksums, which are block-level.
1750 : : */
113 dgustafsson@postgres 1751 [ + + + + :CBC 211481 : if (verify_checksum && DataChecksumsNeedVerify() && (cnt % BLCKSZ != 0))
- + ]
1752 : : {
3035 magnus@hagander.net 1753 [ # # ]:UBC 0 : ereport(WARNING,
1754 : : (errmsg("could not verify checksum in file \"%s\", block "
1755 : : "%u: read buffer size %d and page size %d "
1756 : : "differ",
1757 : : readfilename, blkno, (int) cnt, BLCKSZ)));
1758 : 0 : verify_checksum = false;
1759 : : }
1760 : :
1761 : : /*
1762 : : * If we hit end-of-file, a concurrent truncation must have occurred.
1763 : : * That's not an error condition, because WAL replay will fix things
1764 : : * up.
1765 : : */
1269 rhaas@postgresql.org 1766 [ - + ]:CBC 211481 : if (cnt == 0)
1269 rhaas@postgresql.org 1767 :UBC 0 : break;
1768 : :
1769 : : /* Update block number and # of bytes done for next loop iteration. */
1026 rhaas@postgresql.org 1770 :CBC 211481 : blkno += cnt / BLCKSZ;
1771 : 211481 : bytes_done += cnt;
1772 : :
1773 : : /*
1774 : : * Make sure incremental files with block data are properly aligned
1775 : : * (header is a multiple of BLCKSZ, blocks are BLCKSZ too).
1776 : : */
841 tomas.vondra@postgre 1777 [ + + + - : 211481 : Assert(!((incremental_blocks != NULL && num_incremental_blocks > 0) &&
- + ]
1778 : : (bytes_done % BLCKSZ != 0)));
1779 : :
1780 : : /* Archive the data we just read. */
1723 rhaas@postgresql.org 1781 : 211481 : bbsink_archive_contents(sink, cnt);
1782 : :
1783 : : /* Also feed it to the checksum machinery. */
1784 [ - + ]: 211481 : if (pg_checksum_update(&checksum_ctx,
1785 : 211481 : (uint8 *) sink->bbs_buffer, cnt) < 0)
2061 michael@paquier.xyz 1786 [ # # ]:UBC 0 : elog(ERROR, "could not update checksum of base backup");
1787 : : }
1788 : :
1789 : : /* If the file was truncated while we were sending it, pad it with zeros */
1026 rhaas@postgresql.org 1790 [ - + ]:CBC 187199 : while (bytes_done < statbuf->st_size)
1791 : : {
1026 rhaas@postgresql.org 1792 :UBC 0 : size_t remaining = statbuf->st_size - bytes_done;
1723 1793 : 0 : size_t nbytes = Min(sink->bbs_buffer_length, remaining);
1794 : :
1795 [ # # # # : 0 : MemSet(sink->bbs_buffer, 0, nbytes);
# # # # #
# ]
1796 [ # # ]: 0 : if (pg_checksum_update(&checksum_ctx,
1797 : 0 : (uint8 *) sink->bbs_buffer,
1798 : : nbytes) < 0)
1799 [ # # ]: 0 : elog(ERROR, "could not update checksum of base backup");
1800 : 0 : bbsink_archive_contents(sink, nbytes);
1026 1801 : 0 : bytes_done += nbytes;
1802 : : }
1803 : :
1804 : : /*
1805 : : * Pad to a block boundary, per tar format requirements. (This small piece
1806 : : * of data is probably not worth throttling, and is not checksummed
1807 : : * because it's not actually part of the file.)
1808 : : */
1026 rhaas@postgresql.org 1809 :CBC 187199 : _tarWritePadding(sink, bytes_done);
1810 : :
2229 1811 : 187199 : CloseTransientFile(fd);
1812 : :
3035 magnus@hagander.net 1813 [ + + ]: 187199 : if (checksum_failures > 1)
1814 : : {
1815 [ + - ]: 2 : ereport(WARNING,
1816 : : (errmsg_plural("file \"%s\" has a total of %d checksum verification failure",
1817 : : "file \"%s\" has a total of %d checksum verification failures",
1818 : : checksum_failures,
1819 : : readfilename, checksum_failures)));
1820 : :
482 andres@anarazel.de 1821 : 2 : pgstat_prepare_report_checksum_failure(dboid);
2661 magnus@hagander.net 1822 : 2 : pgstat_report_checksum_failures_in_db(dboid, checksum_failures);
1823 : : }
1824 : :
3035 1825 : 187199 : total_checksum_failures += checksum_failures;
1826 : :
2284 rhaas@postgresql.org 1827 : 187199 : AddFileToBackupManifest(manifest, spcoid, tarfilename, statbuf->st_size,
1828 : 187199 : (pg_time_t) statbuf->st_mtime, &checksum_ctx);
1829 : :
4964 heikki.linnakangas@i 1830 : 187199 : return true;
1831 : : }
1832 : :
1833 : : /*
1834 : : * Read some more data from the file into the bbsink's buffer, verifying
1835 : : * checksums as required.
1836 : : *
1837 : : * 'offset' is the file offset from which we should begin to read, and
1838 : : * 'length' is the amount of data that should be read. The actual amount
1839 : : * of data read will be less than the requested amount if the bbsink's
1840 : : * buffer isn't big enough to hold it all, or if the underlying file has
1841 : : * been truncated. The return value is the number of bytes actually read.
1842 : : *
1843 : : * 'blkno' is the block number of the first page in the bbsink's buffer
1844 : : * relative to the start of the relation.
1845 : : *
1846 : : * 'verify_checksum' determines if the user has asked to verify checksums, but
1847 : : * since data checksums can be disabled, or become disabled, we need to check
1848 : : * state before verifying individual pages. If we do this, we'll update
1849 : : * *checksum_failures and issue warnings as appropriate.
1850 : : */
1851 : : static off_t
1026 rhaas@postgresql.org 1852 : 211481 : read_file_data_into_buffer(bbsink *sink, const char *readfilename, int fd,
1853 : : off_t offset, size_t length, BlockNumber blkno,
1854 : : bool verify_checksum, int *checksum_failures)
1855 : : {
1856 : : off_t cnt;
1857 : : int i;
1858 : : char *page;
1859 : :
1860 : : /* Try to read some more data. */
1861 : 211481 : cnt = basebackup_read_file(fd, sink->bbs_buffer,
1862 : 211481 : Min(sink->bbs_buffer_length, length),
1863 : : offset, readfilename, true);
1864 : :
1865 : : /* Can't verify checksums if read length is not a multiple of BLCKSZ. */
1866 [ + + - + ]: 211481 : if (!verify_checksum || (cnt % BLCKSZ) != 0)
1867 : 4872 : return cnt;
1868 : :
1869 : : /* Verify checksum for each block. */
1870 [ + + ]: 706564 : for (i = 0; i < cnt / BLCKSZ; i++)
1871 : : {
1872 : : int reread_cnt;
1873 : : uint16 expected_checksum;
1874 : :
1875 : : /*
1876 : : * The data checksum state can change at any point, so we need to
1877 : : * re-check before each page.
1878 : : */
113 dgustafsson@postgres 1879 [ + + ]: 502413 : if (!DataChecksumsNeedVerify())
1880 : 2458 : return cnt;
1881 : :
1026 rhaas@postgresql.org 1882 : 499955 : page = sink->bbs_buffer + BLCKSZ * i;
1883 : :
1884 : : /* If the page is OK, go on to the next one. */
1885 [ + + ]: 499955 : if (verify_page_checksum(page, sink->bbs_state->startptr, blkno + i,
1886 : : &expected_checksum))
1887 : 499941 : continue;
1888 : :
1889 : : /*
1890 : : * Retry the block on the first failure. It's possible that we read
1891 : : * the first 4K page of the block just before postgres updated the
1892 : : * entire block so it ends up looking torn to us. If, before we retry
1893 : : * the read, the concurrent write of the block finishes, the page LSN
1894 : : * will be updated and we'll realize that we should ignore this block.
1895 : : *
1896 : : * There's no guarantee that this will actually happen, though: the
1897 : : * torn write could take an arbitrarily long time to complete.
1898 : : * Retrying multiple times wouldn't fix this problem, either, though
1899 : : * it would reduce the chances of it happening in practice. The only
1900 : : * real fix here seems to be to have some kind of interlock that
1901 : : * allows us to wait until we can be certain that no write to the
1902 : : * block is in progress. Since we don't have any such thing right now,
1903 : : * we just do this and hope for the best.
1904 : : *
1905 : : * The data checksum state may also have changed concurrently so check
1906 : : * again.
1907 : : */
113 dgustafsson@postgres 1908 [ - + ]: 14 : if (!DataChecksumsNeedVerify())
113 dgustafsson@postgres 1909 :UBC 0 : return cnt;
1026 rhaas@postgresql.org 1910 :CBC 14 : reread_cnt =
1911 : 14 : basebackup_read_file(fd, sink->bbs_buffer + BLCKSZ * i,
1912 : 14 : BLCKSZ, offset + BLCKSZ * i,
1913 : : readfilename, false);
1914 [ - + ]: 14 : if (reread_cnt == 0)
1915 : : {
1916 : : /*
1917 : : * If we hit end-of-file, a concurrent truncation must have
1918 : : * occurred, so reduce cnt to reflect only the blocks already
1919 : : * processed and break out of this loop.
1920 : : */
1026 rhaas@postgresql.org 1921 :UBC 0 : cnt = BLCKSZ * i;
1922 : 0 : break;
1923 : : }
1924 : :
1925 : : /* If the page now looks OK, go on to the next one. */
1026 rhaas@postgresql.org 1926 [ - + ]:CBC 14 : if (verify_page_checksum(page, sink->bbs_state->startptr, blkno + i,
1927 : : &expected_checksum))
1026 rhaas@postgresql.org 1928 :UBC 0 : continue;
1929 : :
1930 : : /* Handle checksum failure. */
1026 rhaas@postgresql.org 1931 :CBC 14 : (*checksum_failures)++;
1932 [ + + ]: 14 : if (*checksum_failures <= 5)
1933 [ + - ]: 12 : ereport(WARNING,
1934 : : (errmsg("checksum verification failed in "
1935 : : "file \"%s\", block %u: calculated "
1936 : : "%X but expected %X",
1937 : : readfilename, blkno + i, expected_checksum,
1938 : : ((PageHeader) page)->pd_checksum)));
1939 [ + + ]: 14 : if (*checksum_failures == 5)
1940 [ + - ]: 2 : ereport(WARNING,
1941 : : (errmsg("further checksum verification "
1942 : : "failures in file \"%s\" will not "
1943 : : "be reported", readfilename)));
1944 : : }
1945 : :
1946 : 204151 : return cnt;
1947 : : }
1948 : :
1949 : : /*
1950 : : * Push data into a bbsink.
1951 : : *
1952 : : * It's better, when possible, to read data directly into the bbsink's buffer,
1953 : : * rather than using this function to copy it into the buffer; this function is
1954 : : * for cases where that approach is not practical.
1955 : : *
1956 : : * bytes_done should point to a count of the number of bytes that are
1957 : : * currently used in the bbsink's buffer. Upon return, the bytes identified by
1958 : : * data and length will have been copied into the bbsink's buffer, flushing
1959 : : * as required, and *bytes_done will have been updated accordingly. If the
1960 : : * buffer was flushed, the previous contents will also have been fed to
1961 : : * checksum_ctx.
1962 : : *
1963 : : * Note that after one or more calls to this function it is the caller's
1964 : : * responsibility to perform any required final flush.
1965 : : */
1966 : : static void
948 1967 : 33875 : push_to_sink(bbsink *sink, pg_checksum_context *checksum_ctx,
1968 : : size_t *bytes_done, void *data, size_t length)
1969 : : {
1970 [ + + ]: 33875 : while (length > 0)
1971 : : {
1972 : : size_t bytes_to_copy;
1973 : :
1974 : : /*
1975 : : * We use < here rather than <= so that if the data exactly fills the
1976 : : * remaining buffer space, we trigger a flush now.
1977 : : */
1978 [ + - ]: 25440 : if (length < sink->bbs_buffer_length - *bytes_done)
1979 : : {
1980 : : /* Append remaining data to buffer. */
1981 : 25440 : memcpy(sink->bbs_buffer + *bytes_done, data, length);
1982 : 25440 : *bytes_done += length;
1983 : 25440 : return;
1984 : : }
1985 : :
1986 : : /* Copy until buffer is full and flush it. */
948 rhaas@postgresql.org 1987 :UBC 0 : bytes_to_copy = sink->bbs_buffer_length - *bytes_done;
1988 : 0 : memcpy(sink->bbs_buffer + *bytes_done, data, bytes_to_copy);
1989 : 0 : data = ((char *) data) + bytes_to_copy;
1990 : 0 : length -= bytes_to_copy;
1991 : 0 : bbsink_archive_contents(sink, sink->bbs_buffer_length);
1992 [ # # ]: 0 : if (pg_checksum_update(checksum_ctx, (uint8 *) sink->bbs_buffer,
1993 : : sink->bbs_buffer_length) < 0)
1994 [ # # ]: 0 : elog(ERROR, "could not update checksum");
1995 : 0 : *bytes_done = 0;
1996 : : }
1997 : : }
1998 : :
1999 : : /*
2000 : : * Try to verify the checksum for the provided page, if it seems appropriate
2001 : : * to do so.
2002 : : *
2003 : : * Returns true if verification succeeds or if we decide not to check it,
2004 : : * and false if verification fails. When return false, it also sets
2005 : : * *expected_checksum to the computed value.
2006 : : */
2007 : : static bool
1026 rhaas@postgresql.org 2008 :CBC 499969 : verify_page_checksum(Page page, XLogRecPtr start_lsn, BlockNumber blkno,
2009 : : uint16 *expected_checksum)
2010 : : {
2011 : : PageHeader phdr;
2012 : : uint16 checksum;
2013 : :
2014 : : /*
2015 : : * Only check pages which have not been modified since the start of the
2016 : : * base backup. Otherwise, they might have been written only halfway and
2017 : : * the checksum would not be valid. However, replaying WAL would
2018 : : * reinstate the correct page in this case. We also skip completely new
2019 : : * pages, since they don't have a checksum yet.
2020 : : */
2021 [ + + + + ]: 499969 : if (PageIsNew(page) || PageGetLSN(page) >= start_lsn)
2022 : 1055 : return true;
2023 : :
113 dgustafsson@postgres 2024 [ - + ]: 498914 : if (!DataChecksumsNeedVerify())
113 dgustafsson@postgres 2025 :UBC 0 : return true;
2026 : :
2027 : : /* Perform the actual checksum calculation. */
1026 rhaas@postgresql.org 2028 :CBC 498914 : checksum = pg_checksum_page(page, blkno);
2029 : :
2030 : : /* See whether it matches the value from the page. */
2031 : 498914 : phdr = (PageHeader) page;
2032 [ + + ]: 498914 : if (phdr->pd_checksum == checksum)
2033 : 498886 : return true;
2034 : 28 : *expected_checksum = checksum;
2035 : 28 : return false;
2036 : : }
2037 : :
2038 : : static int64
1723 2039 : 197015 : _tarWriteHeader(bbsink *sink, const char *filename, const char *linktarget,
2040 : : struct stat *statbuf, bool sizeonly)
2041 : : {
2042 : : enum tarError rc;
2043 : :
3587 peter_e@gmx.net 2044 [ + + ]: 197015 : if (!sizeonly)
2045 : : {
2046 : : /*
2047 : : * As of this writing, the smallest supported block size is 1kB, which
2048 : : * is twice TAR_BLOCK_SIZE. Since the buffer size is required to be a
2049 : : * multiple of BLCKSZ, it should be safe to assume that the buffer is
2050 : : * large enough to fit an entire tar block. We double-check by means
2051 : : * of these assertions.
2052 : : */
2053 : : StaticAssertDecl(TAR_BLOCK_SIZE <= BLCKSZ,
2054 : : "BLCKSZ too small for tar block");
1723 rhaas@postgresql.org 2055 [ - + ]: 192188 : Assert(sink->bbs_buffer_length >= TAR_BLOCK_SIZE);
2056 : :
2057 : 192188 : rc = tarCreateHeader(sink->bbs_buffer, filename, linktarget,
2058 : : statbuf->st_size, statbuf->st_mode,
2059 : : statbuf->st_uid, statbuf->st_gid,
2060 : : statbuf->st_mtime);
2061 : :
3587 peter_e@gmx.net 2062 [ + + - - ]: 192188 : switch (rc)
2063 : : {
2064 : 192187 : case TAR_OK:
2065 : 192187 : break;
2066 : 1 : case TAR_NAME_TOO_LONG:
2067 [ + - ]: 1 : ereport(ERROR,
2068 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2069 : : errmsg("file name too long for tar format: \"%s\"",
2070 : : filename)));
2071 : : break;
3587 peter_e@gmx.net 2072 :UBC 0 : case TAR_SYMLINK_TOO_LONG:
2073 [ # # ]: 0 : ereport(ERROR,
2074 : : (errcode(ERRCODE_PROGRAM_LIMIT_EXCEEDED),
2075 : : errmsg("symbolic link target too long for tar format: "
2076 : : "file name \"%s\", target \"%s\"",
2077 : : filename, linktarget)));
2078 : : break;
2079 : 0 : default:
2080 [ # # ]: 0 : elog(ERROR, "unrecognized tar error: %d", rc);
2081 : : }
2082 : :
1723 rhaas@postgresql.org 2083 :CBC 192187 : bbsink_archive_contents(sink, TAR_BLOCK_SIZE);
2084 : : }
2085 : :
2086 : 197014 : return TAR_BLOCK_SIZE;
2087 : : }
2088 : :
2089 : : /*
2090 : : * Pad with zero bytes out to a multiple of TAR_BLOCK_SIZE.
2091 : : */
2092 : : static void
2093 : 187423 : _tarWritePadding(bbsink *sink, int len)
2094 : : {
2095 : 187423 : int pad = tarPaddingBytesRequired(len);
2096 : :
2097 : : /*
2098 : : * As in _tarWriteHeader, it should be safe to assume that the buffer is
2099 : : * large enough that we don't need to do this in multiple chunks.
2100 : : */
2101 [ - + ]: 187423 : Assert(sink->bbs_buffer_length >= TAR_BLOCK_SIZE);
2102 [ - + ]: 187423 : Assert(pad <= TAR_BLOCK_SIZE);
2103 : :
2104 [ + + ]: 187423 : if (pad > 0)
2105 : : {
2106 [ + - + + : 33008 : MemSet(sink->bbs_buffer, 0, pad);
+ - + - +
+ ]
2107 : 11207 : bbsink_archive_contents(sink, pad);
2108 : : }
4531 alvherre@alvh.no-ip. 2109 : 187423 : }
2110 : :
2111 : : /*
2112 : : * If the entry in statbuf is a link, then adjust statbuf to make it look like a
2113 : : * directory, so that it will be written that way.
2114 : : */
2115 : : static void
1723 rhaas@postgresql.org 2116 : 2871 : convert_link_to_directory(const char *pathbuf, struct stat *statbuf)
2117 : : {
2118 : : /* If symlink, write it as a directory anyway */
2119 [ + + ]: 2871 : if (S_ISLNK(statbuf->st_mode))
2120 : 66 : statbuf->st_mode = S_IFDIR | pg_dir_create_mode;
2335 fujii@postgresql.org 2121 : 2871 : }
2122 : :
2123 : : /*
2124 : : * Read some data from a file, setting a wait event and reporting any error
2125 : : * encountered.
2126 : : *
2127 : : * If partial_read_ok is false, also report an error if the number of bytes
2128 : : * read is not equal to the number of bytes requested.
2129 : : *
2130 : : * Returns the number of bytes read.
2131 : : */
2132 : : static ssize_t
2229 rhaas@postgresql.org 2133 : 219175 : basebackup_read_file(int fd, char *buf, size_t nbytes, off_t offset,
2134 : : const char *filename, bool partial_read_ok)
2135 : : {
2136 : : ssize_t rc;
2137 : :
2138 : 219175 : pgstat_report_wait_start(WAIT_EVENT_BASEBACKUP_READ);
1395 tmunro@postgresql.or 2139 : 219175 : rc = pg_pread(fd, buf, nbytes, offset);
2229 rhaas@postgresql.org 2140 : 219175 : pgstat_report_wait_end();
2141 : :
2142 [ - + ]: 219175 : if (rc < 0)
2229 rhaas@postgresql.org 2143 [ # # ]:UBC 0 : ereport(ERROR,
2144 : : (errcode_for_file_access(),
2145 : : errmsg("could not read file \"%s\": %m", filename)));
2229 rhaas@postgresql.org 2146 [ + + + - :CBC 219175 : if (!partial_read_ok && rc > 0 && rc != nbytes)
- + ]
2229 rhaas@postgresql.org 2147 [ # # ]:UBC 0 : ereport(ERROR,
2148 : : (errcode_for_file_access(),
2149 : : errmsg("could not read file \"%s\": read %zd of %zu",
2150 : : filename, rc, nbytes)));
2151 : :
2229 rhaas@postgresql.org 2152 :CBC 219175 : return rc;
2153 : : }
|