Age Owner Branch data TLA Line data Source code
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 *
5362 bruce@momjian.us 28 :CBC 267 : connectToServer(ClusterInfo *cluster, const char *db_name)
29 : : {
5247 30 : 267 : PGconn *conn = get_db_conn(cluster, db_name);
31 : :
5596 32 [ + - - + ]: 267 : if (conn == NULL || PQstatus(conn) != CONNECTION_OK)
33 : : {
1688 tgl@sss.pgh.pa.us 34 :UBC 0 : pg_log(PG_REPORT, "%s", PQerrorMessage(conn));
35 : :
5596 bruce@momjian.us 36 [ # # ]: 0 : if (conn)
37 : 0 : PQfinish(conn);
38 : :
3249 peter_e@gmx.net 39 : 0 : printf(_("Failure, exiting\n"));
5267 40 : 0 : exit(1);
41 : : }
42 : :
2749 noah@leadboat.com 43 :CBC 267 : PQclear(executeQueryOrDie(conn, ALWAYS_SECURE_SEARCH_PATH_SQL));
44 : :
5596 bruce@momjian.us 45 : 267 : 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 *
5247 57 : 314 : 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 */
3316 noah@leadboat.com 63 : 314 : initPQExpBuffer(&conn_opts);
64 : 314 : appendPQExpBufferStr(&conn_opts, "dbname=");
65 : 314 : appendConnStrVal(&conn_opts, db_name);
66 : 314 : appendPQExpBufferStr(&conn_opts, " user=");
67 : 314 : appendConnStrVal(&conn_opts, os_info.user);
68 : 314 : appendPQExpBuffer(&conn_opts, " port=%d", cluster->port);
4751 tgl@sss.pgh.pa.us 69 [ + - ]: 314 : if (cluster->sockdir)
70 : : {
3316 noah@leadboat.com 71 : 314 : appendPQExpBufferStr(&conn_opts, " host=");
72 : 314 : appendConnStrVal(&conn_opts, cluster->sockdir);
73 : : }
74 : :
75 : 314 : conn = PQconnectdb(conn_opts.data);
76 : 314 : termPQExpBuffer(&conn_opts);
77 : 314 : return conn;
78 : : }
79 : :
80 : :
81 : : /*
82 : : * cluster_conn_opts()
83 : : *
84 : : * Return standard command-line options for connecting to this cluster when
85 : : * using psql, pg_dump, etc. Ideally this would match what get_db_conn()
86 : : * sets, but the utilities we need aren't very consistent about the treatment
87 : : * of database name options, so we leave that out.
88 : : *
89 : : * Result is valid until the next call to this function.
90 : : */
91 : : char *
4751 tgl@sss.pgh.pa.us 92 : 96 : cluster_conn_opts(ClusterInfo *cluster)
93 : : {
94 : : static PQExpBuffer buf;
95 : :
3316 noah@leadboat.com 96 [ + + ]: 96 : if (buf == NULL)
97 : 10 : buf = createPQExpBuffer();
98 : : else
99 : 86 : resetPQExpBuffer(buf);
100 : :
101 [ + - ]: 96 : if (cluster->sockdir)
102 : : {
103 : 96 : appendPQExpBufferStr(buf, "--host ");
104 : 96 : appendShellString(buf, cluster->sockdir);
105 : 96 : appendPQExpBufferChar(buf, ' ');
106 : : }
107 : 96 : appendPQExpBuffer(buf, "--port %d --username ", cluster->port);
108 : 96 : appendShellString(buf, os_info.user);
109 : :
110 : 96 : return buf->data;
111 : : }
112 : :
113 : :
114 : : /*
115 : : * executeQueryOrDie()
116 : : *
117 : : * Formats a query string from the given arguments and executes the
118 : : * resulting query. If the query fails, this function logs an error
119 : : * message and calls exit() to kill the program.
120 : : */
121 : : PGresult *
5436 bruce@momjian.us 122 : 608 : executeQueryOrDie(PGconn *conn, const char *fmt,...)
123 : : {
124 : : static char query[QUERY_ALLOC];
125 : : va_list args;
126 : : PGresult *result;
127 : : ExecStatusType status;
128 : :
5596 129 : 608 : va_start(args, fmt);
4035 130 : 608 : vsnprintf(query, sizeof(query), fmt, args);
5596 131 : 608 : va_end(args);
132 : :
1152 tgl@sss.pgh.pa.us 133 : 608 : pg_log(PG_VERBOSE, "executing: %s", query);
4035 bruce@momjian.us 134 : 608 : result = PQexec(conn, query);
5596 135 : 608 : status = PQresultStatus(result);
136 : :
137 [ + + - + ]: 608 : if ((status != PGRES_TUPLES_OK) && (status != PGRES_COMMAND_OK))
138 : : {
2937 peter_e@gmx.net 139 :UBC 0 : pg_log(PG_REPORT, "SQL command failed\n%s\n%s", query,
140 : : PQerrorMessage(conn));
5596 bruce@momjian.us 141 : 0 : PQclear(result);
142 : 0 : PQfinish(conn);
3249 peter_e@gmx.net 143 : 0 : printf(_("Failure, exiting\n"));
5267 144 : 0 : exit(1);
145 : : }
146 : : else
5596 bruce@momjian.us 147 :CBC 608 : return result;
148 : : }
149 : :
150 : :
151 : : /*
152 : : * get_major_server_version()
153 : : *
154 : : * gets the version (in unsigned int form) for the given datadir. Assumes
155 : : * that datadir is an absolute path to a valid pgdata directory. The version
156 : : * is retrieved by reading the PG_VERSION file.
157 : : */
158 : : uint32
5362 159 : 34 : get_major_server_version(ClusterInfo *cluster)
160 : : {
161 : : FILE *version_fd;
162 : : char ver_filename[MAXPGPATH];
2861 tgl@sss.pgh.pa.us 163 : 34 : int v1 = 0,
164 : 34 : v2 = 0;
165 : :
5089 bruce@momjian.us 166 : 34 : snprintf(ver_filename, sizeof(ver_filename), "%s/PG_VERSION",
167 : : cluster->pgdata);
5362 168 [ - + ]: 34 : if ((version_fd = fopen(ver_filename, "r")) == NULL)
1152 tgl@sss.pgh.pa.us 169 :UBC 0 : pg_fatal("could not open version file \"%s\": %m", ver_filename);
170 : :
5362 bruce@momjian.us 171 [ + - ]:CBC 34 : if (fscanf(version_fd, "%63s", cluster->major_version_str) == 0 ||
2861 tgl@sss.pgh.pa.us 172 [ - + ]: 34 : sscanf(cluster->major_version_str, "%d.%d", &v1, &v2) < 1)
1152 tgl@sss.pgh.pa.us 173 :UBC 0 : pg_fatal("could not parse version file \"%s\"", ver_filename);
174 : :
5296 bruce@momjian.us 175 :CBC 34 : fclose(version_fd);
176 : :
2861 tgl@sss.pgh.pa.us 177 [ - + ]: 34 : if (v1 < 10)
178 : : {
179 : : /* old style, e.g. 9.6.1 */
2861 tgl@sss.pgh.pa.us 180 :UBC 0 : return v1 * 10000 + v2 * 100;
181 : : }
182 : : else
183 : : {
184 : : /* new style, e.g. 10.1 */
2861 tgl@sss.pgh.pa.us 185 :CBC 34 : return v1 * 10000;
186 : : }
187 : : }
188 : :
189 : :
190 : : static void
5267 peter_e@gmx.net 191 : 16 : stop_postmaster_atexit(void)
192 : : {
5248 bruce@momjian.us 193 : 16 : stop_postmaster(true);
5267 peter_e@gmx.net 194 : 16 : }
195 : :
196 : :
197 : : bool
2798 bruce@momjian.us 198 : 47 : start_postmaster(ClusterInfo *cluster, bool report_and_exit_on_error)
199 : : {
200 : : char cmd[MAXPGPATH * 4 + 1000];
201 : : PGconn *conn;
4758 alvherre@alvh.no-ip. 202 : 47 : bool pg_ctl_return = false;
203 : : char socket_string[MAXPGPATH + 200];
204 : : PQExpBufferData pgoptions;
205 : :
206 : : static bool exit_hook_registered = false;
207 : :
5267 peter_e@gmx.net 208 [ + + ]: 47 : if (!exit_hook_registered)
209 : : {
210 : 16 : atexit(stop_postmaster_atexit);
211 : 16 : exit_hook_registered = true;
212 : : }
213 : :
2035 michael@paquier.xyz 214 : 47 : socket_string[0] = '\0';
215 : :
216 : : #if !defined(WIN32)
217 : : /* prevent TCP/IP connections, restrict socket access */
218 : 47 : strcat(socket_string,
219 : : " -c listen_addresses='' -c unix_socket_permissions=0700");
220 : :
221 : : /* Have a sockdir? Tell the postmaster. */
222 [ + - ]: 47 : if (cluster->sockdir)
223 : 47 : snprintf(socket_string + strlen(socket_string),
224 : 47 : sizeof(socket_string) - strlen(socket_string),
225 : : " -c %s='%s'",
1796 bruce@momjian.us 226 [ - + ]: 47 : (GET_MAJOR_VERSION(cluster->major_version) <= 902) ?
227 : : "unix_socket_directory" : "unix_socket_directories",
228 : : cluster->sockdir);
229 : : #endif
230 : :
681 akapila@postgresql.o 231 : 47 : initPQExpBuffer(&pgoptions);
232 : :
233 : : /*
234 : : * Construct a parameter string which is passed to the server process.
235 : : *
236 : : * Turn off durability requirements to improve object creation speed, and
237 : : * we only modify the new cluster, so only use it there. If there is a
238 : : * crash, the new cluster has to be recreated anyway. fsync=off is a big
239 : : * win on ext4.
240 : : */
241 [ + + ]: 47 : if (cluster == &new_cluster)
242 : 31 : appendPQExpBufferStr(&pgoptions, " -c synchronous_commit=off -c fsync=off -c full_page_writes=off");
243 : :
244 : : /*
245 : : * Use -b to disable autovacuum and logical replication launcher
246 : : * (effective in PG17 or later for the latter).
247 : : */
2035 michael@paquier.xyz 248 : 47 : snprintf(cmd, sizeof(cmd),
249 : : "\"%s/pg_ctl\" -w -l \"%s/%s\" -D \"%s\" -o \"-p %d -b%s %s%s\" start",
250 : : cluster->bindir,
251 : : log_opts.logdir,
1308 252 : 47 : SERVER_LOG_FILE, cluster->pgconfig, cluster->port,
253 : : pgoptions.data,
2035 254 [ - + ]: 47 : cluster->pgopts ? cluster->pgopts : "", socket_string);
255 : :
681 akapila@postgresql.o 256 : 47 : termPQExpBuffer(&pgoptions);
257 : :
258 : : /*
259 : : * Don't throw an error right away, let connecting throw the error because
260 : : * it might supply a reason for the failure.
261 : : */
4758 alvherre@alvh.no-ip. 262 : 47 : pg_ctl_return = exec_prog(SERVER_START_LOG_FILE,
263 : : /* pass both file names if they differ */
264 : : (strcmp(SERVER_LOG_FILE,
265 : : SERVER_START_LOG_FILE) != 0) ?
266 : : SERVER_LOG_FILE : NULL,
267 : : report_and_exit_on_error, false,
268 : : "%s", cmd);
269 : :
270 : : /* Did it fail and we are just testing if the server could be started? */
2798 bruce@momjian.us 271 [ - + - - ]: 47 : if (!pg_ctl_return && !report_and_exit_on_error)
4608 bruce@momjian.us 272 :UBC 0 : return false;
273 : :
274 : : /*
275 : : * We set this here to make sure atexit() shuts down the server, but only
276 : : * if we started the server successfully. We do it before checking for
277 : : * connectivity in case the server started but there is a connectivity
278 : : * failure. If pg_ctl did not return success, we will exit below.
279 : : *
280 : : * Pre-9.1 servers do not have PQping(), so we could be leaving the server
281 : : * running if authentication was misconfigured, so someday we might went
282 : : * to be more aggressive about doing server shutdowns even if pg_ctl
283 : : * fails, but now (2013-08-14) it seems prudent to be cautious. We don't
284 : : * want to shutdown a server that might have been accidentally started
285 : : * during the upgrade.
286 : : */
4404 bruce@momjian.us 287 [ + - ]:CBC 47 : if (pg_ctl_return)
288 : 47 : os_info.running_cluster = cluster;
289 : :
290 : : /*
291 : : * pg_ctl -w might have failed because the server couldn't be started, or
292 : : * there might have been a connection problem in _checking_ if the server
293 : : * has started. Therefore, even if pg_ctl failed, we continue and test
294 : : * for connectivity in case we get a connection reason for the failure.
295 : : */
5247 296 [ + - - + ]: 94 : if ((conn = get_db_conn(cluster, "template1")) == NULL ||
297 : 47 : PQstatus(conn) != CONNECTION_OK)
298 : : {
1688 tgl@sss.pgh.pa.us 299 :UBC 0 : pg_log(PG_REPORT, "\n%s", PQerrorMessage(conn));
5203 bruce@momjian.us 300 [ # # ]: 0 : if (conn)
5247 301 : 0 : PQfinish(conn);
2976 alvherre@alvh.no-ip. 302 [ # # ]: 0 : if (cluster == &old_cluster)
303 : 0 : pg_fatal("could not connect to source postmaster started with the command:\n"
304 : : "%s",
305 : : cmd);
306 : : else
307 : 0 : pg_fatal("could not connect to target postmaster started with the command:\n"
308 : : "%s",
309 : : cmd);
310 : : }
5247 bruce@momjian.us 311 :CBC 47 : PQfinish(conn);
312 : :
313 : : /*
314 : : * If pg_ctl failed, and the connection didn't fail, and
315 : : * report_and_exit_on_error is enabled, fail now. This could happen if
316 : : * the server was already running.
317 : : */
4758 alvherre@alvh.no-ip. 318 [ - + ]: 47 : if (!pg_ctl_return)
319 : : {
2801 bruce@momjian.us 320 [ # # ]:UBC 0 : if (cluster == &old_cluster)
1152 tgl@sss.pgh.pa.us 321 : 0 : pg_fatal("pg_ctl failed to start the source server, or connection failed");
322 : : else
323 : 0 : pg_fatal("pg_ctl failed to start the target server, or connection failed");
324 : : }
325 : :
4608 bruce@momjian.us 326 :CBC 47 : return true;
327 : : }
328 : :
329 : :
330 : : void
2798 331 : 56 : stop_postmaster(bool in_atexit)
332 : : {
333 : : ClusterInfo *cluster;
334 : :
5362 335 [ + + ]: 56 : if (os_info.running_cluster == &old_cluster)
5080 336 : 16 : cluster = &old_cluster;
5362 337 [ + + ]: 40 : else if (os_info.running_cluster == &new_cluster)
5080 338 : 31 : cluster = &new_cluster;
339 : : else
4836 340 : 9 : return; /* no cluster running */
341 : :
2798 342 [ + + ]: 94 : exec_prog(SERVER_STOP_LOG_FILE, NULL, !in_atexit, !in_atexit,
343 : : "\"%s/pg_ctl\" -w -D \"%s\" -o \"%s\" %s stop",
344 : : cluster->bindir, cluster->pgconfig,
4758 alvherre@alvh.no-ip. 345 [ - + ]: 47 : cluster->pgopts ? cluster->pgopts : "",
2798 bruce@momjian.us 346 : 47 : in_atexit ? "-m fast" : "-m smart");
347 : :
5362 348 : 47 : os_info.running_cluster = NULL;
349 : : }
350 : :
351 : :
352 : : /*
353 : : * check_pghost_envvar()
354 : : *
355 : : * Tests that PGHOST does not point to a non-local server
356 : : */
357 : : void
5227 358 : 18 : check_pghost_envvar(void)
359 : : {
360 : : PQconninfoOption *option;
361 : : PQconninfoOption *start;
362 : :
363 : : /* Get valid libpq env vars from the PQconndefaults function */
364 : :
5266 peter_e@gmx.net 365 : 18 : start = PQconndefaults();
366 : :
4295 bruce@momjian.us 367 [ - + ]: 18 : if (!start)
1152 tgl@sss.pgh.pa.us 368 :UBC 0 : pg_fatal("out of memory");
369 : :
5266 peter_e@gmx.net 370 [ + + ]:CBC 936 : for (option = start; option->keyword != NULL; option++)
371 : : {
5227 bruce@momjian.us 372 [ + + + + ]: 918 : if (option->envvar && (strcmp(option->envvar, "PGHOST") == 0 ||
5203 373 [ + + ]: 630 : strcmp(option->envvar, "PGHOSTADDR") == 0))
374 : : {
5227 375 : 36 : const char *value = getenv(option->envvar);
376 : :
377 [ + + + - ]: 36 : if (value && strlen(value) > 0 &&
378 : : /* check for 'local' host values */
379 [ + - + - ]: 18 : (strcmp(value, "localhost") != 0 && strcmp(value, "127.0.0.1") != 0 &&
1284 michael@paquier.xyz 380 [ + - - + ]: 18 : strcmp(value, "::1") != 0 && !is_unixsock_path(value)))
1152 tgl@sss.pgh.pa.us 381 :UBC 0 : pg_fatal("libpq environment variable %s has a non-local server value: %s",
382 : : option->envvar, value);
383 : : }
384 : : }
385 : :
386 : : /* Free the memory that libpq allocated on our behalf */
5596 bruce@momjian.us 387 :CBC 18 : PQconninfoFree(start);
388 : 18 : }
|