Oops, mustn't call textdomain() when compiling without --enable-nls
[PostgreSQL.git] / src / backend / utils / init / postinit.c
blobb1251f945fd11101cb72a474068ef031bdeacda4
1 /*-------------------------------------------------------------------------
3 * postinit.c
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
10 * IDENTIFICATION
11 * $PostgreSQL$
14 *-------------------------------------------------------------------------
16 #include "postgres.h"
18 #include <fcntl.h>
19 #include <unistd.h>
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"
32 #include "pgstat.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;
78 * see InitPostgres.
80 static bool
81 FindMyDatabase(const char *name, Oid *db_id, Oid *db_tablespace)
83 bool result = false;
84 char *filename;
85 FILE *db_file;
86 char thisname[NAMEDATALEN];
87 TransactionId db_frozenxid;
89 filename = database_getflatfilename();
90 db_file = AllocateFile(filename, "r");
91 if (db_file == NULL)
92 ereport(FATAL,
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)
101 result = true;
102 break;
106 FreeFile(db_file);
107 pfree(filename);
109 return result;
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.
119 static bool
120 FindMyDatabaseByOid(Oid dbid, char *dbname, Oid *db_tablespace)
122 bool result = false;
123 char *filename;
124 FILE *db_file;
125 Oid db_id;
126 char thisname[NAMEDATALEN];
127 TransactionId db_frozenxid;
129 filename = database_getflatfilename();
130 db_file = AllocateFile(filename, "r");
131 if (db_file == NULL)
132 ereport(FATAL,
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))
139 if (dbid == db_id)
141 result = true;
142 strlcpy(dbname, thisname, NAMEDATALEN);
143 break;
147 FreeFile(db_file);
148 pfree(filename);
150 return result;
155 * CheckMyDatabase -- fetch information from the pg_database entry for our DB
157 static void
158 CheckMyDatabase(const char *name, bool am_superuser)
160 HeapTuple tup;
161 Form_pg_database dbform;
162 char *collate;
163 char *ctype;
165 /* Fetch our real pg_database row */
166 tup = SearchSysCache(DATABASEOID,
167 ObjectIdGetDatum(MyDatabaseId),
168 0, 0, 0);
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)
175 ereport(FATAL,
176 (errcode(ERRCODE_UNDEFINED_DATABASE),
177 errmsg("database \"%s\" has disappeared from pg_database",
178 name),
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)
197 ereport(FATAL,
198 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
199 errmsg("database \"%s\" is not currently accepting connections",
200 name)));
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.)
207 if (!am_superuser &&
208 pg_database_aclcheck(MyDatabaseId, GetUserId(),
209 ACL_CONNECT) != ACLCHECK_OK)
210 ereport(FATAL,
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 &&
226 !am_superuser &&
227 CountDBBackends(MyDatabaseId) > dbform->datconnlimit)
228 ereport(FATAL,
229 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
230 errmsg("too many connections for database \"%s\"",
231 name)));
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)
251 ereport(FATAL,
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)
258 ereport(FATAL,
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);
268 /* Use the right encoding in translated messages */
269 #ifdef ENABLE_NLS
270 pg_bind_textdomain_codeset(textdomain(NULL));
271 #endif
274 * Lastly, set up any database-specific configuration variables.
276 if (IsUnderPostmaster)
278 Datum datum;
279 bool isnull;
281 datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_datconfig,
282 &isnull);
283 if (!isnull)
285 ArrayType *a = DatumGetArrayTypeP(datum);
288 * We process all the options at SUSET level. We assume that the
289 * right to insert an option into pg_database was checked when it
290 * was inserted.
292 ProcessGUCArray(a, PGC_SUSET, PGC_S_DATABASE, GUC_ACTION_SET);
296 ReleaseSysCache(tup);
301 /* --------------------------------
302 * InitCommunication
304 * This routine initializes stuff needed for ipc, locking, etc.
305 * it should be called something more informative.
306 * --------------------------------
308 static void
309 InitCommunication(void)
312 * initialize shared memory and semaphores appropriately.
314 if (!IsUnderPostmaster) /* postmaster already did this */
317 * We're running a postgres bootstrap process or a standalone backend.
318 * Create private "shmem" and semaphores.
320 CreateSharedMemoryAndSemaphores(true, 0);
326 * Early initialization of a backend (either standalone or under postmaster).
327 * This happens even before InitPostgres.
329 * If you're wondering why this is separate from InitPostgres at all:
330 * the critical distinction is that this stuff has to happen before we can
331 * run XLOG-related initialization, which is done before InitPostgres --- in
332 * fact, for cases such as the background writer process, InitPostgres may
333 * never be done at all.
335 void
336 BaseInit(void)
339 * Attach to shared memory and semaphores, and initialize our
340 * input/output/debugging file descriptors.
342 InitCommunication();
343 DebugFileOpen();
345 /* Do local initialization of file, storage and buffer managers */
346 InitFileAccess();
347 smgrinit();
348 InitBufferPoolAccess();
352 /* --------------------------------
353 * InitPostgres
354 * Initialize POSTGRES.
356 * The database can be specified by name, using the in_dbname parameter, or by
357 * OID, using the dboid parameter. In the latter case, the computed database
358 * name is passed out to the caller as a palloc'ed string in out_dbname.
360 * In bootstrap mode no parameters are used.
362 * The return value indicates whether the userID is a superuser. (That
363 * can only be tested inside a transaction, so we want to do it during
364 * the startup transaction rather than doing a separate one in postgres.c.)
366 * As of PostgreSQL 8.2, we expect InitProcess() was already called, so we
367 * already have a PGPROC struct ... but it's not filled in yet.
369 * Note:
370 * Be very careful with the order of calls in the InitPostgres function.
371 * --------------------------------
373 bool
374 InitPostgres(const char *in_dbname, Oid dboid, const char *username,
375 char **out_dbname)
377 bool bootstrap = IsBootstrapProcessingMode();
378 bool autovacuum = IsAutoVacuumWorkerProcess();
379 bool am_superuser;
380 char *fullpath;
381 char dbname[NAMEDATALEN];
384 * Set up the global variables holding database id and path. But note we
385 * won't actually try to touch the database just yet.
387 * We take a shortcut in the bootstrap case, otherwise we have to look up
388 * the db name in pg_database.
390 if (bootstrap)
392 MyDatabaseId = TemplateDbOid;
393 MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
395 else
398 * Find tablespace of the database we're about to open. Since we're
399 * not yet up and running we have to use one of the hackish
400 * FindMyDatabase variants, which look in the flat-file copy of
401 * pg_database.
403 * If the in_dbname param is NULL, lookup database by OID.
405 if (in_dbname == NULL)
407 if (!FindMyDatabaseByOid(dboid, dbname, &MyDatabaseTableSpace))
408 ereport(FATAL,
409 (errcode(ERRCODE_UNDEFINED_DATABASE),
410 errmsg("database %u does not exist", dboid)));
411 MyDatabaseId = dboid;
412 /* pass the database name to the caller */
413 *out_dbname = pstrdup(dbname);
415 else
417 if (!FindMyDatabase(in_dbname, &MyDatabaseId, &MyDatabaseTableSpace))
418 ereport(FATAL,
419 (errcode(ERRCODE_UNDEFINED_DATABASE),
420 errmsg("database \"%s\" does not exist",
421 in_dbname)));
422 /* our database name is gotten from the caller */
423 strlcpy(dbname, in_dbname, NAMEDATALEN);
427 fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
429 SetDatabasePath(fullpath);
432 * Finish filling in the PGPROC struct, and add it to the ProcArray. (We
433 * need to know MyDatabaseId before we can do this, since it's entered
434 * into the PGPROC struct.)
436 * Once I have done this, I am visible to other backends!
438 InitProcessPhase2();
441 * Initialize my entry in the shared-invalidation manager's array of
442 * per-backend data.
444 * Sets up MyBackendId, a unique backend identifier.
446 MyBackendId = InvalidBackendId;
448 SharedInvalBackendInit();
450 if (MyBackendId > MaxBackends || MyBackendId <= 0)
451 elog(FATAL, "bad backend id: %d", MyBackendId);
454 * bufmgr needs another initialization call too
456 InitBufferPoolBackend();
459 * Initialize local process's access to XLOG. In bootstrap case we may
460 * skip this since StartupXLOG() was run instead.
462 if (!bootstrap)
463 InitXLOGAccess();
466 * Initialize the relation cache and the system catalog caches. Note that
467 * no catalog access happens here; we only set up the hashtable structure.
468 * We must do this before starting a transaction because transaction abort
469 * would try to touch these hashtables.
471 RelationCacheInitialize();
472 InitCatalogCache();
473 InitPlanCache();
475 /* Initialize portal manager */
476 EnablePortalManager();
478 /* Initialize stats collection --- must happen before first xact */
479 if (!bootstrap)
480 pgstat_initialize();
483 * Set up process-exit callback to do pre-shutdown cleanup. This has to
484 * be after we've initialized all the low-level modules like the buffer
485 * manager, because during shutdown this has to run before the low-level
486 * modules start to close down. On the other hand, we want it in place
487 * before we begin our first transaction --- if we fail during the
488 * initialization transaction, as is entirely possible, we need the
489 * AbortTransaction call to clean up.
491 on_shmem_exit(ShutdownPostgres, 0);
494 * Start a new transaction here before first access to db, and get a
495 * snapshot. We don't have a use for the snapshot itself, but we're
496 * interested in the secondary effect that it sets RecentGlobalXmin.
498 if (!bootstrap)
500 StartTransactionCommand();
501 (void) GetTransactionSnapshot();
505 * Now that we have a transaction, we can take locks. Take a writer's
506 * lock on the database we are trying to connect to. If there is a
507 * concurrently running DROP DATABASE on that database, this will block us
508 * until it finishes (and has updated the flat file copy of pg_database).
510 * Note that the lock is not held long, only until the end of this startup
511 * transaction. This is OK since we are already advertising our use of
512 * the database in the PGPROC array; anyone trying a DROP DATABASE after
513 * this point will see us there.
515 * Note: use of RowExclusiveLock here is reasonable because we envision
516 * our session as being a concurrent writer of the database. If we had a
517 * way of declaring a session as being guaranteed-read-only, we could use
518 * AccessShareLock for such sessions and thereby not conflict against
519 * CREATE DATABASE.
521 if (!bootstrap)
522 LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
523 RowExclusiveLock);
526 * Recheck the flat file copy of pg_database to make sure the target
527 * database hasn't gone away. If there was a concurrent DROP DATABASE,
528 * this ensures we will die cleanly without creating a mess.
530 if (!bootstrap)
532 Oid dbid2;
533 Oid tsid2;
535 if (!FindMyDatabase(dbname, &dbid2, &tsid2) ||
536 dbid2 != MyDatabaseId || tsid2 != MyDatabaseTableSpace)
537 ereport(FATAL,
538 (errcode(ERRCODE_UNDEFINED_DATABASE),
539 errmsg("database \"%s\" does not exist",
540 dbname),
541 errdetail("It seems to have just been dropped or renamed.")));
545 * Now we should be able to access the database directory safely. Verify
546 * it's there and looks reasonable.
548 if (!bootstrap)
550 if (access(fullpath, F_OK) == -1)
552 if (errno == ENOENT)
553 ereport(FATAL,
554 (errcode(ERRCODE_UNDEFINED_DATABASE),
555 errmsg("database \"%s\" does not exist",
556 dbname),
557 errdetail("The database subdirectory \"%s\" is missing.",
558 fullpath)));
559 else
560 ereport(FATAL,
561 (errcode_for_file_access(),
562 errmsg("could not access directory \"%s\": %m",
563 fullpath)));
566 ValidatePgVersion(fullpath);
570 * It's now possible to do real access to the system catalogs.
572 * Load relcache entries for the system catalogs. This must create at
573 * least the minimum set of "nailed-in" cache entries.
575 RelationCacheInitializePhase2();
578 * Figure out our postgres user id, and see if we are a superuser.
580 * In standalone mode and in the autovacuum process, we use a fixed id,
581 * otherwise we figure it out from the authenticated user name.
583 if (bootstrap || autovacuum)
585 InitializeSessionUserIdStandalone();
586 am_superuser = true;
588 else if (!IsUnderPostmaster)
590 InitializeSessionUserIdStandalone();
591 am_superuser = true;
592 if (!ThereIsAtLeastOneRole())
593 ereport(WARNING,
594 (errcode(ERRCODE_UNDEFINED_OBJECT),
595 errmsg("no roles are defined in this database system"),
596 errhint("You should immediately run CREATE USER \"%s\" CREATEUSER;.",
597 username)));
599 else
601 /* normal multiuser case */
602 InitializeSessionUserId(username);
603 am_superuser = superuser();
606 /* set up ACL framework (so CheckMyDatabase can check permissions) */
607 initialize_acl();
610 * Read the real pg_database row for our database, check permissions and
611 * set up database-specific GUC settings. We can't do this until all the
612 * database-access infrastructure is up. (Also, it wants to know if the
613 * user is a superuser, so the above stuff has to happen first.)
615 if (!bootstrap)
616 CheckMyDatabase(dbname, am_superuser);
619 * If we're trying to shut down, only superusers can connect.
621 if (!am_superuser &&
622 MyProcPort != NULL &&
623 MyProcPort->canAcceptConnections == CAC_WAITBACKUP)
624 ereport(FATAL,
625 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
626 errmsg("must be superuser to connect during database shutdown")));
629 * Check a normal user hasn't connected to a superuser reserved slot.
631 if (!am_superuser &&
632 ReservedBackends > 0 &&
633 !HaveNFreeProcs(ReservedBackends))
634 ereport(FATAL,
635 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
636 errmsg("connection limit exceeded for non-superusers")));
639 * Initialize various default states that can't be set up until we've
640 * selected the active user and gotten the right GUC settings.
643 /* set default namespace search path */
644 InitializeSearchPath();
646 /* initialize client encoding */
647 InitializeClientEncoding();
649 /* report this backend in the PgBackendStatus array */
650 if (!bootstrap)
651 pgstat_bestart();
653 /* close the transaction we started above */
654 if (!bootstrap)
655 CommitTransactionCommand();
657 return am_superuser;
662 * Backend-shutdown callback. Do cleanup that we want to be sure happens
663 * before all the supporting modules begin to nail their doors shut via
664 * their own callbacks.
666 * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
667 * via separate callbacks that execute before this one. We don't combine the
668 * callbacks because we still want this one to happen if the user-level
669 * cleanup fails.
671 static void
672 ShutdownPostgres(int code, Datum arg)
674 /* Make sure we've killed any active transaction */
675 AbortOutOfAnyTransaction();
678 * User locks are not released by transaction end, so be sure to release
679 * them explicitly.
681 LockReleaseAll(USER_LOCKMETHOD, true);
686 * Returns true if at least one role is defined in this database cluster.
688 static bool
689 ThereIsAtLeastOneRole(void)
691 Relation pg_authid_rel;
692 HeapScanDesc scan;
693 bool result;
695 pg_authid_rel = heap_open(AuthIdRelationId, AccessShareLock);
697 scan = heap_beginscan(pg_authid_rel, SnapshotNow, 0, NULL);
698 result = (heap_getnext(scan, ForwardScanDirection) != NULL);
700 heap_endscan(scan);
701 heap_close(pg_authid_rel, AccessShareLock);
703 return result;