1 /*-------------------------------------------------------------------------
4 * postgres initialization utilities
6 * Copyright (c) 1994, Regents of the University of California
10 * $Header: /cvsroot/pgsql/src/backend/utils/init/postinit.c,v 1.47 1999/07/17 16:25:25 momjian Exp $
13 * InitPostgres() is the function called from PostgresMain
14 * which does all non-trival initialization, mainly by calling
15 * all the other initialization functions. InitPostgres()
16 * is only used within the "postgres" backend and so that routine
17 * is in tcop/postgres.c InitPostgres() is needed in cinterface.a
18 * because things like the bootstrap backend program need it. Hence
19 * you find that in this file...
21 * If you feel the need to add more initialization code, it should be
22 * done in InitPostgres() or someplace lower. Do not start
23 * putting stuff in PostgresMain - if you do then someone
24 * will have to clean it up later, and it's not going to be me!
27 *-------------------------------------------------------------------------
33 #include <sys/types.h>
39 #include "access/heapam.h"
40 #include "catalog/catname.h"
41 #include "libpq/libpq.h"
42 #include "miscadmin.h"
43 #include "storage/backendid.h"
44 #include "storage/proc.h"
45 #include "storage/sinval.h"
46 #include "storage/smgr.h"
47 #include "utils/inval.h"
48 #include "utils/portal.h"
49 #include "utils/relcache.h"
50 #include "utils/syscache.h"
54 #include "mb/pg_wchar.h"
57 static void VerifySystemDatabase(void);
58 static void VerifyMyDatabase(void);
59 static void InitCommunication(void);
60 static void InitMyDatabaseInfo(char *name);
61 static void InitStdio(void);
62 static void InitUserid(void);
64 extern char *ExpandDatabasePath(char *name);
65 extern void GetRawDatabaseInfo(char *name, int4 *owner, Oid *db_id, char *path, int *encoding);
67 static IPCKey PostgresIpcKey;
69 /* ----------------------------------------------------------------
70 * InitPostgres support
71 * ----------------------------------------------------------------
74 /* --------------------------------
75 * InitMyDatabaseInfo() -- Find and record the OID of the database we are
78 * The database's oid forms half of the unique key for the system
79 * caches and lock tables. We therefore want it initialized before
80 * we open any relations, since opening relations puts things in the
81 * cache. To get around this problem, this code opens and scans the
82 * pg_database relation by hand.
84 * This algorithm relies on the fact that first attribute in the
85 * pg_database relation schema is the database name. It also knows
86 * about the internal format of tuples on disk and the length of
87 * the datname attribute. It knows the location of the pg_database
89 * Actually, the code looks as though it is using the pg_database
90 * tuple definition to locate the database name, so the above statement
91 * seems to be no longer correct. - thomas 1997-11-01
93 * This code is called from InitPostgres(), before we chdir() to the
94 * local database directory and before we open any relations.
95 * Used to be called after the chdir(), but we now want to confirm
96 * the location of the target database using pg_database info.
98 * --------------------------------
101 InitMyDatabaseInfo(char *name)
105 myPath[MAXPGPATH + 1];
108 SetDatabaseName(name);
109 GetRawDatabaseInfo(name, &owner, &MyDatabaseId, myPath, &encoding);
111 if (!OidIsValid(MyDatabaseId))
113 "Database %s does not exist in %s",
115 DatabaseRelationName);
117 path = ExpandDatabasePath(myPath);
118 SetDatabasePath(path);
120 SetDatabaseEncoding(encoding);
124 } /* InitMyDatabaseInfo() */
128 * DoChdirAndInitDatabaseNameAndPath
129 * Set current directory to the database directory for the database
131 * Also set global variables DatabasePath and DatabaseName to those
132 * values. Also check for proper version of database system and
133 * database. Exit program via elog() if anything doesn't check out.
136 * Path and name are invalid if it invalid as a string.
137 * Path is "badly formatted" if it is not a string containing a path
138 * to a writable directory.
139 * Name is "badly formatted" if it contains more than 16 characters or if
140 * it is a bad file name (e.g., it contains a '/' or an 8-bit character).
143 * BadState if called more than once.
144 * BadArg if both path and name are "badly formatted" or invalid.
145 * BadArg if path and name are both "inconsistent" and valid.
147 * This routine is inappropriate in bootstrap mode, since the directories
148 * and version files need not exist yet if we're in bootstrap mode.
151 VerifySystemDatabase()
155 /* Failure reason returned by some function. NULL if no failure */
162 if ((fd = open(DataDir, O_RDONLY, 0)) == -1)
164 if ((fd = open(DataDir, O_RDONLY | O_DIROPEN, 0)) == -1)
166 sprintf(errormsg, "Database system does not exist. "
167 "PGDATA directory '%s' not found.\n\tNormally, you "
168 "create a database system by running initdb.",
173 ValidatePgVersion(DataDir, &reason);
176 "InitPostgres could not validate that the database"
177 " system version is compatible with this level of"
178 " Postgres.\n\tYou may need to run initdb to create"
179 " a new database system.\n\t%s", reason);
181 if (errormsg[0] != '\0')
182 elog(FATAL, errormsg);
183 /* Above does not return */
184 } /* VerifySystemDatabase() */
193 /* Failure reason returned by some function. NULL if no failure */
199 myPath = DatabasePath;
202 if ((fd = open(myPath, O_RDONLY, 0)) == -1)
204 if ((fd = open(myPath, O_RDONLY | O_DIROPEN, 0)) == -1)
207 "Database '%s' does not exist."
208 "\n\tWe know this because the directory '%s' does not exist."
209 "\n\tYou can create a database with the SQL command"
210 " CREATE DATABASE.\n\tTo see what databases exist,"
211 " look at the subdirectories of '%s/base/'.",
212 name, myPath, DataDir);
216 ValidatePgVersion(myPath, &reason);
219 "InitPostgres could not validate that the database"
220 " version is compatible with this level of Postgres"
221 "\n\teven though the database system as a whole"
222 " appears to be at a compatible level."
223 "\n\tYou may need to recreate the database with SQL"
224 " commands DROP DATABASE and CREATE DATABASE."
230 * The directories and PG_VERSION files are in order.
232 int rc; /* return code from some function we call */
235 printf("Try changing directory for database %s to %s\n", name, myPath);
241 "InitPostgres unable to change "
242 "current directory to '%s', errno = %s (%d).",
243 myPath, strerror(errno), errno);
249 if (errormsg[0] != '\0')
250 elog(FATAL, errormsg);
251 /* Above does not return */
252 } /* VerifyMyDatabase() */
255 /* --------------------------------
258 * initializes crap associated with the user id.
259 * --------------------------------
268 /* --------------------------------
271 * This routine initializes stuff needed for ipc, locking, etc.
272 * it should be called something more informative.
275 * This does not set MyBackendId. MyBackendTag is set, however.
276 * --------------------------------
281 char *postid; /* value of environment variable */
282 char *postport; /* value of environment variable */
283 char *ipc_key; /* value of environemnt variable */
287 * try and get the backend tag from POSTID
292 postid = getenv("POSTID");
293 if (!PointerIsValid(postid))
297 MyBackendTag = atoi(postid);
298 Assert(MyBackendTag >= 0);
302 ipc_key = getenv("IPC_KEY");
303 if (!PointerIsValid(ipc_key))
308 Assert(MyBackendTag >= 0);
311 postport = getenv("POSTPORT");
313 if (PointerIsValid(postport))
315 if (MyBackendTag == -1)
316 elog(FATAL, "InitCommunication: missing POSTID");
319 * Enable this if you are trying to force the backend to run as if
320 * it is running under the postmaster.
322 * This goto forces Postgres to attach to shared memory instead of
323 * using malloc'ed memory (which is the normal behavior if run
326 * To enable emulation, run the following shell commands (in addition
327 * to enabling this goto)
329 * % setenv POSTID 1 % setenv POSTPORT 4321 % setenv IPC_KEY 4321000
330 * % postmaster & % kill -9 %1
332 * Upon doing this, Postmaster will have allocated the shared memory
333 * resources that Postgres will attach to if you enable
334 * EMULATE_UNDER_POSTMASTER.
336 * This comment may well age with time - it is current as of 8
342 #ifdef EMULATE_UNDER_POSTMASTER
344 goto forcesharedmemory;
349 else if (IsUnderPostmaster)
352 "InitCommunication: under postmaster and POSTPORT not set");
357 * assume we're running a postgres backend by itself with
358 * no front end or postmaster.
361 if (MyBackendTag == -1)
368 * initialize shared memory and semaphores appropriately.
371 #ifdef EMULATE_UNDER_POSTMASTER
377 if (!IsUnderPostmaster) /* postmaster already did this */
379 PostgresIpcKey = key;
380 AttachSharedMemoryAndSemaphores(key);
385 /* --------------------------------
388 * this routine consists of a bunch of code fragments
389 * that used to be randomly scattered through cinit().
390 * they all seem to do stuff associated with io.
391 * --------------------------------
399 /* --------------------------------
401 * Initialize POSTGRES.
404 * Be very careful with the order of calls in the InitPostgres function.
405 * --------------------------------
407 bool PostgresIsInitialized = false;
411 * this global is used by wei for testing his code, but must be declared
412 * here rather than in postgres.c so that it's defined for cinterface.a
416 /*int testFlag = 0;*/
422 InitPostgres(char *name) /* database name */
424 bool bootstrap; /* true if BootstrapProcessing */
427 * see if we're running in BootstrapProcessing mode
430 bootstrap = IsBootstrapProcessingMode();
433 * turn on the exception handler. Note: we cannot use elog, Assert,
434 * AssertState, etc. until after exception handling is on.
437 EnableExceptionHandling(true);
440 * A stupid check to make sure we don't call this more than once.
441 * But things like ReinitPostgres() get around this by just diddling
442 * the PostgresIsInitialized flag.
445 AssertState(!PostgresIsInitialized);
448 * Memory system initialization.
449 * (we may call palloc after EnableMemoryContext())
451 * Note EnableMemoryContext() must happen before EnablePortalManager().
454 EnableMemoryContext(true); /* initializes the "top context" */
455 EnablePortalManager(true); /* memory for portal/transaction stuff */
458 * initialize the backend local portal stack used by
459 * internal PQ function calls. see src/lib/libpq/be-dumpdata.c
460 * This is different from the "portal manager" so this goes here.
467 * attach to shared memory and semaphores, and initialize our
468 * input/output/debugging file descriptors.
475 * initialize the local buffer manager
479 if (!TransactionFlushEnabled())
480 on_shmem_exit(FlushBufferPool, (caddr_t) NULL);
483 * initialize the database id used for system caches and lock tables
488 SetDatabasePath(ExpandDatabasePath(name));
489 SetDatabaseName(name);
494 VerifySystemDatabase();
495 InitMyDatabaseInfo(name);
500 * Code after this point assumes we are in the proper directory!
502 * So, how do we implement alternate locations for databases? There are
503 * two possible locations for tables and we need to look in
504 * DataDir/pg_database to find the true location of an individual
505 * database. We can brute-force it as done in InitMyDatabaseInfo(), or
506 * we can be patient and wait until we open pg_database gracefully.
507 * Will try that, but may not work... - thomas 1997-11-01
510 /* Does not touch files (?) - thomas 1997-11-01 */
514 * initialize the transaction system and the relation descriptor cache.
515 * Note we have to make certain the lock manager is off while we do this.
518 AmiTransactionOverride(IsBootstrapProcessingMode());
522 * Part of the initialization processing done here sets a read lock on
523 * pg_log. Since locking is disabled the set doesn't have intended
524 * effect of locking out writers, but this is ok, since we only lock
525 * it to examine AMI transaction status, and this is never written
526 * after initdb is done. -mer 15 June 1992
528 RelationInitialize(); /* pre-allocated reldescs created here */
529 InitializeTransactionSystem(); /* pg_log,etc init/crash recovery
535 * anyone knows what this does? something having to do with
536 * system catalog cache invalidation in the case of multiple
537 * backends, I think -cim 10/3/90
538 * Sets up MyBackendId a unique backend identifier.
541 InitSharedInvalidationState();
544 * Set up a per backend process in shared memory. Must be done after
545 * InitSharedInvalidationState() as it relies on MyBackendId being
546 * initialized already. XXX -mer 11 Aug 1991
549 InitProcess(PostgresIpcKey);
551 if (MyBackendId > MAXBACKENDS || MyBackendId <= 0)
553 elog(FATAL, "cinit2: bad backend id %d (%d)",
559 * initialize the access methods.
560 * Does not touch files (?) - thomas 1997-11-01
566 * initialize all the system catalog caches.
572 * Does not touch files since all routines are builtins (?) - thomas
578 * set ourselves to the proper user id and figure out our postgres
579 * user id. If we ever add security so that we check for valid
580 * postgres users, we might do it here.
586 * initialize local data in cache invalidation stuff
590 InitLocalInvalidateData();
593 * ok, all done, now let's make sure we don't do it again.
596 PostgresIsInitialized = true;
597 /* on_shmem_exit(DestroyLocalRelList, (caddr_t) NULL); */
600 * Done with "InitPostgres", now change to NormalProcessing unless
601 * we're in BootstrapProcessing mode.
605 SetProcessingMode(NormalProcessing);
606 /* if (testFlag || lockingOff) */