]> granicus.if.org Git - postgresql/blob - contrib/pg_upgrade/pg_upgrade.c
Allow CREATE/ALTER DATABASE to manipulate datistemplate and datallowconn.
[postgresql] / contrib / pg_upgrade / pg_upgrade.c
1 /*
2  *      pg_upgrade.c
3  *
4  *      main source file
5  *
6  *      Copyright (c) 2010-2014, PostgreSQL Global Development Group
7  *      contrib/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
19  *      in a cluster, they can diverge due to CLUSTER, REINDEX, or VACUUM
20  *      FULL.  In the new cluster, pg_class.oid and pg_class.relfilenode will
21  *      be the same and will match the old pg_class.oid value.  Because of
22  *      this, old/new pg_class.relfilenode values will not match if CLUSTER,
23  *      REINDEX, or VACUUM FULL have been performed in the old cluster.
24  *
25  *      We control all assignments of pg_type.oid because these oids are stored
26  *      in user composite type values.
27  *
28  *      We control all assignments of pg_enum.oid because these oids are stored
29  *      in user tables as enum values.
30  *
31  *      We control all assignments of pg_authid.oid because these oids are stored
32  *      in pg_largeobject_metadata.
33  */
34
35
36
37 #include "postgres_fe.h"
38
39 #include "pg_upgrade.h"
40
41 #ifdef HAVE_LANGINFO_H
42 #include <langinfo.h>
43 #endif
44
45 static void prepare_new_cluster(void);
46 static void prepare_new_databases(void);
47 static void create_new_objects(void);
48 static void copy_clog_xlog_xid(void);
49 static void set_frozenxids(void);
50 static void setup(char *argv0, bool *live_check);
51 static void cleanup(void);
52
53 ClusterInfo old_cluster,
54                         new_cluster;
55 OSInfo          os_info;
56
57 char       *output_files[] = {
58         SERVER_LOG_FILE,
59 #ifdef WIN32
60         /* unique file for pg_ctl start */
61         SERVER_START_LOG_FILE,
62 #endif
63         UTILITY_LOG_FILE,
64         INTERNAL_LOG_FILE,
65         NULL
66 };
67
68
69 int
70 main(int argc, char **argv)
71 {
72         char       *sequence_script_file_name = NULL;
73         char       *analyze_script_file_name = NULL;
74         char       *deletion_script_file_name = NULL;
75         bool            live_check = false;
76
77         parseCommandLine(argc, argv);
78
79         adjust_data_dir(&old_cluster);
80         adjust_data_dir(&new_cluster);
81
82         setup(argv[0], &live_check);
83
84         output_check_banner(live_check);
85
86         check_cluster_versions();
87
88         get_sock_dir(&old_cluster, live_check);
89         get_sock_dir(&new_cluster, false);
90
91         check_cluster_compatibility(live_check);
92
93         check_and_dump_old_cluster(live_check, &sequence_script_file_name);
94
95
96         /* -- NEW -- */
97         start_postmaster(&new_cluster, true);
98
99         check_new_cluster();
100         report_clusters_compatible();
101
102         pg_log(PG_REPORT, "\nPerforming Upgrade\n");
103         pg_log(PG_REPORT, "------------------\n");
104
105         prepare_new_cluster();
106
107         stop_postmaster(false);
108
109         /*
110          * Destructive Changes to New Cluster
111          */
112
113         copy_clog_xlog_xid();
114
115         /* New now using xids of the old system */
116
117         /* -- NEW -- */
118         start_postmaster(&new_cluster, true);
119
120         prepare_new_databases();
121
122         create_new_objects();
123
124         stop_postmaster(false);
125
126         /*
127          * Most failures happen in create_new_objects(), which has completed at
128          * this point.  We do this here because it is just before linking, which
129          * will link the old and new cluster data files, preventing the old
130          * cluster from being safely started once the new cluster is started.
131          */
132         if (user_opts.transfer_mode == TRANSFER_MODE_LINK)
133                 disable_old_cluster();
134
135         transfer_all_new_tablespaces(&old_cluster.dbarr, &new_cluster.dbarr,
136                                                                  old_cluster.pgdata, new_cluster.pgdata);
137
138         /*
139          * Assuming OIDs are only used in system tables, there is no need to
140          * restore the OID counter because we have not transferred any OIDs from
141          * the old system, but we do it anyway just in case.  We do it late here
142          * because there is no need to have the schema load use new oids.
143          */
144         prep_status("Setting next OID for new cluster");
145         exec_prog(UTILITY_LOG_FILE, NULL, true,
146                           "\"%s/pg_resetxlog\" -o %u \"%s\"",
147                           new_cluster.bindir, old_cluster.controldata.chkpnt_nxtoid,
148                           new_cluster.pgdata);
149         check_ok();
150
151         prep_status("Sync data directory to disk");
152         exec_prog(UTILITY_LOG_FILE, NULL, true,
153                           "\"%s/initdb\" --sync-only \"%s\"", new_cluster.bindir,
154                           new_cluster.pgdata);
155         check_ok();
156
157         create_script_for_cluster_analyze(&analyze_script_file_name);
158         create_script_for_old_cluster_deletion(&deletion_script_file_name);
159
160         issue_warnings(sequence_script_file_name);
161
162         pg_log(PG_REPORT, "\nUpgrade Complete\n");
163         pg_log(PG_REPORT, "----------------\n");
164
165         output_completion_banner(analyze_script_file_name,
166                                                          deletion_script_file_name);
167
168         pg_free(analyze_script_file_name);
169         pg_free(deletion_script_file_name);
170         pg_free(sequence_script_file_name);
171
172         cleanup();
173
174         return 0;
175 }
176
177
178 static void
179 setup(char *argv0, bool *live_check)
180 {
181         char            exec_path[MAXPGPATH];   /* full path to my executable */
182
183         /*
184          * make sure the user has a clean environment, otherwise, we may confuse
185          * libpq when we connect to one (or both) of the servers.
186          */
187         check_pghost_envvar();
188
189         verify_directories();
190
191         /* no postmasters should be running, except for a live check */
192         if (pid_lock_file_exists(old_cluster.pgdata))
193         {
194                 /*
195                  * If we have a postmaster.pid file, try to start the server.  If it
196                  * starts, the pid file was stale, so stop the server.  If it doesn't
197                  * start, assume the server is running.  If the pid file is left over
198                  * from a server crash, this also allows any committed transactions
199                  * stored in the WAL to be replayed so they are not lost, because WAL
200                  * files are not transfered from old to new servers.
201                  */
202                 if (start_postmaster(&old_cluster, false))
203                         stop_postmaster(false);
204                 else
205                 {
206                         if (!user_opts.check)
207                                 pg_fatal("There seems to be a postmaster servicing the old cluster.\n"
208                                                  "Please shutdown that postmaster and try again.\n");
209                         else
210                                 *live_check = true;
211                 }
212         }
213
214         /* same goes for the new postmaster */
215         if (pid_lock_file_exists(new_cluster.pgdata))
216         {
217                 if (start_postmaster(&new_cluster, false))
218                         stop_postmaster(false);
219                 else
220                         pg_fatal("There seems to be a postmaster servicing the new cluster.\n"
221                                          "Please shutdown that postmaster and try again.\n");
222         }
223
224         /* get path to pg_upgrade executable */
225         if (find_my_exec(argv0, exec_path) < 0)
226                 pg_fatal("Could not get path name to pg_upgrade: %s\n", getErrorText(errno));
227
228         /* Trim off program name and keep just path */
229         *last_dir_separator(exec_path) = '\0';
230         canonicalize_path(exec_path);
231         os_info.exec_path = pg_strdup(exec_path);
232 }
233
234
235 static void
236 prepare_new_cluster(void)
237 {
238         /*
239          * It would make more sense to freeze after loading the schema, but that
240          * would cause us to lose the frozenids restored by the load. We use
241          * --analyze so autovacuum doesn't update statistics later
242          */
243         prep_status("Analyzing all rows in the new cluster");
244         exec_prog(UTILITY_LOG_FILE, NULL, true,
245                           "\"%s/vacuumdb\" %s --all --analyze %s",
246                           new_cluster.bindir, cluster_conn_opts(&new_cluster),
247                           log_opts.verbose ? "--verbose" : "");
248         check_ok();
249
250         /*
251          * We do freeze after analyze so pg_statistic is also frozen. template0 is
252          * not frozen here, but data rows were frozen by initdb, and we set its
253          * datfrozenxid and relfrozenxids later to match the new xid counter
254          * later.
255          */
256         prep_status("Freezing all rows on the new cluster");
257         exec_prog(UTILITY_LOG_FILE, NULL, true,
258                           "\"%s/vacuumdb\" %s --all --freeze %s",
259                           new_cluster.bindir, cluster_conn_opts(&new_cluster),
260                           log_opts.verbose ? "--verbose" : "");
261         check_ok();
262
263         get_pg_database_relfilenode(&new_cluster);
264 }
265
266
267 static void
268 prepare_new_databases(void)
269 {
270         /*
271          * We set autovacuum_freeze_max_age to its maximum value so autovacuum
272          * does not launch here and delete clog files, before the frozen xids are
273          * set.
274          */
275
276         set_frozenxids();
277
278         prep_status("Restoring global objects in the new cluster");
279
280         /*
281          * Install support functions in the global-object restore database to
282          * preserve pg_authid.oid.  pg_dumpall uses 'template0' as its template
283          * database so objects we add into 'template1' are not propogated.  They
284          * are removed on pg_upgrade exit.
285          */
286         install_support_functions_in_new_db("template1");
287
288         /*
289          * We have to create the databases first so we can install support
290          * functions in all the other databases.  Ideally we could create the
291          * support functions in template1 but pg_dumpall creates database using
292          * the template0 template.
293          */
294         exec_prog(UTILITY_LOG_FILE, NULL, true,
295                           "\"%s/psql\" " EXEC_PSQL_ARGS " %s -f \"%s\"",
296                           new_cluster.bindir, cluster_conn_opts(&new_cluster),
297                           GLOBALS_DUMP_FILE);
298         check_ok();
299
300         /* we load this to get a current list of databases */
301         get_db_and_rel_infos(&new_cluster);
302 }
303
304
305 static void
306 create_new_objects(void)
307 {
308         int                     dbnum;
309
310         prep_status("Adding support functions to new cluster");
311
312         /*
313          * Technically, we only need to install these support functions in new
314          * databases that also exist in the old cluster, but for completeness we
315          * process all new databases.
316          */
317         for (dbnum = 0; dbnum < new_cluster.dbarr.ndbs; dbnum++)
318         {
319                 DbInfo     *new_db = &new_cluster.dbarr.dbs[dbnum];
320
321                 /* skip db we already installed */
322                 if (strcmp(new_db->db_name, "template1") != 0)
323                         install_support_functions_in_new_db(new_db->db_name);
324         }
325         check_ok();
326
327         prep_status("Restoring database schemas in the new cluster\n");
328
329         for (dbnum = 0; dbnum < old_cluster.dbarr.ndbs; dbnum++)
330         {
331                 char            sql_file_name[MAXPGPATH],
332                                         log_file_name[MAXPGPATH];
333                 DbInfo     *old_db = &old_cluster.dbarr.dbs[dbnum];
334
335                 pg_log(PG_STATUS, "%s", old_db->db_name);
336                 snprintf(sql_file_name, sizeof(sql_file_name), DB_DUMP_FILE_MASK, old_db->db_oid);
337                 snprintf(log_file_name, sizeof(log_file_name), DB_DUMP_LOG_FILE_MASK, old_db->db_oid);
338
339                 /*
340                  * pg_dump only produces its output at the end, so there is little
341                  * parallelism if using the pipe.
342                  */
343                 parallel_exec_prog(log_file_name,
344                                                    NULL,
345                                                    "\"%s/pg_restore\" %s --exit-on-error --verbose --dbname \"%s\" \"%s\"",
346                                                    new_cluster.bindir,
347                                                    cluster_conn_opts(&new_cluster),
348                                                    old_db->db_name,
349                                                    sql_file_name);
350         }
351
352         /* reap all children */
353         while (reap_child(true) == true)
354                 ;
355
356         end_progress_output();
357         check_ok();
358
359         /* regenerate now that we have objects in the databases */
360         get_db_and_rel_infos(&new_cluster);
361
362         uninstall_support_functions_from_new_cluster();
363 }
364
365 /*
366  * Delete the given subdirectory contents from the new cluster
367  */
368 static void
369 remove_new_subdir(char *subdir, bool rmtopdir)
370 {
371         char            new_path[MAXPGPATH];
372
373         prep_status("Deleting files from new %s", subdir);
374
375         snprintf(new_path, sizeof(new_path), "%s/%s", new_cluster.pgdata, subdir);
376         if (!rmtree(new_path, rmtopdir))
377                 pg_fatal("could not delete directory \"%s\"\n", new_path);
378
379         check_ok();
380 }
381
382 /*
383  * Copy the files from the old cluster into it
384  */
385 static void
386 copy_subdir_files(char *subdir)
387 {
388         char            old_path[MAXPGPATH];
389         char            new_path[MAXPGPATH];
390
391         remove_new_subdir(subdir, true);
392
393         snprintf(old_path, sizeof(old_path), "%s/%s", old_cluster.pgdata, subdir);
394         snprintf(new_path, sizeof(new_path), "%s/%s", new_cluster.pgdata, subdir);
395
396         prep_status("Copying old %s to new server", subdir);
397
398         exec_prog(UTILITY_LOG_FILE, NULL, true,
399 #ifndef WIN32
400                           "cp -Rf \"%s\" \"%s\"",
401 #else
402         /* flags: everything, no confirm, quiet, overwrite read-only */
403                           "xcopy /e /y /q /r \"%s\" \"%s\\\"",
404 #endif
405                           old_path, new_path);
406
407         check_ok();
408 }
409
410 static void
411 copy_clog_xlog_xid(void)
412 {
413         /* copy old commit logs to new data dir */
414         copy_subdir_files("pg_clog");
415
416         /* set the next transaction id of the new cluster */
417         prep_status("Setting next transaction ID for new cluster");
418         exec_prog(UTILITY_LOG_FILE, NULL, true,
419                           "\"%s/pg_resetxlog\" -f -x %u \"%s\"",
420                           new_cluster.bindir, old_cluster.controldata.chkpnt_nxtxid,
421                           new_cluster.pgdata);
422         check_ok();
423
424         /*
425          * If the old server is before the MULTIXACT_FORMATCHANGE_CAT_VER change
426          * (see pg_upgrade.h) and the new server is after, then we don't copy
427          * pg_multixact files, but we need to reset pg_control so that the new
428          * server doesn't attempt to read multis older than the cutoff value.
429          */
430         if (old_cluster.controldata.cat_ver >= MULTIXACT_FORMATCHANGE_CAT_VER &&
431                 new_cluster.controldata.cat_ver >= MULTIXACT_FORMATCHANGE_CAT_VER)
432         {
433                 copy_subdir_files("pg_multixact/offsets");
434                 copy_subdir_files("pg_multixact/members");
435
436                 prep_status("Setting next multixact ID and offset for new cluster");
437
438                 /*
439                  * we preserve all files and contents, so we must preserve both "next"
440                  * counters here and the oldest multi present on system.
441                  */
442                 exec_prog(UTILITY_LOG_FILE, NULL, true,
443                                   "\"%s/pg_resetxlog\" -O %u -m %u,%u \"%s\"",
444                                   new_cluster.bindir,
445                                   old_cluster.controldata.chkpnt_nxtmxoff,
446                                   old_cluster.controldata.chkpnt_nxtmulti,
447                                   old_cluster.controldata.chkpnt_oldstMulti,
448                                   new_cluster.pgdata);
449                 check_ok();
450         }
451         else if (new_cluster.controldata.cat_ver >= MULTIXACT_FORMATCHANGE_CAT_VER)
452         {
453                 /*
454                  * Remove files created by initdb that no longer match the
455                  * new multi-xid value.
456                  */
457                 remove_new_subdir("pg_multixact/offsets", false);
458                 remove_new_subdir("pg_multixact/members", false);
459
460                 prep_status("Setting oldest multixact ID on new cluster");
461
462                 /*
463                  * We don't preserve files in this case, but it's important that the
464                  * oldest multi is set to the latest value used by the old system, so
465                  * that multixact.c returns the empty set for multis that might be
466                  * present on disk.  We set next multi to the value following that; it
467                  * might end up wrapped around (i.e. 0) if the old cluster had
468                  * next=MaxMultiXactId, but multixact.c can cope with that just fine.
469                  */
470                 exec_prog(UTILITY_LOG_FILE, NULL, true,
471                                   "\"%s/pg_resetxlog\" -m %u,%u \"%s\"",
472                                   new_cluster.bindir,
473                                   old_cluster.controldata.chkpnt_nxtmulti + 1,
474                                   old_cluster.controldata.chkpnt_nxtmulti,
475                                   new_cluster.pgdata);
476                 check_ok();
477         }
478
479         /* now reset the wal archives in the new cluster */
480         prep_status("Resetting WAL archives");
481         exec_prog(UTILITY_LOG_FILE, NULL, true,
482                           "\"%s/pg_resetxlog\" -l %s \"%s\"", new_cluster.bindir,
483                           old_cluster.controldata.nextxlogfile,
484                           new_cluster.pgdata);
485         check_ok();
486 }
487
488
489 /*
490  *      set_frozenxids()
491  *
492  *      We have frozen all xids, so set relfrozenxid and datfrozenxid
493  *      to be the old cluster's xid counter, which we just set in the new
494  *      cluster.  User-table frozenxid values will be set by pg_dump
495  *      --binary-upgrade, but objects not set by the pg_dump must have
496  *      proper frozen counters.
497  */
498 static
499 void
500 set_frozenxids(void)
501 {
502         int                     dbnum;
503         PGconn     *conn,
504                            *conn_template1;
505         PGresult   *dbres;
506         int                     ntups;
507         int                     i_datname;
508         int                     i_datallowconn;
509
510         prep_status("Setting frozenxid counters in new cluster");
511
512         conn_template1 = connectToServer(&new_cluster, "template1");
513
514         /* set pg_database.datfrozenxid */
515         PQclear(executeQueryOrDie(conn_template1,
516                                                           "UPDATE pg_catalog.pg_database "
517                                                           "SET  datfrozenxid = '%u'",
518                                                           old_cluster.controldata.chkpnt_nxtxid));
519
520         /* get database names */
521         dbres = executeQueryOrDie(conn_template1,
522                                                           "SELECT       datname, datallowconn "
523                                                           "FROM pg_catalog.pg_database");
524
525         i_datname = PQfnumber(dbres, "datname");
526         i_datallowconn = PQfnumber(dbres, "datallowconn");
527
528         ntups = PQntuples(dbres);
529         for (dbnum = 0; dbnum < ntups; dbnum++)
530         {
531                 char       *datname = PQgetvalue(dbres, dbnum, i_datname);
532                 char       *datallowconn = PQgetvalue(dbres, dbnum, i_datallowconn);
533
534                 /*
535                  * We must update databases where datallowconn = false, e.g.
536                  * template0, because autovacuum increments their datfrozenxids and
537                  * relfrozenxids even if autovacuum is turned off, and even though all
538                  * the data rows are already frozen  To enable this, we temporarily
539                  * change datallowconn.
540                  */
541                 if (strcmp(datallowconn, "f") == 0)
542                         PQclear(executeQueryOrDie(conn_template1,
543                                                                 "ALTER DATABASE %s ALLOW_CONNECTIONS = true",
544                                                                           quote_identifier(datname)));
545
546                 conn = connectToServer(&new_cluster, datname);
547
548                 /* set pg_class.relfrozenxid */
549                 PQclear(executeQueryOrDie(conn,
550                                                                   "UPDATE       pg_catalog.pg_class "
551                                                                   "SET  relfrozenxid = '%u' "
552                 /* only heap, materialized view, and TOAST are vacuumed */
553                                                                   "WHERE        relkind IN ('r', 'm', 't')",
554                                                                   old_cluster.controldata.chkpnt_nxtxid));
555                 PQfinish(conn);
556
557                 /* Reset datallowconn flag */
558                 if (strcmp(datallowconn, "f") == 0)
559                         PQclear(executeQueryOrDie(conn_template1,
560                                                            "ALTER DATABASE %s ALLOW_CONNECTIONS = false",
561                                                                           quote_identifier(datname)));
562         }
563
564         PQclear(dbres);
565
566         PQfinish(conn_template1);
567
568         check_ok();
569 }
570
571
572 static void
573 cleanup(void)
574 {
575         fclose(log_opts.internal);
576
577         /* Remove dump and log files? */
578         if (!log_opts.retain)
579         {
580                 int                     dbnum;
581                 char      **filename;
582
583                 for (filename = output_files; *filename != NULL; filename++)
584                         unlink(*filename);
585
586                 /* remove dump files */
587                 unlink(GLOBALS_DUMP_FILE);
588
589                 if (old_cluster.dbarr.dbs)
590                         for (dbnum = 0; dbnum < old_cluster.dbarr.ndbs; dbnum++)
591                         {
592                                 char            sql_file_name[MAXPGPATH],
593                                                         log_file_name[MAXPGPATH];
594                                 DbInfo     *old_db = &old_cluster.dbarr.dbs[dbnum];
595
596                                 snprintf(sql_file_name, sizeof(sql_file_name), DB_DUMP_FILE_MASK, old_db->db_oid);
597                                 unlink(sql_file_name);
598
599                                 snprintf(log_file_name, sizeof(log_file_name), DB_DUMP_LOG_FILE_MASK, old_db->db_oid);
600                                 unlink(log_file_name);
601                         }
602         }
603 }