Debian Codegraph @

src/bin/pg_upgrade/pg_upgrade.c

raw
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 main(int argc, char **argv)
89 {
90 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 pg_logging_init(argv[0]);
97 set_pglocale_pgservice(argv[0], PG_TEXTDOMAIN("pg_upgrade"));
98
99 /* Set default restrictive mask until new cluster permissions are read */
100 umask(PG_MODE_MASK_OWNER);
101
102 parseCommandLine(argc, argv);
103
104 get_restricted_token();
105
106 adjust_data_dir(&old_cluster);
107 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 if (!GetDataDirectoryCreatePerm(new_cluster.pgdata))
114 pg_fatal("could not read permissions of directory \"%s\": %m",
115 new_cluster.pgdata);
116
117 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 make_outputdirs(new_cluster.pgdata);
124
125 setup(argv[0]);
126
127 output_check_banner();
128
129 check_cluster_versions();
130
131 get_sock_dir(&old_cluster);
132 get_sock_dir(&new_cluster);
133
134 check_cluster_compatibility();
135
136 check_and_dump_old_cluster();
137
138
139 /* -- NEW -- */
140 start_postmaster(&new_cluster, true);
141
142 check_new_cluster();
143 report_clusters_compatible();
144
145 pg_log(PG_REPORT,
146 "\n"
147 "Performing Upgrade\n"
148 "------------------");
149
150 set_locale_and_encoding();
151
152 prepare_new_cluster();
153
154 stop_postmaster(false);
155
156 /*
157 * Destructive Changes to New Cluster
158 */
159
160 copy_xact_xlog_xid();
161 set_new_cluster_char_signedness();
162
163 /* New now using xids of the old system */
164
165 /* -- NEW -- */
166 start_postmaster(&new_cluster, true);
167
168 prepare_new_globals();
169
170 create_new_objects();
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 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 if (user_opts.transfer_mode == TRANSFER_MODE_LINK ||
182 user_opts.transfer_mode == TRANSFER_MODE_SWAP)
183 disable_old_cluster(user_opts.transfer_mode);
184
185 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 prep_status("Setting next OID for new cluster");
195 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 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 if (count_old_cluster_logical_slots())
210 {
211 start_postmaster(&new_cluster, true);
212 create_logical_replication_slots();
213 stop_postmaster(false);
214 }
215
216 if (user_opts.do_sync)
217 {
218 prep_status("Sync data directory to disk");
219 exec_prog(UTILITY_LOG_FILE, NULL, true, true,
220 "\"%s/initdb\" --sync-only %s \"%s\" --sync-method %s",
221 new_cluster.bindir,
222 (user_opts.transfer_mode == TRANSFER_MODE_SWAP) ?
223 "--no-sync-data-files" : "",
224 new_cluster.pgdata,
225 user_opts.sync_method);
226 check_ok();
227 }
228
229 create_script_for_old_cluster_deletion(&deletion_script_file_name);
230
231 issue_warnings_and_set_wal_level();
232
233 pg_log(PG_REPORT,
234 "\n"
235 "Upgrade Complete\n"
236 "----------------");
237
238 output_completion_banner(deletion_script_file_name);
239
240 pg_free(deletion_script_file_name);
241
242 cleanup_output_dirs();
243
244 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 make_outputdirs(char *pgdata)
254 {
255 FILE *fp;
256 char **filename;
257 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 log_opts.rootdir = (char *) pg_malloc0(MAXPGPATH);
265 len = snprintf(log_opts.rootdir, MAXPGPATH, "%s/%s", pgdata, BASE_OUTPUTDIR);
266 if (len >= MAXPGPATH)
267 pg_fatal("directory path for new cluster is too long");
268
269 /* BASE_OUTPUTDIR/$timestamp/ */
270 gettimeofday(&time, NULL);
271 tt = (time_t) time.tv_sec;
272 strftime(timebuf, sizeof(timebuf), "%Y%m%dT%H%M%S", localtime(&tt));
273 /* append milliseconds */
274 snprintf(timebuf + strlen(timebuf), sizeof(timebuf) - strlen(timebuf),
275 ".%03d", (int) (time.tv_usec / 1000));
276 log_opts.basedir = (char *) pg_malloc0(MAXPGPATH);
277 len = snprintf(log_opts.basedir, MAXPGPATH, "%s/%s", log_opts.rootdir,
278 timebuf);
279 if (len >= MAXPGPATH)
280 pg_fatal("directory path for new cluster is too long");
281
282 /* BASE_OUTPUTDIR/$timestamp/dump/ */
283 log_opts.dumpdir = (char *) pg_malloc0(MAXPGPATH);
284 len = snprintf(log_opts.dumpdir, MAXPGPATH, "%s/%s/%s", log_opts.rootdir,
285 timebuf, DUMP_OUTPUTDIR);
286 if (len >= MAXPGPATH)
287 pg_fatal("directory path for new cluster is too long");
288
289 /* BASE_OUTPUTDIR/$timestamp/log/ */
290 log_opts.logdir = (char *) pg_malloc0(MAXPGPATH);
291 len = snprintf(log_opts.logdir, MAXPGPATH, "%s/%s/%s", log_opts.rootdir,
292 timebuf, LOG_OUTPUTDIR);
293 if (len >= MAXPGPATH)
294 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 if (mkdir(log_opts.rootdir, pg_dir_create_mode) < 0 && errno != EEXIST)
301 pg_fatal("could not create directory \"%s\": %m", log_opts.rootdir);
302 if (mkdir(log_opts.basedir, pg_dir_create_mode) < 0)
303 pg_fatal("could not create directory \"%s\": %m", log_opts.basedir);
304 if (mkdir(log_opts.dumpdir, pg_dir_create_mode) < 0)
305 pg_fatal("could not create directory \"%s\": %m", log_opts.dumpdir);
306 if (mkdir(log_opts.logdir, pg_dir_create_mode) < 0)
307 pg_fatal("could not create directory \"%s\": %m", log_opts.logdir);
308
309 len = snprintf(filename_path, sizeof(filename_path), "%s/%s",
310 log_opts.logdir, INTERNAL_LOG_FILE);
311 if (len >= sizeof(filename_path))
312 pg_fatal("directory path for new cluster is too long");
313
314 if ((log_opts.internal = fopen_priv(filename_path, "a")) == NULL)
315 pg_fatal("could not open log file \"%s\": %m", filename_path);
316
317 /* label start of upgrade in logfiles */
318 for (filename = output_files; *filename != NULL; filename++)
319 {
320 len = snprintf(filename_path, sizeof(filename_path), "%s/%s",
321 log_opts.logdir, *filename);
322 if (len >= sizeof(filename_path))
323 pg_fatal("directory path for new cluster is too long");
324 if ((fp = fopen_priv(filename_path, "a")) == NULL)
325 pg_fatal("could not write to log file \"%s\": %m", filename_path);
326
327 fprintf(fp,
328 "-----------------------------------------------------------------\n"
329 " pg_upgrade run on %s"
330 "-----------------------------------------------------------------\n\n",
331 ctime(&run_time));
332 fclose(fp);
333 }
334 }
335
336
337 static void
338 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 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 if (!new_cluster.bindir)
352 {
353 char exec_path[MAXPGPATH];
354
355 if (find_my_exec(argv0, exec_path) < 0)
356 pg_fatal("%s: could not find own program executable", argv0);
357 /* Trim off program name and keep just path */
358 *last_dir_separator(exec_path) = '\0';
359 canonicalize_path(exec_path);
360 new_cluster.bindir = pg_strdup(exec_path);
361 }
362
363 verify_directories();
364
365 /* no postmasters should be running, except for a live check */
366 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 if (start_postmaster(&old_cluster, false))
378 stop_postmaster(false);
379 else
380 {
381 if (!user_opts.check)
382 pg_fatal("There seems to be a postmaster servicing the old cluster.\n"
383 "Please shutdown that postmaster and try again.");
384 else
385 user_opts.live_check = true;
386 }
387 }
388
389 /* same goes for the new postmaster */
390 if (pid_lock_file_exists(new_cluster.pgdata))
391 {
392 if (start_postmaster(&new_cluster, false))
393 stop_postmaster(false);
394 else
395 pg_fatal("There seems to be a postmaster servicing the new cluster.\n"
396 "Please shutdown that postmaster and try again.");
397 }
398 }
399
400 /*
401 * Set the new cluster's default char signedness using the old cluster's
402 * value.
403 */
404 static void
405 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 if (user_opts.char_signedness != -1)
414 new_char_signedness = (user_opts.char_signedness == 1);
415 else
416 new_char_signedness = old_cluster.controldata.default_char_signedness;
417
418 /* Change the char signedness of the new cluster, if necessary */
419 if (new_cluster.controldata.default_char_signedness != new_char_signedness)
420 {
421 prep_status("Setting the default char signedness for new cluster");
422
423 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 check_ok();
430 }
431 }
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 set_locale_and_encoding(void)
442 {
443 PGconn *conn_new_template1;
444 char *datcollate_literal;
445 char *datctype_literal;
446 char *datlocale_literal = NULL;
447 DbLocaleInfo *locale = old_cluster.template0;
448
449 prep_status("Setting locale and encoding for new cluster");
450
451 /* escape literals with respect to new cluster */
452 conn_new_template1 = connectToServer(&new_cluster, "template1");
453
454 datcollate_literal = PQescapeLiteral(conn_new_template1,
455 locale->db_collate,
456 strlen(locale->db_collate));
457 datctype_literal = PQescapeLiteral(conn_new_template1,
458 locale->db_ctype,
459 strlen(locale->db_ctype));
460
461 if (locale->db_locale)
462 datlocale_literal = PQescapeLiteral(conn_new_template1,
463 locale->db_locale,
464 strlen(locale->db_locale));
465 else
466 datlocale_literal = "NULL";
467
468 /* update template0 in new cluster */
469 if (GET_MAJOR_VERSION(new_cluster.major_version) >= 1700)
470 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 locale->db_collprovider,
480 datcollate_literal,
481 datctype_literal,
482 datlocale_literal));
483 else if (GET_MAJOR_VERSION(new_cluster.major_version) >= 1500)
484 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 locale->db_collprovider,
494 datcollate_literal,
495 datctype_literal,
496 datlocale_literal));
497 else
498 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 PQfreemem(datcollate_literal);
509 PQfreemem(datctype_literal);
510 if (locale->db_locale)
511 PQfreemem(datlocale_literal);
512
513 PQfinish(conn_new_template1);
514
515 check_ok();
516 }
517
518
519 static void
520 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 prep_status("Analyzing all rows in the new cluster");
528 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 log_opts.verbose ? "--verbose" : "");
532 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 prep_status("Freezing all rows in the new cluster");
541 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 log_opts.verbose ? "--verbose" : "");
545 check_ok();
546 }
547
548
549 static void
550 prepare_new_globals(void)
551 {
552 /*
553 * Before we restore anything, set frozenxids of initdb-created tables.
554 */
555 set_frozenxids(false);
556
557 /*
558 * Now restore global objects (roles and tablespaces).
559 */
560 prep_status("Restoring global objects in the new cluster");
561
562 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 check_ok();
568 }
569
570
571 static void
572 create_new_objects(void)
573 {
574 int dbnum;
575 PGconn *conn_new_template1;
576
577 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 conn_new_template1 = connectToServer(&new_cluster, "template1");
587 PQclear(executeQueryOrDie(conn_new_template1, "CHECKPOINT"));
588 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 for (dbnum = 0; dbnum < old_cluster.dbarr.ndbs; dbnum++)
596 {
597 char sql_file_name[MAXPGPATH],
598 log_file_name[MAXPGPATH];
599 DbInfo *old_db = &old_cluster.dbarr.dbs[dbnum];
600 const char *create_opts;
601
602 /* Process only template1 in this pass */
603 if (strcmp(old_db->db_name, "template1") != 0)
604 continue;
605
606 pg_log(PG_STATUS, "%s", old_db->db_name);
607 snprintf(sql_file_name, sizeof(sql_file_name), DB_DUMP_FILE_MASK, old_db->db_oid);
608 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 create_opts = "--clean --create";
616
617 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 break; /* done once we've processed template1 */
632 }
633
634 for (dbnum = 0; dbnum < old_cluster.dbarr.ndbs; dbnum++)
635 {
636 char sql_file_name[MAXPGPATH],
637 log_file_name[MAXPGPATH];
638 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 if (strcmp(old_db->db_name, "template1") == 0)
644 continue;
645
646 pg_log(PG_STATUS, "%s", old_db->db_name);
647 snprintf(sql_file_name, sizeof(sql_file_name), DB_DUMP_FILE_MASK, old_db->db_oid);
648 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 if (strcmp(old_db->db_name, "postgres") == 0)
656 create_opts = "--clean --create";
657 else
658 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 txn_size = RESTORE_TRANSACTION_SIZE;
666 if (user_opts.jobs > 1)
667 {
668 txn_size /= user_opts.jobs;
669 /* Keep some sanity if -j is huge */
670 txn_size = Max(txn_size, 10);
671 }
672
673 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 while (reap_child(true) == true)
688 ;
689
690 end_progress_output();
691 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 if (GET_MAJOR_VERSION(old_cluster.major_version) <= 902)
698 set_frozenxids(true);
699
700 /* update new_cluster info now that we have objects in the databases */
701 get_db_rel_and_slot_infos(&new_cluster);
702 }
703
704 /*
705 * Delete the given subdirectory contents from the new cluster
706 */
707 static void
708 remove_new_subdir(const char *subdir, bool rmtopdir)
709 {
710 char new_path[MAXPGPATH];
711
712 prep_status("Deleting files from new %s", subdir);
713
714 snprintf(new_path, sizeof(new_path), "%s/%s", new_cluster.pgdata, subdir);
715 if (!rmtree(new_path, rmtopdir))
716 pg_fatal("could not delete directory \"%s\"", new_path);
717
718 check_ok();
719 }
720
721 /*
722 * Copy the files from the old cluster into it
723 */
724 static void
725 copy_subdir_files(const char *old_subdir, const char *new_subdir)
726 {
727 char old_path[MAXPGPATH];
728 char new_path[MAXPGPATH];
729
730 remove_new_subdir(new_subdir, true);
731
732 snprintf(old_path, sizeof(old_path), "%s/%s", old_cluster.pgdata, old_subdir);
733 snprintf(new_path, sizeof(new_path), "%s/%s", new_cluster.pgdata, new_subdir);
734
735 prep_status("Copying old %s to new server", old_subdir);
736
737 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 check_ok();
747 }
748
749 static void
750 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 copy_subdir_files(GET_MAJOR_VERSION(old_cluster.major_version) <= 906 ?
757 "pg_clog" : "pg_xact",
758 GET_MAJOR_VERSION(new_cluster.major_version) <= 906 ?
759 "pg_clog" : "pg_xact");
760
761 prep_status("Setting oldest XID for new cluster");
762 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 check_ok();
767
768 /* set the next transaction id and epoch of the new cluster */
769 prep_status("Setting next transaction ID and epoch for new cluster");
770 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 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 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 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 if (old_cluster.controldata.cat_ver >= MULTIXACT_FORMATCHANGE_CAT_VER &&
794 new_cluster.controldata.cat_ver >= MULTIXACT_FORMATCHANGE_CAT_VER)
795 {
796 copy_subdir_files("pg_multixact/offsets", "pg_multixact/offsets");
797 copy_subdir_files("pg_multixact/members", "pg_multixact/members");
798
799 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 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 check_ok();
813 }
814 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 remove_new_subdir("pg_multixact/offsets", false);
822
823 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 exec_prog(UTILITY_LOG_FILE, NULL, true, true,
834 "\"%s/pg_resetwal\" -m %u,%u \"%s\"",
835 new_cluster.bindir,
836 old_cluster.controldata.chkpnt_nxtmulti + 1,
837 old_cluster.controldata.chkpnt_nxtmulti,
838 new_cluster.pgdata);
839 check_ok();
840 }
841
842 /* now reset the wal archives in the new cluster */
843 prep_status("Resetting WAL archives");
844 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 check_ok();
850 }
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 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 if (!minmxid_only)
886 prep_status("Setting frozenxid and minmxid counters in new cluster");
887 else
888 prep_status("Setting minmxid counter in new cluster");
889
890 conn_template1 = connectToServer(&new_cluster, "template1");
891
892 if (!minmxid_only)
893 /* set pg_database.datfrozenxid */
894 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 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 dbres = executeQueryOrDie(conn_template1,
907 "SELECT datname, datallowconn "
908 "FROM pg_catalog.pg_database");
909
910 i_datname = PQfnumber(dbres, "datname");
911 i_datallowconn = PQfnumber(dbres, "datallowconn");
912
913 ntups = PQntuples(dbres);
914 for (dbnum = 0; dbnum < ntups; dbnum++)
915 {
916 char *datname = PQgetvalue(dbres, dbnum, i_datname);
917 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 if (strcmp(datallowconn, "f") == 0)
927 PQclear(executeQueryOrDie(conn_template1,
928 "ALTER DATABASE %s ALLOW_CONNECTIONS = true",
929 quote_identifier(datname)));
930
931 conn = connectToServer(&new_cluster, datname);
932
933 if (!minmxid_only)
934 /* set pg_class.relfrozenxid */
935 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 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 PQfinish(conn);
956
957 /* Reset datallowconn flag */
958 if (strcmp(datallowconn, "f") == 0)
959 PQclear(executeQueryOrDie(conn_template1,
960 "ALTER DATABASE %s ALLOW_CONNECTIONS = false",
961 quote_identifier(datname)));
962 }
963
964 PQclear(dbres);
965
966 PQfinish(conn_template1);
967
968 check_ok();
969 }
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 create_logical_replication_slots(void)
978 {
979 prep_status_progress("Restoring logical replication slots in the new cluster");
980
981 for (int dbnum = 0; dbnum < old_cluster.dbarr.ndbs; dbnum++)
982 {
983 DbInfo *old_db = &old_cluster.dbarr.dbs[dbnum];
984 LogicalSlotInfoArr *slot_arr = &old_db->slot_arr;
985 PGconn *conn;
986 PQExpBuffer query;
987
988 /* Skip this database if there are no slots */
989 if (slot_arr->nslots == 0)
990 continue;
991
992 conn = connectToServer(&new_cluster, old_db->db_name);
993 query = createPQExpBuffer();
994
995 pg_log(PG_STATUS, "%s", old_db->db_name);
996
997 for (int slotnum = 0; slotnum < slot_arr->nslots; slotnum++)
998 {
999 LogicalSlotInfo *slot_info = &slot_arr->slots[slotnum];
1000
1001 /* Constructs a query for creating logical replication slots */
1002 appendPQExpBufferStr(query,
1003 "SELECT * FROM "
1004 "pg_catalog.pg_create_logical_replication_slot(");
1005 appendStringLiteralConn(query, slot_info->slotname, conn);
1006 appendPQExpBufferStr(query, ", ");
1007 appendStringLiteralConn(query, slot_info->plugin, conn);
1008
1009 appendPQExpBuffer(query, ", false, %s, %s);",
1010 slot_info->two_phase ? "true" : "false",
1011 slot_info->failover ? "true" : "false");
1012
1013 PQclear(executeQueryOrDie(conn, "%s", query->data));
1014
1015 resetPQExpBuffer(query);
1016 }
1017
1018 PQfinish(conn);
1019
1020 destroyPQExpBuffer(query);
1021 }
1022
1023 end_progress_output();
1024 check_ok();
1025
1026 return;
1027 }