PostgreSQL Source Code  git master
server.c File Reference
#include "postgres_fe.h"
#include "fe_utils/string_utils.h"
#include "pg_upgrade.h"
Include dependency graph for server.c:

Go to the source code of this file.

Functions

static PGconnget_db_conn (ClusterInfo *cluster, const char *db_name)
 
PGconnconnectToServer (ClusterInfo *cluster, const char *db_name)
 
char * cluster_conn_opts (ClusterInfo *cluster)
 
PGresultexecuteQueryOrDie (PGconn *conn, const char *fmt,...)
 
uint32 get_major_server_version (ClusterInfo *cluster)
 
static void stop_postmaster_atexit (void)
 
bool start_postmaster (ClusterInfo *cluster, bool throw_error)
 
void stop_postmaster (bool fast)
 
void check_pghost_envvar (void)
 

Function Documentation

◆ check_pghost_envvar()

void check_pghost_envvar ( void  )

Definition at line 352 of file server.c.

References _PQconninfoOption::envvar, _PQconninfoOption::keyword, pg_fatal(), PQconndefaults(), PQconninfoFree(), and value.

Referenced by setup().

353 {
355  PQconninfoOption *start;
356 
357  /* Get valid libpq env vars from the PQconndefaults function */
358 
359  start = PQconndefaults();
360 
361  if (!start)
362  pg_fatal("out of memory\n");
363 
364  for (option = start; option->keyword != NULL; option++)
365  {
366  if (option->envvar && (strcmp(option->envvar, "PGHOST") == 0 ||
367  strcmp(option->envvar, "PGHOSTADDR") == 0))
368  {
369  const char *value = getenv(option->envvar);
370 
371  if (value && strlen(value) > 0 &&
372  /* check for 'local' host values */
373  (strcmp(value, "localhost") != 0 && strcmp(value, "127.0.0.1") != 0 &&
374  strcmp(value, "::1") != 0 && value[0] != '/'))
375  pg_fatal("libpq environment variable %s has a non-local server value: %s\n",
376  option->envvar, value);
377  }
378  }
379 
380  /* Free the memory that libpq allocated on our behalf */
381  PQconninfoFree(start);
382 }
void pg_fatal(const char *fmt,...)
Definition: logging.c:83
static struct @121 value
void PQconninfoFree(PQconninfoOption *connOptions)
Definition: fe-connect.c:5956
PQconninfoOption * PQconndefaults(void)
Definition: fe-connect.c:1223

◆ cluster_conn_opts()

char* cluster_conn_opts ( ClusterInfo cluster)

Definition at line 88 of file server.c.

References appendPQExpBuffer(), appendPQExpBufferChar(), appendPQExpBufferStr(), appendShellString(), buf, createPQExpBuffer(), PQExpBufferData::data, os_info, ClusterInfo::port, resetPQExpBuffer(), ClusterInfo::sockdir, and OSInfo::user.

Referenced by create_new_objects(), generate_old_dump(), prepare_new_cluster(), and prepare_new_databases().

89 {
90  static PQExpBuffer buf;
91 
92  if (buf == NULL)
93  buf = createPQExpBuffer();
94  else
95  resetPQExpBuffer(buf);
96 
97  if (cluster->sockdir)
98  {
99  appendPQExpBufferStr(buf, "--host ");
100  appendShellString(buf, cluster->sockdir);
101  appendPQExpBufferChar(buf, ' ');
102  }
103  appendPQExpBuffer(buf, "--port %d --username ", cluster->port);
105 
106  return buf->data;
107 }
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:385
unsigned short port
Definition: pg_upgrade.h:273
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:262
static char * buf
Definition: pg_test_fsync.c:67
PQExpBuffer createPQExpBuffer(void)
Definition: pqexpbuffer.c:71
void appendPQExpBufferChar(PQExpBuffer str, char ch)
Definition: pqexpbuffer.c:396
void appendShellString(PQExpBuffer buf, const char *str)
Definition: string_utils.c:434
char * sockdir
Definition: pg_upgrade.h:272
OSInfo os_info
Definition: pg_upgrade.c:58
void resetPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:145
char * user
Definition: pg_upgrade.h:311

◆ connectToServer()

PGconn* connectToServer ( ClusterInfo cluster,
const char *  db_name 
)

Definition at line 27 of file server.c.

References _, conn, CONNECTION_OK, get_db_conn(), pg_log(), PG_REPORT, PQerrorMessage(), PQfinish(), and PQstatus().

Referenced by check_for_isn_and_int8_passing_mismatch(), check_for_jsonb_9_4_usage(), check_for_pg_role_prefix(), check_for_prepared_transactions(), check_for_reg_data_type_usage(), check_is_install_user(), check_loadable_libraries(), check_proper_datallowconn(), get_db_infos(), get_loadable_libraries(), get_rel_infos(), get_tablespace_paths(), new_9_0_populate_pg_largeobject_metadata(), old_9_3_check_for_line_data_type_usage(), old_9_6_check_for_unknown_data_type_usage(), old_9_6_invalidate_hash_indexes(), and set_frozenxids().

28 {
29  PGconn *conn = get_db_conn(cluster, db_name);
30 
31  if (conn == NULL || PQstatus(conn) != CONNECTION_OK)
32  {
33  pg_log(PG_REPORT, "connection to database failed: %s",
34  PQerrorMessage(conn));
35 
36  if (conn)
37  PQfinish(conn);
38 
39  printf(_("Failure, exiting\n"));
40  exit(1);
41  }
42 
43  return conn;
44 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6106
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3629
PGconn * conn
Definition: streamutil.c:46
void pg_log(eLogType type, const char *fmt,...)
Definition: logging.c:69
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6053
static PGconn * get_db_conn(ClusterInfo *cluster, const char *db_name)
Definition: server.c:53
#define _(x)
Definition: elog.c:84

◆ executeQueryOrDie()

PGresult* executeQueryOrDie ( PGconn conn,
const char *  fmt,
  ... 
)

Definition at line 118 of file server.c.

References _, generate_unaccent_rules::args, pg_log(), PG_REPORT, PG_VERBOSE, PGRES_COMMAND_OK, PGRES_TUPLES_OK, PQclear(), PQerrorMessage(), PQexec(), PQfinish(), PQresultStatus(), QUERY_ALLOC, status(), and vsnprintf().

119 {
120  static char query[QUERY_ALLOC];
121  va_list args;
122  PGresult *result;
124 
125  va_start(args, fmt);
126  vsnprintf(query, sizeof(query), fmt, args);
127  va_end(args);
128 
129  pg_log(PG_VERBOSE, "executing: %s\n", query);
130  result = PQexec(conn, query);
131  status = PQresultStatus(result);
132 
133  if ((status != PGRES_TUPLES_OK) && (status != PGRES_COMMAND_OK))
134  {
135  pg_log(PG_REPORT, "SQL command failed\n%s\n%s", query,
136  PQerrorMessage(conn));
137  PQclear(result);
138  PQfinish(conn);
139  printf(_("Failure, exiting\n"));
140  exit(1);
141  }
142  else
143  return result;
144 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6106
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3629
ExecStatusType
Definition: libpq-fe.h:82
#define QUERY_ALLOC
Definition: logging.c:26
ExecStatusType PQresultStatus(const PGresult *res)
Definition: fe-exec.c:2647
int int vsnprintf(char *str, size_t count, const char *fmt, va_list args)
void pg_log(eLogType type, const char *fmt,...)
Definition: logging.c:69
void PQclear(PGresult *res)
Definition: fe-exec.c:671
PGresult * PQexec(PGconn *conn, const char *query)
Definition: fe-exec.c:1897
static void static void status(const char *fmt,...) pg_attribute_printf(1
Definition: pg_regress.c:225
#define _(x)
Definition: elog.c:84

◆ get_db_conn()

static PGconn * get_db_conn ( ClusterInfo cluster,
const char *  db_name 
)
static

Definition at line 53 of file server.c.

References appendConnStrVal(), appendPQExpBuffer(), appendPQExpBufferStr(), conn, PQExpBufferData::data, initPQExpBuffer(), os_info, ClusterInfo::port, PQconnectdb(), ClusterInfo::sockdir, termPQExpBuffer(), and OSInfo::user.

Referenced by connectToServer(), and start_postmaster().

54 {
55  PQExpBufferData conn_opts;
56  PGconn *conn;
57 
58  /* Build connection string with proper quoting */
59  initPQExpBuffer(&conn_opts);
60  appendPQExpBufferStr(&conn_opts, "dbname=");
61  appendConnStrVal(&conn_opts, db_name);
62  appendPQExpBufferStr(&conn_opts, " user=");
63  appendConnStrVal(&conn_opts, os_info.user);
64  appendPQExpBuffer(&conn_opts, " port=%d", cluster->port);
65  if (cluster->sockdir)
66  {
67  appendPQExpBufferStr(&conn_opts, " host=");
68  appendConnStrVal(&conn_opts, cluster->sockdir);
69  }
70 
71  conn = PQconnectdb(conn_opts.data);
72  termPQExpBuffer(&conn_opts);
73  return conn;
74 }
void termPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:128
void appendPQExpBufferStr(PQExpBuffer str, const char *data)
Definition: pqexpbuffer.c:385
void appendConnStrVal(PQExpBuffer buf, const char *str)
Definition: string_utils.c:551
unsigned short port
Definition: pg_upgrade.h:273
PGconn * conn
Definition: streamutil.c:46
void appendPQExpBuffer(PQExpBuffer str, const char *fmt,...)
Definition: pqexpbuffer.c:262
char * sockdir
Definition: pg_upgrade.h:272
OSInfo os_info
Definition: pg_upgrade.c:58
char * user
Definition: pg_upgrade.h:311
void initPQExpBuffer(PQExpBuffer str)
Definition: pqexpbuffer.c:89
PGconn * PQconnectdb(const char *conninfo)
Definition: fe-connect.c:585

◆ get_major_server_version()

uint32 get_major_server_version ( ClusterInfo cluster)

Definition at line 155 of file server.c.

References ClusterInfo::major_version_str, MAXPGPATH, pg_fatal(), ClusterInfo::pgdata, and snprintf().

Referenced by check_data_dir().

156 {
157  FILE *version_fd;
158  char ver_filename[MAXPGPATH];
159  int v1 = 0,
160  v2 = 0;
161 
162  snprintf(ver_filename, sizeof(ver_filename), "%s/PG_VERSION",
163  cluster->pgdata);
164  if ((version_fd = fopen(ver_filename, "r")) == NULL)
165  pg_fatal("could not open version file: %s\n", ver_filename);
166 
167  if (fscanf(version_fd, "%63s", cluster->major_version_str) == 0 ||
168  sscanf(cluster->major_version_str, "%d.%d", &v1, &v2) < 1)
169  pg_fatal("could not parse PG_VERSION file from %s\n", cluster->pgdata);
170 
171  fclose(version_fd);
172 
173  if (v1 < 10)
174  {
175  /* old style, e.g. 9.6.1 */
176  return v1 * 10000 + v2 * 100;
177  }
178  else
179  {
180  /* new style, e.g. 10.1 */
181  return v1 * 10000;
182  }
183 }
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
void pg_fatal(const char *fmt,...)
Definition: logging.c:83
char major_version_str[64]
Definition: pg_upgrade.h:275
#define MAXPGPATH
char * pgdata
Definition: pg_upgrade.h:266

◆ start_postmaster()

bool start_postmaster ( ClusterInfo cluster,
bool  throw_error 
)

Definition at line 194 of file server.c.

References BINARY_UPGRADE_SERVER_FLAG_CAT_VER, ClusterInfo::bindir, ControlData::cat_ver, cluster(), conn, CONNECTION_OK, ClusterInfo::controldata, exec_prog(), get_db_conn(), GET_MAJOR_VERSION, ClusterInfo::major_version, MAXPGPATH, new_cluster, old_cluster, os_info, pg_fatal(), pg_log(), PG_REPORT, ClusterInfo::pgconfig, ClusterInfo::pgopts, ClusterInfo::port, PQerrorMessage(), PQfinish(), PQstatus(), OSInfo::running_cluster, SERVER_LOG_FILE, SERVER_START_LOG_FILE, snprintf(), ClusterInfo::sockdir, and stop_postmaster_atexit().

195 {
196  char cmd[MAXPGPATH * 4 + 1000];
197  PGconn *conn;
198  bool pg_ctl_return = false;
199  char socket_string[MAXPGPATH + 200];
200 
201  static bool exit_hook_registered = false;
202 
203  if (!exit_hook_registered)
204  {
205  atexit(stop_postmaster_atexit);
206  exit_hook_registered = true;
207  }
208 
209  socket_string[0] = '\0';
210 
211 #ifdef HAVE_UNIX_SOCKETS
212  /* prevent TCP/IP connections, restrict socket access */
213  strcat(socket_string,
214  " -c listen_addresses='' -c unix_socket_permissions=0700");
215 
216  /* Have a sockdir? Tell the postmaster. */
217  if (cluster->sockdir)
218  snprintf(socket_string + strlen(socket_string),
219  sizeof(socket_string) - strlen(socket_string),
220  " -c %s='%s'",
221  (GET_MAJOR_VERSION(cluster->major_version) < 903) ?
222  "unix_socket_directory" : "unix_socket_directories",
223  cluster->sockdir);
224 #endif
225 
226  /*
227  * Since PG 9.1, we have used -b to disable autovacuum. For earlier
228  * releases, setting autovacuum=off disables cleanup vacuum and analyze,
229  * but freeze vacuums can still happen, so we set
230  * autovacuum_freeze_max_age to its maximum.
231  * (autovacuum_multixact_freeze_max_age was introduced after 9.1, so there
232  * is no need to set that.) We assume all datfrozenxid and relfrozenxid
233  * values are less than a gap of 2000000000 from the current xid counter,
234  * so autovacuum will not touch them.
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  snprintf(cmd, sizeof(cmd),
242  "\"%s/pg_ctl\" -w -l \"%s\" -D \"%s\" -o \"-p %d%s%s %s%s\" start",
243  cluster->bindir, SERVER_LOG_FILE, cluster->pgconfig, cluster->port,
244  (cluster->controldata.cat_ver >=
246  " -c autovacuum=off -c autovacuum_freeze_max_age=2000000000",
247  (cluster == &new_cluster) ?
248  " -c synchronous_commit=off -c fsync=off -c full_page_writes=off" : "",
249  cluster->pgopts ? cluster->pgopts : "", socket_string);
250 
251  /*
252  * Don't throw an error right away, let connecting throw the error because
253  * it might supply a reason for the failure.
254  */
255  pg_ctl_return = exec_prog(SERVER_START_LOG_FILE,
256  /* pass both file names if they differ */
257  (strcmp(SERVER_LOG_FILE,
258  SERVER_START_LOG_FILE) != 0) ?
259  SERVER_LOG_FILE : NULL,
260  false,
261  "%s", cmd);
262 
263  /* Did it fail and we are just testing if the server could be started? */
264  if (!pg_ctl_return && !throw_error)
265  return false;
266 
267  /*
268  * We set this here to make sure atexit() shuts down the server, but only
269  * if we started the server successfully. We do it before checking for
270  * connectivity in case the server started but there is a connectivity
271  * failure. If pg_ctl did not return success, we will exit below.
272  *
273  * Pre-9.1 servers do not have PQping(), so we could be leaving the server
274  * running if authentication was misconfigured, so someday we might went
275  * to be more aggressive about doing server shutdowns even if pg_ctl
276  * fails, but now (2013-08-14) it seems prudent to be cautious. We don't
277  * want to shutdown a server that might have been accidentally started
278  * during the upgrade.
279  */
280  if (pg_ctl_return)
282 
283  /*
284  * pg_ctl -w might have failed because the server couldn't be started, or
285  * there might have been a connection problem in _checking_ if the server
286  * has started. Therefore, even if pg_ctl failed, we continue and test
287  * for connectivity in case we get a connection reason for the failure.
288  */
289  if ((conn = get_db_conn(cluster, "template1")) == NULL ||
290  PQstatus(conn) != CONNECTION_OK)
291  {
292  pg_log(PG_REPORT, "\nconnection to database failed: %s",
293  PQerrorMessage(conn));
294  if (conn)
295  PQfinish(conn);
296  if (cluster == &old_cluster)
297  pg_fatal("could not connect to source postmaster started with the command:\n"
298  "%s\n",
299  cmd);
300  else
301  pg_fatal("could not connect to target postmaster started with the command:\n"
302  "%s\n",
303  cmd);
304  }
305  PQfinish(conn);
306 
307  /*
308  * If pg_ctl failed, and the connection didn't fail, and throw_error is
309  * enabled, fail now. This could happen if the server was already
310  * running.
311  */
312  if (!pg_ctl_return)
313  {
314  if (cluster == &old_cluster)
315  pg_fatal("pg_ctl failed to start the source server, or connection failed\n");
316  else
317  pg_fatal("pg_ctl failed to start the target server, or connection failed\n");
318  }
319 
320  return true;
321 }
char * PQerrorMessage(const PGconn *conn)
Definition: fe-connect.c:6106
uint32 major_version
Definition: pg_upgrade.h:274
ControlData controldata
Definition: pg_upgrade.h:264
#define GET_MAJOR_VERSION(v)
Definition: pg_upgrade.h:29
void PQfinish(PGconn *conn)
Definition: fe-connect.c:3629
unsigned short port
Definition: pg_upgrade.h:273
int snprintf(char *str, size_t count, const char *fmt,...) pg_attribute_printf(3
void pg_fatal(const char *fmt,...)
Definition: logging.c:83
char * pgopts
Definition: pg_upgrade.h:270
ClusterInfo new_cluster
Definition: pg_upgrade.c:56
char * pgconfig
Definition: pg_upgrade.h:267
PGconn * conn
Definition: streamutil.c:46
#define MAXPGPATH
ClusterInfo old_cluster
Definition: pg_upgrade.c:56
void cluster(ClusterStmt *stmt, bool isTopLevel)
Definition: cluster.c:106
void pg_log(eLogType type, const char *fmt,...)
Definition: logging.c:69
char * bindir
Definition: pg_upgrade.h:269
uint32 cat_ver
Definition: pg_upgrade.h:210
static void stop_postmaster_atexit(void)
Definition: server.c:187
#define SERVER_LOG_FILE
Definition: pg_upgrade.h:36
ClusterInfo * running_cluster
Definition: pg_upgrade.h:317
#define SERVER_START_LOG_FILE
Definition: pg_upgrade.h:59
bool exec_prog(const char *log_file, const char *opt_log_file, bool throw_error, const char *fmt,...)
Definition: exec.c:82
char * sockdir
Definition: pg_upgrade.h:272
OSInfo os_info
Definition: pg_upgrade.c:58
#define BINARY_UPGRADE_SERVER_FLAG_CAT_VER
Definition: pg_upgrade.h:102
ConnStatusType PQstatus(const PGconn *conn)
Definition: fe-connect.c:6053
static PGconn * get_db_conn(ClusterInfo *cluster, const char *db_name)
Definition: server.c:53

◆ stop_postmaster()

void stop_postmaster ( bool  fast)

Definition at line 325 of file server.c.

References ClusterInfo::bindir, cluster(), exec_prog(), new_cluster, old_cluster, os_info, ClusterInfo::pgconfig, ClusterInfo::pgopts, OSInfo::running_cluster, and SERVER_STOP_LOG_FILE.

Referenced by check_and_dump_old_cluster(), issue_warnings_and_set_wal_level(), main(), report_clusters_compatible(), setup(), and stop_postmaster_atexit().

326 {
328 
330  cluster = &old_cluster;
331  else if (os_info.running_cluster == &new_cluster)
332  cluster = &new_cluster;
333  else
334  return; /* no cluster running */
335 
336  exec_prog(SERVER_STOP_LOG_FILE, NULL, !fast,
337  "\"%s/pg_ctl\" -w -D \"%s\" -o \"%s\" %s stop",
338  cluster->bindir, cluster->pgconfig,
339  cluster->pgopts ? cluster->pgopts : "",
340  fast ? "-m fast" : "-m smart");
341 
342  os_info.running_cluster = NULL;
343 }
#define SERVER_STOP_LOG_FILE
Definition: pg_upgrade.h:60
char * pgopts
Definition: pg_upgrade.h:270
ClusterInfo new_cluster
Definition: pg_upgrade.c:56
char * pgconfig
Definition: pg_upgrade.h:267
ClusterInfo old_cluster
Definition: pg_upgrade.c:56
void cluster(ClusterStmt *stmt, bool isTopLevel)
Definition: cluster.c:106
char * bindir
Definition: pg_upgrade.h:269
ClusterInfo * running_cluster
Definition: pg_upgrade.h:317
bool exec_prog(const char *log_file, const char *opt_log_file, bool throw_error, const char *fmt,...)
Definition: exec.c:82
OSInfo os_info
Definition: pg_upgrade.c:58

◆ stop_postmaster_atexit()

static void stop_postmaster_atexit ( void  )
static

Definition at line 187 of file server.c.

References stop_postmaster().

Referenced by start_postmaster().

188 {
189  stop_postmaster(true);
190 }
void stop_postmaster(bool fast)
Definition: server.c:325