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.159 2005/11/22 18:17:26 momjian Exp $
14 *-------------------------------------------------------------------------
23 #include "access/genam.h"
24 #include "access/heapam.h"
25 #include "catalog/catalog.h"
26 #include "catalog/indexing.h"
27 #include "catalog/namespace.h"
28 #include "catalog/pg_authid.h"
29 #include "catalog/pg_database.h"
30 #include "catalog/pg_tablespace.h"
31 #include "libpq/hba.h"
32 #include "mb/pg_wchar.h"
33 #include "miscadmin.h"
34 #include "postmaster/autovacuum.h"
35 #include "postmaster/postmaster.h"
36 #include "storage/backendid.h"
37 #include "storage/fd.h"
38 #include "storage/ipc.h"
39 #include "storage/proc.h"
40 #include "storage/procarray.h"
41 #include "storage/sinval.h"
42 #include "storage/smgr.h"
43 #include "utils/acl.h"
44 #include "utils/flatfiles.h"
45 #include "utils/fmgroids.h"
46 #include "utils/guc.h"
47 #include "utils/portal.h"
48 #include "utils/relcache.h"
49 #include "utils/syscache.h"
53 static bool FindMyDatabase(const char *name, Oid *db_id, Oid *db_tablespace);
54 static void ReverifyMyDatabase(const char *name);
55 static void InitCommunication(void);
56 static void ShutdownPostgres(int code, Datum arg);
57 static bool ThereIsAtLeastOneRole(void);
60 /*** InitPostgres support ***/
64 * FindMyDatabase -- get the critical info needed to locate my database
66 * Find the named database in pg_database, return its database OID and the
67 * OID of its default tablespace. Return TRUE if found, FALSE if not.
69 * Since we are not yet up and running as a backend, we cannot look directly
70 * at pg_database (we can't obtain locks nor participate in transactions).
71 * So to get the info we need before starting up, we must look at the "flat
72 * file" copy of pg_database that is helpfully maintained by flatfiles.c.
73 * This is subject to various race conditions, so after we have the
74 * transaction infrastructure started, we have to recheck the information;
75 * see ReverifyMyDatabase.
78 FindMyDatabase(const char *name, Oid *db_id, Oid *db_tablespace)
83 char thisname[NAMEDATALEN];
84 TransactionId dummyxid;
86 filename = database_getflatfilename();
87 db_file = AllocateFile(filename, "r");
90 (errcode_for_file_access(),
91 errmsg("could not open file \"%s\": %m", filename)));
93 while (read_pg_database_line(db_file, thisname, db_id,
94 db_tablespace, &dummyxid,
97 if (strcmp(thisname, name) == 0)
111 * ReverifyMyDatabase -- recheck info obtained by FindMyDatabase
113 * Since FindMyDatabase cannot lock pg_database, the information it read
114 * could be stale; for example we might have attached to a database that's in
115 * process of being destroyed by dropdb(). This routine is called after
116 * we have all the locking and other infrastructure running --- now we can
117 * check that we are really attached to a valid database.
119 * In reality, if dropdb() is running in parallel with our startup,
120 * it's pretty likely that we will have failed before now, due to being
121 * unable to read some of the system tables within the doomed database.
122 * This routine just exists to make *sure* we have not started up in an
123 * invalid database. If we quit now, we should have managed to avoid
124 * creating any serious problems.
126 * This is also a handy place to fetch the database encoding info out
129 * To avoid having to read pg_database more times than necessary
130 * during session startup, this place is also fitting to set up any
131 * database-specific configuration variables.
134 ReverifyMyDatabase(const char *name)
137 SysScanDesc pgdbscan;
140 Form_pg_database dbform;
143 * Because we grab RowShareLock here, we can be sure that dropdb() is not
144 * running in parallel with us (any more).
146 pgdbrel = heap_open(DatabaseRelationId, RowShareLock);
149 Anum_pg_database_datname,
150 BTEqualStrategyNumber, F_NAMEEQ,
153 pgdbscan = systable_beginscan(pgdbrel, DatabaseNameIndexId, true,
154 SnapshotNow, 1, &key);
156 tup = systable_getnext(pgdbscan);
157 if (!HeapTupleIsValid(tup) ||
158 HeapTupleGetOid(tup) != MyDatabaseId)
161 heap_close(pgdbrel, RowShareLock);
164 * The only real problem I could have created is to load dirty buffers
165 * for the dead database into shared buffer cache; if I did, some
166 * other backend will eventually try to write them and die in
167 * mdblindwrt. Flush any such pages to forestall trouble.
169 DropBuffers(MyDatabaseId);
170 /* Now I can commit hara-kiri with a clear conscience... */
172 (errcode(ERRCODE_UNDEFINED_DATABASE),
173 errmsg("database \"%s\", OID %u, has disappeared from pg_database",
174 name, MyDatabaseId)));
177 dbform = (Form_pg_database) GETSTRUCT(tup);
180 * These next checks are not enforced when in standalone mode, so that
181 * there is a way to recover from disabling all access to all databases,
182 * for example "UPDATE pg_database SET datallowconn = false;".
184 * We do not enforce them for the autovacuum process either.
186 if (IsUnderPostmaster && !IsAutoVacuumProcess())
189 * Check that the database is currently allowing connections.
191 if (!dbform->datallowconn)
193 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
194 errmsg("database \"%s\" is not currently accepting connections",
198 * Check connection limit for this database.
200 * There is a race condition here --- we create our PGPROC before
201 * checking for other PGPROCs. If two backends did this at about the
202 * same time, they might both think they were over the limit, while
203 * ideally one should succeed and one fail. Getting that to work
204 * exactly seems more trouble than it is worth, however; instead we
205 * just document that the connection limit is approximate.
207 if (dbform->datconnlimit >= 0 &&
209 CountDBBackends(MyDatabaseId) > dbform->datconnlimit)
211 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
212 errmsg("too many connections for database \"%s\"",
217 * OK, we're golden. Next to-do item is to save the encoding info out of
218 * the pg_database tuple.
220 SetDatabaseEncoding(dbform->encoding);
221 /* Record it as a GUC internal option, too */
222 SetConfigOption("server_encoding", GetDatabaseEncodingName(),
223 PGC_INTERNAL, PGC_S_OVERRIDE);
224 /* If we have no other source of client_encoding, use server encoding */
225 SetConfigOption("client_encoding", GetDatabaseEncodingName(),
226 PGC_BACKEND, PGC_S_DEFAULT);
229 * Lastly, set up any database-specific configuration variables.
231 if (IsUnderPostmaster)
236 datum = heap_getattr(tup, Anum_pg_database_datconfig,
237 RelationGetDescr(pgdbrel), &isnull);
240 ArrayType *a = DatumGetArrayTypeP(datum);
242 ProcessGUCArray(a, PGC_S_DATABASE);
246 systable_endscan(pgdbscan);
247 heap_close(pgdbrel, RowShareLock);
252 /* --------------------------------
255 * This routine initializes stuff needed for ipc, locking, etc.
256 * it should be called something more informative.
257 * --------------------------------
260 InitCommunication(void)
263 * initialize shared memory and semaphores appropriately.
265 if (!IsUnderPostmaster) /* postmaster already did this */
268 * We're running a postgres bootstrap process or a standalone backend.
269 * Create private "shmem" and semaphores.
271 CreateSharedMemoryAndSemaphores(true, 0);
277 * Early initialization of a backend (either standalone or under postmaster).
278 * This happens even before InitPostgres.
280 * If you're wondering why this is separate from InitPostgres at all:
281 * the critical distinction is that this stuff has to happen before we can
282 * run XLOG-related initialization, which is done before InitPostgres --- in
283 * fact, for cases such as checkpoint creation processes, InitPostgres may
284 * never be done at all.
290 * Attach to shared memory and semaphores, and initialize our
291 * input/output/debugging file descriptors.
296 /* Do local initialization of file, storage and buffer managers */
299 InitBufferPoolAccess();
303 /* --------------------------------
305 * Initialize POSTGRES.
307 * In bootstrap mode neither of the parameters are used. In autovacuum
308 * mode, the username parameter is not used.
310 * The return value indicates whether the userID is a superuser. (That
311 * can only be tested inside a transaction, so we want to do it during
312 * the startup transaction rather than doing a separate one in postgres.c.)
315 * Be very careful with the order of calls in the InitPostgres function.
316 * --------------------------------
319 InitPostgres(const char *dbname, const char *username)
321 bool bootstrap = IsBootstrapProcessingMode();
322 bool autovacuum = IsAutoVacuumProcess();
326 * Set up the global variables holding database id and path.
328 * We take a shortcut in the bootstrap case, otherwise we have to look up
329 * the db name in pg_database.
333 MyDatabaseId = TemplateDbOid;
334 MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
335 SetDatabasePath(GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace));
342 * Formerly we validated DataDir here, but now that's done earlier.
346 * Find oid and tablespace of the database we're about to open. Since
347 * we're not yet up and running we have to use the hackish
350 if (!FindMyDatabase(dbname, &MyDatabaseId, &MyDatabaseTableSpace))
352 (errcode(ERRCODE_UNDEFINED_DATABASE),
353 errmsg("database \"%s\" does not exist",
356 fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
358 /* Verify the database path */
360 if (access(fullpath, F_OK) == -1)
364 (errcode(ERRCODE_UNDEFINED_DATABASE),
365 errmsg("database \"%s\" does not exist",
367 errdetail("The database subdirectory \"%s\" is missing.",
371 (errcode_for_file_access(),
372 errmsg("could not access directory \"%s\": %m",
376 ValidatePgVersion(fullpath);
378 SetDatabasePath(fullpath);
382 * Code after this point assumes we are in the proper directory!
386 * Set up my per-backend PGPROC struct in shared memory. (We need to
387 * know MyDatabaseId before we can do this, since it's entered into the
393 * Initialize my entry in the shared-invalidation manager's array of
394 * per-backend data. (Formerly this came before InitProcess, but now it
395 * must happen after, because it uses MyProc.) Once I have done this, I
396 * am visible to other backends!
398 * Sets up MyBackendId, a unique backend identifier.
400 MyBackendId = InvalidBackendId;
402 InitBackendSharedInvalidationState();
404 if (MyBackendId > MaxBackends || MyBackendId <= 0)
405 elog(FATAL, "bad backend id: %d", MyBackendId);
408 * bufmgr needs another initialization call too
410 InitBufferPoolBackend();
413 * Initialize local process's access to XLOG. In bootstrap case we may
414 * skip this since StartupXLOG() was run instead.
420 * Initialize the relation descriptor cache. This must create at least
421 * the minimum set of "nailed-in" cache entries. No catalog access
424 RelationCacheInitialize();
427 * Initialize all the system catalog caches. Note that no catalog access
428 * happens here; we only set up the cache structure.
432 /* Initialize portal manager */
433 EnablePortalManager();
436 * Set up process-exit callback to do pre-shutdown cleanup. This has to
437 * be after we've initialized all the low-level modules like the buffer
438 * manager, because during shutdown this has to run before the low-level
439 * modules start to close down. On the other hand, we want it in place
440 * before we begin our first transaction --- if we fail during the
441 * initialization transaction, as is entirely possible, we need the
442 * AbortTransaction call to clean up.
444 on_shmem_exit(ShutdownPostgres, 0);
446 /* start a new transaction here before access to db */
448 StartTransactionCommand();
451 * It's now possible to do real access to the system catalogs.
453 * Replace faked-up relcache entries with correct info.
455 RelationCacheInitializePhase2();
458 * Figure out our postgres user id. In standalone mode and in the
459 * autovacuum process, we use a fixed id, otherwise we figure it out from
460 * the authenticated user name.
462 if (bootstrap || autovacuum)
463 InitializeSessionUserIdStandalone();
464 else if (!IsUnderPostmaster)
466 InitializeSessionUserIdStandalone();
467 if (!ThereIsAtLeastOneRole())
469 (errcode(ERRCODE_UNDEFINED_OBJECT),
470 errmsg("no roles are defined in this database system"),
471 errhint("You should immediately run CREATE USER \"%s\" CREATEUSER;.",
476 /* normal multiuser case */
477 InitializeSessionUserId(username);
481 * Unless we are bootstrapping, double-check that InitMyDatabaseInfo() got
482 * a correct result. We can't do this until all the database-access
483 * infrastructure is up. (Also, it wants to know if the user is a
484 * superuser, so the above stuff has to happen first.)
487 ReverifyMyDatabase(dbname);
490 * Final phase of relation cache startup: write a new cache file if
491 * necessary. This is done after ReverifyMyDatabase to avoid writing a
492 * cache file into a dead database.
494 RelationCacheInitializePhase3();
497 * Check if user is a superuser.
499 if (bootstrap || autovacuum)
502 am_superuser = superuser();
505 * Check a normal user hasn't connected to a superuser reserved slot.
508 ReservedBackends > 0 &&
509 !HaveNFreeProcs(ReservedBackends))
511 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
512 errmsg("connection limit exceeded for non-superusers")));
515 * Initialize various default states that can't be set up until we've
516 * selected the active user and done ReverifyMyDatabase.
519 /* set default namespace search path */
520 InitializeSearchPath();
522 /* set up ACL framework (currently just sets RolMemCache callback) */
525 /* initialize client encoding */
526 InitializeClientEncoding();
528 /* initialize statistics collection for this backend */
529 if (IsUnderPostmaster)
532 /* close the transaction we started above */
534 CommitTransactionCommand();
541 * Backend-shutdown callback. Do cleanup that we want to be sure happens
542 * before all the supporting modules begin to nail their doors shut via
543 * their own callbacks.
545 * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
546 * via separate callbacks that execute before this one. We don't combine the
547 * callbacks because we still want this one to happen if the user-level
551 ShutdownPostgres(int code, Datum arg)
553 /* Make sure we've killed any active transaction */
554 AbortOutOfAnyTransaction();
557 * User locks are not released by transaction end, so be sure to release
561 LockReleaseAll(USER_LOCKMETHOD, true);
567 * Returns true if at least one role is defined in this database cluster.
570 ThereIsAtLeastOneRole(void)
572 Relation pg_authid_rel;
576 pg_authid_rel = heap_open(AuthIdRelationId, AccessExclusiveLock);
578 scan = heap_beginscan(pg_authid_rel, SnapshotNow, 0, NULL);
579 result = (heap_getnext(scan, ForwardScanDirection) != NULL);
582 heap_close(pg_authid_rel, AccessExclusiveLock);