1 /*-------------------------------------------------------------------------
4 * postgres initialization utilities
6 * Portions Copyright (c) 1996-2002, 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.111 2002/08/29 21:02:12 momjian Exp $
14 *-------------------------------------------------------------------------
20 #include <sys/types.h>
24 #include "catalog/catalog.h"
25 #include "access/heapam.h"
26 #include "catalog/catname.h"
27 #include "catalog/namespace.h"
28 #include "catalog/pg_database.h"
29 #include "catalog/pg_shadow.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
73 * of pg_database, if we are in MULTIBYTE mode.
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, Anum_pg_database_datname,
96 F_NAMEEQ, NameGetDatum(name));
98 pgdbscan = heap_beginscan(pgdbrel, SnapshotNow, 1, &key);
100 tup = heap_getnext(pgdbscan, ForwardScanDirection);
101 AssertTupleDescHasOid(pgdbrel->rd_att);
102 if (!HeapTupleIsValid(tup) ||
103 HeapTupleGetOid(tup) != MyDatabaseId)
106 heap_close(pgdbrel, AccessShareLock);
109 * The only real problem I could have created is to load dirty
110 * buffers for the dead database into shared buffer cache; if I
111 * did, some other backend will eventually try to write them and
112 * die in mdblindwrt. Flush any such pages to forestall trouble.
114 DropBuffers(MyDatabaseId);
115 /* Now I can commit hara-kiri with a clear conscience... */
116 elog(FATAL, "Database \"%s\", OID %u, has disappeared from pg_database",
121 * Also check that the database is currently allowing connections.
123 dbform = (Form_pg_database) GETSTRUCT(tup);
124 if (!dbform->datallowconn)
125 elog(FATAL, "Database \"%s\" is not currently accepting connections",
129 * OK, we're golden. Only other to-do item is to save the MULTIBYTE
130 * encoding info out of the pg_database tuple --- or complain, if we
133 SetDatabaseEncoding(dbform->encoding);
134 /* If we have no other source of client_encoding, use server encoding */
135 SetConfigOption("client_encoding", GetDatabaseEncodingName(),
136 PGC_BACKEND, PGC_S_DEFAULT);
138 * Set up database-specific configuration variables.
140 if (IsUnderPostmaster)
145 datum = heap_getattr(tup, Anum_pg_database_datconfig,
146 RelationGetDescr(pgdbrel), &isnull);
149 ArrayType *a = DatumGetArrayTypeP(datum);
151 ProcessGUCArray(a, PGC_S_DATABASE);
155 heap_endscan(pgdbscan);
156 heap_close(pgdbrel, AccessShareLock);
161 /* --------------------------------
164 * This routine initializes stuff needed for ipc, locking, etc.
165 * it should be called something more informative.
166 * --------------------------------
169 InitCommunication(void)
172 * initialize shared memory and semaphores appropriately.
174 if (!IsUnderPostmaster) /* postmaster already did this */
177 * we're running a postgres backend by itself with no front end or
178 * postmaster. Create private "shmem" and semaphores. Setting
179 * MaxBackends = 16 is arbitrary.
181 CreateSharedMemoryAndSemaphores(true, 16, 0);
187 * Early initialization of a backend (either standalone or under postmaster).
188 * This happens even before InitPostgres.
190 * If you're wondering why this is separate from InitPostgres at all:
191 * the critical distinction is that this stuff has to happen before we can
192 * run XLOG-related initialization, which is done before InitPostgres --- in
193 * fact, for cases such as checkpoint creation processes, InitPostgres may
194 * never be done at all.
200 * Attach to shared memory and semaphores, and initialize our
201 * input/output/debugging file descriptors.
206 /* Do local initialization of storage and buffer managers */
208 InitBufferPoolAccess();
213 /* --------------------------------
215 * Initialize POSTGRES.
218 * Be very careful with the order of calls in the InitPostgres function.
219 * --------------------------------
222 InitPostgres(const char *dbname, const char *username)
224 bool bootstrap = IsBootstrapProcessingMode();
227 * Set up the global variables holding database name, id, and path.
229 * We take a shortcut in the bootstrap case, otherwise we have to look up
230 * the db name in pg_database.
232 SetDatabaseName(dbname);
236 MyDatabaseId = TemplateDbOid;
237 SetDatabasePath(GetDatabasePath(MyDatabaseId));
245 * Formerly we validated DataDir here, but now that's done
250 * Find oid and path of the database we're about to open. Since
251 * we're not yet up and running we have to use the hackish
252 * GetRawDatabaseInfo.
254 GetRawDatabaseInfo(dbname, &MyDatabaseId, datpath);
256 if (!OidIsValid(MyDatabaseId))
258 "Database \"%s\" does not exist in the system catalog.",
261 fullpath = GetDatabasePath(MyDatabaseId);
263 /* Verify the database path */
265 if (access(fullpath, F_OK) == -1)
266 elog(FATAL, "Database \"%s\" does not exist.\n\t"
267 "The database subdirectory '%s' is missing.",
270 ValidatePgVersion(fullpath);
272 if (chdir(fullpath) == -1)
273 elog(FATAL, "Unable to change directory to '%s': %m", fullpath);
275 SetDatabasePath(fullpath);
279 * Code after this point assumes we are in the proper directory!
283 * Set up my per-backend PGPROC struct in shared memory. (We need to
284 * know MyDatabaseId before we can do this, since it's entered into
285 * the PGPROC struct.)
290 * Initialize my entry in the shared-invalidation manager's array of
291 * per-backend data. (Formerly this came before InitProcess, but now
292 * it must happen after, because it uses MyProc.) Once I have done
293 * this, I am visible to other backends!
295 * Sets up MyBackendId, a unique backend identifier.
297 MyBackendId = InvalidBackendId;
299 InitBackendSharedInvalidationState();
301 if (MyBackendId > MaxBackends || MyBackendId <= 0)
302 elog(FATAL, "InitPostgres: bad backend id %d", MyBackendId);
305 * Initialize the transaction system override state.
307 AmiTransactionOverride(bootstrap);
310 * Initialize the relation descriptor cache. This must create
311 * at least the minimum set of "nailed-in" cache entries. No
312 * catalog access happens here.
314 RelationCacheInitialize();
317 * Initialize all the system catalog caches. Note that no catalog
318 * access happens here; we only set up the cache structure.
322 /* Initialize portal manager */
323 EnablePortalManager();
326 * Initialize the deferred trigger manager --- must happen before
327 * first transaction start.
329 DeferredTriggerInit();
331 /* start a new transaction here before access to db */
333 StartTransactionCommand();
336 * It's now possible to do real access to the system catalogs.
338 * Replace faked-up relcache entries with correct info.
340 RelationCacheInitializePhase2();
343 * Figure out our postgres user id. In standalone mode we use a fixed
344 * id, otherwise we figure it out from the authenticated user name.
347 InitializeSessionUserIdStandalone();
348 else if (!IsUnderPostmaster)
350 InitializeSessionUserIdStandalone();
351 if (!ThereIsAtLeastOneUser())
353 elog(WARNING, "There are currently no users defined in this database system.");
354 elog(WARNING, "You should immediately run 'CREATE USER \"%s\" WITH SYSID %d CREATEUSER;'.",
355 username, BOOTSTRAP_USESYSID);
360 /* normal multiuser case */
361 InitializeSessionUserId(username);
365 * Unless we are bootstrapping, double-check that InitMyDatabaseInfo()
366 * got a correct result. We can't do this until all the
367 * database-access infrastructure is up.
370 ReverifyMyDatabase(dbname);
373 * Final phase of relation cache startup: write a new cache file
374 * if necessary. This is done after ReverifyMyDatabase to avoid
375 * writing a cache file into a dead database.
377 RelationCacheInitializePhase3();
380 * Initialize various default states that can't be set up until
381 * we've selected the active user and done ReverifyMyDatabase.
384 /* set default namespace search path */
385 InitializeSearchPath();
388 * Set up process-exit callback to do pre-shutdown cleanup. This should
389 * be last because we want shmem_exit to call this routine before the exit
390 * callbacks that are registered by buffer manager, lock manager, etc.
391 * We need to run this code before we close down database access!
393 on_shmem_exit(ShutdownPostgres, 0);
395 /* close the transaction we started above */
397 CommitTransactionCommand();
400 * Check a normal user hasn't connected to a superuser reserved slot.
401 * Do this here since we need the user information and that only happens
402 * after we've started bringing the shared memory online. So we wait
403 * until we've registered exit handlers and potentially shut an open
404 * transaction down for an as safety conscious rejection as possible.
406 if (CountEmptyBackendSlots() < ReservedBackends && !superuser())
407 elog(ERROR, "Non-superuser connection limit exceeded");
411 * Backend-shutdown callback. Do cleanup that we want to be sure happens
412 * before all the supporting modules begin to nail their doors shut via
413 * their own callbacks. Note that because this has to be registered very
414 * late in startup, it will not get called if we suffer a failure *during*
417 * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
418 * via separate callbacks that execute before this one. We don't combine the
419 * callbacks because we still want this one to happen if the user-level
423 ShutdownPostgres(void)
426 * These operations are really just a minimal subset of
427 * AbortTransaction(). We don't want to do any inessential cleanup,
428 * since that just raises the odds of failure --- but there's some
429 * stuff we need to do.
431 * Release any LW locks and buffer context locks we might be holding.
432 * This is a kluge to improve the odds that we won't get into a
433 * self-made stuck-lock scenario while trying to shut down.
440 * In case a transaction is open, delete any files it created. This
441 * has to happen before bufmgr shutdown, so having smgr register a
442 * callback for it wouldn't work.
444 smgrDoPendingDeletes(false); /* delete as though aborting xact */
450 * Returns true if at least one user is defined in this database cluster.
453 ThereIsAtLeastOneUser(void)
455 Relation pg_shadow_rel;
456 TupleDesc pg_shadow_dsc;
460 pg_shadow_rel = heap_openr(ShadowRelationName, AccessExclusiveLock);
461 pg_shadow_dsc = RelationGetDescr(pg_shadow_rel);
463 scan = heap_beginscan(pg_shadow_rel, SnapshotNow, 0, NULL);
464 result = (heap_getnext(scan, ForwardScanDirection) != NULL);
467 heap_close(pg_shadow_rel, AccessExclusiveLock);