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

Generated by: LCOV version 1.14