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