LCOV - code coverage report
Current view: top level - src/bin/pg_basebackup - pg_recvlogical.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 342 473 72.3 %
Date: 2024-11-21 10:14:43 Functions: 9 10 90.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * pg_recvlogical.c - receive data from a logical decoding slot in a streaming
       4             :  *                    fashion and write it to a local file.
       5             :  *
       6             :  * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
       7             :  *
       8             :  * IDENTIFICATION
       9             :  *        src/bin/pg_basebackup/pg_recvlogical.c
      10             :  *-------------------------------------------------------------------------
      11             :  */
      12             : 
      13             : #include "postgres_fe.h"
      14             : 
      15             : #include <dirent.h>
      16             : #include <limits.h>
      17             : #include <sys/select.h>
      18             : #include <sys/stat.h>
      19             : #include <unistd.h>
      20             : 
      21             : #include "common/file_perm.h"
      22             : #include "common/logging.h"
      23             : #include "fe_utils/option_utils.h"
      24             : #include "getopt_long.h"
      25             : #include "libpq-fe.h"
      26             : #include "libpq/pqsignal.h"
      27             : #include "pqexpbuffer.h"
      28             : #include "streamutil.h"
      29             : 
      30             : /* Time to sleep between reconnection attempts */
      31             : #define RECONNECT_SLEEP_TIME 5
      32             : 
      33             : typedef enum
      34             : {
      35             :     STREAM_STOP_NONE,
      36             :     STREAM_STOP_END_OF_WAL,
      37             :     STREAM_STOP_KEEPALIVE,
      38             :     STREAM_STOP_SIGNAL
      39             : } StreamStopReason;
      40             : 
      41             : /* Global Options */
      42             : static char *outfile = NULL;
      43             : static int  verbose = 0;
      44             : static bool two_phase = false;
      45             : static int  noloop = 0;
      46             : static int  standby_message_timeout = 10 * 1000;    /* 10 sec = default */
      47             : static int  fsync_interval = 10 * 1000; /* 10 sec = default */
      48             : static XLogRecPtr startpos = InvalidXLogRecPtr;
      49             : static XLogRecPtr endpos = InvalidXLogRecPtr;
      50             : static bool do_create_slot = false;
      51             : static bool slot_exists_ok = false;
      52             : static bool do_start_slot = false;
      53             : static bool do_drop_slot = false;
      54             : static char *replication_slot = NULL;
      55             : 
      56             : /* filled pairwise with option, value. value may be NULL */
      57             : static char **options;
      58             : static size_t noptions = 0;
      59             : static const char *plugin = "test_decoding";
      60             : 
      61             : /* Global State */
      62             : static int  outfd = -1;
      63             : static volatile sig_atomic_t time_to_abort = false;
      64             : static volatile sig_atomic_t stop_reason = STREAM_STOP_NONE;
      65             : static volatile sig_atomic_t output_reopen = false;
      66             : static bool output_isfile;
      67             : static TimestampTz output_last_fsync = -1;
      68             : static bool output_needs_fsync = false;
      69             : static XLogRecPtr output_written_lsn = InvalidXLogRecPtr;
      70             : static XLogRecPtr output_fsync_lsn = InvalidXLogRecPtr;
      71             : 
      72             : static void usage(void);
      73             : static void StreamLogicalLog(void);
      74             : static bool flushAndSendFeedback(PGconn *conn, TimestampTz *now);
      75             : static void prepareToTerminate(PGconn *conn, XLogRecPtr endpos,
      76             :                                StreamStopReason reason,
      77             :                                XLogRecPtr lsn);
      78             : 
      79             : static void
      80           2 : usage(void)
      81             : {
      82           2 :     printf(_("%s controls PostgreSQL logical decoding streams.\n\n"),
      83             :            progname);
      84           2 :     printf(_("Usage:\n"));
      85           2 :     printf(_("  %s [OPTION]...\n"), progname);
      86           2 :     printf(_("\nAction to be performed:\n"));
      87           2 :     printf(_("      --create-slot      create a new replication slot (for the slot's name see --slot)\n"));
      88           2 :     printf(_("      --drop-slot        drop the replication slot (for the slot's name see --slot)\n"));
      89           2 :     printf(_("      --start            start streaming in a replication slot (for the slot's name see --slot)\n"));
      90           2 :     printf(_("\nOptions:\n"));
      91           2 :     printf(_("  -E, --endpos=LSN       exit after receiving the specified LSN\n"));
      92           2 :     printf(_("  -f, --file=FILE        receive log into this file, - for stdout\n"));
      93           2 :     printf(_("  -F  --fsync-interval=SECS\n"
      94             :              "                         time between fsyncs to the output file (default: %d)\n"), (fsync_interval / 1000));
      95           2 :     printf(_("      --if-not-exists    do not error if slot already exists when creating a slot\n"));
      96           2 :     printf(_("  -I, --startpos=LSN     where in an existing slot should the streaming start\n"));
      97           2 :     printf(_("  -n, --no-loop          do not loop on connection lost\n"));
      98           2 :     printf(_("  -o, --option=NAME[=VALUE]\n"
      99             :              "                         pass option NAME with optional value VALUE to the\n"
     100             :              "                         output plugin\n"));
     101           2 :     printf(_("  -P, --plugin=PLUGIN    use output plugin PLUGIN (default: %s)\n"), plugin);
     102           2 :     printf(_("  -s, --status-interval=SECS\n"
     103             :              "                         time between status packets sent to server (default: %d)\n"), (standby_message_timeout / 1000));
     104           2 :     printf(_("  -S, --slot=SLOTNAME    name of the logical replication slot\n"));
     105           2 :     printf(_("  -t, --two-phase        enable decoding of prepared transactions when creating a slot\n"));
     106           2 :     printf(_("  -v, --verbose          output verbose messages\n"));
     107           2 :     printf(_("  -V, --version          output version information, then exit\n"));
     108           2 :     printf(_("  -?, --help             show this help, then exit\n"));
     109           2 :     printf(_("\nConnection options:\n"));
     110           2 :     printf(_("  -d, --dbname=DBNAME    database to connect to\n"));
     111           2 :     printf(_("  -h, --host=HOSTNAME    database server host or socket directory\n"));
     112           2 :     printf(_("  -p, --port=PORT        database server port number\n"));
     113           2 :     printf(_("  -U, --username=NAME    connect as specified database user\n"));
     114           2 :     printf(_("  -w, --no-password      never prompt for password\n"));
     115           2 :     printf(_("  -W, --password         force password prompt (should happen automatically)\n"));
     116           2 :     printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
     117           2 :     printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
     118           2 : }
     119             : 
     120             : /*
     121             :  * Send a Standby Status Update message to server.
     122             :  */
     123             : static bool
     124          50 : sendFeedback(PGconn *conn, TimestampTz now, bool force, bool replyRequested)
     125             : {
     126             :     static XLogRecPtr last_written_lsn = InvalidXLogRecPtr;
     127             :     static XLogRecPtr last_fsync_lsn = InvalidXLogRecPtr;
     128             : 
     129             :     char        replybuf[1 + 8 + 8 + 8 + 8 + 1];
     130          50 :     int         len = 0;
     131             : 
     132             :     /*
     133             :      * we normally don't want to send superfluous feedback, but if it's
     134             :      * because of a timeout we need to, otherwise wal_sender_timeout will kill
     135             :      * us.
     136             :      */
     137          50 :     if (!force &&
     138           0 :         last_written_lsn == output_written_lsn &&
     139           0 :         last_fsync_lsn == output_fsync_lsn)
     140           0 :         return true;
     141             : 
     142          50 :     if (verbose)
     143           0 :         pg_log_info("confirming write up to %X/%X, flush to %X/%X (slot %s)",
     144             :                     LSN_FORMAT_ARGS(output_written_lsn),
     145             :                     LSN_FORMAT_ARGS(output_fsync_lsn),
     146             :                     replication_slot);
     147             : 
     148          50 :     replybuf[len] = 'r';
     149          50 :     len += 1;
     150          50 :     fe_sendint64(output_written_lsn, &replybuf[len]);   /* write */
     151          50 :     len += 8;
     152          50 :     fe_sendint64(output_fsync_lsn, &replybuf[len]); /* flush */
     153          50 :     len += 8;
     154          50 :     fe_sendint64(InvalidXLogRecPtr, &replybuf[len]);    /* apply */
     155          50 :     len += 8;
     156          50 :     fe_sendint64(now, &replybuf[len]);  /* sendTime */
     157          50 :     len += 8;
     158          50 :     replybuf[len] = replyRequested ? 1 : 0; /* replyRequested */
     159          50 :     len += 1;
     160             : 
     161          50 :     startpos = output_written_lsn;
     162          50 :     last_written_lsn = output_written_lsn;
     163          50 :     last_fsync_lsn = output_fsync_lsn;
     164             : 
     165          50 :     if (PQputCopyData(conn, replybuf, len) <= 0 || PQflush(conn))
     166             :     {
     167           0 :         pg_log_error("could not send feedback packet: %s",
     168             :                      PQerrorMessage(conn));
     169           0 :         return false;
     170             :     }
     171             : 
     172          50 :     return true;
     173             : }
     174             : 
     175             : static void
     176          94 : disconnect_atexit(void)
     177             : {
     178          94 :     if (conn != NULL)
     179          48 :         PQfinish(conn);
     180          94 : }
     181             : 
     182             : static bool
     183          50 : OutputFsync(TimestampTz now)
     184             : {
     185          50 :     output_last_fsync = now;
     186             : 
     187          50 :     output_fsync_lsn = output_written_lsn;
     188             : 
     189          50 :     if (fsync_interval <= 0)
     190           0 :         return true;
     191             : 
     192          50 :     if (!output_needs_fsync)
     193          38 :         return true;
     194             : 
     195          12 :     output_needs_fsync = false;
     196             : 
     197             :     /* can only fsync if it's a regular file */
     198          12 :     if (!output_isfile)
     199           8 :         return true;
     200             : 
     201           4 :     if (fsync(outfd) != 0)
     202           0 :         pg_fatal("could not fsync file \"%s\": %m", outfile);
     203             : 
     204           4 :     return true;
     205             : }
     206             : 
     207             : /*
     208             :  * Start the log streaming
     209             :  */
     210             : static void
     211          46 : StreamLogicalLog(void)
     212             : {
     213             :     PGresult   *res;
     214          46 :     char       *copybuf = NULL;
     215          46 :     TimestampTz last_status = -1;
     216             :     int         i;
     217             :     PQExpBuffer query;
     218             :     XLogRecPtr  cur_record_lsn;
     219             : 
     220          46 :     output_written_lsn = InvalidXLogRecPtr;
     221          46 :     output_fsync_lsn = InvalidXLogRecPtr;
     222          46 :     cur_record_lsn = InvalidXLogRecPtr;
     223             : 
     224             :     /*
     225             :      * Connect in replication mode to the server
     226             :      */
     227          46 :     if (!conn)
     228           0 :         conn = GetConnection();
     229          46 :     if (!conn)
     230             :         /* Error message already written in GetConnection() */
     231           0 :         return;
     232             : 
     233             :     /*
     234             :      * Start the replication
     235             :      */
     236          46 :     if (verbose)
     237           0 :         pg_log_info("starting log streaming at %X/%X (slot %s)",
     238             :                     LSN_FORMAT_ARGS(startpos),
     239             :                     replication_slot);
     240             : 
     241             :     /* Initiate the replication stream at specified location */
     242          46 :     query = createPQExpBuffer();
     243          46 :     appendPQExpBuffer(query, "START_REPLICATION SLOT \"%s\" LOGICAL %X/%X",
     244          46 :                       replication_slot, LSN_FORMAT_ARGS(startpos));
     245             : 
     246             :     /* print options if there are any */
     247          46 :     if (noptions)
     248          40 :         appendPQExpBufferStr(query, " (");
     249             : 
     250         126 :     for (i = 0; i < noptions; i++)
     251             :     {
     252             :         /* separator */
     253          80 :         if (i > 0)
     254          40 :             appendPQExpBufferStr(query, ", ");
     255             : 
     256             :         /* write option name */
     257          80 :         appendPQExpBuffer(query, "\"%s\"", options[(i * 2)]);
     258             : 
     259             :         /* write option value if specified */
     260          80 :         if (options[(i * 2) + 1] != NULL)
     261          80 :             appendPQExpBuffer(query, " '%s'", options[(i * 2) + 1]);
     262             :     }
     263             : 
     264          46 :     if (noptions)
     265          40 :         appendPQExpBufferChar(query, ')');
     266             : 
     267          46 :     res = PQexec(conn, query->data);
     268          46 :     if (PQresultStatus(res) != PGRES_COPY_BOTH)
     269             :     {
     270          12 :         pg_log_error("could not send replication command \"%s\": %s",
     271             :                      query->data, PQresultErrorMessage(res));
     272          12 :         PQclear(res);
     273          12 :         goto error;
     274             :     }
     275          34 :     PQclear(res);
     276          34 :     resetPQExpBuffer(query);
     277             : 
     278          34 :     if (verbose)
     279           0 :         pg_log_info("streaming initiated");
     280             : 
     281        1546 :     while (!time_to_abort)
     282             :     {
     283             :         int         r;
     284             :         int         bytes_left;
     285             :         int         bytes_written;
     286             :         TimestampTz now;
     287             :         int         hdr_len;
     288             : 
     289        1544 :         cur_record_lsn = InvalidXLogRecPtr;
     290             : 
     291        1544 :         if (copybuf != NULL)
     292             :         {
     293         804 :             PQfreemem(copybuf);
     294         804 :             copybuf = NULL;
     295             :         }
     296             : 
     297             :         /*
     298             :          * Potentially send a status message to the primary.
     299             :          */
     300        1544 :         now = feGetCurrentTimestamp();
     301             : 
     302        3054 :         if (outfd != -1 &&
     303        1510 :             feTimestampDifferenceExceeds(output_last_fsync, now,
     304             :                                          fsync_interval))
     305             :         {
     306          34 :             if (!OutputFsync(now))
     307           4 :                 goto error;
     308             :         }
     309             : 
     310        3088 :         if (standby_message_timeout > 0 &&
     311        1544 :             feTimestampDifferenceExceeds(last_status, now,
     312             :                                          standby_message_timeout))
     313             :         {
     314             :             /* Time to send feedback! */
     315          34 :             if (!sendFeedback(conn, now, true, false))
     316           0 :                 goto error;
     317             : 
     318          34 :             last_status = now;
     319             :         }
     320             : 
     321             :         /* got SIGHUP, close output file */
     322        1544 :         if (outfd != -1 && output_reopen && strcmp(outfile, "-") != 0)
     323             :         {
     324           0 :             now = feGetCurrentTimestamp();
     325           0 :             if (!OutputFsync(now))
     326           0 :                 goto error;
     327           0 :             close(outfd);
     328           0 :             outfd = -1;
     329             :         }
     330        1544 :         output_reopen = false;
     331             : 
     332             :         /* open the output file, if not open yet */
     333        1544 :         if (outfd == -1)
     334             :         {
     335             :             struct stat statbuf;
     336             : 
     337          34 :             if (strcmp(outfile, "-") == 0)
     338          34 :                 outfd = fileno(stdout);
     339             :             else
     340           0 :                 outfd = open(outfile, O_CREAT | O_APPEND | O_WRONLY | PG_BINARY,
     341             :                              S_IRUSR | S_IWUSR);
     342          34 :             if (outfd == -1)
     343             :             {
     344           0 :                 pg_log_error("could not open log file \"%s\": %m", outfile);
     345           0 :                 goto error;
     346             :             }
     347             : 
     348          34 :             if (fstat(outfd, &statbuf) != 0)
     349             :             {
     350           0 :                 pg_log_error("could not stat file \"%s\": %m", outfile);
     351           0 :                 goto error;
     352             :             }
     353             : 
     354          34 :             output_isfile = S_ISREG(statbuf.st_mode) && !isatty(outfd);
     355             :         }
     356             : 
     357        1544 :         r = PQgetCopyData(conn, &copybuf, 1);
     358        1544 :         if (r == 0)
     359             :         {
     360             :             /*
     361             :              * In async mode, and no data available. We block on reading but
     362             :              * not more than the specified timeout, so that we can send a
     363             :              * response back to the client.
     364             :              */
     365             :             fd_set      input_mask;
     366         712 :             TimestampTz message_target = 0;
     367         712 :             TimestampTz fsync_target = 0;
     368             :             struct timeval timeout;
     369         712 :             struct timeval *timeoutptr = NULL;
     370             : 
     371         712 :             if (PQsocket(conn) < 0)
     372             :             {
     373           0 :                 pg_log_error("invalid socket: %s", PQerrorMessage(conn));
     374           4 :                 goto error;
     375             :             }
     376             : 
     377         712 :             FD_ZERO(&input_mask);
     378         712 :             FD_SET(PQsocket(conn), &input_mask);
     379             : 
     380             :             /* Compute when we need to wakeup to send a keepalive message. */
     381         712 :             if (standby_message_timeout)
     382         712 :                 message_target = last_status + (standby_message_timeout - 1) *
     383             :                     ((int64) 1000);
     384             : 
     385             :             /* Compute when we need to wakeup to fsync the output file. */
     386         712 :             if (fsync_interval > 0 && output_needs_fsync)
     387         294 :                 fsync_target = output_last_fsync + (fsync_interval - 1) *
     388             :                     ((int64) 1000);
     389             : 
     390             :             /* Now compute when to wakeup. */
     391         712 :             if (message_target > 0 || fsync_target > 0)
     392             :             {
     393             :                 TimestampTz targettime;
     394             :                 long        secs;
     395             :                 int         usecs;
     396             : 
     397         712 :                 targettime = message_target;
     398             : 
     399         712 :                 if (fsync_target > 0 && fsync_target < targettime)
     400           0 :                     targettime = fsync_target;
     401             : 
     402         712 :                 feTimestampDifference(now,
     403             :                                       targettime,
     404             :                                       &secs,
     405             :                                       &usecs);
     406         712 :                 if (secs <= 0)
     407           0 :                     timeout.tv_sec = 1; /* Always sleep at least 1 sec */
     408             :                 else
     409         712 :                     timeout.tv_sec = secs;
     410         712 :                 timeout.tv_usec = usecs;
     411         712 :                 timeoutptr = &timeout;
     412             :             }
     413             : 
     414         712 :             r = select(PQsocket(conn) + 1, &input_mask, NULL, NULL, timeoutptr);
     415         712 :             if (r == 0 || (r < 0 && errno == EINTR))
     416             :             {
     417             :                 /*
     418             :                  * Got a timeout or signal. Continue the loop and either
     419             :                  * deliver a status packet to the server or just go back into
     420             :                  * blocking.
     421             :                  */
     422         708 :                 continue;
     423             :             }
     424         710 :             else if (r < 0)
     425             :             {
     426           0 :                 pg_log_error("%s() failed: %m", "select");
     427           0 :                 goto error;
     428             :             }
     429             : 
     430             :             /* Else there is actually data on the socket */
     431         710 :             if (PQconsumeInput(conn) == 0)
     432             :             {
     433           4 :                 pg_log_error("could not receive data from WAL stream: %s",
     434             :                              PQerrorMessage(conn));
     435           4 :                 goto error;
     436             :             }
     437         706 :             continue;
     438             :         }
     439             : 
     440             :         /* End of copy stream */
     441         832 :         if (r == -1)
     442          28 :             break;
     443             : 
     444             :         /* Failure while reading the copy stream */
     445         818 :         if (r == -2)
     446             :         {
     447           0 :             pg_log_error("could not read COPY data: %s",
     448             :                          PQerrorMessage(conn));
     449           0 :             goto error;
     450             :         }
     451             : 
     452             :         /* Check the message type. */
     453         818 :         if (copybuf[0] == 'k')
     454             :         {
     455             :             int         pos;
     456             :             bool        replyRequested;
     457             :             XLogRecPtr  walEnd;
     458         636 :             bool        endposReached = false;
     459             : 
     460             :             /*
     461             :              * Parse the keepalive message, enclosed in the CopyData message.
     462             :              * We just check if the server requested a reply, and ignore the
     463             :              * rest.
     464             :              */
     465         636 :             pos = 1;            /* skip msgtype 'k' */
     466         636 :             walEnd = fe_recvint64(&copybuf[pos]);
     467         636 :             output_written_lsn = Max(walEnd, output_written_lsn);
     468             : 
     469         636 :             pos += 8;           /* read walEnd */
     470             : 
     471         636 :             pos += 8;           /* skip sendTime */
     472             : 
     473         636 :             if (r < pos + 1)
     474             :             {
     475           0 :                 pg_log_error("streaming header too small: %d", r);
     476           0 :                 goto error;
     477             :             }
     478         636 :             replyRequested = copybuf[pos];
     479             : 
     480         636 :             if (endpos != InvalidXLogRecPtr && walEnd >= endpos)
     481             :             {
     482             :                 /*
     483             :                  * If there's nothing to read on the socket until a keepalive
     484             :                  * we know that the server has nothing to send us; and if
     485             :                  * walEnd has passed endpos, we know nothing else can have
     486             :                  * committed before endpos.  So we can bail out now.
     487             :                  */
     488           4 :                 endposReached = true;
     489             :             }
     490             : 
     491             :             /* Send a reply, if necessary */
     492         636 :             if (replyRequested || endposReached)
     493             :             {
     494           6 :                 if (!flushAndSendFeedback(conn, &now))
     495           0 :                     goto error;
     496           6 :                 last_status = now;
     497             :             }
     498             : 
     499         636 :             if (endposReached)
     500             :             {
     501           4 :                 stop_reason = STREAM_STOP_KEEPALIVE;
     502           4 :                 time_to_abort = true;
     503           4 :                 break;
     504             :             }
     505             : 
     506         632 :             continue;
     507             :         }
     508         182 :         else if (copybuf[0] != 'w')
     509             :         {
     510           0 :             pg_log_error("unrecognized streaming header: \"%c\"",
     511             :                          copybuf[0]);
     512           0 :             goto error;
     513             :         }
     514             : 
     515             :         /*
     516             :          * Read the header of the XLogData message, enclosed in the CopyData
     517             :          * message. We only need the WAL location field (dataStart), the rest
     518             :          * of the header is ignored.
     519             :          */
     520         182 :         hdr_len = 1;            /* msgtype 'w' */
     521         182 :         hdr_len += 8;           /* dataStart */
     522         182 :         hdr_len += 8;           /* walEnd */
     523         182 :         hdr_len += 8;           /* sendTime */
     524         182 :         if (r < hdr_len + 1)
     525             :         {
     526           0 :             pg_log_error("streaming header too small: %d", r);
     527           0 :             goto error;
     528             :         }
     529             : 
     530             :         /* Extract WAL location for this block */
     531         182 :         cur_record_lsn = fe_recvint64(&copybuf[1]);
     532             : 
     533         182 :         if (endpos != InvalidXLogRecPtr && cur_record_lsn > endpos)
     534             :         {
     535             :             /*
     536             :              * We've read past our endpoint, so prepare to go away being
     537             :              * cautious about what happens to our output data.
     538             :              */
     539           0 :             if (!flushAndSendFeedback(conn, &now))
     540           0 :                 goto error;
     541           0 :             stop_reason = STREAM_STOP_END_OF_WAL;
     542           0 :             time_to_abort = true;
     543           0 :             break;
     544             :         }
     545             : 
     546         182 :         output_written_lsn = Max(cur_record_lsn, output_written_lsn);
     547             : 
     548         182 :         bytes_left = r - hdr_len;
     549         182 :         bytes_written = 0;
     550             : 
     551             :         /* signal that a fsync is needed */
     552         182 :         output_needs_fsync = true;
     553             : 
     554         364 :         while (bytes_left)
     555             :         {
     556             :             int         ret;
     557             : 
     558         364 :             ret = write(outfd,
     559         182 :                         copybuf + hdr_len + bytes_written,
     560             :                         bytes_left);
     561             : 
     562         182 :             if (ret < 0)
     563             :             {
     564           0 :                 pg_log_error("could not write %d bytes to log file \"%s\": %m",
     565             :                              bytes_left, outfile);
     566           0 :                 goto error;
     567             :             }
     568             : 
     569             :             /* Write was successful, advance our position */
     570         182 :             bytes_written += ret;
     571         182 :             bytes_left -= ret;
     572             :         }
     573             : 
     574         182 :         if (write(outfd, "\n", 1) != 1)
     575             :         {
     576           0 :             pg_log_error("could not write %d bytes to log file \"%s\": %m",
     577             :                          1, outfile);
     578           0 :             goto error;
     579             :         }
     580             : 
     581         182 :         if (endpos != InvalidXLogRecPtr && cur_record_lsn == endpos)
     582             :         {
     583             :             /* endpos was exactly the record we just processed, we're done */
     584          10 :             if (!flushAndSendFeedback(conn, &now))
     585           0 :                 goto error;
     586          10 :             stop_reason = STREAM_STOP_END_OF_WAL;
     587          10 :             time_to_abort = true;
     588          10 :             break;
     589             :         }
     590             :     }
     591             : 
     592             :     /* Clean up connection state if stream has been aborted */
     593          30 :     if (time_to_abort)
     594          16 :         prepareToTerminate(conn, endpos, stop_reason, cur_record_lsn);
     595             : 
     596          30 :     res = PQgetResult(conn);
     597          30 :     if (PQresultStatus(res) == PGRES_COPY_OUT)
     598             :     {
     599          16 :         PQclear(res);
     600             : 
     601             :         /*
     602             :          * We're doing a client-initiated clean exit and have sent CopyDone to
     603             :          * the server. Drain any messages, so we don't miss a last-minute
     604             :          * ErrorResponse. The walsender stops generating XLogData records once
     605             :          * it sees CopyDone, so expect this to finish quickly. After CopyDone,
     606             :          * it's too late for sendFeedback(), even if this were to take a long
     607             :          * time. Hence, use synchronous-mode PQgetCopyData().
     608             :          */
     609             :         while (1)
     610           4 :         {
     611             :             int         r;
     612             : 
     613          20 :             if (copybuf != NULL)
     614             :             {
     615          18 :                 PQfreemem(copybuf);
     616          18 :                 copybuf = NULL;
     617             :             }
     618          20 :             r = PQgetCopyData(conn, &copybuf, 0);
     619          20 :             if (r == -1)
     620          16 :                 break;
     621           4 :             if (r == -2)
     622             :             {
     623           0 :                 pg_log_error("could not read COPY data: %s",
     624             :                              PQerrorMessage(conn));
     625           0 :                 time_to_abort = false;  /* unclean exit */
     626           0 :                 goto error;
     627             :             }
     628             :         }
     629             : 
     630          16 :         res = PQgetResult(conn);
     631             :     }
     632          30 :     if (PQresultStatus(res) != PGRES_COMMAND_OK)
     633             :     {
     634          12 :         pg_log_error("unexpected termination of replication stream: %s",
     635             :                      PQresultErrorMessage(res));
     636          12 :         goto error;
     637             :     }
     638          18 :     PQclear(res);
     639             : 
     640          18 :     if (outfd != -1 && strcmp(outfile, "-") != 0)
     641             :     {
     642           0 :         TimestampTz t = feGetCurrentTimestamp();
     643             : 
     644             :         /* no need to jump to error on failure here, we're finishing anyway */
     645           0 :         OutputFsync(t);
     646             : 
     647           0 :         if (close(outfd) != 0)
     648           0 :             pg_log_error("could not close file \"%s\": %m", outfile);
     649             :     }
     650          18 :     outfd = -1;
     651          46 : error:
     652          46 :     if (copybuf != NULL)
     653             :     {
     654           0 :         PQfreemem(copybuf);
     655           0 :         copybuf = NULL;
     656             :     }
     657          46 :     destroyPQExpBuffer(query);
     658          46 :     PQfinish(conn);
     659          46 :     conn = NULL;
     660             : }
     661             : 
     662             : /*
     663             :  * Unfortunately we can't do sensible signal handling on windows...
     664             :  */
     665             : #ifndef WIN32
     666             : 
     667             : /*
     668             :  * When SIGINT/SIGTERM are caught, just tell the system to exit at the next
     669             :  * possible moment.
     670             :  */
     671             : static void
     672           2 : sigexit_handler(SIGNAL_ARGS)
     673             : {
     674           2 :     stop_reason = STREAM_STOP_SIGNAL;
     675           2 :     time_to_abort = true;
     676           2 : }
     677             : 
     678             : /*
     679             :  * Trigger the output file to be reopened.
     680             :  */
     681             : static void
     682           0 : sighup_handler(SIGNAL_ARGS)
     683             : {
     684           0 :     output_reopen = true;
     685           0 : }
     686             : #endif
     687             : 
     688             : 
     689             : int
     690         110 : main(int argc, char **argv)
     691             : {
     692             :     static struct option long_options[] = {
     693             : /* general options */
     694             :         {"file", required_argument, NULL, 'f'},
     695             :         {"fsync-interval", required_argument, NULL, 'F'},
     696             :         {"no-loop", no_argument, NULL, 'n'},
     697             :         {"verbose", no_argument, NULL, 'v'},
     698             :         {"two-phase", no_argument, NULL, 't'},
     699             :         {"version", no_argument, NULL, 'V'},
     700             :         {"help", no_argument, NULL, '?'},
     701             : /* connection options */
     702             :         {"dbname", required_argument, NULL, 'd'},
     703             :         {"host", required_argument, NULL, 'h'},
     704             :         {"port", required_argument, NULL, 'p'},
     705             :         {"username", required_argument, NULL, 'U'},
     706             :         {"no-password", no_argument, NULL, 'w'},
     707             :         {"password", no_argument, NULL, 'W'},
     708             : /* replication options */
     709             :         {"startpos", required_argument, NULL, 'I'},
     710             :         {"endpos", required_argument, NULL, 'E'},
     711             :         {"option", required_argument, NULL, 'o'},
     712             :         {"plugin", required_argument, NULL, 'P'},
     713             :         {"status-interval", required_argument, NULL, 's'},
     714             :         {"slot", required_argument, NULL, 'S'},
     715             : /* action */
     716             :         {"create-slot", no_argument, NULL, 1},
     717             :         {"start", no_argument, NULL, 2},
     718             :         {"drop-slot", no_argument, NULL, 3},
     719             :         {"if-not-exists", no_argument, NULL, 4},
     720             :         {NULL, 0, NULL, 0}
     721             :     };
     722             :     int         c;
     723             :     int         option_index;
     724             :     uint32      hi,
     725             :                 lo;
     726             :     char       *db_name;
     727             : 
     728         110 :     pg_logging_init(argv[0]);
     729         110 :     progname = get_progname(argv[0]);
     730         110 :     set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_basebackup"));
     731             : 
     732         110 :     if (argc > 1)
     733             :     {
     734         108 :         if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
     735             :         {
     736           2 :             usage();
     737           2 :             exit(0);
     738             :         }
     739         106 :         else if (strcmp(argv[1], "-V") == 0 ||
     740         106 :                  strcmp(argv[1], "--version") == 0)
     741             :         {
     742           2 :             puts("pg_recvlogical (PostgreSQL) " PG_VERSION);
     743           2 :             exit(0);
     744             :         }
     745             :     }
     746             : 
     747         642 :     while ((c = getopt_long(argc, argv, "E:f:F:ntvd:h:p:U:wWI:o:P:s:S:",
     748             :                             long_options, &option_index)) != -1)
     749             :     {
     750         538 :         switch (c)
     751             :         {
     752             : /* general options */
     753          48 :             case 'f':
     754          48 :                 outfile = pg_strdup(optarg);
     755          48 :                 break;
     756           0 :             case 'F':
     757           0 :                 if (!option_parse_int(optarg, "-F/--fsync-interval", 0,
     758             :                                       INT_MAX / 1000,
     759             :                                       &fsync_interval))
     760           0 :                     exit(1);
     761           0 :                 fsync_interval *= 1000;
     762           0 :                 break;
     763          46 :             case 'n':
     764          46 :                 noloop = 1;
     765          46 :                 break;
     766           4 :             case 't':
     767           4 :                 two_phase = true;
     768           4 :                 break;
     769           0 :             case 'v':
     770           0 :                 verbose++;
     771           0 :                 break;
     772             : /* connection options */
     773         100 :             case 'd':
     774         100 :                 dbname = pg_strdup(optarg);
     775         100 :                 break;
     776           0 :             case 'h':
     777           0 :                 dbhost = pg_strdup(optarg);
     778           0 :                 break;
     779           0 :             case 'p':
     780           0 :                 dbport = pg_strdup(optarg);
     781           0 :                 break;
     782           0 :             case 'U':
     783           0 :                 dbuser = pg_strdup(optarg);
     784           0 :                 break;
     785           0 :             case 'w':
     786           0 :                 dbgetpassword = -1;
     787           0 :                 break;
     788           0 :             case 'W':
     789           0 :                 dbgetpassword = 1;
     790           0 :                 break;
     791             : /* replication options */
     792           0 :             case 'I':
     793           0 :                 if (sscanf(optarg, "%X/%X", &hi, &lo) != 2)
     794           0 :                     pg_fatal("could not parse start position \"%s\"", optarg);
     795           0 :                 startpos = ((uint64) hi) << 32 | lo;
     796           0 :                 break;
     797          16 :             case 'E':
     798          16 :                 if (sscanf(optarg, "%X/%X", &hi, &lo) != 2)
     799           0 :                     pg_fatal("could not parse end position \"%s\"", optarg);
     800          16 :                 endpos = ((uint64) hi) << 32 | lo;
     801          16 :                 break;
     802          80 :             case 'o':
     803             :                 {
     804          80 :                     char       *data = pg_strdup(optarg);
     805          80 :                     char       *val = strchr(data, '=');
     806             : 
     807          80 :                     if (val != NULL)
     808             :                     {
     809             :                         /* remove =; separate data from val */
     810          80 :                         *val = '\0';
     811          80 :                         val++;
     812             :                     }
     813             : 
     814          80 :                     noptions += 1;
     815          80 :                     options = pg_realloc(options, sizeof(char *) * noptions * 2);
     816             : 
     817          80 :                     options[(noptions - 1) * 2] = data;
     818          80 :                     options[(noptions - 1) * 2 + 1] = val;
     819             :                 }
     820             : 
     821          80 :                 break;
     822          42 :             case 'P':
     823          42 :                 plugin = pg_strdup(optarg);
     824          42 :                 break;
     825           0 :             case 's':
     826           0 :                 if (!option_parse_int(optarg, "-s/--status-interval", 0,
     827             :                                       INT_MAX / 1000,
     828             :                                       &standby_message_timeout))
     829           0 :                     exit(1);
     830           0 :                 standby_message_timeout *= 1000;
     831           0 :                 break;
     832         102 :             case 'S':
     833         102 :                 replication_slot = pg_strdup(optarg);
     834         102 :                 break;
     835             : /* action */
     836          46 :             case 1:
     837          46 :                 do_create_slot = true;
     838          46 :                 break;
     839          50 :             case 2:
     840          50 :                 do_start_slot = true;
     841          50 :                 break;
     842           2 :             case 3:
     843           2 :                 do_drop_slot = true;
     844           2 :                 break;
     845           0 :             case 4:
     846           0 :                 slot_exists_ok = true;
     847           0 :                 break;
     848             : 
     849           2 :             default:
     850             :                 /* getopt_long already emitted a complaint */
     851           2 :                 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     852           2 :                 exit(1);
     853             :         }
     854             :     }
     855             : 
     856             :     /*
     857             :      * Any non-option arguments?
     858             :      */
     859         104 :     if (optind < argc)
     860             :     {
     861           0 :         pg_log_error("too many command-line arguments (first is \"%s\")",
     862             :                      argv[optind]);
     863           0 :         pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     864           0 :         exit(1);
     865             :     }
     866             : 
     867             :     /*
     868             :      * Required arguments
     869             :      */
     870         104 :     if (replication_slot == NULL)
     871             :     {
     872           2 :         pg_log_error("no slot specified");
     873           2 :         pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     874           2 :         exit(1);
     875             :     }
     876             : 
     877         102 :     if (do_start_slot && outfile == NULL)
     878             :     {
     879           2 :         pg_log_error("no target file specified");
     880           2 :         pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     881           2 :         exit(1);
     882             :     }
     883             : 
     884         100 :     if (!do_drop_slot && dbname == NULL)
     885             :     {
     886           2 :         pg_log_error("no database specified");
     887           2 :         pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     888           2 :         exit(1);
     889             :     }
     890             : 
     891          98 :     if (!do_drop_slot && !do_create_slot && !do_start_slot)
     892             :     {
     893           2 :         pg_log_error("at least one action needs to be specified");
     894           2 :         pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     895           2 :         exit(1);
     896             :     }
     897             : 
     898          96 :     if (do_drop_slot && (do_create_slot || do_start_slot))
     899             :     {
     900           0 :         pg_log_error("cannot use --create-slot or --start together with --drop-slot");
     901           0 :         pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     902           0 :         exit(1);
     903             :     }
     904             : 
     905          96 :     if (startpos != InvalidXLogRecPtr && (do_create_slot || do_drop_slot))
     906             :     {
     907           0 :         pg_log_error("cannot use --create-slot or --drop-slot together with --startpos");
     908           0 :         pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     909           0 :         exit(1);
     910             :     }
     911             : 
     912          96 :     if (endpos != InvalidXLogRecPtr && !do_start_slot)
     913             :     {
     914           0 :         pg_log_error("--endpos may only be specified with --start");
     915           0 :         pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     916           0 :         exit(1);
     917             :     }
     918             : 
     919          96 :     if (two_phase && !do_create_slot)
     920             :     {
     921           2 :         pg_log_error("--two-phase may only be specified with --create-slot");
     922           2 :         pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     923           2 :         exit(1);
     924             :     }
     925             : 
     926             :     /*
     927             :      * Obtain a connection to server.  Notably, if we need a password, we want
     928             :      * to collect it from the user immediately.
     929             :      */
     930          94 :     conn = GetConnection();
     931          94 :     if (!conn)
     932             :         /* Error message already written in GetConnection() */
     933           0 :         exit(1);
     934          94 :     atexit(disconnect_atexit);
     935             : 
     936             :     /*
     937             :      * Trap signals.  (Don't do this until after the initial password prompt,
     938             :      * if one is needed, in GetConnection.)
     939             :      */
     940             : #ifndef WIN32
     941          94 :     pqsignal(SIGINT, sigexit_handler);
     942          94 :     pqsignal(SIGTERM, sigexit_handler);
     943          94 :     pqsignal(SIGHUP, sighup_handler);
     944             : #endif
     945             : 
     946             :     /*
     947             :      * Run IDENTIFY_SYSTEM to make sure we connected using a database specific
     948             :      * replication connection.
     949             :      */
     950          94 :     if (!RunIdentifySystem(conn, NULL, NULL, NULL, &db_name))
     951           0 :         exit(1);
     952             : 
     953          94 :     if (db_name == NULL)
     954           0 :         pg_fatal("could not establish database-specific replication connection");
     955             : 
     956             :     /*
     957             :      * Set umask so that directories/files are created with the same
     958             :      * permissions as directories/files in the source data directory.
     959             :      *
     960             :      * pg_mode_mask is set to owner-only by default and then updated in
     961             :      * GetConnection() where we get the mode from the server-side with
     962             :      * RetrieveDataDirCreatePerm() and then call SetDataDirectoryCreatePerm().
     963             :      */
     964          94 :     umask(pg_mode_mask);
     965             : 
     966             :     /* Drop a replication slot. */
     967          94 :     if (do_drop_slot)
     968             :     {
     969           2 :         if (verbose)
     970           0 :             pg_log_info("dropping replication slot \"%s\"", replication_slot);
     971             : 
     972           2 :         if (!DropReplicationSlot(conn, replication_slot))
     973           0 :             exit(1);
     974             :     }
     975             : 
     976             :     /* Create a replication slot. */
     977          94 :     if (do_create_slot)
     978             :     {
     979          46 :         if (verbose)
     980           0 :             pg_log_info("creating replication slot \"%s\"", replication_slot);
     981             : 
     982          46 :         if (!CreateReplicationSlot(conn, replication_slot, plugin, false,
     983             :                                    false, false, slot_exists_ok, two_phase))
     984           0 :             exit(1);
     985          46 :         startpos = InvalidXLogRecPtr;
     986             :     }
     987             : 
     988          94 :     if (!do_start_slot)
     989          48 :         exit(0);
     990             : 
     991             :     /* Stream loop */
     992             :     while (true)
     993             :     {
     994          46 :         StreamLogicalLog();
     995          46 :         if (time_to_abort)
     996             :         {
     997             :             /*
     998             :              * We've been Ctrl-C'ed or reached an exit limit condition. That's
     999             :              * not an error, so exit without an errorcode.
    1000             :              */
    1001          16 :             exit(0);
    1002             :         }
    1003          30 :         else if (noloop)
    1004          30 :             pg_fatal("disconnected");
    1005             :         else
    1006             :         {
    1007             :             /* translator: check source for value for %d */
    1008           0 :             pg_log_info("disconnected; waiting %d seconds to try again",
    1009             :                         RECONNECT_SLEEP_TIME);
    1010           0 :             pg_usleep(RECONNECT_SLEEP_TIME * 1000000);
    1011             :         }
    1012             :     }
    1013             : }
    1014             : 
    1015             : /*
    1016             :  * Fsync our output data, and send a feedback message to the server.  Returns
    1017             :  * true if successful, false otherwise.
    1018             :  *
    1019             :  * If successful, *now is updated to the current timestamp just before sending
    1020             :  * feedback.
    1021             :  */
    1022             : static bool
    1023          16 : flushAndSendFeedback(PGconn *conn, TimestampTz *now)
    1024             : {
    1025             :     /* flush data to disk, so that we send a recent flush pointer */
    1026          16 :     if (!OutputFsync(*now))
    1027           0 :         return false;
    1028          16 :     *now = feGetCurrentTimestamp();
    1029          16 :     if (!sendFeedback(conn, *now, true, false))
    1030           0 :         return false;
    1031             : 
    1032          16 :     return true;
    1033             : }
    1034             : 
    1035             : /*
    1036             :  * Try to inform the server about our upcoming demise, but don't wait around or
    1037             :  * retry on failure.
    1038             :  */
    1039             : static void
    1040          16 : prepareToTerminate(PGconn *conn, XLogRecPtr endpos, StreamStopReason reason,
    1041             :                    XLogRecPtr lsn)
    1042             : {
    1043          16 :     (void) PQputCopyEnd(conn, NULL);
    1044          16 :     (void) PQflush(conn);
    1045             : 
    1046          16 :     if (verbose)
    1047             :     {
    1048           0 :         switch (reason)
    1049             :         {
    1050           0 :             case STREAM_STOP_SIGNAL:
    1051           0 :                 pg_log_info("received interrupt signal, exiting");
    1052           0 :                 break;
    1053           0 :             case STREAM_STOP_KEEPALIVE:
    1054           0 :                 pg_log_info("end position %X/%X reached by keepalive",
    1055             :                             LSN_FORMAT_ARGS(endpos));
    1056           0 :                 break;
    1057           0 :             case STREAM_STOP_END_OF_WAL:
    1058             :                 Assert(!XLogRecPtrIsInvalid(lsn));
    1059           0 :                 pg_log_info("end position %X/%X reached by WAL record at %X/%X",
    1060             :                             LSN_FORMAT_ARGS(endpos), LSN_FORMAT_ARGS(lsn));
    1061           0 :                 break;
    1062           0 :             case STREAM_STOP_NONE:
    1063             :                 Assert(false);
    1064           0 :                 break;
    1065             :         }
    1066          16 :     }
    1067          16 : }

Generated by: LCOV version 1.14