option.c 13.5 KB
Newer Older
1 2 3 4
/*
 *	opt.c
 *
 *	options functions
5
 *
B
Bruce Momjian 已提交
6
 *	Copyright (c) 2010-2014, PostgreSQL Global Development Group
7
 *	contrib/pg_upgrade/option.c
8 9
 */

10
#include "postgres_fe.h"
11

12 13
#include "miscadmin.h"

14 15
#include "pg_upgrade.h"

16 17 18 19
#include <getopt_long.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
20 21 22 23 24
#ifdef WIN32
#include <io.h>
#endif


25
static void usage(void);
26
static void check_required_directory(char **dirpath, char **configpath,
27
				   char *envVarName, char *cmdLineOption, char *description);
28
#define FIX_DEFAULT_READ_ONLY "-c default_transaction_read_only=false"
29 30


31
UserOpts	user_opts;
32 33 34 35 36


/*
 * parseCommandLine()
 *
37
 *	Parses the command line (argc, argv[]) and loads structures
38 39
 */
void
40
parseCommandLine(int argc, char *argv[])
41 42 43 44 45 46
{
	static struct option long_options[] = {
		{"old-datadir", required_argument, NULL, 'd'},
		{"new-datadir", required_argument, NULL, 'D'},
		{"old-bindir", required_argument, NULL, 'b'},
		{"new-bindir", required_argument, NULL, 'B'},
47 48
		{"old-options", required_argument, NULL, 'o'},
		{"new-options", required_argument, NULL, 'O'},
49 50 51
		{"old-port", required_argument, NULL, 'p'},
		{"new-port", required_argument, NULL, 'P'},

52
		{"username", required_argument, NULL, 'U'},
53 54
		{"check", no_argument, NULL, 'c'},
		{"link", no_argument, NULL, 'k'},
55
		{"retain", no_argument, NULL, 'r'},
B
Bruce Momjian 已提交
56
		{"jobs", required_argument, NULL, 'j'},
57 58 59
		{"verbose", no_argument, NULL, 'v'},
		{NULL, 0, NULL, 0}
	};
60
	int			option;			/* Command line option */
61
	int			optindex = 0;	/* used by getopt_long */
62
	int			os_user_effective_id;
63 64
	FILE	   *fp;
	char	  **filename;
65
	time_t		run_time = time(NULL);
66

67
	user_opts.transfer_mode = TRANSFER_MODE_COPY;
68

69
	os_info.progname = get_progname(argv[0]);
70 71

	/* Process libpq env. variables; load values here for usage() output */
72 73
	old_cluster.port = getenv("PGPORTOLD") ? atoi(getenv("PGPORTOLD")) : DEF_PGUPORT;
	new_cluster.port = getenv("PGPORTNEW") ? atoi(getenv("PGPORTNEW")) : DEF_PGUPORT;
74

75 76 77 78 79 80 81 82
	os_user_effective_id = get_user_info(&os_info.user);
	/* we override just the database user name;  we got the OS id above */
	if (getenv("PGUSER"))
	{
		pg_free(os_info.user);
		/* must save value, getenv()'s pointer is not stable */
		os_info.user = pg_strdup(getenv("PGUSER"));
	}
B
Bruce Momjian 已提交
83

84 85
	if (argc > 1)
	{
B
Bruce Momjian 已提交
86
		if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
87
		{
88
			usage();
89
			exit(0);
90 91 92
		}
		if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
		{
93
			puts("pg_upgrade (PostgreSQL) " PG_VERSION);
94
			exit(0);
95 96 97
		}
	}

98 99
	/* Allow help and version to be run as root, so do the test here. */
	if (os_user_effective_id == 0)
100
		pg_fatal("%s: cannot be run as root\n", os_info.progname);
101

102
	if ((log_opts.internal = fopen_priv(INTERNAL_LOG_FILE, "a")) == NULL)
103
		pg_fatal("cannot write to log file %s\n", INTERNAL_LOG_FILE);
104

105
	while ((option = getopt_long(argc, argv, "d:D:b:B:cj:ko:O:p:P:rU:v",
106 107 108 109 110
								 long_options, &optindex)) != -1)
	{
		switch (option)
		{
			case 'b':
111
				old_cluster.bindir = pg_strdup(optarg);
112 113 114
				break;

			case 'B':
115
				new_cluster.bindir = pg_strdup(optarg);
116 117 118
				break;

			case 'c':
119
				user_opts.check = true;
120 121
				break;

122 123
			case 'd':
				old_cluster.pgdata = pg_strdup(optarg);
124
				old_cluster.pgconfig = pg_strdup(optarg);
125 126 127 128
				break;

			case 'D':
				new_cluster.pgdata = pg_strdup(optarg);
129
				new_cluster.pgconfig = pg_strdup(optarg);
130 131
				break;

B
Bruce Momjian 已提交
132 133 134 135
			case 'j':
				user_opts.jobs = atoi(optarg);
				break;

136
			case 'k':
137
				user_opts.transfer_mode = TRANSFER_MODE_LINK;
138 139
				break;

140 141 142 143 144 145 146 147
			case 'o':
				old_cluster.pgopts = pg_strdup(optarg);
				break;

			case 'O':
				new_cluster.pgopts = pg_strdup(optarg);
				break;

148 149 150 151 152
				/*
				 * Someday, the port number option could be removed and passed
				 * using -o/-O, but that requires postmaster -C to be
				 * supported on all old/new versions.
				 */
153
			case 'p':
154
				if ((old_cluster.port = atoi(optarg)) <= 0)
155
				{
156
					pg_fatal("invalid old port number\n");
157
					exit(1);
158 159 160 161
				}
				break;

			case 'P':
162
				if ((new_cluster.port = atoi(optarg)) <= 0)
163
				{
164
					pg_fatal("invalid new port number\n");
165
					exit(1);
166 167 168
				}
				break;

169 170 171 172
			case 'r':
				log_opts.retain = true;
				break;

173
			case 'U':
174 175
				pg_free(os_info.user);
				os_info.user = pg_strdup(optarg);
176
				os_info.user_specified = true;
B
Bruce Momjian 已提交
177

178 179 180 181 182
				/*
				 * Push the user name into the environment so pre-9.1
				 * pg_ctl/libpq uses it.
				 */
				pg_putenv("PGUSER", os_info.user);
183 184 185
				break;

			case 'v':
186
				pg_log(PG_REPORT, "Running in verbose mode\n");
187
				log_opts.verbose = true;
188 189 190
				break;

			default:
191
				pg_fatal("Try \"%s --help\" for more information.\n",
192
					   os_info.progname);
193 194 195 196
				break;
		}
	}

197
	/* label start of upgrade in logfiles */
198
	for (filename = output_files; *filename != NULL; filename++)
199
	{
200
		if ((fp = fopen_priv(*filename, "a")) == NULL)
201
			pg_fatal("cannot write to log file %s\n", *filename);
202 203

		/* Start with newline because we might be appending to a file. */
204 205
		fprintf(fp, "\n"
		"-----------------------------------------------------------------\n"
206 207 208
				"  pg_upgrade run on %s"
				"-----------------------------------------------------------------\n\n",
				ctime(&run_time));
209
		fclose(fp);
210 211
	}

212 213 214 215 216 217 218 219 220 221 222
	/* Turn off read-only mode;  add prefix to PGOPTIONS? */
	if (getenv("PGOPTIONS"))
	{
		char *pgoptions = psprintf("%s %s", FIX_DEFAULT_READ_ONLY,
									getenv("PGOPTIONS"));
		pg_putenv("PGOPTIONS", pgoptions);
		pfree(pgoptions);
	}
	else
		pg_putenv("PGOPTIONS", FIX_DEFAULT_READ_ONLY);

223
	/* Get values from env if not already set */
224
	check_required_directory(&old_cluster.bindir, NULL, "PGBINOLD", "-b",
225
							 "old cluster binaries reside");
226
	check_required_directory(&new_cluster.bindir, NULL, "PGBINNEW", "-B",
227
							 "new cluster binaries reside");
228 229 230 231
	check_required_directory(&old_cluster.pgdata, &old_cluster.pgconfig,
							 "PGDATAOLD", "-d", "old cluster data resides");
	check_required_directory(&new_cluster.pgdata, &new_cluster.pgconfig,
							 "PGDATANEW", "-D", "new cluster data resides");
232 233 234 235
}


static void
236
usage(void)
237
{
238 239
	printf(_("pg_upgrade upgrades a PostgreSQL cluster to a different major version.\n\
\nUsage:\n\
240
  pg_upgrade [OPTION]...\n\
241 242
\n\
Options:\n\
243 244
  -b, --old-bindir=BINDIR      old cluster executable directory\n\
  -B, --new-bindir=BINDIR       new cluster executable directory\n\
245
  -c, --check                   check clusters only, don't change any data\n\
246 247
  -d, --old-datadir=DATADIR     old cluster data directory\n\
  -D, --new-datadir=DATADIR     new cluster data directory\n\
B
Bruce Momjian 已提交
248
  -j, --jobs                    number of simultaneous processes or threads to use\n\
249
  -k, --link                    link instead of copying files to new cluster\n\
250 251
  -o, --old-options=OPTIONS     old cluster options to pass to the server\n\
  -O, --new-options=OPTIONS     new cluster options to pass to the server\n\
252 253
  -p, --old-port=PORT           old cluster port number (default %d)\n\
  -P, --new-port=PORT           new cluster port number (default %d)\n\
254
  -r, --retain                  retain SQL and log files after success\n\
255
  -U, --username=NAME           cluster superuser (default \"%s\")\n\
256
  -v, --verbose                 enable verbose internal logging\n\
257
  -V, --version                 display version information, then exit\n\
B
Bruce Momjian 已提交
258
  -?, --help                    show this help, then exit\n\
259 260 261 262 263 264 265
\n\
Before running pg_upgrade you must:\n\
  create a new database cluster (using the new version of initdb)\n\
  shutdown the postmaster servicing the old cluster\n\
  shutdown the postmaster servicing the new cluster\n\
\n\
When you run pg_upgrade, you must provide the following information:\n\
266 267 268 269
  the data directory for the old cluster  (-d DATADIR)\n\
  the data directory for the new cluster  (-D DATADIR)\n\
  the \"bin\" directory for the old version (-b BINDIR)\n\
  the \"bin\" directory for the new version (-B BINDIR)\n\
270 271 272
\n\
For example:\n\
  pg_upgrade -d oldCluster/data -D newCluster/data -b oldCluster/bin -B newCluster/bin\n\
273
or\n"), old_cluster.port, new_cluster.port, os_info.user);
274 275
#ifndef WIN32
	printf(_("\
276 277 278 279
  $ export PGDATAOLD=oldCluster/data\n\
  $ export PGDATANEW=newCluster/data\n\
  $ export PGBINOLD=oldCluster/bin\n\
  $ export PGBINNEW=newCluster/bin\n\
280 281 282
  $ pg_upgrade\n"));
#else
	printf(_("\
283 284 285 286
  C:\\> set PGDATAOLD=oldCluster/data\n\
  C:\\> set PGDATANEW=newCluster/data\n\
  C:\\> set PGBINOLD=oldCluster/bin\n\
  C:\\> set PGBINNEW=newCluster/bin\n\
287 288
  C:\\> pg_upgrade\n"));
#endif
289
	printf(_("\nReport bugs to <pgsql-bugs@postgresql.org>.\n"));
290 291 292 293
}


/*
294
 * check_required_directory()
295
 *
296
 * Checks a directory option.
297
 *	dirpath		  - the directory name supplied on the command line
298
 *	configpath	  - optional configuration directory
299 300 301 302 303 304 305 306
 *	envVarName	  - the name of an environment variable to get if dirpath is NULL
 *	cmdLineOption - the command line option corresponds to this directory (-o, -O, -n, -N)
 *	description   - a description of this directory option
 *
 * We use the last two arguments to construct a meaningful error message if the
 * user hasn't provided the required directory name.
 */
static void
307 308 309
check_required_directory(char **dirpath, char **configpath,
						 char *envVarName, char *cmdLineOption,
						 char *description)
310
{
311
	if (*dirpath == NULL || strlen(*dirpath) == 0)
312 313 314 315
	{
		const char *envVar;

		if ((envVar = getenv(envVarName)) && strlen(envVar))
316
		{
317
			*dirpath = pg_strdup(envVar);
318 319 320
			if (configpath)
				*configpath = pg_strdup(envVar);
		}
321
		else
322
			pg_fatal("You must identify the directory where the %s.\n"
323
				   "Please use the %s command-line option or the %s environment variable.\n",
324 325 326 327
				   description, cmdLineOption, envVarName);
	}

	/*
B
Bruce Momjian 已提交
328 329
	 * Trim off any trailing path separators because we construct paths by
	 * appending to this path.
330
	 */
331 332 333 334
#ifndef WIN32
	if ((*dirpath)[strlen(*dirpath) - 1] == '/')
#else
	if ((*dirpath)[strlen(*dirpath) - 1] == '/' ||
B
Bruce Momjian 已提交
335
		(*dirpath)[strlen(*dirpath) - 1] == '\\')
336
#endif
337 338
		(*dirpath)[strlen(*dirpath) - 1] = 0;
}
339 340 341 342 343 344 345 346 347 348 349 350

/*
 * adjust_data_dir
 *
 * If a configuration-only directory was specified, find the real data dir
 * by quering the running server.  This has limited checking because we
 * can't check for a running server because we can't find postmaster.pid.
 */
void
adjust_data_dir(ClusterInfo *cluster)
{
	char		filename[MAXPGPATH];
351 352 353 354
	char		cmd[MAXPGPATH],
				cmd_output[MAX_STRING];
	FILE	   *fp,
			   *output;
355 356 357

	/* If there is no postgresql.conf, it can't be a config-only dir */
	snprintf(filename, sizeof(filename), "%s/postgresql.conf", cluster->pgconfig);
358
	if ((fp = fopen(filename, "r")) == NULL)
359
		return;
360
	fclose(fp);
361 362 363

	/* If PG_VERSION exists, it can't be a config-only dir */
	snprintf(filename, sizeof(filename), "%s/PG_VERSION", cluster->pgconfig);
364
	if ((fp = fopen(filename, "r")) != NULL)
365
	{
366
		fclose(fp);
367 368 369 370 371 372 373 374 375
		return;
	}

	/* Must be a configuration directory, so find the real data directory. */

	prep_status("Finding the real data directory for the %s cluster",
				CLUSTER_NAME(cluster));

	/*
376 377 378
	 * We don't have a data directory yet, so we can't check the PG version,
	 * so this might fail --- only works for PG 9.2+.	If this fails,
	 * pg_upgrade will fail anyway because the data files will not be found.
379 380 381 382 383 384
	 */
	snprintf(cmd, sizeof(cmd), "\"%s/postmaster\" -D \"%s\" -C data_directory",
			 cluster->bindir, cluster->pgconfig);

	if ((output = popen(cmd, "r")) == NULL ||
		fgets(cmd_output, sizeof(cmd_output), output) == NULL)
385
		pg_fatal("Could not get data directory using %s: %s\n",
386
			   cmd, getErrorText(errno));
387 388 389 390 391 392 393 394 395 396 397

	pclose(output);

	/* Remove trailing newline */
	if (strchr(cmd_output, '\n') != NULL)
		*strchr(cmd_output, '\n') = '\0';

	cluster->pgdata = pg_strdup(cmd_output);

	check_ok();
}
398 399 400 401 402 403 404 405 406 407 408 409 410 411


/*
 * get_sock_dir
 *
 * Identify the socket directory to use for this cluster.  If we're doing
 * a live check (old cluster only), we need to find out where the postmaster
 * is listening.  Otherwise, we're going to put the socket into the current
 * directory.
 */
void
get_sock_dir(ClusterInfo *cluster, bool live_check)
{
#ifdef HAVE_UNIX_SOCKETS
B
Bruce Momjian 已提交
412

413
	/*
B
Bruce Momjian 已提交
414 415
	 * sockdir and port were added to postmaster.pid in PG 9.1. Pre-9.1 cannot
	 * process pg_ctl -w for sockets in non-default locations.
416 417
	 */
	if (GET_MAJOR_VERSION(cluster->major_version) >= 901)
418
	{
419
		if (!live_check)
420
		{
421 422 423
			/* Use the current directory for the socket */
			cluster->sockdir = pg_malloc(MAXPGPATH);
			if (!getcwd(cluster->sockdir, MAXPGPATH))
424
				pg_fatal("cannot find current directory\n");
425 426 427 428
		}
		else
		{
			/*
B
Bruce Momjian 已提交
429 430 431
			 * If we are doing a live check, we will use the old cluster's
			 * Unix domain socket directory so we can connect to the live
			 * server.
432 433
			 */
			unsigned short orig_port = cluster->port;
B
Bruce Momjian 已提交
434 435 436
			char		filename[MAXPGPATH],
						line[MAXPGPATH];
			FILE	   *fp;
437
			int			lineno;
B
Bruce Momjian 已提交
438

439 440 441
			snprintf(filename, sizeof(filename), "%s/postmaster.pid",
					 cluster->pgdata);
			if ((fp = fopen(filename, "r")) == NULL)
442
				pg_fatal("Cannot open file %s: %m\n", filename);
B
Bruce Momjian 已提交
443

444
			for (lineno = 1;
B
Bruce Momjian 已提交
445
			   lineno <= Max(LOCK_FILE_LINE_PORT, LOCK_FILE_LINE_SOCKET_DIR);
446 447 448
				 lineno++)
			{
				if (fgets(line, sizeof(line), fp) == NULL)
449
					pg_fatal("Cannot read line %d from %s: %m\n", lineno, filename);
B
Bruce Momjian 已提交
450

451 452 453 454 455 456 457 458 459 460
				/* potentially overwrite user-supplied value */
				if (lineno == LOCK_FILE_LINE_PORT)
					sscanf(line, "%hu", &old_cluster.port);
				if (lineno == LOCK_FILE_LINE_SOCKET_DIR)
				{
					cluster->sockdir = pg_malloc(MAXPGPATH);
					/* strip off newline */
					sscanf(line, "%s\n", cluster->sockdir);
				}
			}
461
			fclose(fp);
B
Bruce Momjian 已提交
462

463 464 465
			/* warn of port number correction */
			if (orig_port != DEF_PGUPORT && old_cluster.port != orig_port)
				pg_log(PG_WARNING, "User-supplied old port number %hu corrected to %hu\n",
B
Bruce Momjian 已提交
466
					   orig_port, cluster->port);
467 468
		}
	}
469 470
	else

B
Bruce Momjian 已提交
471 472 473 474 475 476
		/*
		 * Can't get sockdir and pg_ctl -w can't use a non-default, use
		 * default
		 */
		cluster->sockdir = NULL;
#else							/* !HAVE_UNIX_SOCKETS */
477 478 479
	cluster->sockdir = NULL;
#endif
}