OSDN Git Service

Add postmaster/postgres undocumented -b option for binary upgrades.
[pg-rex/syncrep.git] / contrib / pg_upgrade / server.c
1 /*
2  *      server.c
3  *
4  *      database server functions
5  *
6  *      Copyright (c) 2010-2011, PostgreSQL Global Development Group
7  *      contrib/pg_upgrade/server.c
8  */
9
10 #include "pg_upgrade.h"
11
12 #define POSTMASTER_UPTIME 20
13
14 #define STARTUP_WARNING_TRIES 2
15
16
17 static pgpid_t get_postmaster_pid(const char *datadir);
18 static bool test_server_conn(ClusterInfo *cluster, int timeout);
19
20
21 /*
22  * connectToServer()
23  *
24  *      Connects to the desired database on the designated server.
25  *      If the connection attempt fails, this function logs an error
26  *      message and calls exit() to kill the program.
27  */
28 PGconn *
29 connectToServer(ClusterInfo *cluster, const char *db_name)
30 {
31         unsigned short port = cluster->port;
32         char            connectString[MAXPGPATH];
33         PGconn     *conn;
34
35         snprintf(connectString, sizeof(connectString),
36                  "dbname = '%s' user = '%s' port = %d", db_name, os_info.user, port);
37
38         conn = PQconnectdb(connectString);
39
40         if (conn == NULL || PQstatus(conn) != CONNECTION_OK)
41         {
42                 pg_log(PG_REPORT, "Connection to database failed: %s\n",
43                            PQerrorMessage(conn));
44
45                 if (conn)
46                         PQfinish(conn);
47
48                 printf("Failure, exiting\n");
49                 exit(1);
50         }
51
52         return conn;
53 }
54
55
56 /*
57  * executeQueryOrDie()
58  *
59  *      Formats a query string from the given arguments and executes the
60  *      resulting query.  If the query fails, this function logs an error
61  *      message and calls exit() to kill the program.
62  */
63 PGresult *
64 executeQueryOrDie(PGconn *conn, const char *fmt,...)
65 {
66         static char command[8192];
67         va_list         args;
68         PGresult   *result;
69         ExecStatusType status;
70
71         va_start(args, fmt);
72         vsnprintf(command, sizeof(command), fmt, args);
73         va_end(args);
74
75         pg_log(PG_DEBUG, "executing: %s\n", command);
76         result = PQexec(conn, command);
77         status = PQresultStatus(result);
78
79         if ((status != PGRES_TUPLES_OK) && (status != PGRES_COMMAND_OK))
80         {
81                 pg_log(PG_REPORT, "DB command failed\n%s\n%s\n", command,
82                            PQerrorMessage(conn));
83                 PQclear(result);
84                 PQfinish(conn);
85                 printf("Failure, exiting\n");
86                 exit(1);
87         }
88         else
89                 return result;
90 }
91
92
93 /*
94  * get_postmaster_pid()
95  *
96  * Returns the pid of the postmaster running on datadir. pid is retrieved
97  * from the postmaster.pid file
98  */
99 static pgpid_t
100 get_postmaster_pid(const char *datadir)
101 {
102         FILE       *pidf;
103         long            pid;
104         char            pid_file[MAXPGPATH];
105
106         snprintf(pid_file, sizeof(pid_file), "%s/postmaster.pid", datadir);
107         pidf = fopen(pid_file, "r");
108
109         if (pidf == NULL)
110                 return (pgpid_t) 0;
111
112         if (fscanf(pidf, "%ld", &pid) != 1)
113         {
114                 fclose(pidf);
115                 pg_log(PG_FATAL, "%s: invalid data in PID file \"%s\"\n",
116                            os_info.progname, pid_file);
117         }
118
119         fclose(pidf);
120
121         return (pgpid_t) pid;
122 }
123
124
125 /*
126  * get_major_server_version()
127  *
128  * gets the version (in unsigned int form) for the given "datadir". Assumes
129  * that datadir is an absolute path to a valid pgdata directory. The version
130  * is retrieved by reading the PG_VERSION file.
131  */
132 uint32
133 get_major_server_version(ClusterInfo *cluster)
134 {
135         const char *datadir = cluster->pgdata;
136         FILE       *version_fd;
137         char            ver_filename[MAXPGPATH];
138         int                     integer_version = 0;
139         int                     fractional_version = 0;
140
141         snprintf(ver_filename, sizeof(ver_filename), "%s/PG_VERSION", datadir);
142         if ((version_fd = fopen(ver_filename, "r")) == NULL)
143                 return 0;
144
145         if (fscanf(version_fd, "%63s", cluster->major_version_str) == 0 ||
146                 sscanf(cluster->major_version_str, "%d.%d", &integer_version,
147                            &fractional_version) != 2)
148                 pg_log(PG_FATAL, "could not get version from %s\n", datadir);
149
150         fclose(version_fd);
151
152         return (100 * integer_version + fractional_version) * 100;
153 }
154
155
156 static void
157 #ifdef HAVE_ATEXIT
158 stop_postmaster_atexit(void)
159 #else
160 stop_postmaster_on_exit(int exitstatus, void *arg)
161 #endif
162 {
163         stop_postmaster(true, true);
164
165 }
166
167
168 void
169 start_postmaster(ClusterInfo *cluster, bool quiet)
170 {
171         char            cmd[MAXPGPATH];
172         const char *bindir;
173         const char *datadir;
174         unsigned short port;
175         bool            exit_hook_registered = false;
176 #ifndef WIN32
177         char            *output_filename = log_opts.filename;
178 #else
179         char            *output_filename = DEVNULL;
180 #endif
181
182         bindir = cluster->bindir;
183         datadir = cluster->pgdata;
184         port = cluster->port;
185
186         if (!exit_hook_registered)
187         {
188 #ifdef HAVE_ATEXIT
189                 atexit(stop_postmaster_atexit);
190 #else
191                 on_exit(stop_postmaster_on_exit);
192 #endif
193                 exit_hook_registered = true;
194         }
195
196         /*
197          * On Win32, we can't send both pg_upgrade output and pg_ctl output to the
198          * same file because we get the error: "The process cannot access the file
199          * because it is being used by another process." so we have to send all
200          * other output to 'nul'.
201          * Using autovacuum=off disables cleanup vacuum and analyze, but freeze
202          * vacuums can still happen, so we set autovacuum_freeze_max_age to its
203          * maximum.  We assume all datfrozenxid and relfrozen values are less than
204          * a gap of 2000000000 from the current xid counter, so autovacuum will
205          * not touch them.
206          */
207         snprintf(cmd, sizeof(cmd),
208                          SYSTEMQUOTE "\"%s/pg_ctl\" -l \"%s\" -D \"%s\" "
209                          "-o \"-p %d %s\" start >> \"%s\" 2>&1" SYSTEMQUOTE,
210                          bindir, output_filename, datadir, port,
211                          (cluster->controldata.cat_ver >=
212                                 BINARY_UPGRADE_SERVER_FLAG_CAT_VER) ? "-b" :
213                                 "-c autovacuum=off -c autovacuum_freeze_max_age=2000000000",
214                          log_opts.filename);
215
216         exec_prog(true, "%s", cmd);
217
218         /* wait for the server to start properly */
219
220         if (test_server_conn(cluster, POSTMASTER_UPTIME) == false)
221                 pg_log(PG_FATAL, " Unable to start %s postmaster with the command: %s\nPerhaps pg_hba.conf was not set to \"trust\".",
222                            CLUSTER_NAME(cluster), cmd);
223
224         if ((os_info.postmasterPID = get_postmaster_pid(datadir)) == 0)
225                 pg_log(PG_FATAL, " Unable to get postmaster pid\n");
226         os_info.running_cluster = cluster;
227 }
228
229
230 void
231 stop_postmaster(bool fast, bool quiet)
232 {
233         char            cmd[MAXPGPATH];
234         const char *bindir;
235         const char *datadir;
236
237         if (os_info.running_cluster == &old_cluster)
238         {
239                 bindir = old_cluster.bindir;
240                 datadir = old_cluster.pgdata;
241         }
242         else if (os_info.running_cluster == &new_cluster)
243         {
244                 bindir = new_cluster.bindir;
245                 datadir = new_cluster.pgdata;
246         }
247         else
248                 return;                                 /* no cluster running */
249
250         /* See comment in start_postmaster() about why win32 output is ignored. */
251         snprintf(cmd, sizeof(cmd),
252                          SYSTEMQUOTE "\"%s/pg_ctl\" -l \"%s\" -D \"%s\" %s stop >> "
253                          "\"%s\" 2>&1" SYSTEMQUOTE,
254                          bindir,
255 #ifndef WIN32
256            log_opts.filename, datadir, fast ? "-m fast" : "", log_opts.filename);
257 #else
258                          DEVNULL, datadir, fast ? "-m fast" : "", DEVNULL);
259 #endif
260         exec_prog(fast ? false : true, "%s", cmd);
261
262         os_info.postmasterPID = 0;
263         os_info.running_cluster = NULL;
264 }
265
266
267 /*
268  * test_server_conn()
269  *
270  * tests whether postmaster is running or not by trying to connect
271  * to it. If connection is unsuccessfull we do a sleep of 1 sec and then
272  * try the connection again. This process continues "timeout" times.
273  *
274  * Returns true if the connection attempt was successfull, false otherwise.
275  */
276 static bool
277 test_server_conn(ClusterInfo *cluster, int timeout)
278 {
279         unsigned short port = cluster->port;
280         PGconn     *conn = NULL;
281         char            con_opts[MAX_STRING];
282         int                     tries;
283         bool            ret = false;
284
285         snprintf(con_opts, sizeof(con_opts),
286                   "dbname = 'template1' user = '%s' port = %d ", os_info.user, port);
287
288         for (tries = 0; tries < timeout; tries++)
289         {
290                 sleep(1);
291                 if ((conn = PQconnectdb(con_opts)) != NULL &&
292                         PQstatus(conn) == CONNECTION_OK)
293                 {
294                         PQfinish(conn);
295                         ret = true;
296                         break;
297                 }
298
299                 if (tries == STARTUP_WARNING_TRIES)
300                         prep_status("Trying to start %s server ",
301                                                 CLUSTER_NAME(cluster));
302                 else if (tries > STARTUP_WARNING_TRIES)
303                         pg_log(PG_REPORT, ".");
304         }
305
306         if (tries > STARTUP_WARNING_TRIES)
307                 check_ok();
308
309         return ret;
310 }
311
312
313 /*
314  * check_for_libpq_envvars()
315  *
316  * tests whether any libpq environment variables are set.
317  * Since pg_upgrade connects to both the old and the new server,
318  * it is potentially dangerous to have any of these set.
319  *
320  * If any are found, will log them and cancel.
321  */
322 void
323 check_for_libpq_envvars(void)
324 {
325         PQconninfoOption *option;
326         PQconninfoOption *start;
327         bool            found = false;
328
329         /* Get valid libpq env vars from the PQconndefaults function */
330
331         start = PQconndefaults();
332
333         for (option = start; option->keyword != NULL; option++)
334         {
335                 if (option->envvar)
336                 {
337                         const char *value;
338
339                         if (strcmp(option->envvar, "PGCLIENTENCODING") == 0)
340                                 continue;
341
342                         value = getenv(option->envvar);
343                         if (value && strlen(value) > 0)
344                         {
345                                 found = true;
346
347                                 pg_log(PG_WARNING,
348                                            "libpq env var %-20s is currently set to: %s\n", option->envvar, value);
349                         }
350                 }
351         }
352
353         /* Free the memory that libpq allocated on our behalf */
354         PQconninfoFree(start);
355
356         if (found)
357                 pg_log(PG_FATAL,
358                            "libpq env vars have been found and listed above, please unset them for pg_upgrade\n");
359 }