4 * database server functions
6 * Copyright (c) 2010-2014, PostgreSQL Global Development Group
7 * contrib/pg_upgrade/server.c
10 #include "postgres_fe.h"
12 #include "pg_upgrade.h"
15 static PGconn *get_db_conn(ClusterInfo *cluster, const char *db_name);
21 * Connects to the desired database on the designated server.
22 * If the connection attempt fails, this function logs an error
23 * message and calls exit() to kill the program.
26 connectToServer(ClusterInfo *cluster, const char *db_name)
28 PGconn *conn = get_db_conn(cluster, db_name);
30 if (conn == NULL || PQstatus(conn) != CONNECTION_OK)
32 pg_log(PG_REPORT, "connection to database failed: %s\n",
33 PQerrorMessage(conn));
38 printf("Failure, exiting\n");
49 * get database connection, using named database + standard params for cluster
52 get_db_conn(ClusterInfo *cluster, const char *db_name)
54 char conn_opts[2 * NAMEDATALEN + MAXPGPATH + 100];
57 snprintf(conn_opts, sizeof(conn_opts),
58 "dbname = '%s' user = '%s' host = '%s' port = %d",
59 db_name, os_info.user, cluster->sockdir, cluster->port);
61 snprintf(conn_opts, sizeof(conn_opts),
62 "dbname = '%s' user = '%s' port = %d",
63 db_name, os_info.user, cluster->port);
65 return PQconnectdb(conn_opts);
72 * Return standard command-line options for connecting to this cluster when
73 * using psql, pg_dump, etc. Ideally this would match what get_db_conn()
74 * sets, but the utilities we need aren't very consistent about the treatment
75 * of database name options, so we leave that out.
77 * Note result is in static storage, so use it right away.
80 cluster_conn_opts(ClusterInfo *cluster)
82 static char conn_opts[MAXPGPATH + NAMEDATALEN + 100];
85 snprintf(conn_opts, sizeof(conn_opts),
86 "--host \"%s\" --port %d --username \"%s\"",
87 cluster->sockdir, cluster->port, os_info.user);
89 snprintf(conn_opts, sizeof(conn_opts),
90 "--port %d --username \"%s\"",
91 cluster->port, os_info.user);
100 * Formats a query string from the given arguments and executes the
101 * resulting query. If the query fails, this function logs an error
102 * message and calls exit() to kill the program.
105 executeQueryOrDie(PGconn *conn, const char *fmt,...)
107 static char command[8192];
110 ExecStatusType status;
113 vsnprintf(command, sizeof(command), fmt, args);
116 pg_log(PG_VERBOSE, "executing: %s\n", command);
117 result = PQexec(conn, command);
118 status = PQresultStatus(result);
120 if ((status != PGRES_TUPLES_OK) && (status != PGRES_COMMAND_OK))
122 pg_log(PG_REPORT, "SQL command failed\n%s\n%s\n", command,
123 PQerrorMessage(conn));
126 printf("Failure, exiting\n");
135 * get_major_server_version()
137 * gets the version (in unsigned int form) for the given datadir. Assumes
138 * that datadir is an absolute path to a valid pgdata directory. The version
139 * is retrieved by reading the PG_VERSION file.
142 get_major_server_version(ClusterInfo *cluster)
145 char ver_filename[MAXPGPATH];
146 int integer_version = 0;
147 int fractional_version = 0;
149 snprintf(ver_filename, sizeof(ver_filename), "%s/PG_VERSION",
151 if ((version_fd = fopen(ver_filename, "r")) == NULL)
152 pg_fatal("could not open version file: %s\n", ver_filename);
154 if (fscanf(version_fd, "%63s", cluster->major_version_str) == 0 ||
155 sscanf(cluster->major_version_str, "%d.%d", &integer_version,
156 &fractional_version) != 2)
157 pg_fatal("could not get version from %s\n", cluster->pgdata);
161 return (100 * integer_version + fractional_version) * 100;
166 stop_postmaster_atexit(void)
168 stop_postmaster(true);
173 start_postmaster(ClusterInfo *cluster, bool throw_error)
175 char cmd[MAXPGPATH * 4 + 1000];
177 bool exit_hook_registered = false;
178 bool pg_ctl_return = false;
179 char socket_string[MAXPGPATH + 200];
181 if (!exit_hook_registered)
183 atexit(stop_postmaster_atexit);
184 exit_hook_registered = true;
187 socket_string[0] = '\0';
189 #ifdef HAVE_UNIX_SOCKETS
190 /* prevent TCP/IP connections, restrict socket access */
191 strcat(socket_string,
192 " -c listen_addresses='' -c unix_socket_permissions=0700");
194 /* Have a sockdir? Tell the postmaster. */
195 if (cluster->sockdir)
196 snprintf(socket_string + strlen(socket_string),
197 sizeof(socket_string) - strlen(socket_string),
199 (GET_MAJOR_VERSION(cluster->major_version) < 903) ?
200 "unix_socket_directory" : "unix_socket_directories",
205 * Using autovacuum=off disables cleanup vacuum and analyze, but freeze
206 * vacuums can still happen, so we set autovacuum_freeze_max_age and
207 * autovacuum_multixact_freeze_max_age to their maximums. We assume all
208 * datfrozenxid, relfrozenxid, and relminmxid values are less than a gap
209 * of 2000000000 from the current xid counter, so autovacuum will not
212 * Turn off durability requirements to improve object creation speed, and
213 * we only modify the new cluster, so only use it there. If there is a
214 * crash, the new cluster has to be recreated anyway. fsync=off is a big
217 snprintf(cmd, sizeof(cmd),
218 "\"%s/pg_ctl\" -w -l \"%s\" -D \"%s\" -o \"-p %d%s%s %s%s%s\" start",
219 cluster->bindir, SERVER_LOG_FILE, cluster->pgconfig, cluster->port,
220 (cluster->controldata.cat_ver >=
221 BINARY_UPGRADE_SERVER_FLAG_CAT_VER) ? " -b" :
222 " -c autovacuum=off -c autovacuum_freeze_max_age=2000000000",
223 (GET_MAJOR_VERSION(cluster->major_version) >= 903) ?
224 " -c autovacuum_multixact_freeze_max_age=2000000000" : "",
225 (cluster == &new_cluster) ?
226 " -c synchronous_commit=off -c fsync=off -c full_page_writes=off" : "",
227 cluster->pgopts ? cluster->pgopts : "", socket_string);
230 * Don't throw an error right away, let connecting throw the error because
231 * it might supply a reason for the failure.
233 pg_ctl_return = exec_prog(SERVER_START_LOG_FILE,
234 /* pass both file names if they differ */
235 (strcmp(SERVER_LOG_FILE,
236 SERVER_START_LOG_FILE) != 0) ?
237 SERVER_LOG_FILE : NULL,
241 /* Did it fail and we are just testing if the server could be started? */
242 if (!pg_ctl_return && !throw_error)
246 * We set this here to make sure atexit() shuts down the server, but only
247 * if we started the server successfully. We do it before checking for
248 * connectivity in case the server started but there is a connectivity
249 * failure. If pg_ctl did not return success, we will exit below.
251 * Pre-9.1 servers do not have PQping(), so we could be leaving the server
252 * running if authentication was misconfigured, so someday we might went
253 * to be more aggressive about doing server shutdowns even if pg_ctl
254 * fails, but now (2013-08-14) it seems prudent to be cautious. We don't
255 * want to shutdown a server that might have been accidentally started
256 * during the upgrade.
259 os_info.running_cluster = cluster;
262 * pg_ctl -w might have failed because the server couldn't be started, or
263 * there might have been a connection problem in _checking_ if the server
264 * has started. Therefore, even if pg_ctl failed, we continue and test
265 * for connectivity in case we get a connection reason for the failure.
267 if ((conn = get_db_conn(cluster, "template1")) == NULL ||
268 PQstatus(conn) != CONNECTION_OK)
270 pg_log(PG_REPORT, "\nconnection to database failed: %s\n",
271 PQerrorMessage(conn));
274 pg_fatal("could not connect to %s postmaster started with the command:\n"
276 CLUSTER_NAME(cluster), cmd);
281 * If pg_ctl failed, and the connection didn't fail, and throw_error is
282 * enabled, fail now. This could happen if the server was already
286 pg_fatal("pg_ctl failed to start the %s server, or connection failed\n",
287 CLUSTER_NAME(cluster));
294 stop_postmaster(bool fast)
296 ClusterInfo *cluster;
298 if (os_info.running_cluster == &old_cluster)
299 cluster = &old_cluster;
300 else if (os_info.running_cluster == &new_cluster)
301 cluster = &new_cluster;
303 return; /* no cluster running */
305 exec_prog(SERVER_STOP_LOG_FILE, NULL, !fast,
306 "\"%s/pg_ctl\" -w -D \"%s\" -o \"%s\" %s stop",
307 cluster->bindir, cluster->pgconfig,
308 cluster->pgopts ? cluster->pgopts : "",
309 fast ? "-m fast" : "");
311 os_info.running_cluster = NULL;
316 * check_pghost_envvar()
318 * Tests that PGHOST does not point to a non-local server
321 check_pghost_envvar(void)
323 PQconninfoOption *option;
324 PQconninfoOption *start;
326 /* Get valid libpq env vars from the PQconndefaults function */
328 start = PQconndefaults();
331 pg_fatal("out of memory\n");
333 for (option = start; option->keyword != NULL; option++)
335 if (option->envvar && (strcmp(option->envvar, "PGHOST") == 0 ||
336 strcmp(option->envvar, "PGHOSTADDR") == 0))
338 const char *value = getenv(option->envvar);
340 if (value && strlen(value) > 0 &&
341 /* check for 'local' host values */
342 (strcmp(value, "localhost") != 0 && strcmp(value, "127.0.0.1") != 0 &&
343 strcmp(value, "::1") != 0 && value[0] != '/'))
344 pg_fatal("libpq environment variable %s has a non-local server value: %s\n",
345 option->envvar, value);
349 /* Free the memory that libpq allocated on our behalf */
350 PQconninfoFree(start);