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

Generated by: LCOV version 1.14