]> granicus.if.org Git - postgresql/blob - contrib/pg_upgrade/pg_upgrade.c
Fix pg_upgrade to create pg_authid restore functions in the 'postgres'
[postgresql] / contrib / pg_upgrade / pg_upgrade.c
1 /*
2  *      pg_upgrade.c
3  *
4  *      main source file
5  *
6  *      Copyright (c) 2010-2011, 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  *      FYI, while pg_class.oid and pg_class.relfilenode are intially the same
19  *      in a cluster, but they can diverge due to CLUSTER, REINDEX, or VACUUM
20  *      FULL.  The new cluster will have matching pg_class.oid and
21  *      pg_class.relfilenode values and be based on the old oid value.  This can
22  *      cause the old and new pg_class.relfilenode values to differ.  In summary,
23  *      old and new pg_class.oid and new pg_class.relfilenode will have the
24  *      same value, and old pg_class.relfilenode might differ.
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_auth.oid because these oids are stored
33  *      in pg_largeobject_metadata.
34  */
35
36
37  
38 #include "pg_upgrade.h"
39
40 #ifdef HAVE_LANGINFO_H
41 #include <langinfo.h>
42 #endif
43
44 static void disable_old_cluster(void);
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 /* This is the database used by pg_dumpall to restore global tables */
54 #define GLOBAL_DUMP_DB  "postgres"
55
56 ClusterInfo old_cluster, new_cluster;
57 OSInfo          os_info;
58
59 int
60 main(int argc, char **argv)
61 {
62         char       *sequence_script_file_name = NULL;
63         char       *deletion_script_file_name = NULL;
64         bool            live_check = false;
65
66         parseCommandLine(argc, argv);
67
68         output_check_banner(&live_check);
69
70         setup(argv[0], live_check);
71
72         check_cluster_versions();
73         check_cluster_compatibility(live_check);
74
75         check_old_cluster(live_check, &sequence_script_file_name);
76
77
78         /* -- NEW -- */
79         start_postmaster(&new_cluster, false);
80
81         check_new_cluster();
82         report_clusters_compatible();
83
84         pg_log(PG_REPORT, "\nPerforming Upgrade\n");
85         pg_log(PG_REPORT, "------------------\n");
86
87         disable_old_cluster();
88         prepare_new_cluster();
89
90         stop_postmaster(false, false);
91
92         /*
93          * Destructive Changes to New Cluster
94          */
95
96         copy_clog_xlog_xid();
97
98         /* New now using xids of the old system */
99
100         prepare_new_databases();
101
102         create_new_objects();
103
104         transfer_all_new_dbs(&old_cluster.dbarr, &new_cluster.dbarr,
105                                                  old_cluster.pgdata, new_cluster.pgdata);
106
107         /*
108          * Assuming OIDs are only used in system tables, there is no need to
109          * restore the OID counter because we have not transferred any OIDs from
110          * the old system, but we do it anyway just in case.  We do it late here
111          * because there is no need to have the schema load use new oids.
112          */
113         prep_status("Setting next oid for new cluster");
114         exec_prog(true, SYSTEMQUOTE "\"%s/pg_resetxlog\" -o %u \"%s\" > "
115                           DEVNULL SYSTEMQUOTE,
116                           new_cluster.bindir, old_cluster.controldata.chkpnt_nxtoid, new_cluster.pgdata);
117         check_ok();
118
119         create_script_for_old_cluster_deletion(&deletion_script_file_name);
120
121         issue_warnings(sequence_script_file_name);
122
123         pg_log(PG_REPORT, "\nUpgrade complete\n");
124         pg_log(PG_REPORT, "----------------\n");
125
126         output_completion_banner(deletion_script_file_name);
127
128         pg_free(deletion_script_file_name);
129         pg_free(sequence_script_file_name);
130
131         cleanup();
132
133         return 0;
134 }
135
136
137 static void
138 setup(char *argv0, bool live_check)
139 {
140         char            exec_path[MAXPGPATH];   /* full path to my executable */
141
142         /*
143          * make sure the user has a clean environment, otherwise, we may confuse
144          * libpq when we connect to one (or both) of the servers.
145          */
146         check_for_libpq_envvars();
147
148         verify_directories();
149
150         /* no postmasters should be running */
151         if (!live_check && is_server_running(old_cluster.pgdata))
152         {
153                 pg_log(PG_FATAL, "There seems to be a postmaster servicing the old cluster.\n"
154                            "Please shutdown that postmaster and try again.\n");
155         }
156
157         /* same goes for the new postmaster */
158         if (is_server_running(new_cluster.pgdata))
159         {
160                 pg_log(PG_FATAL, "There seems to be a postmaster servicing the new cluster.\n"
161                            "Please shutdown that postmaster and try again.\n");
162         }
163
164         /* get path to pg_upgrade executable */
165         if (find_my_exec(argv0, exec_path) < 0)
166                 pg_log(PG_FATAL, "Could not get pathname to pg_upgrade: %s\n", getErrorText(errno));
167
168         /* Trim off program name and keep just path */
169         *last_dir_separator(exec_path) = '\0';
170         canonicalize_path(exec_path);
171         os_info.exec_path = pg_strdup(exec_path);
172 }
173
174
175 static void
176 disable_old_cluster(void)
177 {
178         /* rename pg_control so old server cannot be accidentally started */
179         rename_old_pg_control();
180 }
181
182
183 static void
184 prepare_new_cluster(void)
185 {
186         /*
187          * It would make more sense to freeze after loading the schema, but that
188          * would cause us to lose the frozenids restored by the load. We use
189          * --analyze so autovacuum doesn't update statistics later
190          */
191         prep_status("Analyzing all rows in the new cluster");
192         exec_prog(true,
193                           SYSTEMQUOTE "\"%s/vacuumdb\" --port %d --username \"%s\" "
194                           "--all --analyze >> %s 2>&1" SYSTEMQUOTE,
195                    new_cluster.bindir, new_cluster.port, os_info.user, log_opts.filename);
196         check_ok();
197
198         /*
199          * We do freeze after analyze so pg_statistic is also frozen. template0 is
200          * not frozen here, but data rows were frozen by initdb, and we set its
201          * datfrozenxid and relfrozenxids later to match the new xid counter
202          * later.
203          */
204         prep_status("Freezing all rows on the new cluster");
205         exec_prog(true,
206                           SYSTEMQUOTE "\"%s/vacuumdb\" --port %d --username \"%s\" "
207                           "--all --freeze >> %s 2>&1" SYSTEMQUOTE,
208                    new_cluster.bindir, new_cluster.port, os_info.user, log_opts.filename);
209         check_ok();
210
211         get_pg_database_relfilenode(&new_cluster);
212 }
213
214
215 static void
216 prepare_new_databases(void)
217 {
218         /* -- NEW -- */
219         start_postmaster(&new_cluster, false);
220
221         /*
222          * We set autovacuum_freeze_max_age to its maximum value so autovacuum
223          * does not launch here and delete clog files, before the frozen xids are
224          * set.
225          */
226
227         set_frozenxids();
228
229         prep_status("Creating databases in the new cluster");
230
231         /*
232          *      Install support functions in the global-restore database
233          *      to preserve pg_authid.oid.
234          */
235         install_support_functions_in_new_db(GLOBAL_DUMP_DB);
236
237         /*
238          * We have to create the databases first so we can install support
239          * functions in all the other databases.
240          */
241         exec_prog(true,
242                           SYSTEMQUOTE "\"%s/psql\" --set ON_ERROR_STOP=on "
243         /* --no-psqlrc prevents AUTOCOMMIT=off */
244                           "--no-psqlrc --port %d --username \"%s\" "
245                           "-f \"%s/%s\" --dbname template1 >> \"%s\"" SYSTEMQUOTE,
246                           new_cluster.bindir, new_cluster.port, os_info.user, os_info.cwd,
247                           GLOBALS_DUMP_FILE, log_opts.filename);
248         check_ok();
249
250         /* we load this to get a current list of databases */
251         get_db_and_rel_infos(&new_cluster);
252
253         stop_postmaster(false, false);
254 }
255
256
257 static void
258 create_new_objects(void)
259 {
260         int                     dbnum;
261
262         /* -- NEW -- */
263         start_postmaster(&new_cluster, false);
264
265         prep_status("Adding support functions to new cluster");
266
267         for (dbnum = 0; dbnum < new_cluster.dbarr.ndbs; dbnum++)
268         {
269                 DbInfo     *new_db = &new_cluster.dbarr.dbs[dbnum];
270
271                 /* skip db we already installed */
272                 if (strcmp(new_db->db_name, GLOBAL_DUMP_DB) != 0)
273                         install_support_functions_in_new_db(new_db->db_name);
274         }
275         check_ok();
276
277         prep_status("Restoring database schema to new cluster");
278         exec_prog(true,
279                           SYSTEMQUOTE "\"%s/psql\" --set ON_ERROR_STOP=on "
280                           "--no-psqlrc --port %d --username \"%s\" "
281                           "-f \"%s/%s\" --dbname template1 >> \"%s\"" SYSTEMQUOTE,
282                           new_cluster.bindir, new_cluster.port, os_info.user, os_info.cwd,
283                           DB_DUMP_FILE, log_opts.filename);
284         check_ok();
285
286         /* regenerate now that we have objects in the databases */
287         free_db_and_rel_infos(&new_cluster.dbarr);
288         get_db_and_rel_infos(&new_cluster);
289
290         uninstall_support_functions_from_new_cluster();
291
292         stop_postmaster(false, false);
293 }
294
295
296 static void
297 copy_clog_xlog_xid(void)
298 {
299         char            old_clog_path[MAXPGPATH];
300         char            new_clog_path[MAXPGPATH];
301
302         /* copy old commit logs to new data dir */
303         prep_status("Deleting new commit clogs");
304
305         snprintf(old_clog_path, sizeof(old_clog_path), "%s/pg_clog", old_cluster.pgdata);
306         snprintf(new_clog_path, sizeof(new_clog_path), "%s/pg_clog", new_cluster.pgdata);
307         if (!rmtree(new_clog_path, true))
308                 pg_log(PG_FATAL, "Unable to delete directory %s\n", new_clog_path);
309         check_ok();
310
311         prep_status("Copying old commit clogs to new server");
312 #ifndef WIN32
313         exec_prog(true, SYSTEMQUOTE "%s \"%s\" \"%s\"" SYSTEMQUOTE,
314                           "cp -Rf",
315 #else
316         /* flags: everything, no confirm, quiet, overwrite read-only */
317         exec_prog(true, SYSTEMQUOTE "%s \"%s\" \"%s\\\"" SYSTEMQUOTE,
318                           "xcopy /e /y /q /r",
319 #endif
320                           old_clog_path, new_clog_path);
321         check_ok();
322
323         /* set the next transaction id of the new cluster */
324         prep_status("Setting next transaction id for new cluster");
325         exec_prog(true, SYSTEMQUOTE "\"%s/pg_resetxlog\" -f -x %u \"%s\" > " DEVNULL SYSTEMQUOTE,
326                           new_cluster.bindir, old_cluster.controldata.chkpnt_nxtxid, new_cluster.pgdata);
327         check_ok();
328
329         /* now reset the wal archives in the new cluster */
330         prep_status("Resetting WAL archives");
331         exec_prog(true, SYSTEMQUOTE "\"%s/pg_resetxlog\" -l %u,%u,%u \"%s\" >> \"%s\" 2>&1" SYSTEMQUOTE,
332                           new_cluster.bindir, old_cluster.controldata.chkpnt_tli,
333                         old_cluster.controldata.logid, old_cluster.controldata.nxtlogseg,
334                           new_cluster.pgdata, log_opts.filename);
335         check_ok();
336 }
337
338
339 /*
340  *      set_frozenxids()
341  *
342  *      We have frozen all xids, so set relfrozenxid and datfrozenxid
343  *      to be the old cluster's xid counter, which we just set in the new
344  *      cluster.  User-table frozenxid values will be set by pg_dumpall
345  *      --binary-upgrade, but objects not set by the pg_dump must have
346  *      proper frozen counters.
347  */
348 static
349 void
350 set_frozenxids(void)
351 {
352         int                     dbnum;
353         PGconn     *conn,
354                            *conn_template1;
355         PGresult   *dbres;
356         int                     ntups;
357         int                     i_datname;
358         int                     i_datallowconn;
359
360         prep_status("Setting frozenxid counters in new cluster");
361
362         conn_template1 = connectToServer(&new_cluster, "template1");
363
364         /* set pg_database.datfrozenxid */
365         PQclear(executeQueryOrDie(conn_template1,
366                                                           "UPDATE pg_catalog.pg_database "
367                                                           "SET  datfrozenxid = '%u'",
368                                                           old_cluster.controldata.chkpnt_nxtxid));
369
370         /* get database names */
371         dbres = executeQueryOrDie(conn_template1,
372                                                           "SELECT       datname, datallowconn "
373                                                           "FROM pg_catalog.pg_database");
374
375         i_datname = PQfnumber(dbres, "datname");
376         i_datallowconn = PQfnumber(dbres, "datallowconn");
377
378         ntups = PQntuples(dbres);
379         for (dbnum = 0; dbnum < ntups; dbnum++)
380         {
381                 char       *datname = PQgetvalue(dbres, dbnum, i_datname);
382                 char       *datallowconn = PQgetvalue(dbres, dbnum, i_datallowconn);
383
384                 /*
385                  * We must update databases where datallowconn = false, e.g.
386                  * template0, because autovacuum increments their datfrozenxids and
387                  * relfrozenxids even if autovacuum is turned off, and even though all
388                  * the data rows are already frozen  To enable this, we temporarily
389                  * change datallowconn.
390                  */
391                 if (strcmp(datallowconn, "f") == 0)
392                         PQclear(executeQueryOrDie(conn_template1,
393                                                                           "UPDATE pg_catalog.pg_database "
394                                                                           "SET  datallowconn = true "
395                                                                           "WHERE datname = '%s'", datname));
396
397                 conn = connectToServer(&new_cluster, datname);
398
399                 /* set pg_class.relfrozenxid */
400                 PQclear(executeQueryOrDie(conn,
401                                                                   "UPDATE       pg_catalog.pg_class "
402                                                                   "SET  relfrozenxid = '%u' "
403                 /* only heap and TOAST are vacuumed */
404                                                                   "WHERE        relkind IN ('r', 't')",
405                                                                   old_cluster.controldata.chkpnt_nxtxid));
406                 PQfinish(conn);
407
408                 /* Reset datallowconn flag */
409                 if (strcmp(datallowconn, "f") == 0)
410                         PQclear(executeQueryOrDie(conn_template1,
411                                                                           "UPDATE pg_catalog.pg_database "
412                                                                           "SET  datallowconn = false "
413                                                                           "WHERE datname = '%s'", datname));
414         }
415
416         PQclear(dbres);
417
418         PQfinish(conn_template1);
419
420         check_ok();
421 }
422
423
424 static void
425 cleanup(void)
426 {
427         int                     tblnum;
428         char            filename[MAXPGPATH];
429
430         for (tblnum = 0; tblnum < os_info.num_tablespaces; tblnum++)
431                 pg_free(os_info.tablespaces[tblnum]);
432         pg_free(os_info.tablespaces);
433
434         free_db_and_rel_infos(&old_cluster.dbarr);
435         free_db_and_rel_infos(&new_cluster.dbarr);
436         pg_free(log_opts.filename);
437         pg_free(os_info.user);
438         pg_free(old_cluster.controldata.lc_collate);
439         pg_free(new_cluster.controldata.lc_collate);
440         pg_free(old_cluster.controldata.lc_ctype);
441         pg_free(new_cluster.controldata.lc_ctype);
442         pg_free(old_cluster.controldata.encoding);
443         pg_free(new_cluster.controldata.encoding);
444         pg_free(old_cluster.tablespace_suffix);
445         pg_free(new_cluster.tablespace_suffix);
446
447         if (log_opts.fd != NULL)
448         {
449                 fclose(log_opts.fd);
450                 log_opts.fd = NULL;
451         }
452
453         if (log_opts.debug_fd)
454                 fclose(log_opts.debug_fd);
455
456         snprintf(filename, sizeof(filename), "%s/%s", os_info.cwd, ALL_DUMP_FILE);
457         unlink(filename);
458         snprintf(filename, sizeof(filename), "%s/%s", os_info.cwd, GLOBALS_DUMP_FILE);
459         unlink(filename);
460         snprintf(filename, sizeof(filename), "%s/%s", os_info.cwd, DB_DUMP_FILE);
461         unlink(filename);
462 }