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