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