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.31 1998/07/24 03:31:50 scrappy 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>
40 #include <storage/ipc.h>
41 #include <storage/backendid.h>
42 #include <storage/buf_internals.h>
43 #include <storage/smgr.h>
44 #include <storage/proc.h>
45 #include <utils/relcache.h>
47 #include "access/heapam.h"
48 #include "access/xact.h"
49 #include "storage/bufmgr.h"
50 #include "access/transam.h" /* XXX dependency problem */
51 #include "utils/syscache.h"
52 #include "storage/bufpage.h" /* for page layout, for
53 * InitMyDatabaseInfo() */
54 #include "storage/sinval.h"
55 #include "storage/sinvaladt.h"
56 #include "storage/lmgr.h"
58 #include "miscadmin.h" /* for global decls */
59 #include "utils/portal.h" /* for EnablePortalManager, etc. */
61 #include "utils/exc.h" /* for EnableExceptionHandling, etc. */
62 #include "fmgr.h" /* for EnableDynamicFunctionManager, etc. */
63 #include "utils/elog.h"
64 #include "utils/palloc.h"
65 #include "utils/mcxt.h" /* for EnableMemoryContext, etc. */
66 #include "utils/inval.h"
68 #include "catalog/catname.h"
70 #include "catalog/pg_database_mb.h"
71 #include "mb/pg_wchar.h"
73 #include "catalog/pg_database.h"
76 #include "libpq/libpq.h"
78 static void VerifySystemDatabase(void);
79 static void VerifyMyDatabase(void);
80 static void InitCommunication(void);
81 static void InitMyDatabaseInfo(char *name);
82 static void InitStdio(void);
83 static void InitUserid(void);
85 extern char *ExpandDatabasePath(char *name);
87 extern void GetRawDatabaseInfo(char *name, Oid *owner, Oid *db_id, char *path, int *encoding);
89 extern void GetRawDatabaseInfo(char *name, Oid *owner, Oid *db_id, char *path);
92 static IPCKey PostgresIpcKey;
94 /* ----------------------------------------------------------------
95 * InitPostgres support
96 * ----------------------------------------------------------------
99 /* --------------------------------
100 * InitMyDatabaseInfo() -- Find and record the OID of the database we are
103 * The database's oid forms half of the unique key for the system
104 * caches and lock tables. We therefore want it initialized before
105 * we open any relations, since opening relations puts things in the
106 * cache. To get around this problem, this code opens and scans the
107 * pg_database relation by hand.
109 * This algorithm relies on the fact that first attribute in the
110 * pg_database relation schema is the database name. It also knows
111 * about the internal format of tuples on disk and the length of
112 * the datname attribute. It knows the location of the pg_database
114 * Actually, the code looks as though it is using the pg_database
115 * tuple definition to locate the database name, so the above statement
116 * seems to be no longer correct. - thomas 1997-11-01
118 * This code is called from InitPostgres(), before we chdir() to the
119 * local database directory and before we open any relations.
120 * Used to be called after the chdir(), but we now want to confirm
121 * the location of the target database using pg_database info.
122 * - thomas 1997-11-01
123 * --------------------------------
126 InitMyDatabaseInfo(char *name)
130 myPath[MAXPGPATH + 1];
135 SetDatabaseName(name);
137 GetRawDatabaseInfo(name, &owner, &MyDatabaseId, myPath, &encoding);
139 GetRawDatabaseInfo(name, &owner, &MyDatabaseId, myPath);
142 if (!OidIsValid(MyDatabaseId))
144 "Database %s does not exist in %s",
146 DatabaseRelationName);
148 path = ExpandDatabasePath(myPath);
149 SetDatabasePath(path);
151 SetDatabaseEncoding(encoding);
155 } /* InitMyDatabaseInfo() */
159 * DoChdirAndInitDatabaseNameAndPath --
160 * Set current directory to the database directory for the database
162 * Also set global variables DatabasePath and DatabaseName to those
163 * values. Also check for proper version of database system and
164 * database. Exit program via elog() if anything doesn't check out.
167 * Path and name are invalid if it invalid as a string.
168 * Path is "badly formatted" if it is not a string containing a path
169 * to a writable directory.
170 * Name is "badly formatted" if it contains more than 16 characters or if
171 * it is a bad file name (e.g., it contains a '/' or an 8-bit character).
174 * BadState if called more than once.
175 * BadArg if both path and name are "badly formatted" or invalid.
176 * BadArg if path and name are both "inconsistent" and valid.
178 * This routine is inappropriate in bootstrap mode, since the directories
179 * and version files need not exist yet if we're in bootstrap mode.
182 VerifySystemDatabase()
186 /* Failure reason returned by some function. NULL if no failure */
192 if ((fd = open(DataDir, O_RDONLY, 0)) == -1)
193 sprintf(errormsg, "Database system does not exist. "
194 "PGDATA directory '%s' not found.\n\tNormally, you "
195 "create a database system by running initdb.",
200 ValidatePgVersion(DataDir, &reason);
203 "InitPostgres could not validate that the database"
204 " system version is compatible with this level of"
205 " Postgres.\n\tYou may need to run initdb to create"
206 " a new database system.\n\t%s", reason);
208 if (errormsg[0] != '\0')
209 elog(FATAL, errormsg);
210 /* Above does not return */
211 } /* VerifySystemDatabase() */
220 /* Failure reason returned by some function. NULL if no failure */
226 myPath = DatabasePath;
228 if ((fd = open(myPath, O_RDONLY, 0)) == -1)
230 "Database '%s' does not exist."
231 "\n\tWe know this because the directory '%s' does not exist."
232 "\n\tYou can create a database with the SQL command"
233 " CREATE DATABASE.\n\tTo see what databases exist,"
234 " look at the subdirectories of '%s/base/'.",
235 name, myPath, DataDir);
239 ValidatePgVersion(myPath, &reason);
242 "InitPostgres could not validate that the database"
243 " version is compatible with this level of Postgres"
244 "\n\teven though the database system as a whole"
245 " appears to be at a compatible level."
246 "\n\tYou may need to recreate the database with SQL"
247 " commands DROP DATABASE and CREATE DATABASE."
253 * The directories and PG_VERSION files are in order.
255 int rc; /* return code from some function we call */
258 printf("Try changing directory for database %s to %s\n", name, myPath);
264 "InitPostgres unable to change "
265 "current directory to '%s', errno = %s (%d).",
266 myPath, strerror(errno), errno);
272 if (errormsg[0] != '\0')
273 elog(FATAL, errormsg);
274 /* Above does not return */
275 } /* VerifyMyDatabase() */
278 /* --------------------------------
281 * initializes crap associated with the user id.
282 * --------------------------------
291 /* --------------------------------
294 * This routine initializes stuff needed for ipc, locking, etc.
295 * it should be called something more informative.
298 * This does not set MyBackendId. MyBackendTag is set, however.
299 * --------------------------------
304 char *postid; /* value of environment variable */
305 char *postport; /* value of environment variable */
306 char *ipc_key; /* value of environemnt variable */
310 * try and get the backend tag from POSTID
315 postid = getenv("POSTID");
316 if (!PointerIsValid(postid))
320 MyBackendTag = atoi(postid);
321 Assert(MyBackendTag >= 0);
325 ipc_key = getenv("IPC_KEY");
326 if (!PointerIsValid(ipc_key))
331 Assert(MyBackendTag >= 0);
334 postport = getenv("POSTPORT");
336 if (PointerIsValid(postport))
338 if (MyBackendTag == -1)
339 elog(FATAL, "InitCommunication: missing POSTID");
342 * Enable this if you are trying to force the backend to run as if
343 * it is running under the postmaster.
345 * This goto forces Postgres to attach to shared memory instead of
346 * using malloc'ed memory (which is the normal behavior if run
349 * To enable emulation, run the following shell commands (in addition
350 * to enabling this goto)
352 * % setenv POSTID 1 % setenv POSTPORT 4321 % setenv IPC_KEY 4321000
353 * % postmaster & % kill -9 %1
355 * Upon doing this, Postmaster will have allocated the shared memory
356 * resources that Postgres will attach to if you enable
357 * EMULATE_UNDER_POSTMASTER.
359 * This comment may well age with time - it is current as of 8
365 #ifdef EMULATE_UNDER_POSTMASTER
367 goto forcesharedmemory;
372 else if (IsUnderPostmaster)
375 "InitCommunication: under postmaster and POSTPORT not set");
380 * assume we're running a postgres backend by itself with
381 * no front end or postmaster.
384 if (MyBackendTag == -1)
391 * initialize shared memory and semaphores appropriately.
394 #ifdef EMULATE_UNDER_POSTMASTER
400 if (!IsUnderPostmaster) /* postmaster already did this */
402 PostgresIpcKey = key;
403 AttachSharedMemoryAndSemaphores(key);
408 /* --------------------------------
411 * this routine consists of a bunch of code fragments
412 * that used to be randomly scattered through cinit().
413 * they all seem to do stuff associated with io.
414 * --------------------------------
422 /* --------------------------------
424 * Initialize POSTGRES.
427 * Be very careful with the order of calls in the InitPostgres function.
428 * --------------------------------
430 bool PostgresIsInitialized = false;
434 * this global is used by wei for testing his code, but must be declared
435 * here rather than in postgres.c so that it's defined for cinterface.a
439 /*int testFlag = 0;*/
445 InitPostgres(char *name) /* database name */
447 bool bootstrap; /* true if BootstrapProcessing */
450 * see if we're running in BootstrapProcessing mode
453 bootstrap = IsBootstrapProcessingMode();
456 * turn on the exception handler. Note: we cannot use elog, Assert,
457 * AssertState, etc. until after exception handling is on.
460 EnableExceptionHandling(true);
463 * A stupid check to make sure we don't call this more than once.
464 * But things like ReinitPostgres() get around this by just diddling
465 * the PostgresIsInitialized flag.
468 AssertState(!PostgresIsInitialized);
471 * Memory system initialization.
472 * (we may call palloc after EnableMemoryContext())
474 * Note EnableMemoryContext() must happen before EnablePortalManager().
477 EnableMemoryContext(true); /* initializes the "top context" */
478 EnablePortalManager(true); /* memory for portal/transaction stuff */
481 * initialize the backend local portal stack used by
482 * internal PQ function calls. see src/lib/libpq/be-dumpdata.c
483 * This is different from the "portal manager" so this goes here.
490 * attach to shared memory and semaphores, and initialize our
491 * input/output/debugging file descriptors.
498 * initialize the local buffer manager
502 if (!TransactionFlushEnabled())
503 on_shmem_exit(FlushBufferPool, (caddr_t) NULL);
506 * initialize the database id used for system caches and lock tables
511 SetDatabasePath(ExpandDatabasePath(name));
512 SetDatabaseName(name);
517 VerifySystemDatabase();
518 InitMyDatabaseInfo(name);
523 * ********************************
525 * code after this point assumes we are in the proper directory!
527 * So, how do we implement alternate locations for databases? There are
528 * two possible locations for tables and we need to look in
529 * DataDir/pg_database to find the true location of an individual
530 * database. We can brute-force it as done in InitMyDatabaseInfo(), or
531 * we can be patient and wait until we open pg_database gracefully.
532 * Will try that, but may not work... - thomas 1997-11-01 ********************************
536 /* Does not touch files (?) - thomas 1997-11-01 */
540 * initialize the transaction system and the relation descriptor cache.
541 * Note we have to make certain the lock manager is off while we do this.
544 AmiTransactionOverride(IsBootstrapProcessingMode());
548 * Part of the initialization processing done here sets a read lock on
549 * pg_log. Since locking is disabled the set doesn't have intended
550 * effect of locking out writers, but this is ok, since we only lock
551 * it to examine AMI transaction status, and this is never written
552 * after initdb is done. -mer 15 June 1992
554 RelationInitialize(); /* pre-allocated reldescs created here */
555 InitializeTransactionSystem(); /* pg_log,etc init/crash recovery
561 * anyone knows what this does? something having to do with
562 * system catalog cache invalidation in the case of multiple
563 * backends, I think -cim 10/3/90
564 * Sets up MyBackendId a unique backend identifier.
567 InitSharedInvalidationState();
570 * Set up a per backend process in shared memory. Must be done after
571 * InitSharedInvalidationState() as it relies on MyBackendId being
572 * initialized already. XXX -mer 11 Aug 1991
575 InitProcess(PostgresIpcKey);
577 if (MyBackendId > MaxBackendId || MyBackendId <= 0)
579 elog(FATAL, "cinit2: bad backend id %d (%d)",
585 * initialize the access methods.
586 * Does not touch files (?) - thomas 1997-11-01
592 * initialize all the system catalog caches.
598 * Does not touch files since all routines are builtins (?) - thomas
604 * set ourselves to the proper user id and figure out our postgres
605 * user id. If we ever add security so that we check for valid
606 * postgres users, we might do it here.
612 * initialize local data in cache invalidation stuff
616 InitLocalInvalidateData();
619 * ok, all done, now let's make sure we don't do it again.
622 PostgresIsInitialized = true;
623 /* on_shmem_exit(DestroyLocalRelList, (caddr_t) NULL); */
626 * Done with "InitPostgres", now change to NormalProcessing unless
627 * we're in BootstrapProcessing mode.
631 SetProcessingMode(NormalProcessing);
632 /* if (testFlag || lockingOff) */