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

10 11 12
#include "postgres_fe.h"

#include "miscadmin.h"
13
#include "getopt_long.h"
14

15
#include "pg_upgrade.h"
16
#include "greenplum/pg_upgrade_greenplum.h"
17

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


25
static void usage(void);
26 27 28
static void check_required_directory(char **dirpath,
						 const char *envVarName, bool useCwd,
						 const char *cmdLineOption, const char *description);
29
#define FIX_DEFAULT_READ_ONLY "-c default_transaction_read_only=false"
A
Adam Berlin 已提交
30
#define GP_DBID_NOT_SET -1
31

32
UserOpts	user_opts;
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 56
		{"retain", no_argument, NULL, 'r'},
		{"jobs", required_argument, NULL, 'j'},
57
		{"socketdir", required_argument, NULL, 's'},
58
		{"verbose", no_argument, NULL, 'v'},
59 60

		/* Greenplum specific parameters */
61
		{"mode", required_argument, NULL, 1},
62 63 64
		{"progress", no_argument, NULL, 2},
		{"add-checksum", no_argument, NULL, 3},
		{"remove-checksum", no_argument, NULL, 4},
A
Adam Berlin 已提交
65 66 67
		{"old-gp-dbid", required_argument, NULL, 5},
		{"new-gp-dbid", required_argument, NULL, 6},
		{"old-tablespaces-file", required_argument, NULL, 7},
68

69 70 71 72
		{NULL, 0, NULL, 0}
	};
	int			option;			/* Command line option */
	int			optindex = 0;	/* used by getopt_long */
73
	int			os_user_effective_id;
74 75 76
	FILE	   *fp;
	char	  **filename;
	time_t		run_time = time(NULL);
77

78
	user_opts.transfer_mode = TRANSFER_MODE_COPY;
A
Adam Berlin 已提交
79
	user_opts.old_tablespace_file_path = NULL;
80

A
Adam Berlin 已提交
81 82 83
	old_cluster.gp_dbid = GP_DBID_NOT_SET;
	new_cluster.gp_dbid = GP_DBID_NOT_SET;
	old_cluster.old_tablespace_file_contents = NULL;
84

85
	os_info.progname = get_progname(argv[0]);
86

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

91
	os_user_effective_id = get_user_info(&os_info.user);
92

93
	greenplum_user_opts.segment_mode = SEGMENT;
94

95 96 97 98 99 100 101
	/* 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"));
	}
102 103 104

	if (argc > 1)
	{
B
Bruce Momjian 已提交
105
		if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-?") == 0)
106
		{
107
			usage();
108
			exit(0);
109 110 111
		}
		if (strcmp(argv[1], "--version") == 0 || strcmp(argv[1], "-V") == 0)
		{
112
			puts("pg_upgrade (PostgreSQL) " PG_VERSION);
113
			exit(0);
114 115 116
		}
	}

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

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

124
	while ((option = getopt_long(argc, argv, "d:D:b:B:cj:ko:O:p:P:rs:U:v",
125 126 127 128
								 long_options, &optindex)) != -1)
	{
		switch (option)
		{
129
			case 'b':
130
				old_cluster.bindir = pg_strdup(optarg);
131 132
				break;

133
			case 'B':
134
				new_cluster.bindir = pg_strdup(optarg);
135 136
				break;

137
			case 'c':
138
				user_opts.check = true;
139 140
				break;

141 142
			case 'd':
				old_cluster.pgdata = pg_strdup(optarg);
143 144
				break;

145 146
			case 'D':
				new_cluster.pgdata = pg_strdup(optarg);
147 148
				break;

149
			case 'j':
150
				user_opts.jobs = atoi(optarg);
151 152
				break;

153
			case 'k':
154
				user_opts.transfer_mode = TRANSFER_MODE_LINK;
155 156
				break;

157 158
			case 'o':
				old_cluster.pgopts = pg_strdup(optarg);
159 160
				break;

161 162 163 164 165 166 167 168 169
			case 'O':
				new_cluster.pgopts = pg_strdup(optarg);
				break;

				/*
				 * 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.
				 */
170
			case 'p':
171
				if ((old_cluster.port = atoi(optarg)) <= 0)
172
				{
173
					pg_fatal("invalid old port number\n");
174
					exit(1);
175 176 177 178
				}
				break;

			case 'P':
179
				if ((new_cluster.port = atoi(optarg)) <= 0)
180
				{
181
					pg_fatal("invalid new port number\n");
182
					exit(1);
183 184 185
				}
				break;

186 187 188 189
			case 'r':
				log_opts.retain = true;
				break;

190 191 192 193
			case 's':
				user_opts.socketdir = pg_strdup(optarg);
				break;

194
			case 'U':
195 196
				pg_free(os_info.user);
				os_info.user = pg_strdup(optarg);
197
				os_info.user_specified = true;
B
Bruce Momjian 已提交
198

199 200 201 202 203
				/*
				 * Push the user name into the environment so pre-9.1
				 * pg_ctl/libpq uses it.
				 */
				pg_putenv("PGUSER", os_info.user);
204 205 206
				break;

			case 'v':
207
				pg_log(PG_REPORT, "Running in verbose mode\n");
208
				log_opts.verbose = true;
209 210
				break;

211 212 213 214
			/*
			 * Greenplum specific parameters
			 */

215 216
			case 1:		/* --mode={dispatcher|segment} */
				if (pg_strcasecmp("dispatcher", optarg) == 0)
217
					greenplum_user_opts.segment_mode = DISPATCHER;
218
				else if (pg_strcasecmp("segment", optarg) == 0)
219
					greenplum_user_opts.segment_mode = SEGMENT;
220 221 222 223 224 225
				else
				{
					pg_log(PG_FATAL, "invalid segment configuration\n");
					exit(1);
				}

226 227 228
				break;

			case 2:		/* --progress */
229
				greenplum_user_opts.progress = true;
230 231 232
				break;

			case 3:		/* --add-checksum */
233
				greenplum_user_opts.checksum_mode = CHECKSUM_ADD;
234 235 236
				break;

			case 4:		/* --remove-checksum */
237
				greenplum_user_opts.checksum_mode = CHECKSUM_REMOVE;
238
				break;
A
Adam Berlin 已提交
239 240 241 242 243 244 245 246 247 248 249 250
				
			case 5: /* --old-gp-dbid */
				old_cluster.gp_dbid = atoi(optarg);
				break;

			case 6: /* --new-gp-dbid */
				new_cluster.gp_dbid = atoi(optarg);
				break;

			case 7: /* --old-tablespaces-file */
				user_opts.old_tablespace_file_path = pg_strdup(optarg);
				break;
251

252
			default:
253
				pg_fatal("Try \"%s --help\" for more information.\n",
B
Bruce Momjian 已提交
254
						 os_info.progname);
255 256 257 258
				break;
		}
	}

259 260
	/* label start of upgrade in logfiles */
	for (filename = output_files; *filename != NULL; filename++)
261
	{
262
		if ((fp = fopen_priv(*filename, "a")) == NULL)
263
			pg_fatal("cannot write to log file %s\n", *filename);
264 265 266 267 268 269 270 271

		/* Start with newline because we might be appending to a file. */
		fprintf(fp, "\n"
		"-----------------------------------------------------------------\n"
				"  pg_upgrade run on %s"
				"-----------------------------------------------------------------\n\n",
				ctime(&run_time));
		fclose(fp);
272 273
	}

274 275 276
	/* Turn off read-only mode;  add prefix to PGOPTIONS? */
	if (getenv("PGOPTIONS"))
	{
B
Bruce Momjian 已提交
277 278 279
		char	   *pgoptions = psprintf("%s %s", FIX_DEFAULT_READ_ONLY,
										 getenv("PGOPTIONS"));

280 281 282 283 284 285
		pg_putenv("PGOPTIONS", pgoptions);
		pfree(pgoptions);
	}
	else
		pg_putenv("PGOPTIONS", FIX_DEFAULT_READ_ONLY);

286
	/* Get values from env if not already set */
287 288 289 290 291 292 293 294 295 296
	check_required_directory(&old_cluster.bindir, "PGBINOLD", false,
							 "-b", "old cluster binaries reside");
	check_required_directory(&new_cluster.bindir, "PGBINNEW", false,
							 "-B", "new cluster binaries reside");
	check_required_directory(&old_cluster.pgdata, "PGDATAOLD", false,
							 "-d", "old cluster data resides");
	check_required_directory(&new_cluster.pgdata, "PGDATANEW", false,
							 "-D", "new cluster data resides");
	check_required_directory(&user_opts.socketdir, "PGSOCKETDIR", true,
							 "-s", "sockets will be created");
297 298 299

	/* Ensure we are only adding checksums in copy mode */
	if (user_opts.transfer_mode != TRANSFER_MODE_COPY &&
300
		greenplum_user_opts.checksum_mode != CHECKSUM_NONE)
301
		pg_log(PG_FATAL, "Adding and removing checksums only supported in copy mode.\n");
A
Adam Berlin 已提交
302 303

	if (old_cluster.gp_dbid == GP_DBID_NOT_SET)
304
		pg_fatal("--old-gp-dbid must be set\n");
A
Adam Berlin 已提交
305 306

	if (new_cluster.gp_dbid == GP_DBID_NOT_SET)
307
		pg_fatal("--new-gp-dbid must be set\n");
A
Adam Berlin 已提交
308 309 310 311 312 313

	if (user_opts.old_tablespace_file_path) {
		populate_old_cluster_with_old_tablespaces(
			&old_cluster,
			user_opts.old_tablespace_file_path);
	}
314 315 316 317
}


static void
318
usage(void)
319
{
320
	printf(_("pg_upgrade upgrades a Greenplum cluster to a different major version.\n\
321
\nUsage:\n\
322
  pg_upgrade [OPTION]...\n\
323 324
\n\
Options:\n\
325
  -b, --old-bindir=BINDIR       old cluster executable directory\n\
326
  -B, --new-bindir=BINDIR       new cluster executable directory\n\
327
  -c, --check                   check clusters only, don't change any data\n\
328 329
  -d, --old-datadir=DATADIR     old cluster data directory\n\
  -D, --new-datadir=DATADIR     new cluster data directory\n\
330
  -j, --jobs                    number of simultaneous processes or threads to use\n\
331
  -k, --link                    link instead of copying files to new cluster\n\
332 333
  -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\
334 335
  -p, --old-port=PORT           old cluster port number (default %d)\n\
  -P, --new-port=PORT           new cluster port number (default %d)\n\
336
  -r, --retain                  retain SQL and log files after success\n\
337
  -s, --socketdir=DIR           socket directory to use (default CWD)\n\
338
  -U, --username=NAME           cluster superuser (default \"%s\")\n\
339
  -v, --verbose                 enable verbose internal logging\n\
340
  -V, --version                 display version information, then exit\n\
341
      --mode=TYPE               designate node type to upgrade, \"segment\" or \"dispatcher\" (default \"segment\")\n\
342 343 344
      --progress                enable progress reporting\n\
      --remove-checksum         remove data checksums when creating new cluster\n\
      --add-checksum            add data checksumming to the new cluster\n\
A
Adam Berlin 已提交
345 346 347
      --old-gp-dbid             greenplum database id of the old segment\n\
      --new-gp-dbid             greenplum database id of the new segment\n\
      --old-tablespaces-file    file containing the tablespaces from an old gpdb five cluster\n\
B
Bruce Momjian 已提交
348
  -?, --help                    show this help, then exit\n\
349 350 351 352 353 354 355
\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\
356 357 358 359
  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\
360 361 362
\n\
For example:\n\
  pg_upgrade -d oldCluster/data -D newCluster/data -b oldCluster/bin -B newCluster/bin\n\
363
or\n"), old_cluster.port, new_cluster.port, os_info.user);
364 365
#ifndef WIN32
	printf(_("\
366 367 368 369
  $ export PGDATAOLD=oldCluster/data\n\
  $ export PGDATANEW=newCluster/data\n\
  $ export PGBINOLD=oldCluster/bin\n\
  $ export PGBINNEW=newCluster/bin\n\
370 371 372
  $ pg_upgrade\n"));
#else
	printf(_("\
373 374 375 376
  C:\\> set PGDATAOLD=oldCluster/data\n\
  C:\\> set PGDATANEW=newCluster/data\n\
  C:\\> set PGBINOLD=oldCluster/bin\n\
  C:\\> set PGBINNEW=newCluster/bin\n\
377 378
  C:\\> pg_upgrade\n"));
#endif
379
	printf(_("\nReport bugs to <bugs@greenplum.org>.\n"));
380 381 382 383
}


/*
384
 * check_required_directory()
385
 *
386
 * Checks a directory option.
387
 *	dirpath		  - the directory name supplied on the command line, or NULL
388
 *	envVarName	  - the name of an environment variable to get if dirpath is NULL
389 390
 *	useCwd		  - true if OK to default to CWD
 *	cmdLineOption - the command line option for this directory
391 392 393 394 395 396
 *	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
397 398
check_required_directory(char **dirpath, const char *envVarName, bool useCwd,
						 const char *cmdLineOption, const char *description)
399
{
400
	if (*dirpath == NULL || strlen(*dirpath) == 0)
401 402 403 404
	{
		const char *envVar;

		if ((envVar = getenv(envVarName)) && strlen(envVar))
405
			*dirpath = pg_strdup(envVar);
406 407 408 409 410 411 412
		else if (useCwd)
		{
			char		cwd[MAXPGPATH];

			if (!getcwd(cwd, MAXPGPATH))
				pg_fatal("could not determine current directory\n");
			*dirpath = pg_strdup(cwd);
413
		}
414
		else
415
			pg_fatal("You must identify the directory where the %s.\n"
B
Bruce Momjian 已提交
416 417
					 "Please use the %s command-line option or the %s environment variable.\n",
					 description, cmdLineOption, envVarName);
418 419 420
	}

	/*
421 422
	 * Clean up the path, in particular trimming any trailing path separators,
	 * because we construct paths by appending to this path.
423
	 */
424
	canonicalize_path(*dirpath);
425 426
}

427 428 429 430 431 432
/*
 * 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.
433 434 435 436
 *
 * On entry, cluster->pgdata has been set from command line or env variable,
 * but cluster->pgconfig isn't set.  We fill both variables with corrected
 * values.
437 438 439
 */
void
adjust_data_dir(ClusterInfo *cluster)
440
{
441 442 443 444 445 446
	char		filename[MAXPGPATH];
	char		cmd[MAXPGPATH],
				cmd_output[MAX_STRING];
	FILE	   *fp,
			   *output;

447 448 449
	/* Initially assume config dir and data dir are the same */
	cluster->pgconfig = pg_strdup(cluster->pgdata);

450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468
	/* If there is no postgresql.conf, it can't be a config-only dir */
	snprintf(filename, sizeof(filename), "%s/postgresql.conf", cluster->pgconfig);
	if ((fp = fopen(filename, "r")) == NULL)
		return;
	fclose(fp);

	/* If PG_VERSION exists, it can't be a config-only dir */
	snprintf(filename, sizeof(filename), "%s/PG_VERSION", cluster->pgconfig);
	if ((fp = fopen(filename, "r")) != NULL)
	{
		fclose(fp);
		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));

469
	/*
470 471 472
	 * 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.
473
	 */
474 475
	snprintf(cmd, sizeof(cmd), "\"%s/postmaster\" -D \"%s\" -C data_directory",
			 cluster->bindir, cluster->pgconfig);
476

477 478
	if ((output = popen(cmd, "r")) == NULL ||
		fgets(cmd_output, sizeof(cmd_output), output) == NULL)
479
		pg_fatal("Could not get data directory using %s: %s\n",
480
				 cmd, getErrorText());
481

482
	pclose(output);
483

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

488
	cluster->pgdata = pg_strdup(cmd_output);
489

490 491
	check_ok();
}
492 493


494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
/*
 * 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

	/*
	 * 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.
	 */
	if (GET_MAJOR_VERSION(cluster->major_version) >= 901)
	{
		if (!live_check)
514
			cluster->sockdir = user_opts.socketdir;
515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
		else
		{
			/*
			 * 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.
			 */
			unsigned short orig_port = cluster->port;
			char		filename[MAXPGPATH],
						line[MAXPGPATH];
			FILE	   *fp;
			int			lineno;

			snprintf(filename, sizeof(filename), "%s/postmaster.pid",
					 cluster->pgdata);
			if ((fp = fopen(filename, "r")) == NULL)
531
				pg_fatal("Cannot open file %s: %m\n", filename);
532 533 534 535 536 537

			for (lineno = 1;
			   lineno <= Max(LOCK_FILE_LINE_PORT, LOCK_FILE_LINE_SOCKET_DIR);
				 lineno++)
			{
				if (fgets(line, sizeof(line), fp) == NULL)
538
					pg_fatal("Cannot read line %d from %s: %m\n", lineno, filename);
539 540 541 542 543 544

				/* potentially overwrite user-supplied value */
				if (lineno == LOCK_FILE_LINE_PORT)
					sscanf(line, "%hu", &old_cluster.port);
				if (lineno == LOCK_FILE_LINE_SOCKET_DIR)
				{
545
					cluster->sockdir = pg_strdup(line);
546
					/* strip off newline */
547 548
					if (strchr(cluster->sockdir, '\n') != NULL)
						*strchr(cluster->sockdir, '\n') = '\0';
549 550 551
				}
			}
			fclose(fp);
552

553 554 555 556 557 558 559
			/* 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",
					   orig_port, cluster->port);
		}
	}
	else
560

561 562 563 564 565 566 567 568
		/*
		 * Can't get sockdir and pg_ctl -w can't use a non-default, use
		 * default
		 */
		cluster->sockdir = NULL;
#else							/* !HAVE_UNIX_SOCKETS */
	cluster->sockdir = NULL;
#endif
569
}