OSDN Git Service

Re-run pgindent, fixing a problem where comment lines after a blank
[pg-rex/syncrep.git] / src / backend / utils / init / postinit.c
1 /*-------------------------------------------------------------------------
2  *
3  * postinit.c
4  *        postgres initialization utilities
5  *
6  * Portions Copyright (c) 1996-2005, 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.159 2005/11/22 18:17:26 momjian Exp $
12  *
13  *
14  *-------------------------------------------------------------------------
15  */
16 #include "postgres.h"
17
18 #include <fcntl.h>
19 #include <sys/file.h>
20 #include <math.h>
21 #include <unistd.h>
22
23 #include "access/genam.h"
24 #include "access/heapam.h"
25 #include "catalog/catalog.h"
26 #include "catalog/indexing.h"
27 #include "catalog/namespace.h"
28 #include "catalog/pg_authid.h"
29 #include "catalog/pg_database.h"
30 #include "catalog/pg_tablespace.h"
31 #include "libpq/hba.h"
32 #include "mb/pg_wchar.h"
33 #include "miscadmin.h"
34 #include "postmaster/autovacuum.h"
35 #include "postmaster/postmaster.h"
36 #include "storage/backendid.h"
37 #include "storage/fd.h"
38 #include "storage/ipc.h"
39 #include "storage/proc.h"
40 #include "storage/procarray.h"
41 #include "storage/sinval.h"
42 #include "storage/smgr.h"
43 #include "utils/acl.h"
44 #include "utils/flatfiles.h"
45 #include "utils/fmgroids.h"
46 #include "utils/guc.h"
47 #include "utils/portal.h"
48 #include "utils/relcache.h"
49 #include "utils/syscache.h"
50 #include "pgstat.h"
51
52
53 static bool FindMyDatabase(const char *name, Oid *db_id, Oid *db_tablespace);
54 static void ReverifyMyDatabase(const char *name);
55 static void InitCommunication(void);
56 static void ShutdownPostgres(int code, Datum arg);
57 static bool ThereIsAtLeastOneRole(void);
58
59
60 /*** InitPostgres support ***/
61
62
63 /*
64  * FindMyDatabase -- get the critical info needed to locate my database
65  *
66  * Find the named database in pg_database, return its database OID and the
67  * OID of its default tablespace.  Return TRUE if found, FALSE if not.
68  *
69  * Since we are not yet up and running as a backend, we cannot look directly
70  * at pg_database (we can't obtain locks nor participate in transactions).
71  * So to get the info we need before starting up, we must look at the "flat
72  * file" copy of pg_database that is helpfully maintained by flatfiles.c.
73  * This is subject to various race conditions, so after we have the
74  * transaction infrastructure started, we have to recheck the information;
75  * see ReverifyMyDatabase.
76  */
77 static bool
78 FindMyDatabase(const char *name, Oid *db_id, Oid *db_tablespace)
79 {
80         bool            result = false;
81         char       *filename;
82         FILE       *db_file;
83         char            thisname[NAMEDATALEN];
84         TransactionId dummyxid;
85
86         filename = database_getflatfilename();
87         db_file = AllocateFile(filename, "r");
88         if (db_file == NULL)
89                 ereport(FATAL,
90                                 (errcode_for_file_access(),
91                                  errmsg("could not open file \"%s\": %m", filename)));
92
93         while (read_pg_database_line(db_file, thisname, db_id,
94                                                                  db_tablespace, &dummyxid,
95                                                                  &dummyxid))
96         {
97                 if (strcmp(thisname, name) == 0)
98                 {
99                         result = true;
100                         break;
101                 }
102         }
103
104         FreeFile(db_file);
105         pfree(filename);
106
107         return result;
108 }
109
110 /*
111  * ReverifyMyDatabase -- recheck info obtained by FindMyDatabase
112  *
113  * Since FindMyDatabase cannot lock pg_database, the information it read
114  * could be stale; for example we might have attached to a database that's in
115  * process of being destroyed by dropdb().      This routine is called after
116  * we have all the locking and other infrastructure running --- now we can
117  * check that we are really attached to a valid database.
118  *
119  * In reality, if dropdb() is running in parallel with our startup,
120  * it's pretty likely that we will have failed before now, due to being
121  * unable to read some of the system tables within the doomed database.
122  * This routine just exists to make *sure* we have not started up in an
123  * invalid database.  If we quit now, we should have managed to avoid
124  * creating any serious problems.
125  *
126  * This is also a handy place to fetch the database encoding info out
127  * of pg_database.
128  *
129  * To avoid having to read pg_database more times than necessary
130  * during session startup, this place is also fitting to set up any
131  * database-specific configuration variables.
132  */
133 static void
134 ReverifyMyDatabase(const char *name)
135 {
136         Relation        pgdbrel;
137         SysScanDesc pgdbscan;
138         ScanKeyData key;
139         HeapTuple       tup;
140         Form_pg_database dbform;
141
142         /*
143          * Because we grab RowShareLock here, we can be sure that dropdb() is not
144          * running in parallel with us (any more).
145          */
146         pgdbrel = heap_open(DatabaseRelationId, RowShareLock);
147
148         ScanKeyInit(&key,
149                                 Anum_pg_database_datname,
150                                 BTEqualStrategyNumber, F_NAMEEQ,
151                                 NameGetDatum(name));
152
153         pgdbscan = systable_beginscan(pgdbrel, DatabaseNameIndexId, true,
154                                                                   SnapshotNow, 1, &key);
155
156         tup = systable_getnext(pgdbscan);
157         if (!HeapTupleIsValid(tup) ||
158                 HeapTupleGetOid(tup) != MyDatabaseId)
159         {
160                 /* OOPS */
161                 heap_close(pgdbrel, RowShareLock);
162
163                 /*
164                  * The only real problem I could have created is to load dirty buffers
165                  * for the dead database into shared buffer cache; if I did, some
166                  * other backend will eventually try to write them and die in
167                  * mdblindwrt.  Flush any such pages to forestall trouble.
168                  */
169                 DropBuffers(MyDatabaseId);
170                 /* Now I can commit hara-kiri with a clear conscience... */
171                 ereport(FATAL,
172                                 (errcode(ERRCODE_UNDEFINED_DATABASE),
173                   errmsg("database \"%s\", OID %u, has disappeared from pg_database",
174                                  name, MyDatabaseId)));
175         }
176
177         dbform = (Form_pg_database) GETSTRUCT(tup);
178
179         /*
180          * These next checks are not enforced when in standalone mode, so that
181          * there is a way to recover from disabling all access to all databases,
182          * for example "UPDATE pg_database SET datallowconn = false;".
183          *
184          * We do not enforce them for the autovacuum process either.
185          */
186         if (IsUnderPostmaster && !IsAutoVacuumProcess())
187         {
188                 /*
189                  * Check that the database is currently allowing connections.
190                  */
191                 if (!dbform->datallowconn)
192                         ereport(FATAL,
193                                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
194                          errmsg("database \"%s\" is not currently accepting connections",
195                                         name)));
196
197                 /*
198                  * Check connection limit for this database.
199                  *
200                  * There is a race condition here --- we create our PGPROC before
201                  * checking for other PGPROCs.  If two backends did this at about the
202                  * same time, they might both think they were over the limit, while
203                  * ideally one should succeed and one fail.  Getting that to work
204                  * exactly seems more trouble than it is worth, however; instead we
205                  * just document that the connection limit is approximate.
206                  */
207                 if (dbform->datconnlimit >= 0 &&
208                         !superuser() &&
209                         CountDBBackends(MyDatabaseId) > dbform->datconnlimit)
210                         ereport(FATAL,
211                                         (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
212                                          errmsg("too many connections for database \"%s\"",
213                                                         name)));
214         }
215
216         /*
217          * OK, we're golden.  Next to-do item is to save the encoding info out of
218          * the pg_database tuple.
219          */
220         SetDatabaseEncoding(dbform->encoding);
221         /* Record it as a GUC internal option, too */
222         SetConfigOption("server_encoding", GetDatabaseEncodingName(),
223                                         PGC_INTERNAL, PGC_S_OVERRIDE);
224         /* If we have no other source of client_encoding, use server encoding */
225         SetConfigOption("client_encoding", GetDatabaseEncodingName(),
226                                         PGC_BACKEND, PGC_S_DEFAULT);
227
228         /*
229          * Lastly, set up any database-specific configuration variables.
230          */
231         if (IsUnderPostmaster)
232         {
233                 Datum           datum;
234                 bool            isnull;
235
236                 datum = heap_getattr(tup, Anum_pg_database_datconfig,
237                                                          RelationGetDescr(pgdbrel), &isnull);
238                 if (!isnull)
239                 {
240                         ArrayType  *a = DatumGetArrayTypeP(datum);
241
242                         ProcessGUCArray(a, PGC_S_DATABASE);
243                 }
244         }
245
246         systable_endscan(pgdbscan);
247         heap_close(pgdbrel, RowShareLock);
248 }
249
250
251
252 /* --------------------------------
253  *              InitCommunication
254  *
255  *              This routine initializes stuff needed for ipc, locking, etc.
256  *              it should be called something more informative.
257  * --------------------------------
258  */
259 static void
260 InitCommunication(void)
261 {
262         /*
263          * initialize shared memory and semaphores appropriately.
264          */
265         if (!IsUnderPostmaster)         /* postmaster already did this */
266         {
267                 /*
268                  * We're running a postgres bootstrap process or a standalone backend.
269                  * Create private "shmem" and semaphores.
270                  */
271                 CreateSharedMemoryAndSemaphores(true, 0);
272         }
273 }
274
275
276 /*
277  * Early initialization of a backend (either standalone or under postmaster).
278  * This happens even before InitPostgres.
279  *
280  * If you're wondering why this is separate from InitPostgres at all:
281  * the critical distinction is that this stuff has to happen before we can
282  * run XLOG-related initialization, which is done before InitPostgres --- in
283  * fact, for cases such as checkpoint creation processes, InitPostgres may
284  * never be done at all.
285  */
286 void
287 BaseInit(void)
288 {
289         /*
290          * Attach to shared memory and semaphores, and initialize our
291          * input/output/debugging file descriptors.
292          */
293         InitCommunication();
294         DebugFileOpen();
295
296         /* Do local initialization of file, storage and buffer managers */
297         InitFileAccess();
298         smgrinit();
299         InitBufferPoolAccess();
300 }
301
302
303 /* --------------------------------
304  * InitPostgres
305  *              Initialize POSTGRES.
306  *
307  * In bootstrap mode neither of the parameters are used.  In autovacuum
308  * mode, the username parameter is not used.
309  *
310  * The return value indicates whether the userID is a superuser.  (That
311  * can only be tested inside a transaction, so we want to do it during
312  * the startup transaction rather than doing a separate one in postgres.c.)
313  *
314  * Note:
315  *              Be very careful with the order of calls in the InitPostgres function.
316  * --------------------------------
317  */
318 bool
319 InitPostgres(const char *dbname, const char *username)
320 {
321         bool            bootstrap = IsBootstrapProcessingMode();
322         bool            autovacuum = IsAutoVacuumProcess();
323         bool            am_superuser;
324
325         /*
326          * Set up the global variables holding database id and path.
327          *
328          * We take a shortcut in the bootstrap case, otherwise we have to look up
329          * the db name in pg_database.
330          */
331         if (bootstrap)
332         {
333                 MyDatabaseId = TemplateDbOid;
334                 MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
335                 SetDatabasePath(GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace));
336         }
337         else
338         {
339                 char       *fullpath;
340
341                 /*
342                  * Formerly we validated DataDir here, but now that's done earlier.
343                  */
344
345                 /*
346                  * Find oid and tablespace of the database we're about to open. Since
347                  * we're not yet up and running we have to use the hackish
348                  * FindMyDatabase.
349                  */
350                 if (!FindMyDatabase(dbname, &MyDatabaseId, &MyDatabaseTableSpace))
351                         ereport(FATAL,
352                                         (errcode(ERRCODE_UNDEFINED_DATABASE),
353                                          errmsg("database \"%s\" does not exist",
354                                                         dbname)));
355
356                 fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
357
358                 /* Verify the database path */
359
360                 if (access(fullpath, F_OK) == -1)
361                 {
362                         if (errno == ENOENT)
363                                 ereport(FATAL,
364                                                 (errcode(ERRCODE_UNDEFINED_DATABASE),
365                                                  errmsg("database \"%s\" does not exist",
366                                                                 dbname),
367                                         errdetail("The database subdirectory \"%s\" is missing.",
368                                                           fullpath)));
369                         else
370                                 ereport(FATAL,
371                                                 (errcode_for_file_access(),
372                                                  errmsg("could not access directory \"%s\": %m",
373                                                                 fullpath)));
374                 }
375
376                 ValidatePgVersion(fullpath);
377
378                 SetDatabasePath(fullpath);
379         }
380
381         /*
382          * Code after this point assumes we are in the proper directory!
383          */
384
385         /*
386          * Set up my per-backend PGPROC struct in shared memory.        (We need to
387          * know MyDatabaseId before we can do this, since it's entered into the
388          * PGPROC struct.)
389          */
390         InitProcess();
391
392         /*
393          * Initialize my entry in the shared-invalidation manager's array of
394          * per-backend data.  (Formerly this came before InitProcess, but now it
395          * must happen after, because it uses MyProc.)  Once I have done this, I
396          * am visible to other backends!
397          *
398          * Sets up MyBackendId, a unique backend identifier.
399          */
400         MyBackendId = InvalidBackendId;
401
402         InitBackendSharedInvalidationState();
403
404         if (MyBackendId > MaxBackends || MyBackendId <= 0)
405                 elog(FATAL, "bad backend id: %d", MyBackendId);
406
407         /*
408          * bufmgr needs another initialization call too
409          */
410         InitBufferPoolBackend();
411
412         /*
413          * Initialize local process's access to XLOG.  In bootstrap case we may
414          * skip this since StartupXLOG() was run instead.
415          */
416         if (!bootstrap)
417                 InitXLOGAccess();
418
419         /*
420          * Initialize the relation descriptor cache.  This must create at least
421          * the minimum set of "nailed-in" cache entries.  No catalog access
422          * happens here.
423          */
424         RelationCacheInitialize();
425
426         /*
427          * Initialize all the system catalog caches.  Note that no catalog access
428          * happens here; we only set up the cache structure.
429          */
430         InitCatalogCache();
431
432         /* Initialize portal manager */
433         EnablePortalManager();
434
435         /*
436          * Set up process-exit callback to do pre-shutdown cleanup.  This has to
437          * be after we've initialized all the low-level modules like the buffer
438          * manager, because during shutdown this has to run before the low-level
439          * modules start to close down.  On the other hand, we want it in place
440          * before we begin our first transaction --- if we fail during the
441          * initialization transaction, as is entirely possible, we need the
442          * AbortTransaction call to clean up.
443          */
444         on_shmem_exit(ShutdownPostgres, 0);
445
446         /* start a new transaction here before access to db */
447         if (!bootstrap)
448                 StartTransactionCommand();
449
450         /*
451          * It's now possible to do real access to the system catalogs.
452          *
453          * Replace faked-up relcache entries with correct info.
454          */
455         RelationCacheInitializePhase2();
456
457         /*
458          * Figure out our postgres user id.  In standalone mode and in the
459          * autovacuum process, we use a fixed id, otherwise we figure it out from
460          * the authenticated user name.
461          */
462         if (bootstrap || autovacuum)
463                 InitializeSessionUserIdStandalone();
464         else if (!IsUnderPostmaster)
465         {
466                 InitializeSessionUserIdStandalone();
467                 if (!ThereIsAtLeastOneRole())
468                         ereport(WARNING,
469                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
470                                          errmsg("no roles are defined in this database system"),
471                                          errhint("You should immediately run CREATE USER \"%s\" CREATEUSER;.",
472                                                          username)));
473         }
474         else
475         {
476                 /* normal multiuser case */
477                 InitializeSessionUserId(username);
478         }
479
480         /*
481          * Unless we are bootstrapping, double-check that InitMyDatabaseInfo() got
482          * a correct result.  We can't do this until all the database-access
483          * infrastructure is up.  (Also, it wants to know if the user is a
484          * superuser, so the above stuff has to happen first.)
485          */
486         if (!bootstrap)
487                 ReverifyMyDatabase(dbname);
488
489         /*
490          * Final phase of relation cache startup: write a new cache file if
491          * necessary.  This is done after ReverifyMyDatabase to avoid writing a
492          * cache file into a dead database.
493          */
494         RelationCacheInitializePhase3();
495
496         /*
497          * Check if user is a superuser.
498          */
499         if (bootstrap || autovacuum)
500                 am_superuser = true;
501         else
502                 am_superuser = superuser();
503
504         /*
505          * Check a normal user hasn't connected to a superuser reserved slot.
506          */
507         if (!am_superuser &&
508                 ReservedBackends > 0 &&
509                 !HaveNFreeProcs(ReservedBackends))
510                 ereport(FATAL,
511                                 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
512                                  errmsg("connection limit exceeded for non-superusers")));
513
514         /*
515          * Initialize various default states that can't be set up until we've
516          * selected the active user and done ReverifyMyDatabase.
517          */
518
519         /* set default namespace search path */
520         InitializeSearchPath();
521
522         /* set up ACL framework (currently just sets RolMemCache callback) */
523         initialize_acl();
524
525         /* initialize client encoding */
526         InitializeClientEncoding();
527
528         /* initialize statistics collection for this backend */
529         if (IsUnderPostmaster)
530                 pgstat_bestart();
531
532         /* close the transaction we started above */
533         if (!bootstrap)
534                 CommitTransactionCommand();
535
536         return am_superuser;
537 }
538
539
540 /*
541  * Backend-shutdown callback.  Do cleanup that we want to be sure happens
542  * before all the supporting modules begin to nail their doors shut via
543  * their own callbacks.
544  *
545  * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
546  * via separate callbacks that execute before this one.  We don't combine the
547  * callbacks because we still want this one to happen if the user-level
548  * cleanup fails.
549  */
550 static void
551 ShutdownPostgres(int code, Datum arg)
552 {
553         /* Make sure we've killed any active transaction */
554         AbortOutOfAnyTransaction();
555
556         /*
557          * User locks are not released by transaction end, so be sure to release
558          * them explicitly.
559          */
560 #ifdef USER_LOCKS
561         LockReleaseAll(USER_LOCKMETHOD, true);
562 #endif
563 }
564
565
566 /*
567  * Returns true if at least one role is defined in this database cluster.
568  */
569 static bool
570 ThereIsAtLeastOneRole(void)
571 {
572         Relation        pg_authid_rel;
573         HeapScanDesc scan;
574         bool            result;
575
576         pg_authid_rel = heap_open(AuthIdRelationId, AccessExclusiveLock);
577
578         scan = heap_beginscan(pg_authid_rel, SnapshotNow, 0, NULL);
579         result = (heap_getnext(scan, ForwardScanDirection) != NULL);
580
581         heap_endscan(scan);
582         heap_close(pg_authid_rel, AccessExclusiveLock);
583
584         return result;
585 }