PostgreSQL Source Code  git master
pg_upgrade.c File Reference
#include "postgres_fe.h"
#include <time.h>
#include "catalog/pg_class_d.h"
#include "common/file_perm.h"
#include "common/logging.h"
#include "common/restricted_token.h"
#include "fe_utils/string_utils.h"
#include "pg_upgrade.h"
Include dependency graph for pg_upgrade.c:

Go to the source code of this file.

Macros

#define RESTORE_TRANSACTION_SIZE   1000
 

Functions

static void set_locale_and_encoding (void)
 
static void prepare_new_cluster (void)
 
static void prepare_new_globals (void)
 
static void create_new_objects (void)
 
static void copy_xact_xlog_xid (void)
 
static void set_frozenxids (bool minmxid_only)
 
static void make_outputdirs (char *pgdata)
 
static void setup (char *argv0)
 
static void create_logical_replication_slots (void)
 
int main (int argc, char **argv)
 
static void remove_new_subdir (const char *subdir, bool rmtopdir)
 
static void copy_subdir_files (const char *old_subdir, const char *new_subdir)
 

Variables

ClusterInfo old_cluster
 
ClusterInfo new_cluster
 
OSInfo os_info
 
char * output_files []
 

Macro Definition Documentation

◆ RESTORE_TRANSACTION_SIZE

#define RESTORE_TRANSACTION_SIZE   1000

Definition at line 55 of file pg_upgrade.c.

Function Documentation

◆ copy_subdir_files()

static void copy_subdir_files ( const char *  old_subdir,
const char *  new_subdir 
)
static

Definition at line 682 of file pg_upgrade.c.

683 {
684  char old_path[MAXPGPATH];
685  char new_path[MAXPGPATH];
686 
687  remove_new_subdir(new_subdir, true);
688 
689  snprintf(old_path, sizeof(old_path), "%s/%s", old_cluster.pgdata, old_subdir);
690  snprintf(new_path, sizeof(new_path), "%s/%s", new_cluster.pgdata, new_subdir);
691 
692  prep_status("Copying old %s to new server", old_subdir);
693 
694  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
695 #ifndef WIN32
696  "cp -Rf \"%s\" \"%s\"",
697 #else
698  /* flags: everything, no confirm, quiet, overwrite read-only */
699  "xcopy /e /y /q /r \"%s\" \"%s\\\"",
700 #endif
701  old_path, new_path);
702 
703  check_ok();
704 }
bool exec_prog(const char *log_filename, const char *opt_log_file, bool report_error, bool exit_on_error, const char *fmt,...)
Definition: exec.c:85
static void check_ok(void)
Definition: initdb.c:2091
#define MAXPGPATH
ClusterInfo new_cluster
Definition: pg_upgrade.c:68
static void remove_new_subdir(const char *subdir, bool rmtopdir)
Definition: pg_upgrade.c:665
ClusterInfo old_cluster
Definition: pg_upgrade.c:67
#define UTILITY_LOG_FILE
Definition: pg_upgrade.h:45
void prep_status(const char *fmt,...) pg_attribute_printf(1
#define snprintf
Definition: port.h:238
char * pgdata
Definition: pg_upgrade.h:285

References check_ok(), exec_prog(), MAXPGPATH, new_cluster, old_cluster, ClusterInfo::pgdata, prep_status(), remove_new_subdir(), snprintf, and UTILITY_LOG_FILE.

Referenced by copy_xact_xlog_xid().

◆ copy_xact_xlog_xid()

static void copy_xact_xlog_xid ( void  )
static

Definition at line 707 of file pg_upgrade.c.

708 {
709  /*
710  * Copy old commit logs to new data dir. pg_clog has been renamed to
711  * pg_xact in post-10 clusters.
712  */
714  "pg_clog" : "pg_xact",
716  "pg_clog" : "pg_xact");
717 
718  prep_status("Setting oldest XID for new cluster");
719  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
720  "\"%s/pg_resetwal\" -f -u %u \"%s\"",
723  check_ok();
724 
725  /* set the next transaction id and epoch of the new cluster */
726  prep_status("Setting next transaction ID and epoch for new cluster");
727  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
728  "\"%s/pg_resetwal\" -f -x %u \"%s\"",
731  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
732  "\"%s/pg_resetwal\" -f -e %u \"%s\"",
735  /* must reset commit timestamp limits also */
736  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
737  "\"%s/pg_resetwal\" -f -c %u,%u \"%s\"",
742  check_ok();
743 
744  /*
745  * If the old server is before the MULTIXACT_FORMATCHANGE_CAT_VER change
746  * (see pg_upgrade.h) and the new server is after, then we don't copy
747  * pg_multixact files, but we need to reset pg_control so that the new
748  * server doesn't attempt to read multis older than the cutoff value.
749  */
752  {
753  copy_subdir_files("pg_multixact/offsets", "pg_multixact/offsets");
754  copy_subdir_files("pg_multixact/members", "pg_multixact/members");
755 
756  prep_status("Setting next multixact ID and offset for new cluster");
757 
758  /*
759  * we preserve all files and contents, so we must preserve both "next"
760  * counters here and the oldest multi present on system.
761  */
762  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
763  "\"%s/pg_resetwal\" -O %u -m %u,%u \"%s\"",
769  check_ok();
770  }
772  {
773  /*
774  * Remove offsets/0000 file created by initdb that no longer matches
775  * the new multi-xid value. "members" starts at zero so no need to
776  * remove it.
777  */
778  remove_new_subdir("pg_multixact/offsets", false);
779 
780  prep_status("Setting oldest multixact ID in new cluster");
781 
782  /*
783  * We don't preserve files in this case, but it's important that the
784  * oldest multi is set to the latest value used by the old system, so
785  * that multixact.c returns the empty set for multis that might be
786  * present on disk. We set next multi to the value following that; it
787  * might end up wrapped around (i.e. 0) if the old cluster had
788  * next=MaxMultiXactId, but multixact.c can cope with that just fine.
789  */
790  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
791  "\"%s/pg_resetwal\" -m %u,%u \"%s\"",
796  check_ok();
797  }
798 
799  /* now reset the wal archives in the new cluster */
800  prep_status("Resetting WAL archives");
801  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
802  /* use timeline 1 to match controldata and no WAL history file */
803  "\"%s/pg_resetwal\" -l 00000001%s \"%s\"", new_cluster.bindir,
806  check_ok();
807 }
static void copy_subdir_files(const char *old_subdir, const char *new_subdir)
Definition: pg_upgrade.c:682
#define MULTIXACT_FORMATCHANGE_CAT_VER
Definition: pg_upgrade.h:115
#define GET_MAJOR_VERSION(v)
Definition: pg_upgrade.h:27
ControlData controldata
Definition: pg_upgrade.h:282
char * bindir
Definition: pg_upgrade.h:288
uint32 major_version
Definition: pg_upgrade.h:293
uint32 chkpnt_nxtxid
Definition: pg_upgrade.h:229
char nextxlogfile[25]
Definition: pg_upgrade.h:228
uint32 chkpnt_nxtmxoff
Definition: pg_upgrade.h:233
uint32 cat_ver
Definition: pg_upgrade.h:227
uint32 chkpnt_nxtmulti
Definition: pg_upgrade.h:232
uint32 chkpnt_oldstxid
Definition: pg_upgrade.h:235
uint32 chkpnt_nxtepoch
Definition: pg_upgrade.h:230
uint32 chkpnt_oldstMulti
Definition: pg_upgrade.h:234

References ClusterInfo::bindir, ControlData::cat_ver, check_ok(), ControlData::chkpnt_nxtepoch, ControlData::chkpnt_nxtmulti, ControlData::chkpnt_nxtmxoff, ControlData::chkpnt_nxtxid, ControlData::chkpnt_oldstMulti, ControlData::chkpnt_oldstxid, ClusterInfo::controldata, copy_subdir_files(), exec_prog(), GET_MAJOR_VERSION, ClusterInfo::major_version, MULTIXACT_FORMATCHANGE_CAT_VER, new_cluster, ControlData::nextxlogfile, old_cluster, ClusterInfo::pgdata, prep_status(), remove_new_subdir(), and UTILITY_LOG_FILE.

Referenced by main().

◆ create_logical_replication_slots()

static void create_logical_replication_slots ( void  )
static

Definition at line 934 of file pg_upgrade.c.

935 {
936  prep_status_progress("Restoring logical replication slots in the new cluster");
937 
938  for (int dbnum = 0; dbnum < old_cluster.dbarr.ndbs; dbnum++)
939  {
940  DbInfo *old_db = &old_cluster.dbarr.dbs[dbnum];
941  LogicalSlotInfoArr *slot_arr = &old_db->slot_arr;
942  PGconn *conn;
943  PQExpBuffer query;
944 
945  /* Skip this database if there are no slots */
946  if (slot_arr->nslots == 0)
947  continue;
948 
950  query = createPQExpBuffer();
951 
952  pg_log(PG_STATUS, "%s", old_db->db_name);
953 
954  for (int slotnum = 0; slotnum < slot_arr->nslots; slotnum++)
955  {
956  LogicalSlotInfo *slot_info = &slot_arr->slots[slotnum];
957 
958  /* Constructs a query for creating logical replication slots */
959  appendPQExpBuffer(query,
960  "SELECT * FROM "
961  "pg_catalog.pg_create_logical_replication_slot(");
962  appendStringLiteralConn(query, slot_info->slotname, conn);
963  appendPQExpBuffer(query, ", ");
964  appendStringLiteralConn(query, slot_info->plugin, conn);
965 
966  appendPQExpBuffer(query, ", false, %s, %s);",
967  slot_info->two_phase ? "true" : "false",
968  slot_info->failover ? "true" : "false");
969 
970  PQclear(executeQueryOrDie(conn, "%s", query->data));
971 
972  resetPQExpBuffer(query);
973  }
974 
975  PQfinish(conn);
976 
977  destroyPQExpBuffer(query);
978  }
979 
981  check_ok();
982 
983  return;
984 }
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4879
void void pg_log(eLogType type, const char *fmt,...) pg_attribute_printf(2
void void prep_status_progress(const char *fmt,...) pg_attribute_printf(1
@ PG_STATUS
Definition: pg_upgrade.h:267
PGconn * connectToServer(ClusterInfo *cluster, const char *db_name)
Definition: server.c:28
void end_progress_output(void)
Definition: util.c:43
PGresult * executeQueryOrDie(PGconn *conn, const char *fmt,...) pg_attribute_printf(2
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:72
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:146
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:265
void destroyPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:114
PGconn * conn
Definition: streamutil.c:53
void appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
Definition: string_utils.c:293
DbInfoArr dbarr
Definition: pg_upgrade.h:284
DbInfo * dbs
Definition: pg_upgrade.h:215
LogicalSlotInfoArr slot_arr
Definition: pg_upgrade.h:198
char * db_name
Definition: pg_upgrade.h:194
LogicalSlotInfo * slots
Definition: pg_upgrade.h:169

References appendPQExpBuffer(), appendStringLiteralConn(), check_ok(), conn, connectToServer(), createPQExpBuffer(), PQExpBufferData::data, DbInfo::db_name, ClusterInfo::dbarr, DbInfoArr::dbs, destroyPQExpBuffer(), end_progress_output(), executeQueryOrDie(), LogicalSlotInfo::failover, DbInfoArr::ndbs, new_cluster, LogicalSlotInfoArr::nslots, old_cluster, pg_log(), PG_STATUS, LogicalSlotInfo::plugin, PQclear(), PQfinish(), prep_status_progress(), resetPQExpBuffer(), DbInfo::slot_arr, LogicalSlotInfo::slotname, LogicalSlotInfoArr::slots, and LogicalSlotInfo::two_phase.

Referenced by main().

◆ create_new_objects()

static void create_new_objects ( void  )
static

Definition at line 529 of file pg_upgrade.c.

530 {
531  int dbnum;
532  PGconn *conn_new_template1;
533 
534  prep_status_progress("Restoring database schemas in the new cluster");
535 
536  /*
537  * Ensure that any changes to template0 are fully written out to disk
538  * prior to restoring the databases. This is necessary because we use the
539  * FILE_COPY strategy to create the databases (which testing has shown to
540  * be faster), and when the server is in binary upgrade mode, it skips the
541  * checkpoints this strategy ordinarily performs.
542  */
543  conn_new_template1 = connectToServer(&new_cluster, "template1");
544  PQclear(executeQueryOrDie(conn_new_template1, "CHECKPOINT"));
545  PQfinish(conn_new_template1);
546 
547  /*
548  * We cannot process the template1 database concurrently with others,
549  * because when it's transiently dropped, connection attempts would fail.
550  * So handle it in a separate non-parallelized pass.
551  */
552  for (dbnum = 0; dbnum < old_cluster.dbarr.ndbs; dbnum++)
553  {
554  char sql_file_name[MAXPGPATH],
555  log_file_name[MAXPGPATH];
556  DbInfo *old_db = &old_cluster.dbarr.dbs[dbnum];
557  const char *create_opts;
558 
559  /* Process only template1 in this pass */
560  if (strcmp(old_db->db_name, "template1") != 0)
561  continue;
562 
563  pg_log(PG_STATUS, "%s", old_db->db_name);
564  snprintf(sql_file_name, sizeof(sql_file_name), DB_DUMP_FILE_MASK, old_db->db_oid);
565  snprintf(log_file_name, sizeof(log_file_name), DB_DUMP_LOG_FILE_MASK, old_db->db_oid);
566 
567  /*
568  * template1 database will already exist in the target installation,
569  * so tell pg_restore to drop and recreate it; otherwise we would fail
570  * to propagate its database-level properties.
571  */
572  create_opts = "--clean --create";
573 
574  exec_prog(log_file_name,
575  NULL,
576  true,
577  true,
578  "\"%s/pg_restore\" %s %s --exit-on-error --verbose "
579  "--transaction-size=%d "
580  "--dbname postgres \"%s/%s\"",
583  create_opts,
586  sql_file_name);
587 
588  break; /* done once we've processed template1 */
589  }
590 
591  for (dbnum = 0; dbnum < old_cluster.dbarr.ndbs; dbnum++)
592  {
593  char sql_file_name[MAXPGPATH],
594  log_file_name[MAXPGPATH];
595  DbInfo *old_db = &old_cluster.dbarr.dbs[dbnum];
596  const char *create_opts;
597  int txn_size;
598 
599  /* Skip template1 in this pass */
600  if (strcmp(old_db->db_name, "template1") == 0)
601  continue;
602 
603  pg_log(PG_STATUS, "%s", old_db->db_name);
604  snprintf(sql_file_name, sizeof(sql_file_name), DB_DUMP_FILE_MASK, old_db->db_oid);
605  snprintf(log_file_name, sizeof(log_file_name), DB_DUMP_LOG_FILE_MASK, old_db->db_oid);
606 
607  /*
608  * postgres database will already exist in the target installation, so
609  * tell pg_restore to drop and recreate it; otherwise we would fail to
610  * propagate its database-level properties.
611  */
612  if (strcmp(old_db->db_name, "postgres") == 0)
613  create_opts = "--clean --create";
614  else
615  create_opts = "--create";
616 
617  /*
618  * In parallel mode, reduce the --transaction-size of each restore job
619  * so that the total number of locks that could be held across all the
620  * jobs stays in bounds.
621  */
622  txn_size = RESTORE_TRANSACTION_SIZE;
623  if (user_opts.jobs > 1)
624  {
625  txn_size /= user_opts.jobs;
626  /* Keep some sanity if -j is huge */
627  txn_size = Max(txn_size, 10);
628  }
629 
630  parallel_exec_prog(log_file_name,
631  NULL,
632  "\"%s/pg_restore\" %s %s --exit-on-error --verbose "
633  "--transaction-size=%d "
634  "--dbname template1 \"%s/%s\"",
637  create_opts,
638  txn_size,
640  sql_file_name);
641  }
642 
643  /* reap all children */
644  while (reap_child(true) == true)
645  ;
646 
648  check_ok();
649 
650  /*
651  * We don't have minmxids for databases or relations in pre-9.3 clusters,
652  * so set those after we have restored the schema.
653  */
655  set_frozenxids(true);
656 
657  /* update new_cluster info now that we have objects in the databases */
659 }
bool reap_child(bool wait_for_child)
Definition: parallel.c:278
void parallel_exec_prog(const char *log_file, const char *opt_log_file, const char *fmt,...)
Definition: parallel.c:62
#define Max(x, y)
Definition: c.h:1001
void get_db_rel_and_slot_infos(ClusterInfo *cluster)
Definition: info.c:280
static void set_frozenxids(bool minmxid_only)
Definition: pg_upgrade.c:832
#define RESTORE_TRANSACTION_SIZE
Definition: pg_upgrade.c:55
#define DB_DUMP_LOG_FILE_MASK
Definition: pg_upgrade.h:43
LogOpts log_opts
Definition: util.c:17
PGresult char * cluster_conn_opts(ClusterInfo *cluster)
Definition: server.c:92
#define DB_DUMP_FILE_MASK
Definition: pg_upgrade.h:31
UserOpts user_opts
Definition: option.c:30
Oid db_oid
Definition: pg_upgrade.h:193
char * dumpdir
Definition: pg_upgrade.h:312
int jobs
Definition: pg_upgrade.h:327

References ClusterInfo::bindir, check_ok(), cluster_conn_opts(), connectToServer(), DB_DUMP_FILE_MASK, DB_DUMP_LOG_FILE_MASK, DbInfo::db_name, DbInfo::db_oid, ClusterInfo::dbarr, DbInfoArr::dbs, LogOpts::dumpdir, end_progress_output(), exec_prog(), executeQueryOrDie(), get_db_rel_and_slot_infos(), GET_MAJOR_VERSION, UserOpts::jobs, log_opts, ClusterInfo::major_version, Max, MAXPGPATH, DbInfoArr::ndbs, new_cluster, old_cluster, parallel_exec_prog(), pg_log(), PG_STATUS, PQclear(), PQfinish(), prep_status_progress(), reap_child(), RESTORE_TRANSACTION_SIZE, set_frozenxids(), snprintf, and user_opts.

Referenced by main().

◆ main()

int main ( int  argc,
char **  argv 
)

Definition at line 84 of file pg_upgrade.c.

85 {
86  char *deletion_script_file_name = NULL;
87 
88  /*
89  * pg_upgrade doesn't currently use common/logging.c, but initialize it
90  * anyway because we might call common code that does.
91  */
92  pg_logging_init(argv[0]);
93  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_upgrade"));
94 
95  /* Set default restrictive mask until new cluster permissions are read */
96  umask(PG_MODE_MASK_OWNER);
97 
98  parseCommandLine(argc, argv);
99 
101 
104 
105  /*
106  * Set mask based on PGDATA permissions, needed for the creation of the
107  * output directories with correct permissions.
108  */
110  pg_fatal("could not read permissions of directory \"%s\": %m",
112 
113  umask(pg_mode_mask);
114 
115  /*
116  * This needs to happen after adjusting the data directory of the new
117  * cluster in adjust_data_dir().
118  */
120 
121  setup(argv[0]);
122 
124 
126 
129 
131 
133 
134 
135  /* -- NEW -- */
137 
140 
142  "\n"
143  "Performing Upgrade\n"
144  "------------------");
145 
147 
149 
150  stop_postmaster(false);
151 
152  /*
153  * Destructive Changes to New Cluster
154  */
155 
157 
158  /* New now using xids of the old system */
159 
160  /* -- NEW -- */
162 
164 
166 
167  stop_postmaster(false);
168 
169  /*
170  * Most failures happen in create_new_objects(), which has completed at
171  * this point. We do this here because it is just before linking, which
172  * will link the old and new cluster data files, preventing the old
173  * cluster from being safely started once the new cluster is started.
174  */
177 
180 
181  /*
182  * Assuming OIDs are only used in system tables, there is no need to
183  * restore the OID counter because we have not transferred any OIDs from
184  * the old system, but we do it anyway just in case. We do it late here
185  * because there is no need to have the schema load use new oids.
186  */
187  prep_status("Setting next OID for new cluster");
188  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
189  "\"%s/pg_resetwal\" -o %u \"%s\"",
192  check_ok();
193 
194  /*
195  * Migrate the logical slots to the new cluster. Note that we need to do
196  * this after resetting WAL because otherwise the required WAL would be
197  * removed and slots would become unusable. There is a possibility that
198  * background processes might generate some WAL before we could create the
199  * slots in the new cluster but we can ignore that WAL as that won't be
200  * required downstream.
201  */
203  {
206  stop_postmaster(false);
207  }
208 
209  if (user_opts.do_sync)
210  {
211  prep_status("Sync data directory to disk");
212  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
213  "\"%s/initdb\" --sync-only \"%s\" --sync-method %s",
217  check_ok();
218  }
219 
220  create_script_for_old_cluster_deletion(&deletion_script_file_name);
221 
223 
225  "\n"
226  "Upgrade Complete\n"
227  "----------------");
228 
229  output_completion_banner(deletion_script_file_name);
230 
231  pg_free(deletion_script_file_name);
232 
234 
235  return 0;
236 }
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1217
void check_cluster_versions(void)
Definition: check.c:803
void issue_warnings_and_set_wal_level(void)
Definition: check.c:748
void check_cluster_compatibility(void)
Definition: check.c:846
void check_new_cluster(void)
Definition: check.c:693
void report_clusters_compatible(void)
Definition: check.c:729
void create_script_for_old_cluster_deletion(char **deletion_script_file_name)
Definition: check.c:921
void check_and_dump_old_cluster(void)
Definition: check.c:586
void output_completion_banner(char *deletion_script_file_name)
Definition: check.c:769
void output_check_banner(void)
Definition: check.c:568
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:429
void disable_old_cluster(void)
Definition: controldata.c:712
void pg_free(void *ptr)
Definition: fe_memutils.c:105
int pg_mode_mask
Definition: file_perm.c:25
bool GetDataDirectoryCreatePerm(const char *dataDir)
#define PG_MODE_MASK_OWNER
Definition: file_perm.h:24
int count_old_cluster_logical_slots(void)
Definition: info.c:742
void pg_logging_init(const char *argv0)
Definition: logging.c:83
#define pg_fatal(...)
static void adjust_data_dir(void)
Definition: pg_ctl.c:2125
static pid_t start_postmaster(void)
Definition: pg_ctl.c:440
static void create_logical_replication_slots(void)
Definition: pg_upgrade.c:934
static void make_outputdirs(char *pgdata)
Definition: pg_upgrade.c:244
static void prepare_new_cluster(void)
Definition: pg_upgrade.c:477
static void create_new_objects(void)
Definition: pg_upgrade.c:529
static void copy_xact_xlog_xid(void)
Definition: pg_upgrade.c:707
static void set_locale_and_encoding(void)
Definition: pg_upgrade.c:400
static void setup(char *argv0)
Definition: pg_upgrade.c:329
static void prepare_new_globals(void)
Definition: pg_upgrade.c:507
void transfer_all_new_tablespaces(DbInfoArr *old_db_arr, DbInfoArr *new_db_arr, char *old_pgdata, char *new_pgdata)
Definition: relfilenumber.c:27
void cleanup_output_dirs(void)
Definition: util.c:63
@ TRANSFER_MODE_LINK
Definition: pg_upgrade.h:258
@ PG_REPORT
Definition: pg_upgrade.h:269
void stop_postmaster(bool in_atexit)
Definition: server.c:342
void get_restricted_token(void)
void parseCommandLine(int argc, char *argv[])
Definition: option.c:39
void get_sock_dir(ClusterInfo *cluster)
Definition: option.c:473
uint32 chkpnt_nxtoid
Definition: pg_upgrade.h:231
char * sync_method
Definition: pg_upgrade.h:329
bool do_sync
Definition: pg_upgrade.h:325
transferMode transfer_mode
Definition: pg_upgrade.h:326

References adjust_data_dir(), ClusterInfo::bindir, check_and_dump_old_cluster(), check_cluster_compatibility(), check_cluster_versions(), check_new_cluster(), check_ok(), ControlData::chkpnt_nxtoid, cleanup_output_dirs(), ClusterInfo::controldata, copy_xact_xlog_xid(), count_old_cluster_logical_slots(), create_logical_replication_slots(), create_new_objects(), create_script_for_old_cluster_deletion(), ClusterInfo::dbarr, disable_old_cluster(), UserOpts::do_sync, exec_prog(), get_restricted_token(), get_sock_dir(), GetDataDirectoryCreatePerm(), issue_warnings_and_set_wal_level(), make_outputdirs(), new_cluster, old_cluster, output_check_banner(), output_completion_banner(), parseCommandLine(), pg_fatal, pg_free(), pg_log(), pg_logging_init(), pg_mode_mask, PG_MODE_MASK_OWNER, PG_REPORT, PG_TEXTDOMAIN, ClusterInfo::pgdata, prep_status(), prepare_new_cluster(), prepare_new_globals(), report_clusters_compatible(), set_locale_and_encoding(), set_pglocale_pgservice(), setup(), start_postmaster(), stop_postmaster(), UserOpts::sync_method, transfer_all_new_tablespaces(), UserOpts::transfer_mode, TRANSFER_MODE_LINK, user_opts, and UTILITY_LOG_FILE.

◆ make_outputdirs()

static void make_outputdirs ( char *  pgdata)
static

Definition at line 244 of file pg_upgrade.c.

245 {
246  FILE *fp;
247  char **filename;
248  time_t run_time = time(NULL);
249  char filename_path[MAXPGPATH];
250  char timebuf[128];
251  struct timeval time;
252  time_t tt;
253  int len;
254 
255  log_opts.rootdir = (char *) pg_malloc0(MAXPGPATH);
256  len = snprintf(log_opts.rootdir, MAXPGPATH, "%s/%s", pgdata, BASE_OUTPUTDIR);
257  if (len >= MAXPGPATH)
258  pg_fatal("directory path for new cluster is too long");
259 
260  /* BASE_OUTPUTDIR/$timestamp/ */
261  gettimeofday(&time, NULL);
262  tt = (time_t) time.tv_sec;
263  strftime(timebuf, sizeof(timebuf), "%Y%m%dT%H%M%S", localtime(&tt));
264  /* append milliseconds */
265  snprintf(timebuf + strlen(timebuf), sizeof(timebuf) - strlen(timebuf),
266  ".%03d", (int) (time.tv_usec / 1000));
267  log_opts.basedir = (char *) pg_malloc0(MAXPGPATH);
269  timebuf);
270  if (len >= MAXPGPATH)
271  pg_fatal("directory path for new cluster is too long");
272 
273  /* BASE_OUTPUTDIR/$timestamp/dump/ */
274  log_opts.dumpdir = (char *) pg_malloc0(MAXPGPATH);
276  timebuf, DUMP_OUTPUTDIR);
277  if (len >= MAXPGPATH)
278  pg_fatal("directory path for new cluster is too long");
279 
280  /* BASE_OUTPUTDIR/$timestamp/log/ */
281  log_opts.logdir = (char *) pg_malloc0(MAXPGPATH);
283  timebuf, LOG_OUTPUTDIR);
284  if (len >= MAXPGPATH)
285  pg_fatal("directory path for new cluster is too long");
286 
287  /*
288  * Ignore the error case where the root path exists, as it is kept the
289  * same across runs.
290  */
291  if (mkdir(log_opts.rootdir, pg_dir_create_mode) < 0 && errno != EEXIST)
292  pg_fatal("could not create directory \"%s\": %m", log_opts.rootdir);
294  pg_fatal("could not create directory \"%s\": %m", log_opts.basedir);
296  pg_fatal("could not create directory \"%s\": %m", log_opts.dumpdir);
298  pg_fatal("could not create directory \"%s\": %m", log_opts.logdir);
299 
300  len = snprintf(filename_path, sizeof(filename_path), "%s/%s",
302  if (len >= sizeof(filename_path))
303  pg_fatal("directory path for new cluster is too long");
304 
305  if ((log_opts.internal = fopen_priv(filename_path, "a")) == NULL)
306  pg_fatal("could not open log file \"%s\": %m", filename_path);
307 
308  /* label start of upgrade in logfiles */
309  for (filename = output_files; *filename != NULL; filename++)
310  {
311  len = snprintf(filename_path, sizeof(filename_path), "%s/%s",
313  if (len >= sizeof(filename_path))
314  pg_fatal("directory path for new cluster is too long");
315  if ((fp = fopen_priv(filename_path, "a")) == NULL)
316  pg_fatal("could not write to log file \"%s\": %m", filename_path);
317 
318  fprintf(fp,
319  "-----------------------------------------------------------------\n"
320  " pg_upgrade run on %s"
321  "-----------------------------------------------------------------\n\n",
322  ctime(&run_time));
323  fclose(fp);
324  }
325 }
void * pg_malloc0(size_t size)
Definition: fe_memutils.c:53
int pg_dir_create_mode
Definition: file_perm.c:18
const void size_t len
static char * filename
Definition: pg_dumpall.c:119
char * output_files[]
Definition: pg_upgrade.c:71
#define LOG_OUTPUTDIR
Definition: pg_upgrade.h:40
#define fopen_priv(path, mode)
Definition: pg_upgrade.h:419
#define DUMP_OUTPUTDIR
Definition: pg_upgrade.h:41
#define BASE_OUTPUTDIR
Definition: pg_upgrade.h:39
#define INTERNAL_LOG_FILE
Definition: pg_upgrade.h:46
#define fprintf
Definition: port.h:242
char * rootdir
Definition: pg_upgrade.h:310
FILE * internal
Definition: pg_upgrade.h:306
char * basedir
Definition: pg_upgrade.h:311
char * logdir
Definition: pg_upgrade.h:313
#define mkdir(a, b)
Definition: win32_port.h:80
int gettimeofday(struct timeval *tp, void *tzp)

References BASE_OUTPUTDIR, LogOpts::basedir, DUMP_OUTPUTDIR, LogOpts::dumpdir, filename, fopen_priv, fprintf, gettimeofday(), LogOpts::internal, INTERNAL_LOG_FILE, len, log_opts, LOG_OUTPUTDIR, LogOpts::logdir, MAXPGPATH, mkdir, output_files, pg_dir_create_mode, pg_fatal, pg_malloc0(), LogOpts::rootdir, and snprintf.

Referenced by main().

◆ prepare_new_cluster()

static void prepare_new_cluster ( void  )
static

Definition at line 477 of file pg_upgrade.c.

478 {
479  /*
480  * It would make more sense to freeze after loading the schema, but that
481  * would cause us to lose the frozenxids restored by the load. We use
482  * --analyze so autovacuum doesn't update statistics later
483  */
484  prep_status("Analyzing all rows in the new cluster");
485  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
486  "\"%s/vacuumdb\" %s --all --analyze %s",
488  log_opts.verbose ? "--verbose" : "");
489  check_ok();
490 
491  /*
492  * We do freeze after analyze so pg_statistic is also frozen. template0 is
493  * not frozen here, but data rows were frozen by initdb, and we set its
494  * datfrozenxid, relfrozenxids, and relminmxid later to match the new xid
495  * counter later.
496  */
497  prep_status("Freezing all rows in the new cluster");
498  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
499  "\"%s/vacuumdb\" %s --all --freeze %s",
501  log_opts.verbose ? "--verbose" : "");
502  check_ok();
503 }
bool verbose
Definition: pg_upgrade.h:307

References ClusterInfo::bindir, check_ok(), cluster_conn_opts(), exec_prog(), log_opts, new_cluster, prep_status(), UTILITY_LOG_FILE, and LogOpts::verbose.

Referenced by main().

◆ prepare_new_globals()

static void prepare_new_globals ( void  )
static

Definition at line 507 of file pg_upgrade.c.

508 {
509  /*
510  * Before we restore anything, set frozenxids of initdb-created tables.
511  */
512  set_frozenxids(false);
513 
514  /*
515  * Now restore global objects (roles and tablespaces).
516  */
517  prep_status("Restoring global objects in the new cluster");
518 
519  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
520  "\"%s/psql\" " EXEC_PSQL_ARGS " %s -f \"%s/%s\"",
524  check_ok();
525 }
#define GLOBALS_DUMP_FILE
Definition: pg_upgrade.h:30
#define EXEC_PSQL_ARGS
Definition: pg_upgrade.h:394

References ClusterInfo::bindir, check_ok(), cluster_conn_opts(), LogOpts::dumpdir, exec_prog(), EXEC_PSQL_ARGS, GLOBALS_DUMP_FILE, log_opts, new_cluster, prep_status(), set_frozenxids(), and UTILITY_LOG_FILE.

Referenced by main().

◆ remove_new_subdir()

static void remove_new_subdir ( const char *  subdir,
bool  rmtopdir 
)
static

Definition at line 665 of file pg_upgrade.c.

666 {
667  char new_path[MAXPGPATH];
668 
669  prep_status("Deleting files from new %s", subdir);
670 
671  snprintf(new_path, sizeof(new_path), "%s/%s", new_cluster.pgdata, subdir);
672  if (!rmtree(new_path, rmtopdir))
673  pg_fatal("could not delete directory \"%s\"", new_path);
674 
675  check_ok();
676 }
bool rmtree(const char *path, bool rmtopdir)
Definition: rmtree.c:50

References check_ok(), MAXPGPATH, new_cluster, pg_fatal, ClusterInfo::pgdata, prep_status(), rmtree(), and snprintf.

Referenced by copy_subdir_files(), and copy_xact_xlog_xid().

◆ set_frozenxids()

static void set_frozenxids ( bool  minmxid_only)
static

Definition at line 832 of file pg_upgrade.c.

833 {
834  int dbnum;
835  PGconn *conn,
836  *conn_template1;
837  PGresult *dbres;
838  int ntups;
839  int i_datname;
840  int i_datallowconn;
841 
842  if (!minmxid_only)
843  prep_status("Setting frozenxid and minmxid counters in new cluster");
844  else
845  prep_status("Setting minmxid counter in new cluster");
846 
847  conn_template1 = connectToServer(&new_cluster, "template1");
848 
849  if (!minmxid_only)
850  /* set pg_database.datfrozenxid */
851  PQclear(executeQueryOrDie(conn_template1,
852  "UPDATE pg_catalog.pg_database "
853  "SET datfrozenxid = '%u'",
855 
856  /* set pg_database.datminmxid */
857  PQclear(executeQueryOrDie(conn_template1,
858  "UPDATE pg_catalog.pg_database "
859  "SET datminmxid = '%u'",
861 
862  /* get database names */
863  dbres = executeQueryOrDie(conn_template1,
864  "SELECT datname, datallowconn "
865  "FROM pg_catalog.pg_database");
866 
867  i_datname = PQfnumber(dbres, "datname");
868  i_datallowconn = PQfnumber(dbres, "datallowconn");
869 
870  ntups = PQntuples(dbres);
871  for (dbnum = 0; dbnum < ntups; dbnum++)
872  {
873  char *datname = PQgetvalue(dbres, dbnum, i_datname);
874  char *datallowconn = PQgetvalue(dbres, dbnum, i_datallowconn);
875 
876  /*
877  * We must update databases where datallowconn = false, e.g.
878  * template0, because autovacuum increments their datfrozenxids,
879  * relfrozenxids, and relminmxid even if autovacuum is turned off, and
880  * even though all the data rows are already frozen. To enable this,
881  * we temporarily change datallowconn.
882  */
883  if (strcmp(datallowconn, "f") == 0)
884  PQclear(executeQueryOrDie(conn_template1,
885  "ALTER DATABASE %s ALLOW_CONNECTIONS = true",
887 
889 
890  if (!minmxid_only)
891  /* set pg_class.relfrozenxid */
893  "UPDATE pg_catalog.pg_class "
894  "SET relfrozenxid = '%u' "
895  /* only heap, materialized view, and TOAST are vacuumed */
896  "WHERE relkind IN ("
897  CppAsString2(RELKIND_RELATION) ", "
898  CppAsString2(RELKIND_MATVIEW) ", "
899  CppAsString2(RELKIND_TOASTVALUE) ")",
901 
902  /* set pg_class.relminmxid */
904  "UPDATE pg_catalog.pg_class "
905  "SET relminmxid = '%u' "
906  /* only heap, materialized view, and TOAST are vacuumed */
907  "WHERE relkind IN ("
908  CppAsString2(RELKIND_RELATION) ", "
909  CppAsString2(RELKIND_MATVIEW) ", "
910  CppAsString2(RELKIND_TOASTVALUE) ")",
912  PQfinish(conn);
913 
914  /* Reset datallowconn flag */
915  if (strcmp(datallowconn, "f") == 0)
916  PQclear(executeQueryOrDie(conn_template1,
917  "ALTER DATABASE %s ALLOW_CONNECTIONS = false",
919  }
920 
921  PQclear(dbres);
922 
923  PQfinish(conn_template1);
924 
925  check_ok();
926 }
#define CppAsString2(x)
Definition: c.h:342
int PQntuples(const PGresult *res)
Definition: fe-exec.c:3481
char * PQgetvalue(const PGresult *res, int tup_num, int field_num)
Definition: fe-exec.c:3876
int PQfnumber(const PGresult *res, const char *field_name)
Definition: fe-exec.c:3589
NameData datname
Definition: pg_database.h:35
bool datallowconn
Definition: pg_database.h:50
const char * quote_identifier(const char *ident)
Definition: ruleutils.c:12862

References check_ok(), ControlData::chkpnt_nxtmulti, ControlData::chkpnt_nxtxid, conn, connectToServer(), ClusterInfo::controldata, CppAsString2, datallowconn, datname, executeQueryOrDie(), new_cluster, old_cluster, PQclear(), PQfinish(), PQfnumber(), PQgetvalue(), PQntuples(), prep_status(), and quote_identifier().

Referenced by create_new_objects(), and prepare_new_globals().

◆ set_locale_and_encoding()

static void set_locale_and_encoding ( void  )
static

Definition at line 400 of file pg_upgrade.c.

401 {
402  PGconn *conn_new_template1;
403  char *datcollate_literal;
404  char *datctype_literal;
405  char *datlocale_literal = NULL;
407 
408  prep_status("Setting locale and encoding for new cluster");
409 
410  /* escape literals with respect to new cluster */
411  conn_new_template1 = connectToServer(&new_cluster, "template1");
412 
413  datcollate_literal = PQescapeLiteral(conn_new_template1,
414  locale->db_collate,
415  strlen(locale->db_collate));
416  datctype_literal = PQescapeLiteral(conn_new_template1,
417  locale->db_ctype,
418  strlen(locale->db_ctype));
419  if (locale->db_locale)
420  datlocale_literal = PQescapeLiteral(conn_new_template1,
421  locale->db_locale,
422  strlen(locale->db_locale));
423  else
424  datlocale_literal = pg_strdup("NULL");
425 
426  /* update template0 in new cluster */
428  PQclear(executeQueryOrDie(conn_new_template1,
429  "UPDATE pg_catalog.pg_database "
430  " SET encoding = %d, "
431  " datlocprovider = '%c', "
432  " datcollate = %s, "
433  " datctype = %s, "
434  " datlocale = %s "
435  " WHERE datname = 'template0' ",
436  locale->db_encoding,
437  locale->db_collprovider,
438  datcollate_literal,
439  datctype_literal,
440  datlocale_literal));
441  else if (GET_MAJOR_VERSION(new_cluster.major_version) >= 1500)
442  PQclear(executeQueryOrDie(conn_new_template1,
443  "UPDATE pg_catalog.pg_database "
444  " SET encoding = %d, "
445  " datlocprovider = '%c', "
446  " datcollate = %s, "
447  " datctype = %s, "
448  " daticulocale = %s "
449  " WHERE datname = 'template0' ",
450  locale->db_encoding,
451  locale->db_collprovider,
452  datcollate_literal,
453  datctype_literal,
454  datlocale_literal));
455  else
456  PQclear(executeQueryOrDie(conn_new_template1,
457  "UPDATE pg_catalog.pg_database "
458  " SET encoding = %d, "
459  " datcollate = %s, "
460  " datctype = %s "
461  " WHERE datname = 'template0' ",
462  locale->db_encoding,
463  datcollate_literal,
464  datctype_literal));
465 
466  PQfreemem(datcollate_literal);
467  PQfreemem(datctype_literal);
468  PQfreemem(datlocale_literal);
469 
470  PQfinish(conn_new_template1);
471 
472  check_ok();
473 }
void PQfreemem(void *ptr)
Definition: fe-exec.c:4032
char * PQescapeLiteral(PGconn *conn, const char *str, size_t len)
Definition: fe-exec.c:4304
char * pg_strdup(const char *in)
Definition: fe_memutils.c:85
static char * locale
Definition: initdb.c:140
DbLocaleInfo * template0
Definition: pg_upgrade.h:283

References check_ok(), connectToServer(), executeQueryOrDie(), GET_MAJOR_VERSION, locale, ClusterInfo::major_version, new_cluster, old_cluster, pg_strdup(), PQclear(), PQescapeLiteral(), PQfinish(), PQfreemem(), prep_status(), and ClusterInfo::template0.

Referenced by main().

◆ setup()

static void setup ( char *  argv0)
static

Definition at line 329 of file pg_upgrade.c.

330 {
331  /*
332  * make sure the user has a clean environment, otherwise, we may confuse
333  * libpq when we connect to one (or both) of the servers.
334  */
336 
337  /*
338  * In case the user hasn't specified the directory for the new binaries
339  * with -B, default to using the path of the currently executed pg_upgrade
340  * binary.
341  */
342  if (!new_cluster.bindir)
343  {
344  char exec_path[MAXPGPATH];
345 
346  if (find_my_exec(argv0, exec_path) < 0)
347  pg_fatal("%s: could not find own program executable", argv0);
348  /* Trim off program name and keep just path */
349  *last_dir_separator(exec_path) = '\0';
352  }
353 
355 
356  /* no postmasters should be running, except for a live check */
358  {
359  /*
360  * If we have a postmaster.pid file, try to start the server. If it
361  * starts, the pid file was stale, so stop the server. If it doesn't
362  * start, assume the server is running. If the pid file is left over
363  * from a server crash, this also allows any committed transactions
364  * stored in the WAL to be replayed so they are not lost, because WAL
365  * files are not transferred from old to new servers. We later check
366  * for a clean shutdown.
367  */
368  if (start_postmaster(&old_cluster, false))
369  stop_postmaster(false);
370  else
371  {
372  if (!user_opts.check)
373  pg_fatal("There seems to be a postmaster servicing the old cluster.\n"
374  "Please shutdown that postmaster and try again.");
375  else
376  user_opts.live_check = true;
377  }
378  }
379 
380  /* same goes for the new postmaster */
382  {
383  if (start_postmaster(&new_cluster, false))
384  stop_postmaster(false);
385  else
386  pg_fatal("There seems to be a postmaster servicing the new cluster.\n"
387  "Please shutdown that postmaster and try again.");
388  }
389 }
bool pid_lock_file_exists(const char *datadir)
Definition: exec.c:233
void verify_directories(void)
Definition: exec.c:263
int find_my_exec(const char *argv0, char *retpath)
Definition: exec.c:160
static char * argv0
Definition: pg_ctl.c:93
static char * exec_path
Definition: pg_ctl.c:88
void check_pghost_envvar(void)
Definition: server.c:369
char * last_dir_separator(const char *filename)
Definition: path.c:140
void canonicalize_path(char *path)
Definition: path.c:265
bool live_check
Definition: pg_upgrade.h:324
bool check
Definition: pg_upgrade.h:323

References argv0, ClusterInfo::bindir, canonicalize_path(), UserOpts::check, check_pghost_envvar(), exec_path, find_my_exec(), last_dir_separator(), UserOpts::live_check, MAXPGPATH, new_cluster, old_cluster, pg_fatal, pg_strdup(), ClusterInfo::pgdata, pid_lock_file_exists(), start_postmaster(), stop_postmaster(), user_opts, and verify_directories().

Referenced by main().

Variable Documentation

◆ new_cluster

◆ old_cluster

◆ os_info

◆ output_files

char* output_files[]
Initial value:
= {
NULL
}
#define SERVER_LOG_FILE
Definition: pg_upgrade.h:44

Definition at line 71 of file pg_upgrade.c.

Referenced by make_outputdirs().