1 /*-------------------------------------------------------------------------
4 * postgres initialization utilities
6 * Portions Copyright (c) 1996-2005, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/utils/init/postinit.c,v 1.149 2005/06/24 01:06:26 neilc Exp $
14 *-------------------------------------------------------------------------
23 #include "catalog/catalog.h"
24 #include "access/heapam.h"
25 #include "catalog/namespace.h"
26 #include "catalog/pg_database.h"
27 #include "catalog/pg_shadow.h"
28 #include "catalog/pg_tablespace.h"
29 #include "libpq/hba.h"
30 #include "mb/pg_wchar.h"
31 #include "miscadmin.h"
32 #include "postmaster/postmaster.h"
33 #include "storage/backendid.h"
34 #include "storage/fd.h"
35 #include "storage/ipc.h"
36 #include "storage/proc.h"
37 #include "storage/procarray.h"
38 #include "storage/sinval.h"
39 #include "storage/smgr.h"
40 #include "utils/flatfiles.h"
41 #include "utils/fmgroids.h"
42 #include "utils/guc.h"
43 #include "utils/portal.h"
44 #include "utils/relcache.h"
45 #include "utils/syscache.h"
48 static bool FindMyDatabase(const char *name, Oid *db_id, Oid *db_tablespace);
49 static void ReverifyMyDatabase(const char *name);
50 static void InitCommunication(void);
51 static void ShutdownPostgres(int code, Datum arg);
52 static bool ThereIsAtLeastOneUser(void);
55 /*** InitPostgres support ***/
59 * FindMyDatabase -- get the critical info needed to locate my database
61 * Find the named database in pg_database, return its database OID and the
62 * OID of its default tablespace. Return TRUE if found, FALSE if not.
64 * Since we are not yet up and running as a backend, we cannot look directly
65 * at pg_database (we can't obtain locks nor participate in transactions).
66 * So to get the info we need before starting up, we must look at the "flat
67 * file" copy of pg_database that is helpfully maintained by flatfiles.c.
68 * This is subject to various race conditions, so after we have the
69 * transaction infrastructure started, we have to recheck the information;
70 * see ReverifyMyDatabase.
73 FindMyDatabase(const char *name, Oid *db_id, Oid *db_tablespace)
78 char thisname[NAMEDATALEN];
80 filename = database_getflatfilename();
81 db_file = AllocateFile(filename, "r");
84 (errcode_for_file_access(),
85 errmsg("could not open file \"%s\": %m", filename)));
87 while (read_pg_database_line(db_file, thisname, db_id, db_tablespace))
89 if (strcmp(thisname, name) == 0)
103 * ReverifyMyDatabase -- recheck info obtained by FindMyDatabase
105 * Since FindMyDatabase cannot lock pg_database, the information it read
106 * could be stale; for example we might have attached to a database that's in
107 * process of being destroyed by dropdb(). This routine is called after
108 * we have all the locking and other infrastructure running --- now we can
109 * check that we are really attached to a valid database.
111 * In reality, if dropdb() is running in parallel with our startup,
112 * it's pretty likely that we will have failed before now, due to being
113 * unable to read some of the system tables within the doomed database.
114 * This routine just exists to make *sure* we have not started up in an
115 * invalid database. If we quit now, we should have managed to avoid
116 * creating any serious problems.
118 * This is also a handy place to fetch the database encoding info out
121 * To avoid having to read pg_database more times than necessary
122 * during session startup, this place is also fitting to set up any
123 * database-specific configuration variables.
126 ReverifyMyDatabase(const char *name)
129 HeapScanDesc pgdbscan;
132 Form_pg_database dbform;
135 * Because we grab RowShareLock here, we can be sure that dropdb()
136 * is not running in parallel with us (any more).
138 pgdbrel = heap_open(DatabaseRelationId, RowShareLock);
141 Anum_pg_database_datname,
142 BTEqualStrategyNumber, F_NAMEEQ,
145 pgdbscan = heap_beginscan(pgdbrel, SnapshotNow, 1, &key);
147 tup = heap_getnext(pgdbscan, ForwardScanDirection);
148 if (!HeapTupleIsValid(tup) ||
149 HeapTupleGetOid(tup) != MyDatabaseId)
152 heap_close(pgdbrel, RowShareLock);
155 * The only real problem I could have created is to load dirty
156 * buffers for the dead database into shared buffer cache; if I
157 * did, some other backend will eventually try to write them and
158 * die in mdblindwrt. Flush any such pages to forestall trouble.
160 DropBuffers(MyDatabaseId);
161 /* Now I can commit hara-kiri with a clear conscience... */
163 (errcode(ERRCODE_UNDEFINED_DATABASE),
164 errmsg("database \"%s\", OID %u, has disappeared from pg_database",
165 name, MyDatabaseId)));
169 * Also check that the database is currently allowing connections.
170 * (We do not enforce this in standalone mode, however, so that there is
171 * a way to recover from "UPDATE pg_database SET datallowconn = false;")
173 dbform = (Form_pg_database) GETSTRUCT(tup);
174 if (IsUnderPostmaster && !dbform->datallowconn)
176 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
177 errmsg("database \"%s\" is not currently accepting connections",
181 * OK, we're golden. Next to-do item is to save the encoding
182 * info out of the pg_database tuple.
184 SetDatabaseEncoding(dbform->encoding);
185 /* Record it as a GUC internal option, too */
186 SetConfigOption("server_encoding", GetDatabaseEncodingName(),
187 PGC_INTERNAL, PGC_S_OVERRIDE);
188 /* If we have no other source of client_encoding, use server encoding */
189 SetConfigOption("client_encoding", GetDatabaseEncodingName(),
190 PGC_BACKEND, PGC_S_DEFAULT);
193 * Lastly, set up any database-specific configuration variables.
195 if (IsUnderPostmaster)
200 datum = heap_getattr(tup, Anum_pg_database_datconfig,
201 RelationGetDescr(pgdbrel), &isnull);
204 ArrayType *a = DatumGetArrayTypeP(datum);
206 ProcessGUCArray(a, PGC_S_DATABASE);
210 heap_endscan(pgdbscan);
211 heap_close(pgdbrel, RowShareLock);
216 /* --------------------------------
219 * This routine initializes stuff needed for ipc, locking, etc.
220 * it should be called something more informative.
221 * --------------------------------
224 InitCommunication(void)
227 * initialize shared memory and semaphores appropriately.
229 if (!IsUnderPostmaster) /* postmaster already did this */
232 * We're running a postgres bootstrap process or a standalone
233 * backend. Create private "shmem" and semaphores.
235 CreateSharedMemoryAndSemaphores(true, 0);
241 * Early initialization of a backend (either standalone or under postmaster).
242 * This happens even before InitPostgres.
244 * If you're wondering why this is separate from InitPostgres at all:
245 * the critical distinction is that this stuff has to happen before we can
246 * run XLOG-related initialization, which is done before InitPostgres --- in
247 * fact, for cases such as checkpoint creation processes, InitPostgres may
248 * never be done at all.
254 * Attach to shared memory and semaphores, and initialize our
255 * input/output/debugging file descriptors.
260 /* Do local initialization of storage and buffer managers */
262 InitBufferPoolAccess();
266 /* --------------------------------
268 * Initialize POSTGRES.
270 * In bootstrap mode neither of the parameters are used.
272 * The return value indicates whether the userID is a superuser. (That
273 * can only be tested inside a transaction, so we want to do it during
274 * the startup transaction rather than doing a separate one in postgres.c.)
277 * Be very careful with the order of calls in the InitPostgres function.
278 * --------------------------------
281 InitPostgres(const char *dbname, const char *username)
283 bool bootstrap = IsBootstrapProcessingMode();
287 * Set up the global variables holding database id and path.
289 * We take a shortcut in the bootstrap case, otherwise we have to look up
290 * the db name in pg_database.
294 MyDatabaseId = TemplateDbOid;
295 MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
296 SetDatabasePath(GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace));
303 * Formerly we validated DataDir here, but now that's done
308 * Find oid and tablespace of the database we're about to open.
309 * Since we're not yet up and running we have to use the hackish
312 if (!FindMyDatabase(dbname, &MyDatabaseId, &MyDatabaseTableSpace))
314 (errcode(ERRCODE_UNDEFINED_DATABASE),
315 errmsg("database \"%s\" does not exist",
318 fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
320 /* Verify the database path */
322 if (access(fullpath, F_OK) == -1)
326 (errcode(ERRCODE_UNDEFINED_DATABASE),
327 errmsg("database \"%s\" does not exist",
329 errdetail("The database subdirectory \"%s\" is missing.",
333 (errcode_for_file_access(),
334 errmsg("could not access directory \"%s\": %m",
338 ValidatePgVersion(fullpath);
340 if (chdir(fullpath) == -1)
342 (errcode_for_file_access(),
343 errmsg("could not change directory to \"%s\": %m",
346 SetDatabasePath(fullpath);
350 * Code after this point assumes we are in the proper directory!
354 * Set up my per-backend PGPROC struct in shared memory. (We need
355 * to know MyDatabaseId before we can do this, since it's entered into
356 * the PGPROC struct.)
361 * Initialize my entry in the shared-invalidation manager's array of
362 * per-backend data. (Formerly this came before InitProcess, but now
363 * it must happen after, because it uses MyProc.) Once I have done
364 * this, I am visible to other backends!
366 * Sets up MyBackendId, a unique backend identifier.
368 MyBackendId = InvalidBackendId;
370 InitBackendSharedInvalidationState();
372 if (MyBackendId > MaxBackends || MyBackendId <= 0)
373 elog(FATAL, "bad backend id: %d", MyBackendId);
376 * Initialize local process's access to XLOG. In bootstrap case we
377 * may skip this since StartupXLOG() was run instead.
383 * Initialize the relation descriptor cache. This must create at
384 * least the minimum set of "nailed-in" cache entries. No catalog
385 * access happens here.
387 RelationCacheInitialize();
390 * Initialize all the system catalog caches. Note that no catalog
391 * access happens here; we only set up the cache structure.
395 /* Initialize portal manager */
396 EnablePortalManager();
398 /* start a new transaction here before access to db */
400 StartTransactionCommand();
403 * It's now possible to do real access to the system catalogs.
405 * Replace faked-up relcache entries with correct info.
407 RelationCacheInitializePhase2();
410 * Figure out our postgres user id. In standalone mode we use a fixed
411 * id, otherwise we figure it out from the authenticated user name.
414 InitializeSessionUserIdStandalone();
415 else if (!IsUnderPostmaster)
417 InitializeSessionUserIdStandalone();
418 if (!ThereIsAtLeastOneUser())
420 (errcode(ERRCODE_UNDEFINED_OBJECT),
421 errmsg("no users are defined in this database system"),
422 errhint("You should immediately run CREATE USER \"%s\" WITH SYSID %d CREATEUSER;.",
423 username, BOOTSTRAP_USESYSID)));
427 /* normal multiuser case */
428 InitializeSessionUserId(username);
432 * Unless we are bootstrapping, double-check that InitMyDatabaseInfo()
433 * got a correct result. We can't do this until all the
434 * database-access infrastructure is up.
437 ReverifyMyDatabase(dbname);
440 * Final phase of relation cache startup: write a new cache file if
441 * necessary. This is done after ReverifyMyDatabase to avoid writing
442 * a cache file into a dead database.
444 RelationCacheInitializePhase3();
447 * Check if user is a superuser.
452 am_superuser = superuser();
455 * Check a normal user hasn't connected to a superuser reserved slot.
458 ReservedBackends > 0 &&
459 !HaveNFreeProcs(ReservedBackends))
461 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
462 errmsg("connection limit exceeded for non-superusers")));
465 * Initialize various default states that can't be set up until we've
466 * selected the active user and done ReverifyMyDatabase.
469 /* set default namespace search path */
470 InitializeSearchPath();
472 /* initialize client encoding */
473 InitializeClientEncoding();
476 * Set up process-exit callback to do pre-shutdown cleanup. This
477 * should be last because we want shmem_exit to call this routine
478 * before the exit callbacks that are registered by buffer manager,
479 * lock manager, etc. We need to run this code before we close down
482 on_shmem_exit(ShutdownPostgres, 0);
484 /* close the transaction we started above */
486 CommitTransactionCommand();
492 * Backend-shutdown callback. Do cleanup that we want to be sure happens
493 * before all the supporting modules begin to nail their doors shut via
494 * their own callbacks. Note that because this has to be registered very
495 * late in startup, it will not get called if we suffer a failure *during*
498 * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
499 * via separate callbacks that execute before this one. We don't combine the
500 * callbacks because we still want this one to happen if the user-level
504 ShutdownPostgres(int code, Datum arg)
507 * These operations are really just a minimal subset of
508 * AbortTransaction(). We don't want to do any inessential cleanup,
509 * since that just raises the odds of failure --- but there's some
510 * stuff we need to do.
512 * Release any LW locks, buffer content locks, and buffer pins we might be
513 * holding. This is a kluge to improve the odds that we won't get into a
514 * self-made stuck-lock scenario while trying to shut down. We *must*
515 * release buffer pins to make it safe to do file deletion, since we
516 * might have some pins on pages of the target files.
519 AtProcExit_Buffers();
520 AtProcExit_LocalBuffers();
523 * In case a transaction is open, delete any files it created. This
524 * has to happen before bufmgr shutdown, so having smgr register a
525 * callback for it wouldn't work.
527 smgrDoPendingDeletes(false); /* delete as though aborting xact */
533 * Returns true if at least one user is defined in this database cluster.
536 ThereIsAtLeastOneUser(void)
538 Relation pg_shadow_rel;
542 pg_shadow_rel = heap_open(ShadowRelationId, AccessExclusiveLock);
544 scan = heap_beginscan(pg_shadow_rel, SnapshotNow, 0, NULL);
545 result = (heap_getnext(scan, ForwardScanDirection) != NULL);
548 heap_close(pg_shadow_rel, AccessExclusiveLock);