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_warning("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 : : }
558 : :
559 : : /* Write the history file to disk */
560 [ - + ]: 7 : if (!writeTimeLineHistoryFile(stream,
561 : 7 : PQgetvalue(res, 0, 0),
562 : 7 : PQgetvalue(res, 0, 1)))
563 : : {
564 : : /* Error message written in writeTimeLineHistoryFile() */
565 : 0 : PQclear(res);
566 : 0 : return false;
567 : : }
568 : :
569 : 7 : PQclear(res);
570 : : }
571 : :
572 : : /*
573 : : * Before we start streaming from the requested location, check if the
574 : : * callback tells us to stop here.
575 : : */
576 [ - + ]: 177 : if (stream->stream_stop(stream->startpos, stream->timeline, false))
577 : 0 : return true;
578 : :
579 : : /* Initiate the replication stream at specified location */
580 : 177 : query = createPQExpBuffer();
581 : 177 : appendPQExpBufferStr(query, "START_REPLICATION");
582 [ + + ]: 177 : if (stream->replication_slot != NULL)
583 : : {
584 : 172 : appendPQExpBufferStr(query, " SLOT ");
585 : 172 : AppendQuotedIdentifier(query, stream->replication_slot);
586 : : }
587 : 177 : appendPQExpBuffer(query, " %X/%08X TIMELINE %u",
588 : 177 : LSN_FORMAT_ARGS(stream->startpos),
589 : : stream->timeline);
590 : 177 : res = PQexec(conn, query->data);
591 : 177 : destroyPQExpBuffer(query);
592 [ + + ]: 177 : if (PQresultStatus(res) != PGRES_COPY_BOTH)
593 : : {
594 : 1 : pg_log_error("could not send replication command \"%s\": %s",
595 : : "START_REPLICATION", PQresultErrorMessage(res));
596 : 1 : PQclear(res);
597 : 1 : return false;
598 : : }
599 : 176 : PQclear(res);
600 : :
601 : : /* Stream the WAL */
602 : 176 : res = HandleCopyStream(conn, stream, &stoppos);
603 [ - + ]: 176 : if (res == NULL)
604 : 0 : goto error;
605 : :
606 : : /*
607 : : * Streaming finished.
608 : : *
609 : : * There are two possible reasons for that: a controlled shutdown, or
610 : : * we reached the end of the current timeline. In case of
611 : : * end-of-timeline, the server sends a result set after Copy has
612 : : * finished, containing information about the next timeline. Read
613 : : * that, and restart streaming from the next timeline. In case of
614 : : * controlled shutdown, stop here.
615 : : */
616 [ + + ]: 176 : if (PQresultStatus(res) == PGRES_TUPLES_OK)
617 : 1 : {
618 : : /*
619 : : * End-of-timeline. Read the next timeline's ID and starting
620 : : * position. Usually, the starting position will match the end of
621 : : * the previous timeline, but there are corner cases like if the
622 : : * server had sent us half of a WAL record, when it was promoted.
623 : : * The new timeline will begin at the end of the last complete
624 : : * record in that case, overlapping the partial WAL record on the
625 : : * old timeline.
626 : : */
627 : : uint32 newtimeline;
628 : : bool parsed;
629 : :
630 : 1 : parsed = ReadEndOfStreamingResult(res, &stream->startpos, &newtimeline);
631 : 1 : PQclear(res);
632 [ - + ]: 1 : if (!parsed)
633 : 0 : goto error;
634 : :
635 : : /* Sanity check the values the server gave us */
636 [ - + ]: 1 : if (newtimeline <= stream->timeline)
637 : : {
638 : 0 : pg_log_error("server reported unexpected next timeline %u, following timeline %u",
639 : : newtimeline, stream->timeline);
640 : 0 : goto error;
641 : : }
642 [ - + ]: 1 : if (stream->startpos > stoppos)
643 : : {
644 : 0 : pg_log_error("server stopped streaming timeline %u at %X/%08X, but reported next timeline %u to begin at %X/%08X",
645 : : stream->timeline, LSN_FORMAT_ARGS(stoppos),
646 : : newtimeline, LSN_FORMAT_ARGS(stream->startpos));
647 : 0 : goto error;
648 : : }
649 : :
650 : : /* Read the final result, which should be CommandComplete. */
651 : 1 : res = PQgetResult(conn);
652 [ - + ]: 1 : if (PQresultStatus(res) != PGRES_COMMAND_OK)
653 : : {
654 : 0 : pg_log_error("unexpected termination of replication stream: %s",
655 : : PQresultErrorMessage(res));
656 : 0 : PQclear(res);
657 : 0 : goto error;
658 : : }
659 : 1 : PQclear(res);
660 : :
661 : : /*
662 : : * Loop back to start streaming from the new timeline. Always
663 : : * start streaming at the beginning of a segment.
664 : : */
665 : 1 : stream->timeline = newtimeline;
666 : 1 : stream->startpos = stream->startpos -
667 : 1 : XLogSegmentOffset(stream->startpos, WalSegSz);
668 : 1 : continue;
669 : : }
670 [ + + ]: 175 : else if (PQresultStatus(res) == PGRES_COMMAND_OK)
671 : : {
672 : 174 : PQclear(res);
673 : :
674 : : /*
675 : : * End of replication (ie. controlled shut down of the server).
676 : : *
677 : : * Check if the callback thinks it's OK to stop here. If not,
678 : : * complain.
679 : : */
680 [ + - ]: 174 : if (stream->stream_stop(stoppos, stream->timeline, false))
681 : 174 : return true;
682 : : else
683 : : {
684 : 0 : pg_log_error("replication stream was terminated before stop point");
685 : 0 : goto error;
686 : : }
687 : : }
688 : : else
689 : : {
690 : : /* Server returned an error. */
691 : 1 : pg_log_error("unexpected termination of replication stream: %s",
692 : : PQresultErrorMessage(res));
693 : 1 : PQclear(res);
694 : 1 : goto error;
695 : : }
696 : : }
697 : :
698 : 1 : error:
699 [ - + ]: 1 : if (walfile != NULL)
700 : : {
701 : : char walfile_name[MAXPGPATH];
702 : :
703 : : /* The close method can free walfile even on failure. */
704 : 0 : strlcpy(walfile_name, walfile->pathname, sizeof(walfile_name));
705 [ # # ]: 0 : if (stream->walmethod->ops->close(walfile, CLOSE_NO_RENAME) != 0)
706 : 0 : pg_log_error("could not close file \"%s\": %s",
707 : : walfile_name, GetLastWalMethodError(stream->walmethod));
708 : : }
709 : 1 : walfile = NULL;
710 : 1 : return false;
711 : : }
712 : :
713 : : /*
714 : : * Helper function to parse the result set returned by server after streaming
715 : : * has finished. On failure, prints an error to stderr and returns false.
716 : : */
717 : : static bool
718 : 1 : ReadEndOfStreamingResult(PGresult *res, XLogRecPtr *startpos, uint32 *timeline)
719 : : {
720 : : /*----------
721 : : * The result set consists of one row and two columns, e.g:
722 : : *
723 : : * next_tli | next_tli_startpos
724 : : * ----------+-------------------
725 : : * 4 | 0/9949AE0
726 : : *
727 : : * next_tli is the timeline ID of the next timeline after the one that
728 : : * just finished streaming. next_tli_startpos is the WAL location where
729 : : * the server switched to it.
730 : : *----------
731 : : */
732 [ + - - + ]: 1 : if (PQnfields(res) < 2 || PQntuples(res) != 1)
733 : : {
734 : 0 : pg_log_error("unexpected result set after end-of-timeline: got %d rows and %d fields, expected %d rows and %d fields",
735 : : PQntuples(res), PQnfields(res), 1, 2);
736 : 0 : return false;
737 : : }
738 : :
739 : 1 : *timeline = atoi(PQgetvalue(res, 0, 0));
740 [ - + ]: 1 : if (!pg_parse_lsn(PQgetvalue(res, 0, 1), startpos))
741 : : {
742 : 0 : pg_log_error("could not parse next timeline's starting point \"%s\"",
743 : : PQgetvalue(res, 0, 1));
744 : 0 : return false;
745 : : }
746 : :
747 : 1 : return true;
748 : : }
749 : :
750 : : /*
751 : : * The main loop of ReceiveXlogStream. Handles the COPY stream after
752 : : * initiating streaming with the START_REPLICATION command.
753 : : *
754 : : * If the COPY ends (not necessarily successfully) due a message from the
755 : : * server, returns a PGresult and sets *stoppos to the last byte written.
756 : : * On any other sort of error, returns NULL.
757 : : */
758 : : static PGresult *
759 : 176 : HandleCopyStream(PGconn *conn, StreamCtl *stream,
760 : : XLogRecPtr *stoppos)
761 : : {
762 : 176 : char *copybuf = NULL;
763 : 176 : TimestampTz last_status = -1;
764 : 176 : XLogRecPtr blockpos = stream->startpos;
765 : :
766 : 176 : still_sending = true;
767 : :
768 : : while (1)
769 : 633 : {
770 : : int r;
771 : : TimestampTz now;
772 : : long sleeptime;
773 : :
774 : : /*
775 : : * Check if we should continue streaming, or abort at this point.
776 : : */
777 [ - + ]: 809 : if (!CheckCopyStreamStop(conn, stream, blockpos))
778 : 0 : goto error;
779 : :
780 : 809 : now = feGetCurrentTimestamp();
781 : :
782 : : /*
783 : : * If synchronous option is true, issue sync command as soon as there
784 : : * are WAL data which has not been flushed yet.
785 : : */
786 [ + + - + : 809 : if (stream->synchronous && lastFlushPosition < blockpos && walfile != NULL)
- - ]
787 : : {
788 [ # # ]: 0 : if (stream->walmethod->ops->sync(walfile) != 0)
789 : 0 : pg_fatal("could not fsync file \"%s\": %s",
790 : : walfile->pathname, GetLastWalMethodError(stream->walmethod));
791 : 0 : lastFlushPosition = blockpos;
792 : :
793 : : /*
794 : : * Send feedback so that the server sees the latest WAL locations
795 : : * immediately.
796 : : */
797 [ # # ]: 0 : if (!sendFeedback(conn, blockpos, now, false))
798 : 0 : goto error;
799 : 0 : last_status = now;
800 : : }
801 : :
802 : : /*
803 : : * Potentially send a status message to the primary
804 : : */
805 [ + + + - : 1541 : if (still_sending && stream->standby_message_timeout > 0 &&
+ + ]
806 : 732 : feTimestampDifferenceExceeds(last_status, now,
807 : : stream->standby_message_timeout))
808 : : {
809 : : /* Time to send feedback! */
810 [ - + ]: 176 : if (!sendFeedback(conn, blockpos, now, false))
811 : 0 : goto error;
812 : 176 : last_status = now;
813 : : }
814 : :
815 : : /*
816 : : * Calculate how long send/receive loops should sleep
817 : : */
818 : 809 : sleeptime = CalculateCopyStreamSleeptime(now, stream->standby_message_timeout,
819 : : last_status);
820 : :
821 : : /* Done with any prior message */
822 : 809 : PQfreemem(copybuf);
823 : 809 : copybuf = NULL;
824 : :
825 : 809 : r = CopyStreamReceive(conn, sleeptime, stream->stop_socket, ©buf);
826 [ + + ]: 2816 : while (r != 0)
827 : : {
828 [ - + ]: 2183 : if (r == -1)
829 : 0 : goto error;
830 [ + + ]: 2183 : if (r == -2)
831 : : {
832 : 176 : PGresult *res = HandleEndOfCopyStream(conn, stream, copybuf, blockpos, stoppos);
833 : :
834 [ - + ]: 176 : if (res == NULL)
835 : 0 : goto error;
836 : 176 : PQfreemem(copybuf);
837 : 176 : return res;
838 : : }
839 : :
840 : : /* Check the message type. */
841 [ - + ]: 2007 : if (copybuf[0] == PqReplMsg_Keepalive)
842 : : {
843 [ # # ]: 0 : if (!ProcessKeepaliveMsg(conn, stream, copybuf, r, blockpos,
844 : : &last_status))
845 : 0 : goto error;
846 : : }
847 [ + - ]: 2007 : else if (copybuf[0] == PqReplMsg_WALData)
848 : : {
849 [ - + ]: 2007 : if (!ProcessWALDataMsg(conn, stream, copybuf, r, &blockpos))
850 : 0 : goto error;
851 : :
852 : : /*
853 : : * Check if we should continue streaming, or abort at this
854 : : * point.
855 : : */
856 [ - + ]: 2007 : if (!CheckCopyStreamStop(conn, stream, blockpos))
857 : 0 : goto error;
858 : : }
859 : : else
860 : : {
861 : 0 : pg_log_error("unrecognized streaming header: \"%c\"",
862 : : copybuf[0]);
863 : 0 : goto error;
864 : : }
865 : :
866 : : /* Done with that message */
867 : 2007 : PQfreemem(copybuf);
868 : 2007 : copybuf = NULL;
869 : :
870 : : /*
871 : : * Process the received data, and any subsequent data we can read
872 : : * without blocking.
873 : : */
874 : 2007 : r = CopyStreamReceive(conn, 0, stream->stop_socket, ©buf);
875 : : }
876 : : }
877 : :
878 : 0 : error:
879 : 0 : PQfreemem(copybuf);
880 : 0 : return NULL;
881 : : }
882 : :
883 : : /*
884 : : * Wait until we can read a CopyData message,
885 : : * or timeout, or occurrence of a signal or input on the stop_socket.
886 : : * (timeout_ms < 0 means wait indefinitely; 0 means don't wait.)
887 : : *
888 : : * Returns 1 if data has become available for reading, 0 if timed out
889 : : * or interrupted by signal or stop_socket input, and -1 on an error.
890 : : */
891 : : static int
892 : 2522 : CopyStreamPoll(PGconn *conn, long timeout_ms, pgsocket stop_socket)
893 : : {
894 : : int ret;
895 : : fd_set input_mask;
896 : : int connsocket;
897 : : int maxfd;
898 : : struct timeval timeout;
899 : : struct timeval *timeoutptr;
900 : :
901 : 2522 : connsocket = PQsocket(conn);
902 [ - + ]: 2522 : if (connsocket < 0)
903 : : {
904 : 0 : pg_log_error("invalid socket: %s", PQerrorMessage(conn));
905 : 0 : return -1;
906 : : }
907 : :
908 [ + + ]: 42874 : FD_ZERO(&input_mask);
909 : 2522 : FD_SET(connsocket, &input_mask);
910 : 2522 : maxfd = connsocket;
911 [ + + ]: 2522 : if (stop_socket != PGINVALID_SOCKET)
912 : : {
913 : 2456 : FD_SET(stop_socket, &input_mask);
914 : 2456 : maxfd = Max(maxfd, stop_socket);
915 : : }
916 : :
917 [ + + ]: 2522 : if (timeout_ms < 0)
918 : 77 : timeoutptr = NULL;
919 : : else
920 : : {
921 : 2445 : timeout.tv_sec = timeout_ms / 1000L;
922 : 2445 : timeout.tv_usec = (timeout_ms % 1000L) * 1000L;
923 : 2445 : timeoutptr = &timeout;
924 : : }
925 : :
926 : 2522 : ret = select(maxfd + 1, &input_mask, NULL, NULL, timeoutptr);
927 : :
928 [ - + ]: 2522 : if (ret < 0)
929 : : {
930 [ # # ]: 0 : if (errno == EINTR)
931 : 0 : return 0; /* Got a signal, so not an error */
932 : 0 : pg_log_error("%s() failed: %m", "select");
933 : 0 : return -1;
934 : : }
935 [ + + + + ]: 2522 : if (ret > 0 && FD_ISSET(connsocket, &input_mask))
936 : 2181 : return 1; /* Got input on connection socket */
937 : :
938 : 341 : return 0; /* Got timeout or input on stop_socket */
939 : : }
940 : :
941 : : /*
942 : : * Receive CopyData message available from XLOG stream, blocking for
943 : : * maximum of 'timeout' ms.
944 : : *
945 : : * If data was received, returns the length of the data. *buffer is set to
946 : : * point to a buffer holding the received message. The caller must eventually
947 : : * free the buffer with PQfreemem().
948 : : *
949 : : * Returns 0 if no data was available within timeout, or if wait was
950 : : * interrupted by signal or stop_socket input.
951 : : * -1 on error. -2 if the server ended the COPY.
952 : : */
953 : : static int
954 : 2816 : CopyStreamReceive(PGconn *conn, long timeout, pgsocket stop_socket,
955 : : char **buffer)
956 : : {
957 : 2816 : char *copybuf = NULL;
958 : : int rawlen;
959 : :
960 : : /* Caller should have cleared any prior buffer */
961 : : Assert(*buffer == NULL);
962 : :
963 : : /* Try to receive a CopyData message */
964 : 2816 : rawlen = PQgetCopyData(conn, ©buf, 1);
965 [ + + ]: 2816 : if (rawlen == 0)
966 : : {
967 : : int ret;
968 : :
969 : : /*
970 : : * No data available. Wait for some to appear, but not longer than
971 : : * the specified timeout, so that we can ping the server. Also stop
972 : : * waiting if input appears on stop_socket.
973 : : */
974 : 2522 : ret = CopyStreamPoll(conn, timeout, stop_socket);
975 [ + + ]: 2522 : if (ret <= 0)
976 : 341 : return ret;
977 : :
978 : : /* Now there is actually data on the socket */
979 [ - + ]: 2181 : if (PQconsumeInput(conn) == 0)
980 : : {
981 : 0 : pg_log_error("could not receive data from WAL stream: %s",
982 : : PQerrorMessage(conn));
983 : 0 : return -1;
984 : : }
985 : :
986 : : /* Now that we've consumed some input, try again */
987 : 2181 : rawlen = PQgetCopyData(conn, ©buf, 1);
988 [ + + ]: 2181 : if (rawlen == 0)
989 : 292 : return 0;
990 : : }
991 [ + + ]: 2183 : if (rawlen == -1) /* end-of-streaming or error */
992 : 176 : return -2;
993 [ - + ]: 2007 : if (rawlen == -2)
994 : : {
995 : 0 : pg_log_error("could not read COPY data: %s", PQerrorMessage(conn));
996 : 0 : return -1;
997 : : }
998 : :
999 : : /* Return received messages to caller */
1000 : 2007 : *buffer = copybuf;
1001 : 2007 : return rawlen;
1002 : : }
1003 : :
1004 : : /*
1005 : : * Process the keepalive message.
1006 : : */
1007 : : static bool
1008 : 0 : ProcessKeepaliveMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
1009 : : XLogRecPtr blockpos, TimestampTz *last_status)
1010 : : {
1011 : : int pos;
1012 : : bool replyRequested;
1013 : : TimestampTz now;
1014 : :
1015 : : /*
1016 : : * Parse the keepalive message, enclosed in the CopyData message. We just
1017 : : * check if the server requested a reply, and ignore the rest.
1018 : : */
1019 : 0 : pos = 1; /* skip msgtype PqReplMsg_Keepalive */
1020 : 0 : pos += 8; /* skip walEnd */
1021 : 0 : pos += 8; /* skip sendTime */
1022 : :
1023 [ # # ]: 0 : if (len < pos + 1)
1024 : : {
1025 : 0 : pg_log_error("streaming header too small: %d", len);
1026 : 0 : return false;
1027 : : }
1028 : 0 : replyRequested = copybuf[pos];
1029 : :
1030 : : /* If the server requested an immediate reply, send one. */
1031 [ # # # # ]: 0 : if (replyRequested && still_sending)
1032 : : {
1033 [ # # # # ]: 0 : if (reportFlushPosition && lastFlushPosition < blockpos &&
1034 [ # # ]: 0 : walfile != NULL)
1035 : : {
1036 : : /*
1037 : : * If a valid flush location needs to be reported, flush the
1038 : : * current WAL file so that the latest flush location is sent back
1039 : : * to the server. This is necessary to see whether the last WAL
1040 : : * data has been successfully replicated or not, at the normal
1041 : : * shutdown of the server.
1042 : : */
1043 [ # # ]: 0 : if (stream->walmethod->ops->sync(walfile) != 0)
1044 : 0 : pg_fatal("could not fsync file \"%s\": %s",
1045 : : walfile->pathname, GetLastWalMethodError(stream->walmethod));
1046 : 0 : lastFlushPosition = blockpos;
1047 : : }
1048 : :
1049 : 0 : now = feGetCurrentTimestamp();
1050 [ # # ]: 0 : if (!sendFeedback(conn, blockpos, now, false))
1051 : 0 : return false;
1052 : 0 : *last_status = now;
1053 : : }
1054 : :
1055 : 0 : return true;
1056 : : }
1057 : :
1058 : : /*
1059 : : * Process WALData message.
1060 : : */
1061 : : static bool
1062 : 2007 : ProcessWALDataMsg(PGconn *conn, StreamCtl *stream, char *copybuf, int len,
1063 : : XLogRecPtr *blockpos)
1064 : : {
1065 : : int xlogoff;
1066 : : int bytes_left;
1067 : : int bytes_written;
1068 : : int hdr_len;
1069 : :
1070 : : /*
1071 : : * Once we've decided we don't want to receive any more, just ignore any
1072 : : * subsequent WALData messages.
1073 : : */
1074 [ + + ]: 2007 : if (!(still_sending))
1075 : 246 : return true;
1076 : :
1077 : : /*
1078 : : * Read the header of the WALData message, enclosed in the CopyData
1079 : : * message. We only need the WAL location field (dataStart), the rest of
1080 : : * the header is ignored.
1081 : : */
1082 : 1761 : hdr_len = 1; /* msgtype PqReplMsg_WALData */
1083 : 1761 : hdr_len += 8; /* dataStart */
1084 : 1761 : hdr_len += 8; /* walEnd */
1085 : 1761 : hdr_len += 8; /* sendTime */
1086 [ - + ]: 1761 : if (len < hdr_len)
1087 : : {
1088 : 0 : pg_log_error("streaming header too small: %d", len);
1089 : 0 : return false;
1090 : : }
1091 : 1761 : *blockpos = fe_recvint64(©buf[1]);
1092 : :
1093 : : /* Extract WAL location for this block */
1094 : 1761 : xlogoff = XLogSegmentOffset(*blockpos, WalSegSz);
1095 : :
1096 : : /*
1097 : : * Verify that the initial location in the stream matches where we think
1098 : : * we are.
1099 : : */
1100 [ + + ]: 1761 : if (walfile == NULL)
1101 : : {
1102 : : /* No file open yet */
1103 [ - + ]: 182 : if (xlogoff != 0)
1104 : : {
1105 : 0 : pg_log_error("received write-ahead log record for offset %u with no file open",
1106 : : xlogoff);
1107 : 0 : return false;
1108 : : }
1109 : : }
1110 : : else
1111 : : {
1112 : : /* More data in existing segment */
1113 [ - + ]: 1579 : if (walfile->currpos != xlogoff)
1114 : : {
1115 : 0 : pg_log_error("got WAL data offset %08x, expected %08x",
1116 : : xlogoff, (int) walfile->currpos);
1117 : 0 : return false;
1118 : : }
1119 : : }
1120 : :
1121 : 1761 : bytes_left = len - hdr_len;
1122 : 1761 : bytes_written = 0;
1123 : :
1124 [ + + ]: 3522 : while (bytes_left)
1125 : : {
1126 : : int bytes_to_write;
1127 : :
1128 : : /*
1129 : : * If crossing a WAL boundary, only write up until we reach wal
1130 : : * segment size.
1131 : : */
1132 [ - + ]: 1761 : if (xlogoff + bytes_left > WalSegSz)
1133 : 0 : bytes_to_write = WalSegSz - xlogoff;
1134 : : else
1135 : 1761 : bytes_to_write = bytes_left;
1136 : :
1137 [ + + ]: 1761 : if (walfile == NULL)
1138 : : {
1139 [ - + ]: 182 : if (!open_walfile(stream, *blockpos))
1140 : : {
1141 : : /* Error logged by open_walfile */
1142 : 0 : return false;
1143 : : }
1144 : : }
1145 : :
1146 : 3522 : if (stream->walmethod->ops->write(walfile,
1147 : 1761 : copybuf + hdr_len + bytes_written,
1148 [ - + ]: 1761 : bytes_to_write) != bytes_to_write)
1149 : : {
1150 : 0 : pg_log_error("could not write %d bytes to WAL file \"%s\": %s",
1151 : : bytes_to_write, walfile->pathname,
1152 : : GetLastWalMethodError(stream->walmethod));
1153 : 0 : return false;
1154 : : }
1155 : :
1156 : : /* Write was successful, advance our position */
1157 : 1761 : bytes_written += bytes_to_write;
1158 : 1761 : bytes_left -= bytes_to_write;
1159 : 1761 : *blockpos += bytes_to_write;
1160 : 1761 : xlogoff += bytes_to_write;
1161 : :
1162 : : /* Did we reach the end of a WAL segment? */
1163 [ + + ]: 1761 : if (XLogSegmentOffset(*blockpos, WalSegSz) == 0)
1164 : : {
1165 [ - + ]: 13 : if (!close_walfile(stream, *blockpos))
1166 : : /* Error message written in close_walfile() */
1167 : 0 : return false;
1168 : :
1169 : 13 : xlogoff = 0;
1170 : :
1171 [ + - - + ]: 13 : if (still_sending && stream->stream_stop(*blockpos, stream->timeline, true))
1172 : : {
1173 [ # # # # ]: 0 : if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
1174 : : {
1175 : 0 : pg_log_error("could not send copy-end packet: %s",
1176 : : PQerrorMessage(conn));
1177 : 0 : return false;
1178 : : }
1179 : 0 : still_sending = false;
1180 : 0 : return true; /* ignore the rest of this WALData packet */
1181 : : }
1182 : : }
1183 : : }
1184 : : /* No more data left to write, receive next copy packet */
1185 : :
1186 : 1761 : return true;
1187 : : }
1188 : :
1189 : : /*
1190 : : * Handle end of the copy stream.
1191 : : */
1192 : : static PGresult *
1193 : 176 : HandleEndOfCopyStream(PGconn *conn, StreamCtl *stream, char *copybuf,
1194 : : XLogRecPtr blockpos, XLogRecPtr *stoppos)
1195 : : {
1196 : 176 : PGresult *res = PQgetResult(conn);
1197 : :
1198 : : /*
1199 : : * The server closed its end of the copy stream. If we haven't closed
1200 : : * ours already, we need to do so now, unless the server threw an error,
1201 : : * in which case we don't.
1202 : : */
1203 [ + + ]: 176 : if (still_sending)
1204 : : {
1205 [ - + ]: 2 : if (!close_walfile(stream, blockpos))
1206 : : {
1207 : : /* Error message written in close_walfile() */
1208 : 0 : PQclear(res);
1209 : 0 : return NULL;
1210 : : }
1211 [ + + ]: 2 : if (PQresultStatus(res) == PGRES_COPY_IN)
1212 : : {
1213 [ + - - + ]: 1 : if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
1214 : : {
1215 : 0 : pg_log_error("could not send copy-end packet: %s",
1216 : : PQerrorMessage(conn));
1217 : 0 : PQclear(res);
1218 : 0 : return NULL;
1219 : : }
1220 : 1 : res = PQgetResult(conn);
1221 : : }
1222 : 2 : still_sending = false;
1223 : : }
1224 : 176 : *stoppos = blockpos;
1225 : 176 : return res;
1226 : : }
1227 : :
1228 : : /*
1229 : : * Check if we should continue streaming, or abort at this point.
1230 : : */
1231 : : static bool
1232 : 2816 : CheckCopyStreamStop(PGconn *conn, StreamCtl *stream, XLogRecPtr blockpos)
1233 : : {
1234 [ + + + + ]: 2816 : if (still_sending && stream->stream_stop(blockpos, stream->timeline, false))
1235 : : {
1236 [ - + ]: 174 : if (!close_walfile(stream, blockpos))
1237 : : {
1238 : : /* Potential error message is written by close_walfile */
1239 : 0 : return false;
1240 : : }
1241 [ + - - + ]: 174 : if (PQputCopyEnd(conn, NULL) <= 0 || PQflush(conn))
1242 : : {
1243 : 0 : pg_log_error("could not send copy-end packet: %s",
1244 : : PQerrorMessage(conn));
1245 : 0 : return false;
1246 : : }
1247 : 174 : still_sending = false;
1248 : : }
1249 : :
1250 : 2816 : return true;
1251 : : }
1252 : :
1253 : : /*
1254 : : * Calculate how long send/receive loops should sleep
1255 : : */
1256 : : static long
1257 : 809 : CalculateCopyStreamSleeptime(TimestampTz now, int standby_message_timeout,
1258 : : TimestampTz last_status)
1259 : : {
1260 : 809 : TimestampTz status_targettime = 0;
1261 : : long sleeptime;
1262 : :
1263 [ + - + + ]: 809 : if (standby_message_timeout && still_sending)
1264 : 732 : status_targettime = last_status +
1265 : 732 : (standby_message_timeout - 1) * ((int64) 1000);
1266 : :
1267 [ + + ]: 809 : if (status_targettime > 0)
1268 : : {
1269 : : long secs;
1270 : : int usecs;
1271 : :
1272 : 732 : feTimestampDifference(now,
1273 : : status_targettime,
1274 : : &secs,
1275 : : &usecs);
1276 : : /* Always sleep at least 1 sec */
1277 [ - + ]: 732 : if (secs <= 0)
1278 : : {
1279 : 0 : secs = 1;
1280 : 0 : usecs = 0;
1281 : : }
1282 : :
1283 : 732 : sleeptime = secs * 1000 + usecs / 1000;
1284 : : }
1285 : : else
1286 : 77 : sleeptime = -1;
1287 : :
1288 : 809 : return sleeptime;
1289 : : }
|