LCOV - code coverage report
Current view: top level - src/bin/pg_upgrade - server.c (source / functions) Hit Total Coverage
Test: PostgreSQL 17devel Lines: 107 127 84.3 %
Date: 2024-03-29 00:11:46 Functions: 9 9 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*
       2             :  *  server.c
       3             :  *
       4             :  *  database server functions
       5             :  *
       6             :  *  Copyright (c) 2010-2024, 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         590 : connectToServer(ClusterInfo *cluster, const char *db_name)
      29             : {
      30         590 :     PGconn     *conn = get_db_conn(cluster, db_name);
      31             : 
      32         590 :     if (conn == NULL || PQstatus(conn) != CONNECTION_OK)
      33             :     {
      34           2 :         pg_log(PG_REPORT, "%s", PQerrorMessage(conn));
      35             : 
      36           2 :         if (conn)
      37           2 :             PQfinish(conn);
      38             : 
      39           2 :         printf(_("Failure, exiting\n"));
      40           2 :         exit(1);
      41             :     }
      42             : 
      43         588 :     PQclear(executeQueryOrDie(conn, ALWAYS_SECURE_SEARCH_PATH_SQL));
      44             : 
      45         588 :     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         634 : 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         634 :     initPQExpBuffer(&conn_opts);
      64         634 :     appendPQExpBufferStr(&conn_opts, "dbname=");
      65         634 :     appendConnStrVal(&conn_opts, db_name);
      66         634 :     appendPQExpBufferStr(&conn_opts, " user=");
      67         634 :     appendConnStrVal(&conn_opts, os_info.user);
      68         634 :     appendPQExpBuffer(&conn_opts, " port=%d", cluster->port);
      69         634 :     if (cluster->sockdir)
      70             :     {
      71         634 :         appendPQExpBufferStr(&conn_opts, " host=");
      72         634 :         appendConnStrVal(&conn_opts, cluster->sockdir);
      73             :     }
      74             : 
      75         634 :     conn = PQconnectdb(conn_opts.data);
      76         634 :     termPQExpBuffer(&conn_opts);
      77         634 :     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 *
      92          70 : cluster_conn_opts(ClusterInfo *cluster)
      93             : {
      94             :     static PQExpBuffer buf;
      95             : 
      96          70 :     if (buf == NULL)
      97           8 :         buf = createPQExpBuffer();
      98             :     else
      99          62 :         resetPQExpBuffer(buf);
     100             : 
     101          70 :     if (cluster->sockdir)
     102             :     {
     103          70 :         appendPQExpBufferStr(buf, "--host ");
     104          70 :         appendShellString(buf, cluster->sockdir);
     105          70 :         appendPQExpBufferChar(buf, ' ');
     106             :     }
     107          70 :     appendPQExpBuffer(buf, "--port %d --username ", cluster->port);
     108          70 :     appendShellString(buf, os_info.user);
     109             : 
     110          70 :     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 *
     122        1292 : executeQueryOrDie(PGconn *conn, const char *fmt,...)
     123             : {
     124             :     static char query[QUERY_ALLOC];
     125             :     va_list     args;
     126             :     PGresult   *result;
     127             :     ExecStatusType status;
     128             : 
     129        1292 :     va_start(args, fmt);
     130        1292 :     vsnprintf(query, sizeof(query), fmt, args);
     131        1292 :     va_end(args);
     132             : 
     133        1292 :     pg_log(PG_VERBOSE, "executing: %s", query);
     134        1292 :     result = PQexec(conn, query);
     135        1292 :     status = PQresultStatus(result);
     136             : 
     137        1292 :     if ((status != PGRES_TUPLES_OK) && (status != PGRES_COMMAND_OK))
     138             :     {
     139           0 :         pg_log(PG_REPORT, "SQL command failed\n%s\n%s", query,
     140             :                PQerrorMessage(conn));
     141           0 :         PQclear(result);
     142           0 :         PQfinish(conn);
     143           0 :         printf(_("Failure, exiting\n"));
     144           0 :         exit(1);
     145             :     }
     146             :     else
     147        1292 :         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
     159          36 : get_major_server_version(ClusterInfo *cluster)
     160             : {
     161             :     FILE       *version_fd;
     162             :     char        ver_filename[MAXPGPATH];
     163          36 :     int         v1 = 0,
     164          36 :                 v2 = 0;
     165             : 
     166          36 :     snprintf(ver_filename, sizeof(ver_filename), "%s/PG_VERSION",
     167             :              cluster->pgdata);
     168          36 :     if ((version_fd = fopen(ver_filename, "r")) == NULL)
     169           0 :         pg_fatal("could not open version file \"%s\": %m", ver_filename);
     170             : 
     171          36 :     if (fscanf(version_fd, "%63s", cluster->major_version_str) == 0 ||
     172          36 :         sscanf(cluster->major_version_str, "%d.%d", &v1, &v2) < 1)
     173           0 :         pg_fatal("could not parse version file \"%s\"", ver_filename);
     174             : 
     175          36 :     fclose(version_fd);
     176             : 
     177          36 :     if (v1 < 10)
     178             :     {
     179             :         /* old style, e.g. 9.6.1 */
     180           0 :         return v1 * 10000 + v2 * 100;
     181             :     }
     182             :     else
     183             :     {
     184             :         /* new style, e.g. 10.1 */
     185          36 :         return v1 * 10000;
     186             :     }
     187             : }
     188             : 
     189             : 
     190             : static void
     191          18 : stop_postmaster_atexit(void)
     192             : {
     193          18 :     stop_postmaster(true);
     194          18 : }
     195             : 
     196             : 
     197             : bool
     198          44 : start_postmaster(ClusterInfo *cluster, bool report_and_exit_on_error)
     199             : {
     200             :     char        cmd[MAXPGPATH * 4 + 1000];
     201             :     PGconn     *conn;
     202          44 :     bool        pg_ctl_return = false;
     203             :     char        socket_string[MAXPGPATH + 200];
     204             :     PQExpBufferData pgoptions;
     205             : 
     206             :     static bool exit_hook_registered = false;
     207             : 
     208          44 :     if (!exit_hook_registered)
     209             :     {
     210          18 :         atexit(stop_postmaster_atexit);
     211          18 :         exit_hook_registered = true;
     212             :     }
     213             : 
     214          44 :     socket_string[0] = '\0';
     215             : 
     216             : #if !defined(WIN32)
     217             :     /* prevent TCP/IP connections, restrict socket access */
     218          44 :     strcat(socket_string,
     219             :            " -c listen_addresses='' -c unix_socket_permissions=0700");
     220             : 
     221             :     /* Have a sockdir?  Tell the postmaster. */
     222          44 :     if (cluster->sockdir)
     223          44 :         snprintf(socket_string + strlen(socket_string),
     224          44 :                  sizeof(socket_string) - strlen(socket_string),
     225             :                  " -c %s='%s'",
     226          44 :                  (GET_MAJOR_VERSION(cluster->major_version) <= 902) ?
     227             :                  "unix_socket_directory" : "unix_socket_directories",
     228             :                  cluster->sockdir);
     229             : #endif
     230             : 
     231          44 :     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          44 :     if (cluster == &new_cluster)
     242          26 :         appendPQExpBufferStr(&pgoptions, " -c synchronous_commit=off -c fsync=off -c full_page_writes=off");
     243             : 
     244             :     /*
     245             :      * Use max_slot_wal_keep_size as -1 to prevent the WAL removal by the
     246             :      * checkpointer process.  If WALs required by logical replication slots
     247             :      * are removed, the slots are unusable.  This setting prevents the
     248             :      * invalidation of slots during the upgrade. We set this option when
     249             :      * cluster is PG17 or later because logical replication slots can only be
     250             :      * migrated since then. Besides, max_slot_wal_keep_size is added in PG13.
     251             :      */
     252          44 :     if (GET_MAJOR_VERSION(cluster->major_version) >= 1700)
     253          44 :         appendPQExpBufferStr(&pgoptions, " -c max_slot_wal_keep_size=-1");
     254             : 
     255             :     /*
     256             :      * Use -b to disable autovacuum and logical replication launcher
     257             :      * (effective in PG17 or later for the latter).
     258             :      */
     259          44 :     snprintf(cmd, sizeof(cmd),
     260             :              "\"%s/pg_ctl\" -w -l \"%s/%s\" -D \"%s\" -o \"-p %d -b%s %s%s\" start",
     261             :              cluster->bindir,
     262             :              log_opts.logdir,
     263          44 :              SERVER_LOG_FILE, cluster->pgconfig, cluster->port,
     264             :              pgoptions.data,
     265          44 :              cluster->pgopts ? cluster->pgopts : "", socket_string);
     266             : 
     267          44 :     termPQExpBuffer(&pgoptions);
     268             : 
     269             :     /*
     270             :      * Don't throw an error right away, let connecting throw the error because
     271             :      * it might supply a reason for the failure.
     272             :      */
     273          44 :     pg_ctl_return = exec_prog(SERVER_START_LOG_FILE,
     274             :     /* pass both file names if they differ */
     275             :                               (strcmp(SERVER_LOG_FILE,
     276             :                                       SERVER_START_LOG_FILE) != 0) ?
     277             :                               SERVER_LOG_FILE : NULL,
     278             :                               report_and_exit_on_error, false,
     279             :                               "%s", cmd);
     280             : 
     281             :     /* Did it fail and we are just testing if the server could be started? */
     282          44 :     if (!pg_ctl_return && !report_and_exit_on_error)
     283           0 :         return false;
     284             : 
     285             :     /*
     286             :      * We set this here to make sure atexit() shuts down the server, but only
     287             :      * if we started the server successfully.  We do it before checking for
     288             :      * connectivity in case the server started but there is a connectivity
     289             :      * failure.  If pg_ctl did not return success, we will exit below.
     290             :      *
     291             :      * Pre-9.1 servers do not have PQping(), so we could be leaving the server
     292             :      * running if authentication was misconfigured, so someday we might went
     293             :      * to be more aggressive about doing server shutdowns even if pg_ctl
     294             :      * fails, but now (2013-08-14) it seems prudent to be cautious.  We don't
     295             :      * want to shutdown a server that might have been accidentally started
     296             :      * during the upgrade.
     297             :      */
     298          44 :     if (pg_ctl_return)
     299          44 :         os_info.running_cluster = cluster;
     300             : 
     301             :     /*
     302             :      * pg_ctl -w might have failed because the server couldn't be started, or
     303             :      * there might have been a connection problem in _checking_ if the server
     304             :      * has started.  Therefore, even if pg_ctl failed, we continue and test
     305             :      * for connectivity in case we get a connection reason for the failure.
     306             :      */
     307          88 :     if ((conn = get_db_conn(cluster, "template1")) == NULL ||
     308          44 :         PQstatus(conn) != CONNECTION_OK)
     309             :     {
     310           0 :         pg_log(PG_REPORT, "\n%s", PQerrorMessage(conn));
     311           0 :         if (conn)
     312           0 :             PQfinish(conn);
     313           0 :         if (cluster == &old_cluster)
     314           0 :             pg_fatal("could not connect to source postmaster started with the command:\n"
     315             :                      "%s",
     316             :                      cmd);
     317             :         else
     318           0 :             pg_fatal("could not connect to target postmaster started with the command:\n"
     319             :                      "%s",
     320             :                      cmd);
     321             :     }
     322          44 :     PQfinish(conn);
     323             : 
     324             :     /*
     325             :      * If pg_ctl failed, and the connection didn't fail, and
     326             :      * report_and_exit_on_error is enabled, fail now.  This could happen if
     327             :      * the server was already running.
     328             :      */
     329          44 :     if (!pg_ctl_return)
     330             :     {
     331           0 :         if (cluster == &old_cluster)
     332           0 :             pg_fatal("pg_ctl failed to start the source server, or connection failed");
     333             :         else
     334           0 :             pg_fatal("pg_ctl failed to start the target server, or connection failed");
     335             :     }
     336             : 
     337          44 :     return true;
     338             : }
     339             : 
     340             : 
     341             : void
     342          52 : stop_postmaster(bool in_atexit)
     343             : {
     344             :     ClusterInfo *cluster;
     345             : 
     346          52 :     if (os_info.running_cluster == &old_cluster)
     347          18 :         cluster = &old_cluster;
     348          34 :     else if (os_info.running_cluster == &new_cluster)
     349          26 :         cluster = &new_cluster;
     350             :     else
     351           8 :         return;                 /* no cluster running */
     352             : 
     353          88 :     exec_prog(SERVER_STOP_LOG_FILE, NULL, !in_atexit, !in_atexit,
     354             :               "\"%s/pg_ctl\" -w -D \"%s\" -o \"%s\" %s stop",
     355             :               cluster->bindir, cluster->pgconfig,
     356          44 :               cluster->pgopts ? cluster->pgopts : "",
     357          44 :               in_atexit ? "-m fast" : "-m smart");
     358             : 
     359          44 :     os_info.running_cluster = NULL;
     360             : }
     361             : 
     362             : 
     363             : /*
     364             :  * check_pghost_envvar()
     365             :  *
     366             :  * Tests that PGHOST does not point to a non-local server
     367             :  */
     368             : void
     369          20 : check_pghost_envvar(void)
     370             : {
     371             :     PQconninfoOption *option;
     372             :     PQconninfoOption *start;
     373             : 
     374             :     /* Get valid libpq env vars from the PQconndefaults function */
     375             : 
     376          20 :     start = PQconndefaults();
     377             : 
     378          20 :     if (!start)
     379           0 :         pg_fatal("out of memory");
     380             : 
     381         820 :     for (option = start; option->keyword != NULL; option++)
     382             :     {
     383         800 :         if (option->envvar && (strcmp(option->envvar, "PGHOST") == 0 ||
     384         620 :                                strcmp(option->envvar, "PGHOSTADDR") == 0))
     385             :         {
     386          40 :             const char *value = getenv(option->envvar);
     387             : 
     388          40 :             if (value && strlen(value) > 0 &&
     389             :             /* check for 'local' host values */
     390          20 :                 (strcmp(value, "localhost") != 0 && strcmp(value, "127.0.0.1") != 0 &&
     391          20 :                  strcmp(value, "::1") != 0 && !is_unixsock_path(value)))
     392           0 :                 pg_fatal("libpq environment variable %s has a non-local server value: %s",
     393             :                          option->envvar, value);
     394             :         }
     395             :     }
     396             : 
     397             :     /* Free the memory that libpq allocated on our behalf */
     398          20 :     PQconninfoFree(start);
     399          20 : }

Generated by: LCOV version 1.14