1
0
mirror of https://github.com/postgres/postgres.git synced 2025-11-16 15:02:33 +03:00

Fixed everything in and surrounding createdb and dropdb to make it more

error-proof. Rearranged some old code and removed dead sections.
This commit is contained in:
Peter Eisentraut
2000-01-13 18:26:18 +00:00
parent bfa3b59d25
commit 46a28f1b14
14 changed files with 473 additions and 842 deletions

View File

@@ -7,10 +7,12 @@
*
*
* IDENTIFICATION
* $Header: /cvsroot/pgsql/src/backend/utils/init/miscinit.c,v 1.38 2000/01/09 12:15:57 ishii Exp $
* $Header: /cvsroot/pgsql/src/backend/utils/init/miscinit.c,v 1.39 2000/01/13 18:26:11 petere Exp $
*
*-------------------------------------------------------------------------
*/
#include "postgres.h"
#include <sys/param.h>
#include <sys/types.h>
#include <signal.h>
@@ -19,177 +21,21 @@
#include <unistd.h>
#include <grp.h>
#include <pwd.h>
#include <stdlib.h>
#include "postgres.h"
#include "catalog/catname.h"
#include "catalog/pg_shadow.h"
#include "miscadmin.h"
#include "utils/syscache.h"
/*
* EnableAbortEnvVarName
* Enables system abort iff set to a non-empty string in environment.
*/
#define EnableAbortEnvVarName "POSTGRESABORT"
extern char *getenv(const char *name); /* XXX STDLIB */
/* from globals.c */
extern char *UserName;
#ifdef CYR_RECODE
unsigned char RecodeForwTable[128];
unsigned char RecodeBackTable[128];
#endif
ProcessingMode Mode = InitProcessing;
/*
* Define USE_ENVIRONMENT to get PGDATA, etc. from environment variables.
* This is the default on UNIX platforms.
*/
#define USE_ENVIRONMENT
/* ----------------------------------------------------------------
* some of the 19 ways to leave postgres
* ----------------------------------------------------------------
*/
/*
* ExitPostgres
* Exit POSTGRES with a status code.
*
* Note:
* This function never returns.
* ...
*
* Side effects:
* ...
*
* Exceptions:
* none
*/
void
ExitPostgres(ExitStatus status)
{
proc_exit(status);
}
/*
* AbortPostgres
* Abort POSTGRES dumping core.
*
* Note:
* This function never returns.
* ...
*
* Side effects:
* Core is dumped iff EnableAbortEnvVarName is set to a non-empty string.
* ...
*
* Exceptions:
* none
*/
#ifdef NOT_USED
void
AbortPostgres()
{
char *abortValue = getenv(EnableAbortEnvVarName);
if (PointerIsValid(abortValue) && abortValue[0] != '\0')
abort();
else
proc_exit(FatalExitStatus);
}
/* ----------------
* StatusBackendExit
* ----------------
*/
void
StatusBackendExit(int status)
{
/* someday, do some real cleanup and then call the LISP exit */
/* someday, call StatusPostmasterExit if running without postmaster */
proc_exit(status);
}
/* ----------------
* StatusPostmasterExit
* ----------------
*/
void
StatusPostmasterExit(int status)
{
/* someday, do some real cleanup and then call the LISP exit */
proc_exit(status);
}
#endif
/* ----------------------------------------------------------------
* processing mode support stuff (used to be in pmod.c)
* ----------------------------------------------------------------
*/
static ProcessingMode Mode = InitProcessing;
/*
* IsBootstrapProcessingMode
* True iff processing mode is BootstrapProcessing.
*/
bool
IsBootstrapProcessingMode()
{
return (bool) (Mode == BootstrapProcessing);
}
/*
* IsInitProcessingMode
* True iff processing mode is InitProcessing.
*/
bool
IsInitProcessingMode()
{
return (bool) (Mode == InitProcessing);
}
/*
* IsNormalProcessingMode
* True iff processing mode is NormalProcessing.
*/
bool
IsNormalProcessingMode()
{
return (bool) (Mode == NormalProcessing);
}
/*
* SetProcessingMode
* Sets mode of processing as specified.
*
* Exceptions:
* BadArg if called with invalid mode.
*
* Note:
* Mode is InitProcessing before the first time this is called.
*/
void
SetProcessingMode(ProcessingMode mode)
{
AssertArg(mode == BootstrapProcessing || mode == InitProcessing ||
mode == NormalProcessing);
Mode = mode;
}
ProcessingMode
GetProcessingMode()
{
return Mode;
}
/* ----------------------------------------------------------------
* database path / name support stuff
@@ -197,22 +43,26 @@ GetProcessingMode()
*/
void
SetDatabasePath(char *path)
SetDatabasePath(const char *path)
{
/* use malloc since this is done before memory contexts are set up */
if (DatabasePath)
free(DatabasePath);
DatabasePath = malloc(strlen(path) + 1);
strcpy(DatabasePath, path);
free(DatabasePath);
/* use strdup since this is done before memory contexts are set up */
if (path)
{
DatabasePath = strdup(path);
AssertState(DatabasePath);
}
}
void
SetDatabaseName(char *name)
SetDatabaseName(const char *name)
{
if (DatabaseName)
free(DatabaseName);
DatabaseName = malloc(strlen(name) + 1);
strcpy(DatabaseName, name);
free(DatabaseName);
if (name)
{
DatabaseName = strdup(name);
AssertState(DatabaseName);
}
}
#ifndef MULTIBYTE
@@ -431,7 +281,7 @@ static Oid UserId = InvalidOid;
int
GetUserId()
{
Assert(OidIsValid(UserId));
AssertState(OidIsValid(UserId));
return UserId;
}
@@ -441,7 +291,7 @@ SetUserId()
HeapTuple userTup;
char *userName;
Assert(!OidIsValid(UserId));/* only once */
AssertState(!OidIsValid(UserId));/* only once */
/*
* Don't do scans if we're bootstrapping, none of the system catalogs

View File

@@ -7,22 +7,8 @@
*
*
* IDENTIFICATION
* $Header: /cvsroot/pgsql/src/backend/utils/init/postinit.c,v 1.54 1999/12/22 00:07:16 inoue Exp $
* $Header: /cvsroot/pgsql/src/backend/utils/init/postinit.c,v 1.55 2000/01/13 18:26:11 petere Exp $
*
* NOTES
* InitPostgres() is the function called from PostgresMain
* which does all non-trival initialization, mainly by calling
* all the other initialization functions. InitPostgres()
* is only used within the "postgres" backend and so that routine
* is in tcop/postgres.c InitPostgres() is needed in cinterface.a
* because things like the bootstrap backend program need it. Hence
* you find that in this file...
*
* If you feel the need to add more initialization code, it should be
* done in InitPostgres() or someplace lower. Do not start
* putting stuff in PostgresMain - if you do then someone
* will have to clean it up later, and it's not going to be me!
* -cim 10/3/90
*
*-------------------------------------------------------------------------
*/
@@ -55,193 +41,13 @@
void BaseInit(void);
static void VerifySystemDatabase(void);
static void VerifyMyDatabase(void);
static void ReverifyMyDatabase(char *name);
static void ReverifyMyDatabase(const char *name);
static void InitCommunication(void);
static void InitMyDatabaseInfo(char *name);
static void InitUserid(void);
static IPCKey PostgresIpcKey;
/* ----------------------------------------------------------------
* InitPostgres support
* ----------------------------------------------------------------
*/
/*** InitPostgres support ***/
/* --------------------------------
* InitMyDatabaseInfo() -- Find and record the OID of the database we are
* to open.
*
* The database's oid forms half of the unique key for the system
* caches and lock tables. We therefore want it initialized before
* we open any relations, since opening relations puts things in the
* cache. To get around this problem, this code opens and scans the
* pg_database relation by hand.
*
* This algorithm relies on the fact that first attribute in the
* pg_database relation schema is the database name. It also knows
* about the internal format of tuples on disk and the length of
* the datname attribute. It knows the location of the pg_database
* file.
* Actually, the code looks as though it is using the pg_database
* tuple definition to locate the database name, so the above statement
* seems to be no longer correct. - thomas 1997-11-01
*
* This code is called from InitPostgres(), before we chdir() to the
* local database directory and before we open any relations.
* Used to be called after the chdir(), but we now want to confirm
* the location of the target database using pg_database info.
* - thomas 1997-11-01
* --------------------------------
*/
static void
InitMyDatabaseInfo(char *name)
{
char *path,
myPath[MAXPGPATH];
SetDatabaseName(name);
GetRawDatabaseInfo(name, &MyDatabaseId, myPath);
if (!OidIsValid(MyDatabaseId))
elog(FATAL,
"Database %s does not exist in %s",
DatabaseName,
DatabaseRelationName);
path = ExpandDatabasePath(myPath);
SetDatabasePath(path);
} /* InitMyDatabaseInfo() */
/*
* DoChdirAndInitDatabaseNameAndPath
* Set current directory to the database directory for the database
* named <name>.
* Also set global variables DatabasePath and DatabaseName to those
* values. Also check for proper version of database system and
* database. Exit program via elog() if anything doesn't check out.
*
* Arguments:
* Path and name are invalid if it invalid as a string.
* Path is "badly formatted" if it is not a string containing a path
* to a writable directory.
* Name is "badly formatted" if it contains more than 16 characters or if
* it is a bad file name (e.g., it contains a '/' or an 8-bit character).
*
* Exceptions:
* BadState if called more than once.
* BadArg if both path and name are "badly formatted" or invalid.
* BadArg if path and name are both "inconsistent" and valid.
*
* This routine is inappropriate in bootstrap mode, since the directories
* and version files need not exist yet if we're in bootstrap mode.
*/
static void
VerifySystemDatabase()
{
char *reason;
/* Failure reason returned by some function. NULL if no failure */
int fd;
char errormsg[MAXPGPATH+100];
errormsg[0] = '\0';
#ifndef __CYGWIN32__
if ((fd = open(DataDir, O_RDONLY, 0)) == -1)
#else
if ((fd = open(DataDir, O_RDONLY | O_DIROPEN, 0)) == -1)
#endif
snprintf(errormsg, sizeof(errormsg),
"Database system does not exist. "
"PGDATA directory '%s' not found.\n\tNormally, you "
"create a database system by running initdb.",
DataDir);
else
{
close(fd);
ValidatePgVersion(DataDir, &reason);
if (reason != NULL)
snprintf(errormsg, sizeof(errormsg),
"InitPostgres could not validate that the database"
" system version is compatible with this level of"
" Postgres.\n\tYou may need to run initdb to create"
" a new database system.\n\t%s", reason);
}
if (errormsg[0] != '\0')
elog(FATAL, errormsg);
/* Above does not return */
} /* VerifySystemDatabase() */
static void
VerifyMyDatabase()
{
const char *name;
const char *myPath;
/* Failure reason returned by some function. NULL if no failure */
char *reason;
int fd;
char errormsg[MAXPGPATH+100];
name = DatabaseName;
myPath = DatabasePath;
#ifndef __CYGWIN32__
if ((fd = open(myPath, O_RDONLY, 0)) == -1)
#else
if ((fd = open(myPath, O_RDONLY | O_DIROPEN, 0)) == -1)
#endif
snprintf(errormsg, sizeof(errormsg),
"Database '%s' does not exist."
"\n\tWe know this because the directory '%s' does not exist."
"\n\tYou can create a database with the SQL command"
" CREATE DATABASE.\n\tTo see what databases exist,"
" look at the subdirectories of '%s/base/'.",
name, myPath, DataDir);
else
{
close(fd);
ValidatePgVersion(myPath, &reason);
if (reason != NULL)
snprintf(errormsg, sizeof(errormsg),
"InitPostgres could not validate that the database"
" version is compatible with this level of Postgres"
"\n\teven though the database system as a whole"
" appears to be at a compatible level."
"\n\tYou may need to recreate the database with SQL"
" commands DROP DATABASE and CREATE DATABASE."
"\n\t%s", reason);
else
{
/*
* The directories and PG_VERSION files are in order.
*/
int rc; /* return code from some function we call */
#ifdef FILEDEBUG
printf("Try changing directory for database %s to %s\n", name, myPath);
#endif
rc = chdir(myPath);
if (rc < 0)
snprintf(errormsg, sizeof(errormsg),
"InitPostgres unable to change "
"current directory to '%s', errno = %s (%d).",
myPath, strerror(errno), errno);
else
errormsg[0] = '\0';
}
}
if (errormsg[0] != '\0')
elog(FATAL, errormsg);
/* Above does not return */
} /* VerifyMyDatabase() */
/* --------------------------------
* ReverifyMyDatabase
@@ -266,7 +72,7 @@ VerifyMyDatabase()
* --------------------------------
*/
static void
ReverifyMyDatabase(char *name)
ReverifyMyDatabase(const char *name)
{
Relation pgdbrel;
HeapScanDesc pgdbscan;
@@ -324,18 +130,7 @@ ReverifyMyDatabase(char *name)
heap_close(pgdbrel, AccessShareLock);
}
/* --------------------------------
* InitUserid
*
* initializes crap associated with the user id.
* --------------------------------
*/
static void
InitUserid()
{
setuid(geteuid());
SetUserId();
}
/* --------------------------------
* InitCommunication
@@ -416,6 +211,8 @@ InitCommunication()
}
}
/* --------------------------------
* InitPostgres
* Initialize POSTGRES.
@@ -431,14 +228,9 @@ int lockingOff = 0; /* backend -L switch */
/*
*/
void
InitPostgres(char *name) /* database name */
InitPostgres(const char *dbname)
{
bool bootstrap; /* true if BootstrapProcessing */
/*
* See if we're running in BootstrapProcessing mode
*/
bootstrap = IsBootstrapProcessingMode();
bool bootstrap = IsBootstrapProcessingMode();
/* ----------------
* initialize the backend local portal stack used by
@@ -449,9 +241,7 @@ InitPostgres(char *name) /* database name */
*/
be_portalinit();
/*
* initialize the local buffer manager
*/
/* initialize the local buffer manager */
InitLocalBuffer();
#ifndef XLOG
@@ -459,32 +249,72 @@ InitPostgres(char *name) /* database name */
on_shmem_exit(FlushBufferPool, (caddr_t) NULL);
#endif
SetDatabaseName(dbname);
/* ----------------
* initialize the database id used for system caches and lock tables
* ----------------
*/
if (bootstrap)
{
SetDatabasePath(ExpandDatabasePath(name));
SetDatabaseName(name);
SetDatabasePath(ExpandDatabasePath(dbname));
LockDisable(true);
}
else
{
VerifySystemDatabase();
InitMyDatabaseInfo(name);
VerifyMyDatabase();
char *reason;
char *fullpath,
datpath[MAXPGPATH];
/* Verify if DataDir is ok */
if (access(DataDir, F_OK) == -1)
elog(FATAL, "Database system not found. Data directory '%s' does not exist.",
DataDir);
ValidatePgVersion(DataDir, &reason);
if (reason != NULL)
elog(FATAL, reason);
/*-----------------
* Find oid and path of the database we're about to open. Since we're
* not yet up and running we have to use the hackish GetRawDatabaseInfo.
*
* OLD COMMENTS:
* The database's oid forms half of the unique key for the system
* caches and lock tables. We therefore want it initialized before
* we open any relations, since opening relations puts things in the
* cache. To get around this problem, this code opens and scans the
* pg_database relation by hand.
*/
GetRawDatabaseInfo(dbname, &MyDatabaseId, datpath);
if (!OidIsValid(MyDatabaseId))
elog(FATAL,
"Database \"%s\" does not exist in the system catalog.",
dbname);
fullpath = ExpandDatabasePath(datpath);
if (!fullpath)
elog(FATAL, "Database path could not be resolved.");
/* Verify the database path */
if (access(fullpath, F_OK) == -1)
elog(FATAL, "Database \"%s\" does not exist. The data directory '%s' is missing.",
dbname, fullpath);
ValidatePgVersion(fullpath, &reason);
if (reason != NULL)
elog(FATAL, "%s", reason);
if(chdir(fullpath) == -1)
elog(FATAL, "Unable to change directory to '%s': %s", fullpath, strerror(errno));
SetDatabasePath(fullpath);
}
/*
* Code after this point assumes we are in the proper directory!
*
* So, how do we implement alternate locations for databases? There are
* two possible locations for tables and we need to look in
* DataDir/pg_database to find the true location of an individual
* database. We can brute-force it as done in InitMyDatabaseInfo(), or
* we can be patient and wait until we open pg_database gracefully.
* Will try that, but may not work... - thomas 1997-11-01
*/
/*
@@ -549,12 +379,14 @@ InitPostgres(char *name) /* database name */
/* start a new transaction here before access to db */
if (!bootstrap)
StartTransactionCommand();
/*
* Set ourselves to the proper user id and figure out our postgres
* user id. If we ever add security so that we check for valid
* postgres users, we might do it here.
*/
InitUserid();
setuid(geteuid());
SetUserId();
if (lockingOff)
LockDisable(true);
@@ -565,7 +397,7 @@ InitPostgres(char *name) /* database name */
* infrastructure is up, so just do it at the end.
*/
if (!bootstrap)
ReverifyMyDatabase(name);
ReverifyMyDatabase(dbname);
}
void

View File

@@ -7,100 +7,43 @@
*
*
* IDENTIFICATION
* $Header: /cvsroot/pgsql/src/backend/utils/misc/Attic/database.c,v 1.33 1999/12/16 22:19:55 wieck Exp $
* $Header: /cvsroot/pgsql/src/backend/utils/misc/Attic/database.c,v 1.34 2000/01/13 18:26:13 petere Exp $
*
*-------------------------------------------------------------------------
*/
#include <unistd.h>
#include <fcntl.h>
#include "postgres.h"
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "access/xact.h"
#include "catalog/catname.h"
#include "catalog/pg_database.h"
#include "miscadmin.h"
#include "utils/syscache.h"
#ifdef NOT_USED
/* GetDatabaseInfo()
* Pull database information from pg_database.
/*
* ExpandDatabasePath resolves a proposed database path (obtained from
* pg_database.datpath) to a full absolute path for further consumption.
* NULL means an error, which the caller should process. One reason for
* such an error would be an absolute alternative path when no absolute
* paths are alllowed.
*/
int
GetDatabaseInfo(char *name, int4 *owner, char *path)
{
Oid dbowner,
dbid;
char dbpath[MAXPGPATH];
text *dbtext;
Relation dbrel;
HeapTuple dbtup;
HeapTuple tup;
HeapScanDesc scan;
ScanKeyData scanKey;
dbrel = heap_openr(DatabaseRelationName, AccessShareLock);
ScanKeyEntryInitialize(&scanKey, 0, Anum_pg_database_datname,
F_NAMEEQ, NameGetDatum(name));
scan = heap_beginscan(dbrel, 0, SnapshotNow, 1, &scanKey);
if (!HeapScanIsValid(scan))
elog(ERROR, "GetDatabaseInfo: cannot begin scan of %s", DatabaseRelationName);
/*
* Since we're going to close the relation, copy the tuple.
*/
tup = heap_getnext(scan, 0);
if (HeapTupleIsValid(tup))
dbtup = heap_copytuple(tup);
else
dbtup = tup;
heap_endscan(scan);
if (!HeapTupleIsValid(dbtup))
{
elog(NOTICE, "GetDatabaseInfo: %s entry not found %s",
DatabaseRelationName, name);
heap_close(dbrel, AccessShareLock);
return TRUE;
}
dbowner = (Oid) heap_getattr(dbtup,
Anum_pg_database_datdba,
RelationGetDescr(dbrel),
(char *) NULL);
dbid = dbtup->t_oid;
dbtext = (text *) heap_getattr(dbtup,
Anum_pg_database_datpath,
RelationGetDescr(dbrel),
(char *) NULL);
memcpy(dbpath, VARDATA(dbtext), (VARSIZE(dbtext) - VARHDRSZ));
*(dbpath + (VARSIZE(dbtext) - VARHDRSZ)) = '\0';
heap_close(dbrel, AccessShareLock);
owner = palloc(sizeof(Oid));
*owner = dbowner;
path = pstrdup(dbpath); /* doesn't do the right thing! */
return FALSE;
} /* GetDatabaseInfo() */
#endif
char *
ExpandDatabasePath(char *dbpath)
ExpandDatabasePath(const char *dbpath)
{
char buf[MAXPGPATH];
char *cp;
char *envvar;
const char *cp;
int len;
AssertArg(dbpath);
Assert(DataDir);
if (strlen(dbpath) >= MAXPGPATH)
return NULL; /* ain't gonna fit nohow */
@@ -120,17 +63,14 @@ ExpandDatabasePath(char *dbpath)
/* path delimiter somewhere? then has leading environment variable */
else if ((cp = strchr(dbpath, SEP_CHAR)) != NULL)
{
const char *envvar;
len = cp - dbpath;
strncpy(buf, dbpath, len);
buf[len] = '\0';
envvar = getenv(buf);
/*
* problem getting environment variable? let calling routine
* handle it
*/
if (envvar == NULL)
return envvar;
return NULL;
snprintf(buf, sizeof(buf), "%s%cbase%c%s",
envvar, SEP_CHAR, SEP_CHAR, (cp + 1));
@@ -142,10 +82,29 @@ ExpandDatabasePath(char *dbpath)
DataDir, SEP_CHAR, SEP_CHAR, dbpath);
}
/* check for illegal characters in dbpath */
for(cp = buf; *cp; cp++)
{
/* The following characters will not be allowed anywhere in the database
path. (Do not include the slash here.) */
char illegal_dbpath_chars[] =
"\001\002\003\004\005\006\007\010"
"\011\012\013\014\015\016\017\020"
"\021\022\023\024\025\026\027\030"
"\031\032\033\034\035\036\037"
"'.";
const char *cx;
for (cx = illegal_dbpath_chars; *cx; cx++)
if (*cp == *cx)
return NULL;
}
return pstrdup(buf);
} /* ExpandDatabasePath() */
/* --------------------------------
* GetRawDatabaseInfo() -- Find the OID and path of the database.
*
@@ -161,10 +120,9 @@ ExpandDatabasePath(char *dbpath)
* --------------------------------
*/
void
GetRawDatabaseInfo(char *name, Oid *db_id, char *path)
GetRawDatabaseInfo(const char *name, Oid *db_id, char *path)
{
int dbfd;
int fileflags;
int nbytes;
int max,
i;
@@ -174,16 +132,15 @@ GetRawDatabaseInfo(char *name, Oid *db_id, char *path)
char *dbfname;
Form_pg_database tup_db;
dbfname = (char *) palloc(strlen(DataDir) + strlen("pg_database") + 2);
sprintf(dbfname, "%s%cpg_database", DataDir, SEP_CHAR);
fileflags = O_RDONLY;
dbfname = (char *) palloc(strlen(DataDir) + strlen(DatabaseRelationName) + 2);
sprintf(dbfname, "%s%c%s", DataDir, SEP_CHAR, DatabaseRelationName);
#ifndef __CYGWIN32__
if ((dbfd = open(dbfname, O_RDONLY, 0)) < 0)
#else
if ((dbfd = open(dbfname, O_RDONLY | O_BINARY, 0)) < 0)
#endif
elog(FATAL, "Cannot open %s", dbfname);
elog(FATAL, "cannot open %s: %s", dbfname, strerror(errno));
pfree(dbfname);

View File

@@ -7,7 +7,7 @@
*
*
* IDENTIFICATION
* $Header: /cvsroot/pgsql/src/backend/utils/mmgr/Attic/palloc.c,v 1.15 1999/10/23 03:13:24 tgl Exp $
* $Header: /cvsroot/pgsql/src/backend/utils/mmgr/Attic/palloc.c,v 1.16 2000/01/13 18:26:14 petere Exp $
*
*-------------------------------------------------------------------------
*/
@@ -29,7 +29,7 @@
*/
char *
pstrdup(char *string)
pstrdup(const char *string)
{
char *nstr;
int len;