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, bool *live_check)
 
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 59 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 675 of file pg_upgrade.c.

676 {
677  char old_path[MAXPGPATH];
678  char new_path[MAXPGPATH];
679 
680  remove_new_subdir(new_subdir, true);
681 
682  snprintf(old_path, sizeof(old_path), "%s/%s", old_cluster.pgdata, old_subdir);
683  snprintf(new_path, sizeof(new_path), "%s/%s", new_cluster.pgdata, new_subdir);
684 
685  prep_status("Copying old %s to new server", old_subdir);
686 
687  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
688 #ifndef WIN32
689  "cp -Rf \"%s\" \"%s\"",
690 #else
691  /* flags: everything, no confirm, quiet, overwrite read-only */
692  "xcopy /e /y /q /r \"%s\" \"%s\\\"",
693 #endif
694  old_path, new_path);
695 
696  check_ok();
697 }
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:2036
#define MAXPGPATH
ClusterInfo new_cluster
Definition: pg_upgrade.c:72
static void remove_new_subdir(const char *subdir, bool rmtopdir)
Definition: pg_upgrade.c:658
ClusterInfo old_cluster
Definition: pg_upgrade.c:71
#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:287

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 700 of file pg_upgrade.c.

701 {
702  /*
703  * Copy old commit logs to new data dir. pg_clog has been renamed to
704  * pg_xact in post-10 clusters.
705  */
707  "pg_clog" : "pg_xact",
709  "pg_clog" : "pg_xact");
710 
711  prep_status("Setting oldest XID for new cluster");
712  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
713  "\"%s/pg_resetwal\" -f -u %u \"%s\"",
716  check_ok();
717 
718  /* set the next transaction id and epoch of the new cluster */
719  prep_status("Setting next transaction ID and epoch for new cluster");
720  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
721  "\"%s/pg_resetwal\" -f -x %u \"%s\"",
724  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
725  "\"%s/pg_resetwal\" -f -e %u \"%s\"",
728  /* must reset commit timestamp limits also */
729  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
730  "\"%s/pg_resetwal\" -f -c %u,%u \"%s\"",
735  check_ok();
736 
737  /*
738  * If the old server is before the MULTIXACT_FORMATCHANGE_CAT_VER change
739  * (see pg_upgrade.h) and the new server is after, then we don't copy
740  * pg_multixact files, but we need to reset pg_control so that the new
741  * server doesn't attempt to read multis older than the cutoff value.
742  */
745  {
746  copy_subdir_files("pg_multixact/offsets", "pg_multixact/offsets");
747  copy_subdir_files("pg_multixact/members", "pg_multixact/members");
748 
749  prep_status("Setting next multixact ID and offset for new cluster");
750 
751  /*
752  * we preserve all files and contents, so we must preserve both "next"
753  * counters here and the oldest multi present on system.
754  */
755  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
756  "\"%s/pg_resetwal\" -O %u -m %u,%u \"%s\"",
762  check_ok();
763  }
765  {
766  /*
767  * Remove offsets/0000 file created by initdb that no longer matches
768  * the new multi-xid value. "members" starts at zero so no need to
769  * remove it.
770  */
771  remove_new_subdir("pg_multixact/offsets", false);
772 
773  prep_status("Setting oldest multixact ID in new cluster");
774 
775  /*
776  * We don't preserve files in this case, but it's important that the
777  * oldest multi is set to the latest value used by the old system, so
778  * that multixact.c returns the empty set for multis that might be
779  * present on disk. We set next multi to the value following that; it
780  * might end up wrapped around (i.e. 0) if the old cluster had
781  * next=MaxMultiXactId, but multixact.c can cope with that just fine.
782  */
783  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
784  "\"%s/pg_resetwal\" -m %u,%u \"%s\"",
789  check_ok();
790  }
791 
792  /* now reset the wal archives in the new cluster */
793  prep_status("Resetting WAL archives");
794  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
795  /* use timeline 1 to match controldata and no WAL history file */
796  "\"%s/pg_resetwal\" -l 00000001%s \"%s\"", new_cluster.bindir,
799  check_ok();
800 }
static void copy_subdir_files(const char *old_subdir, const char *new_subdir)
Definition: pg_upgrade.c:675
#define MULTIXACT_FORMATCHANGE_CAT_VER
Definition: pg_upgrade.h:116
#define GET_MAJOR_VERSION(v)
Definition: pg_upgrade.h:27
ControlData controldata
Definition: pg_upgrade.h:284
char * bindir
Definition: pg_upgrade.h:290
uint32 major_version
Definition: pg_upgrade.h:295
uint32 chkpnt_nxtxid
Definition: pg_upgrade.h:231
char nextxlogfile[25]
Definition: pg_upgrade.h:230
uint32 chkpnt_nxtmxoff
Definition: pg_upgrade.h:235
uint32 cat_ver
Definition: pg_upgrade.h:229
uint32 chkpnt_nxtmulti
Definition: pg_upgrade.h:234
uint32 chkpnt_oldstxid
Definition: pg_upgrade.h:237
uint32 chkpnt_nxtepoch
Definition: pg_upgrade.h:232
uint32 chkpnt_oldstMulti
Definition: pg_upgrade.h:236

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 927 of file pg_upgrade.c.

928 {
929  prep_status_progress("Restoring logical replication slots in the new cluster");
930 
931  for (int dbnum = 0; dbnum < old_cluster.dbarr.ndbs; dbnum++)
932  {
933  DbInfo *old_db = &old_cluster.dbarr.dbs[dbnum];
934  LogicalSlotInfoArr *slot_arr = &old_db->slot_arr;
935  PGconn *conn;
936  PQExpBuffer query;
937 
938  /* Skip this database if there are no slots */
939  if (slot_arr->nslots == 0)
940  continue;
941 
943  query = createPQExpBuffer();
944 
945  pg_log(PG_STATUS, "%s", old_db->db_name);
946 
947  for (int slotnum = 0; slotnum < slot_arr->nslots; slotnum++)
948  {
949  LogicalSlotInfo *slot_info = &slot_arr->slots[slotnum];
950 
951  /* Constructs a query for creating logical replication slots */
952  appendPQExpBuffer(query,
953  "SELECT * FROM "
954  "pg_catalog.pg_create_logical_replication_slot(");
955  appendStringLiteralConn(query, slot_info->slotname, conn);
956  appendPQExpBuffer(query, ", ");
957  appendStringLiteralConn(query, slot_info->plugin, conn);
958 
959  appendPQExpBuffer(query, ", false, %s, %s);",
960  slot_info->two_phase ? "true" : "false",
961  slot_info->failover ? "true" : "false");
962 
963  PQclear(executeQueryOrDie(conn, "%s", query->data));
964 
965  resetPQExpBuffer(query);
966  }
967 
968  PQfinish(conn);
969 
970  destroyPQExpBuffer(query);
971  }
972 
974  check_ok();
975 
976  return;
977 }
void PQfinish(PGconn *conn)
Definition: fe-connect.c:4888
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:269
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:55
void appendStringLiteralConn(PQExpBuffer buf, const char *str, PGconn *conn)
Definition: string_utils.c:293
DbInfoArr dbarr
Definition: pg_upgrade.h:286
DbInfo * dbs
Definition: pg_upgrade.h:217
LogicalSlotInfoArr slot_arr
Definition: pg_upgrade.h:199
char * db_name
Definition: pg_upgrade.h:195
LogicalSlotInfo * slots
Definition: pg_upgrade.h:170

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 534 of file pg_upgrade.c.

535 {
536  int dbnum;
537 
538  prep_status_progress("Restoring database schemas in the new cluster");
539 
540  /*
541  * We cannot process the template1 database concurrently with others,
542  * because when it's transiently dropped, connection attempts would fail.
543  * So handle it in a separate non-parallelized pass.
544  */
545  for (dbnum = 0; dbnum < old_cluster.dbarr.ndbs; dbnum++)
546  {
547  char sql_file_name[MAXPGPATH],
548  log_file_name[MAXPGPATH];
549  DbInfo *old_db = &old_cluster.dbarr.dbs[dbnum];
550  const char *create_opts;
551 
552  /* Process only template1 in this pass */
553  if (strcmp(old_db->db_name, "template1") != 0)
554  continue;
555 
556  pg_log(PG_STATUS, "%s", old_db->db_name);
557  snprintf(sql_file_name, sizeof(sql_file_name), DB_DUMP_FILE_MASK, old_db->db_oid);
558  snprintf(log_file_name, sizeof(log_file_name), DB_DUMP_LOG_FILE_MASK, old_db->db_oid);
559 
560  /*
561  * template1 database will already exist in the target installation,
562  * so tell pg_restore to drop and recreate it; otherwise we would fail
563  * to propagate its database-level properties.
564  */
565  create_opts = "--clean --create";
566 
567  exec_prog(log_file_name,
568  NULL,
569  true,
570  true,
571  "\"%s/pg_restore\" %s %s --exit-on-error --verbose "
572  "--transaction-size=%d "
573  "--dbname postgres \"%s/%s\"",
576  create_opts,
579  sql_file_name);
580 
581  break; /* done once we've processed template1 */
582  }
583 
584  for (dbnum = 0; dbnum < old_cluster.dbarr.ndbs; dbnum++)
585  {
586  char sql_file_name[MAXPGPATH],
587  log_file_name[MAXPGPATH];
588  DbInfo *old_db = &old_cluster.dbarr.dbs[dbnum];
589  const char *create_opts;
590  int txn_size;
591 
592  /* Skip template1 in this pass */
593  if (strcmp(old_db->db_name, "template1") == 0)
594  continue;
595 
596  pg_log(PG_STATUS, "%s", old_db->db_name);
597  snprintf(sql_file_name, sizeof(sql_file_name), DB_DUMP_FILE_MASK, old_db->db_oid);
598  snprintf(log_file_name, sizeof(log_file_name), DB_DUMP_LOG_FILE_MASK, old_db->db_oid);
599 
600  /*
601  * postgres database will already exist in the target installation, so
602  * tell pg_restore to drop and recreate it; otherwise we would fail to
603  * propagate its database-level properties.
604  */
605  if (strcmp(old_db->db_name, "postgres") == 0)
606  create_opts = "--clean --create";
607  else
608  create_opts = "--create";
609 
610  /*
611  * In parallel mode, reduce the --transaction-size of each restore job
612  * so that the total number of locks that could be held across all the
613  * jobs stays in bounds.
614  */
615  txn_size = RESTORE_TRANSACTION_SIZE;
616  if (user_opts.jobs > 1)
617  {
618  txn_size /= user_opts.jobs;
619  /* Keep some sanity if -j is huge */
620  txn_size = Max(txn_size, 10);
621  }
622 
623  parallel_exec_prog(log_file_name,
624  NULL,
625  "\"%s/pg_restore\" %s %s --exit-on-error --verbose "
626  "--transaction-size=%d "
627  "--dbname template1 \"%s/%s\"",
630  create_opts,
631  txn_size,
633  sql_file_name);
634  }
635 
636  /* reap all children */
637  while (reap_child(true) == true)
638  ;
639 
641  check_ok();
642 
643  /*
644  * We don't have minmxids for databases or relations in pre-9.3 clusters,
645  * so set those after we have restored the schema.
646  */
648  set_frozenxids(true);
649 
650  /* update new_cluster info now that we have objects in the databases */
652 }
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:998
void get_db_rel_and_slot_infos(ClusterInfo *cluster, bool live_check)
Definition: info.c:280
static void set_frozenxids(bool minmxid_only)
Definition: pg_upgrade.c:825
#define RESTORE_TRANSACTION_SIZE
Definition: pg_upgrade.c:59
#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:194
char * dumpdir
Definition: pg_upgrade.h:313
int jobs
Definition: pg_upgrade.h:328

References ClusterInfo::bindir, check_ok(), cluster_conn_opts(), 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(), 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, 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 88 of file pg_upgrade.c.

89 {
90  char *deletion_script_file_name = NULL;
91  bool live_check = false;
92 
93  /*
94  * pg_upgrade doesn't currently use common/logging.c, but initialize it
95  * anyway because we might call common code that does.
96  */
97  pg_logging_init(argv[0]);
98  set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_upgrade"));
99 
100  /* Set default restrictive mask until new cluster permissions are read */
101  umask(PG_MODE_MASK_OWNER);
102 
103  parseCommandLine(argc, argv);
104 
106 
109 
110  /*
111  * Set mask based on PGDATA permissions, needed for the creation of the
112  * output directories with correct permissions.
113  */
115  pg_fatal("could not read permissions of directory \"%s\": %m",
117 
118  umask(pg_mode_mask);
119 
120  /*
121  * This needs to happen after adjusting the data directory of the new
122  * cluster in adjust_data_dir().
123  */
125 
126  setup(argv[0], &live_check);
127 
128  output_check_banner(live_check);
129 
131 
132  get_sock_dir(&old_cluster, live_check);
133  get_sock_dir(&new_cluster, false);
134 
135  check_cluster_compatibility(live_check);
136 
137  check_and_dump_old_cluster(live_check);
138 
139 
140  /* -- NEW -- */
142 
145 
147  "\n"
148  "Performing Upgrade\n"
149  "------------------");
150 
152 
154 
155  stop_postmaster(false);
156 
157  /*
158  * Destructive Changes to New Cluster
159  */
160 
162 
163  /* New now using xids of the old system */
164 
165  /* -- NEW -- */
167 
169 
171 
172  stop_postmaster(false);
173 
174  /*
175  * Most failures happen in create_new_objects(), which has completed at
176  * this point. We do this here because it is just before linking, which
177  * will link the old and new cluster data files, preventing the old
178  * cluster from being safely started once the new cluster is started.
179  */
182 
185 
186  /*
187  * Assuming OIDs are only used in system tables, there is no need to
188  * restore the OID counter because we have not transferred any OIDs from
189  * the old system, but we do it anyway just in case. We do it late here
190  * because there is no need to have the schema load use new oids.
191  */
192  prep_status("Setting next OID for new cluster");
193  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
194  "\"%s/pg_resetwal\" -o %u \"%s\"",
197  check_ok();
198 
199  /*
200  * Migrate the logical slots to the new cluster. Note that we need to do
201  * this after resetting WAL because otherwise the required WAL would be
202  * removed and slots would become unusable. There is a possibility that
203  * background processes might generate some WAL before we could create the
204  * slots in the new cluster but we can ignore that WAL as that won't be
205  * required downstream.
206  */
208  {
211  stop_postmaster(false);
212  }
213 
214  if (user_opts.do_sync)
215  {
216  prep_status("Sync data directory to disk");
217  exec_prog(UTILITY_LOG_FILE, NULL, true, true,
218  "\"%s/initdb\" --sync-only \"%s\" --sync-method %s",
222  check_ok();
223  }
224 
225  create_script_for_old_cluster_deletion(&deletion_script_file_name);
226 
228 
230  "\n"
231  "Upgrade Complete\n"
232  "----------------");
233 
234  output_completion_banner(deletion_script_file_name);
235 
236  pg_free(deletion_script_file_name);
237 
239 
240  return 0;
241 }
#define PG_TEXTDOMAIN(domain)
Definition: c.h:1214
void output_check_banner(bool live_check)
Definition: check.c:558
void check_cluster_versions(void)
Definition: check.c:786
void check_cluster_compatibility(bool live_check)
Definition: check.c:829
void check_and_dump_old_cluster(bool live_check)
Definition: check.c:576
void issue_warnings_and_set_wal_level(void)
Definition: check.c:731
void check_new_cluster(void)
Definition: check.c:676
void report_clusters_compatible(void)
Definition: check.c:712
void create_script_for_old_cluster_deletion(char **deletion_script_file_name)
Definition: check.c:904
void output_completion_banner(char *deletion_script_file_name)
Definition: check.c:752
void set_pglocale_pgservice(const char *argv0, const char *app)
Definition: exec.c:448
void disable_old_cluster(void)
Definition: controldata.c:711
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:740
void pg_logging_init(const char *argv0)
Definition: logging.c:83
#define pg_fatal(...)
static void adjust_data_dir(void)
Definition: pg_ctl.c:2113
static pid_t start_postmaster(void)
Definition: pg_ctl.c:439
static void create_logical_replication_slots(void)
Definition: pg_upgrade.c:927
static void make_outputdirs(char *pgdata)
Definition: pg_upgrade.c:249
static void prepare_new_cluster(void)
Definition: pg_upgrade.c:482
static void create_new_objects(void)
Definition: pg_upgrade.c:534
static void copy_xact_xlog_xid(void)
Definition: pg_upgrade.c:700
static void set_locale_and_encoding(void)
Definition: pg_upgrade.c:405
static void setup(char *argv0, bool *live_check)
Definition: pg_upgrade.c:334
static void prepare_new_globals(void)
Definition: pg_upgrade.c:512
void transfer_all_new_tablespaces(DbInfoArr *old_db_arr, DbInfoArr *new_db_arr, char *old_pgdata, char *new_pgdata)
Definition: relfilenumber.c:29
void cleanup_output_dirs(void)
Definition: util.c:63
@ TRANSFER_MODE_LINK
Definition: pg_upgrade.h:260
@ PG_REPORT
Definition: pg_upgrade.h:271
void stop_postmaster(bool in_atexit)
Definition: server.c:342
void get_restricted_token(void)
void get_sock_dir(ClusterInfo *cluster, bool live_check)
Definition: option.c:473
void parseCommandLine(int argc, char *argv[])
Definition: option.c:39
uint32 chkpnt_nxtoid
Definition: pg_upgrade.h:233
char * sync_method
Definition: pg_upgrade.h:330
bool do_sync
Definition: pg_upgrade.h:326
transferMode transfer_mode
Definition: pg_upgrade.h:327

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 249 of file pg_upgrade.c.

250 {
251  FILE *fp;
252  char **filename;
253  time_t run_time = time(NULL);
254  char filename_path[MAXPGPATH];
255  char timebuf[128];
256  struct timeval time;
257  time_t tt;
258  int len;
259 
260  log_opts.rootdir = (char *) pg_malloc0(MAXPGPATH);
261  len = snprintf(log_opts.rootdir, MAXPGPATH, "%s/%s", pgdata, BASE_OUTPUTDIR);
262  if (len >= MAXPGPATH)
263  pg_fatal("directory path for new cluster is too long");
264 
265  /* BASE_OUTPUTDIR/$timestamp/ */
266  gettimeofday(&time, NULL);
267  tt = (time_t) time.tv_sec;
268  strftime(timebuf, sizeof(timebuf), "%Y%m%dT%H%M%S", localtime(&tt));
269  /* append milliseconds */
270  snprintf(timebuf + strlen(timebuf), sizeof(timebuf) - strlen(timebuf),
271  ".%03d", (int) (time.tv_usec / 1000));
272  log_opts.basedir = (char *) pg_malloc0(MAXPGPATH);
274  timebuf);
275  if (len >= MAXPGPATH)
276  pg_fatal("directory path for new cluster is too long");
277 
278  /* BASE_OUTPUTDIR/$timestamp/dump/ */
279  log_opts.dumpdir = (char *) pg_malloc0(MAXPGPATH);
281  timebuf, DUMP_OUTPUTDIR);
282  if (len >= MAXPGPATH)
283  pg_fatal("directory path for new cluster is too long");
284 
285  /* BASE_OUTPUTDIR/$timestamp/log/ */
286  log_opts.logdir = (char *) pg_malloc0(MAXPGPATH);
288  timebuf, LOG_OUTPUTDIR);
289  if (len >= MAXPGPATH)
290  pg_fatal("directory path for new cluster is too long");
291 
292  /*
293  * Ignore the error case where the root path exists, as it is kept the
294  * same across runs.
295  */
296  if (mkdir(log_opts.rootdir, pg_dir_create_mode) < 0 && errno != EEXIST)
297  pg_fatal("could not create directory \"%s\": %m", log_opts.rootdir);
299  pg_fatal("could not create directory \"%s\": %m", log_opts.basedir);
301  pg_fatal("could not create directory \"%s\": %m", log_opts.dumpdir);
303  pg_fatal("could not create directory \"%s\": %m", log_opts.logdir);
304 
305  len = snprintf(filename_path, sizeof(filename_path), "%s/%s",
307  if (len >= sizeof(filename_path))
308  pg_fatal("directory path for new cluster is too long");
309 
310  if ((log_opts.internal = fopen_priv(filename_path, "a")) == NULL)
311  pg_fatal("could not open log file \"%s\": %m", filename_path);
312 
313  /* label start of upgrade in logfiles */
314  for (filename = output_files; *filename != NULL; filename++)
315  {
316  len = snprintf(filename_path, sizeof(filename_path), "%s/%s",
318  if (len >= sizeof(filename_path))
319  pg_fatal("directory path for new cluster is too long");
320  if ((fp = fopen_priv(filename_path, "a")) == NULL)
321  pg_fatal("could not write to log file \"%s\": %m", filename_path);
322 
323  fprintf(fp,
324  "-----------------------------------------------------------------\n"
325  " pg_upgrade run on %s"
326  "-----------------------------------------------------------------\n\n",
327  ctime(&run_time));
328  fclose(fp);
329  }
330 }
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:75
#define LOG_OUTPUTDIR
Definition: pg_upgrade.h:40
#define fopen_priv(path, mode)
Definition: pg_upgrade.h:420
#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:311
FILE * internal
Definition: pg_upgrade.h:307
char * basedir
Definition: pg_upgrade.h:312
char * logdir
Definition: pg_upgrade.h:314
#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 482 of file pg_upgrade.c.

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

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 512 of file pg_upgrade.c.

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

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 658 of file pg_upgrade.c.

659 {
660  char new_path[MAXPGPATH];
661 
662  prep_status("Deleting files from new %s", subdir);
663 
664  snprintf(new_path, sizeof(new_path), "%s/%s", new_cluster.pgdata, subdir);
665  if (!rmtree(new_path, rmtopdir))
666  pg_fatal("could not delete directory \"%s\"", new_path);
667 
668  check_ok();
669 }
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 825 of file pg_upgrade.c.

826 {
827  int dbnum;
828  PGconn *conn,
829  *conn_template1;
830  PGresult *dbres;
831  int ntups;
832  int i_datname;
833  int i_datallowconn;
834 
835  if (!minmxid_only)
836  prep_status("Setting frozenxid and minmxid counters in new cluster");
837  else
838  prep_status("Setting minmxid counter in new cluster");
839 
840  conn_template1 = connectToServer(&new_cluster, "template1");
841 
842  if (!minmxid_only)
843  /* set pg_database.datfrozenxid */
844  PQclear(executeQueryOrDie(conn_template1,
845  "UPDATE pg_catalog.pg_database "
846  "SET datfrozenxid = '%u'",
848 
849  /* set pg_database.datminmxid */
850  PQclear(executeQueryOrDie(conn_template1,
851  "UPDATE pg_catalog.pg_database "
852  "SET datminmxid = '%u'",
854 
855  /* get database names */
856  dbres = executeQueryOrDie(conn_template1,
857  "SELECT datname, datallowconn "
858  "FROM pg_catalog.pg_database");
859 
860  i_datname = PQfnumber(dbres, "datname");
861  i_datallowconn = PQfnumber(dbres, "datallowconn");
862 
863  ntups = PQntuples(dbres);
864  for (dbnum = 0; dbnum < ntups; dbnum++)
865  {
866  char *datname = PQgetvalue(dbres, dbnum, i_datname);
867  char *datallowconn = PQgetvalue(dbres, dbnum, i_datallowconn);
868 
869  /*
870  * We must update databases where datallowconn = false, e.g.
871  * template0, because autovacuum increments their datfrozenxids,
872  * relfrozenxids, and relminmxid even if autovacuum is turned off, and
873  * even though all the data rows are already frozen. To enable this,
874  * we temporarily change datallowconn.
875  */
876  if (strcmp(datallowconn, "f") == 0)
877  PQclear(executeQueryOrDie(conn_template1,
878  "ALTER DATABASE %s ALLOW_CONNECTIONS = true",
880 
882 
883  if (!minmxid_only)
884  /* set pg_class.relfrozenxid */
886  "UPDATE pg_catalog.pg_class "
887  "SET relfrozenxid = '%u' "
888  /* only heap, materialized view, and TOAST are vacuumed */
889  "WHERE relkind IN ("
890  CppAsString2(RELKIND_RELATION) ", "
891  CppAsString2(RELKIND_MATVIEW) ", "
892  CppAsString2(RELKIND_TOASTVALUE) ")",
894 
895  /* set pg_class.relminmxid */
897  "UPDATE pg_catalog.pg_class "
898  "SET relminmxid = '%u' "
899  /* only heap, materialized view, and TOAST are vacuumed */
900  "WHERE relkind IN ("
901  CppAsString2(RELKIND_RELATION) ", "
902  CppAsString2(RELKIND_MATVIEW) ", "
903  CppAsString2(RELKIND_TOASTVALUE) ")",
905  PQfinish(conn);
906 
907  /* Reset datallowconn flag */
908  if (strcmp(datallowconn, "f") == 0)
909  PQclear(executeQueryOrDie(conn_template1,
910  "ALTER DATABASE %s ALLOW_CONNECTIONS = false",
912  }
913 
914  PQclear(dbres);
915 
916  PQfinish(conn_template1);
917 
918  check_ok();
919 }
#define CppAsString2(x)
Definition: c.h:327
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:12596

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 405 of file pg_upgrade.c.

406 {
407  PGconn *conn_new_template1;
408  char *datcollate_literal;
409  char *datctype_literal;
410  char *datlocale_literal = NULL;
412 
413  prep_status("Setting locale and encoding for new cluster");
414 
415  /* escape literals with respect to new cluster */
416  conn_new_template1 = connectToServer(&new_cluster, "template1");
417 
418  datcollate_literal = PQescapeLiteral(conn_new_template1,
419  locale->db_collate,
420  strlen(locale->db_collate));
421  datctype_literal = PQescapeLiteral(conn_new_template1,
422  locale->db_ctype,
423  strlen(locale->db_ctype));
424  if (locale->db_locale)
425  datlocale_literal = PQescapeLiteral(conn_new_template1,
426  locale->db_locale,
427  strlen(locale->db_locale));
428  else
429  datlocale_literal = pg_strdup("NULL");
430 
431  /* update template0 in new cluster */
433  PQclear(executeQueryOrDie(conn_new_template1,
434  "UPDATE pg_catalog.pg_database "
435  " SET encoding = %d, "
436  " datlocprovider = '%c', "
437  " datcollate = %s, "
438  " datctype = %s, "
439  " datlocale = %s "
440  " WHERE datname = 'template0' ",
441  locale->db_encoding,
442  locale->db_collprovider,
443  datcollate_literal,
444  datctype_literal,
445  datlocale_literal));
446  else if (GET_MAJOR_VERSION(new_cluster.major_version) >= 1500)
447  PQclear(executeQueryOrDie(conn_new_template1,
448  "UPDATE pg_catalog.pg_database "
449  " SET encoding = %d, "
450  " datlocprovider = '%c', "
451  " datcollate = %s, "
452  " datctype = %s, "
453  " daticulocale = %s "
454  " WHERE datname = 'template0' ",
455  locale->db_encoding,
456  locale->db_collprovider,
457  datcollate_literal,
458  datctype_literal,
459  datlocale_literal));
460  else
461  PQclear(executeQueryOrDie(conn_new_template1,
462  "UPDATE pg_catalog.pg_database "
463  " SET encoding = %d, "
464  " datcollate = %s, "
465  " datctype = %s "
466  " WHERE datname = 'template0' ",
467  locale->db_encoding,
468  datcollate_literal,
469  datctype_literal));
470 
471  PQfreemem(datcollate_literal);
472  PQfreemem(datctype_literal);
473  PQfreemem(datlocale_literal);
474 
475  PQfinish(conn_new_template1);
476 
477  check_ok();
478 }
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:285

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,
bool live_check 
)
static

Definition at line 334 of file pg_upgrade.c.

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

References argv0, ClusterInfo::bindir, canonicalize_path(), UserOpts::check, check_pghost_envvar(), exec_path, find_my_exec(), last_dir_separator(), 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 75 of file pg_upgrade.c.

Referenced by make_outputdirs().