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.19 1997/11/18 07:58:10 vadim 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/tqual.h"
52 #include "utils/syscache.h"
53 #include "storage/bufpage.h" /* for page layout, for 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. */
67 #include "catalog/catname.h"
68 #include "catalog/pg_database.h"
70 #include "port-protos.h"
71 #include "libpq/libpq-be.h"
73 static void VerifySystemDatabase(void);
74 static void VerifyMyDatabase(void);
75 static void InitCommunication(void);
76 static void InitMyDatabaseInfo(char *name);
77 static void InitStdio(void);
78 static void InitUserid(void);
80 extern char *ExpandDatabasePath(char *name);
81 extern void GetRawDatabaseInfo(char *name, Oid *owner, Oid *db_id, char *path);
83 static IPCKey PostgresIpcKey;
85 /* ----------------------------------------------------------------
86 * InitPostgres support
87 * ----------------------------------------------------------------
90 /* --------------------------------
91 * InitMyDatabaseInfo() -- Find and record the OID of the database we are
94 * The database's oid forms half of the unique key for the system
95 * caches and lock tables. We therefore want it initialized before
96 * we open any relations, since opening relations puts things in the
97 * cache. To get around this problem, this code opens and scans the
98 * pg_database relation by hand.
100 * This algorithm relies on the fact that first attribute in the
101 * pg_database relation schema is the database name. It also knows
102 * about the internal format of tuples on disk and the length of
103 * the datname attribute. It knows the location of the pg_database
105 * Actually, the code looks as though it is using the pg_database
106 * tuple definition to locate the database name, so the above statement
107 * seems to be no longer correct. - thomas 1997-11-01
109 * This code is called from InitPostgres(), before we chdir() to the
110 * local database directory and before we open any relations.
111 * Used to be called after the chdir(), but we now want to confirm
112 * the location of the target database using pg_database info.
113 * - thomas 1997-11-01
114 * --------------------------------
117 InitMyDatabaseInfo(char *name)
123 SetDatabaseName(name);
124 GetRawDatabaseInfo(name, &owner, &MyDatabaseId, myPath);
126 if (!OidIsValid(MyDatabaseId))
128 "Database %s does not exist in %s",
130 DatabaseRelationName);
132 path = ExpandDatabasePath(myPath);
133 SetDatabasePath(path);
136 } /* InitMyDatabaseInfo() */
140 * DoChdirAndInitDatabaseNameAndPath --
141 * Set current directory to the database directory for the database
143 * Also set global variables DatabasePath and DatabaseName to those
144 * values. Also check for proper version of database system and
145 * database. Exit program via elog() if anything doesn't check out.
148 * Path and name are invalid if it invalid as a string.
149 * Path is "badly formatted" if it is not a string containing a path
150 * to a writable directory.
151 * Name is "badly formatted" if it contains more than 16 characters or if
152 * it is a bad file name (e.g., it contains a '/' or an 8-bit character).
155 * BadState if called more than once.
156 * BadArg if both path and name are "badly formatted" or invalid.
157 * BadArg if path and name are both "inconsistent" and valid.
159 * This routine is inappropriate in bootstrap mode, since the directories
160 * and version files need not exist yet if we're in bootstrap mode.
163 VerifySystemDatabase()
167 /* Failure reason returned by some function. NULL if no failure */
173 if ((fd = open(DataDir, O_RDONLY, 0)) == -1)
174 sprintf(errormsg, "Database system does not exist. "
175 "PGDATA directory '%s' not found.\n\tNormally, you "
176 "create a database system by running initdb.",
181 ValidatePgVersion(DataDir, &reason);
184 "InitPostgres could not validate that the database"
185 " system version is compatible with this level of"
186 " Postgres.\n\tYou may need to run initdb to create"
187 " a new database system.\n\t%s", reason);
189 if (errormsg[0] != '\0')
190 elog(FATAL, errormsg);
191 /* Above does not return */
192 } /* VerifySystemDatabase() */
201 /* Failure reason returned by some function. NULL if no failure */
206 name = GetDatabaseName();
207 myPath = GetDatabasePath();
209 if ((fd = open(myPath, O_RDONLY, 0)) == -1)
211 "Database '%s' does not exist."
212 "\n\tWe know this because the directory '%s' does not exist."
213 "\n\tYou can create a database with the SQL command"
214 " CREATE DATABASE.\n\tTo see what databases exist,"
215 " look at the subdirectories of '%s/base/'.",
216 name, myPath, DataDir);
220 ValidatePgVersion(myPath, &reason);
223 "InitPostgres could not validate that the database"
224 " version is compatible with this level of Postgres"
225 "\n\teven though the database system as a whole"
226 " appears to be at a compatible level."
227 "\n\tYou may need to recreate the database with SQL"
228 " commands DROP DATABASE and CREATE DATABASE."
233 * The directories and PG_VERSION files are in order.
235 int rc; /* return code from some function we call */
238 printf("Try changing directory for database %s to %s\n", name, myPath);
244 "InitPostgres unable to change "
245 "current directory to '%s', errno = %s (%d).",
246 myPath, strerror(errno), errno);
252 if (errormsg[0] != '\0')
253 elog(FATAL, errormsg);
254 /* Above does not return */
255 } /* VerifyMyDatabase() */
258 /* --------------------------------
261 * initializes crap associated with the user id.
262 * --------------------------------
271 /* --------------------------------
274 * This routine initializes stuff needed for ipc, locking, etc.
275 * it should be called something more informative.
278 * This does not set MyBackendId. MyBackendTag is set, however.
279 * --------------------------------
284 char *postid; /* value of environment variable */
285 char *postport; /* value of environment variable */
286 char *ipc_key; /* value of environemnt variable */
290 * try and get the backend tag from POSTID
295 postid = getenv("POSTID");
296 if (!PointerIsValid(postid))
302 MyBackendTag = atoi(postid);
303 Assert(MyBackendTag >= 0);
307 ipc_key = getenv("IPC_KEY");
308 if (!PointerIsValid(ipc_key)) {
312 Assert(MyBackendTag >= 0);
315 postport = getenv("POSTPORT");
317 if (PointerIsValid(postport))
319 if (MyBackendTag == -1)
320 elog(FATAL, "InitCommunication: missing POSTID");
323 * Enable this if you are trying to force the backend to run as if
324 * it is running under the postmaster.
326 * This goto forces Postgres to attach to shared memory instead of
327 * using malloc'ed memory (which is the normal behavior if run
330 * To enable emulation, run the following shell commands (in addition
331 * to enabling this goto)
334 * % setenv POSTPORT 4321
335 * % setenv IPC_KEY 4321000
339 * Upon doing this, Postmaster will have allocated the shared memory
340 * resources that Postgres will attach to if you enable
341 * EMULATE_UNDER_POSTMASTER.
343 * This comment may well age with time - it is current as of 8
349 #ifdef EMULATE_UNDER_POSTMASTER
351 goto forcesharedmemory;
356 else if (IsUnderPostmaster)
359 "InitCommunication: under postmaster and POSTPORT not set");
364 * assume we're running a postgres backend by itself with
365 * no front end or postmaster.
368 if (MyBackendTag == -1)
377 * initialize shared memory and semaphores appropriately.
380 #ifdef EMULATE_UNDER_POSTMASTER
386 PostgresIpcKey = key;
387 AttachSharedMemoryAndSemaphores(key);
391 /* --------------------------------
394 * this routine consists of a bunch of code fragments
395 * that used to be randomly scattered through cinit().
396 * they all seem to do stuff associated with io.
397 * --------------------------------
405 /* --------------------------------
407 * Initialize POSTGRES.
410 * Be very careful with the order of calls in the InitPostgres function.
411 * --------------------------------
413 bool PostgresIsInitialized = false;
417 * this global is used by wei for testing his code, but must be declared
418 * here rather than in postgres.c so that it's defined for cinterface.a
422 /*int testFlag = 0;*/
428 InitPostgres(char *name) /* database name */
430 bool bootstrap; /* true if BootstrapProcessing */
433 * see if we're running in BootstrapProcessing mode
436 bootstrap = IsBootstrapProcessingMode();
439 * turn on the exception handler. Note: we cannot use elog, Assert,
440 * AssertState, etc. until after exception handling is on.
443 EnableExceptionHandling(true);
446 * A stupid check to make sure we don't call this more than once.
447 * But things like ReinitPostgres() get around this by just diddling
448 * the PostgresIsInitialized flag.
451 AssertState(!PostgresIsInitialized);
454 * Memory system initialization.
455 * (we may call palloc after EnableMemoryContext())
457 * Note EnableMemoryContext() must happen before EnablePortalManager().
460 EnableMemoryContext(true); /* initializes the "top context" */
461 EnablePortalManager(true); /* memory for portal/transaction stuff */
464 * initialize the backend local portal stack used by
465 * internal PQ function calls. see src/lib/libpq/be-dumpdata.c
466 * This is different from the "portal manager" so this goes here.
473 * attach to shared memory and semaphores, and initialize our
474 * input/output/debugging file descriptors.
481 * initialize the local buffer manager
485 if (!TransactionFlushEnabled())
486 on_exitpg(FlushBufferPool, (caddr_t) NULL);
489 * initialize the database id used for system caches and lock tables
494 SetDatabasePath(ExpandDatabasePath(name));
495 SetDatabaseName(name);
500 VerifySystemDatabase();
501 InitMyDatabaseInfo(name);
506 * ********************************
507 * code after this point assumes we are in the proper directory!
509 * So, how do we implement alternate locations for databases?
510 * There are two possible locations for tables and we need to look
511 * in DataDir/pg_database to find the true location of an
512 * individual database. We can brute-force it as done in
513 * InitMyDatabaseInfo(), or we can be patient and wait until we
514 * open pg_database gracefully. Will try that, but may not work...
515 * - thomas 1997-11-01
516 * ********************************
519 /* Does not touch files (?) - thomas 1997-11-01 */
523 * initialize the transaction system and the relation descriptor cache.
524 * Note we have to make certain the lock manager is off while we do this.
527 AmiTransactionOverride(IsBootstrapProcessingMode());
531 * Part of the initialization processing done here sets a read lock on
532 * pg_log. Since locking is disabled the set doesn't have intended
533 * effect of locking out writers, but this is ok, since we only lock
534 * it to examine AMI transaction status, and this is never written
535 * after initdb is done. -mer 15 June 1992
537 RelationInitialize(); /* pre-allocated reldescs created here */
538 InitializeTransactionSystem(); /* pg_log,etc init/crash recovery here */
543 * anyone knows what this does? something having to do with
544 * system catalog cache invalidation in the case of multiple
545 * backends, I think -cim 10/3/90
546 * Sets up MyBackendId a unique backend identifier.
549 InitSharedInvalidationState();
552 * Set up a per backend process in shared memory. Must be done after
553 * InitSharedInvalidationState() as it relies on MyBackendId being
554 * initialized already. XXX -mer 11 Aug 1991
557 InitProcess(PostgresIpcKey);
559 if (MyBackendId > MaxBackendId || MyBackendId <= 0)
561 elog(FATAL, "cinit2: bad backend id %d (%d)",
567 * initialize the access methods.
568 * Does not touch files (?) - thomas 1997-11-01
574 * initialize all the system catalog caches.
578 /* Does not touch files since all routines are builtins (?)
579 * - thomas 1997-11-01
584 * set ourselves to the proper user id and figure out our postgres
585 * user id. If we ever add security so that we check for valid
586 * postgres users, we might do it here.
592 * ok, all done, now let's make sure we don't do it again.
595 PostgresIsInitialized = true;
596 /* on_exitpg(DestroyLocalRelList, (caddr_t) NULL); */
599 * Done with "InitPostgres", now change to NormalProcessing unless
600 * we're in BootstrapProcessing mode.
604 SetProcessingMode(NormalProcessing);
605 /* if (testFlag || lockingOff) */