Need to use pg_perm_setlocale when setting LC_CTYPE and LC_COLLATE at startup.
[PostgreSQL.git] / src / backend / utils / init / postinit.c
blob327ba7c180571db72d13e56a980a04176d3f8d45
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/pg_locale.h"
48 #include "utils/plancache.h"
49 #include "utils/portal.h"
50 #include "utils/relcache.h"
51 #include "utils/snapmgr.h"
52 #include "utils/syscache.h"
53 #include "utils/tqual.h"
56 static bool FindMyDatabase(const char *name, Oid *db_id, Oid *db_tablespace);
57 static bool FindMyDatabaseByOid(Oid dbid, char *dbname, Oid *db_tablespace);
58 static void CheckMyDatabase(const char *name, bool am_superuser);
59 static void InitCommunication(void);
60 static void ShutdownPostgres(int code, Datum arg);
61 static bool ThereIsAtLeastOneRole(void);
64 /*** InitPostgres support ***/
68 * FindMyDatabase -- get the critical info needed to locate my database
70 * Find the named database in pg_database, return its database OID and the
71 * OID of its default tablespace. Return TRUE if found, FALSE if not.
73 * Since we are not yet up and running as a backend, we cannot look directly
74 * at pg_database (we can't obtain locks nor participate in transactions).
75 * So to get the info we need before starting up, we must look at the "flat
76 * file" copy of pg_database that is helpfully maintained by flatfiles.c.
77 * This is subject to various race conditions, so after we have the
78 * transaction infrastructure started, we have to recheck the information;
79 * see InitPostgres.
81 static bool
82 FindMyDatabase(const char *name, Oid *db_id, Oid *db_tablespace)
84 bool result = false;
85 char *filename;
86 FILE *db_file;
87 char thisname[NAMEDATALEN];
88 TransactionId db_frozenxid;
90 filename = database_getflatfilename();
91 db_file = AllocateFile(filename, "r");
92 if (db_file == NULL)
93 ereport(FATAL,
94 (errcode_for_file_access(),
95 errmsg("could not open file \"%s\": %m", filename)));
97 while (read_pg_database_line(db_file, thisname, db_id,
98 db_tablespace, &db_frozenxid))
100 if (strcmp(thisname, name) == 0)
102 result = true;
103 break;
107 FreeFile(db_file);
108 pfree(filename);
110 return result;
114 * FindMyDatabaseByOid
116 * As above, but the actual database Id is known. Return its name and the
117 * tablespace OID. Return TRUE if found, FALSE if not. The same restrictions
118 * as FindMyDatabase apply.
120 static bool
121 FindMyDatabaseByOid(Oid dbid, char *dbname, Oid *db_tablespace)
123 bool result = false;
124 char *filename;
125 FILE *db_file;
126 Oid db_id;
127 char thisname[NAMEDATALEN];
128 TransactionId db_frozenxid;
130 filename = database_getflatfilename();
131 db_file = AllocateFile(filename, "r");
132 if (db_file == NULL)
133 ereport(FATAL,
134 (errcode_for_file_access(),
135 errmsg("could not open file \"%s\": %m", filename)));
137 while (read_pg_database_line(db_file, thisname, &db_id,
138 db_tablespace, &db_frozenxid))
140 if (dbid == db_id)
142 result = true;
143 strlcpy(dbname, thisname, NAMEDATALEN);
144 break;
148 FreeFile(db_file);
149 pfree(filename);
151 return result;
156 * CheckMyDatabase -- fetch information from the pg_database entry for our DB
158 static void
159 CheckMyDatabase(const char *name, bool am_superuser)
161 HeapTuple tup;
162 Form_pg_database dbform;
163 char *collate;
164 char *ctype;
166 /* Fetch our real pg_database row */
167 tup = SearchSysCache(DATABASEOID,
168 ObjectIdGetDatum(MyDatabaseId),
169 0, 0, 0);
170 if (!HeapTupleIsValid(tup))
171 elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
172 dbform = (Form_pg_database) GETSTRUCT(tup);
174 /* This recheck is strictly paranoia */
175 if (strcmp(name, NameStr(dbform->datname)) != 0)
176 ereport(FATAL,
177 (errcode(ERRCODE_UNDEFINED_DATABASE),
178 errmsg("database \"%s\" has disappeared from pg_database",
179 name),
180 errdetail("Database OID %u now seems to belong to \"%s\".",
181 MyDatabaseId, NameStr(dbform->datname))));
184 * Check permissions to connect to the database.
186 * These checks are not enforced when in standalone mode, so that there is
187 * a way to recover from disabling all access to all databases, for
188 * example "UPDATE pg_database SET datallowconn = false;".
190 * We do not enforce them for the autovacuum worker processes either.
192 if (IsUnderPostmaster && !IsAutoVacuumWorkerProcess())
195 * Check that the database is currently allowing connections.
197 if (!dbform->datallowconn)
198 ereport(FATAL,
199 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
200 errmsg("database \"%s\" is not currently accepting connections",
201 name)));
204 * Check privilege to connect to the database. (The am_superuser test
205 * is redundant, but since we have the flag, might as well check it
206 * and save a few cycles.)
208 if (!am_superuser &&
209 pg_database_aclcheck(MyDatabaseId, GetUserId(),
210 ACL_CONNECT) != ACLCHECK_OK)
211 ereport(FATAL,
212 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
213 errmsg("permission denied for database \"%s\"", name),
214 errdetail("User does not have CONNECT privilege.")));
217 * Check connection limit for this database.
219 * There is a race condition here --- we create our PGPROC before
220 * checking for other PGPROCs. If two backends did this at about the
221 * same time, they might both think they were over the limit, while
222 * ideally one should succeed and one fail. Getting that to work
223 * exactly seems more trouble than it is worth, however; instead we
224 * just document that the connection limit is approximate.
226 if (dbform->datconnlimit >= 0 &&
227 !am_superuser &&
228 CountDBBackends(MyDatabaseId) > dbform->datconnlimit)
229 ereport(FATAL,
230 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
231 errmsg("too many connections for database \"%s\"",
232 name)));
236 * OK, we're golden. Next to-do item is to save the encoding info out of
237 * the pg_database tuple.
239 SetDatabaseEncoding(dbform->encoding);
240 /* Record it as a GUC internal option, too */
241 SetConfigOption("server_encoding", GetDatabaseEncodingName(),
242 PGC_INTERNAL, PGC_S_OVERRIDE);
243 /* If we have no other source of client_encoding, use server encoding */
244 SetConfigOption("client_encoding", GetDatabaseEncodingName(),
245 PGC_BACKEND, PGC_S_DEFAULT);
247 /* assign locale variables */
248 collate = NameStr(dbform->datcollate);
249 ctype = NameStr(dbform->datctype);
251 if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
252 ereport(FATAL,
253 (errmsg("database locale is incompatible with operating system"),
254 errdetail("The database was initialized with LC_COLLATE \"%s\", "
255 " which is not recognized by setlocale().", collate),
256 errhint("Recreate the database with another locale or install the missing locale.")));
258 if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
259 ereport(FATAL,
260 (errmsg("database locale is incompatible with operating system"),
261 errdetail("The database was initialized with LC_CTYPE \"%s\", "
262 " which is not recognized by setlocale().", ctype),
263 errhint("Recreate the database with another locale or install the missing locale.")));
265 /* Make the locale settings visible as GUC variables, too */
266 SetConfigOption("lc_collate", collate, PGC_INTERNAL, PGC_S_OVERRIDE);
267 SetConfigOption("lc_ctype", ctype, PGC_INTERNAL, PGC_S_OVERRIDE);
269 /* Use the right encoding in translated messages */
270 #ifdef ENABLE_NLS
271 pg_bind_textdomain_codeset(textdomain(NULL));
272 #endif
275 * Lastly, set up any database-specific configuration variables.
277 if (IsUnderPostmaster)
279 Datum datum;
280 bool isnull;
282 datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_datconfig,
283 &isnull);
284 if (!isnull)
286 ArrayType *a = DatumGetArrayTypeP(datum);
289 * We process all the options at SUSET level. We assume that the
290 * right to insert an option into pg_database was checked when it
291 * was inserted.
293 ProcessGUCArray(a, PGC_SUSET, PGC_S_DATABASE, GUC_ACTION_SET);
297 ReleaseSysCache(tup);
302 /* --------------------------------
303 * InitCommunication
305 * This routine initializes stuff needed for ipc, locking, etc.
306 * it should be called something more informative.
307 * --------------------------------
309 static void
310 InitCommunication(void)
313 * initialize shared memory and semaphores appropriately.
315 if (!IsUnderPostmaster) /* postmaster already did this */
318 * We're running a postgres bootstrap process or a standalone backend.
319 * Create private "shmem" and semaphores.
321 CreateSharedMemoryAndSemaphores(true, 0);
327 * Early initialization of a backend (either standalone or under postmaster).
328 * This happens even before InitPostgres.
330 * If you're wondering why this is separate from InitPostgres at all:
331 * the critical distinction is that this stuff has to happen before we can
332 * run XLOG-related initialization, which is done before InitPostgres --- in
333 * fact, for cases such as the background writer process, InitPostgres may
334 * never be done at all.
336 void
337 BaseInit(void)
340 * Attach to shared memory and semaphores, and initialize our
341 * input/output/debugging file descriptors.
343 InitCommunication();
344 DebugFileOpen();
346 /* Do local initialization of file, storage and buffer managers */
347 InitFileAccess();
348 smgrinit();
349 InitBufferPoolAccess();
353 /* --------------------------------
354 * InitPostgres
355 * Initialize POSTGRES.
357 * The database can be specified by name, using the in_dbname parameter, or by
358 * OID, using the dboid parameter. In the latter case, the computed database
359 * name is passed out to the caller as a palloc'ed string in out_dbname.
361 * In bootstrap mode no parameters are used.
363 * The return value indicates whether the userID is a superuser. (That
364 * can only be tested inside a transaction, so we want to do it during
365 * the startup transaction rather than doing a separate one in postgres.c.)
367 * As of PostgreSQL 8.2, we expect InitProcess() was already called, so we
368 * already have a PGPROC struct ... but it's not filled in yet.
370 * Note:
371 * Be very careful with the order of calls in the InitPostgres function.
372 * --------------------------------
374 bool
375 InitPostgres(const char *in_dbname, Oid dboid, const char *username,
376 char **out_dbname)
378 bool bootstrap = IsBootstrapProcessingMode();
379 bool autovacuum = IsAutoVacuumWorkerProcess();
380 bool am_superuser;
381 char *fullpath;
382 char dbname[NAMEDATALEN];
385 * Set up the global variables holding database id and path. But note we
386 * won't actually try to touch the database just yet.
388 * We take a shortcut in the bootstrap case, otherwise we have to look up
389 * the db name in pg_database.
391 if (bootstrap)
393 MyDatabaseId = TemplateDbOid;
394 MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
396 else
399 * Find tablespace of the database we're about to open. Since we're
400 * not yet up and running we have to use one of the hackish
401 * FindMyDatabase variants, which look in the flat-file copy of
402 * pg_database.
404 * If the in_dbname param is NULL, lookup database by OID.
406 if (in_dbname == NULL)
408 if (!FindMyDatabaseByOid(dboid, dbname, &MyDatabaseTableSpace))
409 ereport(FATAL,
410 (errcode(ERRCODE_UNDEFINED_DATABASE),
411 errmsg("database %u does not exist", dboid)));
412 MyDatabaseId = dboid;
413 /* pass the database name to the caller */
414 *out_dbname = pstrdup(dbname);
416 else
418 if (!FindMyDatabase(in_dbname, &MyDatabaseId, &MyDatabaseTableSpace))
419 ereport(FATAL,
420 (errcode(ERRCODE_UNDEFINED_DATABASE),
421 errmsg("database \"%s\" does not exist",
422 in_dbname)));
423 /* our database name is gotten from the caller */
424 strlcpy(dbname, in_dbname, NAMEDATALEN);
428 fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
430 SetDatabasePath(fullpath);
433 * Finish filling in the PGPROC struct, and add it to the ProcArray. (We
434 * need to know MyDatabaseId before we can do this, since it's entered
435 * into the PGPROC struct.)
437 * Once I have done this, I am visible to other backends!
439 InitProcessPhase2();
442 * Initialize my entry in the shared-invalidation manager's array of
443 * per-backend data.
445 * Sets up MyBackendId, a unique backend identifier.
447 MyBackendId = InvalidBackendId;
449 SharedInvalBackendInit();
451 if (MyBackendId > MaxBackends || MyBackendId <= 0)
452 elog(FATAL, "bad backend id: %d", MyBackendId);
455 * bufmgr needs another initialization call too
457 InitBufferPoolBackend();
460 * Initialize local process's access to XLOG. In bootstrap case we may
461 * skip this since StartupXLOG() was run instead.
463 if (!bootstrap)
464 InitXLOGAccess();
467 * Initialize the relation cache and the system catalog caches. Note that
468 * no catalog access happens here; we only set up the hashtable structure.
469 * We must do this before starting a transaction because transaction abort
470 * would try to touch these hashtables.
472 RelationCacheInitialize();
473 InitCatalogCache();
474 InitPlanCache();
476 /* Initialize portal manager */
477 EnablePortalManager();
479 /* Initialize stats collection --- must happen before first xact */
480 if (!bootstrap)
481 pgstat_initialize();
484 * Set up process-exit callback to do pre-shutdown cleanup. This has to
485 * be after we've initialized all the low-level modules like the buffer
486 * manager, because during shutdown this has to run before the low-level
487 * modules start to close down. On the other hand, we want it in place
488 * before we begin our first transaction --- if we fail during the
489 * initialization transaction, as is entirely possible, we need the
490 * AbortTransaction call to clean up.
492 on_shmem_exit(ShutdownPostgres, 0);
495 * Start a new transaction here before first access to db, and get a
496 * snapshot. We don't have a use for the snapshot itself, but we're
497 * interested in the secondary effect that it sets RecentGlobalXmin.
499 if (!bootstrap)
501 StartTransactionCommand();
502 (void) GetTransactionSnapshot();
506 * Now that we have a transaction, we can take locks. Take a writer's
507 * lock on the database we are trying to connect to. If there is a
508 * concurrently running DROP DATABASE on that database, this will block us
509 * until it finishes (and has updated the flat file copy of pg_database).
511 * Note that the lock is not held long, only until the end of this startup
512 * transaction. This is OK since we are already advertising our use of
513 * the database in the PGPROC array; anyone trying a DROP DATABASE after
514 * this point will see us there.
516 * Note: use of RowExclusiveLock here is reasonable because we envision
517 * our session as being a concurrent writer of the database. If we had a
518 * way of declaring a session as being guaranteed-read-only, we could use
519 * AccessShareLock for such sessions and thereby not conflict against
520 * CREATE DATABASE.
522 if (!bootstrap)
523 LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
524 RowExclusiveLock);
527 * Recheck the flat file copy of pg_database to make sure the target
528 * database hasn't gone away. If there was a concurrent DROP DATABASE,
529 * this ensures we will die cleanly without creating a mess.
531 if (!bootstrap)
533 Oid dbid2;
534 Oid tsid2;
536 if (!FindMyDatabase(dbname, &dbid2, &tsid2) ||
537 dbid2 != MyDatabaseId || tsid2 != MyDatabaseTableSpace)
538 ereport(FATAL,
539 (errcode(ERRCODE_UNDEFINED_DATABASE),
540 errmsg("database \"%s\" does not exist",
541 dbname),
542 errdetail("It seems to have just been dropped or renamed.")));
546 * Now we should be able to access the database directory safely. Verify
547 * it's there and looks reasonable.
549 if (!bootstrap)
551 if (access(fullpath, F_OK) == -1)
553 if (errno == ENOENT)
554 ereport(FATAL,
555 (errcode(ERRCODE_UNDEFINED_DATABASE),
556 errmsg("database \"%s\" does not exist",
557 dbname),
558 errdetail("The database subdirectory \"%s\" is missing.",
559 fullpath)));
560 else
561 ereport(FATAL,
562 (errcode_for_file_access(),
563 errmsg("could not access directory \"%s\": %m",
564 fullpath)));
567 ValidatePgVersion(fullpath);
571 * It's now possible to do real access to the system catalogs.
573 * Load relcache entries for the system catalogs. This must create at
574 * least the minimum set of "nailed-in" cache entries.
576 RelationCacheInitializePhase2();
579 * Figure out our postgres user id, and see if we are a superuser.
581 * In standalone mode and in the autovacuum process, we use a fixed id,
582 * otherwise we figure it out from the authenticated user name.
584 if (bootstrap || autovacuum)
586 InitializeSessionUserIdStandalone();
587 am_superuser = true;
589 else if (!IsUnderPostmaster)
591 InitializeSessionUserIdStandalone();
592 am_superuser = true;
593 if (!ThereIsAtLeastOneRole())
594 ereport(WARNING,
595 (errcode(ERRCODE_UNDEFINED_OBJECT),
596 errmsg("no roles are defined in this database system"),
597 errhint("You should immediately run CREATE USER \"%s\" CREATEUSER;.",
598 username)));
600 else
602 /* normal multiuser case */
603 InitializeSessionUserId(username);
604 am_superuser = superuser();
607 /* set up ACL framework (so CheckMyDatabase can check permissions) */
608 initialize_acl();
611 * Read the real pg_database row for our database, check permissions and
612 * set up database-specific GUC settings. We can't do this until all the
613 * database-access infrastructure is up. (Also, it wants to know if the
614 * user is a superuser, so the above stuff has to happen first.)
616 if (!bootstrap)
617 CheckMyDatabase(dbname, am_superuser);
620 * If we're trying to shut down, only superusers can connect.
622 if (!am_superuser &&
623 MyProcPort != NULL &&
624 MyProcPort->canAcceptConnections == CAC_WAITBACKUP)
625 ereport(FATAL,
626 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
627 errmsg("must be superuser to connect during database shutdown")));
630 * Check a normal user hasn't connected to a superuser reserved slot.
632 if (!am_superuser &&
633 ReservedBackends > 0 &&
634 !HaveNFreeProcs(ReservedBackends))
635 ereport(FATAL,
636 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
637 errmsg("connection limit exceeded for non-superusers")));
640 * Initialize various default states that can't be set up until we've
641 * selected the active user and gotten the right GUC settings.
644 /* set default namespace search path */
645 InitializeSearchPath();
647 /* initialize client encoding */
648 InitializeClientEncoding();
650 /* report this backend in the PgBackendStatus array */
651 if (!bootstrap)
652 pgstat_bestart();
654 /* close the transaction we started above */
655 if (!bootstrap)
656 CommitTransactionCommand();
658 return am_superuser;
663 * Backend-shutdown callback. Do cleanup that we want to be sure happens
664 * before all the supporting modules begin to nail their doors shut via
665 * their own callbacks.
667 * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
668 * via separate callbacks that execute before this one. We don't combine the
669 * callbacks because we still want this one to happen if the user-level
670 * cleanup fails.
672 static void
673 ShutdownPostgres(int code, Datum arg)
675 /* Make sure we've killed any active transaction */
676 AbortOutOfAnyTransaction();
679 * User locks are not released by transaction end, so be sure to release
680 * them explicitly.
682 LockReleaseAll(USER_LOCKMETHOD, true);
687 * Returns true if at least one role is defined in this database cluster.
689 static bool
690 ThereIsAtLeastOneRole(void)
692 Relation pg_authid_rel;
693 HeapScanDesc scan;
694 bool result;
696 pg_authid_rel = heap_open(AuthIdRelationId, AccessShareLock);
698 scan = heap_beginscan(pg_authid_rel, SnapshotNow, 0, NULL);
699 result = (heap_getnext(scan, ForwardScanDirection) != NULL);
701 heap_endscan(scan);
702 heap_close(pg_authid_rel, AccessShareLock);
704 return result;