Age Owner Branch data TLA Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * pg_receivewal.c - receive streaming WAL data and write it
4 : : * to a local file.
5 : : *
6 : : * Author: Magnus Hagander <magnus@hagander.net>
7 : : *
8 : : * Portions Copyright (c) 1996-2026, PostgreSQL Global Development Group
9 : : *
10 : : * IDENTIFICATION
11 : : * src/bin/pg_basebackup/pg_receivewal.c
12 : : *-------------------------------------------------------------------------
13 : : */
14 : :
15 : : #include "postgres_fe.h"
16 : :
17 : : #include <dirent.h>
18 : : #include <limits.h>
19 : : #include <signal.h>
20 : : #include <sys/stat.h>
21 : : #include <unistd.h>
22 : :
23 : : #ifdef USE_LZ4
24 : : #include <lz4frame.h>
25 : : #endif
26 : : #ifdef HAVE_LIBZ
27 : : #include <zlib.h>
28 : : #endif
29 : :
30 : : #include "access/xlog_internal.h"
31 : : #include "common/file_perm.h"
32 : : #include "common/logging.h"
33 : : #include "common/pg_parse_lsn.h"
34 : : #include "fe_utils/option_utils.h"
35 : : #include "getopt_long.h"
36 : : #include "libpq-fe.h"
37 : : #include "receivelog.h"
38 : : #include "streamutil.h"
39 : :
40 : : /* Time to sleep between reconnection attempts */
41 : : #define RECONNECT_SLEEP_TIME 5
42 : :
43 : : /* Global options */
44 : : static char *basedir = NULL;
45 : : static int verbose = 0;
46 : : static int compresslevel = 0;
47 : : static bool noloop = false;
48 : : static int standby_message_timeout = 10 * 1000; /* 10 sec = default */
49 : : static volatile sig_atomic_t time_to_stop = false;
50 : : static bool do_create_slot = false;
51 : : static bool slot_exists_ok = false;
52 : : static bool do_drop_slot = false;
53 : : static bool do_sync = true;
54 : : static bool synchronous = false;
55 : : static char *replication_slot = NULL;
56 : : static pg_compress_algorithm compression_algorithm = PG_COMPRESSION_NONE;
57 : : static XLogRecPtr endpos = InvalidXLogRecPtr;
58 : :
59 : :
60 : : static void usage(void);
61 : : static DIR *get_destination_dir(char *dest_folder);
62 : : static void close_destination_dir(DIR *dest_dir, char *dest_folder);
63 : : static XLogRecPtr FindStreamingStart(uint32 *tli_p);
64 : : static void StreamLog(void);
65 : : static bool stop_streaming(XLogRecPtr xlogpos, uint32 timeline,
66 : : bool segment_finished);
67 : :
68 : : static void
2891 peter@eisentraut.org 69 :CBC 9 : disconnect_atexit(void)
70 : : {
71 [ + + ]: 9 : if (conn != NULL)
72 : 3 : PQfinish(conn);
73 : 9 : }
74 : :
75 : : static void
5512 magnus@hagander.net 76 : 1 : usage(void)
77 : : {
3487 peter_e@gmx.net 78 : 1 : printf(_("%s receives PostgreSQL streaming write-ahead logs.\n\n"),
79 : : progname);
5512 magnus@hagander.net 80 : 1 : printf(_("Usage:\n"));
81 : 1 : printf(_(" %s [OPTION]...\n"), progname);
5282 peter_e@gmx.net 82 : 1 : printf(_("\nOptions:\n"));
3487 83 : 1 : printf(_(" -D, --directory=DIR receive write-ahead log files into this directory\n"));
3365 84 : 1 : printf(_(" -E, --endpos=LSN exit after receiving the specified LSN\n"));
4091 85 : 1 : printf(_(" --if-not-exists do not error if slot already exists when creating a slot\n"));
5233 alvherre@alvh.no-ip. 86 : 1 : printf(_(" -n, --no-loop do not loop on connection lost\n"));
3317 rhaas@postgresql.org 87 : 1 : printf(_(" --no-sync do not wait for changes to be written safely to disk\n"));
4430 peter_e@gmx.net 88 : 1 : printf(_(" -s, --status-interval=SECS\n"
89 : : " time between status packets sent to server (default: %d)\n"), (standby_message_timeout / 1000));
90 : 1 : printf(_(" -S, --slot=SLOTNAME replication slot to use\n"));
3487 91 : 1 : printf(_(" --synchronous flush write-ahead log immediately after writing\n"));
5233 alvherre@alvh.no-ip. 92 : 1 : printf(_(" -v, --verbose output verbose messages\n"));
93 : 1 : printf(_(" -V, --version output version information, then exit\n"));
1690 michael@paquier.xyz 94 : 1 : printf(_(" -Z, --compress=METHOD[:DETAIL]\n"
95 : : " compress as specified\n"));
5233 alvherre@alvh.no-ip. 96 : 1 : printf(_(" -?, --help show this help, then exit\n"));
5512 magnus@hagander.net 97 : 1 : printf(_("\nConnection options:\n"));
5024 heikki.linnakangas@i 98 : 1 : printf(_(" -d, --dbname=CONNSTR connection string\n"));
5233 alvherre@alvh.no-ip. 99 : 1 : printf(_(" -h, --host=HOSTNAME database server host or socket directory\n"));
100 : 1 : printf(_(" -p, --port=PORT database server port number\n"));
101 : 1 : printf(_(" -U, --username=NAME connect as specified database user\n"));
102 : 1 : printf(_(" -w, --no-password never prompt for password\n"));
103 : 1 : printf(_(" -W, --password force password prompt (should happen automatically)\n"));
4436 andres@anarazel.de 104 : 1 : printf(_("\nOptional actions:\n"));
105 : 1 : printf(_(" --create-slot create a new replication slot (for the slot's name see --slot)\n"));
106 : 1 : printf(_(" --drop-slot drop the replication slot (for the slot's name see --slot)\n"));
2465 peter@eisentraut.org 107 : 1 : printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
108 : 1 : printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
5512 magnus@hagander.net 109 : 1 : }
110 : :
111 : :
112 : : /*
113 : : * Check if the filename looks like a WAL file, letting caller know if this
114 : : * WAL segment is partial and/or compressed.
115 : : */
116 : : static bool
1850 michael@paquier.xyz 117 : 23 : is_xlogfilename(const char *filename, bool *ispartial,
118 : : pg_compress_algorithm *wal_compression_algorithm)
119 : : {
120 : 23 : size_t fname_len = strlen(filename);
121 : 23 : size_t xlog_pattern_len = strspn(filename, "0123456789ABCDEF");
122 : :
123 : : /* File does not look like a WAL file */
124 [ + + ]: 23 : if (xlog_pattern_len != XLOG_FNAME_LEN)
125 : 14 : return false;
126 : :
127 : : /* File looks like a completed uncompressed WAL file */
128 [ - + ]: 9 : if (fname_len == XLOG_FNAME_LEN)
129 : : {
1850 michael@paquier.xyz 130 :UBC 0 : *ispartial = false;
1691 131 : 0 : *wal_compression_algorithm = PG_COMPRESSION_NONE;
1850 132 : 0 : return true;
133 : : }
134 : :
135 : : /* File looks like a completed gzip-compressed WAL file */
1850 michael@paquier.xyz 136 [ + + ]:CBC 9 : if (fname_len == XLOG_FNAME_LEN + strlen(".gz") &&
137 [ + - ]: 2 : strcmp(filename + XLOG_FNAME_LEN, ".gz") == 0)
138 : : {
139 : 2 : *ispartial = false;
1691 140 : 2 : *wal_compression_algorithm = PG_COMPRESSION_GZIP;
1850 141 : 2 : return true;
142 : : }
143 : :
144 : : /* File looks like a completed LZ4-compressed WAL file */
1849 145 [ + + ]: 7 : if (fname_len == XLOG_FNAME_LEN + strlen(".lz4") &&
146 [ + - ]: 1 : strcmp(filename + XLOG_FNAME_LEN, ".lz4") == 0)
147 : : {
148 : 1 : *ispartial = false;
1691 149 : 1 : *wal_compression_algorithm = PG_COMPRESSION_LZ4;
1849 150 : 1 : return true;
151 : : }
152 : :
153 : : /* File looks like a partial uncompressed WAL file */
1850 154 [ + + ]: 6 : if (fname_len == XLOG_FNAME_LEN + strlen(".partial") &&
155 [ + - ]: 3 : strcmp(filename + XLOG_FNAME_LEN, ".partial") == 0)
156 : : {
157 : 3 : *ispartial = true;
1691 158 : 3 : *wal_compression_algorithm = PG_COMPRESSION_NONE;
1850 159 : 3 : return true;
160 : : }
161 : :
162 : : /* File looks like a partial gzip-compressed WAL file */
163 [ + + ]: 3 : if (fname_len == XLOG_FNAME_LEN + strlen(".gz.partial") &&
164 [ + - ]: 2 : strcmp(filename + XLOG_FNAME_LEN, ".gz.partial") == 0)
165 : : {
166 : 2 : *ispartial = true;
1691 167 : 2 : *wal_compression_algorithm = PG_COMPRESSION_GZIP;
1850 168 : 2 : return true;
169 : : }
170 : :
171 : : /* File looks like a partial LZ4-compressed WAL file */
1849 172 [ + - ]: 1 : if (fname_len == XLOG_FNAME_LEN + strlen(".lz4.partial") &&
173 [ + - ]: 1 : strcmp(filename + XLOG_FNAME_LEN, ".lz4.partial") == 0)
174 : : {
175 : 1 : *ispartial = true;
1691 176 : 1 : *wal_compression_algorithm = PG_COMPRESSION_LZ4;
1849 177 : 1 : return true;
178 : : }
179 : :
180 : : /* File does not look like something we know */
1850 michael@paquier.xyz 181 :UBC 0 : return false;
182 : : }
183 : :
184 : : static bool
5063 heikki.linnakangas@i 185 :CBC 97 : stop_streaming(XLogRecPtr xlogpos, uint32 timeline, bool segment_finished)
186 : : {
187 : : static uint32 prevtimeline = 0;
188 : : static XLogRecPtr prevpos = InvalidXLogRecPtr;
189 : :
190 : : /* we assume that we get called once at the end of each segment */
5300 magnus@hagander.net 191 [ + - + + ]: 97 : if (verbose && segment_finished)
509 alvherre@kurilemu.de 192 : 6 : pg_log_info("finished segment at %X/%08X (timeline %u)",
193 : : LSN_FORMAT_ARGS(xlogpos),
194 : : timeline);
195 : :
387 196 [ + - + + ]: 97 : if (XLogRecPtrIsValid(endpos) && endpos < xlogpos)
197 : : {
3365 peter_e@gmx.net 198 [ + - ]: 12 : if (verbose)
509 alvherre@kurilemu.de 199 : 12 : pg_log_info("stopped log streaming at %X/%08X (timeline %u)",
200 : : LSN_FORMAT_ARGS(xlogpos),
201 : : timeline);
3365 peter_e@gmx.net 202 : 12 : time_to_stop = true;
203 : 12 : return true;
204 : : }
205 : :
206 : : /*
207 : : * Note that we report the previous, not current, position here. After a
208 : : * timeline switch, xlogpos points to the beginning of the segment because
209 : : * that's where we always begin streaming. Reporting the end of previous
210 : : * timeline isn't totally accurate, because the next timeline can begin
211 : : * slightly before the end of the WAL that we received on the previous
212 : : * timeline, but it's close enough for reporting purposes.
213 : : */
3392 214 [ + - + + : 85 : if (verbose && prevtimeline != 0 && prevtimeline != timeline)
+ + ]
509 alvherre@kurilemu.de 215 : 1 : pg_log_info("switched to timeline %u at %X/%08X",
216 : : timeline,
217 : : LSN_FORMAT_ARGS(prevpos));
218 : :
5063 heikki.linnakangas@i 219 : 85 : prevtimeline = timeline;
220 : 85 : prevpos = xlogpos;
221 : :
3365 peter_e@gmx.net 222 [ - + ]: 85 : if (time_to_stop)
223 : : {
3392 peter_e@gmx.net 224 [ # # ]:UBC 0 : if (verbose)
2798 peter@eisentraut.org 225 : 0 : pg_log_info("received interrupt signal, exiting");
5512 magnus@hagander.net 226 : 0 : return true;
227 : : }
5512 magnus@hagander.net 228 :CBC 85 : return false;
229 : : }
230 : :
231 : :
232 : : /*
233 : : * Get destination directory.
234 : : */
235 : : static DIR *
4436 andres@anarazel.de 236 : 14 : get_destination_dir(char *dest_folder)
237 : : {
238 : : DIR *dir;
239 : :
240 [ - + ]: 14 : Assert(dest_folder != NULL);
241 : 14 : dir = opendir(dest_folder);
242 [ - + ]: 14 : if (dir == NULL)
1695 tgl@sss.pgh.pa.us 243 :UBC 0 : pg_fatal("could not open directory \"%s\": %m", dest_folder);
244 : :
4436 andres@anarazel.de 245 :CBC 14 : return dir;
246 : : }
247 : :
248 : :
249 : : /*
250 : : * Close existing directory.
251 : : */
252 : : static void
253 : 14 : close_destination_dir(DIR *dest_dir, char *dest_folder)
254 : : {
255 [ + - + - ]: 14 : Assert(dest_dir != NULL && dest_folder != NULL);
256 [ - + ]: 14 : if (closedir(dest_dir))
1695 tgl@sss.pgh.pa.us 257 :UBC 0 : pg_fatal("could not close directory \"%s\": %m", dest_folder);
4436 andres@anarazel.de 258 :CBC 14 : }
259 : :
260 : :
261 : : /*
262 : : * Determine starting location for streaming, based on any existing xlog
263 : : * segments in the directory. We start at the end of the last one that is
264 : : * complete (size matches wal segment size), on the timeline with highest ID.
265 : : *
266 : : * If there are no WAL files in the directory, returns InvalidXLogRecPtr.
267 : : */
268 : : static XLogRecPtr
81 peter@eisentraut.org 269 :GNC 7 : FindStreamingStart(uint32 *tli_p)
270 : : {
271 : : DIR *dir;
272 : : struct dirent *dirent;
5270 heikki.linnakangas@i 273 :CBC 7 : XLogSegNo high_segno = 0;
5063 274 : 7 : uint32 high_tli = 0;
4814 275 : 7 : bool high_ispartial = false;
276 : :
4436 andres@anarazel.de 277 : 7 : dir = get_destination_dir(basedir);
278 : :
4635 bruce@momjian.us 279 [ + + ]: 30 : while (errno = 0, (dirent = readdir(dir)) != NULL)
280 : : {
281 : : uint32 tli;
282 : : XLogSegNo segno;
283 : : pg_compress_algorithm wal_compression_algorithm;
284 : : bool ispartial;
285 : :
1850 michael@paquier.xyz 286 [ + + ]: 23 : if (!is_xlogfilename(dirent->d_name,
287 : : &ispartial, &wal_compression_algorithm))
5512 magnus@hagander.net 288 : 14 : continue;
289 : :
290 : : /*
291 : : * Looks like an xlog file. Parse its position.
292 : : */
3357 andres@anarazel.de 293 : 9 : XLogFromFileName(dirent->d_name, &tli, &segno, WalSegSz);
294 : :
295 : : /*
296 : : * Check that the segment has the right size, if it's supposed to be
297 : : * completed. For non-compressed segments just check the on-disk size
298 : : * and see if it matches a completed segment. For gzip-compressed
299 : : * segments, look at the last 4 bytes of the compressed file, which is
300 : : * where the uncompressed size is located for files with a size lower
301 : : * than 4GB, and then compare it to the size of a completed segment.
302 : : * The 4 last bytes correspond to the ISIZE member according to
303 : : * http://www.zlib.org/rfc-gzip.html.
304 : : *
305 : : * For LZ4-compressed segments, uncompress the file in a throw-away
306 : : * buffer keeping track of the uncompressed size, then compare it to
307 : : * the size of a completed segment. Per its protocol, LZ4 does not
308 : : * store the uncompressed size of an object by default. contentSize
309 : : * is one possible way to do that, but we need to rely on a method
310 : : * where WAL segments could have been compressed by a different source
311 : : * than pg_receivewal, like an archive_command with lz4.
312 : : */
1691 michael@paquier.xyz 313 [ + + - + ]: 9 : if (!ispartial && wal_compression_algorithm == PG_COMPRESSION_NONE)
5512 magnus@hagander.net 314 :UBC 0 : {
315 : : struct stat statbuf;
316 : : char fullpath[MAXPGPATH * 2];
317 : :
4814 heikki.linnakangas@i 318 : 0 : snprintf(fullpath, sizeof(fullpath), "%s/%s", basedir, dirent->d_name);
319 [ # # ]: 0 : if (stat(fullpath, &statbuf) != 0)
1695 tgl@sss.pgh.pa.us 320 : 0 : pg_fatal("could not stat file \"%s\": %m", fullpath);
321 : :
3357 andres@anarazel.de 322 [ # # ]: 0 : if (statbuf.st_size != WalSegSz)
323 : : {
2256 peter@eisentraut.org 324 : 0 : pg_log_warning("segment file \"%s\" has incorrect size %lld, skipping",
325 : : dirent->d_name, (long long int) statbuf.st_size);
5512 magnus@hagander.net 326 : 0 : continue;
327 : : }
328 : : }
1691 michael@paquier.xyz 329 [ + + + + ]:CBC 9 : else if (!ispartial && wal_compression_algorithm == PG_COMPRESSION_GZIP)
3602 magnus@hagander.net 330 : 2 : {
331 : : int fd;
332 : : char buf[4];
333 : : int bytes_out;
334 : : char fullpath[MAXPGPATH * 2];
335 : : ssize_t r;
336 : :
337 : 2 : snprintf(fullpath, sizeof(fullpath), "%s/%s", basedir, dirent->d_name);
338 : :
2997 michael@paquier.xyz 339 : 2 : fd = open(fullpath, O_RDONLY | PG_BINARY, 0);
3602 magnus@hagander.net 340 [ - + ]: 2 : if (fd < 0)
1695 tgl@sss.pgh.pa.us 341 :UBC 0 : pg_fatal("could not open compressed file \"%s\": %m",
342 : : fullpath);
3482 bruce@momjian.us 343 [ - + ]:CBC 2 : if (lseek(fd, (off_t) (-4), SEEK_END) < 0)
1695 tgl@sss.pgh.pa.us 344 :UBC 0 : pg_fatal("could not seek in compressed file \"%s\": %m",
345 : : fullpath);
646 peter@eisentraut.org 346 :CBC 2 : r = read(fd, buf, sizeof(buf));
3055 michael@paquier.xyz 347 [ - + ]: 2 : if (r != sizeof(buf))
348 : : {
3055 michael@paquier.xyz 349 [ # # ]:UBC 0 : if (r < 0)
1695 tgl@sss.pgh.pa.us 350 : 0 : pg_fatal("could not read compressed file \"%s\": %m",
351 : : fullpath);
352 : : else
136 peter@eisentraut.org 353 :UNC 0 : pg_fatal("could not read compressed file \"%s\": read %zd of %zu",
354 : : fullpath, r, sizeof(buf));
355 : : }
356 : :
3602 magnus@hagander.net 357 :CBC 2 : close(fd);
358 : 2 : bytes_out = (buf[3] << 24) | (buf[2] << 16) |
3482 bruce@momjian.us 359 : 2 : (buf[1] << 8) | buf[0];
360 : :
3357 andres@anarazel.de 361 [ - + ]: 2 : if (bytes_out != WalSegSz)
362 : : {
2798 peter@eisentraut.org 363 :UBC 0 : pg_log_warning("compressed segment file \"%s\" has incorrect uncompressed size %d, skipping",
364 : : dirent->d_name, bytes_out);
3602 magnus@hagander.net 365 : 0 : continue;
366 : : }
367 : : }
1691 michael@paquier.xyz 368 [ + + + - ]:CBC 7 : else if (!ispartial && wal_compression_algorithm == PG_COMPRESSION_LZ4)
369 : : {
370 : : #ifdef USE_LZ4
371 : : #define LZ4_CHUNK_SZ 64 * 1024 /* 64kB as maximum chunk size read */
372 : : int fd;
373 : : ssize_t r;
1849 374 : 1 : size_t uncompressed_size = 0;
0 375 : 1 : bool frame_complete = false;
376 : : char fullpath[MAXPGPATH * 2];
377 : : char *outbuf;
378 : : char *readbuf;
1849 379 : 1 : LZ4F_decompressionContext_t ctx = NULL;
380 : : LZ4F_decompressOptions_t dec_opt;
381 : : LZ4F_errorCode_t status;
382 : :
383 : 1 : memset(&dec_opt, 0, sizeof(dec_opt));
384 : 1 : snprintf(fullpath, sizeof(fullpath), "%s/%s", basedir, dirent->d_name);
385 : :
386 : 1 : fd = open(fullpath, O_RDONLY | PG_BINARY, 0);
387 [ - + ]: 1 : if (fd < 0)
1695 tgl@sss.pgh.pa.us 388 :UBC 0 : pg_fatal("could not open file \"%s\": %m", fullpath);
389 : :
1849 michael@paquier.xyz 390 :CBC 1 : status = LZ4F_createDecompressionContext(&ctx, LZ4F_VERSION);
391 [ - + ]: 1 : if (LZ4F_isError(status))
1695 tgl@sss.pgh.pa.us 392 :UBC 0 : pg_fatal("could not create LZ4 decompression context: %s",
393 : : LZ4F_getErrorName(status));
394 : :
1849 michael@paquier.xyz 395 :CBC 1 : outbuf = pg_malloc0(LZ4_CHUNK_SZ);
396 : 1 : readbuf = pg_malloc0(LZ4_CHUNK_SZ);
397 : : do
398 : : {
399 : : char *readp;
400 : : char *readend;
401 : :
402 : 2 : r = read(fd, readbuf, LZ4_CHUNK_SZ);
403 [ - + ]: 2 : if (r < 0)
1695 tgl@sss.pgh.pa.us 404 :UBC 0 : pg_fatal("could not read file \"%s\": %m", fullpath);
405 : :
406 : : /* Done reading the file */
1849 michael@paquier.xyz 407 [ + + ]:CBC 2 : if (r == 0)
408 : 1 : break;
409 : :
410 : : /* Process one chunk */
411 : 1 : readp = readbuf;
412 : 1 : readend = readbuf + r;
413 [ + + ]: 17 : while (readp < readend)
414 : : {
415 : 16 : size_t out_size = LZ4_CHUNK_SZ;
416 : 16 : size_t read_size = readend - readp;
417 : :
418 : 16 : memset(outbuf, 0, LZ4_CHUNK_SZ);
419 : 16 : status = LZ4F_decompress(ctx, outbuf, &out_size,
420 : : readp, &read_size, &dec_opt);
421 [ - + ]: 16 : if (LZ4F_isError(status))
1695 tgl@sss.pgh.pa.us 422 :UBC 0 : pg_fatal("could not decompress file \"%s\": %s",
423 : : fullpath,
424 : : LZ4F_getErrorName(status));
425 : :
1849 michael@paquier.xyz 426 :CBC 16 : readp += read_size;
427 : 16 : uncompressed_size += out_size;
428 : :
429 : : /* LZ4F_decompress() returns 0 once the frame is complete */
0 430 : 16 : frame_complete = (status == 0);
431 : : }
432 : :
433 : : /*
434 : : * No need to continue reading the file when the
435 : : * uncompressed_size exceeds WalSegSz, even if there are still
436 : : * data left to read. However, if uncompressed_size is equal
437 : : * to WalSegSz, it should verify that there is no more data to
438 : : * read.
439 : : */
1849 440 [ + - + - ]: 1 : } while (uncompressed_size <= WalSegSz && r > 0);
441 : :
442 : 1 : close(fd);
443 : 1 : pg_free(outbuf);
444 : 1 : pg_free(readbuf);
445 : :
446 : 1 : status = LZ4F_freeDecompressionContext(ctx);
447 [ - + ]: 1 : if (LZ4F_isError(status))
1695 tgl@sss.pgh.pa.us 448 :UBC 0 : pg_fatal("could not free LZ4 decompression context: %s",
449 : : LZ4F_getErrorName(status));
450 : :
1849 michael@paquier.xyz 451 [ - + ]:CBC 1 : if (uncompressed_size != WalSegSz)
452 : : {
1846 tgl@sss.pgh.pa.us 453 :UBC 0 : pg_log_warning("compressed segment file \"%s\" has incorrect uncompressed size %zu, skipping",
454 : : dirent->d_name, uncompressed_size);
1849 michael@paquier.xyz 455 : 0 : continue;
456 : : }
457 : :
0 michael@paquier.xyz 458 [ - + ]:CBC 1 : if (!frame_complete)
459 : : {
0 michael@paquier.xyz 460 :UBC 0 : pg_log_warning("compressed segment file \"%s\" is incomplete, skipping",
461 : : dirent->d_name);
462 : 0 : continue;
463 : : }
464 : : #else
465 : : pg_log_error("cannot check file \"%s\": compression with %s not supported by this build",
466 : : dirent->d_name, "LZ4");
467 : : exit(1);
468 : : #endif
469 : : }
470 : :
471 : : /* Looks like a valid segment. Remember that we saw it. */
4814 heikki.linnakangas@i 472 [ + + ]:CBC 9 : if ((segno > high_segno) ||
473 [ + + + - ]: 4 : (segno == high_segno && tli > high_tli) ||
474 [ + + + - : 4 : (segno == high_segno && tli == high_tli && high_ispartial && !ispartial))
- + - - ]
475 : : {
476 : 5 : high_segno = segno;
477 : 5 : high_tli = tli;
478 : 5 : high_ispartial = ispartial;
479 : : }
480 : : }
481 : :
4635 bruce@momjian.us 482 [ - + ]: 7 : if (errno)
1695 tgl@sss.pgh.pa.us 483 :UBC 0 : pg_fatal("could not read directory \"%s\": %m", basedir);
484 : :
4436 andres@anarazel.de 485 :CBC 7 : close_destination_dir(dir, basedir);
486 : :
5270 heikki.linnakangas@i 487 [ + + ]: 7 : if (high_segno > 0)
488 : : {
489 : : XLogRecPtr high_ptr;
490 : :
491 : : /*
492 : : * Move the starting pointer to the start of the next segment, if the
493 : : * highest one we saw was completed. Otherwise start streaming from
494 : : * the beginning of the .partial segment.
495 : : */
4814 496 [ - + ]: 3 : if (!high_ispartial)
4814 heikki.linnakangas@i 497 :UBC 0 : high_segno++;
498 : :
3064 alvherre@alvh.no-ip. 499 :CBC 3 : XLogSegNoOffsetToRecPtr(high_segno, 0, WalSegSz, high_ptr);
500 : :
81 peter@eisentraut.org 501 :GNC 3 : *tli_p = high_tli;
5512 magnus@hagander.net 502 :CBC 3 : return high_ptr;
503 : : }
504 : : else
5063 heikki.linnakangas@i 505 : 4 : return InvalidXLogRecPtr;
506 : : }
507 : :
508 : : /*
509 : : * Start the log streaming
510 : : */
511 : : static void
5512 magnus@hagander.net 512 : 7 : StreamLog(void)
513 : : {
514 : : XLogRecPtr serverpos;
515 : : TimeLineID servertli;
1596 peter@eisentraut.org 516 : 7 : StreamCtl stream = {0};
517 : : char *sysidentifier;
518 : :
519 : : /*
520 : : * Connect in replication mode to the server
521 : : */
4424 fujii@postgresql.org 522 [ - + ]: 7 : if (conn == NULL)
4424 fujii@postgresql.org 523 :UBC 0 : conn = GetConnection();
5298 magnus@hagander.net 524 [ - + ]:CBC 7 : if (!conn)
525 : : /* Error message already written in GetConnection() */
526 : 1 : return;
527 : :
4999 heikki.linnakangas@i 528 [ - + ]: 7 : if (!CheckServerVersionForStreaming(conn))
529 : : {
530 : : /*
531 : : * Error message already written in CheckServerVersionForStreaming().
532 : : * There's no hope of recovering from a version mismatch, so don't
533 : : * retry.
534 : : */
2891 peter@eisentraut.org 535 :UBC 0 : exit(1);
536 : : }
537 : :
538 : : /*
539 : : * Identify server, obtaining start LSN position and current timeline ID
540 : : * at the same time, necessary if not valid data can be found in the
541 : : * existing output directory.
542 : : */
1897 michael@paquier.xyz 543 [ - + ]:CBC 7 : if (!RunIdentifySystem(conn, &sysidentifier, &servertli, &serverpos, NULL))
2891 peter@eisentraut.org 544 :UBC 0 : exit(1);
545 : :
546 : : /*
547 : : * Figure out where to start streaming. First scan the local directory.
548 : : */
3914 magnus@hagander.net 549 :CBC 7 : stream.startpos = FindStreamingStart(&stream.timeline);
387 alvherre@kurilemu.de 550 [ + + ]: 7 : if (!XLogRecPtrIsValid(stream.startpos))
551 : : {
552 : : /*
553 : : * Try to get the starting point from the slot if any. This is
554 : : * supported in PostgreSQL 15 and newer.
555 : : */
1859 michael@paquier.xyz 556 [ + + + - ]: 7 : if (replication_slot != NULL &&
557 : 3 : PQserverVersion(conn) >= 150000)
558 : : {
559 [ + + ]: 3 : if (!GetSlotInformation(conn, replication_slot, &stream.startpos,
560 : : &stream.timeline))
561 : : {
562 : : /* Error is logged by GetSlotInformation() */
563 : 1 : return;
564 : : }
565 : : }
566 : :
567 : : /*
568 : : * If it the starting point is still not known, use the current WAL
569 : : * flush value as last resort.
570 : : */
387 alvherre@kurilemu.de 571 [ + + ]: 3 : if (!XLogRecPtrIsValid(stream.startpos))
572 : : {
1859 michael@paquier.xyz 573 : 1 : stream.startpos = serverpos;
574 : 1 : stream.timeline = servertli;
575 : : }
576 : : }
577 : :
387 alvherre@kurilemu.de 578 [ + - + - ]: 6 : Assert(XLogRecPtrIsValid(stream.startpos) &&
579 : : stream.timeline != 0);
580 : :
581 : : /*
582 : : * Always start streaming at the beginning of a segment
583 : : */
3357 andres@anarazel.de 584 : 6 : stream.startpos -= XLogSegmentOffset(stream.startpos, WalSegSz);
585 : :
586 : : /*
587 : : * Start the replication
588 : : */
5512 magnus@hagander.net 589 [ + - ]: 6 : if (verbose)
509 alvherre@kurilemu.de 590 : 6 : pg_log_info("starting log streaming at %X/%08X (timeline %u)",
591 : : LSN_FORMAT_ARGS(stream.startpos),
592 : : stream.timeline);
593 : :
3914 magnus@hagander.net 594 : 6 : stream.stream_stop = stop_streaming;
3502 tgl@sss.pgh.pa.us 595 : 6 : stream.stop_socket = PGINVALID_SOCKET;
3914 magnus@hagander.net 596 : 6 : stream.standby_message_timeout = standby_message_timeout;
597 : 6 : stream.synchronous = synchronous;
3317 rhaas@postgresql.org 598 : 6 : stream.do_sync = do_sync;
3914 magnus@hagander.net 599 : 6 : stream.mark_done = false;
1850 michael@paquier.xyz 600 : 12 : stream.walmethod = CreateWalDirectoryMethod(basedir,
601 : : compression_algorithm,
602 : : compresslevel,
3602 magnus@hagander.net 603 : 6 : stream.do_sync);
3914 604 : 6 : stream.partial_suffix = ".partial";
3603 605 : 6 : stream.replication_slot = replication_slot;
1897 michael@paquier.xyz 606 : 6 : stream.sysidentifier = sysidentifier;
607 : :
3914 magnus@hagander.net 608 : 6 : ReceiveXlogStream(conn, &stream);
609 : :
1531 rhaas@postgresql.org 610 [ - + ]: 6 : if (!stream.walmethod->ops->finish(stream.walmethod))
611 : : {
2798 peter@eisentraut.org 612 :UBC 0 : pg_log_info("could not finish writing WAL files: %m");
3688 magnus@hagander.net 613 : 0 : return;
614 : : }
615 : :
5504 magnus@hagander.net 616 :CBC 6 : PQfinish(conn);
2891 peter@eisentraut.org 617 : 6 : conn = NULL;
618 : :
1531 rhaas@postgresql.org 619 : 6 : stream.walmethod->ops->free(stream.walmethod);
620 : : }
621 : :
622 : : /*
623 : : * When SIGINT/SIGTERM are caught, just tell the system to exit at the next
624 : : * possible moment.
625 : : */
626 : : #ifndef WIN32
627 : :
628 : : static void
1536 tgl@sss.pgh.pa.us 629 :UBC 0 : sigexit_handler(SIGNAL_ARGS)
630 : : {
3365 peter_e@gmx.net 631 : 0 : time_to_stop = true;
5512 magnus@hagander.net 632 : 0 : }
633 : : #endif
634 : :
635 : : int
5512 magnus@hagander.net 636 :CBC 19 : main(int argc, char **argv)
637 : : {
638 : : static struct option long_options[] = {
639 : : {"help", no_argument, NULL, '?'},
640 : : {"version", no_argument, NULL, 'V'},
641 : : {"directory", required_argument, NULL, 'D'},
642 : : {"dbname", required_argument, NULL, 'd'},
643 : : {"endpos", required_argument, NULL, 'E'},
644 : : {"host", required_argument, NULL, 'h'},
645 : : {"port", required_argument, NULL, 'p'},
646 : : {"username", required_argument, NULL, 'U'},
647 : : {"no-loop", no_argument, NULL, 'n'},
648 : : {"no-password", no_argument, NULL, 'w'},
649 : : {"password", no_argument, NULL, 'W'},
650 : : {"status-interval", required_argument, NULL, 's'},
651 : : {"slot", required_argument, NULL, 'S'},
652 : : {"verbose", no_argument, NULL, 'v'},
653 : : {"compress", required_argument, NULL, 'Z'},
654 : : /* action */
655 : : {"create-slot", no_argument, NULL, 1},
656 : : {"drop-slot", no_argument, NULL, 2},
657 : : {"if-not-exists", no_argument, NULL, 3},
658 : : {"synchronous", no_argument, NULL, 4},
659 : : {"no-sync", no_argument, NULL, 5},
660 : : {NULL, 0, NULL, 0}
661 : : };
662 : :
663 : : int c;
664 : : int option_index;
665 : : char *db_name;
666 : : pg_compress_specification compression_spec;
1690 michael@paquier.xyz 667 : 19 : char *compression_detail = NULL;
668 : 19 : char *compression_algorithm_str = "none";
669 : 19 : char *error_detail = NULL;
670 : :
2798 peter@eisentraut.org 671 : 19 : pg_logging_init(argv[0]);
5512 magnus@hagander.net 672 : 19 : progname = get_progname(argv[0]);
3988 alvherre@alvh.no-ip. 673 : 19 : set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_basebackup"));
674 : :
5512 magnus@hagander.net 675 [ + + ]: 19 : if (argc > 1)
676 : : {
677 [ + + - + ]: 18 : if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
678 : : {
679 : 1 : usage();
680 : 1 : exit(0);
681 : : }
5233 alvherre@alvh.no-ip. 682 [ + - ]: 17 : else if (strcmp(argv[1], "-V") == 0 ||
683 [ + + ]: 17 : strcmp(argv[1], "--version") == 0)
684 : : {
3579 rhaas@postgresql.org 685 : 1 : puts("pg_receivewal (PostgreSQL) " PG_VERSION);
5512 magnus@hagander.net 686 : 1 : exit(0);
687 : : }
688 : : }
689 : :
1447 peter@eisentraut.org 690 : 68 : while ((c = getopt_long(argc, argv, "d:D:E:h:np:s:S:U:vwWZ:",
5512 magnus@hagander.net 691 [ + + ]: 68 : long_options, &option_index)) != -1)
692 : : {
693 [ - + + - : 54 : switch (c)
+ - - + -
+ - - + +
+ - + +
+ ]
694 : : {
1447 peter@eisentraut.org 695 :UBC 0 : case 'd':
696 : 0 : connection_string = pg_strdup(optarg);
697 : 0 : break;
5512 magnus@hagander.net 698 :CBC 11 : case 'D':
5170 tgl@sss.pgh.pa.us 699 : 11 : basedir = pg_strdup(optarg);
5512 magnus@hagander.net 700 : 11 : break;
1447 peter@eisentraut.org 701 : 9 : case 'E':
108 fujii@postgresql.org 702 [ + + ]:GNC 9 : if (!pg_parse_lsn(optarg, &endpos))
1447 peter@eisentraut.org 703 :GBC 2 : pg_fatal("could not parse end position \"%s\"", optarg);
5024 heikki.linnakangas@i 704 :CBC 7 : break;
5512 magnus@hagander.net 705 :UBC 0 : case 'h':
5170 tgl@sss.pgh.pa.us 706 : 0 : dbhost = pg_strdup(optarg);
5512 magnus@hagander.net 707 : 0 : break;
1447 peter@eisentraut.org 708 :CBC 7 : case 'n':
709 : 7 : noloop = true;
710 : 7 : break;
5512 magnus@hagander.net 711 :UBC 0 : case 'p':
5170 tgl@sss.pgh.pa.us 712 : 0 : dbport = pg_strdup(optarg);
5512 magnus@hagander.net 713 : 0 : break;
714 : 0 : case 's':
1953 michael@paquier.xyz 715 [ # # ]: 0 : if (!option_parse_int(optarg, "-s/--status-interval", 0,
716 : : INT_MAX / 1000,
717 : : &standby_message_timeout))
5512 magnus@hagander.net 718 : 0 : exit(1);
1953 michael@paquier.xyz 719 : 0 : standby_message_timeout *= 1000;
5512 magnus@hagander.net 720 : 0 : break;
4684 rhaas@postgresql.org 721 :CBC 5 : case 'S':
722 : 5 : replication_slot = pg_strdup(optarg);
723 : 5 : break;
1447 peter@eisentraut.org 724 :UBC 0 : case 'U':
725 : 0 : dbuser = pg_strdup(optarg);
5298 magnus@hagander.net 726 : 0 : break;
5512 magnus@hagander.net 727 :CBC 7 : case 'v':
728 : 7 : verbose++;
729 : 7 : break;
1447 peter@eisentraut.org 730 :UBC 0 : case 'w':
731 : 0 : dbgetpassword = -1;
732 : 0 : break;
733 : 0 : case 'W':
734 : 0 : dbgetpassword = 1;
735 : 0 : break;
3602 magnus@hagander.net 736 :CBC 3 : case 'Z':
1690 michael@paquier.xyz 737 : 3 : parse_compress_options(optarg, &compression_algorithm_str,
738 : : &compression_detail);
3602 magnus@hagander.net 739 : 3 : break;
4436 andres@anarazel.de 740 : 3 : case 1:
741 : 3 : do_create_slot = true;
742 : 3 : break;
743 : 2 : case 2:
744 : 2 : do_drop_slot = true;
745 : 2 : break;
4393 fujii@postgresql.org 746 :UBC 0 : case 3:
4157 andres@anarazel.de 747 : 0 : slot_exists_ok = true;
748 : 0 : break;
4157 andres@anarazel.de 749 :CBC 2 : case 4:
4393 fujii@postgresql.org 750 : 2 : synchronous = true;
751 : 2 : break;
3317 rhaas@postgresql.org 752 : 4 : case 5:
753 : 4 : do_sync = false;
754 : 4 : break;
5512 magnus@hagander.net 755 : 1 : default:
756 : : /* getopt_long already emitted a complaint */
1695 tgl@sss.pgh.pa.us 757 : 1 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
5512 magnus@hagander.net 758 : 1 : exit(1);
759 : : }
760 : : }
761 : :
762 : : /*
763 : : * Any non-option arguments?
764 : : */
765 [ - + ]: 14 : if (optind < argc)
766 : : {
2798 peter@eisentraut.org 767 :UBC 0 : pg_log_error("too many command-line arguments (first is \"%s\")",
768 : : argv[optind]);
1695 tgl@sss.pgh.pa.us 769 : 0 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
5512 magnus@hagander.net 770 : 0 : exit(1);
771 : : }
772 : :
4212 peter_e@gmx.net 773 [ + + + + ]:CBC 14 : if (do_drop_slot && do_create_slot)
774 : : {
2798 peter@eisentraut.org 775 : 1 : pg_log_error("cannot use --create-slot together with --drop-slot");
1695 tgl@sss.pgh.pa.us 776 : 1 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
4436 andres@anarazel.de 777 : 1 : exit(1);
778 : : }
779 : :
4212 peter_e@gmx.net 780 [ + + + - : 13 : if (replication_slot == NULL && (do_drop_slot || do_create_slot))
+ + ]
781 : : {
782 : : /* translator: %s is an option name */
2798 peter@eisentraut.org 783 [ - + ]: 1 : pg_log_error("%s needs a slot to be specified using --slot",
784 : : do_drop_slot ? "--drop-slot" : "--create-slot");
1695 tgl@sss.pgh.pa.us 785 : 1 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
4436 andres@anarazel.de 786 : 1 : exit(1);
787 : : }
788 : :
3317 rhaas@postgresql.org 789 [ + + + + ]: 12 : if (synchronous && !do_sync)
790 : : {
2798 peter@eisentraut.org 791 : 1 : pg_log_error("cannot use --synchronous together with --no-sync");
1695 tgl@sss.pgh.pa.us 792 : 1 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
3317 rhaas@postgresql.org 793 : 1 : exit(1);
794 : : }
795 : :
796 : : /*
797 : : * Required arguments
798 : : */
4128 andres@anarazel.de 799 [ + + + + : 11 : if (basedir == NULL && !do_drop_slot && !do_create_slot)
+ + ]
800 : : {
2798 peter@eisentraut.org 801 : 1 : pg_log_error("no target directory specified");
1695 tgl@sss.pgh.pa.us 802 : 1 : pg_log_error_hint("Try \"%s --help\" for more information.", progname);
5512 magnus@hagander.net 803 : 1 : exit(1);
804 : : }
805 : :
806 : : /*
807 : : * Compression options
808 : : */
1690 michael@paquier.xyz 809 [ - + ]: 10 : if (!parse_compress_algorithm(compression_algorithm_str,
810 : : &compression_algorithm))
1526 peter@eisentraut.org 811 :UBC 0 : pg_fatal("unrecognized compression algorithm: \"%s\"",
812 : : compression_algorithm_str);
813 : :
1690 michael@paquier.xyz 814 :CBC 10 : parse_compress_specification(compression_algorithm, compression_detail,
815 : : &compression_spec);
816 : 10 : error_detail = validate_compress_specification(&compression_spec);
817 [ + + ]: 10 : if (error_detail != NULL)
818 : 1 : pg_fatal("invalid compression specification: %s",
819 : : error_detail);
820 : :
821 : : /* Extract the compression level */
1536 822 : 9 : compresslevel = compression_spec.level;
823 : :
824 [ - + ]: 9 : if (compression_algorithm == PG_COMPRESSION_ZSTD)
1536 michael@paquier.xyz 825 :UBC 0 : pg_fatal("compression with %s is not yet supported", "ZSTD");
826 : :
827 : : /*
828 : : * Check existence of destination folder.
829 : : */
4128 andres@anarazel.de 830 [ + + + + ]:CBC 9 : if (!do_drop_slot && !do_create_slot)
831 : : {
4207 bruce@momjian.us 832 : 7 : DIR *dir = get_destination_dir(basedir);
833 : :
4436 andres@anarazel.de 834 : 7 : close_destination_dir(dir, basedir);
835 : : }
836 : :
837 : : /*
838 : : * Obtain a connection before doing anything.
839 : : */
840 : 9 : conn = GetConnection();
841 [ - + ]: 9 : if (!conn)
842 : : /* error message already written in GetConnection() */
4436 andres@anarazel.de 843 :UBC 0 : exit(1);
2891 peter@eisentraut.org 844 :CBC 9 : atexit(disconnect_atexit);
845 : :
846 : : /*
847 : : * Trap signals. (Don't do this until after the initial password prompt,
848 : : * if one is needed, in GetConnection.)
849 : : */
850 : : #ifndef WIN32
1536 dgustafsson@postgres 851 : 9 : pqsignal(SIGINT, sigexit_handler);
852 : 9 : pqsignal(SIGTERM, sigexit_handler);
853 : : #endif
854 : :
855 : : /*
856 : : * Run IDENTIFY_SYSTEM to make sure we've successfully have established a
857 : : * replication connection and haven't connected using a database specific
858 : : * connection.
859 : : */
4436 andres@anarazel.de 860 [ - + ]: 9 : if (!RunIdentifySystem(conn, NULL, NULL, NULL, &db_name))
2891 peter@eisentraut.org 861 :UBC 0 : exit(1);
862 : :
863 : : /*
864 : : * Check that there is a database associated with connection, none should
865 : : * be defined in this context.
866 : : */
4436 andres@anarazel.de 867 [ - + ]:CBC 9 : if (db_name)
1695 tgl@sss.pgh.pa.us 868 :UBC 0 : pg_fatal("replication connection using slot \"%s\" is unexpectedly database specific",
869 : : replication_slot);
870 : :
871 : : /*
872 : : * Set umask so that directories/files are created with the same
873 : : * permissions as directories/files in the source data directory.
874 : : *
875 : : * pg_mode_mask is set to owner-only by default and then updated in
876 : : * GetConnection() where we get the mode from the server-side with
877 : : * RetrieveDataDirCreatePerm() and then call SetDataDirectoryCreatePerm().
878 : : */
1897 michael@paquier.xyz 879 :CBC 9 : umask(pg_mode_mask);
880 : :
881 : : /*
882 : : * Drop a replication slot.
883 : : */
4436 andres@anarazel.de 884 [ + + ]: 9 : if (do_drop_slot)
885 : : {
886 [ - + ]: 1 : if (verbose)
2747 tgl@sss.pgh.pa.us 887 :UBC 0 : pg_log_info("dropping replication slot \"%s\"", replication_slot);
888 : :
4436 andres@anarazel.de 889 [ - + ]:CBC 1 : if (!DropReplicationSlot(conn, replication_slot))
2891 peter@eisentraut.org 890 :UBC 0 : exit(1);
2891 peter@eisentraut.org 891 :CBC 1 : exit(0);
892 : : }
893 : :
894 : : /* Create a replication slot */
4436 andres@anarazel.de 895 [ + + ]: 8 : if (do_create_slot)
896 : : {
897 [ - + ]: 1 : if (verbose)
2798 peter@eisentraut.org 898 :UBC 0 : pg_log_info("creating replication slot \"%s\"", replication_slot);
899 : :
3350 peter_e@gmx.net 900 [ - + ]:CBC 1 : if (!CreateReplicationSlot(conn, replication_slot, NULL, false, true, false,
901 : : slot_exists_ok, false, false))
2891 peter@eisentraut.org 902 :UBC 0 : exit(1);
2891 peter@eisentraut.org 903 :CBC 1 : exit(0);
904 : : }
905 : :
906 : : /* determine remote server's xlog segment size */
1897 michael@paquier.xyz 907 [ - + ]: 7 : if (!RetrieveWalSegSize(conn))
1897 michael@paquier.xyz 908 :UBC 0 : exit(1);
909 : :
910 : : /*
911 : : * Don't close the connection here so that subsequent StreamLog() can
912 : : * reuse it.
913 : : */
914 : :
915 : : while (true)
916 : : {
5298 magnus@hagander.net 917 :CBC 7 : StreamLog();
3365 peter_e@gmx.net 918 [ + + ]: 7 : if (time_to_stop)
919 : : {
920 : : /*
921 : : * We've been Ctrl-C'ed or end of streaming position has been
922 : : * willingly reached, so exit without an error code.
923 : : */
5298 magnus@hagander.net 924 : 6 : exit(0);
925 : : }
926 [ + - ]: 1 : else if (noloop)
1695 tgl@sss.pgh.pa.us 927 : 1 : pg_fatal("disconnected");
928 : : else
929 : : {
930 : : /* translator: check source for value for %d */
2798 peter@eisentraut.org 931 :UBC 0 : pg_log_info("disconnected; waiting %d seconds to try again",
932 : : RECONNECT_SLEEP_TIME);
5298 magnus@hagander.net 933 : 0 : pg_usleep(RECONNECT_SLEEP_TIME * 1000000);
934 : : }
935 : : }
936 : : }
|