PostgreSQL Source Code git master
Loading...
Searching...
No Matches
server.c
Go to the documentation of this file.
1/*
2 * server.c
3 *
4 * database server functions
5 *
6 * Copyright (c) 2010-2026, PostgreSQL Global Development Group
7 * src/bin/pg_upgrade/server.c
8 */
9
10#include "postgres_fe.h"
11
12#include "common/connect.h"
14#include "libpq/pqcomm.h"
15#include "pg_upgrade.h"
16
17static 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 */
27PGconn *
28connectToServer(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 {
35
36 if (conn)
38
39 printf(_("Failure, exiting\n"));
40 exit(1);
41 }
42
44
45 return conn;
46}
47
48
49/*
50 * get_db_conn()
51 *
52 * get database connection, using named database + standard params for cluster
53 *
54 * Caller must check for connection failure!
55 */
56static PGconn *
57get_db_conn(ClusterInfo *cluster, const char *db_name)
58{
60 PGconn *conn;
61
62 /* Build connection string with proper quoting */
65 appendConnStrVal(&conn_opts, db_name);
68 appendPQExpBuffer(&conn_opts, " port=%d", cluster->port);
69 if (cluster->sockdir)
70 {
73 }
75 appendPQExpBufferStr(&conn_opts, " max_protocol_version=3.0");
76
79 return conn;
80}
81
82
83/*
84 * cluster_conn_opts()
85 *
86 * Return standard command-line options for connecting to this cluster when
87 * using psql, pg_dump, etc. Ideally this would match what get_db_conn()
88 * sets, but the utilities we need aren't very consistent about the treatment
89 * of database name options, so we leave that out.
90 *
91 * Result is valid until the next call to this function.
92 */
93char *
95{
96 static PQExpBuffer buf;
97
98 if (buf == NULL)
100 else
102
103 if (cluster->sockdir)
104 {
105 appendPQExpBufferStr(buf, "--host ");
106 appendShellString(buf, cluster->sockdir);
108 }
109 appendPQExpBuffer(buf, "--port %d --username ", cluster->port);
111
112 return buf->data;
113}
114
115
116/*
117 * executeQueryOrDie()
118 *
119 * Formats a query string from the given arguments and executes the
120 * resulting query. If the query fails, this function logs an error
121 * message and calls exit() to kill the program.
122 */
123PGresult *
125{
126 static char query[QUERY_ALLOC];
127 va_list args;
128 PGresult *result;
129 ExecStatusType status;
130
131 va_start(args, fmt);
132 vsnprintf(query, sizeof(query), fmt, args);
133 va_end(args);
134
135 pg_log(PG_VERBOSE, "executing: %s", query);
136 result = PQexec(conn, query);
137 status = PQresultStatus(result);
138
139 if ((status != PGRES_TUPLES_OK) && (status != PGRES_COMMAND_OK))
140 {
141 pg_log(PG_REPORT, "SQL command failed\n%s\n%s", query,
143 PQclear(result);
144 PQfinish(conn);
145 printf(_("Failure, exiting\n"));
146 exit(1);
147 }
148 else
149 return result;
150}
151
152
153static void
155{
156 stop_postmaster(true);
157}
158
159
160bool
162{
163 char cmd[MAXPGPATH * 4 + 1000];
164 PGconn *conn;
165 bool pg_ctl_return = false;
166 char socket_string[MAXPGPATH + 200];
167 PQExpBufferData pgoptions;
168
169 static bool exit_hook_registered = false;
170
172 {
175 }
176
177 socket_string[0] = '\0';
178
179#if !defined(WIN32)
180 /* prevent TCP/IP connections, restrict socket access */
182 " -c listen_addresses='' -c unix_socket_permissions=0700");
183
184 /* Have a sockdir? Tell the postmaster. */
185 if (cluster->sockdir)
188 " -c %s='%s'",
189 (GET_MAJOR_VERSION(cluster->major_version) <= 902) ?
190 "unix_socket_directory" : "unix_socket_directories",
191 cluster->sockdir);
192#endif
193
194 initPQExpBuffer(&pgoptions);
195
196 /*
197 * Construct a parameter string which is passed to the server process.
198 *
199 * Turn off durability requirements to improve object creation speed, and
200 * we only modify the new cluster, so only use it there. If there is a
201 * crash, the new cluster has to be recreated anyway. fsync=off is a big
202 * win on ext4.
203 */
204 if (cluster == &new_cluster)
205 appendPQExpBufferStr(&pgoptions, " -c synchronous_commit=off -c fsync=off -c full_page_writes=off");
206
207 /*
208 * Use -b to disable autovacuum and logical replication launcher
209 * (effective in PG17 or later for the latter).
210 */
211 snprintf(cmd, sizeof(cmd),
212 "\"%s/pg_ctl\" -w -l \"%s/%s\" -D \"%s\" -o \"-p %d -b%s %s%s\" start",
213 cluster->bindir,
215 SERVER_LOG_FILE, cluster->pgconfig, cluster->port,
216 pgoptions.data,
217 cluster->pgopts ? cluster->pgopts : "", socket_string);
218
219 termPQExpBuffer(&pgoptions);
220
221 /*
222 * Don't throw an error right away, let connecting throw the error because
223 * it might supply a reason for the failure.
224 */
226 /* pass both file names if they differ */
228 SERVER_START_LOG_FILE) != 0) ?
231 "%s", cmd);
232
233 /* Did it fail and we are just testing if the server could be started? */
235 return false;
236
237 /*
238 * We set this here to make sure atexit() shuts down the server, but only
239 * if we started the server successfully. We do it before checking for
240 * connectivity in case the server started but there is a connectivity
241 * failure. If pg_ctl did not return success, we will exit below.
242 *
243 * Pre-9.1 servers do not have PQping(), so we could be leaving the server
244 * running if authentication was misconfigured, so someday we might went
245 * to be more aggressive about doing server shutdowns even if pg_ctl
246 * fails, but now (2013-08-14) it seems prudent to be cautious. We don't
247 * want to shutdown a server that might have been accidentally started
248 * during the upgrade.
249 */
250 if (pg_ctl_return)
252
253 /*
254 * pg_ctl -w might have failed because the server couldn't be started, or
255 * there might have been a connection problem in _checking_ if the server
256 * has started. Therefore, even if pg_ctl failed, we continue and test
257 * for connectivity in case we get a connection reason for the failure.
258 */
259 if ((conn = get_db_conn(cluster, "template1")) == NULL ||
261 {
263 if (conn)
264 PQfinish(conn);
265 if (cluster == &old_cluster)
266 pg_fatal("could not connect to source postmaster started with the command:\n"
267 "%s",
268 cmd);
269 else
270 pg_fatal("could not connect to target postmaster started with the command:\n"
271 "%s",
272 cmd);
273 }
274 PQfinish(conn);
275
276 /*
277 * If pg_ctl failed, and the connection didn't fail, and
278 * report_and_exit_on_error is enabled, fail now. This could happen if
279 * the server was already running.
280 */
281 if (!pg_ctl_return)
282 {
283 if (cluster == &old_cluster)
284 pg_fatal("pg_ctl failed to start the source server, or connection failed");
285 else
286 pg_fatal("pg_ctl failed to start the target server, or connection failed");
287 }
288
289 return true;
290}
291
292
293void
295{
297
302 else
303 return; /* no cluster running */
304
306 "\"%s/pg_ctl\" -w -D \"%s\" -o \"%s\" %s stop",
307 cluster->bindir, cluster->pgconfig,
308 cluster->pgopts ? cluster->pgopts : "",
309 in_atexit ? "-m fast" : "-m smart");
310
312}
313
314
315/*
316 * check_pghost_envvar()
317 *
318 * Tests that PGHOST does not point to a non-local server
319 */
320void
322{
325
326 /* Get valid libpq env vars from the PQconndefaults function */
327
329
330 if (!start)
331 pg_fatal("out of memory");
332
333 for (option = start; option->keyword != NULL; option++)
334 {
335 if (option->envvar && (strcmp(option->envvar, "PGHOST") == 0 ||
336 strcmp(option->envvar, "PGHOSTADDR") == 0))
337 {
338 const char *value = getenv(option->envvar);
339
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 && !is_unixsock_path(value)))
344 pg_fatal("libpq environment variable %s has a non-local server value: %s",
345 option->envvar, value);
346 }
347 }
348
349 /* Free the memory that libpq allocated on our behalf */
351}
bool exec_prog(const char *log_filename, const char *opt_log_file, bool report_error, bool exit_on_error, const char *fmt,...)
Definition exec.c:86
void cluster(ParseState *pstate, ClusterStmt *stmt, bool isTopLevel)
Definition cluster.c:107
#define ALWAYS_SECURE_SEARCH_PATH_SQL
Definition connect.h:25
#define _(x)
Definition elog.c:95
PGconn * PQconnectdb(const char *conninfo)
Definition fe-connect.c:826
void PQconninfoFree(PQconninfoOption *connOptions)
ConnStatusType PQstatus(const PGconn *conn)
void PQfinish(PGconn *conn)
PQconninfoOption * PQconndefaults(void)
char * PQerrorMessage(const PGconn *conn)
PGresult * PQexec(PGconn *conn, const char *query)
Definition fe-exec.c:2279
return str start
static struct @174 value
#define PQclear
#define PQresultStatus
@ CONNECTION_OK
Definition libpq-fe.h:84
ExecStatusType
Definition libpq-fe.h:123
@ PGRES_COMMAND_OK
Definition libpq-fe.h:125
@ PGRES_TUPLES_OK
Definition libpq-fe.h:128
#define pg_fatal(...)
#define MAXPGPATH
static pid_t start_postmaster(void)
Definition pg_ctl.c:441
static void stop_postmaster(void)
Definition pg_regress.c:433
static char buf[DEFAULT_XLOG_SEG_SIZE]
OSInfo os_info
Definition pg_upgrade.c:75
ClusterInfo new_cluster
Definition pg_upgrade.c:74
ClusterInfo old_cluster
Definition pg_upgrade.c:73
#define SERVER_START_LOG_FILE
Definition pg_upgrade.h:67
#define SERVER_STOP_LOG_FILE
Definition pg_upgrade.h:68
#define QUERY_ALLOC
Definition pg_upgrade.h:23
void void pg_log(eLogType type, const char *fmt,...) pg_attribute_printf(2
#define SERVER_LOG_FILE
Definition pg_upgrade.h:44
LogOpts log_opts
Definition util.c:17
@ PG_VERBOSE
Definition pg_upgrade.h:280
@ PG_REPORT
Definition pg_upgrade.h:283
#define GET_MAJOR_VERSION(v)
Definition pg_upgrade.h:27
bool protocol_negotiation_supported(const ClusterInfo *cluster)
Definition version.c:36
#define vsnprintf
Definition port.h:259
#define snprintf
Definition port.h:260
#define printf(...)
Definition port.h:266
static bool is_unixsock_path(const char *path)
Definition pqcomm.h:66
PQExpBuffer createPQExpBuffer(void)
Definition pqexpbuffer.c:72
void initPQExpBuffer(PQExpBuffer str)
Definition pqexpbuffer.c:90
void resetPQExpBuffer(PQExpBuffer str)
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
void appendPQExpBufferChar(PQExpBuffer str, char ch)
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
void termPQExpBuffer(PQExpBuffer str)
static int fb(int x)
static PGconn * get_db_conn(ClusterInfo *cluster, const char *db_name)
Definition server.c:57
void check_pghost_envvar(void)
Definition server.c:321
PGresult * executeQueryOrDie(PGconn *conn, const char *fmt,...)
Definition server.c:124
PGconn * connectToServer(ClusterInfo *cluster, const char *db_name)
Definition server.c:28
char * cluster_conn_opts(ClusterInfo *cluster)
Definition server.c:94
static void stop_postmaster_atexit(void)
Definition server.c:154
PGconn * conn
Definition streamutil.c:52
void appendShellString(PQExpBuffer buf, const char *str)
void appendConnStrVal(PQExpBuffer buf, const char *str)
char * logdir
Definition pg_upgrade.h:331
char * user
Definition pg_upgrade.h:366
ClusterInfo * running_cluster
Definition pg_upgrade.h:370