aboutsummaryrefslogtreecommitdiff
path: root/src/bin/pg_basebackup/bbstreamer_file.c
blob: 77ca2221a0e505595fd59a4c7fdd7a7714157d2a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
/*-------------------------------------------------------------------------
 *
 * bbstreamer_file.c
 *
 * Portions Copyright (c) 1996-2022, PostgreSQL Global Development Group
 *
 * IDENTIFICATION
 *		  src/bin/pg_basebackup/bbstreamer_file.c
 *-------------------------------------------------------------------------
 */

#include "postgres_fe.h"

#ifdef HAVE_LIBZ
#include <zlib.h>
#endif

#include <unistd.h>

#include "bbstreamer.h"
#include "common/logging.h"
#include "common/file_perm.h"
#include "common/string.h"

typedef struct bbstreamer_plain_writer
{
	bbstreamer	base;
	char	   *pathname;
	FILE	   *file;
	bool		should_close_file;
} bbstreamer_plain_writer;

#ifdef HAVE_LIBZ
typedef struct bbstreamer_gzip_writer
{
	bbstreamer	base;
	char	   *pathname;
	gzFile		gzfile;
}			bbstreamer_gzip_writer;
#endif

typedef struct bbstreamer_extractor
{
	bbstreamer	base;
	char	   *basepath;
	const char *(*link_map) (const char *);
	void		(*report_output_file) (const char *);
	char		filename[MAXPGPATH];
	FILE	   *file;
}			bbstreamer_extractor;

static void bbstreamer_plain_writer_content(bbstreamer *streamer,
											bbstreamer_member *member,
											const char *data, int len,
											bbstreamer_archive_context context);
static void bbstreamer_plain_writer_finalize(bbstreamer *streamer);
static void bbstreamer_plain_writer_free(bbstreamer *streamer);

const bbstreamer_ops bbstreamer_plain_writer_ops = {
	.content = bbstreamer_plain_writer_content,
	.finalize = bbstreamer_plain_writer_finalize,
	.free = bbstreamer_plain_writer_free
};

#ifdef HAVE_LIBZ
static void bbstreamer_gzip_writer_content(bbstreamer *streamer,
										   bbstreamer_member *member,
										   const char *data, int len,
										   bbstreamer_archive_context context);
static void bbstreamer_gzip_writer_finalize(bbstreamer *streamer);
static void bbstreamer_gzip_writer_free(bbstreamer *streamer);
static const char *get_gz_error(gzFile gzf);

const bbstreamer_ops bbstreamer_gzip_writer_ops = {
	.content = bbstreamer_gzip_writer_content,
	.finalize = bbstreamer_gzip_writer_finalize,
	.free = bbstreamer_gzip_writer_free
};
#endif

static void bbstreamer_extractor_content(bbstreamer *streamer,
										 bbstreamer_member *member,
										 const char *data, int len,
										 bbstreamer_archive_context context);
static void bbstreamer_extractor_finalize(bbstreamer *streamer);
static void bbstreamer_extractor_free(bbstreamer *streamer);
static void extract_directory(const char *filename, mode_t mode);
static void extract_link(const char *filename, const char *linktarget);
static FILE *create_file_for_extract(const char *filename, mode_t mode);

const bbstreamer_ops bbstreamer_extractor_ops = {
	.content = bbstreamer_extractor_content,
	.finalize = bbstreamer_extractor_finalize,
	.free = bbstreamer_extractor_free
};

/*
 * Create a bbstreamer that just writes data to a file.
 *
 * The caller must specify a pathname and may specify a file. The pathname is
 * used for error-reporting purposes either way. If file is NULL, the pathname
 * also identifies the file to which the data should be written: it is opened
 * for writing and closed when done. If file is not NULL, the data is written
 * there.
 */
bbstreamer *
bbstreamer_plain_writer_new(char *pathname, FILE *file)
{
	bbstreamer_plain_writer *streamer;

	streamer = palloc0(sizeof(bbstreamer_plain_writer));
	*((const bbstreamer_ops **) &streamer->base.bbs_ops) =
		&bbstreamer_plain_writer_ops;

	streamer->pathname = pstrdup(pathname);
	streamer->file = file;

	if (file == NULL)
	{
		streamer->file = fopen(pathname, "wb");
		if (streamer->file == NULL)
		{
			pg_log_error("could not create file \"%s\": %m", pathname);
			exit(1);
		}
		streamer->should_close_file = true;
	}

	return &streamer->base;
}

/*
 * Write archive content to file.
 */
static void
bbstreamer_plain_writer_content(bbstreamer *streamer,
								bbstreamer_member *member, const char *data,
								int len, bbstreamer_archive_context context)
{
	bbstreamer_plain_writer *mystreamer;

	mystreamer = (bbstreamer_plain_writer *) streamer;

	if (len == 0)
		return;

	errno = 0;
	if (fwrite(data, len, 1, mystreamer->file) != 1)
	{
		/* if write didn't set errno, assume problem is no disk space */
		if (errno == 0)
			errno = ENOSPC;
		pg_log_error("could not write to file \"%s\": %m",
					 mystreamer->pathname);
		exit(1);
	}
}

/*
 * End-of-archive processing when writing to a plain file consists of closing
 * the file if we opened it, but not if the caller provided it.
 */
static void
bbstreamer_plain_writer_finalize(bbstreamer *streamer)
{
	bbstreamer_plain_writer *mystreamer;

	mystreamer = (bbstreamer_plain_writer *) streamer;

	if (mystreamer->should_close_file && fclose(mystreamer->file) != 0)
	{
		pg_log_error("could not close file \"%s\": %m",
					 mystreamer->pathname);
		exit(1);
	}

	mystreamer->file = NULL;
	mystreamer->should_close_file = false;
}

/*
 * Free memory associated with this bbstreamer.
 */
static void
bbstreamer_plain_writer_free(bbstreamer *streamer)
{
	bbstreamer_plain_writer *mystreamer;

	mystreamer = (bbstreamer_plain_writer *) streamer;

	Assert(!mystreamer->should_close_file);
	Assert(mystreamer->base.bbs_next == NULL);

	pfree(mystreamer->pathname);
	pfree(mystreamer);
}

/*
 * Create a bbstreamer that just compresses data using gzip, and then writes
 * it to a file.
 *
 * As in the case of bbstreamer_plain_writer_new, pathname is always used
 * for error reporting purposes; if file is NULL, it is also the opened and
 * closed so that the data may be written there.
 */
bbstreamer *
bbstreamer_gzip_writer_new(char *pathname, FILE *file, int compresslevel)
{
#ifdef HAVE_LIBZ
	bbstreamer_gzip_writer *streamer;

	streamer = palloc0(sizeof(bbstreamer_gzip_writer));
	*((const bbstreamer_ops **) &streamer->base.bbs_ops) =
		&bbstreamer_gzip_writer_ops;

	streamer->pathname = pstrdup(pathname);

	if (file == NULL)
	{
		streamer->gzfile = gzopen(pathname, "wb");
		if (streamer->gzfile == NULL)
		{
			pg_log_error("could not create compressed file \"%s\": %m",
						 pathname);
			exit(1);
		}
	}
	else
	{
		int			fd = dup(fileno(file));

		if (fd < 0)
		{
			pg_log_error("could not duplicate stdout: %m");
			exit(1);
		}

		streamer->gzfile = gzdopen(fd, "wb");
		if (streamer->gzfile == NULL)
		{
			pg_log_error("could not open output file: %m");
			exit(1);
		}
	}

	if (gzsetparams(streamer->gzfile, compresslevel,
					Z_DEFAULT_STRATEGY) != Z_OK)
	{
		pg_log_error("could not set compression level %d: %s",
					 compresslevel, get_gz_error(streamer->gzfile));
		exit(1);
	}

	return &streamer->base;
#else
	pg_log_error("this build does not support compression");
	exit(1);
#endif
}

#ifdef HAVE_LIBZ
/*
 * Write archive content to gzip file.
 */
static void
bbstreamer_gzip_writer_content(bbstreamer *streamer,
							   bbstreamer_member *member, const char *data,
							   int len, bbstreamer_archive_context context)
{
	bbstreamer_gzip_writer *mystreamer;

	mystreamer = (bbstreamer_gzip_writer *) streamer;

	if (len == 0)
		return;

	errno = 0;
	if (gzwrite(mystreamer->gzfile, data, len) != len)
	{
		/* if write didn't set errno, assume problem is no disk space */
		if (errno == 0)
			errno = ENOSPC;
		pg_log_error("could not write to compressed file \"%s\": %s",
					 mystreamer->pathname, get_gz_error(mystreamer->gzfile));
		exit(1);
	}
}

/*
 * End-of-archive processing when writing to a gzip file consists of just
 * calling gzclose.
 *
 * It makes no difference whether we opened the file or the caller did it,
 * because libz provides no way of avoiding a close on the underling file
 * handle. Notice, however, that bbstreamer_gzip_writer_new() uses dup() to
 * work around this issue, so that the behavior from the caller's viewpoint
 * is the same as for bbstreamer_plain_writer.
 */
static void
bbstreamer_gzip_writer_finalize(bbstreamer *streamer)
{
	bbstreamer_gzip_writer *mystreamer;

	mystreamer = (bbstreamer_gzip_writer *) streamer;

	errno = 0;					/* in case gzclose() doesn't set it */
	if (gzclose(mystreamer->gzfile) != 0)
	{
		pg_log_error("could not close compressed file \"%s\": %m",
					 mystreamer->pathname);
		exit(1);
	}

	mystreamer->gzfile = NULL;
}

/*
 * Free memory associated with this bbstreamer.
 */
static void
bbstreamer_gzip_writer_free(bbstreamer *streamer)
{
	bbstreamer_gzip_writer *mystreamer;

	mystreamer = (bbstreamer_gzip_writer *) streamer;

	Assert(mystreamer->base.bbs_next == NULL);
	Assert(mystreamer->gzfile == NULL);

	pfree(mystreamer->pathname);
	pfree(mystreamer);
}

/*
 * Helper function for libz error reporting.
 */
static const char *
get_gz_error(gzFile gzf)
{
	int			errnum;
	const char *errmsg;

	errmsg = gzerror(gzf, &errnum);
	if (errnum == Z_ERRNO)
		return strerror(errno);
	else
		return errmsg;
}
#endif

/*
 * Create a bbstreamer that extracts an archive.
 *
 * All pathnames in the archive are interpreted relative to basepath.
 *
 * Unlike e.g. bbstreamer_plain_writer_new() we can't do anything useful here
 * with untyped chunks; we need typed chunks which follow the rules described
 * in bbstreamer.h. Assuming we have that, we don't need to worry about the
 * original archive format; it's enough to just look at the member information
 * provided and write to the corresponding file.
 *
 * 'link_map' is a function that will be applied to the target of any
 * symbolic link, and which should return a replacement pathname to be used
 * in its place.  If NULL, the symbolic link target is used without
 * modification.
 *
 * 'report_output_file' is a function that will be called each time we open a
 * new output file. The pathname to that file is passed as an argument. If
 * NULL, the call is skipped.
 */
bbstreamer *
bbstreamer_extractor_new(const char *basepath,
						 const char *(*link_map) (const char *),
						 void (*report_output_file) (const char *))
{
	bbstreamer_extractor *streamer;

	streamer = palloc0(sizeof(bbstreamer_extractor));
	*((const bbstreamer_ops **) &streamer->base.bbs_ops) =
		&bbstreamer_extractor_ops;
	streamer->basepath = pstrdup(basepath);
	streamer->link_map = link_map;
	streamer->report_output_file = report_output_file;

	return &streamer->base;
}

/*
 * Extract archive contents to the filesystem.
 */
static void
bbstreamer_extractor_content(bbstreamer *streamer, bbstreamer_member *member,
							 const char *data, int len,
							 bbstreamer_archive_context context)
{
	bbstreamer_extractor *mystreamer = (bbstreamer_extractor *) streamer;
	int			fnamelen;

	Assert(member != NULL || context == BBSTREAMER_ARCHIVE_TRAILER);
	Assert(context != BBSTREAMER_UNKNOWN);

	switch (context)
	{
		case BBSTREAMER_MEMBER_HEADER:
			Assert(mystreamer->file == NULL);

			/* Prepend basepath. */
			snprintf(mystreamer->filename, sizeof(mystreamer->filename),
					 "%s/%s", mystreamer->basepath, member->pathname);

			/* Remove any trailing slash. */
			fnamelen = strlen(mystreamer->filename);
			if (mystreamer->filename[fnamelen - 1] == '/')
				mystreamer->filename[fnamelen - 1] = '\0';

			/* Dispatch based on file type. */
			if (member->is_directory)
				extract_directory(mystreamer->filename, member->mode);
			else if (member->is_link)
			{
				const char *linktarget = member->linktarget;

				if (mystreamer->link_map)
					linktarget = mystreamer->link_map(linktarget);
				extract_link(mystreamer->filename, linktarget);
			}
			else
				mystreamer->file =
					create_file_for_extract(mystreamer->filename,
											member->mode);

			/* Report output file change. */
			if (mystreamer->report_output_file)
				mystreamer->report_output_file(mystreamer->filename);
			break;

		case BBSTREAMER_MEMBER_CONTENTS:
			if (mystreamer->file == NULL)
				break;

			errno = 0;
			if (len > 0 && fwrite(data, len, 1, mystreamer->file) != 1)
			{
				/* if write didn't set errno, assume problem is no disk space */
				if (errno == 0)
					errno = ENOSPC;
				pg_log_error("could not write to file \"%s\": %m",
							 mystreamer->filename);
				exit(1);
			}
			break;

		case BBSTREAMER_MEMBER_TRAILER:
			if (mystreamer->file == NULL)
				break;
			fclose(mystreamer->file);
			mystreamer->file = NULL;
			break;

		case BBSTREAMER_ARCHIVE_TRAILER:
			break;

		default:
			/* Shouldn't happen. */
			pg_log_error("unexpected state while extracting archive");
			exit(1);
	}
}

/*
 * Create a directory.
 */
static void
extract_directory(const char *filename, mode_t mode)
{
	if (mkdir(filename, pg_dir_create_mode) != 0)
	{
		/*
		 * When streaming WAL, pg_wal (or pg_xlog for pre-9.6 clusters) will
		 * have been created by the wal receiver process. Also, when the WAL
		 * directory location was specified, pg_wal (or pg_xlog) has already
		 * been created as a symbolic link before starting the actual backup.
		 * So just ignore creation failures on related directories.
		 */
		if (!((pg_str_endswith(filename, "/pg_wal") ||
			   pg_str_endswith(filename, "/pg_xlog") ||
			   pg_str_endswith(filename, "/archive_status")) &&
			  errno == EEXIST))
		{
			pg_log_error("could not create directory \"%s\": %m",
						 filename);
			exit(1);
		}
	}

#ifndef WIN32
	if (chmod(filename, mode))
	{
		pg_log_error("could not set permissions on directory \"%s\": %m",
					 filename);
		exit(1);
	}
#endif
}

/*
 * Create a symbolic link.
 *
 * It's most likely a link in pg_tblspc directory, to the location of a
 * tablespace. Apply any tablespace mapping given on the command line
 * (--tablespace-mapping). (We blindly apply the mapping without checking that
 * the link really is inside pg_tblspc. We don't expect there to be other
 * symlinks in a data directory, but if there are, you can call it an
 * undocumented feature that you can map them too.)
 */
static void
extract_link(const char *filename, const char *linktarget)
{
	if (symlink(linktarget, filename) != 0)
	{
		pg_log_error("could not create symbolic link from \"%s\" to \"%s\": %m",
					 filename, linktarget);
		exit(1);
	}
}

/*
 * Create a regular file.
 *
 * Return the resulting handle so we can write the content to the file.
 */
static FILE *
create_file_for_extract(const char *filename, mode_t mode)
{
	FILE	   *file;

	file = fopen(filename, "wb");
	if (file == NULL)
	{
		pg_log_error("could not create file \"%s\": %m", filename);
		exit(1);
	}

#ifndef WIN32
	if (chmod(filename, mode))
	{
		pg_log_error("could not set permissions on file \"%s\": %m",
					 filename);
		exit(1);
	}
#endif

	return file;
}

/*
 * End-of-stream processing for extracting an archive.
 *
 * There's nothing to do here but sanity checking.
 */
static void
bbstreamer_extractor_finalize(bbstreamer *streamer)
{
	bbstreamer_extractor *mystreamer PG_USED_FOR_ASSERTS_ONLY
		= (bbstreamer_extractor *) streamer;

	Assert(mystreamer->file == NULL);
}

/*
 * Free memory.
 */
static void
bbstreamer_extractor_free(bbstreamer *streamer)
{
	bbstreamer_extractor *mystreamer = (bbstreamer_extractor *) streamer;

	pfree(mystreamer->basepath);
	pfree(mystreamer);
}