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