1 /*-------------------------------------------------------------------------
4 * postgres initialization utilities
6 * Portions Copyright (c) 1996-2007, 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.175 2007/03/13 00:33:42 tgl Exp $
14 *-------------------------------------------------------------------------
21 #include "access/heapam.h"
22 #include "access/xact.h"
23 #include "catalog/catalog.h"
24 #include "catalog/namespace.h"
25 #include "catalog/pg_authid.h"
26 #include "catalog/pg_database.h"
27 #include "catalog/pg_tablespace.h"
28 #include "libpq/hba.h"
29 #include "mb/pg_wchar.h"
30 #include "miscadmin.h"
32 #include "postmaster/autovacuum.h"
33 #include "postmaster/postmaster.h"
34 #include "storage/backendid.h"
35 #include "storage/fd.h"
36 #include "storage/ipc.h"
37 #include "storage/proc.h"
38 #include "storage/procarray.h"
39 #include "storage/sinval.h"
40 #include "storage/smgr.h"
41 #include "utils/acl.h"
42 #include "utils/flatfiles.h"
43 #include "utils/guc.h"
44 #include "utils/plancache.h"
45 #include "utils/portal.h"
46 #include "utils/relcache.h"
47 #include "utils/syscache.h"
50 static bool FindMyDatabase(const char *name, Oid *db_id, Oid *db_tablespace);
51 static bool FindMyDatabaseByOid(Oid dbid, char *dbname, Oid *db_tablespace);
52 static void CheckMyDatabase(const char *name, bool am_superuser);
53 static void InitCommunication(void);
54 static void ShutdownPostgres(int code, Datum arg);
55 static bool ThereIsAtLeastOneRole(void);
58 /*** InitPostgres support ***/
62 * FindMyDatabase -- get the critical info needed to locate my database
64 * Find the named database in pg_database, return its database OID and the
65 * OID of its default tablespace. Return TRUE if found, FALSE if not.
67 * Since we are not yet up and running as a backend, we cannot look directly
68 * at pg_database (we can't obtain locks nor participate in transactions).
69 * So to get the info we need before starting up, we must look at the "flat
70 * file" copy of pg_database that is helpfully maintained by flatfiles.c.
71 * This is subject to various race conditions, so after we have the
72 * transaction infrastructure started, we have to recheck the information;
76 FindMyDatabase(const char *name, Oid *db_id, Oid *db_tablespace)
81 char thisname[NAMEDATALEN];
82 TransactionId db_frozenxid;
84 filename = database_getflatfilename();
85 db_file = AllocateFile(filename, "r");
88 (errcode_for_file_access(),
89 errmsg("could not open file \"%s\": %m", filename)));
91 while (read_pg_database_line(db_file, thisname, db_id,
92 db_tablespace, &db_frozenxid))
94 if (strcmp(thisname, name) == 0)
108 * FindMyDatabaseByOid
110 * As above, but the actual database Id is known. Return its name and the
111 * tablespace OID. Return TRUE if found, FALSE if not. The same restrictions
112 * as FindMyDatabase apply.
115 FindMyDatabaseByOid(Oid dbid, char *dbname, Oid *db_tablespace)
121 char thisname[NAMEDATALEN];
122 TransactionId db_frozenxid;
124 filename = database_getflatfilename();
125 db_file = AllocateFile(filename, "r");
128 (errcode_for_file_access(),
129 errmsg("could not open file \"%s\": %m", filename)));
131 while (read_pg_database_line(db_file, thisname, &db_id,
132 db_tablespace, &db_frozenxid))
137 strlcpy(dbname, thisname, NAMEDATALEN);
150 * CheckMyDatabase -- fetch information from the pg_database entry for our DB
153 CheckMyDatabase(const char *name, bool am_superuser)
156 Form_pg_database dbform;
158 /* Fetch our real pg_database row */
159 tup = SearchSysCache(DATABASEOID,
160 ObjectIdGetDatum(MyDatabaseId),
162 if (!HeapTupleIsValid(tup))
163 elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
164 dbform = (Form_pg_database) GETSTRUCT(tup);
166 /* This recheck is strictly paranoia */
167 if (strcmp(name, NameStr(dbform->datname)) != 0)
169 (errcode(ERRCODE_UNDEFINED_DATABASE),
170 errmsg("database \"%s\" has disappeared from pg_database",
172 errdetail("Database OID %u now seems to belong to \"%s\".",
173 MyDatabaseId, NameStr(dbform->datname))));
176 * Check permissions to connect to the database.
178 * These checks are not enforced when in standalone mode, so that there is
179 * a way to recover from disabling all access to all databases, for
180 * example "UPDATE pg_database SET datallowconn = false;".
182 * We do not enforce them for the autovacuum worker processes either.
184 if (IsUnderPostmaster && !IsAutoVacuumWorkerProcess())
187 * Check that the database is currently allowing connections.
189 if (!dbform->datallowconn)
191 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
192 errmsg("database \"%s\" is not currently accepting connections",
196 * Check privilege to connect to the database. (The am_superuser test
197 * is redundant, but since we have the flag, might as well check it
198 * and save a few cycles.)
201 pg_database_aclcheck(MyDatabaseId, GetUserId(),
202 ACL_CONNECT) != ACLCHECK_OK)
204 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
205 errmsg("permission denied for database \"%s\"", name),
206 errdetail("User does not have CONNECT privilege.")));
209 * Check connection limit for this database.
211 * There is a race condition here --- we create our PGPROC before
212 * checking for other PGPROCs. If two backends did this at about the
213 * same time, they might both think they were over the limit, while
214 * ideally one should succeed and one fail. Getting that to work
215 * exactly seems more trouble than it is worth, however; instead we
216 * just document that the connection limit is approximate.
218 if (dbform->datconnlimit >= 0 &&
220 CountDBBackends(MyDatabaseId) > dbform->datconnlimit)
222 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
223 errmsg("too many connections for database \"%s\"",
228 * OK, we're golden. Next to-do item is to save the encoding info out of
229 * the pg_database tuple.
231 SetDatabaseEncoding(dbform->encoding);
232 /* Record it as a GUC internal option, too */
233 SetConfigOption("server_encoding", GetDatabaseEncodingName(),
234 PGC_INTERNAL, PGC_S_OVERRIDE);
235 /* If we have no other source of client_encoding, use server encoding */
236 SetConfigOption("client_encoding", GetDatabaseEncodingName(),
237 PGC_BACKEND, PGC_S_DEFAULT);
240 * Lastly, set up any database-specific configuration variables.
242 if (IsUnderPostmaster)
247 datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_datconfig,
251 ArrayType *a = DatumGetArrayTypeP(datum);
253 ProcessGUCArray(a, PGC_S_DATABASE);
257 ReleaseSysCache(tup);
262 /* --------------------------------
265 * This routine initializes stuff needed for ipc, locking, etc.
266 * it should be called something more informative.
267 * --------------------------------
270 InitCommunication(void)
273 * initialize shared memory and semaphores appropriately.
275 if (!IsUnderPostmaster) /* postmaster already did this */
278 * We're running a postgres bootstrap process or a standalone backend.
279 * Create private "shmem" and semaphores.
281 CreateSharedMemoryAndSemaphores(true, 0);
287 * Early initialization of a backend (either standalone or under postmaster).
288 * This happens even before InitPostgres.
290 * If you're wondering why this is separate from InitPostgres at all:
291 * the critical distinction is that this stuff has to happen before we can
292 * run XLOG-related initialization, which is done before InitPostgres --- in
293 * fact, for cases such as checkpoint creation processes, InitPostgres may
294 * never be done at all.
300 * Attach to shared memory and semaphores, and initialize our
301 * input/output/debugging file descriptors.
306 /* Do local initialization of file, storage and buffer managers */
309 InitBufferPoolAccess();
313 /* --------------------------------
315 * Initialize POSTGRES.
317 * The database can be specified by name, using the in_dbname parameter, or by
318 * OID, using the dboid parameter. In the latter case, the computed database
319 * name is passed out to the caller as a palloc'ed string in out_dbname.
321 * In bootstrap mode no parameters are used.
323 * The return value indicates whether the userID is a superuser. (That
324 * can only be tested inside a transaction, so we want to do it during
325 * the startup transaction rather than doing a separate one in postgres.c.)
327 * As of PostgreSQL 8.2, we expect InitProcess() was already called, so we
328 * already have a PGPROC struct ... but it's not filled in yet.
331 * Be very careful with the order of calls in the InitPostgres function.
332 * --------------------------------
335 InitPostgres(const char *in_dbname, Oid dboid, const char *username,
338 bool bootstrap = IsBootstrapProcessingMode();
339 bool autovacuum = IsAutoVacuumWorkerProcess();
342 char dbname[NAMEDATALEN];
345 * Set up the global variables holding database id and path. But note we
346 * won't actually try to touch the database just yet.
348 * We take a shortcut in the bootstrap case, otherwise we have to look up
349 * the db name in pg_database.
353 MyDatabaseId = TemplateDbOid;
354 MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
359 * Find tablespace of the database we're about to open. Since we're not
360 * yet up and running we have to use one of the hackish FindMyDatabase
361 * variants, which look in the flat-file copy of pg_database.
363 * If the in_dbname param is NULL, lookup database by OID.
365 if (in_dbname == NULL)
367 if (!FindMyDatabaseByOid(dboid, dbname, &MyDatabaseTableSpace))
369 (errcode(ERRCODE_UNDEFINED_DATABASE),
370 errmsg("database %u does not exist", dboid)));
371 MyDatabaseId = dboid;
372 /* pass the database name to the caller */
373 *out_dbname = pstrdup(dbname);
377 if (!FindMyDatabase(in_dbname, &MyDatabaseId, &MyDatabaseTableSpace))
379 (errcode(ERRCODE_UNDEFINED_DATABASE),
380 errmsg("database \"%s\" does not exist",
382 /* our database name is gotten from the caller */
383 strlcpy(dbname, in_dbname, NAMEDATALEN);
387 fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
389 SetDatabasePath(fullpath);
392 * Finish filling in the PGPROC struct, and add it to the ProcArray. (We
393 * need to know MyDatabaseId before we can do this, since it's entered
394 * into the PGPROC struct.)
396 * Once I have done this, I am visible to other backends!
401 * Initialize my entry in the shared-invalidation manager's array of
404 * Sets up MyBackendId, a unique backend identifier.
406 MyBackendId = InvalidBackendId;
408 InitBackendSharedInvalidationState();
410 if (MyBackendId > MaxBackends || MyBackendId <= 0)
411 elog(FATAL, "bad backend id: %d", MyBackendId);
414 * bufmgr needs another initialization call too
416 InitBufferPoolBackend();
419 * Initialize local process's access to XLOG. In bootstrap case we may
420 * skip this since StartupXLOG() was run instead.
426 * Initialize the relation cache and the system catalog caches. Note that
427 * no catalog access happens here; we only set up the hashtable structure.
428 * We must do this before starting a transaction because transaction abort
429 * would try to touch these hashtables.
431 RelationCacheInitialize();
435 /* Initialize portal manager */
436 EnablePortalManager();
439 * Set up process-exit callback to do pre-shutdown cleanup. This has to
440 * be after we've initialized all the low-level modules like the buffer
441 * manager, because during shutdown this has to run before the low-level
442 * modules start to close down. On the other hand, we want it in place
443 * before we begin our first transaction --- if we fail during the
444 * initialization transaction, as is entirely possible, we need the
445 * AbortTransaction call to clean up.
447 on_shmem_exit(ShutdownPostgres, 0);
450 * Start a new transaction here before first access to db
453 StartTransactionCommand();
456 * Now that we have a transaction, we can take locks. Take a writer's
457 * lock on the database we are trying to connect to. If there is a
458 * concurrently running DROP DATABASE on that database, this will block us
459 * until it finishes (and has updated the flat file copy of pg_database).
461 * Note that the lock is not held long, only until the end of this startup
462 * transaction. This is OK since we are already advertising our use of
463 * the database in the PGPROC array; anyone trying a DROP DATABASE after
464 * this point will see us there.
466 * Note: use of RowExclusiveLock here is reasonable because we envision
467 * our session as being a concurrent writer of the database. If we had a
468 * way of declaring a session as being guaranteed-read-only, we could use
469 * AccessShareLock for such sessions and thereby not conflict against
473 LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
477 * Recheck the flat file copy of pg_database to make sure the target
478 * database hasn't gone away. If there was a concurrent DROP DATABASE,
479 * this ensures we will die cleanly without creating a mess.
486 if (!FindMyDatabase(dbname, &dbid2, &tsid2) ||
487 dbid2 != MyDatabaseId || tsid2 != MyDatabaseTableSpace)
489 (errcode(ERRCODE_UNDEFINED_DATABASE),
490 errmsg("database \"%s\" does not exist",
492 errdetail("It seems to have just been dropped or renamed.")));
496 * Now we should be able to access the database directory safely. Verify
497 * it's there and looks reasonable.
501 if (access(fullpath, F_OK) == -1)
505 (errcode(ERRCODE_UNDEFINED_DATABASE),
506 errmsg("database \"%s\" does not exist",
508 errdetail("The database subdirectory \"%s\" is missing.",
512 (errcode_for_file_access(),
513 errmsg("could not access directory \"%s\": %m",
517 ValidatePgVersion(fullpath);
521 * It's now possible to do real access to the system catalogs.
523 * Load relcache entries for the system catalogs. This must create at
524 * least the minimum set of "nailed-in" cache entries.
526 RelationCacheInitializePhase2();
529 * Figure out our postgres user id, and see if we are a superuser.
531 * In standalone mode and in the autovacuum process, we use a fixed id,
532 * otherwise we figure it out from the authenticated user name.
534 if (bootstrap || autovacuum)
536 InitializeSessionUserIdStandalone();
539 else if (!IsUnderPostmaster)
541 InitializeSessionUserIdStandalone();
543 if (!ThereIsAtLeastOneRole())
545 (errcode(ERRCODE_UNDEFINED_OBJECT),
546 errmsg("no roles are defined in this database system"),
547 errhint("You should immediately run CREATE USER \"%s\" CREATEUSER;.",
552 /* normal multiuser case */
553 InitializeSessionUserId(username);
554 am_superuser = superuser();
557 /* set up ACL framework (so CheckMyDatabase can check permissions) */
561 * Read the real pg_database row for our database, check permissions and
562 * set up database-specific GUC settings. We can't do this until all the
563 * database-access infrastructure is up. (Also, it wants to know if the
564 * user is a superuser, so the above stuff has to happen first.)
567 CheckMyDatabase(dbname, am_superuser);
570 * Check a normal user hasn't connected to a superuser reserved slot.
573 ReservedBackends > 0 &&
574 !HaveNFreeProcs(ReservedBackends))
576 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
577 errmsg("connection limit exceeded for non-superusers")));
580 * Initialize various default states that can't be set up until we've
581 * selected the active user and gotten the right GUC settings.
584 /* set default namespace search path */
585 InitializeSearchPath();
587 /* initialize client encoding */
588 InitializeClientEncoding();
590 /* initialize statistics collection for this backend */
594 /* close the transaction we started above */
596 CommitTransactionCommand();
603 * Backend-shutdown callback. Do cleanup that we want to be sure happens
604 * before all the supporting modules begin to nail their doors shut via
605 * their own callbacks.
607 * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
608 * via separate callbacks that execute before this one. We don't combine the
609 * callbacks because we still want this one to happen if the user-level
613 ShutdownPostgres(int code, Datum arg)
615 /* Make sure we've killed any active transaction */
616 AbortOutOfAnyTransaction();
619 * User locks are not released by transaction end, so be sure to release
622 LockReleaseAll(USER_LOCKMETHOD, true);
627 * Returns true if at least one role is defined in this database cluster.
630 ThereIsAtLeastOneRole(void)
632 Relation pg_authid_rel;
636 pg_authid_rel = heap_open(AuthIdRelationId, AccessShareLock);
638 scan = heap_beginscan(pg_authid_rel, SnapshotNow, 0, NULL);
639 result = (heap_getnext(scan, ForwardScanDirection) != NULL);
642 heap_close(pg_authid_rel, AccessShareLock);