6 * Copyright (c) 2010-2014, PostgreSQL Global Development Group
7 * contrib/pg_upgrade/pg_upgrade.c
11 * To simplify the upgrade process, we force certain system values to be
12 * identical between old and new clusters:
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.
18 * While pg_class.oid and pg_class.relfilenode are initially the same
19 * in a cluster, they can diverge due to CLUSTER, REINDEX, or VACUUM
20 * FULL. In the new cluster, pg_class.oid and pg_class.relfilenode will
21 * be the same and will match the old pg_class.oid value. Because of
22 * this, old/new pg_class.relfilenode values will not match if CLUSTER,
23 * REINDEX, or VACUUM FULL have been performed in the old cluster.
25 * We control all assignments of pg_type.oid because these oids are stored
26 * in user composite type values.
28 * We control all assignments of pg_enum.oid because these oids are stored
29 * in user tables as enum values.
31 * We control all assignments of pg_authid.oid because these oids are stored
32 * in pg_largeobject_metadata.
37 #include "postgres_fe.h"
39 #include "pg_upgrade.h"
41 #ifdef HAVE_LANGINFO_H
45 static void prepare_new_cluster(void);
46 static void prepare_new_databases(void);
47 static void create_new_objects(void);
48 static void copy_clog_xlog_xid(void);
49 static void set_frozenxids(void);
50 static void setup(char *argv0, bool *live_check);
51 static void cleanup(void);
53 ClusterInfo old_cluster,
57 char *output_files[] = {
60 /* unique file for pg_ctl start */
61 SERVER_START_LOG_FILE,
70 main(int argc, char **argv)
72 char *sequence_script_file_name = NULL;
73 char *analyze_script_file_name = NULL;
74 char *deletion_script_file_name = NULL;
75 bool live_check = false;
77 parseCommandLine(argc, argv);
79 adjust_data_dir(&old_cluster);
80 adjust_data_dir(&new_cluster);
82 setup(argv[0], &live_check);
84 output_check_banner(live_check);
86 check_cluster_versions();
88 get_sock_dir(&old_cluster, live_check);
89 get_sock_dir(&new_cluster, false);
91 check_cluster_compatibility(live_check);
93 check_and_dump_old_cluster(live_check, &sequence_script_file_name);
97 start_postmaster(&new_cluster, true);
100 report_clusters_compatible();
102 pg_log(PG_REPORT, "\nPerforming Upgrade\n");
103 pg_log(PG_REPORT, "------------------\n");
105 prepare_new_cluster();
107 stop_postmaster(false);
110 * Destructive Changes to New Cluster
113 copy_clog_xlog_xid();
115 /* New now using xids of the old system */
118 start_postmaster(&new_cluster, true);
120 prepare_new_databases();
122 create_new_objects();
124 stop_postmaster(false);
127 * Most failures happen in create_new_objects(), which has completed at
128 * this point. We do this here because it is just before linking, which
129 * will link the old and new cluster data files, preventing the old
130 * cluster from being safely started once the new cluster is started.
132 if (user_opts.transfer_mode == TRANSFER_MODE_LINK)
133 disable_old_cluster();
135 transfer_all_new_tablespaces(&old_cluster.dbarr, &new_cluster.dbarr,
136 old_cluster.pgdata, new_cluster.pgdata);
139 * Assuming OIDs are only used in system tables, there is no need to
140 * restore the OID counter because we have not transferred any OIDs from
141 * the old system, but we do it anyway just in case. We do it late here
142 * because there is no need to have the schema load use new oids.
144 prep_status("Setting next OID for new cluster");
145 exec_prog(UTILITY_LOG_FILE, NULL, true,
146 "\"%s/pg_resetxlog\" -o %u \"%s\"",
147 new_cluster.bindir, old_cluster.controldata.chkpnt_nxtoid,
151 prep_status("Sync data directory to disk");
152 exec_prog(UTILITY_LOG_FILE, NULL, true,
153 "\"%s/initdb\" --sync-only \"%s\"", new_cluster.bindir,
157 create_script_for_cluster_analyze(&analyze_script_file_name);
158 create_script_for_old_cluster_deletion(&deletion_script_file_name);
160 issue_warnings(sequence_script_file_name);
162 pg_log(PG_REPORT, "\nUpgrade Complete\n");
163 pg_log(PG_REPORT, "----------------\n");
165 output_completion_banner(analyze_script_file_name,
166 deletion_script_file_name);
168 pg_free(analyze_script_file_name);
169 pg_free(deletion_script_file_name);
170 pg_free(sequence_script_file_name);
179 setup(char *argv0, bool *live_check)
181 char exec_path[MAXPGPATH]; /* full path to my executable */
184 * make sure the user has a clean environment, otherwise, we may confuse
185 * libpq when we connect to one (or both) of the servers.
187 check_pghost_envvar();
189 verify_directories();
191 /* no postmasters should be running, except for a live check */
192 if (pid_lock_file_exists(old_cluster.pgdata))
195 * If we have a postmaster.pid file, try to start the server. If it
196 * starts, the pid file was stale, so stop the server. If it doesn't
197 * start, assume the server is running. If the pid file is left over
198 * from a server crash, this also allows any committed transactions
199 * stored in the WAL to be replayed so they are not lost, because WAL
200 * files are not transfered from old to new servers.
202 if (start_postmaster(&old_cluster, false))
203 stop_postmaster(false);
206 if (!user_opts.check)
207 pg_fatal("There seems to be a postmaster servicing the old cluster.\n"
208 "Please shutdown that postmaster and try again.\n");
214 /* same goes for the new postmaster */
215 if (pid_lock_file_exists(new_cluster.pgdata))
217 if (start_postmaster(&new_cluster, false))
218 stop_postmaster(false);
220 pg_fatal("There seems to be a postmaster servicing the new cluster.\n"
221 "Please shutdown that postmaster and try again.\n");
224 /* get path to pg_upgrade executable */
225 if (find_my_exec(argv0, exec_path) < 0)
226 pg_fatal("Could not get path name to pg_upgrade: %s\n", getErrorText(errno));
228 /* Trim off program name and keep just path */
229 *last_dir_separator(exec_path) = '\0';
230 canonicalize_path(exec_path);
231 os_info.exec_path = pg_strdup(exec_path);
236 prepare_new_cluster(void)
239 * It would make more sense to freeze after loading the schema, but that
240 * would cause us to lose the frozenids restored by the load. We use
241 * --analyze so autovacuum doesn't update statistics later
243 prep_status("Analyzing all rows in the new cluster");
244 exec_prog(UTILITY_LOG_FILE, NULL, true,
245 "\"%s/vacuumdb\" %s --all --analyze %s",
246 new_cluster.bindir, cluster_conn_opts(&new_cluster),
247 log_opts.verbose ? "--verbose" : "");
251 * We do freeze after analyze so pg_statistic is also frozen. template0 is
252 * not frozen here, but data rows were frozen by initdb, and we set its
253 * datfrozenxid and relfrozenxids later to match the new xid counter
256 prep_status("Freezing all rows on the new cluster");
257 exec_prog(UTILITY_LOG_FILE, NULL, true,
258 "\"%s/vacuumdb\" %s --all --freeze %s",
259 new_cluster.bindir, cluster_conn_opts(&new_cluster),
260 log_opts.verbose ? "--verbose" : "");
263 get_pg_database_relfilenode(&new_cluster);
268 prepare_new_databases(void)
271 * We set autovacuum_freeze_max_age to its maximum value so autovacuum
272 * does not launch here and delete clog files, before the frozen xids are
278 prep_status("Restoring global objects in the new cluster");
281 * Install support functions in the global-object restore database to
282 * preserve pg_authid.oid. pg_dumpall uses 'template0' as its template
283 * database so objects we add into 'template1' are not propogated. They
284 * are removed on pg_upgrade exit.
286 install_support_functions_in_new_db("template1");
289 * We have to create the databases first so we can install support
290 * functions in all the other databases. Ideally we could create the
291 * support functions in template1 but pg_dumpall creates database using
292 * the template0 template.
294 exec_prog(UTILITY_LOG_FILE, NULL, true,
295 "\"%s/psql\" " EXEC_PSQL_ARGS " %s -f \"%s\"",
296 new_cluster.bindir, cluster_conn_opts(&new_cluster),
300 /* we load this to get a current list of databases */
301 get_db_and_rel_infos(&new_cluster);
306 create_new_objects(void)
310 prep_status("Adding support functions to new cluster");
313 * Technically, we only need to install these support functions in new
314 * databases that also exist in the old cluster, but for completeness we
315 * process all new databases.
317 for (dbnum = 0; dbnum < new_cluster.dbarr.ndbs; dbnum++)
319 DbInfo *new_db = &new_cluster.dbarr.dbs[dbnum];
321 /* skip db we already installed */
322 if (strcmp(new_db->db_name, "template1") != 0)
323 install_support_functions_in_new_db(new_db->db_name);
327 prep_status("Restoring database schemas in the new cluster\n");
329 for (dbnum = 0; dbnum < old_cluster.dbarr.ndbs; dbnum++)
331 char sql_file_name[MAXPGPATH],
332 log_file_name[MAXPGPATH];
333 DbInfo *old_db = &old_cluster.dbarr.dbs[dbnum];
335 pg_log(PG_STATUS, "%s", old_db->db_name);
336 snprintf(sql_file_name, sizeof(sql_file_name), DB_DUMP_FILE_MASK, old_db->db_oid);
337 snprintf(log_file_name, sizeof(log_file_name), DB_DUMP_LOG_FILE_MASK, old_db->db_oid);
340 * pg_dump only produces its output at the end, so there is little
341 * parallelism if using the pipe.
343 parallel_exec_prog(log_file_name,
345 "\"%s/pg_restore\" %s --exit-on-error --verbose --dbname \"%s\" \"%s\"",
347 cluster_conn_opts(&new_cluster),
352 /* reap all children */
353 while (reap_child(true) == true)
356 end_progress_output();
359 /* regenerate now that we have objects in the databases */
360 get_db_and_rel_infos(&new_cluster);
362 uninstall_support_functions_from_new_cluster();
366 * Delete the given subdirectory contents from the new cluster
369 remove_new_subdir(char *subdir, bool rmtopdir)
371 char new_path[MAXPGPATH];
373 prep_status("Deleting files from new %s", subdir);
375 snprintf(new_path, sizeof(new_path), "%s/%s", new_cluster.pgdata, subdir);
376 if (!rmtree(new_path, rmtopdir))
377 pg_fatal("could not delete directory \"%s\"\n", new_path);
383 * Copy the files from the old cluster into it
386 copy_subdir_files(char *subdir)
388 char old_path[MAXPGPATH];
389 char new_path[MAXPGPATH];
391 remove_new_subdir(subdir, true);
393 snprintf(old_path, sizeof(old_path), "%s/%s", old_cluster.pgdata, subdir);
394 snprintf(new_path, sizeof(new_path), "%s/%s", new_cluster.pgdata, subdir);
396 prep_status("Copying old %s to new server", subdir);
398 exec_prog(UTILITY_LOG_FILE, NULL, true,
400 "cp -Rf \"%s\" \"%s\"",
402 /* flags: everything, no confirm, quiet, overwrite read-only */
403 "xcopy /e /y /q /r \"%s\" \"%s\\\"",
411 copy_clog_xlog_xid(void)
413 /* copy old commit logs to new data dir */
414 copy_subdir_files("pg_clog");
416 /* set the next transaction id of the new cluster */
417 prep_status("Setting next transaction ID for new cluster");
418 exec_prog(UTILITY_LOG_FILE, NULL, true,
419 "\"%s/pg_resetxlog\" -f -x %u \"%s\"",
420 new_cluster.bindir, old_cluster.controldata.chkpnt_nxtxid,
425 * If the old server is before the MULTIXACT_FORMATCHANGE_CAT_VER change
426 * (see pg_upgrade.h) and the new server is after, then we don't copy
427 * pg_multixact files, but we need to reset pg_control so that the new
428 * server doesn't attempt to read multis older than the cutoff value.
430 if (old_cluster.controldata.cat_ver >= MULTIXACT_FORMATCHANGE_CAT_VER &&
431 new_cluster.controldata.cat_ver >= MULTIXACT_FORMATCHANGE_CAT_VER)
433 copy_subdir_files("pg_multixact/offsets");
434 copy_subdir_files("pg_multixact/members");
436 prep_status("Setting next multixact ID and offset for new cluster");
439 * we preserve all files and contents, so we must preserve both "next"
440 * counters here and the oldest multi present on system.
442 exec_prog(UTILITY_LOG_FILE, NULL, true,
443 "\"%s/pg_resetxlog\" -O %u -m %u,%u \"%s\"",
445 old_cluster.controldata.chkpnt_nxtmxoff,
446 old_cluster.controldata.chkpnt_nxtmulti,
447 old_cluster.controldata.chkpnt_oldstMulti,
451 else if (new_cluster.controldata.cat_ver >= MULTIXACT_FORMATCHANGE_CAT_VER)
454 * Remove offsets/0000 file created by initdb that no longer matches
455 * the new multi-xid value. "members" starts at zero so no need to
458 remove_new_subdir("pg_multixact/offsets", false);
460 prep_status("Setting oldest multixact ID on new cluster");
463 * We don't preserve files in this case, but it's important that the
464 * oldest multi is set to the latest value used by the old system, so
465 * that multixact.c returns the empty set for multis that might be
466 * present on disk. We set next multi to the value following that; it
467 * might end up wrapped around (i.e. 0) if the old cluster had
468 * next=MaxMultiXactId, but multixact.c can cope with that just fine.
470 exec_prog(UTILITY_LOG_FILE, NULL, true,
471 "\"%s/pg_resetxlog\" -m %u,%u \"%s\"",
473 old_cluster.controldata.chkpnt_nxtmulti + 1,
474 old_cluster.controldata.chkpnt_nxtmulti,
479 /* now reset the wal archives in the new cluster */
480 prep_status("Resetting WAL archives");
481 exec_prog(UTILITY_LOG_FILE, NULL, true,
482 "\"%s/pg_resetxlog\" -l %s \"%s\"", new_cluster.bindir,
483 old_cluster.controldata.nextxlogfile,
492 * We have frozen all xids, so set relfrozenxid and datfrozenxid
493 * to be the old cluster's xid counter, which we just set in the new
494 * cluster. User-table frozenxid values will be set by pg_dump
495 * --binary-upgrade, but objects not set by the pg_dump must have
496 * proper frozen counters.
510 prep_status("Setting frozenxid counters in new cluster");
512 conn_template1 = connectToServer(&new_cluster, "template1");
514 /* set pg_database.datfrozenxid */
515 PQclear(executeQueryOrDie(conn_template1,
516 "UPDATE pg_catalog.pg_database "
517 "SET datfrozenxid = '%u'",
518 old_cluster.controldata.chkpnt_nxtxid));
520 /* get database names */
521 dbres = executeQueryOrDie(conn_template1,
522 "SELECT datname, datallowconn "
523 "FROM pg_catalog.pg_database");
525 i_datname = PQfnumber(dbres, "datname");
526 i_datallowconn = PQfnumber(dbres, "datallowconn");
528 ntups = PQntuples(dbres);
529 for (dbnum = 0; dbnum < ntups; dbnum++)
531 char *datname = PQgetvalue(dbres, dbnum, i_datname);
532 char *datallowconn = PQgetvalue(dbres, dbnum, i_datallowconn);
535 * We must update databases where datallowconn = false, e.g.
536 * template0, because autovacuum increments their datfrozenxids and
537 * relfrozenxids even if autovacuum is turned off, and even though all
538 * the data rows are already frozen To enable this, we temporarily
539 * change datallowconn.
541 if (strcmp(datallowconn, "f") == 0)
542 PQclear(executeQueryOrDie(conn_template1,
543 "ALTER DATABASE %s ALLOW_CONNECTIONS = true",
544 quote_identifier(datname)));
546 conn = connectToServer(&new_cluster, datname);
548 /* set pg_class.relfrozenxid */
549 PQclear(executeQueryOrDie(conn,
550 "UPDATE pg_catalog.pg_class "
551 "SET relfrozenxid = '%u' "
552 /* only heap, materialized view, and TOAST are vacuumed */
553 "WHERE relkind IN ('r', 'm', 't')",
554 old_cluster.controldata.chkpnt_nxtxid));
557 /* Reset datallowconn flag */
558 if (strcmp(datallowconn, "f") == 0)
559 PQclear(executeQueryOrDie(conn_template1,
560 "ALTER DATABASE %s ALLOW_CONNECTIONS = false",
561 quote_identifier(datname)));
566 PQfinish(conn_template1);
575 fclose(log_opts.internal);
577 /* Remove dump and log files? */
578 if (!log_opts.retain)
583 for (filename = output_files; *filename != NULL; filename++)
586 /* remove dump files */
587 unlink(GLOBALS_DUMP_FILE);
589 if (old_cluster.dbarr.dbs)
590 for (dbnum = 0; dbnum < old_cluster.dbarr.ndbs; dbnum++)
592 char sql_file_name[MAXPGPATH],
593 log_file_name[MAXPGPATH];
594 DbInfo *old_db = &old_cluster.dbarr.dbs[dbnum];
596 snprintf(sql_file_name, sizeof(sql_file_name), DB_DUMP_FILE_MASK, old_db->db_oid);
597 unlink(sql_file_name);
599 snprintf(log_file_name, sizeof(log_file_name), DB_DUMP_LOG_FILE_MASK, old_db->db_oid);
600 unlink(log_file_name);