]> granicus.if.org Git - postgresql/blob - src/backend/utils/init/postinit.c
daef3199fa6285a2848cf81783c5c39fef63ee24
[postgresql] / src / backend / utils / init / postinit.c
1 /*-------------------------------------------------------------------------
2  *
3  * postinit.c
4  *        postgres initialization utilities
5  *
6  * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/utils/init/postinit.c,v 1.175 2007/03/13 00:33:42 tgl Exp $
12  *
13  *
14  *-------------------------------------------------------------------------
15  */
16 #include "postgres.h"
17
18 #include <fcntl.h>
19 #include <unistd.h>
20
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"
31 #include "pgstat.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"
48
49
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);
56
57
58 /*** InitPostgres support ***/
59
60
61 /*
62  * FindMyDatabase -- get the critical info needed to locate my database
63  *
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.
66  *
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;
73  * see InitPostgres.
74  */
75 static bool
76 FindMyDatabase(const char *name, Oid *db_id, Oid *db_tablespace)
77 {
78         bool            result = false;
79         char       *filename;
80         FILE       *db_file;
81         char            thisname[NAMEDATALEN];
82         TransactionId db_frozenxid;
83
84         filename = database_getflatfilename();
85         db_file = AllocateFile(filename, "r");
86         if (db_file == NULL)
87                 ereport(FATAL,
88                                 (errcode_for_file_access(),
89                                  errmsg("could not open file \"%s\": %m", filename)));
90
91         while (read_pg_database_line(db_file, thisname, db_id,
92                                                                  db_tablespace, &db_frozenxid))
93         {
94                 if (strcmp(thisname, name) == 0)
95                 {
96                         result = true;
97                         break;
98                 }
99         }
100
101         FreeFile(db_file);
102         pfree(filename);
103
104         return result;
105 }
106
107 /*
108  * FindMyDatabaseByOid
109  *
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.
113  */
114 static bool
115 FindMyDatabaseByOid(Oid dbid, char *dbname, Oid *db_tablespace)
116 {
117         bool            result = false;
118         char       *filename;
119         FILE       *db_file;
120         Oid                     db_id;
121         char            thisname[NAMEDATALEN];
122         TransactionId db_frozenxid;
123
124         filename = database_getflatfilename();
125         db_file = AllocateFile(filename, "r");
126         if (db_file == NULL)
127                 ereport(FATAL,
128                                 (errcode_for_file_access(),
129                                  errmsg("could not open file \"%s\": %m", filename)));
130
131         while (read_pg_database_line(db_file, thisname, &db_id,
132                                                                  db_tablespace, &db_frozenxid))
133         {
134                 if (dbid == db_id)
135                 {
136                         result = true;
137                         strlcpy(dbname, thisname, NAMEDATALEN);
138                         break;
139                 }
140         }
141
142         FreeFile(db_file);
143         pfree(filename);
144
145         return result;
146 }
147
148
149 /*
150  * CheckMyDatabase -- fetch information from the pg_database entry for our DB
151  */
152 static void
153 CheckMyDatabase(const char *name, bool am_superuser)
154 {
155         HeapTuple       tup;
156         Form_pg_database dbform;
157
158         /* Fetch our real pg_database row */
159         tup = SearchSysCache(DATABASEOID,
160                                                  ObjectIdGetDatum(MyDatabaseId),
161                                                  0, 0, 0);
162         if (!HeapTupleIsValid(tup))
163                 elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
164         dbform = (Form_pg_database) GETSTRUCT(tup);
165
166         /* This recheck is strictly paranoia */
167         if (strcmp(name, NameStr(dbform->datname)) != 0)
168                 ereport(FATAL,
169                                 (errcode(ERRCODE_UNDEFINED_DATABASE),
170                                  errmsg("database \"%s\" has disappeared from pg_database",
171                                                 name),
172                                  errdetail("Database OID %u now seems to belong to \"%s\".",
173                                                    MyDatabaseId, NameStr(dbform->datname))));
174
175         /*
176          * Check permissions to connect to the database.
177          *
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;".
181          *
182          * We do not enforce them for the autovacuum worker processes either.
183          */
184         if (IsUnderPostmaster && !IsAutoVacuumWorkerProcess())
185         {
186                 /*
187                  * Check that the database is currently allowing connections.
188                  */
189                 if (!dbform->datallowconn)
190                         ereport(FATAL,
191                                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
192                          errmsg("database \"%s\" is not currently accepting connections",
193                                         name)));
194
195                 /*
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.)
199                  */
200                 if (!am_superuser &&
201                         pg_database_aclcheck(MyDatabaseId, GetUserId(),
202                                                                  ACL_CONNECT) != ACLCHECK_OK)
203                         ereport(FATAL,
204                                         (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
205                                          errmsg("permission denied for database \"%s\"", name),
206                                          errdetail("User does not have CONNECT privilege.")));
207
208                 /*
209                  * Check connection limit for this database.
210                  *
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.
217                  */
218                 if (dbform->datconnlimit >= 0 &&
219                         !am_superuser &&
220                         CountDBBackends(MyDatabaseId) > dbform->datconnlimit)
221                         ereport(FATAL,
222                                         (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
223                                          errmsg("too many connections for database \"%s\"",
224                                                         name)));
225         }
226
227         /*
228          * OK, we're golden.  Next to-do item is to save the encoding info out of
229          * the pg_database tuple.
230          */
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);
238
239         /*
240          * Lastly, set up any database-specific configuration variables.
241          */
242         if (IsUnderPostmaster)
243         {
244                 Datum           datum;
245                 bool            isnull;
246
247                 datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_datconfig,
248                                                                 &isnull);
249                 if (!isnull)
250                 {
251                         ArrayType  *a = DatumGetArrayTypeP(datum);
252
253                         ProcessGUCArray(a, PGC_S_DATABASE);
254                 }
255         }
256
257         ReleaseSysCache(tup);
258 }
259
260
261
262 /* --------------------------------
263  *              InitCommunication
264  *
265  *              This routine initializes stuff needed for ipc, locking, etc.
266  *              it should be called something more informative.
267  * --------------------------------
268  */
269 static void
270 InitCommunication(void)
271 {
272         /*
273          * initialize shared memory and semaphores appropriately.
274          */
275         if (!IsUnderPostmaster)         /* postmaster already did this */
276         {
277                 /*
278                  * We're running a postgres bootstrap process or a standalone backend.
279                  * Create private "shmem" and semaphores.
280                  */
281                 CreateSharedMemoryAndSemaphores(true, 0);
282         }
283 }
284
285
286 /*
287  * Early initialization of a backend (either standalone or under postmaster).
288  * This happens even before InitPostgres.
289  *
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.
295  */
296 void
297 BaseInit(void)
298 {
299         /*
300          * Attach to shared memory and semaphores, and initialize our
301          * input/output/debugging file descriptors.
302          */
303         InitCommunication();
304         DebugFileOpen();
305
306         /* Do local initialization of file, storage and buffer managers */
307         InitFileAccess();
308         smgrinit();
309         InitBufferPoolAccess();
310 }
311
312
313 /* --------------------------------
314  * InitPostgres
315  *              Initialize POSTGRES.
316  *
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.
320  *
321  * In bootstrap mode no parameters are used.
322  *
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.)
326  *
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.
329  *
330  * Note:
331  *              Be very careful with the order of calls in the InitPostgres function.
332  * --------------------------------
333  */
334 bool
335 InitPostgres(const char *in_dbname, Oid dboid, const char *username,
336                          char **out_dbname)
337 {
338         bool            bootstrap = IsBootstrapProcessingMode();
339         bool            autovacuum = IsAutoVacuumWorkerProcess();
340         bool            am_superuser;
341         char       *fullpath;
342         char            dbname[NAMEDATALEN];
343
344         /*
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.
347          *
348          * We take a shortcut in the bootstrap case, otherwise we have to look up
349          * the db name in pg_database.
350          */
351         if (bootstrap)
352         {
353                 MyDatabaseId = TemplateDbOid;
354                 MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
355         }
356         else
357         {
358                 /*
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.
362                  *
363                  * If the in_dbname param is NULL, lookup database by OID.
364                  */
365                 if (in_dbname == NULL)
366                 {
367                         if (!FindMyDatabaseByOid(dboid, dbname, &MyDatabaseTableSpace))
368                                 ereport(FATAL,
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);
374                 }
375                 else
376                 {
377                         if (!FindMyDatabase(in_dbname, &MyDatabaseId, &MyDatabaseTableSpace))
378                                 ereport(FATAL,
379                                                 (errcode(ERRCODE_UNDEFINED_DATABASE),
380                                                  errmsg("database \"%s\" does not exist",
381                                                                 in_dbname)));
382                         /* our database name is gotten from the caller */
383                         strlcpy(dbname, in_dbname, NAMEDATALEN);
384                 }
385         }
386
387         fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
388
389         SetDatabasePath(fullpath);
390
391         /*
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.)
395          *
396          * Once I have done this, I am visible to other backends!
397          */
398         InitProcessPhase2();
399
400         /*
401          * Initialize my entry in the shared-invalidation manager's array of
402          * per-backend data.
403          *
404          * Sets up MyBackendId, a unique backend identifier.
405          */
406         MyBackendId = InvalidBackendId;
407
408         InitBackendSharedInvalidationState();
409
410         if (MyBackendId > MaxBackends || MyBackendId <= 0)
411                 elog(FATAL, "bad backend id: %d", MyBackendId);
412
413         /*
414          * bufmgr needs another initialization call too
415          */
416         InitBufferPoolBackend();
417
418         /*
419          * Initialize local process's access to XLOG.  In bootstrap case we may
420          * skip this since StartupXLOG() was run instead.
421          */
422         if (!bootstrap)
423                 InitXLOGAccess();
424
425         /*
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.
430          */
431         RelationCacheInitialize();
432         InitCatalogCache();
433         InitPlanCache();
434
435         /* Initialize portal manager */
436         EnablePortalManager();
437
438         /*
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.
446          */
447         on_shmem_exit(ShutdownPostgres, 0);
448
449         /*
450          * Start a new transaction here before first access to db
451          */
452         if (!bootstrap)
453                 StartTransactionCommand();
454
455         /*
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).
460          *
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.
465          *
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
470          * CREATE DATABASE.
471          */
472         if (!bootstrap)
473                 LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
474                                                  RowExclusiveLock);
475
476         /*
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.
480          */
481         if (!bootstrap)
482         {
483                 Oid                     dbid2;
484                 Oid                     tsid2;
485
486                 if (!FindMyDatabase(dbname, &dbid2, &tsid2) ||
487                         dbid2 != MyDatabaseId || tsid2 != MyDatabaseTableSpace)
488                         ereport(FATAL,
489                                         (errcode(ERRCODE_UNDEFINED_DATABASE),
490                                          errmsg("database \"%s\" does not exist",
491                                                         dbname),
492                            errdetail("It seems to have just been dropped or renamed.")));
493         }
494
495         /*
496          * Now we should be able to access the database directory safely. Verify
497          * it's there and looks reasonable.
498          */
499         if (!bootstrap)
500         {
501                 if (access(fullpath, F_OK) == -1)
502                 {
503                         if (errno == ENOENT)
504                                 ereport(FATAL,
505                                                 (errcode(ERRCODE_UNDEFINED_DATABASE),
506                                                  errmsg("database \"%s\" does not exist",
507                                                                 dbname),
508                                         errdetail("The database subdirectory \"%s\" is missing.",
509                                                           fullpath)));
510                         else
511                                 ereport(FATAL,
512                                                 (errcode_for_file_access(),
513                                                  errmsg("could not access directory \"%s\": %m",
514                                                                 fullpath)));
515                 }
516
517                 ValidatePgVersion(fullpath);
518         }
519
520         /*
521          * It's now possible to do real access to the system catalogs.
522          *
523          * Load relcache entries for the system catalogs.  This must create at
524          * least the minimum set of "nailed-in" cache entries.
525          */
526         RelationCacheInitializePhase2();
527
528         /*
529          * Figure out our postgres user id, and see if we are a superuser.
530          *
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.
533          */
534         if (bootstrap || autovacuum)
535         {
536                 InitializeSessionUserIdStandalone();
537                 am_superuser = true;
538         }
539         else if (!IsUnderPostmaster)
540         {
541                 InitializeSessionUserIdStandalone();
542                 am_superuser = true;
543                 if (!ThereIsAtLeastOneRole())
544                         ereport(WARNING,
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;.",
548                                                          username)));
549         }
550         else
551         {
552                 /* normal multiuser case */
553                 InitializeSessionUserId(username);
554                 am_superuser = superuser();
555         }
556
557         /* set up ACL framework (so CheckMyDatabase can check permissions) */
558         initialize_acl();
559
560         /*
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.)
565          */
566         if (!bootstrap)
567                 CheckMyDatabase(dbname, am_superuser);
568
569         /*
570          * Check a normal user hasn't connected to a superuser reserved slot.
571          */
572         if (!am_superuser &&
573                 ReservedBackends > 0 &&
574                 !HaveNFreeProcs(ReservedBackends))
575                 ereport(FATAL,
576                                 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
577                                  errmsg("connection limit exceeded for non-superusers")));
578
579         /*
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.
582          */
583
584         /* set default namespace search path */
585         InitializeSearchPath();
586
587         /* initialize client encoding */
588         InitializeClientEncoding();
589
590         /* initialize statistics collection for this backend */
591         if (!bootstrap)
592                 pgstat_bestart();
593
594         /* close the transaction we started above */
595         if (!bootstrap)
596                 CommitTransactionCommand();
597
598         return am_superuser;
599 }
600
601
602 /*
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.
606  *
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
610  * cleanup fails.
611  */
612 static void
613 ShutdownPostgres(int code, Datum arg)
614 {
615         /* Make sure we've killed any active transaction */
616         AbortOutOfAnyTransaction();
617
618         /*
619          * User locks are not released by transaction end, so be sure to release
620          * them explicitly.
621          */
622         LockReleaseAll(USER_LOCKMETHOD, true);
623 }
624
625
626 /*
627  * Returns true if at least one role is defined in this database cluster.
628  */
629 static bool
630 ThereIsAtLeastOneRole(void)
631 {
632         Relation        pg_authid_rel;
633         HeapScanDesc scan;
634         bool            result;
635
636         pg_authid_rel = heap_open(AuthIdRelationId, AccessShareLock);
637
638         scan = heap_beginscan(pg_authid_rel, SnapshotNow, 0, NULL);
639         result = (heap_getnext(scan, ForwardScanDirection) != NULL);
640
641         heap_endscan(scan);
642         heap_close(pg_authid_rel, AccessShareLock);
643
644         return result;
645 }