LCOV - code coverage report
Current view: top level - src/bin/pg_upgrade - option.c (source / functions) Hit Total Coverage
Test: PostgreSQL 16devel Lines: 113 200 56.5 %
Date: 2022-12-05 11:11:09 Functions: 5 5 100.0 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*
       2             :  *  option.c
       3             :  *
       4             :  *  options functions
       5             :  *
       6             :  *  Copyright (c) 2010-2022, PostgreSQL Global Development Group
       7             :  *  src/bin/pg_upgrade/option.c
       8             :  */
       9             : 
      10             : #include "postgres_fe.h"
      11             : 
      12             : #ifdef WIN32
      13             : #include <io.h>
      14             : #endif
      15             : 
      16             : #include "common/string.h"
      17             : #include "getopt_long.h"
      18             : #include "pg_upgrade.h"
      19             : #include "utils/pidfile.h"
      20             : 
      21             : static void usage(void);
      22             : static void check_required_directory(char **dirpath,
      23             :                                      const char *envVarName, bool useCwd,
      24             :                                      const char *cmdLineOption, const char *description,
      25             :                                      bool missingOk);
      26             : #define FIX_DEFAULT_READ_ONLY "-c default_transaction_read_only=false"
      27             : 
      28             : 
      29             : UserOpts    user_opts;
      30             : 
      31             : 
      32             : /*
      33             :  * parseCommandLine()
      34             :  *
      35             :  *  Parses the command line (argc, argv[]) and loads structures
      36             :  */
      37             : void
      38          12 : parseCommandLine(int argc, char *argv[])
      39             : {
      40             :     static struct option long_options[] = {
      41             :         {"old-datadir", required_argument, NULL, 'd'},
      42             :         {"new-datadir", required_argument, NULL, 'D'},
      43             :         {"old-bindir", required_argument, NULL, 'b'},
      44             :         {"new-bindir", required_argument, NULL, 'B'},
      45             :         {"no-sync", no_argument, NULL, 'N'},
      46             :         {"old-options", required_argument, NULL, 'o'},
      47             :         {"new-options", required_argument, NULL, 'O'},
      48             :         {"old-port", required_argument, NULL, 'p'},
      49             :         {"new-port", required_argument, NULL, 'P'},
      50             : 
      51             :         {"username", required_argument, NULL, 'U'},
      52             :         {"check", no_argument, NULL, 'c'},
      53             :         {"link", no_argument, NULL, 'k'},
      54             :         {"retain", no_argument, NULL, 'r'},
      55             :         {"jobs", required_argument, NULL, 'j'},
      56             :         {"socketdir", required_argument, NULL, 's'},
      57             :         {"verbose", no_argument, NULL, 'v'},
      58             :         {"clone", no_argument, NULL, 1},
      59             : 
      60             :         {NULL, 0, NULL, 0}
      61             :     };
      62             :     int         option;         /* Command line option */
      63          12 :     int         optindex = 0;   /* used by getopt_long */
      64             :     int         os_user_effective_id;
      65             : 
      66          12 :     user_opts.do_sync = true;
      67          12 :     user_opts.transfer_mode = TRANSFER_MODE_COPY;
      68             : 
      69          12 :     os_info.progname = get_progname(argv[0]);
      70             : 
      71             :     /* Process libpq env. variables; load values here for usage() output */
      72          12 :     old_cluster.port = getenv("PGPORTOLD") ? atoi(getenv("PGPORTOLD")) : DEF_PGUPORT;
      73          12 :     new_cluster.port = getenv("PGPORTNEW") ? atoi(getenv("PGPORTNEW")) : DEF_PGUPORT;
      74             : 
      75          12 :     os_user_effective_id = get_user_info(&os_info.user);
      76             :     /* we override just the database user name;  we got the OS id above */
      77          12 :     if (getenv("PGUSER"))
      78             :     {
      79           0 :         pg_free(os_info.user);
      80             :         /* must save value, getenv()'s pointer is not stable */
      81           0 :         os_info.user = pg_strdup(getenv("PGUSER"));
      82             :     }
      83             : 
      84          12 :     if (argc > 1)
      85             :     {
      86          12 :         if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
      87             :         {
      88           2 :             usage();
      89           2 :             exit(0);
      90             :         }
      91          10 :         if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
      92             :         {
      93           2 :             puts("pg_upgrade (PostgreSQL) " PG_VERSION);
      94           2 :             exit(0);
      95             :         }
      96             :     }
      97             : 
      98             :     /* Allow help and version to be run as root, so do the test here. */
      99           8 :     if (os_user_effective_id == 0)
     100           0 :         pg_fatal("%s: cannot be run as root", os_info.progname);
     101             : 
     102          60 :     while ((option = getopt_long(argc, argv, "d:D:b:B:cj:kNo:O:p:P:rs:U:v",
     103             :                                  long_options, &optindex)) != -1)
     104             :     {
     105          54 :         switch (option)
     106             :         {
     107           6 :             case 'b':
     108           6 :                 old_cluster.bindir = pg_strdup(optarg);
     109           6 :                 break;
     110             : 
     111           6 :             case 'B':
     112           6 :                 new_cluster.bindir = pg_strdup(optarg);
     113           6 :                 break;
     114             : 
     115           4 :             case 'c':
     116           4 :                 user_opts.check = true;
     117           4 :                 break;
     118             : 
     119           6 :             case 'd':
     120           6 :                 old_cluster.pgdata = pg_strdup(optarg);
     121           6 :                 break;
     122             : 
     123           6 :             case 'D':
     124           6 :                 new_cluster.pgdata = pg_strdup(optarg);
     125           6 :                 break;
     126             : 
     127           0 :             case 'j':
     128           0 :                 user_opts.jobs = atoi(optarg);
     129           0 :                 break;
     130             : 
     131           0 :             case 'k':
     132           0 :                 user_opts.transfer_mode = TRANSFER_MODE_LINK;
     133           0 :                 break;
     134             : 
     135           6 :             case 'N':
     136           6 :                 user_opts.do_sync = false;
     137           6 :                 break;
     138             : 
     139           0 :             case 'o':
     140             :                 /* append option? */
     141           0 :                 if (!old_cluster.pgopts)
     142           0 :                     old_cluster.pgopts = pg_strdup(optarg);
     143             :                 else
     144             :                 {
     145           0 :                     char       *old_pgopts = old_cluster.pgopts;
     146             : 
     147           0 :                     old_cluster.pgopts = psprintf("%s %s", old_pgopts, optarg);
     148           0 :                     free(old_pgopts);
     149             :                 }
     150           0 :                 break;
     151             : 
     152           0 :             case 'O':
     153             :                 /* append option? */
     154           0 :                 if (!new_cluster.pgopts)
     155           0 :                     new_cluster.pgopts = pg_strdup(optarg);
     156             :                 else
     157             :                 {
     158           0 :                     char       *new_pgopts = new_cluster.pgopts;
     159             : 
     160           0 :                     new_cluster.pgopts = psprintf("%s %s", new_pgopts, optarg);
     161           0 :                     free(new_pgopts);
     162             :                 }
     163           0 :                 break;
     164             : 
     165           6 :             case 'p':
     166           6 :                 if ((old_cluster.port = atoi(optarg)) <= 0)
     167           0 :                     pg_fatal("invalid old port number");
     168           6 :                 break;
     169             : 
     170           6 :             case 'P':
     171           6 :                 if ((new_cluster.port = atoi(optarg)) <= 0)
     172           0 :                     pg_fatal("invalid new port number");
     173           6 :                 break;
     174             : 
     175           0 :             case 'r':
     176           0 :                 log_opts.retain = true;
     177           0 :                 break;
     178             : 
     179           6 :             case 's':
     180           6 :                 user_opts.socketdir = pg_strdup(optarg);
     181           6 :                 break;
     182             : 
     183           0 :             case 'U':
     184           0 :                 pg_free(os_info.user);
     185           0 :                 os_info.user = pg_strdup(optarg);
     186           0 :                 os_info.user_specified = true;
     187           0 :                 break;
     188             : 
     189           0 :             case 'v':
     190           0 :                 log_opts.verbose = true;
     191           0 :                 break;
     192             : 
     193           0 :             case 1:
     194           0 :                 user_opts.transfer_mode = TRANSFER_MODE_CLONE;
     195           0 :                 break;
     196             : 
     197           2 :             default:
     198           2 :                 fprintf(stderr, _("Try \"%s --help\" for more information.\n"),
     199             :                         os_info.progname);
     200           2 :                 exit(1);
     201             :         }
     202             :     }
     203             : 
     204           6 :     if (optind < argc)
     205           0 :         pg_fatal("too many command-line arguments (first is \"%s\")", argv[optind]);
     206             : 
     207           6 :     if (log_opts.verbose)
     208           0 :         pg_log(PG_REPORT, "Running in verbose mode");
     209             : 
     210           6 :     log_opts.isatty = isatty(fileno(stdout));
     211             : 
     212             :     /* Turn off read-only mode;  add prefix to PGOPTIONS? */
     213           6 :     if (getenv("PGOPTIONS"))
     214             :     {
     215           0 :         char       *pgoptions = psprintf("%s %s", FIX_DEFAULT_READ_ONLY,
     216             :                                          getenv("PGOPTIONS"));
     217             : 
     218           0 :         setenv("PGOPTIONS", pgoptions, 1);
     219           0 :         pfree(pgoptions);
     220             :     }
     221             :     else
     222           6 :         setenv("PGOPTIONS", FIX_DEFAULT_READ_ONLY, 1);
     223             : 
     224             :     /* Get values from env if not already set */
     225           6 :     check_required_directory(&old_cluster.bindir, "PGBINOLD", false,
     226           6 :                              "-b", _("old cluster binaries reside"), false);
     227           6 :     check_required_directory(&new_cluster.bindir, "PGBINNEW", false,
     228           6 :                              "-B", _("new cluster binaries reside"), true);
     229           6 :     check_required_directory(&old_cluster.pgdata, "PGDATAOLD", false,
     230           6 :                              "-d", _("old cluster data resides"), false);
     231           6 :     check_required_directory(&new_cluster.pgdata, "PGDATANEW", false,
     232           6 :                              "-D", _("new cluster data resides"), false);
     233           6 :     check_required_directory(&user_opts.socketdir, "PGSOCKETDIR", true,
     234           6 :                              "-s", _("sockets will be created"), false);
     235             : 
     236             : #ifdef WIN32
     237             : 
     238             :     /*
     239             :      * On Windows, initdb --sync-only will fail with a "Permission denied"
     240             :      * error on file pg_upgrade_utility.log if pg_upgrade is run inside the
     241             :      * new cluster directory, so we do a check here.
     242             :      */
     243             :     {
     244             :         char        cwd[MAXPGPATH],
     245             :                     new_cluster_pgdata[MAXPGPATH];
     246             : 
     247             :         strlcpy(new_cluster_pgdata, new_cluster.pgdata, MAXPGPATH);
     248             :         canonicalize_path(new_cluster_pgdata);
     249             : 
     250             :         if (!getcwd(cwd, MAXPGPATH))
     251             :             pg_fatal("could not determine current directory");
     252             :         canonicalize_path(cwd);
     253             :         if (path_is_prefix_of_path(new_cluster_pgdata, cwd))
     254             :             pg_fatal("cannot run pg_upgrade from inside the new cluster data directory on Windows");
     255             :     }
     256             : #endif
     257           6 : }
     258             : 
     259             : 
     260             : static void
     261           2 : usage(void)
     262             : {
     263           2 :     printf(_("pg_upgrade upgrades a PostgreSQL cluster to a different major version.\n\n"));
     264           2 :     printf(_("Usage:\n"));
     265           2 :     printf(_("  pg_upgrade [OPTION]...\n\n"));
     266           2 :     printf(_("Options:\n"));
     267           2 :     printf(_("  -b, --old-bindir=BINDIR       old cluster executable directory\n"));
     268           2 :     printf(_("  -B, --new-bindir=BINDIR       new cluster executable directory (default\n"
     269             :              "                                same directory as pg_upgrade)\n"));
     270           2 :     printf(_("  -c, --check                   check clusters only, don't change any data\n"));
     271           2 :     printf(_("  -d, --old-datadir=DATADIR     old cluster data directory\n"));
     272           2 :     printf(_("  -D, --new-datadir=DATADIR     new cluster data directory\n"));
     273           2 :     printf(_("  -j, --jobs=NUM                number of simultaneous processes or threads to use\n"));
     274           2 :     printf(_("  -k, --link                    link instead of copying files to new cluster\n"));
     275           2 :     printf(_("  -N, --no-sync                 do not wait for changes to be written safely to disk\n"));
     276           2 :     printf(_("  -o, --old-options=OPTIONS     old cluster options to pass to the server\n"));
     277           2 :     printf(_("  -O, --new-options=OPTIONS     new cluster options to pass to the server\n"));
     278           2 :     printf(_("  -p, --old-port=PORT           old cluster port number (default %d)\n"), old_cluster.port);
     279           2 :     printf(_("  -P, --new-port=PORT           new cluster port number (default %d)\n"), new_cluster.port);
     280           2 :     printf(_("  -r, --retain                  retain SQL and log files after success\n"));
     281           2 :     printf(_("  -s, --socketdir=DIR           socket directory to use (default current dir.)\n"));
     282           2 :     printf(_("  -U, --username=NAME           cluster superuser (default \"%s\")\n"), os_info.user);
     283           2 :     printf(_("  -v, --verbose                 enable verbose internal logging\n"));
     284           2 :     printf(_("  -V, --version                 display version information, then exit\n"));
     285           2 :     printf(_("  --clone                       clone instead of copying files to new cluster\n"));
     286           2 :     printf(_("  -?, --help                    show this help, then exit\n"));
     287           2 :     printf(_("\n"
     288             :              "Before running pg_upgrade you must:\n"
     289             :              "  create a new database cluster (using the new version of initdb)\n"
     290             :              "  shutdown the postmaster servicing the old cluster\n"
     291             :              "  shutdown the postmaster servicing the new cluster\n"));
     292           2 :     printf(_("\n"
     293             :              "When you run pg_upgrade, you must provide the following information:\n"
     294             :              "  the data directory for the old cluster  (-d DATADIR)\n"
     295             :              "  the data directory for the new cluster  (-D DATADIR)\n"
     296             :              "  the \"bin\" directory for the old version (-b BINDIR)\n"
     297             :              "  the \"bin\" directory for the new version (-B BINDIR)\n"));
     298           2 :     printf(_("\n"
     299             :              "For example:\n"
     300             :              "  pg_upgrade -d oldCluster/data -D newCluster/data -b oldCluster/bin -B newCluster/bin\n"
     301             :              "or\n"));
     302             : #ifndef WIN32
     303           2 :     printf(_("  $ export PGDATAOLD=oldCluster/data\n"
     304             :              "  $ export PGDATANEW=newCluster/data\n"
     305             :              "  $ export PGBINOLD=oldCluster/bin\n"
     306             :              "  $ export PGBINNEW=newCluster/bin\n"
     307             :              "  $ pg_upgrade\n"));
     308             : #else
     309             :     printf(_("  C:\\> set PGDATAOLD=oldCluster/data\n"
     310             :              "  C:\\> set PGDATANEW=newCluster/data\n"
     311             :              "  C:\\> set PGBINOLD=oldCluster/bin\n"
     312             :              "  C:\\> set PGBINNEW=newCluster/bin\n"
     313             :              "  C:\\> pg_upgrade\n"));
     314             : #endif
     315           2 :     printf(_("\nReport bugs to <%s>.\n"), PACKAGE_BUGREPORT);
     316           2 :     printf(_("%s home page: <%s>\n"), PACKAGE_NAME, PACKAGE_URL);
     317           2 : }
     318             : 
     319             : 
     320             : /*
     321             :  * check_required_directory()
     322             :  *
     323             :  * Checks a directory option.
     324             :  *  dirpath       - the directory name supplied on the command line, or NULL
     325             :  *  envVarName    - the name of an environment variable to get if dirpath is NULL
     326             :  *  useCwd        - true if OK to default to CWD
     327             :  *  cmdLineOption - the command line option for this directory
     328             :  *  description   - a description of this directory option
     329             :  *  missingOk     - true if OK that both dirpath and envVarName are not existing
     330             :  *
     331             :  * We use the last two arguments to construct a meaningful error message if the
     332             :  * user hasn't provided the required directory name.
     333             :  */
     334             : static void
     335          30 : check_required_directory(char **dirpath, const char *envVarName, bool useCwd,
     336             :                          const char *cmdLineOption, const char *description,
     337             :                          bool missingOk)
     338             : {
     339          30 :     if (*dirpath == NULL || strlen(*dirpath) == 0)
     340             :     {
     341             :         const char *envVar;
     342             : 
     343           0 :         if ((envVar = getenv(envVarName)) && strlen(envVar))
     344           0 :             *dirpath = pg_strdup(envVar);
     345           0 :         else if (useCwd)
     346             :         {
     347             :             char        cwd[MAXPGPATH];
     348             : 
     349           0 :             if (!getcwd(cwd, MAXPGPATH))
     350           0 :                 pg_fatal("could not determine current directory");
     351           0 :             *dirpath = pg_strdup(cwd);
     352             :         }
     353           0 :         else if (missingOk)
     354           0 :             return;
     355             :         else
     356           0 :             pg_fatal("You must identify the directory where the %s.\n"
     357             :                      "Please use the %s command-line option or the %s environment variable.",
     358             :                      description, cmdLineOption, envVarName);
     359             :     }
     360             : 
     361             :     /*
     362             :      * Clean up the path, in particular trimming any trailing path separators,
     363             :      * because we construct paths by appending to this path.
     364             :      */
     365          30 :     canonicalize_path(*dirpath);
     366             : }
     367             : 
     368             : /*
     369             :  * adjust_data_dir
     370             :  *
     371             :  * If a configuration-only directory was specified, find the real data dir
     372             :  * by querying the running server.  This has limited checking because we
     373             :  * can't check for a running server because we can't find postmaster.pid.
     374             :  *
     375             :  * On entry, cluster->pgdata has been set from command line or env variable,
     376             :  * but cluster->pgconfig isn't set.  We fill both variables with corrected
     377             :  * values.
     378             :  */
     379             : void
     380          12 : adjust_data_dir(ClusterInfo *cluster)
     381             : {
     382             :     char        filename[MAXPGPATH];
     383             :     char        cmd[MAXPGPATH],
     384             :                 cmd_output[MAX_STRING];
     385             :     FILE       *fp,
     386             :                *output;
     387             :     int         rc;
     388             : 
     389             :     /* Initially assume config dir and data dir are the same */
     390          12 :     cluster->pgconfig = pg_strdup(cluster->pgdata);
     391             : 
     392             :     /* If there is no postgresql.conf, it can't be a config-only dir */
     393          12 :     snprintf(filename, sizeof(filename), "%s/postgresql.conf", cluster->pgconfig);
     394          12 :     if ((fp = fopen(filename, "r")) == NULL)
     395          12 :         return;
     396          12 :     fclose(fp);
     397             : 
     398             :     /* If PG_VERSION exists, it can't be a config-only dir */
     399          12 :     snprintf(filename, sizeof(filename), "%s/PG_VERSION", cluster->pgconfig);
     400          12 :     if ((fp = fopen(filename, "r")) != NULL)
     401             :     {
     402          12 :         fclose(fp);
     403          12 :         return;
     404             :     }
     405             : 
     406             :     /* Must be a configuration directory, so find the real data directory. */
     407             : 
     408           0 :     if (cluster == &old_cluster)
     409           0 :         prep_status("Finding the real data directory for the source cluster");
     410             :     else
     411           0 :         prep_status("Finding the real data directory for the target cluster");
     412             : 
     413             :     /*
     414             :      * We don't have a data directory yet, so we can't check the PG version,
     415             :      * so this might fail --- only works for PG 9.2+.   If this fails,
     416             :      * pg_upgrade will fail anyway because the data files will not be found.
     417             :      */
     418           0 :     snprintf(cmd, sizeof(cmd), "\"%s/postgres\" -D \"%s\" -C data_directory",
     419             :              cluster->bindir, cluster->pgconfig);
     420           0 :     fflush(NULL);
     421             : 
     422           0 :     if ((output = popen(cmd, "r")) == NULL ||
     423           0 :         fgets(cmd_output, sizeof(cmd_output), output) == NULL)
     424           0 :         pg_fatal("could not get data directory using %s: %s",
     425           0 :                  cmd, strerror(errno));
     426             : 
     427           0 :     rc = pclose(output);
     428           0 :     if (rc != 0)
     429           0 :         pg_fatal("could not get control data directory using %s: %s",
     430             :                  cmd, wait_result_to_str(rc));
     431             : 
     432             :     /* strip trailing newline and carriage return */
     433           0 :     (void) pg_strip_crlf(cmd_output);
     434             : 
     435           0 :     cluster->pgdata = pg_strdup(cmd_output);
     436             : 
     437           0 :     check_ok();
     438             : }
     439             : 
     440             : 
     441             : /*
     442             :  * get_sock_dir
     443             :  *
     444             :  * Identify the socket directory to use for this cluster.  If we're doing
     445             :  * a live check (old cluster only), we need to find out where the postmaster
     446             :  * is listening.  Otherwise, we're going to put the socket into the current
     447             :  * directory.
     448             :  */
     449             : void
     450           8 : get_sock_dir(ClusterInfo *cluster, bool live_check)
     451             : {
     452             : #if !defined(WIN32)
     453           8 :     if (!live_check)
     454           8 :         cluster->sockdir = user_opts.socketdir;
     455             :     else
     456             :     {
     457             :         /*
     458             :          * If we are doing a live check, we will use the old cluster's Unix
     459             :          * domain socket directory so we can connect to the live server.
     460             :          */
     461           0 :         unsigned short orig_port = cluster->port;
     462             :         char        filename[MAXPGPATH],
     463             :                     line[MAXPGPATH];
     464             :         FILE       *fp;
     465             :         int         lineno;
     466             : 
     467           0 :         snprintf(filename, sizeof(filename), "%s/postmaster.pid",
     468             :                  cluster->pgdata);
     469           0 :         if ((fp = fopen(filename, "r")) == NULL)
     470           0 :             pg_fatal("could not open file \"%s\": %s",
     471           0 :                      filename, strerror(errno));
     472             : 
     473           0 :         for (lineno = 1;
     474             :              lineno <= Max(LOCK_FILE_LINE_PORT, LOCK_FILE_LINE_SOCKET_DIR);
     475           0 :              lineno++)
     476             :         {
     477           0 :             if (fgets(line, sizeof(line), fp) == NULL)
     478           0 :                 pg_fatal("could not read line %d from file \"%s\": %s",
     479           0 :                          lineno, filename, strerror(errno));
     480             : 
     481             :             /* potentially overwrite user-supplied value */
     482           0 :             if (lineno == LOCK_FILE_LINE_PORT)
     483           0 :                 sscanf(line, "%hu", &old_cluster.port);
     484           0 :             if (lineno == LOCK_FILE_LINE_SOCKET_DIR)
     485             :             {
     486             :                 /* strip trailing newline and carriage return */
     487           0 :                 cluster->sockdir = pg_strdup(line);
     488           0 :                 (void) pg_strip_crlf(cluster->sockdir);
     489             :             }
     490             :         }
     491           0 :         fclose(fp);
     492             : 
     493             :         /* warn of port number correction */
     494           0 :         if (orig_port != DEF_PGUPORT && old_cluster.port != orig_port)
     495           0 :             pg_log(PG_WARNING, "user-supplied old port number %hu corrected to %hu",
     496           0 :                    orig_port, cluster->port);
     497             :     }
     498             : #else                           /* WIN32 */
     499             :     cluster->sockdir = NULL;
     500             : #endif
     501           8 : }

Generated by: LCOV version 1.14