LCOV - code coverage report
Current view: top level - src/bin/pg_upgrade - pg_upgrade.c (source / functions) Hit Total Coverage
Test: PostgreSQL 17devel Lines: 247 289 85.5 %
Date: 2024-02-28 06:10:54 Functions: 12 12 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*
       2             :  *  pg_upgrade.c
       3             :  *
       4             :  *  main source file
       5             :  *
       6             :  *  Copyright (c) 2010-2024, PostgreSQL Global Development Group
       7             :  *  src/bin/pg_upgrade/pg_upgrade.c
       8             :  */
       9             : 
      10             : /*
      11             :  *  To simplify the upgrade process, we force certain system values to be
      12             :  *  identical between old and new clusters:
      13             :  *
      14             :  *  We control all assignments of pg_class.oid (and relfilenode) so toast
      15             :  *  oids are the same between old and new clusters.  This is important
      16             :  *  because toast oids are stored as toast pointers in user tables.
      17             :  *
      18             :  *  While pg_class.oid and pg_class.relfilenode are initially the same in a
      19             :  *  cluster, they can diverge due to CLUSTER, REINDEX, or VACUUM FULL. We
      20             :  *  control assignments of pg_class.relfilenode because we want the filenames
      21             :  *  to match between the old and new cluster.
      22             :  *
      23             :  *  We control assignment of pg_tablespace.oid because we want the oid to match
      24             :  *  between the old and new cluster.
      25             :  *
      26             :  *  We control all assignments of pg_type.oid because these oids are stored
      27             :  *  in user composite type values.
      28             :  *
      29             :  *  We control all assignments of pg_enum.oid because these oids are stored
      30             :  *  in user tables as enum values.
      31             :  *
      32             :  *  We control all assignments of pg_authid.oid for historical reasons (the
      33             :  *  oids used to be stored in pg_largeobject_metadata, which is now copied via
      34             :  *  SQL commands), that might change at some point in the future.
      35             :  */
      36             : 
      37             : 
      38             : 
      39             : #include "postgres_fe.h"
      40             : 
      41             : #include <time.h>
      42             : 
      43             : #ifdef HAVE_LANGINFO_H
      44             : #include <langinfo.h>
      45             : #endif
      46             : 
      47             : #include "catalog/pg_class_d.h"
      48             : #include "common/file_perm.h"
      49             : #include "common/logging.h"
      50             : #include "common/restricted_token.h"
      51             : #include "fe_utils/string_utils.h"
      52             : #include "pg_upgrade.h"
      53             : 
      54             : static void set_locale_and_encoding(void);
      55             : static void prepare_new_cluster(void);
      56             : static void prepare_new_globals(void);
      57             : static void create_new_objects(void);
      58             : static void copy_xact_xlog_xid(void);
      59             : static void set_frozenxids(bool minmxid_only);
      60             : static void make_outputdirs(char *pgdata);
      61             : static void setup(char *argv0, bool *live_check);
      62             : static void create_logical_replication_slots(void);
      63             : 
      64             : ClusterInfo old_cluster,
      65             :             new_cluster;
      66             : OSInfo      os_info;
      67             : 
      68             : char       *output_files[] = {
      69             :     SERVER_LOG_FILE,
      70             : #ifdef WIN32
      71             :     /* unique file for pg_ctl start */
      72             :     SERVER_START_LOG_FILE,
      73             : #endif
      74             :     UTILITY_LOG_FILE,
      75             :     INTERNAL_LOG_FILE,
      76             :     NULL
      77             : };
      78             : 
      79             : 
      80             : int
      81          26 : main(int argc, char **argv)
      82             : {
      83          26 :     char       *deletion_script_file_name = NULL;
      84          26 :     bool        live_check = false;
      85             : 
      86             :     /*
      87             :      * pg_upgrade doesn't currently use common/logging.c, but initialize it
      88             :      * anyway because we might call common code that does.
      89             :      */
      90          26 :     pg_logging_init(argv[0]);
      91          26 :     set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_upgrade"));
      92             : 
      93             :     /* Set default restrictive mask until new cluster permissions are read */
      94          26 :     umask(PG_MODE_MASK_OWNER);
      95             : 
      96          26 :     parseCommandLine(argc, argv);
      97             : 
      98          20 :     get_restricted_token();
      99             : 
     100          20 :     adjust_data_dir(&old_cluster);
     101          20 :     adjust_data_dir(&new_cluster);
     102             : 
     103             :     /*
     104             :      * Set mask based on PGDATA permissions, needed for the creation of the
     105             :      * output directories with correct permissions.
     106             :      */
     107          20 :     if (!GetDataDirectoryCreatePerm(new_cluster.pgdata))
     108           0 :         pg_fatal("could not read permissions of directory \"%s\": %s",
     109           0 :                  new_cluster.pgdata, strerror(errno));
     110             : 
     111          20 :     umask(pg_mode_mask);
     112             : 
     113             :     /*
     114             :      * This needs to happen after adjusting the data directory of the new
     115             :      * cluster in adjust_data_dir().
     116             :      */
     117          20 :     make_outputdirs(new_cluster.pgdata);
     118             : 
     119          20 :     setup(argv[0], &live_check);
     120             : 
     121          18 :     output_check_banner(live_check);
     122             : 
     123          18 :     check_cluster_versions();
     124             : 
     125          18 :     get_sock_dir(&old_cluster, live_check);
     126          18 :     get_sock_dir(&new_cluster, false);
     127             : 
     128          18 :     check_cluster_compatibility(live_check);
     129             : 
     130          18 :     check_and_dump_old_cluster(live_check);
     131             : 
     132             : 
     133             :     /* -- NEW -- */
     134          12 :     start_postmaster(&new_cluster, true);
     135             : 
     136          12 :     check_new_cluster();
     137           8 :     report_clusters_compatible();
     138             : 
     139           6 :     pg_log(PG_REPORT,
     140             :            "\n"
     141             :            "Performing Upgrade\n"
     142             :            "------------------");
     143             : 
     144           6 :     set_locale_and_encoding();
     145             : 
     146           6 :     prepare_new_cluster();
     147             : 
     148           6 :     stop_postmaster(false);
     149             : 
     150             :     /*
     151             :      * Destructive Changes to New Cluster
     152             :      */
     153             : 
     154           6 :     copy_xact_xlog_xid();
     155             : 
     156             :     /* New now using xids of the old system */
     157             : 
     158             :     /* -- NEW -- */
     159           6 :     start_postmaster(&new_cluster, true);
     160             : 
     161           6 :     prepare_new_globals();
     162             : 
     163           6 :     create_new_objects();
     164             : 
     165           6 :     stop_postmaster(false);
     166             : 
     167             :     /*
     168             :      * Most failures happen in create_new_objects(), which has completed at
     169             :      * this point.  We do this here because it is just before linking, which
     170             :      * will link the old and new cluster data files, preventing the old
     171             :      * cluster from being safely started once the new cluster is started.
     172             :      */
     173           6 :     if (user_opts.transfer_mode == TRANSFER_MODE_LINK)
     174           0 :         disable_old_cluster();
     175             : 
     176           6 :     transfer_all_new_tablespaces(&old_cluster.dbarr, &new_cluster.dbarr,
     177             :                                  old_cluster.pgdata, new_cluster.pgdata);
     178             : 
     179             :     /*
     180             :      * Assuming OIDs are only used in system tables, there is no need to
     181             :      * restore the OID counter because we have not transferred any OIDs from
     182             :      * the old system, but we do it anyway just in case.  We do it late here
     183             :      * because there is no need to have the schema load use new oids.
     184             :      */
     185           6 :     prep_status("Setting next OID for new cluster");
     186           6 :     exec_prog(UTILITY_LOG_FILE, NULL, true, true,
     187             :               "\"%s/pg_resetwal\" -o %u \"%s\"",
     188             :               new_cluster.bindir, old_cluster.controldata.chkpnt_nxtoid,
     189             :               new_cluster.pgdata);
     190           6 :     check_ok();
     191             : 
     192             :     /*
     193             :      * Migrate the logical slots to the new cluster.  Note that we need to do
     194             :      * this after resetting WAL because otherwise the required WAL would be
     195             :      * removed and slots would become unusable.  There is a possibility that
     196             :      * background processes might generate some WAL before we could create the
     197             :      * slots in the new cluster but we can ignore that WAL as that won't be
     198             :      * required downstream.
     199             :      */
     200           6 :     if (count_old_cluster_logical_slots())
     201             :     {
     202           2 :         start_postmaster(&new_cluster, true);
     203           2 :         create_logical_replication_slots();
     204           2 :         stop_postmaster(false);
     205             :     }
     206             : 
     207           6 :     if (user_opts.do_sync)
     208             :     {
     209           0 :         prep_status("Sync data directory to disk");
     210           0 :         exec_prog(UTILITY_LOG_FILE, NULL, true, true,
     211             :                   "\"%s/initdb\" --sync-only \"%s\" --sync-method %s",
     212             :                   new_cluster.bindir,
     213             :                   new_cluster.pgdata,
     214             :                   user_opts.sync_method);
     215           0 :         check_ok();
     216             :     }
     217             : 
     218           6 :     create_script_for_old_cluster_deletion(&deletion_script_file_name);
     219             : 
     220           6 :     issue_warnings_and_set_wal_level();
     221             : 
     222           6 :     pg_log(PG_REPORT,
     223             :            "\n"
     224             :            "Upgrade Complete\n"
     225             :            "----------------");
     226             : 
     227           6 :     output_completion_banner(deletion_script_file_name);
     228             : 
     229           6 :     pg_free(deletion_script_file_name);
     230             : 
     231           6 :     cleanup_output_dirs();
     232             : 
     233           6 :     return 0;
     234             : }
     235             : 
     236             : /*
     237             :  * Create and assign proper permissions to the set of output directories
     238             :  * used to store any data generated internally, filling in log_opts in
     239             :  * the process.
     240             :  */
     241             : static void
     242          20 : make_outputdirs(char *pgdata)
     243             : {
     244             :     FILE       *fp;
     245             :     char      **filename;
     246          20 :     time_t      run_time = time(NULL);
     247             :     char        filename_path[MAXPGPATH];
     248             :     char        timebuf[128];
     249             :     struct timeval time;
     250             :     time_t      tt;
     251             :     int         len;
     252             : 
     253          20 :     log_opts.rootdir = (char *) pg_malloc0(MAXPGPATH);
     254          20 :     len = snprintf(log_opts.rootdir, MAXPGPATH, "%s/%s", pgdata, BASE_OUTPUTDIR);
     255          20 :     if (len >= MAXPGPATH)
     256           0 :         pg_fatal("directory path for new cluster is too long");
     257             : 
     258             :     /* BASE_OUTPUTDIR/$timestamp/ */
     259          20 :     gettimeofday(&time, NULL);
     260          20 :     tt = (time_t) time.tv_sec;
     261          20 :     strftime(timebuf, sizeof(timebuf), "%Y%m%dT%H%M%S", localtime(&tt));
     262             :     /* append milliseconds */
     263          20 :     snprintf(timebuf + strlen(timebuf), sizeof(timebuf) - strlen(timebuf),
     264          20 :              ".%03d", (int) (time.tv_usec / 1000));
     265          20 :     log_opts.basedir = (char *) pg_malloc0(MAXPGPATH);
     266          20 :     len = snprintf(log_opts.basedir, MAXPGPATH, "%s/%s", log_opts.rootdir,
     267             :                    timebuf);
     268          20 :     if (len >= MAXPGPATH)
     269           0 :         pg_fatal("directory path for new cluster is too long");
     270             : 
     271             :     /* BASE_OUTPUTDIR/$timestamp/dump/ */
     272          20 :     log_opts.dumpdir = (char *) pg_malloc0(MAXPGPATH);
     273          20 :     len = snprintf(log_opts.dumpdir, MAXPGPATH, "%s/%s/%s", log_opts.rootdir,
     274             :                    timebuf, DUMP_OUTPUTDIR);
     275          20 :     if (len >= MAXPGPATH)
     276           0 :         pg_fatal("directory path for new cluster is too long");
     277             : 
     278             :     /* BASE_OUTPUTDIR/$timestamp/log/ */
     279          20 :     log_opts.logdir = (char *) pg_malloc0(MAXPGPATH);
     280          20 :     len = snprintf(log_opts.logdir, MAXPGPATH, "%s/%s/%s", log_opts.rootdir,
     281             :                    timebuf, LOG_OUTPUTDIR);
     282          20 :     if (len >= MAXPGPATH)
     283           0 :         pg_fatal("directory path for new cluster is too long");
     284             : 
     285             :     /*
     286             :      * Ignore the error case where the root path exists, as it is kept the
     287             :      * same across runs.
     288             :      */
     289          20 :     if (mkdir(log_opts.rootdir, pg_dir_create_mode) < 0 && errno != EEXIST)
     290           0 :         pg_fatal("could not create directory \"%s\": %m", log_opts.rootdir);
     291          20 :     if (mkdir(log_opts.basedir, pg_dir_create_mode) < 0)
     292           0 :         pg_fatal("could not create directory \"%s\": %m", log_opts.basedir);
     293          20 :     if (mkdir(log_opts.dumpdir, pg_dir_create_mode) < 0)
     294           0 :         pg_fatal("could not create directory \"%s\": %m", log_opts.dumpdir);
     295          20 :     if (mkdir(log_opts.logdir, pg_dir_create_mode) < 0)
     296           0 :         pg_fatal("could not create directory \"%s\": %m", log_opts.logdir);
     297             : 
     298          20 :     len = snprintf(filename_path, sizeof(filename_path), "%s/%s",
     299             :                    log_opts.logdir, INTERNAL_LOG_FILE);
     300          20 :     if (len >= sizeof(filename_path))
     301           0 :         pg_fatal("directory path for new cluster is too long");
     302             : 
     303          20 :     if ((log_opts.internal = fopen_priv(filename_path, "a")) == NULL)
     304           0 :         pg_fatal("could not open log file \"%s\": %m", filename_path);
     305             : 
     306             :     /* label start of upgrade in logfiles */
     307          80 :     for (filename = output_files; *filename != NULL; filename++)
     308             :     {
     309          60 :         len = snprintf(filename_path, sizeof(filename_path), "%s/%s",
     310             :                        log_opts.logdir, *filename);
     311          60 :         if (len >= sizeof(filename_path))
     312           0 :             pg_fatal("directory path for new cluster is too long");
     313          60 :         if ((fp = fopen_priv(filename_path, "a")) == NULL)
     314           0 :             pg_fatal("could not write to log file \"%s\": %m", filename_path);
     315             : 
     316          60 :         fprintf(fp,
     317             :                 "-----------------------------------------------------------------\n"
     318             :                 "  pg_upgrade run on %s"
     319             :                 "-----------------------------------------------------------------\n\n",
     320             :                 ctime(&run_time));
     321          60 :         fclose(fp);
     322             :     }
     323          20 : }
     324             : 
     325             : 
     326             : static void
     327          20 : setup(char *argv0, bool *live_check)
     328             : {
     329             :     /*
     330             :      * make sure the user has a clean environment, otherwise, we may confuse
     331             :      * libpq when we connect to one (or both) of the servers.
     332             :      */
     333          20 :     check_pghost_envvar();
     334             : 
     335             :     /*
     336             :      * In case the user hasn't specified the directory for the new binaries
     337             :      * with -B, default to using the path of the currently executed pg_upgrade
     338             :      * binary.
     339             :      */
     340          20 :     if (!new_cluster.bindir)
     341             :     {
     342             :         char        exec_path[MAXPGPATH];
     343             : 
     344           0 :         if (find_my_exec(argv0, exec_path) < 0)
     345           0 :             pg_fatal("%s: could not find own program executable", argv0);
     346             :         /* Trim off program name and keep just path */
     347           0 :         *last_dir_separator(exec_path) = '\0';
     348           0 :         canonicalize_path(exec_path);
     349           0 :         new_cluster.bindir = pg_strdup(exec_path);
     350             :     }
     351             : 
     352          20 :     verify_directories();
     353             : 
     354             :     /* no postmasters should be running, except for a live check */
     355          18 :     if (pid_lock_file_exists(old_cluster.pgdata))
     356             :     {
     357             :         /*
     358             :          * If we have a postmaster.pid file, try to start the server.  If it
     359             :          * starts, the pid file was stale, so stop the server.  If it doesn't
     360             :          * start, assume the server is running.  If the pid file is left over
     361             :          * from a server crash, this also allows any committed transactions
     362             :          * stored in the WAL to be replayed so they are not lost, because WAL
     363             :          * files are not transferred from old to new servers.  We later check
     364             :          * for a clean shutdown.
     365             :          */
     366           0 :         if (start_postmaster(&old_cluster, false))
     367           0 :             stop_postmaster(false);
     368             :         else
     369             :         {
     370           0 :             if (!user_opts.check)
     371           0 :                 pg_fatal("There seems to be a postmaster servicing the old cluster.\n"
     372             :                          "Please shutdown that postmaster and try again.");
     373             :             else
     374           0 :                 *live_check = true;
     375             :         }
     376             :     }
     377             : 
     378             :     /* same goes for the new postmaster */
     379          18 :     if (pid_lock_file_exists(new_cluster.pgdata))
     380             :     {
     381           0 :         if (start_postmaster(&new_cluster, false))
     382           0 :             stop_postmaster(false);
     383             :         else
     384           0 :             pg_fatal("There seems to be a postmaster servicing the new cluster.\n"
     385             :                      "Please shutdown that postmaster and try again.");
     386             :     }
     387          18 : }
     388             : 
     389             : 
     390             : /*
     391             :  * Copy locale and encoding information into the new cluster's template0.
     392             :  *
     393             :  * We need to copy the encoding, datlocprovider, datcollate, datctype, and
     394             :  * daticulocale. We don't need datcollversion because that's never set for
     395             :  * template0.
     396             :  */
     397             : static void
     398           6 : set_locale_and_encoding(void)
     399             : {
     400             :     PGconn     *conn_new_template1;
     401             :     char       *datcollate_literal;
     402             :     char       *datctype_literal;
     403           6 :     char       *daticulocale_literal = NULL;
     404           6 :     DbLocaleInfo *locale = old_cluster.template0;
     405             : 
     406           6 :     prep_status("Setting locale and encoding for new cluster");
     407             : 
     408             :     /* escape literals with respect to new cluster */
     409           6 :     conn_new_template1 = connectToServer(&new_cluster, "template1");
     410             : 
     411           6 :     datcollate_literal = PQescapeLiteral(conn_new_template1,
     412           6 :                                          locale->db_collate,
     413           6 :                                          strlen(locale->db_collate));
     414           6 :     datctype_literal = PQescapeLiteral(conn_new_template1,
     415           6 :                                        locale->db_ctype,
     416           6 :                                        strlen(locale->db_ctype));
     417           6 :     if (locale->db_iculocale)
     418           2 :         daticulocale_literal = PQescapeLiteral(conn_new_template1,
     419           2 :                                                locale->db_iculocale,
     420           2 :                                                strlen(locale->db_iculocale));
     421             :     else
     422           4 :         daticulocale_literal = pg_strdup("NULL");
     423             : 
     424             :     /* update template0 in new cluster */
     425           6 :     if (GET_MAJOR_VERSION(new_cluster.major_version) >= 1500)
     426           6 :         PQclear(executeQueryOrDie(conn_new_template1,
     427             :                                   "UPDATE pg_catalog.pg_database "
     428             :                                   "  SET encoding = %d, "
     429             :                                   "      datlocprovider = '%c', "
     430             :                                   "      datcollate = %s, "
     431             :                                   "      datctype = %s, "
     432             :                                   "      daticulocale = %s "
     433             :                                   "  WHERE datname = 'template0' ",
     434             :                                   locale->db_encoding,
     435           6 :                                   locale->db_collprovider,
     436             :                                   datcollate_literal,
     437             :                                   datctype_literal,
     438             :                                   daticulocale_literal));
     439             :     else
     440           0 :         PQclear(executeQueryOrDie(conn_new_template1,
     441             :                                   "UPDATE pg_catalog.pg_database "
     442             :                                   "  SET encoding = %d, "
     443             :                                   "      datcollate = %s, "
     444             :                                   "      datctype = %s "
     445             :                                   "  WHERE datname = 'template0' ",
     446             :                                   locale->db_encoding,
     447             :                                   datcollate_literal,
     448             :                                   datctype_literal));
     449             : 
     450           6 :     PQfreemem(datcollate_literal);
     451           6 :     PQfreemem(datctype_literal);
     452           6 :     PQfreemem(daticulocale_literal);
     453             : 
     454           6 :     PQfinish(conn_new_template1);
     455             : 
     456           6 :     check_ok();
     457           6 : }
     458             : 
     459             : 
     460             : static void
     461           6 : prepare_new_cluster(void)
     462             : {
     463             :     /*
     464             :      * It would make more sense to freeze after loading the schema, but that
     465             :      * would cause us to lose the frozenxids restored by the load. We use
     466             :      * --analyze so autovacuum doesn't update statistics later
     467             :      */
     468           6 :     prep_status("Analyzing all rows in the new cluster");
     469           6 :     exec_prog(UTILITY_LOG_FILE, NULL, true, true,
     470             :               "\"%s/vacuumdb\" %s --all --analyze %s",
     471             :               new_cluster.bindir, cluster_conn_opts(&new_cluster),
     472           6 :               log_opts.verbose ? "--verbose" : "");
     473           6 :     check_ok();
     474             : 
     475             :     /*
     476             :      * We do freeze after analyze so pg_statistic is also frozen. template0 is
     477             :      * not frozen here, but data rows were frozen by initdb, and we set its
     478             :      * datfrozenxid, relfrozenxids, and relminmxid later to match the new xid
     479             :      * counter later.
     480             :      */
     481           6 :     prep_status("Freezing all rows in the new cluster");
     482           6 :     exec_prog(UTILITY_LOG_FILE, NULL, true, true,
     483             :               "\"%s/vacuumdb\" %s --all --freeze %s",
     484             :               new_cluster.bindir, cluster_conn_opts(&new_cluster),
     485           6 :               log_opts.verbose ? "--verbose" : "");
     486           6 :     check_ok();
     487           6 : }
     488             : 
     489             : 
     490             : static void
     491           6 : prepare_new_globals(void)
     492             : {
     493             :     /*
     494             :      * Before we restore anything, set frozenxids of initdb-created tables.
     495             :      */
     496           6 :     set_frozenxids(false);
     497             : 
     498             :     /*
     499             :      * Now restore global objects (roles and tablespaces).
     500             :      */
     501           6 :     prep_status("Restoring global objects in the new cluster");
     502             : 
     503           6 :     exec_prog(UTILITY_LOG_FILE, NULL, true, true,
     504             :               "\"%s/psql\" " EXEC_PSQL_ARGS " %s -f \"%s/%s\"",
     505             :               new_cluster.bindir, cluster_conn_opts(&new_cluster),
     506             :               log_opts.dumpdir,
     507             :               GLOBALS_DUMP_FILE);
     508           6 :     check_ok();
     509           6 : }
     510             : 
     511             : 
     512             : static void
     513           6 : create_new_objects(void)
     514             : {
     515             :     int         dbnum;
     516             : 
     517           6 :     prep_status_progress("Restoring database schemas in the new cluster");
     518             : 
     519             :     /*
     520             :      * We cannot process the template1 database concurrently with others,
     521             :      * because when it's transiently dropped, connection attempts would fail.
     522             :      * So handle it in a separate non-parallelized pass.
     523             :      */
     524           6 :     for (dbnum = 0; dbnum < old_cluster.dbarr.ndbs; dbnum++)
     525             :     {
     526             :         char        sql_file_name[MAXPGPATH],
     527             :                     log_file_name[MAXPGPATH];
     528           6 :         DbInfo     *old_db = &old_cluster.dbarr.dbs[dbnum];
     529             :         const char *create_opts;
     530             : 
     531             :         /* Process only template1 in this pass */
     532           6 :         if (strcmp(old_db->db_name, "template1") != 0)
     533           0 :             continue;
     534             : 
     535           6 :         pg_log(PG_STATUS, "%s", old_db->db_name);
     536           6 :         snprintf(sql_file_name, sizeof(sql_file_name), DB_DUMP_FILE_MASK, old_db->db_oid);
     537           6 :         snprintf(log_file_name, sizeof(log_file_name), DB_DUMP_LOG_FILE_MASK, old_db->db_oid);
     538             : 
     539             :         /*
     540             :          * template1 database will already exist in the target installation,
     541             :          * so tell pg_restore to drop and recreate it; otherwise we would fail
     542             :          * to propagate its database-level properties.
     543             :          */
     544           6 :         create_opts = "--clean --create";
     545             : 
     546           6 :         exec_prog(log_file_name,
     547             :                   NULL,
     548             :                   true,
     549             :                   true,
     550             :                   "\"%s/pg_restore\" %s %s --exit-on-error --verbose "
     551             :                   "--dbname postgres \"%s/%s\"",
     552             :                   new_cluster.bindir,
     553             :                   cluster_conn_opts(&new_cluster),
     554             :                   create_opts,
     555             :                   log_opts.dumpdir,
     556             :                   sql_file_name);
     557             : 
     558           6 :         break;                  /* done once we've processed template1 */
     559             :     }
     560             : 
     561          26 :     for (dbnum = 0; dbnum < old_cluster.dbarr.ndbs; dbnum++)
     562             :     {
     563             :         char        sql_file_name[MAXPGPATH],
     564             :                     log_file_name[MAXPGPATH];
     565          20 :         DbInfo     *old_db = &old_cluster.dbarr.dbs[dbnum];
     566             :         const char *create_opts;
     567             : 
     568             :         /* Skip template1 in this pass */
     569          20 :         if (strcmp(old_db->db_name, "template1") == 0)
     570           6 :             continue;
     571             : 
     572          14 :         pg_log(PG_STATUS, "%s", old_db->db_name);
     573          14 :         snprintf(sql_file_name, sizeof(sql_file_name), DB_DUMP_FILE_MASK, old_db->db_oid);
     574          14 :         snprintf(log_file_name, sizeof(log_file_name), DB_DUMP_LOG_FILE_MASK, old_db->db_oid);
     575             : 
     576             :         /*
     577             :          * postgres database will already exist in the target installation, so
     578             :          * tell pg_restore to drop and recreate it; otherwise we would fail to
     579             :          * propagate its database-level properties.
     580             :          */
     581          14 :         if (strcmp(old_db->db_name, "postgres") == 0)
     582           6 :             create_opts = "--clean --create";
     583             :         else
     584           8 :             create_opts = "--create";
     585             : 
     586          14 :         parallel_exec_prog(log_file_name,
     587             :                            NULL,
     588             :                            "\"%s/pg_restore\" %s %s --exit-on-error --verbose "
     589             :                            "--dbname template1 \"%s/%s\"",
     590             :                            new_cluster.bindir,
     591             :                            cluster_conn_opts(&new_cluster),
     592             :                            create_opts,
     593             :                            log_opts.dumpdir,
     594             :                            sql_file_name);
     595             :     }
     596             : 
     597             :     /* reap all children */
     598           6 :     while (reap_child(true) == true)
     599             :         ;
     600             : 
     601           6 :     end_progress_output();
     602           6 :     check_ok();
     603             : 
     604             :     /*
     605             :      * We don't have minmxids for databases or relations in pre-9.3 clusters,
     606             :      * so set those after we have restored the schema.
     607             :      */
     608           6 :     if (GET_MAJOR_VERSION(old_cluster.major_version) <= 902)
     609           0 :         set_frozenxids(true);
     610             : 
     611             :     /* update new_cluster info now that we have objects in the databases */
     612           6 :     get_db_rel_and_slot_infos(&new_cluster, false);
     613           6 : }
     614             : 
     615             : /*
     616             :  * Delete the given subdirectory contents from the new cluster
     617             :  */
     618             : static void
     619          18 : remove_new_subdir(const char *subdir, bool rmtopdir)
     620             : {
     621             :     char        new_path[MAXPGPATH];
     622             : 
     623          18 :     prep_status("Deleting files from new %s", subdir);
     624             : 
     625          18 :     snprintf(new_path, sizeof(new_path), "%s/%s", new_cluster.pgdata, subdir);
     626          18 :     if (!rmtree(new_path, rmtopdir))
     627           0 :         pg_fatal("could not delete directory \"%s\"", new_path);
     628             : 
     629          18 :     check_ok();
     630          18 : }
     631             : 
     632             : /*
     633             :  * Copy the files from the old cluster into it
     634             :  */
     635             : static void
     636          18 : copy_subdir_files(const char *old_subdir, const char *new_subdir)
     637             : {
     638             :     char        old_path[MAXPGPATH];
     639             :     char        new_path[MAXPGPATH];
     640             : 
     641          18 :     remove_new_subdir(new_subdir, true);
     642             : 
     643          18 :     snprintf(old_path, sizeof(old_path), "%s/%s", old_cluster.pgdata, old_subdir);
     644          18 :     snprintf(new_path, sizeof(new_path), "%s/%s", new_cluster.pgdata, new_subdir);
     645             : 
     646          18 :     prep_status("Copying old %s to new server", old_subdir);
     647             : 
     648          18 :     exec_prog(UTILITY_LOG_FILE, NULL, true, true,
     649             : #ifndef WIN32
     650             :               "cp -Rf \"%s\" \"%s\"",
     651             : #else
     652             :     /* flags: everything, no confirm, quiet, overwrite read-only */
     653             :               "xcopy /e /y /q /r \"%s\" \"%s\\\"",
     654             : #endif
     655             :               old_path, new_path);
     656             : 
     657          18 :     check_ok();
     658          18 : }
     659             : 
     660             : static void
     661           6 : copy_xact_xlog_xid(void)
     662             : {
     663             :     /*
     664             :      * Copy old commit logs to new data dir. pg_clog has been renamed to
     665             :      * pg_xact in post-10 clusters.
     666             :      */
     667           6 :     copy_subdir_files(GET_MAJOR_VERSION(old_cluster.major_version) <= 906 ?
     668             :                       "pg_clog" : "pg_xact",
     669           6 :                       GET_MAJOR_VERSION(new_cluster.major_version) <= 906 ?
     670             :                       "pg_clog" : "pg_xact");
     671             : 
     672           6 :     prep_status("Setting oldest XID for new cluster");
     673           6 :     exec_prog(UTILITY_LOG_FILE, NULL, true, true,
     674             :               "\"%s/pg_resetwal\" -f -u %u \"%s\"",
     675             :               new_cluster.bindir, old_cluster.controldata.chkpnt_oldstxid,
     676             :               new_cluster.pgdata);
     677           6 :     check_ok();
     678             : 
     679             :     /* set the next transaction id and epoch of the new cluster */
     680           6 :     prep_status("Setting next transaction ID and epoch for new cluster");
     681           6 :     exec_prog(UTILITY_LOG_FILE, NULL, true, true,
     682             :               "\"%s/pg_resetwal\" -f -x %u \"%s\"",
     683             :               new_cluster.bindir, old_cluster.controldata.chkpnt_nxtxid,
     684             :               new_cluster.pgdata);
     685           6 :     exec_prog(UTILITY_LOG_FILE, NULL, true, true,
     686             :               "\"%s/pg_resetwal\" -f -e %u \"%s\"",
     687             :               new_cluster.bindir, old_cluster.controldata.chkpnt_nxtepoch,
     688             :               new_cluster.pgdata);
     689             :     /* must reset commit timestamp limits also */
     690           6 :     exec_prog(UTILITY_LOG_FILE, NULL, true, true,
     691             :               "\"%s/pg_resetwal\" -f -c %u,%u \"%s\"",
     692             :               new_cluster.bindir,
     693             :               old_cluster.controldata.chkpnt_nxtxid,
     694             :               old_cluster.controldata.chkpnt_nxtxid,
     695             :               new_cluster.pgdata);
     696           6 :     check_ok();
     697             : 
     698             :     /*
     699             :      * If the old server is before the MULTIXACT_FORMATCHANGE_CAT_VER change
     700             :      * (see pg_upgrade.h) and the new server is after, then we don't copy
     701             :      * pg_multixact files, but we need to reset pg_control so that the new
     702             :      * server doesn't attempt to read multis older than the cutoff value.
     703             :      */
     704           6 :     if (old_cluster.controldata.cat_ver >= MULTIXACT_FORMATCHANGE_CAT_VER &&
     705           6 :         new_cluster.controldata.cat_ver >= MULTIXACT_FORMATCHANGE_CAT_VER)
     706             :     {
     707           6 :         copy_subdir_files("pg_multixact/offsets", "pg_multixact/offsets");
     708           6 :         copy_subdir_files("pg_multixact/members", "pg_multixact/members");
     709             : 
     710           6 :         prep_status("Setting next multixact ID and offset for new cluster");
     711             : 
     712             :         /*
     713             :          * we preserve all files and contents, so we must preserve both "next"
     714             :          * counters here and the oldest multi present on system.
     715             :          */
     716           6 :         exec_prog(UTILITY_LOG_FILE, NULL, true, true,
     717             :                   "\"%s/pg_resetwal\" -O %u -m %u,%u \"%s\"",
     718             :                   new_cluster.bindir,
     719             :                   old_cluster.controldata.chkpnt_nxtmxoff,
     720             :                   old_cluster.controldata.chkpnt_nxtmulti,
     721             :                   old_cluster.controldata.chkpnt_oldstMulti,
     722             :                   new_cluster.pgdata);
     723           6 :         check_ok();
     724             :     }
     725           0 :     else if (new_cluster.controldata.cat_ver >= MULTIXACT_FORMATCHANGE_CAT_VER)
     726             :     {
     727             :         /*
     728             :          * Remove offsets/0000 file created by initdb that no longer matches
     729             :          * the new multi-xid value.  "members" starts at zero so no need to
     730             :          * remove it.
     731             :          */
     732           0 :         remove_new_subdir("pg_multixact/offsets", false);
     733             : 
     734           0 :         prep_status("Setting oldest multixact ID in new cluster");
     735             : 
     736             :         /*
     737             :          * We don't preserve files in this case, but it's important that the
     738             :          * oldest multi is set to the latest value used by the old system, so
     739             :          * that multixact.c returns the empty set for multis that might be
     740             :          * present on disk.  We set next multi to the value following that; it
     741             :          * might end up wrapped around (i.e. 0) if the old cluster had
     742             :          * next=MaxMultiXactId, but multixact.c can cope with that just fine.
     743             :          */
     744           0 :         exec_prog(UTILITY_LOG_FILE, NULL, true, true,
     745             :                   "\"%s/pg_resetwal\" -m %u,%u \"%s\"",
     746             :                   new_cluster.bindir,
     747           0 :                   old_cluster.controldata.chkpnt_nxtmulti + 1,
     748             :                   old_cluster.controldata.chkpnt_nxtmulti,
     749             :                   new_cluster.pgdata);
     750           0 :         check_ok();
     751             :     }
     752             : 
     753             :     /* now reset the wal archives in the new cluster */
     754           6 :     prep_status("Resetting WAL archives");
     755           6 :     exec_prog(UTILITY_LOG_FILE, NULL, true, true,
     756             :     /* use timeline 1 to match controldata and no WAL history file */
     757             :               "\"%s/pg_resetwal\" -l 00000001%s \"%s\"", new_cluster.bindir,
     758             :               old_cluster.controldata.nextxlogfile + 8,
     759             :               new_cluster.pgdata);
     760           6 :     check_ok();
     761           6 : }
     762             : 
     763             : 
     764             : /*
     765             :  *  set_frozenxids()
     766             :  *
     767             :  * This is called on the new cluster before we restore anything, with
     768             :  * minmxid_only = false.  Its purpose is to ensure that all initdb-created
     769             :  * vacuumable tables have relfrozenxid/relminmxid matching the old cluster's
     770             :  * xid/mxid counters.  We also initialize the datfrozenxid/datminmxid of the
     771             :  * built-in databases to match.
     772             :  *
     773             :  * As we create user tables later, their relfrozenxid/relminmxid fields will
     774             :  * be restored properly by the binary-upgrade restore script.  Likewise for
     775             :  * user-database datfrozenxid/datminmxid.  However, if we're upgrading from a
     776             :  * pre-9.3 database, which does not store per-table or per-DB minmxid, then
     777             :  * the relminmxid/datminmxid values filled in by the restore script will just
     778             :  * be zeroes.
     779             :  *
     780             :  * Hence, with a pre-9.3 source database, a second call occurs after
     781             :  * everything is restored, with minmxid_only = true.  This pass will
     782             :  * initialize all tables and databases, both those made by initdb and user
     783             :  * objects, with the desired minmxid value.  frozenxid values are left alone.
     784             :  */
     785             : static void
     786           6 : set_frozenxids(bool minmxid_only)
     787             : {
     788             :     int         dbnum;
     789             :     PGconn     *conn,
     790             :                *conn_template1;
     791             :     PGresult   *dbres;
     792             :     int         ntups;
     793             :     int         i_datname;
     794             :     int         i_datallowconn;
     795             : 
     796           6 :     if (!minmxid_only)
     797           6 :         prep_status("Setting frozenxid and minmxid counters in new cluster");
     798             :     else
     799           0 :         prep_status("Setting minmxid counter in new cluster");
     800             : 
     801           6 :     conn_template1 = connectToServer(&new_cluster, "template1");
     802             : 
     803           6 :     if (!minmxid_only)
     804             :         /* set pg_database.datfrozenxid */
     805           6 :         PQclear(executeQueryOrDie(conn_template1,
     806             :                                   "UPDATE pg_catalog.pg_database "
     807             :                                   "SET datfrozenxid = '%u'",
     808             :                                   old_cluster.controldata.chkpnt_nxtxid));
     809             : 
     810             :     /* set pg_database.datminmxid */
     811           6 :     PQclear(executeQueryOrDie(conn_template1,
     812             :                               "UPDATE pg_catalog.pg_database "
     813             :                               "SET datminmxid = '%u'",
     814             :                               old_cluster.controldata.chkpnt_nxtmulti));
     815             : 
     816             :     /* get database names */
     817           6 :     dbres = executeQueryOrDie(conn_template1,
     818             :                               "SELECT  datname, datallowconn "
     819             :                               "FROM    pg_catalog.pg_database");
     820             : 
     821           6 :     i_datname = PQfnumber(dbres, "datname");
     822           6 :     i_datallowconn = PQfnumber(dbres, "datallowconn");
     823             : 
     824           6 :     ntups = PQntuples(dbres);
     825          24 :     for (dbnum = 0; dbnum < ntups; dbnum++)
     826             :     {
     827          18 :         char       *datname = PQgetvalue(dbres, dbnum, i_datname);
     828          18 :         char       *datallowconn = PQgetvalue(dbres, dbnum, i_datallowconn);
     829             : 
     830             :         /*
     831             :          * We must update databases where datallowconn = false, e.g.
     832             :          * template0, because autovacuum increments their datfrozenxids,
     833             :          * relfrozenxids, and relminmxid even if autovacuum is turned off, and
     834             :          * even though all the data rows are already frozen.  To enable this,
     835             :          * we temporarily change datallowconn.
     836             :          */
     837          18 :         if (strcmp(datallowconn, "f") == 0)
     838           6 :             PQclear(executeQueryOrDie(conn_template1,
     839             :                                       "ALTER DATABASE %s ALLOW_CONNECTIONS = true",
     840             :                                       quote_identifier(datname)));
     841             : 
     842          18 :         conn = connectToServer(&new_cluster, datname);
     843             : 
     844          18 :         if (!minmxid_only)
     845             :             /* set pg_class.relfrozenxid */
     846          18 :             PQclear(executeQueryOrDie(conn,
     847             :                                       "UPDATE  pg_catalog.pg_class "
     848             :                                       "SET relfrozenxid = '%u' "
     849             :             /* only heap, materialized view, and TOAST are vacuumed */
     850             :                                       "WHERE   relkind IN ("
     851             :                                       CppAsString2(RELKIND_RELATION) ", "
     852             :                                       CppAsString2(RELKIND_MATVIEW) ", "
     853             :                                       CppAsString2(RELKIND_TOASTVALUE) ")",
     854             :                                       old_cluster.controldata.chkpnt_nxtxid));
     855             : 
     856             :         /* set pg_class.relminmxid */
     857          18 :         PQclear(executeQueryOrDie(conn,
     858             :                                   "UPDATE  pg_catalog.pg_class "
     859             :                                   "SET relminmxid = '%u' "
     860             :         /* only heap, materialized view, and TOAST are vacuumed */
     861             :                                   "WHERE   relkind IN ("
     862             :                                   CppAsString2(RELKIND_RELATION) ", "
     863             :                                   CppAsString2(RELKIND_MATVIEW) ", "
     864             :                                   CppAsString2(RELKIND_TOASTVALUE) ")",
     865             :                                   old_cluster.controldata.chkpnt_nxtmulti));
     866          18 :         PQfinish(conn);
     867             : 
     868             :         /* Reset datallowconn flag */
     869          18 :         if (strcmp(datallowconn, "f") == 0)
     870           6 :             PQclear(executeQueryOrDie(conn_template1,
     871             :                                       "ALTER DATABASE %s ALLOW_CONNECTIONS = false",
     872             :                                       quote_identifier(datname)));
     873             :     }
     874             : 
     875           6 :     PQclear(dbres);
     876             : 
     877           6 :     PQfinish(conn_template1);
     878             : 
     879           6 :     check_ok();
     880           6 : }
     881             : 
     882             : /*
     883             :  * create_logical_replication_slots()
     884             :  *
     885             :  * Similar to create_new_objects() but only restores logical replication slots.
     886             :  */
     887             : static void
     888           2 : create_logical_replication_slots(void)
     889             : {
     890           2 :     prep_status_progress("Restoring logical replication slots in the new cluster");
     891             : 
     892           6 :     for (int dbnum = 0; dbnum < old_cluster.dbarr.ndbs; dbnum++)
     893             :     {
     894           4 :         DbInfo     *old_db = &old_cluster.dbarr.dbs[dbnum];
     895           4 :         LogicalSlotInfoArr *slot_arr = &old_db->slot_arr;
     896             :         PGconn     *conn;
     897             :         PQExpBuffer query;
     898             : 
     899             :         /* Skip this database if there are no slots */
     900           4 :         if (slot_arr->nslots == 0)
     901           2 :             continue;
     902             : 
     903           2 :         conn = connectToServer(&new_cluster, old_db->db_name);
     904           2 :         query = createPQExpBuffer();
     905             : 
     906           2 :         pg_log(PG_STATUS, "%s", old_db->db_name);
     907             : 
     908           4 :         for (int slotnum = 0; slotnum < slot_arr->nslots; slotnum++)
     909             :         {
     910           2 :             LogicalSlotInfo *slot_info = &slot_arr->slots[slotnum];
     911             : 
     912             :             /* Constructs a query for creating logical replication slots */
     913           2 :             appendPQExpBuffer(query,
     914             :                               "SELECT * FROM "
     915             :                               "pg_catalog.pg_create_logical_replication_slot(");
     916           2 :             appendStringLiteralConn(query, slot_info->slotname, conn);
     917           2 :             appendPQExpBuffer(query, ", ");
     918           2 :             appendStringLiteralConn(query, slot_info->plugin, conn);
     919             : 
     920           4 :             appendPQExpBuffer(query, ", false, %s, %s);",
     921           2 :                               slot_info->two_phase ? "true" : "false",
     922           2 :                               slot_info->failover ? "true" : "false");
     923             : 
     924           2 :             PQclear(executeQueryOrDie(conn, "%s", query->data));
     925             : 
     926           2 :             resetPQExpBuffer(query);
     927             :         }
     928             : 
     929           2 :         PQfinish(conn);
     930             : 
     931           2 :         destroyPQExpBuffer(query);
     932             :     }
     933             : 
     934           2 :     end_progress_output();
     935           2 :     check_ok();
     936             : 
     937           2 :     return;
     938             : }

Generated by: LCOV version 1.14