LCOV - code coverage report
Current view: top level - src/bin/pg_rewind - pg_rewind.c (source / functions) Hit Total Coverage
Test: PostgreSQL 18devel Lines: 340 411 82.7 %
Date: 2024-11-10 04:14:54 Functions: 14 14 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * pg_rewind.c
       4             :  *    Synchronizes a PostgreSQL data directory to a new timeline
       5             :  *
       6             :  * Portions Copyright (c) 1996-2024, PostgreSQL Global Development Group
       7             :  *
       8             :  *-------------------------------------------------------------------------
       9             :  */
      10             : #include "postgres_fe.h"
      11             : 
      12             : #include <sys/stat.h>
      13             : #include <fcntl.h>
      14             : #include <time.h>
      15             : #include <unistd.h>
      16             : 
      17             : #include "access/timeline.h"
      18             : #include "access/xlog_internal.h"
      19             : #include "catalog/catversion.h"
      20             : #include "catalog/pg_control.h"
      21             : #include "common/controldata_utils.h"
      22             : #include "common/file_perm.h"
      23             : #include "common/restricted_token.h"
      24             : #include "common/string.h"
      25             : #include "fe_utils/option_utils.h"
      26             : #include "fe_utils/recovery_gen.h"
      27             : #include "fe_utils/string_utils.h"
      28             : #include "file_ops.h"
      29             : #include "filemap.h"
      30             : #include "getopt_long.h"
      31             : #include "pg_rewind.h"
      32             : #include "rewind_source.h"
      33             : #include "storage/bufpage.h"
      34             : 
      35             : static void usage(const char *progname);
      36             : 
      37             : static void perform_rewind(filemap_t *filemap, rewind_source *source,
      38             :                            XLogRecPtr chkptrec,
      39             :                            TimeLineID chkpttli,
      40             :                            XLogRecPtr chkptredo);
      41             : 
      42             : static void createBackupLabel(XLogRecPtr startpoint, TimeLineID starttli,
      43             :                               XLogRecPtr checkpointloc);
      44             : 
      45             : static void digestControlFile(ControlFileData *ControlFile,
      46             :                               const char *content, size_t size);
      47             : static void getRestoreCommand(const char *argv0);
      48             : static void sanityChecks(void);
      49             : static TimeLineHistoryEntry *getTimelineHistory(TimeLineID tli, bool is_source,
      50             :                                                 int *nentries);
      51             : static void findCommonAncestorTimeline(TimeLineHistoryEntry *a_history,
      52             :                                        int a_nentries,
      53             :                                        TimeLineHistoryEntry *b_history,
      54             :                                        int b_nentries,
      55             :                                        XLogRecPtr *recptr, int *tliIndex);
      56             : static void ensureCleanShutdown(const char *argv0);
      57             : static void disconnect_atexit(void);
      58             : 
      59             : static ControlFileData ControlFile_target;
      60             : static ControlFileData ControlFile_source;
      61             : static ControlFileData ControlFile_source_after;
      62             : 
      63             : static const char *progname;
      64             : int         WalSegSz;
      65             : 
      66             : /* Configuration options */
      67             : char       *datadir_target = NULL;
      68             : static char *datadir_source = NULL;
      69             : static char *connstr_source = NULL;
      70             : static char *restore_command = NULL;
      71             : static char *config_file = NULL;
      72             : 
      73             : static bool debug = false;
      74             : bool        showprogress = false;
      75             : bool        dry_run = false;
      76             : bool        do_sync = true;
      77             : static bool restore_wal = false;
      78             : DataDirSyncMethod sync_method = DATA_DIR_SYNC_METHOD_FSYNC;
      79             : 
      80             : /* Target history */
      81             : TimeLineHistoryEntry *targetHistory;
      82             : int         targetNentries;
      83             : 
      84             : /* Progress counters */
      85             : uint64      fetch_size;
      86             : uint64      fetch_done;
      87             : 
      88             : static PGconn *conn;
      89             : static rewind_source *source;
      90             : 
      91             : static void
      92           2 : usage(const char *progname)
      93             : {
      94           2 :     printf(_("%s resynchronizes a PostgreSQL cluster with another copy of the cluster.\n\n"), progname);
      95           2 :     printf(_("Usage:\n  %s [OPTION]...\n\n"), progname);
      96           2 :     printf(_("Options:\n"));
      97           2 :     printf(_("  -c, --restore-target-wal       use \"restore_command\" in target configuration to\n"
      98             :              "                                 retrieve WAL files from archives\n"));
      99           2 :     printf(_("  -D, --target-pgdata=DIRECTORY  existing data directory to modify\n"));
     100           2 :     printf(_("      --source-pgdata=DIRECTORY  source data directory to synchronize with\n"));
     101           2 :     printf(_("      --source-server=CONNSTR    source server to synchronize with\n"));
     102           2 :     printf(_("  -n, --dry-run                  stop before modifying anything\n"));
     103           2 :     printf(_("  -N, --no-sync                  do not wait for changes to be written\n"
     104             :              "                                 safely to disk\n"));
     105           2 :     printf(_("  -P, --progress                 write progress messages\n"));
     106           2 :     printf(_("  -R, --write-recovery-conf      write configuration for replication\n"
     107             :              "                                 (requires --source-server)\n"));
     108           2 :     printf(_("      --config-file=FILENAME     use specified main server configuration\n"
     109             :              "                                 file when running target cluster\n"));
     110           2 :     printf(_("      --debug                    write a lot of debug messages\n"));
     111           2 :     printf(_("      --no-ensure-shutdown       do not automatically fix unclean shutdown\n"));
     112           2 :     printf(_("      --sync-method=METHOD       set method for syncing files to disk\n"));
     113           2 :     printf(_("  -V, --version                  output version information, then exit\n"));
     114           2 :     printf(_("  -?, --help                     show this help, then exit\n"));
     115           2 :     printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
     116           2 :     printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
     117           2 : }
     118             : 
     119             : 
     120             : int
     121          48 : main(int argc, char **argv)
     122             : {
     123             :     static struct option long_options[] = {
     124             :         {"help", no_argument, NULL, '?'},
     125             :         {"target-pgdata", required_argument, NULL, 'D'},
     126             :         {"write-recovery-conf", no_argument, NULL, 'R'},
     127             :         {"source-pgdata", required_argument, NULL, 1},
     128             :         {"source-server", required_argument, NULL, 2},
     129             :         {"no-ensure-shutdown", no_argument, NULL, 4},
     130             :         {"config-file", required_argument, NULL, 5},
     131             :         {"version", no_argument, NULL, 'V'},
     132             :         {"restore-target-wal", no_argument, NULL, 'c'},
     133             :         {"dry-run", no_argument, NULL, 'n'},
     134             :         {"no-sync", no_argument, NULL, 'N'},
     135             :         {"progress", no_argument, NULL, 'P'},
     136             :         {"debug", no_argument, NULL, 3},
     137             :         {"sync-method", required_argument, NULL, 6},
     138             :         {NULL, 0, NULL, 0}
     139             :     };
     140             :     int         option_index;
     141             :     int         c;
     142             :     XLogRecPtr  divergerec;
     143             :     int         lastcommontliIndex;
     144             :     XLogRecPtr  chkptrec;
     145             :     TimeLineID  chkpttli;
     146             :     XLogRecPtr  chkptredo;
     147             :     TimeLineID  source_tli;
     148             :     TimeLineID  target_tli;
     149             :     XLogRecPtr  target_wal_endrec;
     150             :     size_t      size;
     151             :     char       *buffer;
     152          48 :     bool        no_ensure_shutdown = false;
     153             :     bool        rewind_needed;
     154          48 :     bool        writerecoveryconf = false;
     155             :     filemap_t  *filemap;
     156             : 
     157          48 :     pg_logging_init(argv[0]);
     158          48 :     set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_rewind"));
     159          48 :     progname = get_progname(argv[0]);
     160             : 
     161             :     /* Process command-line arguments */
     162          48 :     if (argc > 1)
     163             :     {
     164          48 :         if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
     165             :         {
     166           2 :             usage(progname);
     167           2 :             exit(0);
     168             :         }
     169          46 :         if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
     170             :         {
     171           2 :             puts("pg_rewind (PostgreSQL) " PG_VERSION);
     172           2 :             exit(0);
     173             :         }
     174             :     }
     175             : 
     176         242 :     while ((c = getopt_long(argc, argv, "cD:nNPR", long_options, &option_index)) != -1)
     177             :     {
     178         200 :         switch (c)
     179             :         {
     180           2 :             case 'c':
     181           2 :                 restore_wal = true;
     182           2 :                 break;
     183             : 
     184           0 :             case 'P':
     185           0 :                 showprogress = true;
     186           0 :                 break;
     187             : 
     188           2 :             case 'n':
     189           2 :                 dry_run = true;
     190           2 :                 break;
     191             : 
     192          32 :             case 'N':
     193          32 :                 do_sync = false;
     194          32 :                 break;
     195             : 
     196          12 :             case 'R':
     197          12 :                 writerecoveryconf = true;
     198          12 :                 break;
     199             : 
     200          40 :             case 3:
     201          40 :                 debug = true;
     202          40 :                 pg_logging_increase_verbosity();
     203          40 :                 break;
     204             : 
     205          42 :             case 'D':           /* -D or --target-pgdata */
     206          42 :                 datadir_target = pg_strdup(optarg);
     207          42 :                 break;
     208             : 
     209          28 :             case 1:             /* --source-pgdata */
     210          28 :                 datadir_source = pg_strdup(optarg);
     211          28 :                 break;
     212             : 
     213          14 :             case 2:             /* --source-server */
     214          14 :                 connstr_source = pg_strdup(optarg);
     215          14 :                 break;
     216             : 
     217           6 :             case 4:
     218           6 :                 no_ensure_shutdown = true;
     219           6 :                 break;
     220             : 
     221          20 :             case 5:
     222          20 :                 config_file = pg_strdup(optarg);
     223          20 :                 break;
     224             : 
     225           0 :             case 6:
     226           0 :                 if (!parse_sync_method(optarg, &sync_method))
     227           0 :                     exit(1);
     228           0 :                 break;
     229             : 
     230           2 :             default:
     231             :                 /* getopt_long already emitted a complaint */
     232           2 :                 pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     233           2 :                 exit(1);
     234             :         }
     235             :     }
     236             : 
     237          42 :     if (datadir_source == NULL && connstr_source == NULL)
     238             :     {
     239           2 :         pg_log_error("no source specified (--source-pgdata or --source-server)");
     240           2 :         pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     241           2 :         exit(1);
     242             :     }
     243             : 
     244          40 :     if (datadir_source != NULL && connstr_source != NULL)
     245             :     {
     246           2 :         pg_log_error("only one of --source-pgdata or --source-server can be specified");
     247           2 :         pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     248           2 :         exit(1);
     249             :     }
     250             : 
     251          38 :     if (datadir_target == NULL)
     252             :     {
     253           0 :         pg_log_error("no target data directory specified (--target-pgdata)");
     254           0 :         pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     255           0 :         exit(1);
     256             :     }
     257             : 
     258          38 :     if (writerecoveryconf && connstr_source == NULL)
     259             :     {
     260           2 :         pg_log_error("no source server information (--source-server) specified for --write-recovery-conf");
     261           2 :         pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     262           2 :         exit(1);
     263             :     }
     264             : 
     265          36 :     if (optind < argc)
     266             :     {
     267           2 :         pg_log_error("too many command-line arguments (first is \"%s\")",
     268             :                      argv[optind]);
     269           2 :         pg_log_error_hint("Try \"%s --help\" for more information.", progname);
     270           2 :         exit(1);
     271             :     }
     272             : 
     273             :     /*
     274             :      * Don't allow pg_rewind to be run as root, to avoid overwriting the
     275             :      * ownership of files in the data directory. We need only check for root
     276             :      * -- any other user won't have sufficient permissions to modify files in
     277             :      * the data directory.
     278             :      */
     279             : #ifndef WIN32
     280          34 :     if (geteuid() == 0)
     281             :     {
     282           0 :         pg_log_error("cannot be executed by \"root\"");
     283           0 :         pg_log_error_hint("You must run %s as the PostgreSQL superuser.",
     284             :                           progname);
     285           0 :         exit(1);
     286             :     }
     287             : #endif
     288             : 
     289          34 :     get_restricted_token();
     290             : 
     291             :     /* Set mask based on PGDATA permissions */
     292          34 :     if (!GetDataDirectoryCreatePerm(datadir_target))
     293           0 :         pg_fatal("could not read permissions of directory \"%s\": %m",
     294             :                  datadir_target);
     295             : 
     296          34 :     umask(pg_mode_mask);
     297             : 
     298          34 :     getRestoreCommand(argv[0]);
     299             : 
     300          34 :     atexit(disconnect_atexit);
     301             : 
     302             :     /*
     303             :      * Ok, we have all the options and we're ready to start. First, connect to
     304             :      * remote server.
     305             :      */
     306          34 :     if (connstr_source)
     307             :     {
     308          12 :         conn = PQconnectdb(connstr_source);
     309             : 
     310          12 :         if (PQstatus(conn) == CONNECTION_BAD)
     311           0 :             pg_fatal("%s", PQerrorMessage(conn));
     312             : 
     313          12 :         if (showprogress)
     314           0 :             pg_log_info("connected to server");
     315             : 
     316          12 :         source = init_libpq_source(conn);
     317             :     }
     318             :     else
     319          22 :         source = init_local_source(datadir_source);
     320             : 
     321             :     /*
     322             :      * Check the status of the target instance.
     323             :      *
     324             :      * If the target instance was not cleanly shut down, start and stop the
     325             :      * target cluster once in single-user mode to enforce recovery to finish,
     326             :      * ensuring that the cluster can be used by pg_rewind.  Note that if
     327             :      * no_ensure_shutdown is specified, pg_rewind ignores this step, and users
     328             :      * need to make sure by themselves that the target cluster is in a clean
     329             :      * state.
     330             :      */
     331          34 :     buffer = slurpFile(datadir_target, "global/pg_control", &size);
     332          34 :     digestControlFile(&ControlFile_target, buffer, size);
     333          34 :     pg_free(buffer);
     334             : 
     335          34 :     if (!no_ensure_shutdown &&
     336          28 :         ControlFile_target.state != DB_SHUTDOWNED &&
     337          22 :         ControlFile_target.state != DB_SHUTDOWNED_IN_RECOVERY)
     338             :     {
     339          20 :         ensureCleanShutdown(argv[0]);
     340             : 
     341          18 :         buffer = slurpFile(datadir_target, "global/pg_control", &size);
     342          18 :         digestControlFile(&ControlFile_target, buffer, size);
     343          18 :         pg_free(buffer);
     344             :     }
     345             : 
     346          32 :     buffer = source->fetch_file(source, "global/pg_control", &size);
     347          32 :     digestControlFile(&ControlFile_source, buffer, size);
     348          32 :     pg_free(buffer);
     349             : 
     350          32 :     sanityChecks();
     351             : 
     352             :     /*
     353             :      * Usually, the TLI can be found in the latest checkpoint record. But if
     354             :      * the source server is just being promoted (or it's a standby that's
     355             :      * following a primary that's just being promoted), and the checkpoint
     356             :      * requested by the promotion hasn't completed yet, the latest timeline is
     357             :      * in minRecoveryPoint. So we check which is later, the TLI of the
     358             :      * minRecoveryPoint or the latest checkpoint.
     359             :      */
     360          28 :     source_tli = Max(ControlFile_source.minRecoveryPointTLI,
     361             :                      ControlFile_source.checkPointCopy.ThisTimeLineID);
     362             : 
     363             :     /* Similarly for the target. */
     364          28 :     target_tli = Max(ControlFile_target.minRecoveryPointTLI,
     365             :                      ControlFile_target.checkPointCopy.ThisTimeLineID);
     366             : 
     367             :     /*
     368             :      * Find the common ancestor timeline between the clusters.
     369             :      *
     370             :      * If both clusters are already on the same timeline, there's nothing to
     371             :      * do.
     372             :      */
     373          28 :     if (target_tli == source_tli)
     374             :     {
     375           2 :         pg_log_info("source and target cluster are on the same timeline");
     376           2 :         rewind_needed = false;
     377           2 :         target_wal_endrec = 0;
     378             :     }
     379             :     else
     380             :     {
     381             :         XLogRecPtr  chkptendrec;
     382             :         TimeLineHistoryEntry *sourceHistory;
     383             :         int         sourceNentries;
     384             : 
     385             :         /*
     386             :          * Retrieve timelines for both source and target, and find the point
     387             :          * where they diverged.
     388             :          */
     389          26 :         sourceHistory = getTimelineHistory(source_tli, true, &sourceNentries);
     390          26 :         targetHistory = getTimelineHistory(target_tli, false, &targetNentries);
     391             : 
     392          26 :         findCommonAncestorTimeline(sourceHistory, sourceNentries,
     393             :                                    targetHistory, targetNentries,
     394             :                                    &divergerec, &lastcommontliIndex);
     395             : 
     396          26 :         pg_log_info("servers diverged at WAL location %X/%X on timeline %u",
     397             :                     LSN_FORMAT_ARGS(divergerec),
     398             :                     targetHistory[lastcommontliIndex].tli);
     399             : 
     400             :         /*
     401             :          * Don't need the source history anymore. The target history is still
     402             :          * needed by the routines in parsexlog.c, when we read the target WAL.
     403             :          */
     404          26 :         pfree(sourceHistory);
     405             : 
     406             : 
     407             :         /*
     408             :          * Determine the end-of-WAL on the target.
     409             :          *
     410             :          * The WAL ends at the last shutdown checkpoint, or at
     411             :          * minRecoveryPoint if it was a standby. (If we supported rewinding a
     412             :          * server that was not shut down cleanly, we would need to replay
     413             :          * until we reach the first invalid record, like crash recovery does.)
     414             :          */
     415             : 
     416             :         /* read the checkpoint record on the target to see where it ends. */
     417          26 :         chkptendrec = readOneRecord(datadir_target,
     418             :                                     ControlFile_target.checkPoint,
     419             :                                     targetNentries - 1,
     420             :                                     restore_command);
     421             : 
     422          26 :         if (ControlFile_target.minRecoveryPoint > chkptendrec)
     423             :         {
     424           2 :             target_wal_endrec = ControlFile_target.minRecoveryPoint;
     425             :         }
     426             :         else
     427             :         {
     428          24 :             target_wal_endrec = chkptendrec;
     429             :         }
     430             : 
     431             :         /*
     432             :          * Check for the possibility that the target is in fact a direct
     433             :          * ancestor of the source. In that case, there is no divergent history
     434             :          * in the target that needs rewinding.
     435             :          */
     436          26 :         if (target_wal_endrec > divergerec)
     437             :         {
     438          26 :             rewind_needed = true;
     439             :         }
     440             :         else
     441             :         {
     442             :             /* the last common checkpoint record must be part of target WAL */
     443             :             Assert(target_wal_endrec == divergerec);
     444             : 
     445           0 :             rewind_needed = false;
     446             :         }
     447             :     }
     448             : 
     449          28 :     if (!rewind_needed)
     450             :     {
     451           2 :         pg_log_info("no rewind required");
     452           2 :         if (writerecoveryconf && !dry_run)
     453           0 :             WriteRecoveryConfig(conn, datadir_target,
     454             :                                 GenerateRecoveryConfig(conn, NULL, NULL));
     455           2 :         exit(0);
     456             :     }
     457             : 
     458          26 :     findLastCheckpoint(datadir_target, divergerec, lastcommontliIndex,
     459             :                        &chkptrec, &chkpttli, &chkptredo, restore_command);
     460          26 :     pg_log_info("rewinding from last common checkpoint at %X/%X on timeline %u",
     461             :                 LSN_FORMAT_ARGS(chkptrec), chkpttli);
     462             : 
     463             :     /* Initialize the hash table to track the status of each file */
     464          26 :     filehash_init();
     465             : 
     466             :     /*
     467             :      * Collect information about all files in the both data directories.
     468             :      */
     469          26 :     if (showprogress)
     470           0 :         pg_log_info("reading source file list");
     471          26 :     source->traverse_files(source, &process_source_file);
     472             : 
     473          26 :     if (showprogress)
     474           0 :         pg_log_info("reading target file list");
     475          26 :     traverse_datadir(datadir_target, &process_target_file);
     476             : 
     477             :     /*
     478             :      * Read the target WAL from last checkpoint before the point of fork, to
     479             :      * extract all the pages that were modified on the target cluster after
     480             :      * the fork.
     481             :      */
     482          26 :     if (showprogress)
     483           0 :         pg_log_info("reading WAL in target");
     484          26 :     extractPageMap(datadir_target, chkptrec, lastcommontliIndex,
     485             :                    target_wal_endrec, restore_command);
     486             : 
     487             :     /*
     488             :      * We have collected all information we need from both systems. Decide
     489             :      * what to do with each file.
     490             :      */
     491          26 :     filemap = decide_file_actions();
     492          26 :     if (showprogress)
     493           0 :         calculate_totals(filemap);
     494             : 
     495             :     /* this is too verbose even for verbose mode */
     496          26 :     if (debug)
     497          26 :         print_filemap(filemap);
     498             : 
     499             :     /*
     500             :      * Ok, we're ready to start copying things over.
     501             :      */
     502          26 :     if (showprogress)
     503             :     {
     504           0 :         pg_log_info("need to copy %lu MB (total source directory size is %lu MB)",
     505             :                     (unsigned long) (filemap->fetch_size / (1024 * 1024)),
     506             :                     (unsigned long) (filemap->total_size / (1024 * 1024)));
     507             : 
     508           0 :         fetch_size = filemap->fetch_size;
     509           0 :         fetch_done = 0;
     510             :     }
     511             : 
     512             :     /*
     513             :      * We have now collected all the information we need from both systems,
     514             :      * and we are ready to start modifying the target directory.
     515             :      *
     516             :      * This is the point of no return. Once we start copying things, there is
     517             :      * no turning back!
     518             :      */
     519          26 :     perform_rewind(filemap, source, chkptrec, chkpttli, chkptredo);
     520             : 
     521          24 :     if (showprogress)
     522           0 :         pg_log_info("syncing target data directory");
     523          24 :     sync_target_dir();
     524             : 
     525             :     /* Also update the standby configuration, if requested. */
     526          24 :     if (writerecoveryconf && !dry_run)
     527          10 :         WriteRecoveryConfig(conn, datadir_target,
     528             :                             GenerateRecoveryConfig(conn, NULL, NULL));
     529             : 
     530             :     /* don't need the source connection anymore */
     531          24 :     source->destroy(source);
     532          24 :     if (conn)
     533             :     {
     534          12 :         PQfinish(conn);
     535          12 :         conn = NULL;
     536             :     }
     537             : 
     538          24 :     pg_log_info("Done!");
     539             : 
     540          24 :     return 0;
     541             : }
     542             : 
     543             : /*
     544             :  * Perform the rewind.
     545             :  *
     546             :  * We have already collected all the information we need from the
     547             :  * target and the source.
     548             :  */
     549             : static void
     550          26 : perform_rewind(filemap_t *filemap, rewind_source *source,
     551             :                XLogRecPtr chkptrec,
     552             :                TimeLineID chkpttli,
     553             :                XLogRecPtr chkptredo)
     554             : {
     555             :     XLogRecPtr  endrec;
     556             :     TimeLineID  endtli;
     557             :     ControlFileData ControlFile_new;
     558             :     size_t      size;
     559             :     char       *buffer;
     560             : 
     561             :     /*
     562             :      * Execute the actions in the file map, fetching data from the source
     563             :      * system as needed.
     564             :      */
     565       29860 :     for (int i = 0; i < filemap->nentries; i++)
     566             :     {
     567       29836 :         file_entry_t *entry = filemap->entries[i];
     568             : 
     569             :         /*
     570             :          * If this is a relation file, copy the modified blocks.
     571             :          *
     572             :          * This is in addition to any other changes.
     573             :          */
     574       29836 :         if (entry->target_pages_to_overwrite.bitmapsize > 0)
     575             :         {
     576             :             datapagemap_iterator_t *iter;
     577             :             BlockNumber blkno;
     578             :             off_t       offset;
     579             : 
     580         812 :             iter = datapagemap_iterate(&entry->target_pages_to_overwrite);
     581        4100 :             while (datapagemap_next(iter, &blkno))
     582             :             {
     583        3288 :                 offset = blkno * BLCKSZ;
     584        3288 :                 source->queue_fetch_range(source, entry->path, offset, BLCKSZ);
     585             :             }
     586         812 :             pg_free(iter);
     587             :         }
     588             : 
     589       29836 :         switch (entry->action)
     590             :         {
     591       20032 :             case FILE_ACTION_NONE:
     592             :                 /* nothing else to do */
     593       20032 :                 break;
     594             : 
     595        8360 :             case FILE_ACTION_COPY:
     596        8360 :                 source->queue_fetch_file(source, entry->path, entry->source_size);
     597        8358 :                 break;
     598             : 
     599           8 :             case FILE_ACTION_TRUNCATE:
     600           8 :                 truncate_target_file(entry->path, entry->source_size);
     601           8 :                 break;
     602             : 
     603          10 :             case FILE_ACTION_COPY_TAIL:
     604          10 :                 source->queue_fetch_range(source, entry->path,
     605          10 :                                           entry->target_size,
     606          10 :                                           entry->source_size - entry->target_size);
     607          10 :                 break;
     608             : 
     609        1408 :             case FILE_ACTION_REMOVE:
     610        1408 :                 remove_target(entry);
     611        1408 :                 break;
     612             : 
     613          18 :             case FILE_ACTION_CREATE:
     614          18 :                 create_target(entry);
     615          18 :                 break;
     616             : 
     617           0 :             case FILE_ACTION_UNDECIDED:
     618           0 :                 pg_fatal("no action decided for file \"%s\"", entry->path);
     619             :                 break;
     620             :         }
     621       29834 :     }
     622             : 
     623             :     /* Complete any remaining range-fetches that we queued up above. */
     624          24 :     source->finish_fetch(source);
     625             : 
     626          24 :     close_target_file();
     627             : 
     628          24 :     progress_report(true);
     629             : 
     630             :     /*
     631             :      * Fetch the control file from the source last. This ensures that the
     632             :      * minRecoveryPoint is up-to-date.
     633             :      */
     634          24 :     buffer = source->fetch_file(source, "global/pg_control", &size);
     635          24 :     digestControlFile(&ControlFile_source_after, buffer, size);
     636          24 :     pg_free(buffer);
     637             : 
     638             :     /*
     639             :      * Sanity check: If the source is a local system, the control file should
     640             :      * not have changed since we started.
     641             :      *
     642             :      * XXX: We assume it hasn't been modified, but actually, what could go
     643             :      * wrong? The logic handles a libpq source that's modified concurrently,
     644             :      * why not a local datadir?
     645             :      */
     646          24 :     if (datadir_source &&
     647          12 :         memcmp(&ControlFile_source, &ControlFile_source_after,
     648             :                sizeof(ControlFileData)) != 0)
     649             :     {
     650           0 :         pg_fatal("source system was modified while pg_rewind was running");
     651             :     }
     652             : 
     653          24 :     if (showprogress)
     654           0 :         pg_log_info("creating backup label and updating control file");
     655             : 
     656             :     /*
     657             :      * Create a backup label file, to tell the target where to begin the WAL
     658             :      * replay. Normally, from the last common checkpoint between the source
     659             :      * and the target. But if the source is a standby server, it's possible
     660             :      * that the last common checkpoint is *after* the standby's restartpoint.
     661             :      * That implies that the source server has applied the checkpoint record,
     662             :      * but hasn't performed a corresponding restartpoint yet. Make sure we
     663             :      * start at the restartpoint's redo point in that case.
     664             :      *
     665             :      * Use the old version of the source's control file for this. The server
     666             :      * might have finished the restartpoint after we started copying files,
     667             :      * but we must begin from the redo point at the time that started copying.
     668             :      */
     669          24 :     if (ControlFile_source.checkPointCopy.redo < chkptredo)
     670             :     {
     671           4 :         chkptredo = ControlFile_source.checkPointCopy.redo;
     672           4 :         chkpttli = ControlFile_source.checkPointCopy.ThisTimeLineID;
     673           4 :         chkptrec = ControlFile_source.checkPoint;
     674             :     }
     675          24 :     createBackupLabel(chkptredo, chkpttli, chkptrec);
     676             : 
     677             :     /*
     678             :      * Update control file of target, to tell the target how far it must
     679             :      * replay the WAL (minRecoveryPoint).
     680             :      */
     681          24 :     if (connstr_source)
     682             :     {
     683             :         /*
     684             :          * The source is a live server. Like in an online backup, it's
     685             :          * important that we recover all the WAL that was generated while we
     686             :          * were copying files.
     687             :          */
     688          12 :         if (ControlFile_source_after.state == DB_IN_ARCHIVE_RECOVERY)
     689             :         {
     690             :             /*
     691             :              * Source is a standby server. We must replay to its
     692             :              * minRecoveryPoint.
     693             :              */
     694           2 :             endrec = ControlFile_source_after.minRecoveryPoint;
     695           2 :             endtli = ControlFile_source_after.minRecoveryPointTLI;
     696             :         }
     697             :         else
     698             :         {
     699             :             /*
     700             :              * Source is a production, non-standby, server. We must replay to
     701             :              * the last WAL insert location.
     702             :              */
     703          10 :             if (ControlFile_source_after.state != DB_IN_PRODUCTION)
     704           0 :                 pg_fatal("source system was in unexpected state at end of rewind");
     705             : 
     706          10 :             endrec = source->get_current_wal_insert_lsn(source);
     707          10 :             endtli = Max(ControlFile_source_after.checkPointCopy.ThisTimeLineID,
     708             :                          ControlFile_source_after.minRecoveryPointTLI);
     709             :         }
     710             :     }
     711             :     else
     712             :     {
     713             :         /*
     714             :          * Source is a local data directory. It should've shut down cleanly,
     715             :          * and we must replay to the latest shutdown checkpoint.
     716             :          */
     717          12 :         endrec = ControlFile_source_after.checkPoint;
     718          12 :         endtli = ControlFile_source_after.checkPointCopy.ThisTimeLineID;
     719             :     }
     720             : 
     721          24 :     memcpy(&ControlFile_new, &ControlFile_source_after, sizeof(ControlFileData));
     722          24 :     ControlFile_new.minRecoveryPoint = endrec;
     723          24 :     ControlFile_new.minRecoveryPointTLI = endtli;
     724          24 :     ControlFile_new.state = DB_IN_ARCHIVE_RECOVERY;
     725          24 :     if (!dry_run)
     726          22 :         update_controlfile(datadir_target, &ControlFile_new, do_sync);
     727          24 : }
     728             : 
     729             : static void
     730          32 : sanityChecks(void)
     731             : {
     732             :     /* TODO Check that there's no backup_label in either cluster */
     733             : 
     734             :     /* Check system_identifier match */
     735          32 :     if (ControlFile_target.system_identifier != ControlFile_source.system_identifier)
     736           0 :         pg_fatal("source and target clusters are from different systems");
     737             : 
     738             :     /* check version */
     739          32 :     if (ControlFile_target.pg_control_version != PG_CONTROL_VERSION ||
     740          32 :         ControlFile_source.pg_control_version != PG_CONTROL_VERSION ||
     741          32 :         ControlFile_target.catalog_version_no != CATALOG_VERSION_NO ||
     742          32 :         ControlFile_source.catalog_version_no != CATALOG_VERSION_NO)
     743             :     {
     744           0 :         pg_fatal("clusters are not compatible with this version of pg_rewind");
     745             :     }
     746             : 
     747             :     /*
     748             :      * Target cluster need to use checksums or hint bit wal-logging, this to
     749             :      * prevent from data corruption that could occur because of hint bits.
     750             :      */
     751          32 :     if (ControlFile_target.data_checksum_version != PG_DATA_CHECKSUM_VERSION &&
     752           0 :         !ControlFile_target.wal_log_hints)
     753             :     {
     754           0 :         pg_fatal("target server needs to use either data checksums or \"wal_log_hints = on\"");
     755             :     }
     756             : 
     757             :     /*
     758             :      * Target cluster better not be running. This doesn't guard against
     759             :      * someone starting the cluster concurrently. Also, this is probably more
     760             :      * strict than necessary; it's OK if the target node was not shut down
     761             :      * cleanly, as long as it isn't running at the moment.
     762             :      */
     763          32 :     if (ControlFile_target.state != DB_SHUTDOWNED &&
     764           4 :         ControlFile_target.state != DB_SHUTDOWNED_IN_RECOVERY)
     765           2 :         pg_fatal("target server must be shut down cleanly");
     766             : 
     767             :     /*
     768             :      * When the source is a data directory, also require that the source
     769             :      * server is shut down. There isn't any very strong reason for this
     770             :      * limitation, but better safe than sorry.
     771             :      */
     772          30 :     if (datadir_source &&
     773          18 :         ControlFile_source.state != DB_SHUTDOWNED &&
     774           4 :         ControlFile_source.state != DB_SHUTDOWNED_IN_RECOVERY)
     775           2 :         pg_fatal("source data directory must be shut down cleanly");
     776          28 : }
     777             : 
     778             : /*
     779             :  * Print a progress report based on the fetch_size and fetch_done variables.
     780             :  *
     781             :  * Progress report is written at maximum once per second, except that the
     782             :  * last progress report is always printed.
     783             :  *
     784             :  * If finished is set to true, this is the last progress report. The cursor
     785             :  * is moved to the next line.
     786             :  */
     787             : void
     788       98306 : progress_report(bool finished)
     789             : {
     790             :     static pg_time_t last_progress_report = 0;
     791             :     int         percent;
     792             :     char        fetch_done_str[32];
     793             :     char        fetch_size_str[32];
     794             :     pg_time_t   now;
     795             : 
     796       98306 :     if (!showprogress)
     797       98306 :         return;
     798             : 
     799           0 :     now = time(NULL);
     800           0 :     if (now == last_progress_report && !finished)
     801           0 :         return;                 /* Max once per second */
     802             : 
     803           0 :     last_progress_report = now;
     804           0 :     percent = fetch_size ? (int) ((fetch_done) * 100 / fetch_size) : 0;
     805             : 
     806             :     /*
     807             :      * Avoid overflowing past 100% or the full size. This may make the total
     808             :      * size number change as we approach the end of the backup (the estimate
     809             :      * will always be wrong if WAL is included), but that's better than having
     810             :      * the done column be bigger than the total.
     811             :      */
     812           0 :     if (percent > 100)
     813           0 :         percent = 100;
     814           0 :     if (fetch_done > fetch_size)
     815           0 :         fetch_size = fetch_done;
     816             : 
     817           0 :     snprintf(fetch_done_str, sizeof(fetch_done_str), UINT64_FORMAT,
     818             :              fetch_done / 1024);
     819           0 :     snprintf(fetch_size_str, sizeof(fetch_size_str), UINT64_FORMAT,
     820             :              fetch_size / 1024);
     821             : 
     822           0 :     fprintf(stderr, _("%*s/%s kB (%d%%) copied"),
     823           0 :             (int) strlen(fetch_size_str), fetch_done_str, fetch_size_str,
     824             :             percent);
     825             : 
     826             :     /*
     827             :      * Stay on the same line if reporting to a terminal and we're not done
     828             :      * yet.
     829             :      */
     830           0 :     fputc((!finished && isatty(fileno(stderr))) ? '\r' : '\n', stderr);
     831             : }
     832             : 
     833             : /*
     834             :  * Find minimum from two WAL locations assuming InvalidXLogRecPtr means
     835             :  * infinity as src/include/access/timeline.h states. This routine should
     836             :  * be used only when comparing WAL locations related to history files.
     837             :  */
     838             : static XLogRecPtr
     839          26 : MinXLogRecPtr(XLogRecPtr a, XLogRecPtr b)
     840             : {
     841          26 :     if (XLogRecPtrIsInvalid(a))
     842           2 :         return b;
     843          24 :     else if (XLogRecPtrIsInvalid(b))
     844          24 :         return a;
     845             :     else
     846           0 :         return Min(a, b);
     847             : }
     848             : 
     849             : /*
     850             :  * Retrieve timeline history for the source or target system.
     851             :  */
     852             : static TimeLineHistoryEntry *
     853          52 : getTimelineHistory(TimeLineID tli, bool is_source, int *nentries)
     854             : {
     855             :     TimeLineHistoryEntry *history;
     856             : 
     857             :     /*
     858             :      * Timeline 1 does not have a history file, so there is no need to check
     859             :      * and fake an entry with infinite start and end positions.
     860             :      */
     861          52 :     if (tli == 1)
     862             :     {
     863          24 :         history = (TimeLineHistoryEntry *) pg_malloc(sizeof(TimeLineHistoryEntry));
     864          24 :         history->tli = tli;
     865          24 :         history->begin = history->end = InvalidXLogRecPtr;
     866          24 :         *nentries = 1;
     867             :     }
     868             :     else
     869             :     {
     870             :         char        path[MAXPGPATH];
     871             :         char       *histfile;
     872             : 
     873          28 :         TLHistoryFilePath(path, tli);
     874             : 
     875             :         /* Get history file from appropriate source */
     876          28 :         if (is_source)
     877          24 :             histfile = source->fetch_file(source, path, NULL);
     878             :         else
     879           4 :             histfile = slurpFile(datadir_target, path, NULL);
     880             : 
     881          28 :         history = rewind_parseTimeLineHistory(histfile, tli, nentries);
     882          28 :         pg_free(histfile);
     883             :     }
     884             : 
     885             :     /* In debugging mode, print what we read */
     886          52 :     if (debug)
     887             :     {
     888             :         int         i;
     889             : 
     890          52 :         if (is_source)
     891          26 :             pg_log_debug("Source timeline history:");
     892             :         else
     893          26 :             pg_log_debug("Target timeline history:");
     894             : 
     895         134 :         for (i = 0; i < *nentries; i++)
     896             :         {
     897             :             TimeLineHistoryEntry *entry;
     898             : 
     899          82 :             entry = &history[i];
     900          82 :             pg_log_debug("%u: %X/%X - %X/%X", entry->tli,
     901             :                          LSN_FORMAT_ARGS(entry->begin),
     902             :                          LSN_FORMAT_ARGS(entry->end));
     903             :         }
     904             :     }
     905             : 
     906          52 :     return history;
     907             : }
     908             : 
     909             : /*
     910             :  * Determine the TLI of the last common timeline in the timeline history of
     911             :  * two clusters. *tliIndex is set to the index of last common timeline in
     912             :  * the arrays, and *recptr is set to the position where the timeline history
     913             :  * diverged (ie. the first WAL record that's not the same in both clusters).
     914             :  */
     915             : static void
     916          26 : findCommonAncestorTimeline(TimeLineHistoryEntry *a_history, int a_nentries,
     917             :                            TimeLineHistoryEntry *b_history, int b_nentries,
     918             :                            XLogRecPtr *recptr, int *tliIndex)
     919             : {
     920             :     int         i,
     921             :                 n;
     922             : 
     923             :     /*
     924             :      * Trace the history forward, until we hit the timeline diverge. It may
     925             :      * still be possible that the source and target nodes used the same
     926             :      * timeline number in their history but with different start position
     927             :      * depending on the history files that each node has fetched in previous
     928             :      * recovery processes. Hence check the start position of the new timeline
     929             :      * as well and move down by one extra timeline entry if they do not match.
     930             :      */
     931          26 :     n = Min(a_nentries, b_nentries);
     932          54 :     for (i = 0; i < n; i++)
     933             :     {
     934          28 :         if (a_history[i].tli != b_history[i].tli ||
     935          28 :             a_history[i].begin != b_history[i].begin)
     936             :             break;
     937             :     }
     938             : 
     939          26 :     if (i > 0)
     940             :     {
     941          26 :         i--;
     942          26 :         *recptr = MinXLogRecPtr(a_history[i].end, b_history[i].end);
     943          26 :         *tliIndex = i;
     944          26 :         return;
     945             :     }
     946             :     else
     947             :     {
     948           0 :         pg_fatal("could not find common ancestor of the source and target cluster's timelines");
     949             :     }
     950             : }
     951             : 
     952             : 
     953             : /*
     954             :  * Create a backup_label file that forces recovery to begin at the last common
     955             :  * checkpoint.
     956             :  */
     957             : static void
     958          24 : createBackupLabel(XLogRecPtr startpoint, TimeLineID starttli, XLogRecPtr checkpointloc)
     959             : {
     960             :     XLogSegNo   startsegno;
     961             :     time_t      stamp_time;
     962             :     char        strfbuf[128];
     963             :     char        xlogfilename[MAXFNAMELEN];
     964             :     struct tm  *tmp;
     965             :     char        buf[1000];
     966             :     int         len;
     967             : 
     968          24 :     XLByteToSeg(startpoint, startsegno, WalSegSz);
     969          24 :     XLogFileName(xlogfilename, starttli, startsegno, WalSegSz);
     970             : 
     971             :     /*
     972             :      * Construct backup label file
     973             :      */
     974          24 :     stamp_time = time(NULL);
     975          24 :     tmp = localtime(&stamp_time);
     976          24 :     strftime(strfbuf, sizeof(strfbuf), "%Y-%m-%d %H:%M:%S %Z", tmp);
     977             : 
     978          24 :     len = snprintf(buf, sizeof(buf),
     979             :                    "START WAL LOCATION: %X/%X (file %s)\n"
     980             :                    "CHECKPOINT LOCATION: %X/%X\n"
     981             :                    "BACKUP METHOD: pg_rewind\n"
     982             :                    "BACKUP FROM: standby\n"
     983             :                    "START TIME: %s\n",
     984             :     /* omit LABEL: line */
     985          24 :                    LSN_FORMAT_ARGS(startpoint), xlogfilename,
     986          24 :                    LSN_FORMAT_ARGS(checkpointloc),
     987             :                    strfbuf);
     988          24 :     if (len >= sizeof(buf))
     989           0 :         pg_fatal("backup label buffer too small");    /* shouldn't happen */
     990             : 
     991             :     /* TODO: move old file out of the way, if any. */
     992          24 :     open_target_file("backup_label", true); /* BACKUP_LABEL_FILE */
     993          24 :     write_target_range(buf, 0, len);
     994          24 :     close_target_file();
     995          24 : }
     996             : 
     997             : /*
     998             :  * Check CRC of control file
     999             :  */
    1000             : static void
    1001         108 : checkControlFile(ControlFileData *ControlFile)
    1002             : {
    1003             :     pg_crc32c   crc;
    1004             : 
    1005             :     /* Calculate CRC */
    1006         108 :     INIT_CRC32C(crc);
    1007         108 :     COMP_CRC32C(crc, (char *) ControlFile, offsetof(ControlFileData, crc));
    1008         108 :     FIN_CRC32C(crc);
    1009             : 
    1010             :     /* And simply compare it */
    1011         108 :     if (!EQ_CRC32C(crc, ControlFile->crc))
    1012           0 :         pg_fatal("unexpected control file CRC");
    1013         108 : }
    1014             : 
    1015             : /*
    1016             :  * Verify control file contents in the buffer 'content', and copy it to
    1017             :  * *ControlFile.
    1018             :  */
    1019             : static void
    1020         108 : digestControlFile(ControlFileData *ControlFile, const char *content,
    1021             :                   size_t size)
    1022             : {
    1023         108 :     if (size != PG_CONTROL_FILE_SIZE)
    1024           0 :         pg_fatal("unexpected control file size %d, expected %d",
    1025             :                  (int) size, PG_CONTROL_FILE_SIZE);
    1026             : 
    1027         108 :     memcpy(ControlFile, content, sizeof(ControlFileData));
    1028             : 
    1029             :     /* set and validate WalSegSz */
    1030         108 :     WalSegSz = ControlFile->xlog_seg_size;
    1031             : 
    1032         108 :     if (!IsValidWalSegSize(WalSegSz))
    1033             :     {
    1034           0 :         pg_log_error(ngettext("invalid WAL segment size in control file (%d byte)",
    1035             :                               "invalid WAL segment size in control file (%d bytes)",
    1036             :                               WalSegSz),
    1037             :                      WalSegSz);
    1038           0 :         pg_log_error_detail("The WAL segment size must be a power of two between 1 MB and 1 GB.");
    1039           0 :         exit(1);
    1040             :     }
    1041             : 
    1042             :     /* Additional checks on control file */
    1043         108 :     checkControlFile(ControlFile);
    1044         108 : }
    1045             : 
    1046             : /*
    1047             :  * Get value of GUC parameter restore_command from the target cluster.
    1048             :  *
    1049             :  * This uses a logic based on "postgres -C" to get the value from the
    1050             :  * cluster.
    1051             :  */
    1052             : static void
    1053          34 : getRestoreCommand(const char *argv0)
    1054             : {
    1055             :     int         rc;
    1056             :     char        postgres_exec_path[MAXPGPATH];
    1057             :     PQExpBuffer postgres_cmd;
    1058             : 
    1059          34 :     if (!restore_wal)
    1060          32 :         return;
    1061             : 
    1062             :     /* find postgres executable */
    1063           2 :     rc = find_other_exec(argv0, "postgres",
    1064             :                          PG_BACKEND_VERSIONSTR,
    1065             :                          postgres_exec_path);
    1066             : 
    1067           2 :     if (rc < 0)
    1068             :     {
    1069             :         char        full_path[MAXPGPATH];
    1070             : 
    1071           0 :         if (find_my_exec(argv0, full_path) < 0)
    1072           0 :             strlcpy(full_path, progname, sizeof(full_path));
    1073             : 
    1074           0 :         if (rc == -1)
    1075           0 :             pg_fatal("program \"%s\" is needed by %s but was not found in the same directory as \"%s\"",
    1076             :                      "postgres", progname, full_path);
    1077             :         else
    1078           0 :             pg_fatal("program \"%s\" was found by \"%s\" but was not the same version as %s",
    1079             :                      "postgres", full_path, progname);
    1080             :     }
    1081             : 
    1082             :     /*
    1083             :      * Build a command able to retrieve the value of GUC parameter
    1084             :      * restore_command, if set.
    1085             :      */
    1086           2 :     postgres_cmd = createPQExpBuffer();
    1087             : 
    1088             :     /* path to postgres, properly quoted */
    1089           2 :     appendShellString(postgres_cmd, postgres_exec_path);
    1090             : 
    1091             :     /* add -D switch, with properly quoted data directory */
    1092           2 :     appendPQExpBufferStr(postgres_cmd, " -D ");
    1093           2 :     appendShellString(postgres_cmd, datadir_target);
    1094             : 
    1095             :     /* add custom configuration file only if requested */
    1096           2 :     if (config_file != NULL)
    1097             :     {
    1098           2 :         appendPQExpBufferStr(postgres_cmd, " -c config_file=");
    1099           2 :         appendShellString(postgres_cmd, config_file);
    1100             :     }
    1101             : 
    1102             :     /* add -C switch, for restore_command */
    1103           2 :     appendPQExpBufferStr(postgres_cmd, " -C restore_command");
    1104             : 
    1105           2 :     restore_command = pipe_read_line(postgres_cmd->data);
    1106           2 :     if (restore_command == NULL)
    1107           0 :         pg_fatal("could not read \"restore_command\" from target cluster");
    1108             : 
    1109           2 :     (void) pg_strip_crlf(restore_command);
    1110             : 
    1111           2 :     if (strcmp(restore_command, "") == 0)
    1112           0 :         pg_fatal("\"restore_command\" is not set in the target cluster");
    1113             : 
    1114           2 :     pg_log_debug("using for rewind \"restore_command = \'%s\'\"",
    1115             :                  restore_command);
    1116             : 
    1117           2 :     destroyPQExpBuffer(postgres_cmd);
    1118             : }
    1119             : 
    1120             : 
    1121             : /*
    1122             :  * Ensure clean shutdown of target instance by launching single-user mode
    1123             :  * postgres to do crash recovery.
    1124             :  */
    1125             : static void
    1126          20 : ensureCleanShutdown(const char *argv0)
    1127             : {
    1128             :     int         ret;
    1129             :     char        exec_path[MAXPGPATH];
    1130             :     PQExpBuffer postgres_cmd;
    1131             : 
    1132             :     /* locate postgres binary */
    1133          20 :     if ((ret = find_other_exec(argv0, "postgres",
    1134             :                                PG_BACKEND_VERSIONSTR,
    1135             :                                exec_path)) < 0)
    1136             :     {
    1137             :         char        full_path[MAXPGPATH];
    1138             : 
    1139           0 :         if (find_my_exec(argv0, full_path) < 0)
    1140           0 :             strlcpy(full_path, progname, sizeof(full_path));
    1141             : 
    1142           0 :         if (ret == -1)
    1143           0 :             pg_fatal("program \"%s\" is needed by %s but was not found in the same directory as \"%s\"",
    1144             :                      "postgres", progname, full_path);
    1145             :         else
    1146           0 :             pg_fatal("program \"%s\" was found by \"%s\" but was not the same version as %s",
    1147             :                      "postgres", full_path, progname);
    1148             :     }
    1149             : 
    1150          20 :     pg_log_info("executing \"%s\" for target server to complete crash recovery",
    1151             :                 exec_path);
    1152             : 
    1153             :     /*
    1154             :      * Skip processing if requested, but only after ensuring presence of
    1155             :      * postgres.
    1156             :      */
    1157          20 :     if (dry_run)
    1158           0 :         return;
    1159             : 
    1160             :     /*
    1161             :      * Finally run postgres in single-user mode.  There is no need to use
    1162             :      * fsync here.  This makes the recovery faster, and the target data folder
    1163             :      * is synced at the end anyway.
    1164             :      */
    1165          20 :     postgres_cmd = createPQExpBuffer();
    1166             : 
    1167             :     /* path to postgres, properly quoted */
    1168          20 :     appendShellString(postgres_cmd, exec_path);
    1169             : 
    1170             :     /* add set of options with properly quoted data directory */
    1171          20 :     appendPQExpBufferStr(postgres_cmd, " --single -F -D ");
    1172          20 :     appendShellString(postgres_cmd, datadir_target);
    1173             : 
    1174             :     /* add custom configuration file only if requested */
    1175          20 :     if (config_file != NULL)
    1176             :     {
    1177          18 :         appendPQExpBufferStr(postgres_cmd, " -c config_file=");
    1178          18 :         appendShellString(postgres_cmd, config_file);
    1179             :     }
    1180             : 
    1181             :     /* finish with the database name, and a properly quoted redirection */
    1182          20 :     appendPQExpBufferStr(postgres_cmd, " template1 < ");
    1183          20 :     appendShellString(postgres_cmd, DEVNULL);
    1184             : 
    1185          20 :     fflush(NULL);
    1186          20 :     if (system(postgres_cmd->data) != 0)
    1187             :     {
    1188           2 :         pg_log_error("postgres single-user mode in target cluster failed");
    1189           2 :         pg_log_error_detail("Command was: %s", postgres_cmd->data);
    1190           2 :         exit(1);
    1191             :     }
    1192             : 
    1193          18 :     destroyPQExpBuffer(postgres_cmd);
    1194             : }
    1195             : 
    1196             : static void
    1197          34 : disconnect_atexit(void)
    1198             : {
    1199          34 :     if (conn != NULL)
    1200           0 :         PQfinish(conn);
    1201          34 : }

Generated by: LCOV version 1.14