OSDN Git Service

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