OSDN Git Service

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