1 /*
2  *	server.c
3  *
4  *	database server functions
5  *
6  *	Copyright (c) 2010-2016, PostgreSQL Global Development Group
7  *	src/bin/pg_upgrade/server.c
8  */
9 
10 #include "postgres_fe.h"
11 
12 #include "fe_utils/connect.h"
13 #include "fe_utils/string_utils.h"
14 #include "pg_upgrade.h"
15 
16 
17 static PGconn *get_db_conn(ClusterInfo *cluster, const char *db_name);
18 
19 
20 /*
21  * connectToServer()
22  *
23  *	Connects to the desired database on the designated server.
24  *	If the connection attempt fails, this function logs an error
25  *	message and calls exit() to kill the program.
26  */
27 PGconn *
connectToServer(ClusterInfo * cluster,const char * db_name)28 connectToServer(ClusterInfo *cluster, const char *db_name)
29 {
30 	PGconn	   *conn = get_db_conn(cluster, db_name);
31 
32 	if (conn == NULL || PQstatus(conn) != CONNECTION_OK)
33 	{
34 		pg_log(PG_REPORT, "connection to database failed: %s\n",
35 			   PQerrorMessage(conn));
36 
37 		if (conn)
38 			PQfinish(conn);
39 
40 		printf("Failure, exiting\n");
41 		exit(1);
42 	}
43 
44 	PQclear(executeQueryOrDie(conn, ALWAYS_SECURE_SEARCH_PATH_SQL));
45 
46 	return conn;
47 }
48 
49 
50 /*
51  * get_db_conn()
52  *
53  * get database connection, using named database + standard params for cluster
54  */
55 static PGconn *
get_db_conn(ClusterInfo * cluster,const char * db_name)56 get_db_conn(ClusterInfo *cluster, const char *db_name)
57 {
58 	PQExpBufferData conn_opts;
59 	PGconn	   *conn;
60 
61 	/* Build connection string with proper quoting */
62 	initPQExpBuffer(&conn_opts);
63 	appendPQExpBufferStr(&conn_opts, "dbname=");
64 	appendConnStrVal(&conn_opts, db_name);
65 	appendPQExpBufferStr(&conn_opts, " user=");
66 	appendConnStrVal(&conn_opts, os_info.user);
67 	appendPQExpBuffer(&conn_opts, " port=%d", cluster->port);
68 	if (cluster->sockdir)
69 	{
70 		appendPQExpBufferStr(&conn_opts, " host=");
71 		appendConnStrVal(&conn_opts, cluster->sockdir);
72 	}
73 
74 	conn = PQconnectdb(conn_opts.data);
75 	termPQExpBuffer(&conn_opts);
76 	return conn;
77 }
78 
79 
80 /*
81  * cluster_conn_opts()
82  *
83  * Return standard command-line options for connecting to this cluster when
84  * using psql, pg_dump, etc.  Ideally this would match what get_db_conn()
85  * sets, but the utilities we need aren't very consistent about the treatment
86  * of database name options, so we leave that out.
87  *
88  * Result is valid until the next call to this function.
89  */
90 char *
cluster_conn_opts(ClusterInfo * cluster)91 cluster_conn_opts(ClusterInfo *cluster)
92 {
93 	static PQExpBuffer buf;
94 
95 	if (buf == NULL)
96 		buf = createPQExpBuffer();
97 	else
98 		resetPQExpBuffer(buf);
99 
100 	if (cluster->sockdir)
101 	{
102 		appendPQExpBufferStr(buf, "--host ");
103 		appendShellString(buf, cluster->sockdir);
104 		appendPQExpBufferChar(buf, ' ');
105 	}
106 	appendPQExpBuffer(buf, "--port %d --username ", cluster->port);
107 	appendShellString(buf, os_info.user);
108 
109 	return buf->data;
110 }
111 
112 
113 /*
114  * executeQueryOrDie()
115  *
116  *	Formats a query string from the given arguments and executes the
117  *	resulting query.  If the query fails, this function logs an error
118  *	message and calls exit() to kill the program.
119  */
120 PGresult *
executeQueryOrDie(PGconn * conn,const char * fmt,...)121 executeQueryOrDie(PGconn *conn, const char *fmt,...)
122 {
123 	static char query[QUERY_ALLOC];
124 	va_list		args;
125 	PGresult   *result;
126 	ExecStatusType status;
127 
128 	va_start(args, fmt);
129 	vsnprintf(query, sizeof(query), fmt, args);
130 	va_end(args);
131 
132 	pg_log(PG_VERBOSE, "executing: %s\n", query);
133 	result = PQexec(conn, query);
134 	status = PQresultStatus(result);
135 
136 	if ((status != PGRES_TUPLES_OK) && (status != PGRES_COMMAND_OK))
137 	{
138 		pg_log(PG_REPORT, "SQL command failed\n%s\n%s\n", query,
139 			   PQerrorMessage(conn));
140 		PQclear(result);
141 		PQfinish(conn);
142 		printf("Failure, exiting\n");
143 		exit(1);
144 	}
145 	else
146 		return result;
147 }
148 
149 
150 /*
151  * get_major_server_version()
152  *
153  * gets the version (in unsigned int form) for the given datadir. Assumes
154  * that datadir is an absolute path to a valid pgdata directory. The version
155  * is retrieved by reading the PG_VERSION file.
156  */
157 uint32
get_major_server_version(ClusterInfo * cluster)158 get_major_server_version(ClusterInfo *cluster)
159 {
160 	FILE	   *version_fd;
161 	char		ver_filename[MAXPGPATH];
162 	int			integer_version = 0;
163 	int			fractional_version = 0;
164 
165 	snprintf(ver_filename, sizeof(ver_filename), "%s/PG_VERSION",
166 			 cluster->pgdata);
167 	if ((version_fd = fopen(ver_filename, "r")) == NULL)
168 		pg_fatal("could not open version file \"%s\"\n", ver_filename);
169 
170 	if (fscanf(version_fd, "%63s", cluster->major_version_str) == 0 ||
171 		sscanf(cluster->major_version_str, "%d.%d", &integer_version,
172 			   &fractional_version) != 2)
173 		pg_fatal("could not parse version file \"%s\"\n", ver_filename);
174 
175 	fclose(version_fd);
176 
177 	return (100 * integer_version + fractional_version) * 100;
178 }
179 
180 
181 static void
stop_postmaster_atexit(void)182 stop_postmaster_atexit(void)
183 {
184 	stop_postmaster(true);
185 }
186 
187 
188 bool
start_postmaster(ClusterInfo * cluster,bool throw_error)189 start_postmaster(ClusterInfo *cluster, bool throw_error)
190 {
191 	char		cmd[MAXPGPATH * 4 + 1000];
192 	PGconn	   *conn;
193 	bool		pg_ctl_return = false;
194 	char		socket_string[MAXPGPATH + 200];
195 
196 	static bool exit_hook_registered = false;
197 
198 	if (!exit_hook_registered)
199 	{
200 		atexit(stop_postmaster_atexit);
201 		exit_hook_registered = true;
202 	}
203 
204 	socket_string[0] = '\0';
205 
206 #ifdef HAVE_UNIX_SOCKETS
207 	/* prevent TCP/IP connections, restrict socket access */
208 	strcat(socket_string,
209 		   " -c listen_addresses='' -c unix_socket_permissions=0700");
210 
211 	/* Have a sockdir?	Tell the postmaster. */
212 	if (cluster->sockdir)
213 		snprintf(socket_string + strlen(socket_string),
214 				 sizeof(socket_string) - strlen(socket_string),
215 				 " -c %s='%s'",
216 				 (GET_MAJOR_VERSION(cluster->major_version) <= 902) ?
217 				 "unix_socket_directory" : "unix_socket_directories",
218 				 cluster->sockdir);
219 #endif
220 
221 	/*
222 	 * Since PG 9.1, we have used -b to disable autovacuum.  For earlier
223 	 * releases, setting autovacuum=off disables cleanup vacuum and analyze,
224 	 * but freeze vacuums can still happen, so we set
225 	 * autovacuum_freeze_max_age to its maximum.
226 	 * (autovacuum_multixact_freeze_max_age was introduced after 9.1, so there
227 	 * is no need to set that.)  We assume all datfrozenxid and relfrozenxid
228 	 * values are less than a gap of 2000000000 from the current xid counter,
229 	 * so autovacuum will not touch them.
230 	 *
231 	 * Turn off durability requirements to improve object creation speed, and
232 	 * we only modify the new cluster, so only use it there.  If there is a
233 	 * crash, the new cluster has to be recreated anyway.  fsync=off is a big
234 	 * win on ext4.
235 	 *
236 	 * Force vacuum_defer_cleanup_age to 0 on the new cluster, so that
237 	 * vacuumdb --freeze actually freezes the tuples.
238 	 */
239 	snprintf(cmd, sizeof(cmd),
240 		  "\"%s/pg_ctl\" -w -l \"%s\" -D \"%s\" -o \"-p %d%s%s %s%s\" start",
241 		  cluster->bindir, SERVER_LOG_FILE, cluster->pgconfig, cluster->port,
242 			 (cluster->controldata.cat_ver >=
243 			  BINARY_UPGRADE_SERVER_FLAG_CAT_VER) ? " -b" :
244 			 " -c autovacuum=off -c autovacuum_freeze_max_age=2000000000",
245 			 (cluster == &new_cluster) ?
246 	  " -c synchronous_commit=off -c fsync=off -c full_page_writes=off -c vacuum_defer_cleanup_age=0" : "",
247 			 cluster->pgopts ? cluster->pgopts : "", socket_string);
248 
249 	/*
250 	 * Don't throw an error right away, let connecting throw the error because
251 	 * it might supply a reason for the failure.
252 	 */
253 	pg_ctl_return = exec_prog(SERVER_START_LOG_FILE,
254 	/* pass both file names if they differ */
255 							  (strcmp(SERVER_LOG_FILE,
256 									  SERVER_START_LOG_FILE) != 0) ?
257 							  SERVER_LOG_FILE : NULL,
258 							  false,
259 							  "%s", cmd);
260 
261 	/* Did it fail and we are just testing if the server could be started? */
262 	if (!pg_ctl_return && !throw_error)
263 		return false;
264 
265 	/*
266 	 * We set this here to make sure atexit() shuts down the server, but only
267 	 * if we started the server successfully.  We do it before checking for
268 	 * connectivity in case the server started but there is a connectivity
269 	 * failure.  If pg_ctl did not return success, we will exit below.
270 	 *
271 	 * Pre-9.1 servers do not have PQping(), so we could be leaving the server
272 	 * running if authentication was misconfigured, so someday we might went
273 	 * to be more aggressive about doing server shutdowns even if pg_ctl
274 	 * fails, but now (2013-08-14) it seems prudent to be cautious.  We don't
275 	 * want to shutdown a server that might have been accidentally started
276 	 * during the upgrade.
277 	 */
278 	if (pg_ctl_return)
279 		os_info.running_cluster = cluster;
280 
281 	/*
282 	 * pg_ctl -w might have failed because the server couldn't be started, or
283 	 * there might have been a connection problem in _checking_ if the server
284 	 * has started.  Therefore, even if pg_ctl failed, we continue and test
285 	 * for connectivity in case we get a connection reason for the failure.
286 	 */
287 	if ((conn = get_db_conn(cluster, "template1")) == NULL ||
288 		PQstatus(conn) != CONNECTION_OK)
289 	{
290 		pg_log(PG_REPORT, "\nconnection to database failed: %s\n",
291 			   PQerrorMessage(conn));
292 		if (conn)
293 			PQfinish(conn);
294 		pg_fatal("could not connect to %s postmaster started with the command:\n"
295 				 "%s\n",
296 				 CLUSTER_NAME(cluster), cmd);
297 	}
298 	PQfinish(conn);
299 
300 	/*
301 	 * If pg_ctl failed, and the connection didn't fail, and throw_error is
302 	 * enabled, fail now.  This could happen if the server was already
303 	 * running.
304 	 */
305 	if (!pg_ctl_return)
306 		pg_fatal("pg_ctl failed to start the %s server, or connection failed\n",
307 				 CLUSTER_NAME(cluster));
308 
309 	return true;
310 }
311 
312 
313 void
stop_postmaster(bool fast)314 stop_postmaster(bool fast)
315 {
316 	ClusterInfo *cluster;
317 
318 	if (os_info.running_cluster == &old_cluster)
319 		cluster = &old_cluster;
320 	else if (os_info.running_cluster == &new_cluster)
321 		cluster = &new_cluster;
322 	else
323 		return;					/* no cluster running */
324 
325 	exec_prog(SERVER_STOP_LOG_FILE, NULL, !fast,
326 			  "\"%s/pg_ctl\" -w -D \"%s\" -o \"%s\" %s stop",
327 			  cluster->bindir, cluster->pgconfig,
328 			  cluster->pgopts ? cluster->pgopts : "",
329 			  fast ? "-m fast" : "-m smart");
330 
331 	os_info.running_cluster = NULL;
332 }
333 
334 
335 /*
336  * check_pghost_envvar()
337  *
338  * Tests that PGHOST does not point to a non-local server
339  */
340 void
check_pghost_envvar(void)341 check_pghost_envvar(void)
342 {
343 	PQconninfoOption *option;
344 	PQconninfoOption *start;
345 
346 	/* Get valid libpq env vars from the PQconndefaults function */
347 
348 	start = PQconndefaults();
349 
350 	if (!start)
351 		pg_fatal("out of memory\n");
352 
353 	for (option = start; option->keyword != NULL; option++)
354 	{
355 		if (option->envvar && (strcmp(option->envvar, "PGHOST") == 0 ||
356 							   strcmp(option->envvar, "PGHOSTADDR") == 0))
357 		{
358 			const char *value = getenv(option->envvar);
359 
360 			if (value && strlen(value) > 0 &&
361 			/* check for 'local' host values */
362 				(strcmp(value, "localhost") != 0 && strcmp(value, "127.0.0.1") != 0 &&
363 				 strcmp(value, "::1") != 0 && value[0] != '/'))
364 				pg_fatal("libpq environment variable %s has a non-local server value: %s\n",
365 						 option->envvar, value);
366 		}
367 	}
368 
369 	/* Free the memory that libpq allocated on our behalf */
370 	PQconninfoFree(start);
371 }
372