Debian Codegraph @

src/bin/pg_upgrade/server.c

raw
1 /*
2 * server.c
3 *
4 * database server functions
5 *
6 * Copyright (c) 2010-2025, PostgreSQL Global Development Group
7 * src/bin/pg_upgrade/server.c
8 */
9
10 #include "postgres_fe.h"
11
12 #include "common/connect.h"
13 #include "fe_utils/string_utils.h"
14 #include "libpq/pqcomm.h"
15 #include "pg_upgrade.h"
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 *
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, "%s", PQerrorMessage(conn));
35
36 if (conn)
37 PQfinish(conn);
38
39 printf(_("Failure, exiting\n"));
40 exit(1);
41 }
42
43 PQclear(executeQueryOrDie(conn, ALWAYS_SECURE_SEARCH_PATH_SQL));
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 */
56 static PGconn *
57 get_db_conn(ClusterInfo *cluster, const char *db_name)
58 {
59 PQExpBufferData conn_opts;
60 PGconn *conn;
61
62 /* Build connection string with proper quoting */
63 initPQExpBuffer(&conn_opts);
64 appendPQExpBufferStr(&conn_opts, "dbname=");
65 appendConnStrVal(&conn_opts, db_name);
66 appendPQExpBufferStr(&conn_opts, " user=");
67 appendConnStrVal(&conn_opts, os_info.user);
68 appendPQExpBuffer(&conn_opts, " port=%d", cluster->port);
69 if (cluster->sockdir)
70 {
71 appendPQExpBufferStr(&conn_opts, " host=");
72 appendConnStrVal(&conn_opts, cluster->sockdir);
73 }
74 if (!protocol_negotiation_supported(cluster))
75 appendPQExpBufferStr(&conn_opts, " max_protocol_version=3.0");
76
77 conn = PQconnectdb(conn_opts.data);
78 termPQExpBuffer(&conn_opts);
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 */
93 char *
94 cluster_conn_opts(ClusterInfo *cluster)
95 {
96 static PQExpBuffer buf;
97
98 if (buf == NULL)
99 buf = createPQExpBuffer();
100 else
101 resetPQExpBuffer(buf);
102
103 if (cluster->sockdir)
104 {
105 appendPQExpBufferStr(buf, "--host ");
106 appendShellString(buf, cluster->sockdir);
107 appendPQExpBufferChar(buf, ' ');
108 }
109 appendPQExpBuffer(buf, "--port %d --username ", cluster->port);
110 appendShellString(buf, os_info.user);
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 */
123 PGresult *
124 executeQueryOrDie(PGconn *conn, const char *fmt,...)
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,
142 PQerrorMessage(conn));
143 PQclear(result);
144 PQfinish(conn);
145 printf(_("Failure, exiting\n"));
146 exit(1);
147 }
148 else
149 return result;
150 }
151
152
153 /*
154 * get_major_server_version()
155 *
156 * gets the version (in unsigned int form) for the given datadir. Assumes
157 * that datadir is an absolute path to a valid pgdata directory. The version
158 * is retrieved by reading the PG_VERSION file.
159 */
160 uint32
161 get_major_server_version(ClusterInfo *cluster)
162 {
163 FILE *version_fd;
164 char ver_filename[MAXPGPATH];
165 int v1 = 0,
166 v2 = 0;
167
168 snprintf(ver_filename, sizeof(ver_filename), "%s/PG_VERSION",
169 cluster->pgdata);
170 if ((version_fd = fopen(ver_filename, "r")) == NULL)
171 pg_fatal("could not open version file \"%s\": %m", ver_filename);
172
173 if (fscanf(version_fd, "%63s", cluster->major_version_str) == 0 ||
174 sscanf(cluster->major_version_str, "%d.%d", &v1, &v2) < 1)
175 pg_fatal("could not parse version file \"%s\"", ver_filename);
176
177 fclose(version_fd);
178
179 if (v1 < 10)
180 {
181 /* old style, e.g. 9.6.1 */
182 return v1 * 10000 + v2 * 100;
183 }
184 else
185 {
186 /* new style, e.g. 10.1 */
187 return v1 * 10000;
188 }
189 }
190
191
192 static void
193 stop_postmaster_atexit(void)
194 {
195 stop_postmaster(true);
196 }
197
198
199 bool
200 start_postmaster(ClusterInfo *cluster, bool report_and_exit_on_error)
201 {
202 char cmd[MAXPGPATH * 4 + 1000];
203 PGconn *conn;
204 bool pg_ctl_return = false;
205 char socket_string[MAXPGPATH + 200];
206 PQExpBufferData pgoptions;
207
208 static bool exit_hook_registered = false;
209
210 if (!exit_hook_registered)
211 {
212 atexit(stop_postmaster_atexit);
213 exit_hook_registered = true;
214 }
215
216 socket_string[0] = '\0';
217
218 #if !defined(WIN32)
219 /* prevent TCP/IP connections, restrict socket access */
220 strcat(socket_string,
221 " -c listen_addresses='' -c unix_socket_permissions=0700");
222
223 /* Have a sockdir? Tell the postmaster. */
224 if (cluster->sockdir)
225 snprintf(socket_string + strlen(socket_string),
226 sizeof(socket_string) - strlen(socket_string),
227 " -c %s='%s'",
228 (GET_MAJOR_VERSION(cluster->major_version) <= 902) ?
229 "unix_socket_directory" : "unix_socket_directories",
230 cluster->sockdir);
231 #endif
232
233 initPQExpBuffer(&pgoptions);
234
235 /*
236 * Construct a parameter string which is passed to the server process.
237 *
238 * Turn off durability requirements to improve object creation speed, and
239 * we only modify the new cluster, so only use it there. If there is a
240 * crash, the new cluster has to be recreated anyway. fsync=off is a big
241 * win on ext4.
242 */
243 if (cluster == &new_cluster)
244 appendPQExpBufferStr(&pgoptions, " -c synchronous_commit=off -c fsync=off -c full_page_writes=off");
245
246 /*
247 * Use -b to disable autovacuum and logical replication launcher
248 * (effective in PG17 or later for the latter).
249 */
250 snprintf(cmd, sizeof(cmd),
251 "\"%s/pg_ctl\" -w -l \"%s/%s\" -D \"%s\" -o \"-p %d -b%s %s%s\" start",
252 cluster->bindir,
253 log_opts.logdir,
254 SERVER_LOG_FILE, cluster->pgconfig, cluster->port,
255 pgoptions.data,
256 cluster->pgopts ? cluster->pgopts : "", socket_string);
257
258 termPQExpBuffer(&pgoptions);
259
260 /*
261 * Don't throw an error right away, let connecting throw the error because
262 * it might supply a reason for the failure.
263 */
264 pg_ctl_return = exec_prog(SERVER_START_LOG_FILE,
265 /* pass both file names if they differ */
266 (strcmp(SERVER_LOG_FILE,
267 SERVER_START_LOG_FILE) != 0) ?
268 SERVER_LOG_FILE : NULL,
269 report_and_exit_on_error, false,
270 "%s", cmd);
271
272 /* Did it fail and we are just testing if the server could be started? */
273 if (!pg_ctl_return && !report_and_exit_on_error)
274 return false;
275
276 /*
277 * We set this here to make sure atexit() shuts down the server, but only
278 * if we started the server successfully. We do it before checking for
279 * connectivity in case the server started but there is a connectivity
280 * failure. If pg_ctl did not return success, we will exit below.
281 *
282 * Pre-9.1 servers do not have PQping(), so we could be leaving the server
283 * running if authentication was misconfigured, so someday we might went
284 * to be more aggressive about doing server shutdowns even if pg_ctl
285 * fails, but now (2013-08-14) it seems prudent to be cautious. We don't
286 * want to shutdown a server that might have been accidentally started
287 * during the upgrade.
288 */
289 if (pg_ctl_return)
290 os_info.running_cluster = cluster;
291
292 /*
293 * pg_ctl -w might have failed because the server couldn't be started, or
294 * there might have been a connection problem in _checking_ if the server
295 * has started. Therefore, even if pg_ctl failed, we continue and test
296 * for connectivity in case we get a connection reason for the failure.
297 */
298 if ((conn = get_db_conn(cluster, "template1")) == NULL ||
299 PQstatus(conn) != CONNECTION_OK)
300 {
301 pg_log(PG_REPORT, "\n%s", PQerrorMessage(conn));
302 if (conn)
303 PQfinish(conn);
304 if (cluster == &old_cluster)
305 pg_fatal("could not connect to source postmaster started with the command:\n"
306 "%s",
307 cmd);
308 else
309 pg_fatal("could not connect to target postmaster started with the command:\n"
310 "%s",
311 cmd);
312 }
313 PQfinish(conn);
314
315 /*
316 * If pg_ctl failed, and the connection didn't fail, and
317 * report_and_exit_on_error is enabled, fail now. This could happen if
318 * the server was already running.
319 */
320 if (!pg_ctl_return)
321 {
322 if (cluster == &old_cluster)
323 pg_fatal("pg_ctl failed to start the source server, or connection failed");
324 else
325 pg_fatal("pg_ctl failed to start the target server, or connection failed");
326 }
327
328 return true;
329 }
330
331
332 void
333 stop_postmaster(bool in_atexit)
334 {
335 ClusterInfo *cluster;
336
337 if (os_info.running_cluster == &old_cluster)
338 cluster = &old_cluster;
339 else if (os_info.running_cluster == &new_cluster)
340 cluster = &new_cluster;
341 else
342 return; /* no cluster running */
343
344 exec_prog(SERVER_STOP_LOG_FILE, NULL, !in_atexit, !in_atexit,
345 "\"%s/pg_ctl\" -w -D \"%s\" -o \"%s\" %s stop",
346 cluster->bindir, cluster->pgconfig,
347 cluster->pgopts ? cluster->pgopts : "",
348 in_atexit ? "-m fast" : "-m smart");
349
350 os_info.running_cluster = NULL;
351 }
352
353
354 /*
355 * check_pghost_envvar()
356 *
357 * Tests that PGHOST does not point to a non-local server
358 */
359 void
360 check_pghost_envvar(void)
361 {
362 PQconninfoOption *option;
363 PQconninfoOption *start;
364
365 /* Get valid libpq env vars from the PQconndefaults function */
366
367 start = PQconndefaults();
368
369 if (!start)
370 pg_fatal("out of memory");
371
372 for (option = start; option->keyword != NULL; option++)
373 {
374 if (option->envvar && (strcmp(option->envvar, "PGHOST") == 0 ||
375 strcmp(option->envvar, "PGHOSTADDR") == 0))
376 {
377 const char *value = getenv(option->envvar);
378
379 if (value && strlen(value) > 0 &&
380 /* check for 'local' host values */
381 (strcmp(value, "localhost") != 0 && strcmp(value, "127.0.0.1") != 0 &&
382 strcmp(value, "::1") != 0 && !is_unixsock_path(value)))
383 pg_fatal("libpq environment variable %s has a non-local server value: %s",
384 option->envvar, value);
385 }
386 }
387
388 /* Free the memory that libpq allocated on our behalf */
389 PQconninfoFree(start);
390 }