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.93 2001/09/29 04:02:25 tgl 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/pg_database.h"
28 #include "catalog/pg_shadow.h"
29 #include "commands/trigger.h"
30 #include "commands/variable.h" /* for set_default_client_encoding() */
31 #include "mb/pg_wchar.h"
32 #include "miscadmin.h"
33 #include "storage/backendid.h"
34 #include "storage/proc.h"
35 #include "storage/sinval.h"
36 #include "storage/smgr.h"
37 #include "utils/fmgroids.h"
38 #include "utils/portal.h"
39 #include "utils/relcache.h"
40 #include "utils/syscache.h"
41 #include "utils/temprel.h"
44 static void ReverifyMyDatabase(const char *name);
45 static void InitCommunication(void);
46 static void ShutdownPostgres(void);
47 static bool ThereIsAtLeastOneUser(void);
50 /*** InitPostgres support ***/
53 /* --------------------------------
56 * Since we are forced to fetch the database OID out of pg_database without
57 * benefit of locking or transaction ID checking (see utils/misc/database.c),
58 * we might have gotten a wrong answer. Or, we might have attached to a
59 * database that's in process of being destroyed by destroydb(). This
60 * routine is called after we have all the locking and other infrastructure
61 * running --- now we can check that we are really attached to a valid
64 * In reality, if destroydb() is running in parallel with our startup,
65 * it's pretty likely that we will have failed before now, due to being
66 * unable to read some of the system tables within the doomed database.
67 * This routine just exists to make *sure* we have not started up in an
68 * invalid database. If we quit now, we should have managed to avoid
69 * creating any serious problems.
71 * This is also a handy place to fetch the database encoding info out
72 * of pg_database, if we are in MULTIBYTE mode.
73 * --------------------------------
76 ReverifyMyDatabase(const char *name)
79 HeapScanDesc pgdbscan;
82 Form_pg_database dbform;
85 * Because we grab AccessShareLock here, we can be sure that destroydb
86 * is not running in parallel with us (any more).
88 pgdbrel = heap_openr(DatabaseRelationName, AccessShareLock);
90 ScanKeyEntryInitialize(&key, 0, Anum_pg_database_datname,
91 F_NAMEEQ, NameGetDatum(name));
93 pgdbscan = heap_beginscan(pgdbrel, 0, SnapshotNow, 1, &key);
95 tup = heap_getnext(pgdbscan, 0);
96 if (!HeapTupleIsValid(tup) ||
97 tup->t_data->t_oid != MyDatabaseId)
100 heap_close(pgdbrel, AccessShareLock);
103 * The only real problem I could have created is to load dirty
104 * buffers for the dead database into shared buffer cache; if I
105 * did, some other backend will eventually try to write them and
106 * die in mdblindwrt. Flush any such pages to forestall trouble.
108 DropBuffers(MyDatabaseId);
109 /* Now I can commit hara-kiri with a clear conscience... */
110 elog(FATAL, "Database \"%s\", OID %u, has disappeared from pg_database",
115 * Also check that the database is currently allowing connections.
117 dbform = (Form_pg_database) GETSTRUCT(tup);
118 if (!dbform->datallowconn)
119 elog(FATAL, "Database \"%s\" is not currently accepting connections",
123 * OK, we're golden. Only other to-do item is to save the MULTIBYTE
124 * encoding info out of the pg_database tuple --- or complain, if we
128 SetDatabaseEncoding(dbform->encoding);
130 if (dbform->encoding != PG_SQL_ASCII)
131 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.",
135 heap_endscan(pgdbscan);
136 heap_close(pgdbrel, AccessShareLock);
141 /* --------------------------------
144 * This routine initializes stuff needed for ipc, locking, etc.
145 * it should be called something more informative.
146 * --------------------------------
149 InitCommunication(void)
152 * initialize shared memory and semaphores appropriately.
154 if (!IsUnderPostmaster) /* postmaster already did this */
157 * we're running a postgres backend by itself with no front end or
158 * postmaster. Create private "shmem" and semaphores. Setting
159 * MaxBackends = 16 is arbitrary.
161 CreateSharedMemoryAndSemaphores(true, 16);
167 * Early initialization of a backend (either standalone or under postmaster).
168 * This happens even before InitPostgres.
170 * If you're wondering why this is separate from InitPostgres at all:
171 * the critical distinction is that this stuff has to happen before we can
172 * run XLOG-related initialization, which is done before InitPostgres --- in
173 * fact, for cases such as checkpoint creation processes, InitPostgres may
174 * never be done at all.
180 * Attach to shared memory and semaphores, and initialize our
181 * input/output/debugging file descriptors.
186 /* Do local initialization of storage and buffer managers */
188 InitBufferPoolAccess();
193 /* --------------------------------
195 * Initialize POSTGRES.
198 * Be very careful with the order of calls in the InitPostgres function.
199 * --------------------------------
202 InitPostgres(const char *dbname, const char *username)
204 bool bootstrap = IsBootstrapProcessingMode();
207 * Set up the global variables holding database name, id, and path.
209 * We take a shortcut in the bootstrap case, otherwise we have to look up
210 * the db name in pg_database.
212 SetDatabaseName(dbname);
216 MyDatabaseId = TemplateDbOid;
217 SetDatabasePath(GetDatabasePath(MyDatabaseId));
224 /* Verify if DataDir is ok */
225 if (access(DataDir, F_OK) == -1)
226 elog(FATAL, "Database system not found.\n\t"
227 "Data directory '%s' does not exist.",
230 ValidatePgVersion(DataDir);
233 * Find oid and path of the database we're about to open. Since
234 * we're not yet up and running we have to use the hackish
235 * GetRawDatabaseInfo.
237 GetRawDatabaseInfo(dbname, &MyDatabaseId, datpath);
239 if (!OidIsValid(MyDatabaseId))
241 "Database \"%s\" does not exist in the system catalog.",
244 fullpath = GetDatabasePath(MyDatabaseId);
246 /* Verify the database path */
248 if (access(fullpath, F_OK) == -1)
249 elog(FATAL, "Database \"%s\" does not exist.\n\t"
250 "The database subdirectory '%s' is missing.",
253 ValidatePgVersion(fullpath);
255 if (chdir(fullpath) == -1)
256 elog(FATAL, "Unable to change directory to '%s': %m", fullpath);
258 SetDatabasePath(fullpath);
262 * Code after this point assumes we are in the proper directory!
266 * Set up my per-backend PROC struct in shared memory. (We need to
267 * know MyDatabaseId before we can do this, since it's entered into
273 * Initialize my entry in the shared-invalidation manager's array of
274 * per-backend data. (Formerly this came before InitProcess, but now
275 * it must happen after, because it uses MyProc.) Once I have done
276 * this, I am visible to other backends!
278 * Sets up MyBackendId, a unique backend identifier.
280 MyBackendId = InvalidBackendId;
282 InitBackendSharedInvalidationState();
284 if (MyBackendId > MaxBackends || MyBackendId <= 0)
285 elog(FATAL, "InitPostgres: bad backend id %d", MyBackendId);
288 * Initialize the transaction system override state.
290 AmiTransactionOverride(bootstrap);
293 * Initialize the relation descriptor cache.
294 * The pre-allocated reldescs are created here.
296 RelationCacheInitialize();
299 * Initialize the access methods. Does not touch files (?) - thomas
305 * Initialize all the system catalog caches.
307 * Does not touch files since all routines are builtins (?) - thomas
312 /* Initialize portal manager */
313 EnablePortalManager();
316 * Initialize the deferred trigger manager --- must happen before
317 * first transaction start.
319 DeferredTriggerInit();
321 /* start a new transaction here before access to db */
323 StartTransactionCommand();
325 /* replace faked-up relcache entries with the real info */
326 RelationCacheInitializePhase2();
329 * Figure out our postgres user id. In standalone mode we use a
330 * fixed id, otherwise we figure it out from the authenticated
334 InitializeSessionUserIdStandalone();
335 else if (!IsUnderPostmaster)
337 InitializeSessionUserIdStandalone();
338 if (!ThereIsAtLeastOneUser())
340 elog(NOTICE, "There are currently no users defined in this database system.");
341 elog(NOTICE, "You should immediately run 'CREATE USER \"%s\" WITH SYSID %d CREATEUSER;'.",
342 username, BOOTSTRAP_USESYSID);
346 /* normal multiuser case */
347 InitializeSessionUserId(username);
350 * Unless we are bootstrapping, double-check that InitMyDatabaseInfo()
351 * got a correct result. We can't do this until all the
352 * database-access infrastructure is up.
355 ReverifyMyDatabase(dbname);
358 /* set default client encoding --- uses info from ReverifyMyDatabase */
359 set_default_client_encoding();
363 * Set up process-exit callbacks to remove temp relations and then do
364 * pre-shutdown cleanup. This should be last because we want
365 * shmem_exit to call these routines before the exit callbacks that
366 * are registered by buffer manager, lock manager, etc. We need to
367 * run this code before we close down database access!
369 on_shmem_exit(ShutdownPostgres, 0);
372 * because callbacks are called in reverse order, this gets done
375 on_shmem_exit(remove_all_temp_relations, 0);
377 /* close the transaction we started above */
379 CommitTransactionCommand();
383 * Backend-shutdown callback. Do cleanup that we want to be sure happens
384 * before all the supporting modules begin to nail their doors shut via
385 * their own callbacks. Note that because this has to be registered very
386 * late in startup, it will not get called if we suffer a failure *during*
389 * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
390 * via separate callbacks that execute before this one. We don't combine the
391 * callbacks because we still want this one to happen if the user-level
395 ShutdownPostgres(void)
399 * These operations are really just a minimal subset of
400 * AbortTransaction(). We don't want to do any inessential cleanup,
401 * since that just raises the odds of failure --- but there's some
402 * stuff we need to do.
404 * Release any LW locks and buffer context locks we might be holding.
405 * This is a kluge to improve the odds that we won't get into a
406 * self-made stuck-lock scenario while trying to shut down.
413 * In case a transaction is open, delete any files it created. This
414 * has to happen before bufmgr shutdown, so having smgr register a
415 * callback for it wouldn't work.
417 smgrDoPendingDeletes(false);/* delete as though aborting xact */
423 * Returns true if at least one user is defined in this database cluster.
426 ThereIsAtLeastOneUser(void)
428 Relation pg_shadow_rel;
429 TupleDesc pg_shadow_dsc;
433 pg_shadow_rel = heap_openr(ShadowRelationName, AccessExclusiveLock);
434 pg_shadow_dsc = RelationGetDescr(pg_shadow_rel);
436 scan = heap_beginscan(pg_shadow_rel, false, SnapshotNow, 0, 0);
437 result = HeapTupleIsValid(heap_getnext(scan, 0));
440 heap_close(pg_shadow_rel, AccessExclusiveLock);