1 /*-------------------------------------------------------------------------
4 * postgres initialization utilities
6 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
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 "libpq/libpq-be.h"
30 #include "mb/pg_wchar.h"
31 #include "miscadmin.h"
33 #include "postmaster/autovacuum.h"
34 #include "postmaster/postmaster.h"
35 #include "storage/backendid.h"
36 #include "storage/bufmgr.h"
37 #include "storage/fd.h"
38 #include "storage/ipc.h"
39 #include "storage/lmgr.h"
40 #include "storage/proc.h"
41 #include "storage/procarray.h"
42 #include "storage/sinvaladt.h"
43 #include "storage/smgr.h"
44 #include "utils/acl.h"
45 #include "utils/flatfiles.h"
46 #include "utils/guc.h"
47 #include "utils/plancache.h"
48 #include "utils/portal.h"
49 #include "utils/relcache.h"
50 #include "utils/snapmgr.h"
51 #include "utils/syscache.h"
52 #include "utils/tqual.h"
55 static bool FindMyDatabase(const char *name
, Oid
*db_id
, Oid
*db_tablespace
);
56 static bool FindMyDatabaseByOid(Oid dbid
, char *dbname
, Oid
*db_tablespace
);
57 static void CheckMyDatabase(const char *name
, bool am_superuser
);
58 static void InitCommunication(void);
59 static void ShutdownPostgres(int code
, Datum arg
);
60 static bool ThereIsAtLeastOneRole(void);
63 /*** InitPostgres support ***/
67 * FindMyDatabase -- get the critical info needed to locate my database
69 * Find the named database in pg_database, return its database OID and the
70 * OID of its default tablespace. Return TRUE if found, FALSE if not.
72 * Since we are not yet up and running as a backend, we cannot look directly
73 * at pg_database (we can't obtain locks nor participate in transactions).
74 * So to get the info we need before starting up, we must look at the "flat
75 * file" copy of pg_database that is helpfully maintained by flatfiles.c.
76 * This is subject to various race conditions, so after we have the
77 * transaction infrastructure started, we have to recheck the information;
81 FindMyDatabase(const char *name
, Oid
*db_id
, Oid
*db_tablespace
)
86 char thisname
[NAMEDATALEN
];
87 TransactionId db_frozenxid
;
89 filename
= database_getflatfilename();
90 db_file
= AllocateFile(filename
, "r");
93 (errcode_for_file_access(),
94 errmsg("could not open file \"%s\": %m", filename
)));
96 while (read_pg_database_line(db_file
, thisname
, db_id
,
97 db_tablespace
, &db_frozenxid
))
99 if (strcmp(thisname
, name
) == 0)
113 * FindMyDatabaseByOid
115 * As above, but the actual database Id is known. Return its name and the
116 * tablespace OID. Return TRUE if found, FALSE if not. The same restrictions
117 * as FindMyDatabase apply.
120 FindMyDatabaseByOid(Oid dbid
, char *dbname
, Oid
*db_tablespace
)
126 char thisname
[NAMEDATALEN
];
127 TransactionId db_frozenxid
;
129 filename
= database_getflatfilename();
130 db_file
= AllocateFile(filename
, "r");
133 (errcode_for_file_access(),
134 errmsg("could not open file \"%s\": %m", filename
)));
136 while (read_pg_database_line(db_file
, thisname
, &db_id
,
137 db_tablespace
, &db_frozenxid
))
142 strlcpy(dbname
, thisname
, NAMEDATALEN
);
155 * CheckMyDatabase -- fetch information from the pg_database entry for our DB
158 CheckMyDatabase(const char *name
, bool am_superuser
)
161 Form_pg_database dbform
;
165 /* Fetch our real pg_database row */
166 tup
= SearchSysCache(DATABASEOID
,
167 ObjectIdGetDatum(MyDatabaseId
),
169 if (!HeapTupleIsValid(tup
))
170 elog(ERROR
, "cache lookup failed for database %u", MyDatabaseId
);
171 dbform
= (Form_pg_database
) GETSTRUCT(tup
);
173 /* This recheck is strictly paranoia */
174 if (strcmp(name
, NameStr(dbform
->datname
)) != 0)
176 (errcode(ERRCODE_UNDEFINED_DATABASE
),
177 errmsg("database \"%s\" has disappeared from pg_database",
179 errdetail("Database OID %u now seems to belong to \"%s\".",
180 MyDatabaseId
, NameStr(dbform
->datname
))));
183 * Check permissions to connect to the database.
185 * These checks are not enforced when in standalone mode, so that there is
186 * a way to recover from disabling all access to all databases, for
187 * example "UPDATE pg_database SET datallowconn = false;".
189 * We do not enforce them for the autovacuum worker processes either.
191 if (IsUnderPostmaster
&& !IsAutoVacuumWorkerProcess())
194 * Check that the database is currently allowing connections.
196 if (!dbform
->datallowconn
)
198 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE
),
199 errmsg("database \"%s\" is not currently accepting connections",
203 * Check privilege to connect to the database. (The am_superuser test
204 * is redundant, but since we have the flag, might as well check it
205 * and save a few cycles.)
208 pg_database_aclcheck(MyDatabaseId
, GetUserId(),
209 ACL_CONNECT
) != ACLCHECK_OK
)
211 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE
),
212 errmsg("permission denied for database \"%s\"", name
),
213 errdetail("User does not have CONNECT privilege.")));
216 * Check connection limit for this database.
218 * There is a race condition here --- we create our PGPROC before
219 * checking for other PGPROCs. If two backends did this at about the
220 * same time, they might both think they were over the limit, while
221 * ideally one should succeed and one fail. Getting that to work
222 * exactly seems more trouble than it is worth, however; instead we
223 * just document that the connection limit is approximate.
225 if (dbform
->datconnlimit
>= 0 &&
227 CountDBBackends(MyDatabaseId
) > dbform
->datconnlimit
)
229 (errcode(ERRCODE_TOO_MANY_CONNECTIONS
),
230 errmsg("too many connections for database \"%s\"",
235 * OK, we're golden. Next to-do item is to save the encoding info out of
236 * the pg_database tuple.
238 SetDatabaseEncoding(dbform
->encoding
);
239 /* Record it as a GUC internal option, too */
240 SetConfigOption("server_encoding", GetDatabaseEncodingName(),
241 PGC_INTERNAL
, PGC_S_OVERRIDE
);
242 /* If we have no other source of client_encoding, use server encoding */
243 SetConfigOption("client_encoding", GetDatabaseEncodingName(),
244 PGC_BACKEND
, PGC_S_DEFAULT
);
246 /* assign locale variables */
247 collate
= NameStr(dbform
->datcollate
);
248 ctype
= NameStr(dbform
->datctype
);
250 if (setlocale(LC_COLLATE
, collate
) == NULL
)
252 (errmsg("database locale is incompatible with operating system"),
253 errdetail("The database was initialized with LC_COLLATE \"%s\", "
254 " which is not recognized by setlocale().", collate
),
255 errhint("Recreate the database with another locale or install the missing locale.")));
257 if (setlocale(LC_CTYPE
, ctype
) == NULL
)
259 (errmsg("database locale is incompatible with operating system"),
260 errdetail("The database was initialized with LC_CTYPE \"%s\", "
261 " which is not recognized by setlocale().", ctype
),
262 errhint("Recreate the database with another locale or install the missing locale.")));
264 /* Make the locale settings visible as GUC variables, too */
265 SetConfigOption("lc_collate", collate
, PGC_INTERNAL
, PGC_S_OVERRIDE
);
266 SetConfigOption("lc_ctype", ctype
, PGC_INTERNAL
, PGC_S_OVERRIDE
);
269 * Lastly, set up any database-specific configuration variables.
271 if (IsUnderPostmaster
)
276 datum
= SysCacheGetAttr(DATABASEOID
, tup
, Anum_pg_database_datconfig
,
280 ArrayType
*a
= DatumGetArrayTypeP(datum
);
283 * We process all the options at SUSET level. We assume that the
284 * right to insert an option into pg_database was checked when it
287 ProcessGUCArray(a
, PGC_SUSET
, PGC_S_DATABASE
, GUC_ACTION_SET
);
291 ReleaseSysCache(tup
);
296 /* --------------------------------
299 * This routine initializes stuff needed for ipc, locking, etc.
300 * it should be called something more informative.
301 * --------------------------------
304 InitCommunication(void)
307 * initialize shared memory and semaphores appropriately.
309 if (!IsUnderPostmaster
) /* postmaster already did this */
312 * We're running a postgres bootstrap process or a standalone backend.
313 * Create private "shmem" and semaphores.
315 CreateSharedMemoryAndSemaphores(true, 0);
321 * Early initialization of a backend (either standalone or under postmaster).
322 * This happens even before InitPostgres.
324 * If you're wondering why this is separate from InitPostgres at all:
325 * the critical distinction is that this stuff has to happen before we can
326 * run XLOG-related initialization, which is done before InitPostgres --- in
327 * fact, for cases such as the background writer process, InitPostgres may
328 * never be done at all.
334 * Attach to shared memory and semaphores, and initialize our
335 * input/output/debugging file descriptors.
340 /* Do local initialization of file, storage and buffer managers */
343 InitBufferPoolAccess();
347 /* --------------------------------
349 * Initialize POSTGRES.
351 * The database can be specified by name, using the in_dbname parameter, or by
352 * OID, using the dboid parameter. In the latter case, the computed database
353 * name is passed out to the caller as a palloc'ed string in out_dbname.
355 * In bootstrap mode no parameters are used.
357 * The return value indicates whether the userID is a superuser. (That
358 * can only be tested inside a transaction, so we want to do it during
359 * the startup transaction rather than doing a separate one in postgres.c.)
361 * As of PostgreSQL 8.2, we expect InitProcess() was already called, so we
362 * already have a PGPROC struct ... but it's not filled in yet.
365 * Be very careful with the order of calls in the InitPostgres function.
366 * --------------------------------
369 InitPostgres(const char *in_dbname
, Oid dboid
, const char *username
,
372 bool bootstrap
= IsBootstrapProcessingMode();
373 bool autovacuum
= IsAutoVacuumWorkerProcess();
376 char dbname
[NAMEDATALEN
];
379 * Set up the global variables holding database id and path. But note we
380 * won't actually try to touch the database just yet.
382 * We take a shortcut in the bootstrap case, otherwise we have to look up
383 * the db name in pg_database.
387 MyDatabaseId
= TemplateDbOid
;
388 MyDatabaseTableSpace
= DEFAULTTABLESPACE_OID
;
393 * Find tablespace of the database we're about to open. Since we're
394 * not yet up and running we have to use one of the hackish
395 * FindMyDatabase variants, which look in the flat-file copy of
398 * If the in_dbname param is NULL, lookup database by OID.
400 if (in_dbname
== NULL
)
402 if (!FindMyDatabaseByOid(dboid
, dbname
, &MyDatabaseTableSpace
))
404 (errcode(ERRCODE_UNDEFINED_DATABASE
),
405 errmsg("database %u does not exist", dboid
)));
406 MyDatabaseId
= dboid
;
407 /* pass the database name to the caller */
408 *out_dbname
= pstrdup(dbname
);
412 if (!FindMyDatabase(in_dbname
, &MyDatabaseId
, &MyDatabaseTableSpace
))
414 (errcode(ERRCODE_UNDEFINED_DATABASE
),
415 errmsg("database \"%s\" does not exist",
417 /* our database name is gotten from the caller */
418 strlcpy(dbname
, in_dbname
, NAMEDATALEN
);
422 fullpath
= GetDatabasePath(MyDatabaseId
, MyDatabaseTableSpace
);
424 SetDatabasePath(fullpath
);
427 * Finish filling in the PGPROC struct, and add it to the ProcArray. (We
428 * need to know MyDatabaseId before we can do this, since it's entered
429 * into the PGPROC struct.)
431 * Once I have done this, I am visible to other backends!
436 * Initialize my entry in the shared-invalidation manager's array of
439 * Sets up MyBackendId, a unique backend identifier.
441 MyBackendId
= InvalidBackendId
;
443 SharedInvalBackendInit();
445 if (MyBackendId
> MaxBackends
|| MyBackendId
<= 0)
446 elog(FATAL
, "bad backend id: %d", MyBackendId
);
449 * bufmgr needs another initialization call too
451 InitBufferPoolBackend();
454 * Initialize local process's access to XLOG. In bootstrap case we may
455 * skip this since StartupXLOG() was run instead.
461 * Initialize the relation cache and the system catalog caches. Note that
462 * no catalog access happens here; we only set up the hashtable structure.
463 * We must do this before starting a transaction because transaction abort
464 * would try to touch these hashtables.
466 RelationCacheInitialize();
470 /* Initialize portal manager */
471 EnablePortalManager();
473 /* Initialize stats collection --- must happen before first xact */
478 * Set up process-exit callback to do pre-shutdown cleanup. This has to
479 * be after we've initialized all the low-level modules like the buffer
480 * manager, because during shutdown this has to run before the low-level
481 * modules start to close down. On the other hand, we want it in place
482 * before we begin our first transaction --- if we fail during the
483 * initialization transaction, as is entirely possible, we need the
484 * AbortTransaction call to clean up.
486 on_shmem_exit(ShutdownPostgres
, 0);
489 * Start a new transaction here before first access to db, and get a
490 * snapshot. We don't have a use for the snapshot itself, but we're
491 * interested in the secondary effect that it sets RecentGlobalXmin.
495 StartTransactionCommand();
496 (void) GetTransactionSnapshot();
500 * Now that we have a transaction, we can take locks. Take a writer's
501 * lock on the database we are trying to connect to. If there is a
502 * concurrently running DROP DATABASE on that database, this will block us
503 * until it finishes (and has updated the flat file copy of pg_database).
505 * Note that the lock is not held long, only until the end of this startup
506 * transaction. This is OK since we are already advertising our use of
507 * the database in the PGPROC array; anyone trying a DROP DATABASE after
508 * this point will see us there.
510 * Note: use of RowExclusiveLock here is reasonable because we envision
511 * our session as being a concurrent writer of the database. If we had a
512 * way of declaring a session as being guaranteed-read-only, we could use
513 * AccessShareLock for such sessions and thereby not conflict against
517 LockSharedObject(DatabaseRelationId
, MyDatabaseId
, 0,
521 * Recheck the flat file copy of pg_database to make sure the target
522 * database hasn't gone away. If there was a concurrent DROP DATABASE,
523 * this ensures we will die cleanly without creating a mess.
530 if (!FindMyDatabase(dbname
, &dbid2
, &tsid2
) ||
531 dbid2
!= MyDatabaseId
|| tsid2
!= MyDatabaseTableSpace
)
533 (errcode(ERRCODE_UNDEFINED_DATABASE
),
534 errmsg("database \"%s\" does not exist",
536 errdetail("It seems to have just been dropped or renamed.")));
540 * Now we should be able to access the database directory safely. Verify
541 * it's there and looks reasonable.
545 if (access(fullpath
, F_OK
) == -1)
549 (errcode(ERRCODE_UNDEFINED_DATABASE
),
550 errmsg("database \"%s\" does not exist",
552 errdetail("The database subdirectory \"%s\" is missing.",
556 (errcode_for_file_access(),
557 errmsg("could not access directory \"%s\": %m",
561 ValidatePgVersion(fullpath
);
565 * It's now possible to do real access to the system catalogs.
567 * Load relcache entries for the system catalogs. This must create at
568 * least the minimum set of "nailed-in" cache entries.
570 RelationCacheInitializePhase2();
573 * Figure out our postgres user id, and see if we are a superuser.
575 * In standalone mode and in the autovacuum process, we use a fixed id,
576 * otherwise we figure it out from the authenticated user name.
578 if (bootstrap
|| autovacuum
)
580 InitializeSessionUserIdStandalone();
583 else if (!IsUnderPostmaster
)
585 InitializeSessionUserIdStandalone();
587 if (!ThereIsAtLeastOneRole())
589 (errcode(ERRCODE_UNDEFINED_OBJECT
),
590 errmsg("no roles are defined in this database system"),
591 errhint("You should immediately run CREATE USER \"%s\" CREATEUSER;.",
596 /* normal multiuser case */
597 InitializeSessionUserId(username
);
598 am_superuser
= superuser();
601 /* set up ACL framework (so CheckMyDatabase can check permissions) */
605 * Read the real pg_database row for our database, check permissions and
606 * set up database-specific GUC settings. We can't do this until all the
607 * database-access infrastructure is up. (Also, it wants to know if the
608 * user is a superuser, so the above stuff has to happen first.)
611 CheckMyDatabase(dbname
, am_superuser
);
614 * If we're trying to shut down, only superusers can connect.
617 MyProcPort
!= NULL
&&
618 MyProcPort
->canAcceptConnections
== CAC_WAITBACKUP
)
620 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE
),
621 errmsg("must be superuser to connect during database shutdown")));
624 * Check a normal user hasn't connected to a superuser reserved slot.
627 ReservedBackends
> 0 &&
628 !HaveNFreeProcs(ReservedBackends
))
630 (errcode(ERRCODE_TOO_MANY_CONNECTIONS
),
631 errmsg("connection limit exceeded for non-superusers")));
634 * Initialize various default states that can't be set up until we've
635 * selected the active user and gotten the right GUC settings.
638 /* set default namespace search path */
639 InitializeSearchPath();
641 /* initialize client encoding */
642 InitializeClientEncoding();
644 /* report this backend in the PgBackendStatus array */
648 /* close the transaction we started above */
650 CommitTransactionCommand();
657 * Backend-shutdown callback. Do cleanup that we want to be sure happens
658 * before all the supporting modules begin to nail their doors shut via
659 * their own callbacks.
661 * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
662 * via separate callbacks that execute before this one. We don't combine the
663 * callbacks because we still want this one to happen if the user-level
667 ShutdownPostgres(int code
, Datum arg
)
669 /* Make sure we've killed any active transaction */
670 AbortOutOfAnyTransaction();
673 * User locks are not released by transaction end, so be sure to release
676 LockReleaseAll(USER_LOCKMETHOD
, true);
681 * Returns true if at least one role is defined in this database cluster.
684 ThereIsAtLeastOneRole(void)
686 Relation pg_authid_rel
;
690 pg_authid_rel
= heap_open(AuthIdRelationId
, AccessShareLock
);
692 scan
= heap_beginscan(pg_authid_rel
, SnapshotNow
, 0, NULL
);
693 result
= (heap_getnext(scan
, ForwardScanDirection
) != NULL
);
696 heap_close(pg_authid_rel
, AccessShareLock
);