LCOV - code coverage report
Current view: top level - src/bin/pg_upgrade - server.c (source / functions) Coverage Total Hit
Test: PostgreSQL 20devel Lines: 80.2 % 121 97
Test Date: 2026-11-24 01:16:08 Functions: 100.0 % 8 8
Legend: Lines:     hit not hit
Branches: + taken - not taken # not executed
Branches: 63.2 % 76 48

             Branch data     Line data    Source code
       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"
      13                 :             : #include "fe_utils/string_utils.h"
      14                 :             : #include "lib/stringinfo.h"
      15                 :             : #include "libpq/pqcomm.h"
      16                 :             : #include "pg_upgrade.h"
      17                 :             : 
      18                 :             : static PGconn *get_db_conn(ClusterInfo *cluster, const char *db_name);
      19                 :             : 
      20                 :             : 
      21                 :             : /*
      22                 :             :  * connectToServer()
      23                 :             :  *
      24                 :             :  *  Connects to the desired database on the designated server.
      25                 :             :  *  If the connection attempt fails, this function logs an error
      26                 :             :  *  message and calls exit() to kill the program.
      27                 :             :  */
      28                 :             : PGconn *
      29                 :         404 : connectToServer(ClusterInfo *cluster, const char *db_name)
      30                 :             : {
      31                 :         404 :     PGconn     *conn = get_db_conn(cluster, db_name);
      32                 :             : 
      33   [ +  -  -  + ]:         404 :     if (conn == NULL || PQstatus(conn) != CONNECTION_OK)
      34                 :             :     {
      35                 :           0 :         pg_log(PG_REPORT, "%s", PQerrorMessage(conn));
      36                 :             : 
      37         [ #  # ]:           0 :         if (conn)
      38                 :           0 :             PQfinish(conn);
      39                 :             : 
      40                 :           0 :         printf(_("Failure, exiting\n"));
      41                 :           0 :         exit(1);
      42                 :             :     }
      43                 :             : 
      44                 :         404 :     PQclear(executeQueryOrDie(conn, ALWAYS_SECURE_SEARCH_PATH_SQL));
      45                 :             : 
      46                 :         404 :     return conn;
      47                 :             : }
      48                 :             : 
      49                 :             : 
      50                 :             : /*
      51                 :             :  * get_db_conn()
      52                 :             :  *
      53                 :             :  * get database connection, using named database + standard params for cluster
      54                 :             :  *
      55                 :             :  * Caller must check for connection failure!
      56                 :             :  */
      57                 :             : static PGconn *
      58                 :         465 : get_db_conn(ClusterInfo *cluster, const char *db_name)
      59                 :             : {
      60                 :             :     PQExpBufferData conn_opts;
      61                 :             :     PGconn     *conn;
      62                 :             : 
      63                 :             :     /* Build connection string with proper quoting */
      64                 :         465 :     initPQExpBuffer(&conn_opts);
      65                 :         465 :     appendPQExpBufferStr(&conn_opts, "dbname=");
      66                 :         465 :     appendConnStrVal(&conn_opts, db_name);
      67                 :         465 :     appendPQExpBufferStr(&conn_opts, " user=");
      68                 :         465 :     appendConnStrVal(&conn_opts, os_info.user);
      69                 :         465 :     appendPQExpBuffer(&conn_opts, " port=%d", cluster->port);
      70         [ +  - ]:         465 :     if (cluster->sockdir)
      71                 :             :     {
      72                 :         465 :         appendPQExpBufferStr(&conn_opts, " host=");
      73                 :         465 :         appendConnStrVal(&conn_opts, cluster->sockdir);
      74                 :             :     }
      75         [ -  + ]:         465 :     if (!protocol_negotiation_supported(cluster))
      76                 :           0 :         appendPQExpBufferStr(&conn_opts, " max_protocol_version=3.0");
      77                 :             : 
      78                 :         465 :     conn = PQconnectdb(conn_opts.data);
      79                 :         465 :     termPQExpBuffer(&conn_opts);
      80                 :         465 :     return conn;
      81                 :             : }
      82                 :             : 
      83                 :             : 
      84                 :             : /*
      85                 :             :  * cluster_conn_opts()
      86                 :             :  *
      87                 :             :  * Return standard command-line options for connecting to this cluster when
      88                 :             :  * using psql, pg_dump, etc.  Ideally this would match what get_db_conn()
      89                 :             :  * sets, but the utilities we need aren't very consistent about the treatment
      90                 :             :  * of database name options, so we leave that out.
      91                 :             :  *
      92                 :             :  * Result is valid until the next call to this function.
      93                 :             :  */
      94                 :             : char *
      95                 :         123 : cluster_conn_opts(ClusterInfo *cluster)
      96                 :             : {
      97                 :             :     static PQExpBuffer buf;
      98                 :             : 
      99         [ +  + ]:         123 :     if (buf == NULL)
     100                 :          14 :         buf = createPQExpBuffer();
     101                 :             :     else
     102                 :         109 :         resetPQExpBuffer(buf);
     103                 :             : 
     104         [ +  - ]:         123 :     if (cluster->sockdir)
     105                 :             :     {
     106                 :         123 :         appendPQExpBufferStr(buf, "--host ");
     107                 :         123 :         appendShellString(buf, cluster->sockdir);
     108                 :         123 :         appendPQExpBufferChar(buf, ' ');
     109                 :             :     }
     110                 :         123 :     appendPQExpBuffer(buf, "--port %d --username ", cluster->port);
     111                 :         123 :     appendShellString(buf, os_info.user);
     112                 :             : 
     113                 :         123 :     return buf->data;
     114                 :             : }
     115                 :             : 
     116                 :             : 
     117                 :             : /*
     118                 :             :  * executeQueryOrDie()
     119                 :             :  *
     120                 :             :  *  Formats a query string from the given arguments and executes the
     121                 :             :  *  resulting query.  If the query fails, this function logs an error
     122                 :             :  *  message and calls exit() to kill the program.
     123                 :             :  */
     124                 :             : PGresult *
     125                 :         909 : executeQueryOrDie(PGconn *conn, const char *fmt, ...)
     126                 :             : {
     127                 :         909 :     int         save_errno = errno;
     128                 :             :     StringInfoData query;
     129                 :             :     PGresult   *result;
     130                 :             :     ExecStatusType status;
     131                 :             : 
     132                 :         909 :     initStringInfo(&query);
     133                 :             :     for (;;)
     134                 :           0 :     {
     135                 :             :         va_list     args;
     136                 :             :         int         needed;
     137                 :             : 
     138                 :         909 :         errno = save_errno;
     139                 :         909 :         va_start(args, fmt);
     140                 :         909 :         needed = appendStringInfoVA(&query, fmt, args);
     141                 :         909 :         va_end(args);
     142         [ +  - ]:         909 :         if (needed == 0)
     143                 :         909 :             break;
     144                 :           0 :         enlargeStringInfo(&query, needed);
     145                 :             :     }
     146                 :             : 
     147                 :         909 :     pg_log(PG_VERBOSE, "executing: %s", query.data);
     148                 :         909 :     result = PQexec(conn, query.data);
     149                 :         909 :     status = PQresultStatus(result);
     150                 :             : 
     151   [ +  +  -  + ]:         909 :     if ((status != PGRES_TUPLES_OK) && (status != PGRES_COMMAND_OK))
     152                 :             :     {
     153                 :           0 :         pg_log(PG_REPORT, "SQL command failed\n%s\n%s", query.data,
     154                 :             :                PQerrorMessage(conn));
     155                 :           0 :         PQclear(result);
     156                 :           0 :         PQfinish(conn);
     157                 :           0 :         printf(_("Failure, exiting\n"));
     158                 :           0 :         exit(1);
     159                 :             :     }
     160                 :         909 :     pg_free(query.data);
     161                 :         909 :     return result;
     162                 :             : }
     163                 :             : 
     164                 :             : 
     165                 :             : static void
     166                 :          21 : stop_postmaster_atexit(void)
     167                 :             : {
     168                 :          21 :     stop_postmaster(true);
     169                 :          21 : }
     170                 :             : 
     171                 :             : 
     172                 :             : bool
     173                 :          63 : start_postmaster(ClusterInfo *cluster, bool report_and_exit_on_error)
     174                 :             : {
     175                 :             :     char        cmd[MAXPGPATH * 4 + 1000];
     176                 :             :     PGconn     *conn;
     177                 :          63 :     bool        pg_ctl_return = false;
     178                 :             :     char        socket_string[MAXPGPATH + 200];
     179                 :             :     PQExpBufferData pgoptions;
     180                 :             : 
     181                 :             :     static bool exit_hook_registered = false;
     182                 :             : 
     183         [ +  + ]:          63 :     if (!exit_hook_registered)
     184                 :             :     {
     185                 :          21 :         atexit(stop_postmaster_atexit);
     186                 :          21 :         exit_hook_registered = true;
     187                 :             :     }
     188                 :             : 
     189                 :          63 :     socket_string[0] = '\0';
     190                 :             : 
     191                 :             : #if !defined(WIN32)
     192                 :             :     /* prevent TCP/IP connections, restrict socket access */
     193                 :          63 :     strcat(socket_string,
     194                 :             :            " -c listen_addresses='' -c unix_socket_permissions=0700");
     195                 :             : 
     196                 :             :     /* Have a sockdir?  Tell the postmaster. */
     197         [ +  + ]:          63 :     if (cluster->sockdir)
     198                 :          61 :         snprintf(socket_string + strlen(socket_string),
     199                 :          61 :                  sizeof(socket_string) - strlen(socket_string),
     200                 :             :                  " -c %s='%s'",
     201                 :             :                  "unix_socket_directories",
     202                 :             :                  cluster->sockdir);
     203                 :             : #endif
     204                 :             : 
     205                 :          63 :     initPQExpBuffer(&pgoptions);
     206                 :             : 
     207                 :             :     /*
     208                 :             :      * Construct a parameter string which is passed to the server process.
     209                 :             :      *
     210                 :             :      * Turn off durability requirements to improve object creation speed, and
     211                 :             :      * we only modify the new cluster, so only use it there.  If there is a
     212                 :             :      * crash, the new cluster has to be recreated anyway.  fsync=off is a big
     213                 :             :      * win on ext4.
     214                 :             :      */
     215         [ +  + ]:          63 :     if (cluster == &new_cluster)
     216                 :          42 :         appendPQExpBufferStr(&pgoptions, " -c synchronous_commit=off -c fsync=off -c full_page_writes=off");
     217                 :             : 
     218                 :             :     /*
     219                 :             :      * Use -b to disable autovacuum and logical replication launcher
     220                 :             :      * (effective in PG17 or later for the latter).
     221                 :             :      */
     222                 :          63 :     snprintf(cmd, sizeof(cmd),
     223                 :             :              "\"%s/pg_ctl\" -w -l \"%s/%s\" -D \"%s\" -o \"-p %d -b%s %s%s\" start",
     224                 :             :              cluster->bindir,
     225                 :             :              log_opts.logdir,
     226                 :          63 :              SERVER_LOG_FILE, cluster->pgconfig, cluster->port,
     227                 :             :              pgoptions.data,
     228         [ -  + ]:          63 :              cluster->pgopts ? cluster->pgopts : "", socket_string);
     229                 :             : 
     230                 :          63 :     termPQExpBuffer(&pgoptions);
     231                 :             : 
     232                 :             :     /*
     233                 :             :      * Don't throw an error right away, let connecting throw the error because
     234                 :             :      * it might supply a reason for the failure.
     235                 :             :      */
     236                 :          63 :     pg_ctl_return = exec_prog(SERVER_START_LOG_FILE,
     237                 :             :     /* pass both file names if they differ */
     238                 :             :                               (strcmp(SERVER_LOG_FILE,
     239                 :             :                                       SERVER_START_LOG_FILE) != 0) ?
     240                 :             :                               SERVER_LOG_FILE : NULL,
     241                 :             :                               report_and_exit_on_error, false,
     242                 :             :                               "%s", cmd);
     243                 :             : 
     244                 :             :     /* Did it fail and we are just testing if the server could be started? */
     245   [ +  +  +  - ]:          63 :     if (!pg_ctl_return && !report_and_exit_on_error)
     246                 :           2 :         return false;
     247                 :             : 
     248                 :             :     /*
     249                 :             :      * We set this here to make sure atexit() shuts down the server, but only
     250                 :             :      * if we started the server successfully.  We do it before checking for
     251                 :             :      * connectivity in case the server started but there is a connectivity
     252                 :             :      * failure.  If pg_ctl did not return success, we will exit below.
     253                 :             :      *
     254                 :             :      * Pre-9.1 servers do not have PQping(), so we could be leaving the server
     255                 :             :      * running if authentication was misconfigured, so someday we might went
     256                 :             :      * to be more aggressive about doing server shutdowns even if pg_ctl
     257                 :             :      * fails, but now (2013-08-14) it seems prudent to be cautious.  We don't
     258                 :             :      * want to shutdown a server that might have been accidentally started
     259                 :             :      * during the upgrade.
     260                 :             :      */
     261         [ +  - ]:          61 :     if (pg_ctl_return)
     262                 :          61 :         os_info.running_cluster = cluster;
     263                 :             : 
     264                 :             :     /*
     265                 :             :      * pg_ctl -w might have failed because the server couldn't be started, or
     266                 :             :      * there might have been a connection problem in _checking_ if the server
     267                 :             :      * has started.  Therefore, even if pg_ctl failed, we continue and test
     268                 :             :      * for connectivity in case we get a connection reason for the failure.
     269                 :             :      */
     270   [ +  -  -  + ]:         122 :     if ((conn = get_db_conn(cluster, "template1")) == NULL ||
     271                 :          61 :         PQstatus(conn) != CONNECTION_OK)
     272                 :             :     {
     273                 :           0 :         pg_log(PG_REPORT, "\n%s", PQerrorMessage(conn));
     274         [ #  # ]:           0 :         if (conn)
     275                 :           0 :             PQfinish(conn);
     276         [ #  # ]:           0 :         if (cluster == &old_cluster)
     277                 :           0 :             pg_fatal("could not connect to source postmaster started with the command:\n"
     278                 :             :                      "%s",
     279                 :             :                      cmd);
     280                 :             :         else
     281                 :           0 :             pg_fatal("could not connect to target postmaster started with the command:\n"
     282                 :             :                      "%s",
     283                 :             :                      cmd);
     284                 :             :     }
     285                 :          61 :     PQfinish(conn);
     286                 :             : 
     287                 :             :     /*
     288                 :             :      * If pg_ctl failed, and the connection didn't fail, and
     289                 :             :      * report_and_exit_on_error is enabled, fail now.  This could happen if
     290                 :             :      * the server was already running.
     291                 :             :      */
     292         [ -  + ]:          61 :     if (!pg_ctl_return)
     293                 :             :     {
     294         [ #  # ]:           0 :         if (cluster == &old_cluster)
     295                 :           0 :             pg_fatal("pg_ctl failed to start the source server, or connection failed");
     296                 :             :         else
     297                 :           0 :             pg_fatal("pg_ctl failed to start the target server, or connection failed");
     298                 :             :     }
     299                 :             : 
     300                 :          61 :     return true;
     301                 :             : }
     302                 :             : 
     303                 :             : 
     304                 :             : void
     305                 :          75 : stop_postmaster(bool in_atexit)
     306                 :             : {
     307                 :             :     ClusterInfo *cluster;
     308                 :             : 
     309         [ +  + ]:          75 :     if (os_info.running_cluster == &old_cluster)
     310                 :          19 :         cluster = &old_cluster;
     311         [ +  + ]:          56 :     else if (os_info.running_cluster == &new_cluster)
     312                 :          42 :         cluster = &new_cluster;
     313                 :             :     else
     314                 :          14 :         return;                 /* no cluster running */
     315                 :             : 
     316         [ +  + ]:         122 :     exec_prog(SERVER_STOP_LOG_FILE, NULL, !in_atexit, !in_atexit,
     317                 :             :               "\"%s/pg_ctl\" -w -D \"%s\" -o \"%s\" %s stop",
     318                 :             :               cluster->bindir, cluster->pgconfig,
     319         [ -  + ]:          61 :               cluster->pgopts ? cluster->pgopts : "",
     320                 :          61 :               in_atexit ? "-m fast" : "-m smart");
     321                 :             : 
     322                 :          61 :     os_info.running_cluster = NULL;
     323                 :             : }
     324                 :             : 
     325                 :             : 
     326                 :             : /*
     327                 :             :  * check_pghost_envvar()
     328                 :             :  *
     329                 :             :  * Tests that PGHOST does not point to a non-local server
     330                 :             :  */
     331                 :             : void
     332                 :          22 : check_pghost_envvar(void)
     333                 :             : {
     334                 :             :     PQconninfoOption *option;
     335                 :             :     PQconninfoOption *start;
     336                 :             : 
     337                 :             :     /* Get valid libpq env vars from the PQconndefaults function */
     338                 :             : 
     339                 :          22 :     start = PQconndefaults();
     340                 :             : 
     341         [ -  + ]:          22 :     if (!start)
     342                 :           0 :         pg_fatal("out of memory");
     343                 :             : 
     344         [ +  + ]:        1144 :     for (option = start; option->keyword != NULL; option++)
     345                 :             :     {
     346   [ +  +  +  + ]:        1122 :         if (option->envvar && (strcmp(option->envvar, "PGHOST") == 0 ||
     347         [ +  + ]:         770 :                                strcmp(option->envvar, "PGHOSTADDR") == 0))
     348                 :             :         {
     349                 :          44 :             const char *value = getenv(option->envvar);
     350                 :             : 
     351   [ +  +  +  - ]:          44 :             if (value && strlen(value) > 0 &&
     352                 :             :             /* check for 'local' host values */
     353   [ +  -  +  - ]:          22 :                 (strcmp(value, "localhost") != 0 && strcmp(value, "127.0.0.1") != 0 &&
     354   [ +  -  -  + ]:          22 :                  strcmp(value, "::1") != 0 && !is_unixsock_path(value)))
     355                 :           0 :                 pg_fatal("libpq environment variable %s has a non-local server value: %s",
     356                 :             :                          option->envvar, value);
     357                 :             :         }
     358                 :             :     }
     359                 :             : 
     360                 :             :     /* Free the memory that libpq allocated on our behalf */
     361                 :          22 :     PQconninfoFree(start);
     362                 :          22 : }
        

Generated by: LCOV version 2.0-1