1 /*-------------------------------------------------------------------------
4 * postgres initialization utilities
6 * Portions Copyright (c) 1996-2003, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $Header: /cvsroot/pgsql/src/backend/utils/init/postinit.c,v 1.128 2003/11/09 21:30:37 tgl Exp $
14 *-------------------------------------------------------------------------
23 #include "catalog/catalog.h"
24 #include "access/heapam.h"
25 #include "catalog/catname.h"
26 #include "catalog/namespace.h"
27 #include "catalog/pg_database.h"
28 #include "catalog/pg_shadow.h"
29 #include "catalog/pg_type.h"
30 #include "commands/trigger.h"
31 #include "mb/pg_wchar.h"
32 #include "miscadmin.h"
33 #include "storage/backendid.h"
34 #include "storage/ipc.h"
35 #include "storage/proc.h"
36 #include "storage/sinval.h"
37 #include "storage/smgr.h"
38 #include "utils/fmgroids.h"
39 #include "utils/guc.h"
40 #include "utils/portal.h"
41 #include "utils/relcache.h"
42 #include "utils/syscache.h"
45 static void ReverifyMyDatabase(const char *name);
46 static void InitCommunication(void);
47 static void ShutdownPostgres(void);
48 static bool ThereIsAtLeastOneUser(void);
51 /*** InitPostgres support ***/
54 /* --------------------------------
57 * Since we are forced to fetch the database OID out of pg_database without
58 * benefit of locking or transaction ID checking (see utils/misc/database.c),
59 * we might have gotten a wrong answer. Or, we might have attached to a
60 * database that's in process of being destroyed by destroydb(). This
61 * routine is called after we have all the locking and other infrastructure
62 * running --- now we can check that we are really attached to a valid
65 * In reality, if destroydb() is running in parallel with our startup,
66 * it's pretty likely that we will have failed before now, due to being
67 * unable to read some of the system tables within the doomed database.
68 * This routine just exists to make *sure* we have not started up in an
69 * invalid database. If we quit now, we should have managed to avoid
70 * creating any serious problems.
72 * This is also a handy place to fetch the database encoding info out
75 * To avoid having to read pg_database more times than necessary
76 * during session startup, this place is also fitting to set up any
77 * database-specific configuration variables.
78 * --------------------------------
81 ReverifyMyDatabase(const char *name)
84 HeapScanDesc pgdbscan;
87 Form_pg_database dbform;
90 * Because we grab AccessShareLock here, we can be sure that destroydb
91 * is not running in parallel with us (any more).
93 pgdbrel = heap_openr(DatabaseRelationName, AccessShareLock);
95 ScanKeyEntryInitialize(&key, 0,
96 Anum_pg_database_datname,
97 BTEqualStrategyNumber, F_NAMEEQ,
98 NameGetDatum(name), NAMEOID);
100 pgdbscan = heap_beginscan(pgdbrel, SnapshotNow, 1, &key);
102 tup = heap_getnext(pgdbscan, ForwardScanDirection);
103 if (!HeapTupleIsValid(tup) ||
104 HeapTupleGetOid(tup) != MyDatabaseId)
107 heap_close(pgdbrel, AccessShareLock);
110 * The only real problem I could have created is to load dirty
111 * buffers for the dead database into shared buffer cache; if I
112 * did, some other backend will eventually try to write them and
113 * die in mdblindwrt. Flush any such pages to forestall trouble.
115 DropBuffers(MyDatabaseId);
116 /* Now I can commit hara-kiri with a clear conscience... */
118 (errcode(ERRCODE_UNDEFINED_DATABASE),
119 errmsg("database \"%s\", OID %u, has disappeared from pg_database",
120 name, MyDatabaseId)));
124 * Also check that the database is currently allowing connections.
126 dbform = (Form_pg_database) GETSTRUCT(tup);
127 if (!dbform->datallowconn)
129 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
130 errmsg("database \"%s\" is not currently accepting connections",
134 * OK, we're golden. Only other to-do item is to save the encoding
135 * info out of the pg_database tuple.
137 SetDatabaseEncoding(dbform->encoding);
138 /* Record it as a GUC internal option, too */
139 SetConfigOption("server_encoding", GetDatabaseEncodingName(),
140 PGC_INTERNAL, PGC_S_OVERRIDE);
141 /* If we have no other source of client_encoding, use server encoding */
142 SetConfigOption("client_encoding", GetDatabaseEncodingName(),
143 PGC_BACKEND, PGC_S_DEFAULT);
146 * Set up database-specific configuration variables.
148 if (IsUnderPostmaster)
153 datum = heap_getattr(tup, Anum_pg_database_datconfig,
154 RelationGetDescr(pgdbrel), &isnull);
157 ArrayType *a = DatumGetArrayTypeP(datum);
159 ProcessGUCArray(a, PGC_S_DATABASE);
163 heap_endscan(pgdbscan);
164 heap_close(pgdbrel, AccessShareLock);
169 /* --------------------------------
172 * This routine initializes stuff needed for ipc, locking, etc.
173 * it should be called something more informative.
174 * --------------------------------
177 InitCommunication(void)
180 * initialize shared memory and semaphores appropriately.
182 if (!IsUnderPostmaster) /* postmaster already did this */
185 * We're running a postgres bootstrap process or a standalone
186 * backend. Create private "shmem" and semaphores.
188 CreateSharedMemoryAndSemaphores(true, MaxBackends, 0);
194 * Early initialization of a backend (either standalone or under postmaster).
195 * This happens even before InitPostgres.
197 * If you're wondering why this is separate from InitPostgres at all:
198 * the critical distinction is that this stuff has to happen before we can
199 * run XLOG-related initialization, which is done before InitPostgres --- in
200 * fact, for cases such as checkpoint creation processes, InitPostgres may
201 * never be done at all.
207 * Attach to shared memory and semaphores, and initialize our
208 * input/output/debugging file descriptors.
213 /* Do local initialization of storage and buffer managers */
215 InitBufferPoolAccess();
220 /* --------------------------------
222 * Initialize POSTGRES.
225 * Be very careful with the order of calls in the InitPostgres function.
226 * --------------------------------
229 InitPostgres(const char *dbname, const char *username)
231 bool bootstrap = IsBootstrapProcessingMode();
234 * Set up the global variables holding database id and path.
236 * We take a shortcut in the bootstrap case, otherwise we have to look up
237 * the db name in pg_database.
241 MyDatabaseId = TemplateDbOid;
242 SetDatabasePath(GetDatabasePath(MyDatabaseId));
250 * Formerly we validated DataDir here, but now that's done
255 * Find oid and path of the database we're about to open. Since
256 * we're not yet up and running we have to use the hackish
257 * GetRawDatabaseInfo.
259 GetRawDatabaseInfo(dbname, &MyDatabaseId, datpath);
261 if (!OidIsValid(MyDatabaseId))
263 (errcode(ERRCODE_UNDEFINED_DATABASE),
264 errmsg("database \"%s\" does not exist",
267 fullpath = GetDatabasePath(MyDatabaseId);
269 /* Verify the database path */
271 if (access(fullpath, F_OK) == -1)
275 (errcode(ERRCODE_UNDEFINED_DATABASE),
276 errmsg("database \"%s\" does not exist",
278 errdetail("The database subdirectory \"%s\" is missing.",
282 (errcode_for_file_access(),
283 errmsg("could not access directory \"%s\": %m",
287 ValidatePgVersion(fullpath);
289 if (chdir(fullpath) == -1)
291 (errcode_for_file_access(),
292 errmsg("could not change directory to \"%s\": %m",
295 SetDatabasePath(fullpath);
299 * Code after this point assumes we are in the proper directory!
303 * Set up my per-backend PGPROC struct in shared memory. (We need
304 * to know MyDatabaseId before we can do this, since it's entered into
305 * the PGPROC struct.)
310 * Initialize my entry in the shared-invalidation manager's array of
311 * per-backend data. (Formerly this came before InitProcess, but now
312 * it must happen after, because it uses MyProc.) Once I have done
313 * this, I am visible to other backends!
315 * Sets up MyBackendId, a unique backend identifier.
317 MyBackendId = InvalidBackendId;
319 InitBackendSharedInvalidationState();
321 if (MyBackendId > MaxBackends || MyBackendId <= 0)
322 elog(FATAL, "bad backend id: %d", MyBackendId);
325 * Initialize the transaction system override state.
327 AmiTransactionOverride(bootstrap);
330 * Initialize the relation descriptor cache. This must create at
331 * least the minimum set of "nailed-in" cache entries. No catalog
332 * access happens here.
334 RelationCacheInitialize();
337 * Initialize all the system catalog caches. Note that no catalog
338 * access happens here; we only set up the cache structure.
342 /* Initialize portal manager */
343 EnablePortalManager();
346 * Initialize the deferred trigger manager --- must happen before
347 * first transaction start.
349 DeferredTriggerInit();
351 /* start a new transaction here before access to db */
353 StartTransactionCommand();
356 * It's now possible to do real access to the system catalogs.
358 * Replace faked-up relcache entries with correct info.
360 RelationCacheInitializePhase2();
363 * Figure out our postgres user id. In standalone mode we use a fixed
364 * id, otherwise we figure it out from the authenticated user name.
367 InitializeSessionUserIdStandalone();
368 else if (!IsUnderPostmaster)
370 InitializeSessionUserIdStandalone();
371 if (!ThereIsAtLeastOneUser())
373 (errcode(ERRCODE_UNDEFINED_OBJECT),
374 errmsg("no users are defined in this database system"),
375 errhint("You should immediately run CREATE USER \"%s\" WITH SYSID %d CREATEUSER;.",
376 username, BOOTSTRAP_USESYSID)));
380 /* normal multiuser case */
381 InitializeSessionUserId(username);
385 * Unless we are bootstrapping, double-check that InitMyDatabaseInfo()
386 * got a correct result. We can't do this until all the
387 * database-access infrastructure is up.
390 ReverifyMyDatabase(dbname);
393 * Final phase of relation cache startup: write a new cache file if
394 * necessary. This is done after ReverifyMyDatabase to avoid writing
395 * a cache file into a dead database.
397 RelationCacheInitializePhase3();
400 * Check a normal user hasn't connected to a superuser reserved slot.
401 * We can't do this till after we've read the user information, and we
402 * must do it inside a transaction since checking superuserness may
403 * require database access. The superuser check is probably the most
404 * expensive part; don't do it until necessary.
406 if (ReservedBackends > 0 &&
407 CountEmptyBackendSlots() < ReservedBackends &&
410 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
411 errmsg("connection limit exceeded for non-superusers")));
414 * Initialize various default states that can't be set up until we've
415 * selected the active user and done ReverifyMyDatabase.
418 /* set default namespace search path */
419 InitializeSearchPath();
421 /* initialize client encoding */
422 InitializeClientEncoding();
425 * Now all default states are fully set up. Report them to client if
428 BeginReportingGUCOptions();
431 * Set up process-exit callback to do pre-shutdown cleanup. This
432 * should be last because we want shmem_exit to call this routine
433 * before the exit callbacks that are registered by buffer manager,
434 * lock manager, etc. We need to run this code before we close down
437 on_shmem_exit(ShutdownPostgres, 0);
439 /* close the transaction we started above */
441 CommitTransactionCommand();
445 * Backend-shutdown callback. Do cleanup that we want to be sure happens
446 * before all the supporting modules begin to nail their doors shut via
447 * their own callbacks. Note that because this has to be registered very
448 * late in startup, it will not get called if we suffer a failure *during*
451 * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
452 * via separate callbacks that execute before this one. We don't combine the
453 * callbacks because we still want this one to happen if the user-level
457 ShutdownPostgres(void)
460 * These operations are really just a minimal subset of
461 * AbortTransaction(). We don't want to do any inessential cleanup,
462 * since that just raises the odds of failure --- but there's some
463 * stuff we need to do.
465 * Release any LW locks and buffer context locks we might be holding.
466 * This is a kluge to improve the odds that we won't get into a
467 * self-made stuck-lock scenario while trying to shut down.
474 * In case a transaction is open, delete any files it created. This
475 * has to happen before bufmgr shutdown, so having smgr register a
476 * callback for it wouldn't work.
478 smgrDoPendingDeletes(false); /* delete as though aborting xact */
484 * Returns true if at least one user is defined in this database cluster.
487 ThereIsAtLeastOneUser(void)
489 Relation pg_shadow_rel;
490 TupleDesc pg_shadow_dsc;
494 pg_shadow_rel = heap_openr(ShadowRelationName, AccessExclusiveLock);
495 pg_shadow_dsc = RelationGetDescr(pg_shadow_rel);
497 scan = heap_beginscan(pg_shadow_rel, SnapshotNow, 0, NULL);
498 result = (heap_getnext(scan, ForwardScanDirection) != NULL);
501 heap_close(pg_shadow_rel, AccessExclusiveLock);