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