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