1 /*-------------------------------------------------------------------------
4 * postgres initialization utilities
6 * Portions Copyright (c) 1996-2001, 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.107 2002/06/11 13:40:52 wieck 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 if (!HeapTupleIsValid(tup) ||
102 tup->t_data->t_oid != MyDatabaseId)
105 heap_close(pgdbrel, AccessShareLock);
108 * The only real problem I could have created is to load dirty
109 * buffers for the dead database into shared buffer cache; if I
110 * did, some other backend will eventually try to write them and
111 * die in mdblindwrt. Flush any such pages to forestall trouble.
113 DropBuffers(MyDatabaseId);
114 /* Now I can commit hara-kiri with a clear conscience... */
115 elog(FATAL, "Database \"%s\", OID %u, has disappeared from pg_database",
120 * Also check that the database is currently allowing connections.
122 dbform = (Form_pg_database) GETSTRUCT(tup);
123 if (!dbform->datallowconn)
124 elog(FATAL, "Database \"%s\" is not currently accepting connections",
128 * OK, we're golden. Only other to-do item is to save the MULTIBYTE
129 * 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 if (dbform->encoding != PG_SQL_ASCII)
139 elog(FATAL, "database was initialized with MULTIBYTE encoding %d,\n\tbut the backend was compiled without multibyte support.\n\tlooks like you need to initdb or recompile.",
144 * Set up database-specific configuration variables.
146 if (IsUnderPostmaster)
151 datum = heap_getattr(tup, Anum_pg_database_datconfig,
152 RelationGetDescr(pgdbrel), &isnull);
155 ArrayType *a = DatumGetArrayTypeP(datum);
157 ProcessGUCArray(a, PGC_S_DATABASE);
161 heap_endscan(pgdbscan);
162 heap_close(pgdbrel, AccessShareLock);
167 /* --------------------------------
170 * This routine initializes stuff needed for ipc, locking, etc.
171 * it should be called something more informative.
172 * --------------------------------
175 InitCommunication(void)
178 * initialize shared memory and semaphores appropriately.
180 if (!IsUnderPostmaster) /* postmaster already did this */
183 * we're running a postgres backend by itself with no front end or
184 * postmaster. Create private "shmem" and semaphores. Setting
185 * MaxBackends = 16 is arbitrary.
187 CreateSharedMemoryAndSemaphores(true, 16, 0);
193 * Early initialization of a backend (either standalone or under postmaster).
194 * This happens even before InitPostgres.
196 * If you're wondering why this is separate from InitPostgres at all:
197 * the critical distinction is that this stuff has to happen before we can
198 * run XLOG-related initialization, which is done before InitPostgres --- in
199 * fact, for cases such as checkpoint creation processes, InitPostgres may
200 * never be done at all.
206 * Attach to shared memory and semaphores, and initialize our
207 * input/output/debugging file descriptors.
212 /* Do local initialization of storage and buffer managers */
214 InitBufferPoolAccess();
219 /* --------------------------------
221 * Initialize POSTGRES.
224 * Be very careful with the order of calls in the InitPostgres function.
225 * --------------------------------
228 InitPostgres(const char *dbname, const char *username)
230 bool bootstrap = IsBootstrapProcessingMode();
233 * Set up the global variables holding database name, id, and path.
235 * We take a shortcut in the bootstrap case, otherwise we have to look up
236 * the db name in pg_database.
238 SetDatabaseName(dbname);
242 MyDatabaseId = TemplateDbOid;
243 SetDatabasePath(GetDatabasePath(MyDatabaseId));
251 * Formerly we validated DataDir here, but now that's done
256 * Find oid and path of the database we're about to open. Since
257 * we're not yet up and running we have to use the hackish
258 * GetRawDatabaseInfo.
260 GetRawDatabaseInfo(dbname, &MyDatabaseId, datpath);
262 if (!OidIsValid(MyDatabaseId))
264 "Database \"%s\" does not exist in the system catalog.",
267 fullpath = GetDatabasePath(MyDatabaseId);
269 /* Verify the database path */
271 if (access(fullpath, F_OK) == -1)
272 elog(FATAL, "Database \"%s\" does not exist.\n\t"
273 "The database subdirectory '%s' is missing.",
276 ValidatePgVersion(fullpath);
278 if (chdir(fullpath) == -1)
279 elog(FATAL, "Unable to change directory to '%s': %m", fullpath);
281 SetDatabasePath(fullpath);
285 * Code after this point assumes we are in the proper directory!
289 * Set up my per-backend PGPROC struct in shared memory. (We need to
290 * know MyDatabaseId before we can do this, since it's entered into
291 * the PGPROC struct.)
296 * Initialize my entry in the shared-invalidation manager's array of
297 * per-backend data. (Formerly this came before InitProcess, but now
298 * it must happen after, because it uses MyProc.) Once I have done
299 * this, I am visible to other backends!
301 * Sets up MyBackendId, a unique backend identifier.
303 MyBackendId = InvalidBackendId;
305 InitBackendSharedInvalidationState();
307 if (MyBackendId > MaxBackends || MyBackendId <= 0)
308 elog(FATAL, "InitPostgres: bad backend id %d", MyBackendId);
311 * Initialize the transaction system override state.
313 AmiTransactionOverride(bootstrap);
316 * Initialize the relation descriptor cache. This must create
317 * at least the minimum set of "nailed-in" cache entries. No
318 * catalog access happens here.
320 RelationCacheInitialize();
323 * Initialize all the system catalog caches. Note that no catalog
324 * access happens here; we only set up the cache structure.
328 /* Initialize portal manager */
329 EnablePortalManager();
332 * Initialize the deferred trigger manager --- must happen before
333 * first transaction start.
335 DeferredTriggerInit();
337 /* start a new transaction here before access to db */
339 StartTransactionCommand();
342 * It's now possible to do real access to the system catalogs.
344 * Replace faked-up relcache entries with correct info.
346 RelationCacheInitializePhase2();
349 * Figure out our postgres user id. In standalone mode we use a fixed
350 * id, otherwise we figure it out from the authenticated user name.
353 InitializeSessionUserIdStandalone();
354 else if (!IsUnderPostmaster)
356 InitializeSessionUserIdStandalone();
357 if (!ThereIsAtLeastOneUser())
359 elog(WARNING, "There are currently no users defined in this database system.");
360 elog(WARNING, "You should immediately run 'CREATE USER \"%s\" WITH SYSID %d CREATEUSER;'.",
361 username, BOOTSTRAP_USESYSID);
366 /* normal multiuser case */
367 InitializeSessionUserId(username);
371 * Unless we are bootstrapping, double-check that InitMyDatabaseInfo()
372 * got a correct result. We can't do this until all the
373 * database-access infrastructure is up.
376 ReverifyMyDatabase(dbname);
379 * Final phase of relation cache startup: write a new cache file
380 * if necessary. This is done after ReverifyMyDatabase to avoid
381 * writing a cache file into a dead database.
383 RelationCacheInitializePhase3();
386 * Initialize various default states that can't be set up until
387 * we've selected the active user and done ReverifyMyDatabase.
390 /* set default namespace search path */
391 InitializeSearchPath();
394 * Set up process-exit callback to do pre-shutdown cleanup. This should
395 * be last because we want shmem_exit to call this routine before the exit
396 * callbacks that are registered by buffer manager, lock manager, etc.
397 * We need to run this code before we close down database access!
399 on_shmem_exit(ShutdownPostgres, 0);
401 /* close the transaction we started above */
403 CommitTransactionCommand();
407 * Backend-shutdown callback. Do cleanup that we want to be sure happens
408 * before all the supporting modules begin to nail their doors shut via
409 * their own callbacks. Note that because this has to be registered very
410 * late in startup, it will not get called if we suffer a failure *during*
413 * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
414 * via separate callbacks that execute before this one. We don't combine the
415 * callbacks because we still want this one to happen if the user-level
419 ShutdownPostgres(void)
422 * These operations are really just a minimal subset of
423 * AbortTransaction(). We don't want to do any inessential cleanup,
424 * since that just raises the odds of failure --- but there's some
425 * stuff we need to do.
427 * Release any LW locks and buffer context locks we might be holding.
428 * This is a kluge to improve the odds that we won't get into a
429 * self-made stuck-lock scenario while trying to shut down.
436 * In case a transaction is open, delete any files it created. This
437 * has to happen before bufmgr shutdown, so having smgr register a
438 * callback for it wouldn't work.
440 smgrDoPendingDeletes(false); /* delete as though aborting xact */
446 * Returns true if at least one user is defined in this database cluster.
449 ThereIsAtLeastOneUser(void)
451 Relation pg_shadow_rel;
452 TupleDesc pg_shadow_dsc;
456 pg_shadow_rel = heap_openr(ShadowRelationName, AccessExclusiveLock);
457 pg_shadow_dsc = RelationGetDescr(pg_shadow_rel);
459 scan = heap_beginscan(pg_shadow_rel, SnapshotNow, 0, NULL);
460 result = (heap_getnext(scan, ForwardScanDirection) != NULL);
463 heap_close(pg_shadow_rel, AccessExclusiveLock);