]> granicus.if.org Git - postgresql/blob - src/backend/utils/init/postinit.c
Move the HTSU_Result enum definition into snapshot.h, to avoid including
[postgresql] / src / backend / utils / init / postinit.c
1 /*-------------------------------------------------------------------------
2  *
3  * postinit.c
4  *        postgres initialization utilities
5  *
6  * Portions Copyright (c) 1996-2008, 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.182 2008/03/26 21:10:39 alvherre 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/sinvaladt.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 #include "utils/tqual.h"
49
50
51 static bool FindMyDatabase(const char *name, Oid *db_id, Oid *db_tablespace);
52 static bool FindMyDatabaseByOid(Oid dbid, char *dbname, Oid *db_tablespace);
53 static void CheckMyDatabase(const char *name, bool am_superuser);
54 static void InitCommunication(void);
55 static void ShutdownPostgres(int code, Datum arg);
56 static bool ThereIsAtLeastOneRole(void);
57
58
59 /*** InitPostgres support ***/
60
61
62 /*
63  * FindMyDatabase -- get the critical info needed to locate my database
64  *
65  * Find the named database in pg_database, return its database OID and the
66  * OID of its default tablespace.  Return TRUE if found, FALSE if not.
67  *
68  * Since we are not yet up and running as a backend, we cannot look directly
69  * at pg_database (we can't obtain locks nor participate in transactions).
70  * So to get the info we need before starting up, we must look at the "flat
71  * file" copy of pg_database that is helpfully maintained by flatfiles.c.
72  * This is subject to various race conditions, so after we have the
73  * transaction infrastructure started, we have to recheck the information;
74  * see InitPostgres.
75  */
76 static bool
77 FindMyDatabase(const char *name, Oid *db_id, Oid *db_tablespace)
78 {
79         bool            result = false;
80         char       *filename;
81         FILE       *db_file;
82         char            thisname[NAMEDATALEN];
83         TransactionId db_frozenxid;
84
85         filename = database_getflatfilename();
86         db_file = AllocateFile(filename, "r");
87         if (db_file == NULL)
88                 ereport(FATAL,
89                                 (errcode_for_file_access(),
90                                  errmsg("could not open file \"%s\": %m", filename)));
91
92         while (read_pg_database_line(db_file, thisname, db_id,
93                                                                  db_tablespace, &db_frozenxid))
94         {
95                 if (strcmp(thisname, name) == 0)
96                 {
97                         result = true;
98                         break;
99                 }
100         }
101
102         FreeFile(db_file);
103         pfree(filename);
104
105         return result;
106 }
107
108 /*
109  * FindMyDatabaseByOid
110  *
111  * As above, but the actual database Id is known.  Return its name and the
112  * tablespace OID.      Return TRUE if found, FALSE if not.  The same restrictions
113  * as FindMyDatabase apply.
114  */
115 static bool
116 FindMyDatabaseByOid(Oid dbid, char *dbname, Oid *db_tablespace)
117 {
118         bool            result = false;
119         char       *filename;
120         FILE       *db_file;
121         Oid                     db_id;
122         char            thisname[NAMEDATALEN];
123         TransactionId db_frozenxid;
124
125         filename = database_getflatfilename();
126         db_file = AllocateFile(filename, "r");
127         if (db_file == NULL)
128                 ereport(FATAL,
129                                 (errcode_for_file_access(),
130                                  errmsg("could not open file \"%s\": %m", filename)));
131
132         while (read_pg_database_line(db_file, thisname, &db_id,
133                                                                  db_tablespace, &db_frozenxid))
134         {
135                 if (dbid == db_id)
136                 {
137                         result = true;
138                         strlcpy(dbname, thisname, NAMEDATALEN);
139                         break;
140                 }
141         }
142
143         FreeFile(db_file);
144         pfree(filename);
145
146         return result;
147 }
148
149
150 /*
151  * CheckMyDatabase -- fetch information from the pg_database entry for our DB
152  */
153 static void
154 CheckMyDatabase(const char *name, bool am_superuser)
155 {
156         HeapTuple       tup;
157         Form_pg_database dbform;
158
159         /* Fetch our real pg_database row */
160         tup = SearchSysCache(DATABASEOID,
161                                                  ObjectIdGetDatum(MyDatabaseId),
162                                                  0, 0, 0);
163         if (!HeapTupleIsValid(tup))
164                 elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
165         dbform = (Form_pg_database) GETSTRUCT(tup);
166
167         /* This recheck is strictly paranoia */
168         if (strcmp(name, NameStr(dbform->datname)) != 0)
169                 ereport(FATAL,
170                                 (errcode(ERRCODE_UNDEFINED_DATABASE),
171                                  errmsg("database \"%s\" has disappeared from pg_database",
172                                                 name),
173                                  errdetail("Database OID %u now seems to belong to \"%s\".",
174                                                    MyDatabaseId, NameStr(dbform->datname))));
175
176         /*
177          * Check permissions to connect to the database.
178          *
179          * These checks are not enforced when in standalone mode, so that there is
180          * a way to recover from disabling all access to all databases, for
181          * example "UPDATE pg_database SET datallowconn = false;".
182          *
183          * We do not enforce them for the autovacuum worker processes either.
184          */
185         if (IsUnderPostmaster && !IsAutoVacuumWorkerProcess())
186         {
187                 /*
188                  * Check that the database is currently allowing connections.
189                  */
190                 if (!dbform->datallowconn)
191                         ereport(FATAL,
192                                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
193                          errmsg("database \"%s\" is not currently accepting connections",
194                                         name)));
195
196                 /*
197                  * Check privilege to connect to the database.  (The am_superuser test
198                  * is redundant, but since we have the flag, might as well check it
199                  * and save a few cycles.)
200                  */
201                 if (!am_superuser &&
202                         pg_database_aclcheck(MyDatabaseId, GetUserId(),
203                                                                  ACL_CONNECT) != ACLCHECK_OK)
204                         ereport(FATAL,
205                                         (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
206                                          errmsg("permission denied for database \"%s\"", name),
207                                          errdetail("User does not have CONNECT privilege.")));
208
209                 /*
210                  * Check connection limit for this database.
211                  *
212                  * There is a race condition here --- we create our PGPROC before
213                  * checking for other PGPROCs.  If two backends did this at about the
214                  * same time, they might both think they were over the limit, while
215                  * ideally one should succeed and one fail.  Getting that to work
216                  * exactly seems more trouble than it is worth, however; instead we
217                  * just document that the connection limit is approximate.
218                  */
219                 if (dbform->datconnlimit >= 0 &&
220                         !am_superuser &&
221                         CountDBBackends(MyDatabaseId) > dbform->datconnlimit)
222                         ereport(FATAL,
223                                         (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
224                                          errmsg("too many connections for database \"%s\"",
225                                                         name)));
226         }
227
228         /*
229          * OK, we're golden.  Next to-do item is to save the encoding info out of
230          * the pg_database tuple.
231          */
232         SetDatabaseEncoding(dbform->encoding);
233         /* Record it as a GUC internal option, too */
234         SetConfigOption("server_encoding", GetDatabaseEncodingName(),
235                                         PGC_INTERNAL, PGC_S_OVERRIDE);
236         /* If we have no other source of client_encoding, use server encoding */
237         SetConfigOption("client_encoding", GetDatabaseEncodingName(),
238                                         PGC_BACKEND, PGC_S_DEFAULT);
239
240         /*
241          * Lastly, set up any database-specific configuration variables.
242          */
243         if (IsUnderPostmaster)
244         {
245                 Datum           datum;
246                 bool            isnull;
247
248                 datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_datconfig,
249                                                                 &isnull);
250                 if (!isnull)
251                 {
252                         ArrayType  *a = DatumGetArrayTypeP(datum);
253
254                         /*
255                          * We process all the options at SUSET level.  We assume that the
256                          * right to insert an option into pg_database was checked when it
257                          * was inserted.
258                          */
259                         ProcessGUCArray(a, PGC_SUSET, PGC_S_DATABASE, GUC_ACTION_SET);
260                 }
261         }
262
263         ReleaseSysCache(tup);
264 }
265
266
267
268 /* --------------------------------
269  *              InitCommunication
270  *
271  *              This routine initializes stuff needed for ipc, locking, etc.
272  *              it should be called something more informative.
273  * --------------------------------
274  */
275 static void
276 InitCommunication(void)
277 {
278         /*
279          * initialize shared memory and semaphores appropriately.
280          */
281         if (!IsUnderPostmaster)         /* postmaster already did this */
282         {
283                 /*
284                  * We're running a postgres bootstrap process or a standalone backend.
285                  * Create private "shmem" and semaphores.
286                  */
287                 CreateSharedMemoryAndSemaphores(true, 0);
288         }
289 }
290
291
292 /*
293  * Early initialization of a backend (either standalone or under postmaster).
294  * This happens even before InitPostgres.
295  *
296  * If you're wondering why this is separate from InitPostgres at all:
297  * the critical distinction is that this stuff has to happen before we can
298  * run XLOG-related initialization, which is done before InitPostgres --- in
299  * fact, for cases such as checkpoint creation processes, InitPostgres may
300  * never be done at all.
301  */
302 void
303 BaseInit(void)
304 {
305         /*
306          * Attach to shared memory and semaphores, and initialize our
307          * input/output/debugging file descriptors.
308          */
309         InitCommunication();
310         DebugFileOpen();
311
312         /* Do local initialization of file, storage and buffer managers */
313         InitFileAccess();
314         smgrinit();
315         InitBufferPoolAccess();
316 }
317
318
319 /* --------------------------------
320  * InitPostgres
321  *              Initialize POSTGRES.
322  *
323  * The database can be specified by name, using the in_dbname parameter, or by
324  * OID, using the dboid parameter.      In the latter case, the computed database
325  * name is passed out to the caller as a palloc'ed string in out_dbname.
326  *
327  * In bootstrap mode no parameters are used.
328  *
329  * The return value indicates whether the userID is a superuser.  (That
330  * can only be tested inside a transaction, so we want to do it during
331  * the startup transaction rather than doing a separate one in postgres.c.)
332  *
333  * As of PostgreSQL 8.2, we expect InitProcess() was already called, so we
334  * already have a PGPROC struct ... but it's not filled in yet.
335  *
336  * Note:
337  *              Be very careful with the order of calls in the InitPostgres function.
338  * --------------------------------
339  */
340 bool
341 InitPostgres(const char *in_dbname, Oid dboid, const char *username,
342                          char **out_dbname)
343 {
344         bool            bootstrap = IsBootstrapProcessingMode();
345         bool            autovacuum = IsAutoVacuumWorkerProcess();
346         bool            am_superuser;
347         char       *fullpath;
348         char            dbname[NAMEDATALEN];
349
350         /*
351          * Set up the global variables holding database id and path.  But note we
352          * won't actually try to touch the database just yet.
353          *
354          * We take a shortcut in the bootstrap case, otherwise we have to look up
355          * the db name in pg_database.
356          */
357         if (bootstrap)
358         {
359                 MyDatabaseId = TemplateDbOid;
360                 MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
361         }
362         else
363         {
364                 /*
365                  * Find tablespace of the database we're about to open. Since we're
366                  * not yet up and running we have to use one of the hackish
367                  * FindMyDatabase variants, which look in the flat-file copy of
368                  * pg_database.
369                  *
370                  * If the in_dbname param is NULL, lookup database by OID.
371                  */
372                 if (in_dbname == NULL)
373                 {
374                         if (!FindMyDatabaseByOid(dboid, dbname, &MyDatabaseTableSpace))
375                                 ereport(FATAL,
376                                                 (errcode(ERRCODE_UNDEFINED_DATABASE),
377                                                  errmsg("database %u does not exist", dboid)));
378                         MyDatabaseId = dboid;
379                         /* pass the database name to the caller */
380                         *out_dbname = pstrdup(dbname);
381                 }
382                 else
383                 {
384                         if (!FindMyDatabase(in_dbname, &MyDatabaseId, &MyDatabaseTableSpace))
385                                 ereport(FATAL,
386                                                 (errcode(ERRCODE_UNDEFINED_DATABASE),
387                                                  errmsg("database \"%s\" does not exist",
388                                                                 in_dbname)));
389                         /* our database name is gotten from the caller */
390                         strlcpy(dbname, in_dbname, NAMEDATALEN);
391                 }
392         }
393
394         fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
395
396         SetDatabasePath(fullpath);
397
398         /*
399          * Finish filling in the PGPROC struct, and add it to the ProcArray. (We
400          * need to know MyDatabaseId before we can do this, since it's entered
401          * into the PGPROC struct.)
402          *
403          * Once I have done this, I am visible to other backends!
404          */
405         InitProcessPhase2();
406
407         /*
408          * Initialize my entry in the shared-invalidation manager's array of
409          * per-backend data.
410          *
411          * Sets up MyBackendId, a unique backend identifier.
412          */
413         MyBackendId = InvalidBackendId;
414
415         SharedInvalBackendInit();
416
417         if (MyBackendId > MaxBackends || MyBackendId <= 0)
418                 elog(FATAL, "bad backend id: %d", MyBackendId);
419
420         /*
421          * bufmgr needs another initialization call too
422          */
423         InitBufferPoolBackend();
424
425         /*
426          * Initialize local process's access to XLOG.  In bootstrap case we may
427          * skip this since StartupXLOG() was run instead.
428          */
429         if (!bootstrap)
430                 InitXLOGAccess();
431
432         /*
433          * Initialize the relation cache and the system catalog caches.  Note that
434          * no catalog access happens here; we only set up the hashtable structure.
435          * We must do this before starting a transaction because transaction abort
436          * would try to touch these hashtables.
437          */
438         RelationCacheInitialize();
439         InitCatalogCache();
440         InitPlanCache();
441
442         /* Initialize portal manager */
443         EnablePortalManager();
444
445         /* Initialize stats collection --- must happen before first xact */
446         if (!bootstrap)
447                 pgstat_initialize();
448
449         /*
450          * Set up process-exit callback to do pre-shutdown cleanup.  This has to
451          * be after we've initialized all the low-level modules like the buffer
452          * manager, because during shutdown this has to run before the low-level
453          * modules start to close down.  On the other hand, we want it in place
454          * before we begin our first transaction --- if we fail during the
455          * initialization transaction, as is entirely possible, we need the
456          * AbortTransaction call to clean up.
457          */
458         on_shmem_exit(ShutdownPostgres, 0);
459
460         /*
461          * Start a new transaction here before first access to db
462          */
463         if (!bootstrap)
464                 StartTransactionCommand();
465
466         /*
467          * Now that we have a transaction, we can take locks.  Take a writer's
468          * lock on the database we are trying to connect to.  If there is a
469          * concurrently running DROP DATABASE on that database, this will block us
470          * until it finishes (and has updated the flat file copy of pg_database).
471          *
472          * Note that the lock is not held long, only until the end of this startup
473          * transaction.  This is OK since we are already advertising our use of
474          * the database in the PGPROC array; anyone trying a DROP DATABASE after
475          * this point will see us there.
476          *
477          * Note: use of RowExclusiveLock here is reasonable because we envision
478          * our session as being a concurrent writer of the database.  If we had a
479          * way of declaring a session as being guaranteed-read-only, we could use
480          * AccessShareLock for such sessions and thereby not conflict against
481          * CREATE DATABASE.
482          */
483         if (!bootstrap)
484                 LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
485                                                  RowExclusiveLock);
486
487         /*
488          * Recheck the flat file copy of pg_database to make sure the target
489          * database hasn't gone away.  If there was a concurrent DROP DATABASE,
490          * this ensures we will die cleanly without creating a mess.
491          */
492         if (!bootstrap)
493         {
494                 Oid                     dbid2;
495                 Oid                     tsid2;
496
497                 if (!FindMyDatabase(dbname, &dbid2, &tsid2) ||
498                         dbid2 != MyDatabaseId || tsid2 != MyDatabaseTableSpace)
499                         ereport(FATAL,
500                                         (errcode(ERRCODE_UNDEFINED_DATABASE),
501                                          errmsg("database \"%s\" does not exist",
502                                                         dbname),
503                            errdetail("It seems to have just been dropped or renamed.")));
504         }
505
506         /*
507          * Now we should be able to access the database directory safely. Verify
508          * it's there and looks reasonable.
509          */
510         if (!bootstrap)
511         {
512                 if (access(fullpath, F_OK) == -1)
513                 {
514                         if (errno == ENOENT)
515                                 ereport(FATAL,
516                                                 (errcode(ERRCODE_UNDEFINED_DATABASE),
517                                                  errmsg("database \"%s\" does not exist",
518                                                                 dbname),
519                                         errdetail("The database subdirectory \"%s\" is missing.",
520                                                           fullpath)));
521                         else
522                                 ereport(FATAL,
523                                                 (errcode_for_file_access(),
524                                                  errmsg("could not access directory \"%s\": %m",
525                                                                 fullpath)));
526                 }
527
528                 ValidatePgVersion(fullpath);
529         }
530
531         /*
532          * It's now possible to do real access to the system catalogs.
533          *
534          * Load relcache entries for the system catalogs.  This must create at
535          * least the minimum set of "nailed-in" cache entries.
536          */
537         RelationCacheInitializePhase2();
538
539         /*
540          * Figure out our postgres user id, and see if we are a superuser.
541          *
542          * In standalone mode and in the autovacuum process, we use a fixed id,
543          * otherwise we figure it out from the authenticated user name.
544          */
545         if (bootstrap || autovacuum)
546         {
547                 InitializeSessionUserIdStandalone();
548                 am_superuser = true;
549         }
550         else if (!IsUnderPostmaster)
551         {
552                 InitializeSessionUserIdStandalone();
553                 am_superuser = true;
554                 if (!ThereIsAtLeastOneRole())
555                         ereport(WARNING,
556                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
557                                          errmsg("no roles are defined in this database system"),
558                                          errhint("You should immediately run CREATE USER \"%s\" CREATEUSER;.",
559                                                          username)));
560         }
561         else
562         {
563                 /* normal multiuser case */
564                 InitializeSessionUserId(username);
565                 am_superuser = superuser();
566         }
567
568         /* set up ACL framework (so CheckMyDatabase can check permissions) */
569         initialize_acl();
570
571         /*
572          * Read the real pg_database row for our database, check permissions and
573          * set up database-specific GUC settings.  We can't do this until all the
574          * database-access infrastructure is up.  (Also, it wants to know if the
575          * user is a superuser, so the above stuff has to happen first.)
576          */
577         if (!bootstrap)
578                 CheckMyDatabase(dbname, am_superuser);
579
580         /*
581          * Check a normal user hasn't connected to a superuser reserved slot.
582          */
583         if (!am_superuser &&
584                 ReservedBackends > 0 &&
585                 !HaveNFreeProcs(ReservedBackends))
586                 ereport(FATAL,
587                                 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
588                                  errmsg("connection limit exceeded for non-superusers")));
589
590         /*
591          * Initialize various default states that can't be set up until we've
592          * selected the active user and gotten the right GUC settings.
593          */
594
595         /* set default namespace search path */
596         InitializeSearchPath();
597
598         /* initialize client encoding */
599         InitializeClientEncoding();
600
601         /* report this backend in the PgBackendStatus array */
602         if (!bootstrap)
603                 pgstat_bestart();
604
605         /* close the transaction we started above */
606         if (!bootstrap)
607                 CommitTransactionCommand();
608
609         return am_superuser;
610 }
611
612
613 /*
614  * Backend-shutdown callback.  Do cleanup that we want to be sure happens
615  * before all the supporting modules begin to nail their doors shut via
616  * their own callbacks.
617  *
618  * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
619  * via separate callbacks that execute before this one.  We don't combine the
620  * callbacks because we still want this one to happen if the user-level
621  * cleanup fails.
622  */
623 static void
624 ShutdownPostgres(int code, Datum arg)
625 {
626         /* Make sure we've killed any active transaction */
627         AbortOutOfAnyTransaction();
628
629         /*
630          * User locks are not released by transaction end, so be sure to release
631          * them explicitly.
632          */
633         LockReleaseAll(USER_LOCKMETHOD, true);
634 }
635
636
637 /*
638  * Returns true if at least one role is defined in this database cluster.
639  */
640 static bool
641 ThereIsAtLeastOneRole(void)
642 {
643         Relation        pg_authid_rel;
644         HeapScanDesc scan;
645         bool            result;
646
647         pg_authid_rel = heap_open(AuthIdRelationId, AccessShareLock);
648
649         scan = heap_beginscan(pg_authid_rel, SnapshotNow, 0, NULL);
650         result = (heap_getnext(scan, ForwardScanDirection) != NULL);
651
652         heap_endscan(scan);
653         heap_close(pg_authid_rel, AccessShareLock);
654
655         return result;
656 }