Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * libpq_source.c
4 : : * Functions for fetching files from a remote server via libpq.
5 : : *
6 : : * Copyright (c) 2013-2026, PostgreSQL Global Development Group
7 : : *
8 : : *-------------------------------------------------------------------------
9 : : */
10 : : #include "postgres_fe.h"
11 : :
12 : : #include "catalog/pg_type_d.h"
13 : : #include "common/connect.h"
14 : : #include "common/pg_parse_lsn.h"
15 : : #include "file_ops.h"
16 : : #include "filemap.h"
17 : : #include "lib/stringinfo.h"
18 : : #include "pg_rewind.h"
19 : : #include "port/pg_bswap.h"
20 : : #include "rewind_source.h"
21 : :
22 : : /*
23 : : * Files are fetched MAX_CHUNK_SIZE bytes at a time, and with a
24 : : * maximum of MAX_CHUNKS_PER_QUERY chunks in a single query.
25 : : */
26 : : #define MAX_CHUNK_SIZE (1024 * 1024)
27 : : #define MAX_CHUNKS_PER_QUERY 1000
28 : :
29 : : /* represents a request to fetch a piece of a file from the source */
30 : : typedef struct
31 : : {
32 : : const char *path; /* path relative to data directory root */
33 : : off_t offset;
34 : : size_t length;
35 : : } fetch_range_request;
36 : :
37 : : typedef struct
38 : : {
39 : : rewind_source common; /* common interface functions */
40 : :
41 : : PGconn *conn;
42 : :
43 : : /*
44 : : * Queue of chunks that have been requested with the queue_fetch_range()
45 : : * function, but have not been fetched from the remote server yet.
46 : : */
47 : : int num_requests;
48 : : fetch_range_request request_queue[MAX_CHUNKS_PER_QUERY];
49 : :
50 : : /* temporary space for process_queued_fetch_requests() */
51 : : StringInfoData paths;
52 : : StringInfoData offsets;
53 : : StringInfoData lengths;
54 : : } libpq_source;
55 : :
56 : : static void init_libpq_conn(PGconn *conn);
57 : : static char *run_simple_query(PGconn *conn, const char *sql);
58 : : static void run_simple_command(PGconn *conn, const char *sql);
59 : : static void appendArrayEscapedString(StringInfo buf, const char *str);
60 : :
61 : : static void process_queued_fetch_requests(libpq_source *src);
62 : :
63 : : /* public interface functions */
64 : : static void libpq_traverse_files(rewind_source *source,
65 : : process_file_callback_t callback);
66 : : static void libpq_queue_fetch_file(rewind_source *source, const char *path, size_t len);
67 : : static void libpq_queue_fetch_range(rewind_source *source, const char *path,
68 : : off_t off, size_t len);
69 : : static void libpq_finish_fetch(rewind_source *source);
70 : : static char *libpq_fetch_file(rewind_source *source, const char *path,
71 : : size_t *filesize);
72 : : static XLogRecPtr libpq_get_current_wal_insert_lsn(rewind_source *source);
73 : : static void libpq_destroy(rewind_source *source);
74 : :
75 : : /*
76 : : * Create a new libpq source.
77 : : *
78 : : * The caller has already established the connection, but should not try
79 : : * to use it while the source is active.
80 : : */
81 : : rewind_source *
82 : 6 : init_libpq_source(PGconn *conn)
83 : : {
84 : : libpq_source *src;
85 : :
86 : 6 : init_libpq_conn(conn);
87 : :
88 : 6 : src = pg_malloc0_object(libpq_source);
89 : :
90 : 6 : src->common.traverse_files = libpq_traverse_files;
91 : 6 : src->common.fetch_file = libpq_fetch_file;
92 : 6 : src->common.queue_fetch_file = libpq_queue_fetch_file;
93 : 6 : src->common.queue_fetch_range = libpq_queue_fetch_range;
94 : 6 : src->common.finish_fetch = libpq_finish_fetch;
95 : 6 : src->common.get_current_wal_insert_lsn = libpq_get_current_wal_insert_lsn;
96 : 6 : src->common.destroy = libpq_destroy;
97 : :
98 : 6 : src->conn = conn;
99 : :
100 : 6 : initStringInfo(&src->paths);
101 : 6 : initStringInfo(&src->offsets);
102 : 6 : initStringInfo(&src->lengths);
103 : :
104 : 6 : return &src->common;
105 : : }
106 : :
107 : : /*
108 : : * Initialize a libpq connection for use.
109 : : */
110 : : static void
111 : 6 : init_libpq_conn(PGconn *conn)
112 : : {
113 : : PGresult *res;
114 : : char *str;
115 : :
116 : : /* disable all types of timeouts */
117 : 6 : run_simple_command(conn, "SET statement_timeout = 0");
118 : 6 : run_simple_command(conn, "SET lock_timeout = 0");
119 : 6 : run_simple_command(conn, "SET idle_in_transaction_session_timeout = 0");
120 : 6 : run_simple_command(conn, "SET transaction_timeout = 0");
121 : :
122 : : /*
123 : : * we don't intend to do any updates, put the connection in read-only mode
124 : : * to keep us honest
125 : : */
126 : 6 : run_simple_command(conn, "SET default_transaction_read_only = on");
127 : :
128 : : /* secure search_path */
129 : 6 : res = PQexec(conn, ALWAYS_SECURE_SEARCH_PATH_SQL);
130 [ - + ]: 6 : if (PQresultStatus(res) != PGRES_TUPLES_OK)
131 : 0 : pg_fatal("could not clear \"search_path\": %s",
132 : : PQresultErrorMessage(res));
133 : 6 : PQclear(res);
134 : :
135 : : /*
136 : : * Also check that full_page_writes is enabled. We can get torn pages if
137 : : * a page is modified while we read it with pg_read_binary_file(), and we
138 : : * rely on full page images to fix them.
139 : : */
140 : 6 : str = run_simple_query(conn, "SHOW full_page_writes");
141 [ - + ]: 6 : if (strcmp(str, "on") != 0)
142 : 0 : pg_fatal("\"full_page_writes\" must be enabled in the source server");
143 : 6 : pg_free(str);
144 : :
145 : : /* Prepare a statement we'll use to fetch files */
146 : 6 : res = PQprepare(conn, "fetch_chunks_stmt",
147 : : "SELECT path, begin,\n"
148 : : " pg_read_binary_file(path, begin, len, true) AS chunk\n"
149 : : "FROM unnest ($1::text[], $2::int8[], $3::int4[]) as x(path, begin, len)",
150 : : 3, NULL);
151 : :
152 [ - + ]: 6 : if (PQresultStatus(res) != PGRES_COMMAND_OK)
153 : 0 : pg_fatal("could not prepare statement to fetch file contents: %s",
154 : : PQresultErrorMessage(res));
155 : 6 : PQclear(res);
156 : 6 : }
157 : :
158 : : /*
159 : : * Run a query that returns a single value.
160 : : *
161 : : * The result should be pg_free'd after use.
162 : : */
163 : : static char *
164 : 11 : run_simple_query(PGconn *conn, const char *sql)
165 : : {
166 : : PGresult *res;
167 : : char *result;
168 : :
169 : 11 : res = PQexec(conn, sql);
170 : :
171 [ - + ]: 11 : if (PQresultStatus(res) != PGRES_TUPLES_OK)
172 : 0 : pg_fatal("error running query (%s) on source server: %s",
173 : : sql, PQresultErrorMessage(res));
174 : :
175 : : /* sanity check the result set */
176 [ + - + - : 11 : if (PQnfields(res) != 1 || PQntuples(res) != 1 || PQgetisnull(res, 0, 0))
- + ]
177 : 0 : pg_fatal("unexpected result set from query");
178 : :
179 : 11 : result = pg_strdup(PQgetvalue(res, 0, 0));
180 : :
181 : 11 : PQclear(res);
182 : :
183 : 11 : return result;
184 : : }
185 : :
186 : : /*
187 : : * Run a command.
188 : : *
189 : : * In the event of a failure, exit immediately.
190 : : */
191 : : static void
192 : 30 : run_simple_command(PGconn *conn, const char *sql)
193 : : {
194 : : PGresult *res;
195 : :
196 : 30 : res = PQexec(conn, sql);
197 : :
198 [ - + ]: 30 : if (PQresultStatus(res) != PGRES_COMMAND_OK)
199 : 0 : pg_fatal("error running query (%s) in source server: %s",
200 : : sql, PQresultErrorMessage(res));
201 : :
202 : 30 : PQclear(res);
203 : 30 : }
204 : :
205 : : /*
206 : : * Call the pg_current_wal_insert_lsn() function in the remote system.
207 : : */
208 : : static XLogRecPtr
209 : 5 : libpq_get_current_wal_insert_lsn(rewind_source *source)
210 : : {
211 : 5 : PGconn *conn = ((libpq_source *) source)->conn;
212 : : XLogRecPtr result;
213 : : char *val;
214 : :
215 : 5 : val = run_simple_query(conn, "SELECT pg_current_wal_insert_lsn()");
216 : :
217 [ - + ]: 5 : if (!pg_parse_lsn(val, &result))
218 : 0 : pg_fatal("unrecognized result \"%s\" for current WAL insert location", val);
219 : :
220 : 5 : pg_free(val);
221 : :
222 : 5 : return result;
223 : : }
224 : :
225 : : /*
226 : : * Get a list of all files in the data directory.
227 : : */
228 : : static void
229 : 6 : libpq_traverse_files(rewind_source *source, process_file_callback_t callback)
230 : : {
231 : 6 : PGconn *conn = ((libpq_source *) source)->conn;
232 : : PGresult *res;
233 : : const char *sql;
234 : : int i;
235 : :
236 : : /*
237 : : * Create a recursive directory listing of the whole data directory.
238 : : *
239 : : * The WITH RECURSIVE part does most of the work. The second part gets the
240 : : * targets of the symlinks in pg_tblspc directory.
241 : : *
242 : : * XXX: There is no backend function to get a symbolic link's target in
243 : : * general, so if the admin has put any custom symbolic links in the data
244 : : * directory, they won't be copied correctly.
245 : : */
246 : 6 : sql =
247 : : "WITH RECURSIVE files (path, filename, size, isdir) AS (\n"
248 : : " SELECT '' AS path, filename, size, isdir FROM\n"
249 : : " (SELECT pg_ls_dir('.', true, false) AS filename) AS fn,\n"
250 : : " pg_stat_file(fn.filename, true) AS this\n"
251 : : " UNION ALL\n"
252 : : " SELECT parent.path || parent.filename || '/' AS path,\n"
253 : : " fn, this.size, this.isdir\n"
254 : : " FROM files AS parent,\n"
255 : : " pg_ls_dir(parent.path || parent.filename, true, false) AS fn,\n"
256 : : " pg_stat_file(parent.path || parent.filename || '/' || fn, true) AS this\n"
257 : : " WHERE parent.isdir = 't'\n"
258 : : ")\n"
259 : : "SELECT path || filename, size, isdir,\n"
260 : : " pg_tablespace_location(pg_tablespace.oid) AS link_target\n"
261 : : "FROM files\n"
262 : : "LEFT OUTER JOIN pg_tablespace ON files.path = 'pg_tblspc/'\n"
263 : : " AND oid::text = files.filename\n";
264 : 6 : res = PQexec(conn, sql);
265 : :
266 [ - + ]: 6 : if (PQresultStatus(res) != PGRES_TUPLES_OK)
267 : 0 : pg_fatal("could not fetch file list: %s",
268 : : PQresultErrorMessage(res));
269 : :
270 : : /* sanity check the result set */
271 [ - + ]: 6 : if (PQnfields(res) != 4)
272 : 0 : pg_fatal("unexpected result set while fetching file list");
273 : :
274 : : /* Read result to local variables */
275 [ + + ]: 7409 : for (i = 0; i < PQntuples(res); i++)
276 : : {
277 : : char *path;
278 : : int64 filesize;
279 : : bool isdir;
280 : : char *link_target;
281 : : file_type_t type;
282 : :
283 [ - + ]: 7403 : if (PQgetisnull(res, i, 1))
284 : : {
285 : : /*
286 : : * The file was removed from the server while the query was
287 : : * running. Ignore it.
288 : : */
289 : 0 : continue;
290 : : }
291 : :
292 : 7403 : path = PQgetvalue(res, i, 0);
293 : 7403 : filesize = atoll(PQgetvalue(res, i, 1));
294 : 7403 : isdir = (strcmp(PQgetvalue(res, i, 2), "t") == 0);
295 : 7403 : link_target = PQgetvalue(res, i, 3);
296 : :
297 [ + + ]: 7403 : if (link_target[0])
298 : : {
299 : : /*
300 : : * In-place tablespaces are directories located in pg_tblspc/ with
301 : : * relative paths.
302 : : */
303 [ - + ]: 1 : if (is_absolute_path(link_target))
304 : 0 : type = FILE_TYPE_SYMLINK;
305 : : else
306 : 1 : type = FILE_TYPE_DIRECTORY;
307 : : }
308 [ + + ]: 7402 : else if (isdir)
309 : 167 : type = FILE_TYPE_DIRECTORY;
310 : : else
311 : 7235 : type = FILE_TYPE_REGULAR;
312 : :
313 : 7403 : callback(path, type, filesize, link_target);
314 : : }
315 : 6 : PQclear(res);
316 : 6 : }
317 : :
318 : : /*
319 : : * Queue up a request to fetch a file from remote system.
320 : : */
321 : : static void
322 : 1979 : libpq_queue_fetch_file(rewind_source *source, const char *path, size_t len)
323 : : {
324 : : /*
325 : : * Truncate the target file immediately, and queue a request to fetch it
326 : : * from the source. If the file is small, smaller than MAX_CHUNK_SIZE,
327 : : * request fetching a full-sized chunk anyway, so that if the file has
328 : : * become larger in the source system, after we scanned the source
329 : : * directory, we still fetch the whole file. This only works for files up
330 : : * to MAX_CHUNK_SIZE, but that's good enough for small configuration files
331 : : * and such that are changed every now and then, but not WAL-logged. For
332 : : * larger files, we fetch up to the original size.
333 : : *
334 : : * Even with that mechanism, there is an inherent race condition if the
335 : : * file is modified at the same instant that we're copying it, so that we
336 : : * might copy a torn version of the file with one half from the old
337 : : * version and another half from the new. But pg_basebackup has the same
338 : : * problem, and it hasn't been a problem in practice.
339 : : *
340 : : * It might seem more natural to truncate the file later, when we receive
341 : : * it from the source server, but then we'd need to track which
342 : : * fetch-requests are for a whole file.
343 : : */
344 : 1979 : open_target_file(path, true);
345 : 1979 : libpq_queue_fetch_range(source, path, 0, Max(len, MAX_CHUNK_SIZE));
346 : 1979 : }
347 : :
348 : : /*
349 : : * Queue up a request to fetch a piece of a file from remote system.
350 : : */
351 : : static void
352 : 2830 : libpq_queue_fetch_range(rewind_source *source, const char *path, off_t off,
353 : : size_t len)
354 : : {
355 : 2830 : libpq_source *src = (libpq_source *) source;
356 : :
357 : : /*
358 : : * Does this request happen to be a continuation of the previous chunk? If
359 : : * so, merge it with the previous one.
360 : : *
361 : : * XXX: We use pointer equality to compare the path. That's good enough
362 : : * for our purposes; the caller always passes the same pointer for the
363 : : * same filename. If it didn't, we would fail to merge requests, but it
364 : : * wouldn't affect correctness.
365 : : */
366 [ + + ]: 2830 : if (src->num_requests > 0)
367 : : {
368 : 2824 : fetch_range_request *prev = &src->request_queue[src->num_requests - 1];
369 : :
370 [ + + ]: 2824 : if (prev->offset + prev->length == off &&
371 [ + - ]: 640 : prev->length < MAX_CHUNK_SIZE &&
372 [ + + ]: 640 : prev->path == path)
373 : : {
374 : : /*
375 : : * Extend the previous request to cover as much of this new
376 : : * request as possible, without exceeding MAX_CHUNK_SIZE.
377 : : */
378 : : size_t thislen;
379 : :
380 : 639 : thislen = Min(len, MAX_CHUNK_SIZE - prev->length);
381 : 639 : prev->length += thislen;
382 : :
383 : 639 : off += thislen;
384 : 639 : len -= thislen;
385 : :
386 : : /*
387 : : * Fall through to create new requests for any remaining 'len'
388 : : * that didn't fit in the previous chunk.
389 : : */
390 : : }
391 : : }
392 : :
393 : : /* Divide the request into pieces of MAX_CHUNK_SIZE bytes each */
394 [ + + ]: 5216 : while (len > 0)
395 : : {
396 : : int32 thislen;
397 : :
398 : : /* if the queue is full, perform all the work queued up so far */
399 [ - + ]: 2386 : if (src->num_requests == MAX_CHUNKS_PER_QUERY)
400 : 0 : process_queued_fetch_requests(src);
401 : :
402 : 2386 : thislen = Min(len, MAX_CHUNK_SIZE);
403 : 2386 : src->request_queue[src->num_requests].path = path;
404 : 2386 : src->request_queue[src->num_requests].offset = off;
405 : 2386 : src->request_queue[src->num_requests].length = thislen;
406 : 2386 : src->num_requests++;
407 : :
408 : 2386 : off += thislen;
409 : 2386 : len -= thislen;
410 : : }
411 : 2830 : }
412 : :
413 : : /*
414 : : * Fetch all the queued chunks and write them to the target data directory.
415 : : */
416 : : static void
417 : 6 : libpq_finish_fetch(rewind_source *source)
418 : : {
419 : 6 : process_queued_fetch_requests((libpq_source *) source);
420 : 6 : }
421 : :
422 : : static void
423 : 6 : process_queued_fetch_requests(libpq_source *src)
424 : : {
425 : : const char *params[3];
426 : : PGresult *res;
427 : : int chunkno;
428 : :
429 [ - + ]: 6 : if (src->num_requests == 0)
430 : 0 : return;
431 : :
432 [ + - ]: 6 : pg_log_debug("getting %d file chunks", src->num_requests);
433 : :
434 : : /*
435 : : * The prepared statement, 'fetch_chunks_stmt', takes three arrays with
436 : : * the same length as parameters: paths, offsets and lengths. Construct
437 : : * the string representations of them.
438 : : */
439 : 6 : resetStringInfo(&src->paths);
440 : 6 : resetStringInfo(&src->offsets);
441 : 6 : resetStringInfo(&src->lengths);
442 : :
443 : 6 : appendStringInfoChar(&src->paths, '{');
444 : 6 : appendStringInfoChar(&src->offsets, '{');
445 : 6 : appendStringInfoChar(&src->lengths, '{');
446 [ + + ]: 2392 : for (int i = 0; i < src->num_requests; i++)
447 : : {
448 : 2386 : fetch_range_request *rq = &src->request_queue[i];
449 : :
450 [ + + ]: 2386 : if (i > 0)
451 : : {
452 : 2380 : appendStringInfoChar(&src->paths, ',');
453 : 2380 : appendStringInfoChar(&src->offsets, ',');
454 : 2380 : appendStringInfoChar(&src->lengths, ',');
455 : : }
456 : :
457 : 2386 : appendArrayEscapedString(&src->paths, rq->path);
458 : 2386 : appendStringInfo(&src->offsets, "%lld", (long long int) rq->offset);
459 : 2386 : appendStringInfo(&src->lengths, "%zu", rq->length);
460 : : }
461 : 6 : appendStringInfoChar(&src->paths, '}');
462 : 6 : appendStringInfoChar(&src->offsets, '}');
463 : 6 : appendStringInfoChar(&src->lengths, '}');
464 : :
465 : : /*
466 : : * Execute the prepared statement.
467 : : */
468 : 6 : params[0] = src->paths.data;
469 : 6 : params[1] = src->offsets.data;
470 : 6 : params[2] = src->lengths.data;
471 : :
472 [ - + ]: 6 : if (PQsendQueryPrepared(src->conn, "fetch_chunks_stmt", 3, params, NULL, NULL, 1) != 1)
473 : 0 : pg_fatal("could not send query: %s", PQerrorMessage(src->conn));
474 : :
475 [ - + ]: 6 : if (PQsetSingleRowMode(src->conn) != 1)
476 : 0 : pg_fatal("could not set libpq connection to single row mode");
477 : :
478 : : /*----
479 : : * The result set is of format:
480 : : *
481 : : * path text -- path in the data directory, e.g "base/1/123"
482 : : * begin int8 -- offset within the file
483 : : * chunk bytea -- file content
484 : : *----
485 : : */
486 : 6 : chunkno = 0;
487 [ + + ]: 2398 : while ((res = PQgetResult(src->conn)) != NULL)
488 : : {
489 : 2392 : fetch_range_request *rq = &src->request_queue[chunkno];
490 : : char *filename;
491 : : int filenamelen;
492 : : int64 chunkoff;
493 : : int chunksize;
494 : : char *chunk;
495 : :
496 [ + + - ]: 2392 : switch (PQresultStatus(res))
497 : : {
498 : 2386 : case PGRES_SINGLE_TUPLE:
499 : 2386 : break;
500 : :
501 : 6 : case PGRES_TUPLES_OK:
502 : 6 : PQclear(res);
503 : 6 : continue; /* final zero-row result */
504 : :
505 : 0 : default:
506 : 0 : pg_fatal("unexpected result while fetching remote files: %s",
507 : : PQresultErrorMessage(res));
508 : : }
509 : :
510 [ - + ]: 2386 : if (chunkno > src->num_requests)
511 : 0 : pg_fatal("received more data chunks than requested");
512 : :
513 : : /* sanity check the result set */
514 [ + - - + ]: 2386 : if (PQnfields(res) != 3 || PQntuples(res) != 1)
515 : 0 : pg_fatal("unexpected result set size while fetching remote files");
516 : :
517 [ + - + - ]: 4772 : if (PQftype(res, 0) != TEXTOID ||
518 [ - + ]: 4772 : PQftype(res, 1) != INT8OID ||
519 : 2386 : PQftype(res, 2) != BYTEAOID)
520 : : {
521 : 0 : pg_fatal("unexpected data types in result set while fetching remote files: %u %u %u",
522 : : PQftype(res, 0), PQftype(res, 1), PQftype(res, 2));
523 : : }
524 : :
525 [ - + - - ]: 2386 : if (PQfformat(res, 0) != 1 &&
526 [ # # ]: 0 : PQfformat(res, 1) != 1 &&
527 : 0 : PQfformat(res, 2) != 1)
528 : : {
529 : 0 : pg_fatal("unexpected result format while fetching remote files");
530 : : }
531 : :
532 [ + - - + ]: 4772 : if (PQgetisnull(res, 0, 0) ||
533 : 2386 : PQgetisnull(res, 0, 1))
534 : : {
535 : 0 : pg_fatal("unexpected null values in result while fetching remote files");
536 : : }
537 : :
538 [ - + ]: 2386 : if (PQgetlength(res, 0, 1) != sizeof(int64))
539 : 0 : pg_fatal("unexpected result length while fetching remote files");
540 : :
541 : : /* Read result set to local variables */
542 : 2386 : memcpy(&chunkoff, PQgetvalue(res, 0, 1), sizeof(int64));
543 : 2386 : chunkoff = pg_ntoh64(chunkoff);
544 : 2386 : chunksize = PQgetlength(res, 0, 2);
545 : :
546 : 2386 : filenamelen = PQgetlength(res, 0, 0);
547 : 2386 : filename = pg_malloc(filenamelen + 1);
548 : 2386 : memcpy(filename, PQgetvalue(res, 0, 0), filenamelen);
549 : 2386 : filename[filenamelen] = '\0';
550 : :
551 : 2386 : chunk = PQgetvalue(res, 0, 2);
552 : :
553 : : /*
554 : : * If a file has been deleted on the source, remove it on the target
555 : : * as well. Note that multiple unlink() calls may happen on the same
556 : : * file if multiple data chunks are associated with it, hence ignore
557 : : * unconditionally anything missing.
558 : : */
559 [ - + ]: 2386 : if (PQgetisnull(res, 0, 2))
560 : : {
561 [ # # ]: 0 : pg_log_debug("received null value for chunk for file \"%s\", file has been deleted",
562 : : filename);
563 : 0 : remove_target_file(filename, true);
564 : : }
565 : : else
566 : : {
567 [ + - ]: 2386 : pg_log_debug("received chunk for file \"%s\", offset %" PRId64 ", size %d",
568 : : filename, chunkoff, chunksize);
569 : :
570 [ - + ]: 2386 : if (strcmp(filename, rq->path) != 0)
571 : : {
572 : 0 : pg_fatal("received data for file \"%s\", when requested for \"%s\"",
573 : : filename, rq->path);
574 : : }
575 [ - + ]: 2386 : if (chunkoff != rq->offset)
576 : 0 : pg_fatal("received data at offset %" PRId64 " of file \"%s\", when requested for offset %lld",
577 : : chunkoff, rq->path, (long long int) rq->offset);
578 : :
579 : : /*
580 : : * We should not receive more data than we requested, or
581 : : * pg_read_binary_file() messed up. We could receive less,
582 : : * though, if the file was truncated in the source after we
583 : : * checked its size. That's OK, there should be a WAL record of
584 : : * the truncation, which will get replayed when you start the
585 : : * target system for the first time after pg_rewind has completed.
586 : : */
587 [ - + ]: 2386 : if (chunksize > rq->length)
588 : 0 : pg_fatal("received more than requested for file \"%s\"", rq->path);
589 : :
590 : 2386 : open_target_file(filename, false);
591 : :
592 : 2386 : write_target_range(chunk, chunkoff, chunksize);
593 : : }
594 : :
595 : 2386 : pg_free(filename);
596 : :
597 : 2386 : PQclear(res);
598 : 2386 : chunkno++;
599 : : }
600 [ - + ]: 6 : if (chunkno != src->num_requests)
601 : 0 : pg_fatal("unexpected number of data chunks received");
602 : :
603 : 6 : src->num_requests = 0;
604 : : }
605 : :
606 : : /*
607 : : * Escape a string to be used as element in a text array constant
608 : : */
609 : : static void
610 : 2386 : appendArrayEscapedString(StringInfo buf, const char *str)
611 : : {
612 [ - + ]: 2386 : appendStringInfoCharMacro(buf, '\"');
613 [ + + ]: 42372 : while (*str)
614 : : {
615 : 39986 : char ch = *str;
616 : :
617 [ + - - + ]: 39986 : if (ch == '"' || ch == '\\')
618 [ # # ]: 0 : appendStringInfoCharMacro(buf, '\\');
619 : :
620 [ + + ]: 39986 : appendStringInfoCharMacro(buf, ch);
621 : :
622 : 39986 : str++;
623 : : }
624 [ - + ]: 2386 : appendStringInfoCharMacro(buf, '\"');
625 : 2386 : }
626 : :
627 : : /*
628 : : * Fetch a single file as a malloc'd buffer.
629 : : */
630 : : static char *
631 : 17 : libpq_fetch_file(rewind_source *source, const char *path, size_t *filesize)
632 : : {
633 : 17 : PGconn *conn = ((libpq_source *) source)->conn;
634 : : PGresult *res;
635 : : char *result;
636 : : int len;
637 : : const char *paramValues[1];
638 : :
639 : 17 : paramValues[0] = path;
640 : 17 : res = PQexecParams(conn, "SELECT pg_read_binary_file($1)",
641 : : 1, NULL, paramValues, NULL, NULL, 1);
642 : :
643 [ - + ]: 17 : if (PQresultStatus(res) != PGRES_TUPLES_OK)
644 : 0 : pg_fatal("could not fetch remote file \"%s\": %s",
645 : : path, PQresultErrorMessage(res));
646 : :
647 : : /* sanity check the result set */
648 [ + - - + ]: 17 : if (PQntuples(res) != 1 || PQgetisnull(res, 0, 0))
649 : 0 : pg_fatal("unexpected result set while fetching remote file \"%s\"",
650 : : path);
651 : :
652 : : /* Read result to local variables */
653 : 17 : len = PQgetlength(res, 0, 0);
654 : 17 : result = pg_malloc(len + 1);
655 : 17 : memcpy(result, PQgetvalue(res, 0, 0), len);
656 : 17 : result[len] = '\0';
657 : :
658 : 17 : PQclear(res);
659 : :
660 [ + - ]: 17 : pg_log_debug("fetched file \"%s\", length %d", path, len);
661 : :
662 [ + + ]: 17 : if (filesize)
663 : 12 : *filesize = len;
664 : 17 : return result;
665 : : }
666 : :
667 : : /*
668 : : * Close a libpq source.
669 : : */
670 : : static void
671 : 6 : libpq_destroy(rewind_source *source)
672 : : {
673 : 6 : libpq_source *src = (libpq_source *) source;
674 : :
675 : 6 : pfree(src->paths.data);
676 : 6 : pfree(src->offsets.data);
677 : 6 : pfree(src->lengths.data);
678 : 6 : pfree(src);
679 : :
680 : : /* NOTE: we don't close the connection here, as it was not opened by us. */
681 : 6 : }
|