Branch data Line data Source code
1 : : /*-------------------------------------------------------------------------
2 : : *
3 : : * receivelog.c - receive WAL files using the streaming
4 : : * replication protocol.
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/receivelog.c
12 : : *-------------------------------------------------------------------------
13 : : */
14 : :
15 : : #include "postgres_fe.h"
16 : :
17 : : #include <sys/select.h>
18 : : #include <sys/stat.h>
19 : : #include <unistd.h>
20 : :
21 : : #include "access/xlog_internal.h"
22 : : #include "common/logging.h"
23 : : #include "common/pg_parse_lsn.h"
24 : : #include "libpq-fe.h"
25 : : #include "libpq/protocol.h"
26 : : #include "receivelog.h"
27 : : #include "streamutil.h"
28 : :
29 : : /* currently open WAL file */
30 : : static Walfile *walfile = NULL;
31 : : static bool reportFlushPosition = false;
32 : : static XLogRecPtr lastFlushPosition = InvalidXLogRecPtr;
33 : :
34 : : static bool still_sending = true; /* feedback still needs to be sent? */
35 : :
36 : : static PGresult *HandleCopyStream(PGconn *conn, StreamCtl *stream,
37 : : XLogRecPtr *stoppos);
38 : : static int CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket);
39 : : static int CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
40 : : char **buffer);
41 : : static bool ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf,
42 : : int len, XLogRecPtr blockpos, TimestampTz *last_status);
43 : : static bool ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
44 : : XLogRecPtr *blockpos);
45 : : static PGresult *HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
46 : : XLogRecPtr blockpos, XLogRecPtr *stoppos);
47 : : static bool CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos);
48 : : static long CalculateCopyStreamSleeptime(TimestampTz now, int standby_message_timeout,
49 : : TimestampTz last_status);
50 : :
51 : : static bool ReadEndOfStreamingResult(PGresult *res, XLogRecPtr *startpos,
52 : : uint32 *timeline);
53 : :
54 : : static bool
55 : 13 : mark_file_as_archived(StreamCtl *stream, const char *fname)
56 : : {
57 : : Walfile *f;
58 : : static char tmppath[MAXPGPATH];
59 : :
60 : 13 : snprintf(tmppath, sizeof(tmppath), "archive_status/%s.done",
61 : : fname);
62 : :
63 : 13 : f = stream->walmethod->ops->open_for_write(stream->walmethod, tmppath,
64 : : NULL, 0);
65 [ - + ]: 13 : if (f == NULL)
66 : : {
67 : 0 : pg_log_error("could not create archive status file \"%s\": %s",
68 : : tmppath, GetLastWalMethodError(stream->walmethod));
69 : 0 : return false;
70 : : }
71 : :
72 [ - + ]: 13 : if (stream->walmethod->ops->close(f, CLOSE_NORMAL) != 0)
73 : : {
74 : 0 : pg_log_error("could not close archive status file \"%s\": %s",
75 : : tmppath, GetLastWalMethodError(stream->walmethod));
76 : 0 : return false;
77 : : }
78 : :
79 : 13 : return true;
80 : : }
81 : :
82 : : /*
83 : : * Open a new WAL file in the specified directory.
84 : : *
85 : : * Returns true if OK; on failure, returns false after printing an error msg.
86 : : * On success, 'walfile' is set to the opened WAL file.
87 : : *
88 : : * The file will be padded to 16Mb with zeroes.
89 : : */
90 : : static bool
91 : 182 : open_walfile(StreamCtl *stream, XLogRecPtr startpoint)
92 : : {
93 : : Walfile *f;
94 : : char *fn;
95 : : ssize_t size;
96 : : XLogSegNo segno;
97 : : char walfile_name[MAXPGPATH];
98 : :
99 : 182 : XLByteToSeg(startpoint, segno, WalSegSz);
100 : 182 : XLogFileName(walfile_name, stream->timeline, segno, WalSegSz);
101 : :
102 : : /* Note that this considers the compression used if necessary */
103 : 182 : fn = stream->walmethod->ops->get_file_name(stream->walmethod,
104 : : walfile_name,
105 : 182 : stream->partial_suffix);
106 : :
107 : : /*
108 : : * When streaming to files, if an existing file exists we verify that it's
109 : : * either empty (just created), or a complete WalSegSz segment (in which
110 : : * case it has been created and padded). Anything else indicates a corrupt
111 : : * file. Compressed files have no need for padding, so just ignore this
112 : : * case.
113 : : *
114 : : * When streaming to tar, no file with this name will exist before, so we
115 : : * never have to verify a size.
116 : : */
117 [ + + - + ]: 356 : if (stream->walmethod->compression_algorithm == PG_COMPRESSION_NONE &&
118 : 174 : stream->walmethod->ops->existsfile(stream->walmethod, fn))
119 : : {
120 : 0 : size = stream->walmethod->ops->get_file_size(stream->walmethod, fn);
121 [ # # ]: 0 : if (size < 0)
122 : : {
123 : 0 : pg_log_error("could not get size of write-ahead log file \"%s\": %s",
124 : : fn, GetLastWalMethodError(stream->walmethod));
125 : 0 : pg_free(fn);
126 : 0 : return false;
127 : : }
128 [ # # ]: 0 : if (size == WalSegSz)
129 : : {
130 : : /* Already padded file. Open it for use */
131 : 0 : f = stream->walmethod->ops->open_for_write(stream->walmethod, walfile_name, stream->partial_suffix, 0);
132 [ # # ]: 0 : if (f == NULL)
133 : : {
134 : 0 : pg_log_error("could not open existing write-ahead log file \"%s\": %s",
135 : : fn, GetLastWalMethodError(stream->walmethod));
136 : 0 : pg_free(fn);
137 : 0 : return false;
138 : : }
139 : :
140 : : /* fsync file in case of a previous crash */
141 [ # # ]: 0 : if (stream->walmethod->ops->sync(f) != 0)
142 : : {
143 : 0 : pg_log_error("could not fsync existing write-ahead log file \"%s\": %s",
144 : : fn, GetLastWalMethodError(stream->walmethod));
145 : 0 : stream->walmethod->ops->close(f, CLOSE_UNLINK);
146 : 0 : exit(1);
147 : : }
148 : :
149 : 0 : walfile = f;
150 : 0 : pg_free(fn);
151 : 0 : return true;
152 : : }
153 [ # # ]: 0 : if (size != 0)
154 : : {
155 : : /* if write didn't set errno, assume problem is no disk space */
156 [ # # ]: 0 : if (errno == 0)
157 : 0 : errno = ENOSPC;
158 : 0 : pg_log_error(ngettext("write-ahead log file \"%s\" has %zd byte, should be 0 or %d",
159 : : "write-ahead log file \"%s\" has %zd bytes, should be 0 or %d",
160 : : size),
161 : : fn, size, WalSegSz);
162 : 0 : pg_free(fn);
163 : 0 : return false;
164 : : }
165 : : /* File existed and was empty, so fall through and open */
166 : : }
167 : :
168 : : /* No file existed, so create one */
169 : :
170 : 182 : f = stream->walmethod->ops->open_for_write(stream->walmethod,
171 : : walfile_name,
172 : 182 : stream->partial_suffix,
173 : : WalSegSz);
174 [ - + ]: 182 : if (f == NULL)
175 : : {
176 : 0 : pg_log_error("could not open write-ahead log file \"%s\": %s",
177 : : fn, GetLastWalMethodError(stream->walmethod));
178 : 0 : pg_free(fn);
179 : 0 : return false;
180 : : }
181 : :
182 : 182 : pg_free(fn);
183 : 182 : walfile = f;
184 : 182 : return true;
185 : : }
186 : :
187 : : /*
188 : : * Close the current WAL file (if open), and rename it to the correct
189 : : * filename if it's complete. On failure, prints an error message to stderr
190 : : * and returns false, otherwise returns true.
191 : : */
192 : : static bool
193 : 189 : close_walfile(StreamCtl *stream, XLogRecPtr pos)
194 : : {
195 : : char *fn;
196 : : pgoff_t currpos;
197 : : int r;
198 : : char walfile_name[MAXPGPATH];
199 : :
200 [ + + ]: 189 : if (walfile == NULL)
201 : 7 : return true;
202 : :
203 : 182 : strlcpy(walfile_name, walfile->pathname, MAXPGPATH);
204 : 182 : currpos = walfile->currpos;
205 : :
206 : : /* Note that this considers the compression used if necessary */
207 : 182 : fn = stream->walmethod->ops->get_file_name(stream->walmethod,
208 : : walfile_name,
209 : 182 : stream->partial_suffix);
210 : :
211 [ + + ]: 182 : if (stream->partial_suffix)
212 : : {
213 [ + + ]: 12 : if (currpos == WalSegSz)
214 : 6 : r = stream->walmethod->ops->close(walfile, CLOSE_NORMAL);
215 : : else
216 : : {
217 : 6 : pg_log_info("not renaming \"%s\", segment is not complete", fn);
218 : 6 : r = stream->walmethod->ops->close(walfile, CLOSE_NO_RENAME);
219 : : }
220 : : }
221 : : else
222 : 170 : r = stream->walmethod->ops->close(walfile, CLOSE_NORMAL);
223 : :
224 : 182 : walfile = NULL;
225 : :
226 [ - + ]: 182 : if (r != 0)
227 : : {
228 : 0 : pg_log_error("could not close file \"%s\": %s",
229 : : fn, GetLastWalMethodError(stream->walmethod));
230 : :
231 : 0 : pg_free(fn);
232 : 0 : return false;
233 : : }
234 : :
235 : 182 : pg_free(fn);
236 : :
237 : : /*
238 : : * Mark file as archived if requested by the caller - pg_basebackup needs
239 : : * to do so as files can otherwise get archived again after promotion of a
240 : : * new node. This is in line with walreceiver.c always doing a
241 : : * XLogArchiveForceDone() after a complete segment.
242 : : */
243 [ + + + + ]: 182 : if (currpos == WalSegSz && stream->mark_done)
244 : : {
245 : : /* writes error message if failed */
246 [ - + ]: 7 : if (!mark_file_as_archived(stream, walfile_name))
247 : 0 : return false;
248 : : }
249 : :
250 : 182 : lastFlushPosition = pos;
251 : 182 : return true;
252 : : }
253 : :
254 : :
255 : : /*
256 : : * Check if a timeline history file exists.
257 : : */
258 : : static bool
259 : 177 : existsTimeLineHistoryFile(StreamCtl *stream)
260 : : {
261 : : char histfname[MAXFNAMELEN];
262 : :
263 : : /*
264 : : * Timeline 1 never has a history file. We treat that as if it existed,
265 : : * since we never need to stream it.
266 : : */
267 [ + + ]: 177 : if (stream->timeline == 1)
268 : 170 : return true;
269 : :
270 : 7 : TLHistoryFileName(histfname, stream->timeline);
271 : :
272 : 7 : return stream->walmethod->ops->existsfile(stream->walmethod, histfname);
273 : : }
274 : :
275 : : static bool
276 : 7 : writeTimeLineHistoryFile(StreamCtl *stream, const char *filename, const char *content)
277 : : {
278 : 7 : size_t size = strlen(content);
279 : : char histfname[MAXFNAMELEN];
280 : : Walfile *f;
281 : :
282 : : /*
283 : : * Check that the server's idea of how timeline history files should be
284 : : * named matches ours.
285 : : */
286 : 7 : TLHistoryFileName(histfname, stream->timeline);
287 [ - + ]: 7 : if (strcmp(histfname, filename) != 0)
288 : : {
289 : 0 : pg_log_error("server reported unexpected history file name for timeline %u: %s",
290 : : stream->timeline, filename);
291 : 0 : return false;
292 : : }
293 : :
294 : 7 : f = stream->walmethod->ops->open_for_write(stream->walmethod,
295 : : histfname, ".tmp", 0);
296 [ - + ]: 7 : if (f == NULL)
297 : : {
298 : 0 : pg_log_error("could not create timeline history file \"%s\": %s",
299 : : histfname, GetLastWalMethodError(stream->walmethod));
300 : 0 : return false;
301 : : }
302 : :
303 [ - + ]: 7 : if (stream->walmethod->ops->write(f, content, size) != size)
304 : : {
305 : 0 : pg_log_error("could not write timeline history file \"%s\": %s",
306 : : histfname, GetLastWalMethodError(stream->walmethod));
307 : :
308 : : /*
309 : : * If we fail to make the file, delete it to release disk space
310 : : */
311 : 0 : stream->walmethod->ops->close(f, CLOSE_UNLINK);
312 : :
313 : 0 : return false;
314 : : }
315 : :
316 [ - + ]: 7 : if (stream->walmethod->ops->close(f, CLOSE_NORMAL) != 0)
317 : : {
318 : 0 : pg_log_error("could not close file \"%s\": %s",
319 : : histfname, GetLastWalMethodError(stream->walmethod));
320 : 0 : return false;
321 : : }
322 : :
323 : : /* Maintain archive_status, check close_walfile() for details. */
324 [ + + ]: 7 : if (stream->mark_done)
325 : : {
326 : : /* writes error message if failed */
327 [ - + ]: 6 : if (!mark_file_as_archived(stream, histfname))
328 : 0 : return false;
329 : : }
330 : :
331 : 7 : return true;
332 : : }
333 : :
334 : : /*
335 : : * Send a Standby Status Update message to server.
336 : : */
337 : : static bool
338 : 176 : sendFeedback(PGconn *conn, XLogRecPtr blockpos, TimestampTz now, bool replyRequested)
339 : : {
340 : : char replybuf[1 + 8 + 8 + 8 + 8 + 1];
341 : 176 : int len = 0;
342 : :
343 : 176 : replybuf[len] = PqReplMsg_StandbyStatusUpdate;
344 : 176 : len += 1;
345 : 176 : fe_sendint64(blockpos, &replybuf[len]); /* write */
346 : 176 : len += 8;
347 [ + + ]: 176 : if (reportFlushPosition)
348 : 172 : fe_sendint64(lastFlushPosition, &replybuf[len]); /* flush */
349 : : else
350 : 4 : fe_sendint64(InvalidXLogRecPtr, &replybuf[len]); /* flush */
351 : 176 : len += 8;
352 : 176 : fe_sendint64(InvalidXLogRecPtr, &replybuf[len]); /* apply */
353 : 176 : len += 8;
354 : 176 : fe_sendint64(now, &replybuf[len]); /* sendTime */
355 : 176 : len += 8;
356 : 176 : replybuf[len] = replyRequested ? 1 : 0; /* replyRequested */
357 : 176 : len += 1;
358 : :
359 [ + - - + ]: 176 : if (PQputCopyData(conn, replybuf, len) <= 0 || PQflush(conn))
360 : : {
361 : 0 : pg_log_error("could not send feedback packet: %s",
362 : : PQerrorMessage(conn));
363 : 0 : return false;
364 : : }
365 : :
366 : 176 : return true;
367 : : }
368 : :
369 : : /*
370 : : * Check that the server version we're connected to is supported by
371 : : * ReceiveXlogStream().
372 : : *
373 : : * If it's not, an error message is printed to stderr, and false is returned.
374 : : */
375 : : bool
376 : 374 : CheckServerVersionForStreaming(PGconn *conn)
377 : : {
378 : : int minServerMajor,
379 : : maxServerMajor;
380 : : int serverMajor;
381 : :
382 : : /*
383 : : * The message format used in streaming replication changed in 9.3, so we
384 : : * cannot stream from older servers. And we don't support servers newer
385 : : * than the client; it might work, but we don't know, so err on the safe
386 : : * side.
387 : : */
388 : 374 : minServerMajor = 903;
389 : 374 : maxServerMajor = PG_VERSION_NUM / 100;
390 : 374 : serverMajor = PQserverVersion(conn) / 100;
391 [ - + ]: 374 : if (serverMajor < minServerMajor)
392 : : {
393 : 0 : const char *serverver = PQparameterStatus(conn, "server_version");
394 : :
395 [ # # ]: 0 : pg_log_error("incompatible server version %s; client does not support streaming from server versions older than %s",
396 : : serverver ? serverver : "'unknown'",
397 : : "9.3");
398 : 0 : return false;
399 : : }
400 [ - + ]: 374 : else if (serverMajor > maxServerMajor)
401 : : {
402 : 0 : const char *serverver = PQparameterStatus(conn, "server_version");
403 : :
404 [ # # ]: 0 : pg_log_error("incompatible server version %s; client does not support streaming from server versions newer than %s",
405 : : serverver ? serverver : "'unknown'",
406 : : PG_VERSION);
407 : 0 : return false;
408 : : }
409 : 374 : return true;
410 : : }
411 : :
412 : : /*
413 : : * Receive a log stream starting at the specified position.
414 : : *
415 : : * Individual parameters are passed through the StreamCtl structure.
416 : : *
417 : : * If sysidentifier is specified, validate that both the system
418 : : * identifier and the timeline matches the specified ones
419 : : * (by sending an extra IDENTIFY_SYSTEM command)
420 : : *
421 : : * All received segments will be written to the directory
422 : : * specified by basedir. This will also fetch any missing timeline history
423 : : * files.
424 : : *
425 : : * The stream_stop callback will be called every time data
426 : : * is received, and whenever a segment is completed. If it returns
427 : : * true, the streaming will stop and the function
428 : : * return. As long as it returns false, streaming will continue
429 : : * indefinitely.
430 : : *
431 : : * If stream_stop() checks for external input, stop_socket should be set to
432 : : * the FD it checks. This will allow such input to be detected promptly
433 : : * rather than after standby_message_timeout (which might be indefinite).
434 : : * Note that signals will interrupt waits for input as well, but that is
435 : : * race-y since a signal received while busy won't interrupt the wait.
436 : : *
437 : : * standby_message_timeout controls how often we send a message
438 : : * back to the primary letting it know our progress, in milliseconds.
439 : : * Zero means no messages are sent.
440 : : * This message will only contain the write location, and never
441 : : * flush or replay.
442 : : *
443 : : * If 'partial_suffix' is not NULL, files are initially created with the
444 : : * given suffix, and the suffix is removed once the file is finished. That
445 : : * allows you to tell the difference between partial and completed files,
446 : : * so that you can continue later where you left.
447 : : *
448 : : * If 'synchronous' is true, the received WAL is flushed as soon as written,
449 : : * otherwise only when the WAL file is closed.
450 : : *
451 : : * Note: The WAL location *must* be at a log segment start!
452 : : */
453 : : bool
454 : 176 : ReceiveXlogStream(PGconn *conn, StreamCtl *stream)
455 : : {
456 : : PQExpBuffer query;
457 : : PGresult *res;
458 : : XLogRecPtr stoppos;
459 : :
460 : : /*
461 : : * The caller should've checked the server version already, but doesn't do
462 : : * any harm to check it here too.
463 : : */
464 [ - + ]: 176 : if (!CheckServerVersionForStreaming(conn))
465 : 0 : return false;
466 : :
467 : : /*
468 : : * Decide whether we want to report the flush position. If we report the
469 : : * flush position, the primary will know what WAL we'll possibly
470 : : * re-request, and it can then remove older WAL safely. We must always do
471 : : * that when we are using slots.
472 : : *
473 : : * Reporting the flush position makes one eligible as a synchronous
474 : : * replica. People shouldn't include generic names in
475 : : * synchronous_standby_names, but we've protected them against it so far,
476 : : * so let's continue to do so unless specifically requested.
477 : : */
478 [ + + ]: 176 : if (stream->replication_slot != NULL)
479 : : {
480 : 171 : reportFlushPosition = true;
481 : : }
482 : : else
483 : : {
484 [ + + ]: 5 : if (stream->synchronous)
485 : 1 : reportFlushPosition = true;
486 : : else
487 : 4 : reportFlushPosition = false;
488 : : }
489 : :
490 [ + - ]: 176 : if (stream->sysidentifier != NULL)
491 : : {
492 : 176 : char *sysidentifier = NULL;
493 : : TimeLineID servertli;
494 : :
495 : : /*
496 : : * Get the server system identifier and timeline, and validate them.
497 : : */
498 [ - + ]: 176 : if (!RunIdentifySystem(conn, &sysidentifier, &servertli, NULL, NULL))
499 : : {
500 : 0 : pg_free(sysidentifier);
501 : 0 : return false;
502 : : }
503 : :
504 [ - + ]: 176 : if (strcmp(stream->sysidentifier, sysidentifier) != 0)
505 : : {
506 : 0 : pg_log_error("system identifier does not match between base backup and streaming connection");
507 : 0 : pg_free(sysidentifier);
508 : 0 : return false;
509 : : }
510 : 176 : pg_free(sysidentifier);
511 : :
512 [ - + ]: 176 : if (stream->timeline > servertli)
513 : : {
514 : 0 : pg_log_error("starting timeline %u is not present in the server",
515 : : stream->timeline);
516 : 0 : return false;
517 : : }
518 : : }
519 : :
520 : : /*
521 : : * initialize flush position to starting point, it's the caller's
522 : : * responsibility that that's sane.
523 : : */
524 : 176 : lastFlushPosition = stream->startpos;
525 : :
526 : : while (1)
527 : 1 : {
528 : : /*
529 : : * Fetch the timeline history file for this timeline, if we don't have
530 : : * it already. When streaming log to tar, this will always return
531 : : * false, as we are never streaming into an existing file and
532 : : * therefore there can be no pre-existing timeline history file.
533 : : */
534 [ + + ]: 177 : if (!existsTimeLineHistoryFile(stream))
535 : : {
536 : 7 : query = createPQExpBuffer();
537 : 7 : appendPQExpBuffer(query, "TIMELINE_HISTORY %u", stream->timeline);
538 : 7 : res = PQexec(conn, query->data);
539 : 7 : destroyPQExpBuffer(query);
540 [ - + ]: 7 : if (PQresultStatus(res) != PGRES_TUPLES_OK)
541 : : {
542 : : /* FIXME: we might send it ok, but get an error */
543 : 0 : pg_log_error("could not send replication command \"%s\": %s",
544 : : "TIMELINE_HISTORY", PQresultErrorMessage(res));
545 : 0 : PQclear(res);
546 : 0 : return false;
547 : : }
548 : :
549 : : /*
550 : : * The response to TIMELINE_HISTORY is a single row result set
551 : : * with two fields: filename and content
552 : : */
553 [ + - - + ]: 7 : if (PQnfields(res) != 2 || PQntuples(res) != 1)
554 : : {
555 : 0 : pg_log_error("unexpected response to TIMELINE_HISTORY command: got %d rows and %d fields, expected %d rows and %d fields",
556 : : PQntuples(res), PQnfields(res), 1, 2);
557 : 0 : PQclear(res);
558 : 0 : return false;
559 : : }
560 : :
561 : : /* Write the history file to disk */
562 [ - + ]: 7 : if (!writeTimeLineHistoryFile(stream,
563 : 7 : PQgetvalue(res, 0, 0),
564 : 7 : PQgetvalue(res, 0, 1)))
565 : : {
566 : : /* Error message written in writeTimeLineHistoryFile() */
567 : 0 : PQclear(res);
568 : 0 : return false;
569 : : }
570 : :
571 : 7 : PQclear(res);
572 : : }
573 : :
574 : : /*
575 : : * Before we start streaming from the requested location, check if the
576 : : * callback tells us to stop here.
577 : : */
578 [ - + ]: 177 : if (stream->stream_stop(stream->startpos, stream->timeline, false))
579 : 0 : return true;
580 : :
581 : : /* Initiate the replication stream at specified location */
582 : 177 : query = createPQExpBuffer();
583 : 177 : appendPQExpBufferStr(query, "START_REPLICATION");
584 [ + + ]: 177 : if (stream->replication_slot != NULL)
585 : : {
586 : 172 : appendPQExpBufferStr(query, " SLOT ");
587 : 172 : AppendQuotedIdentifier(query, stream->replication_slot);
588 : : }
589 : 177 : appendPQExpBuffer(query, " %X/%08X TIMELINE %u",
590 : 177 : LSN_FORMAT_ARGS(stream->startpos),
591 : : stream->timeline);
592 : 177 : res = PQexec(conn, query->data);
593 : 177 : destroyPQExpBuffer(query);
594 [ + + ]: 177 : if (PQresultStatus(res) != PGRES_COPY_BOTH)
595 : : {
596 : 1 : pg_log_error("could not send replication command \"%s\": %s",
597 : : "START_REPLICATION", PQresultErrorMessage(res));
598 : 1 : PQclear(res);
599 : 1 : return false;
600 : : }
601 : 176 : PQclear(res);
602 : :
603 : : /* Stream the WAL */
604 : 176 : res = HandleCopyStream(conn, stream, &stoppos);
605 [ - + ]: 176 : if (res == NULL)
606 : 0 : goto error;
607 : :
608 : : /*
609 : : * Streaming finished.
610 : : *
611 : : * There are two possible reasons for that: a controlled shutdown, or
612 : : * we reached the end of the current timeline. In case of
613 : : * end-of-timeline, the server sends a result set after Copy has
614 : : * finished, containing information about the next timeline. Read
615 : : * that, and restart streaming from the next timeline. In case of
616 : : * controlled shutdown, stop here.
617 : : */
618 [ + + ]: 176 : if (PQresultStatus(res) == PGRES_TUPLES_OK)
619 : 1 : {
620 : : /*
621 : : * End-of-timeline. Read the next timeline's ID and starting
622 : : * position. Usually, the starting position will match the end of
623 : : * the previous timeline, but there are corner cases like if the
624 : : * server had sent us half of a WAL record, when it was promoted.
625 : : * The new timeline will begin at the end of the last complete
626 : : * record in that case, overlapping the partial WAL record on the
627 : : * old timeline.
628 : : */
629 : : uint32 newtimeline;
630 : : bool parsed;
631 : :
632 : 1 : parsed = ReadEndOfStreamingResult(res, &stream->startpos, &newtimeline);
633 : 1 : PQclear(res);
634 [ - + ]: 1 : if (!parsed)
635 : 0 : goto error;
636 : :
637 : : /* Sanity check the values the server gave us */
638 [ - + ]: 1 : if (newtimeline <= stream->timeline)
639 : : {
640 : 0 : pg_log_error("server reported unexpected next timeline %u, following timeline %u",
641 : : newtimeline, stream->timeline);
642 : 0 : goto error;
643 : : }
644 [ - + ]: 1 : if (stream->startpos > stoppos)
645 : : {
646 : 0 : pg_log_error("server stopped streaming timeline %u at %X/%08X, but reported next timeline %u to begin at %X/%08X",
647 : : stream->timeline, LSN_FORMAT_ARGS(stoppos),
648 : : newtimeline, LSN_FORMAT_ARGS(stream->startpos));
649 : 0 : goto error;
650 : : }
651 : :
652 : : /* Read the final result, which should be CommandComplete. */
653 : 1 : res = PQgetResult(conn);
654 [ - + ]: 1 : if (PQresultStatus(res) != PGRES_COMMAND_OK)
655 : : {
656 : 0 : pg_log_error("unexpected termination of replication stream: %s",
657 : : PQresultErrorMessage(res));
658 : 0 : PQclear(res);
659 : 0 : goto error;
660 : : }
661 : 1 : PQclear(res);
662 : :
663 : : /*
664 : : * Loop back to start streaming from the new timeline. Always
665 : : * start streaming at the beginning of a segment.
666 : : */
667 : 1 : stream->timeline = newtimeline;
668 : 1 : stream->startpos = stream->startpos -
669 : 1 : XLogSegmentOffset(stream->startpos, WalSegSz);
670 : 1 : continue;
671 : : }
672 [ + + ]: 175 : else if (PQresultStatus(res) == PGRES_COMMAND_OK)
673 : : {
674 : 174 : PQclear(res);
675 : :
676 : : /*
677 : : * End of replication (ie. controlled shut down of the server).
678 : : *
679 : : * Check if the callback thinks it's OK to stop here. If not,
680 : : * complain.
681 : : */
682 [ + - ]: 174 : if (stream->stream_stop(stoppos, stream->timeline, false))
683 : 174 : return true;
684 : : else
685 : : {
686 : 0 : pg_log_error("replication stream was terminated before stop point");
687 : 0 : goto error;
688 : : }
689 : : }
690 : : else
691 : : {
692 : : /* Server returned an error. */
693 : 1 : pg_log_error("unexpected termination of replication stream: %s",
694 : : PQresultErrorMessage(res));
695 : 1 : PQclear(res);
696 : 1 : goto error;
697 : : }
698 : : }
699 : :
700 : 1 : error:
701 [ - + ]: 1 : if (walfile != NULL)
702 : : {
703 : : char walfile_name[MAXPGPATH];
704 : :
705 : : /* The close method can free walfile even on failure. */
706 : 0 : strlcpy(walfile_name, walfile->pathname, sizeof(walfile_name));
707 [ # # ]: 0 : if (stream->walmethod->ops->close(walfile, CLOSE_NO_RENAME) != 0)
708 : 0 : pg_log_error("could not close file \"%s\": %s",
709 : : walfile_name, GetLastWalMethodError(stream->walmethod));
710 : : }
711 : 1 : walfile = NULL;
712 : 1 : return false;
713 : : }
714 : :
715 : : /*
716 : : * Helper function to parse the result set returned by server after streaming
717 : : * has finished. On failure, prints an error to stderr and returns false.
718 : : */
719 : : static bool
720 : 1 : ReadEndOfStreamingResult(PGresult *res, XLogRecPtr *startpos, uint32 *timeline)
721 : : {
722 : : /*----------
723 : : * The result set consists of one row and two columns, e.g:
724 : : *
725 : : * next_tli | next_tli_startpos
726 : : * ----------+-------------------
727 : : * 4 | 0/9949AE0
728 : : *
729 : : * next_tli is the timeline ID of the next timeline after the one that
730 : : * just finished streaming. next_tli_startpos is the WAL location where
731 : : * the server switched to it.
732 : : *----------
733 : : */
734 [ + - - + ]: 1 : if (PQnfields(res) < 2 || PQntuples(res) != 1)
735 : : {
736 : 0 : pg_log_error("unexpected result set after end-of-timeline: got %d rows and %d fields, expected %d rows and %d fields",
737 : : PQntuples(res), PQnfields(res), 1, 2);
738 : 0 : return false;
739 : : }
740 : :
741 : 1 : *timeline = atoi(PQgetvalue(res, 0, 0));
742 [ - + ]: 1 : if (!pg_parse_lsn(PQgetvalue(res, 0, 1), startpos))
743 : : {
744 : 0 : pg_log_error("could not parse next timeline's starting point \"%s\"",
745 : : PQgetvalue(res, 0, 1));
746 : 0 : return false;
747 : : }
748 : :
749 : 1 : return true;
750 : : }
751 : :
752 : : /*
753 : : * The main loop of ReceiveXlogStream. Handles the COPY stream after
754 : : * initiating streaming with the START_REPLICATION command.
755 : : *
756 : : * If the COPY ends (not necessarily successfully) due a message from the
757 : : * server, returns a PGresult and sets *stoppos to the last byte written.
758 : : * On any other sort of error, returns NULL.
759 : : */
760 : : static PGresult *
761 : 176 : HandleCopyStream(PGconn *conn, StreamCtl *stream,
762 : : XLogRecPtr *stoppos)
763 : : {
764 : 176 : char *copybuf = NULL;
765 : 176 : TimestampTz last_status = -1;
766 : 176 : XLogRecPtr blockpos = stream->startpos;
767 : :
768 : 176 : still_sending = true;
769 : :
770 : : while (1)
771 : 558 : {
772 : : int r;
773 : : TimestampTz now;
774 : : long sleeptime;
775 : :
776 : : /*
777 : : * Check if we should continue streaming, or abort at this point.
778 : : */
779 [ - + ]: 734 : if (!CheckCopyStreamStop(conn, stream, blockpos))
780 : 0 : goto error;
781 : :
782 : 734 : now = feGetCurrentTimestamp();
783 : :
784 : : /*
785 : : * If synchronous option is true, issue sync command as soon as there
786 : : * are WAL data which has not been flushed yet.
787 : : */
788 [ + + - + : 734 : if (stream->synchronous && lastFlushPosition < blockpos && walfile != NULL)
- - ]
789 : : {
790 [ # # ]: 0 : if (stream->walmethod->ops->sync(walfile) != 0)
791 : 0 : pg_fatal("could not fsync file \"%s\": %s",
792 : : walfile->pathname, GetLastWalMethodError(stream->walmethod));
793 : 0 : lastFlushPosition = blockpos;
794 : :
795 : : /*
796 : : * Send feedback so that the server sees the latest WAL locations
797 : : * immediately.
798 : : */
799 [ # # ]: 0 : if (!sendFeedback(conn, blockpos, now, false))
800 : 0 : goto error;
801 : 0 : last_status = now;
802 : : }
803 : :
804 : : /*
805 : : * Potentially send a status message to the primary
806 : : */
807 [ + + + - : 1398 : if (still_sending && stream->standby_message_timeout > 0 &&
+ + ]
808 : 664 : feTimestampDifferenceExceeds(last_status, now,
809 : : stream->standby_message_timeout))
810 : : {
811 : : /* Time to send feedback! */
812 [ - + ]: 176 : if (!sendFeedback(conn, blockpos, now, false))
813 : 0 : goto error;
814 : 176 : last_status = now;
815 : : }
816 : :
817 : : /*
818 : : * Calculate how long send/receive loops should sleep
819 : : */
820 : 734 : sleeptime = CalculateCopyStreamSleeptime(now, stream->standby_message_timeout,
821 : : last_status);
822 : :
823 : : /* Done with any prior message */
824 : 734 : PQfreemem(copybuf);
825 : 734 : copybuf = NULL;
826 : :
827 : 734 : r = CopyStreamReceive(conn, sleeptime, stream->stop_socket, ©buf);
828 [ + + ]: 2999 : while (r != 0)
829 : : {
830 [ - + ]: 2441 : if (r == -1)
831 : 0 : goto error;
832 [ + + ]: 2441 : if (r == -2)
833 : : {
834 : 176 : PGresult *res = HandleEndOfCopyStream(conn, stream, copybuf, blockpos, stoppos);
835 : :
836 [ - + ]: 176 : if (res == NULL)
837 : 0 : goto error;
838 : 176 : PQfreemem(copybuf);
839 : 176 : return res;
840 : : }
841 : :
842 : : /* Check the message type. */
843 [ - + ]: 2265 : if (copybuf[0] == PqReplMsg_Keepalive)
844 : : {
845 [ # # ]: 0 : if (!ProcessKeepaliveMsg(conn, stream, copybuf, r, blockpos,
846 : : &last_status))
847 : 0 : goto error;
848 : : }
849 [ + - ]: 2265 : else if (copybuf[0] == PqReplMsg_WALData)
850 : : {
851 [ - + ]: 2265 : if (!ProcessWALDataMsg(conn, stream, copybuf, r, &blockpos))
852 : 0 : goto error;
853 : :
854 : : /*
855 : : * Check if we should continue streaming, or abort at this
856 : : * point.
857 : : */
858 [ - + ]: 2265 : if (!CheckCopyStreamStop(conn, stream, blockpos))
859 : 0 : goto error;
860 : : }
861 : : else
862 : : {
863 : 0 : pg_log_error("unrecognized streaming header: \"%c\"",
864 : : copybuf[0]);
865 : 0 : goto error;
866 : : }
867 : :
868 : : /* Done with that message */
869 : 2265 : PQfreemem(copybuf);
870 : 2265 : copybuf = NULL;
871 : :
872 : : /*
873 : : * Process the received data, and any subsequent data we can read
874 : : * without blocking.
875 : : */
876 : 2265 : r = CopyStreamReceive(conn, 0, stream->stop_socket, ©buf);
877 : : }
878 : : }
879 : :
880 : 0 : error:
881 : 0 : PQfreemem(copybuf);
882 : 0 : return NULL;
883 : : }
884 : :
885 : : /*
886 : : * Wait until we can read a CopyData message,
887 : : * or timeout, or occurrence of a signal or input on the stop_socket.
888 : : * (timeout_ms < 0 means wait indefinitely; 0 means don't wait.)
889 : : *
890 : : * Returns 1 if data has become available for reading, 0 if timed out
891 : : * or interrupted by signal or stop_socket input, and -1 on an error.
892 : : */
893 : : static int
894 : 2702 : CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
895 : : {
896 : : int ret;
897 : : fd_set input_mask;
898 : : int connsocket;
899 : : int maxfd;
900 : : struct timeval timeout;
901 : : struct timeval *timeoutptr;
902 : :
903 : 2702 : connsocket = PQsocket(conn);
904 [ - + ]: 2702 : if (connsocket < 0)
905 : : {
906 : 0 : pg_log_error("invalid socket: %s", PQerrorMessage(conn));
907 : 0 : return -1;
908 : : }
909 : :
910 [ + + ]: 45934 : FD_ZERO(&input_mask);
911 : 2702 : FD_SET(connsocket, &input_mask);
912 : 2702 : maxfd = connsocket;
913 [ + + ]: 2702 : if (stop_socket != PGINVALID_SOCKET)
914 : : {
915 : 2639 : FD_SET(stop_socket, &input_mask);
916 : 2639 : maxfd = Max(maxfd, stop_socket);
917 : : }
918 : :
919 [ + + ]: 2702 : if (timeout_ms < 0)
920 : 70 : timeoutptr = NULL;
921 : : else
922 : : {
923 : 2632 : timeout.tv_sec = timeout_ms / 1000L;
924 : 2632 : timeout.tv_usec = (timeout_ms % 1000L) * 1000L;
925 : 2632 : timeoutptr = &timeout;
926 : : }
927 : :
928 : 2702 : ret = select(maxfd + 1, &input_mask, NULL, NULL, timeoutptr);
929 : :
930 [ - + ]: 2702 : if (ret < 0)
931 : : {
932 [ # # ]: 0 : if (errno == EINTR)
933 : 0 : return 0; /* Got a signal, so not an error */
934 : 0 : pg_log_error("%s() failed: %m", "select");
935 : 0 : return -1;
936 : : }
937 [ + + + + ]: 2702 : if (ret > 0 && FD_ISSET(connsocket, &input_mask))
938 : 2384 : return 1; /* Got input on connection socket */
939 : :
940 : 318 : return 0; /* Got timeout or input on stop_socket */
941 : : }
942 : :
943 : : /*
944 : : * Receive CopyData message available from XLOG stream, blocking for
945 : : * maximum of 'timeout' ms.
946 : : *
947 : : * If data was received, returns the length of the data. *buffer is set to
948 : : * point to a buffer holding the received message. The caller must eventually
949 : : * free the buffer with PQfreemem().
950 : : *
951 : : * Returns 0 if no data was available within timeout, or if wait was
952 : : * interrupted by signal or stop_socket input.
953 : : * -1 on error. -2 if the server ended the COPY.
954 : : */
955 : : static int
956 : 2999 : CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
957 : : char **buffer)
958 : : {
959 : 2999 : char *copybuf = NULL;
960 : : int rawlen;
961 : :
962 : : /* Caller should have cleared any prior buffer */
963 : : Assert(*buffer == NULL);
964 : :
965 : : /* Try to receive a CopyData message */
966 : 2999 : rawlen = PQgetCopyData(conn, ©buf, 1);
967 [ + + ]: 2999 : if (rawlen == 0)
968 : : {
969 : : int ret;
970 : :
971 : : /*
972 : : * No data available. Wait for some to appear, but not longer than
973 : : * the specified timeout, so that we can ping the server. Also stop
974 : : * waiting if input appears on stop_socket.
975 : : */
976 : 2702 : ret = CopyStreamPoll(conn, timeout, stop_socket);
977 [ + + ]: 2702 : if (ret <= 0)
978 : 318 : return ret;
979 : :
980 : : /* Now there is actually data on the socket */
981 [ - + ]: 2384 : if (PQconsumeInput(conn) == 0)
982 : : {
983 : 0 : pg_log_error("could not receive data from WAL stream: %s",
984 : : PQerrorMessage(conn));
985 : 0 : return -1;
986 : : }
987 : :
988 : : /* Now that we've consumed some input, try again */
989 : 2384 : rawlen = PQgetCopyData(conn, ©buf, 1);
990 [ + + ]: 2384 : if (rawlen == 0)
991 : 240 : return 0;
992 : : }
993 [ + + ]: 2441 : if (rawlen == -1) /* end-of-streaming or error */
994 : 176 : return -2;
995 [ - + ]: 2265 : if (rawlen == -2)
996 : : {
997 : 0 : pg_log_error("could not read COPY data: %s", PQerrorMessage(conn));
998 : 0 : return -1;
999 : : }
1000 : :
1001 : : /* Return received messages to caller */
1002 : 2265 : *buffer = copybuf;
1003 : 2265 : return rawlen;
1004 : : }
1005 : :
1006 : : /*
1007 : : * Process the keepalive message.
1008 : : */
1009 : : static bool
1010 : 0 : ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
1011 : : XLogRecPtr blockpos, TimestampTz *last_status)
1012 : : {
1013 : : int pos;
1014 : : bool replyRequested;
1015 : : TimestampTz now;
1016 : :
1017 : : /*
1018 : : * Parse the keepalive message, enclosed in the CopyData message. We just
1019 : : * check if the server requested a reply, and ignore the rest.
1020 : : */
1021 : 0 : pos = 1; /* skip msgtype PqReplMsg_Keepalive */
1022 : 0 : pos += 8; /* skip walEnd */
1023 : 0 : pos += 8; /* skip sendTime */
1024 : :
1025 [ # # ]: 0 : if (len < pos + 1)
1026 : : {
1027 : 0 : pg_log_error("streaming header too small: %d", len);
1028 : 0 : return false;
1029 : : }
1030 : 0 : replyRequested = copybuf[pos];
1031 : :
1032 : : /* If the server requested an immediate reply, send one. */
1033 [ # # # # ]: 0 : if (replyRequested && still_sending)
1034 : : {
1035 [ # # # # ]: 0 : if (reportFlushPosition && lastFlushPosition < blockpos &&
1036 [ # # ]: 0 : walfile != NULL)
1037 : : {
1038 : : /*
1039 : : * If a valid flush location needs to be reported, flush the
1040 : : * current WAL file so that the latest flush location is sent back
1041 : : * to the server. This is necessary to see whether the last WAL
1042 : : * data has been successfully replicated or not, at the normal
1043 : : * shutdown of the server.
1044 : : */
1045 [ # # ]: 0 : if (stream->walmethod->ops->sync(walfile) != 0)
1046 : 0 : pg_fatal("could not fsync file \"%s\": %s",
1047 : : walfile->pathname, GetLastWalMethodError(stream->walmethod));
1048 : 0 : lastFlushPosition = blockpos;
1049 : : }
1050 : :
1051 : 0 : now = feGetCurrentTimestamp();
1052 [ # # ]: 0 : if (!sendFeedback(conn, blockpos, now, false))
1053 : 0 : return false;
1054 : 0 : *last_status = now;
1055 : : }
1056 : :
1057 : 0 : return true;
1058 : : }
1059 : :
1060 : : /*
1061 : : * Process WALData message.
1062 : : */
1063 : : static bool
1064 : 2265 : ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
1065 : : XLogRecPtr *blockpos)
1066 : : {
1067 : : int xlogoff;
1068 : : int bytes_left;
1069 : : int bytes_written;
1070 : : int hdr_len;
1071 : :
1072 : : /*
1073 : : * Once we've decided we don't want to receive any more, just ignore any
1074 : : * subsequent WALData messages.
1075 : : */
1076 [ + + ]: 2265 : if (!(still_sending))
1077 : 263 : return true;
1078 : :
1079 : : /*
1080 : : * Read the header of the WALData message, enclosed in the CopyData
1081 : : * message. We only need the WAL location field (dataStart), the rest of
1082 : : * the header is ignored.
1083 : : */
1084 : 2002 : hdr_len = 1; /* msgtype PqReplMsg_WALData */
1085 : 2002 : hdr_len += 8; /* dataStart */
1086 : 2002 : hdr_len += 8; /* walEnd */
1087 : 2002 : hdr_len += 8; /* sendTime */
1088 [ - + ]: 2002 : if (len < hdr_len)
1089 : : {
1090 : 0 : pg_log_error("streaming header too small: %d", len);
1091 : 0 : return false;
1092 : : }
1093 : 2002 : *blockpos = fe_recvint64(©buf[1]);
1094 : :
1095 : : /* Extract WAL location for this block */
1096 : 2002 : xlogoff = XLogSegmentOffset(*blockpos, WalSegSz);
1097 : :
1098 : : /*
1099 : : * Verify that the initial location in the stream matches where we think
1100 : : * we are.
1101 : : */
1102 [ + + ]: 2002 : if (walfile == NULL)
1103 : : {
1104 : : /* No file open yet */
1105 [ - + ]: 182 : if (xlogoff != 0)
1106 : : {
1107 : 0 : pg_log_error("received write-ahead log record for offset %u with no file open",
1108 : : xlogoff);
1109 : 0 : return false;
1110 : : }
1111 : : }
1112 : : else
1113 : : {
1114 : : /* More data in existing segment */
1115 [ - + ]: 1820 : if (walfile->currpos != xlogoff)
1116 : : {
1117 : 0 : pg_log_error("got WAL data offset %08x, expected %08x",
1118 : : xlogoff, (int) walfile->currpos);
1119 : 0 : return false;
1120 : : }
1121 : : }
1122 : :
1123 : 2002 : bytes_left = len - hdr_len;
1124 : 2002 : bytes_written = 0;
1125 : :
1126 [ + + ]: 4004 : while (bytes_left)
1127 : : {
1128 : : int bytes_to_write;
1129 : :
1130 : : /*
1131 : : * If crossing a WAL boundary, only write up until we reach wal
1132 : : * segment size.
1133 : : */
1134 [ - + ]: 2002 : if (xlogoff + bytes_left > WalSegSz)
1135 : 0 : bytes_to_write = WalSegSz - xlogoff;
1136 : : else
1137 : 2002 : bytes_to_write = bytes_left;
1138 : :
1139 [ + + ]: 2002 : if (walfile == NULL)
1140 : : {
1141 [ - + ]: 182 : if (!open_walfile(stream, *blockpos))
1142 : : {
1143 : : /* Error logged by open_walfile */
1144 : 0 : return false;
1145 : : }
1146 : : }
1147 : :
1148 : 4004 : if (stream->walmethod->ops->write(walfile,
1149 : 2002 : copybuf + hdr_len + bytes_written,
1150 [ - + ]: 2002 : bytes_to_write) != bytes_to_write)
1151 : : {
1152 : 0 : pg_log_error("could not write %d bytes to WAL file \"%s\": %s",
1153 : : bytes_to_write, walfile->pathname,
1154 : : GetLastWalMethodError(stream->walmethod));
1155 : 0 : return false;
1156 : : }
1157 : :
1158 : : /* Write was successful, advance our position */
1159 : 2002 : bytes_written += bytes_to_write;
1160 : 2002 : bytes_left -= bytes_to_write;
1161 : 2002 : *blockpos += bytes_to_write;
1162 : 2002 : xlogoff += bytes_to_write;
1163 : :
1164 : : /* Did we reach the end of a WAL segment? */
1165 [ + + ]: 2002 : if (XLogSegmentOffset(*blockpos, WalSegSz) == 0)
1166 : : {
1167 [ - + ]: 13 : if (!close_walfile(stream, *blockpos))
1168 : : /* Error message written in close_walfile() */
1169 : 0 : return false;
1170 : :
1171 : 13 : xlogoff = 0;
1172 : :
1173 [ + - - + ]: 13 : if (still_sending && stream->stream_stop(*blockpos, stream->timeline, true))
1174 : : {
1175 [ # # # # ]: 0 : if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
1176 : : {
1177 : 0 : pg_log_error("could not send copy-end packet: %s",
1178 : : PQerrorMessage(conn));
1179 : 0 : return false;
1180 : : }
1181 : 0 : still_sending = false;
1182 : 0 : return true; /* ignore the rest of this WALData packet */
1183 : : }
1184 : : }
1185 : : }
1186 : : /* No more data left to write, receive next copy packet */
1187 : :
1188 : 2002 : return true;
1189 : : }
1190 : :
1191 : : /*
1192 : : * Handle end of the copy stream.
1193 : : */
1194 : : static PGresult *
1195 : 176 : HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
1196 : : XLogRecPtr blockpos, XLogRecPtr *stoppos)
1197 : : {
1198 : 176 : PGresult *res = PQgetResult(conn);
1199 : :
1200 : : /*
1201 : : * The server closed its end of the copy stream. If we haven't closed
1202 : : * ours already, we need to do so now, unless the server threw an error,
1203 : : * in which case we don't.
1204 : : */
1205 [ + + ]: 176 : if (still_sending)
1206 : : {
1207 [ - + ]: 2 : if (!close_walfile(stream, blockpos))
1208 : : {
1209 : : /* Error message written in close_walfile() */
1210 : 0 : PQclear(res);
1211 : 0 : return NULL;
1212 : : }
1213 [ + + ]: 2 : if (PQresultStatus(res) == PGRES_COPY_IN)
1214 : : {
1215 [ + - - + ]: 1 : if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
1216 : : {
1217 : 0 : pg_log_error("could not send copy-end packet: %s",
1218 : : PQerrorMessage(conn));
1219 : 0 : PQclear(res);
1220 : 0 : return NULL;
1221 : : }
1222 : 1 : res = PQgetResult(conn);
1223 : : }
1224 : 2 : still_sending = false;
1225 : : }
1226 : 176 : *stoppos = blockpos;
1227 : 176 : return res;
1228 : : }
1229 : :
1230 : : /*
1231 : : * Check if we should continue streaming, or abort at this point.
1232 : : */
1233 : : static bool
1234 : 2999 : CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos)
1235 : : {
1236 [ + + + + ]: 2999 : if (still_sending && stream->stream_stop(blockpos, stream->timeline, false))
1237 : : {
1238 [ - + ]: 174 : if (!close_walfile(stream, blockpos))
1239 : : {
1240 : : /* Potential error message is written by close_walfile */
1241 : 0 : return false;
1242 : : }
1243 [ + - - + ]: 174 : if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
1244 : : {
1245 : 0 : pg_log_error("could not send copy-end packet: %s",
1246 : : PQerrorMessage(conn));
1247 : 0 : return false;
1248 : : }
1249 : 174 : still_sending = false;
1250 : : }
1251 : :
1252 : 2999 : return true;
1253 : : }
1254 : :
1255 : : /*
1256 : : * Calculate how long send/receive loops should sleep
1257 : : */
1258 : : static long
1259 : 734 : CalculateCopyStreamSleeptime(TimestampTz now, int standby_message_timeout,
1260 : : TimestampTz last_status)
1261 : : {
1262 : 734 : TimestampTz status_targettime = 0;
1263 : : long sleeptime;
1264 : :
1265 [ + - + + ]: 734 : if (standby_message_timeout && still_sending)
1266 : 664 : status_targettime = last_status +
1267 : 664 : (standby_message_timeout - 1) * ((int64) 1000);
1268 : :
1269 [ + + ]: 734 : if (status_targettime > 0)
1270 : : {
1271 : : long secs;
1272 : : int usecs;
1273 : :
1274 : 664 : feTimestampDifference(now,
1275 : : status_targettime,
1276 : : &secs,
1277 : : &usecs);
1278 : : /* Always sleep at least 1 sec */
1279 [ - + ]: 664 : if (secs <= 0)
1280 : : {
1281 : 0 : secs = 1;
1282 : 0 : usecs = 0;
1283 : : }
1284 : :
1285 : 664 : sleeptime = secs * 1000 + usecs / 1000;
1286 : : }
1287 : : else
1288 : 70 : sleeptime = -1;
1289 : :
1290 : 734 : return sleeptime;
1291 : : }
|