OSDN Git Service

Katherine Ward wrote:
[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-2001, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $Header: /cvsroot/pgsql/src/backend/utils/init/postinit.c,v 1.107 2002/06/11 13:40:52 wieck Exp $
12  *
13  *
14  *-------------------------------------------------------------------------
15  */
16 #include "postgres.h"
17
18 #include <fcntl.h>
19 #include <sys/file.h>
20 #include <sys/types.h>
21 #include <math.h>
22 #include <unistd.h>
23
24 #include "catalog/catalog.h"
25 #include "access/heapam.h"
26 #include "catalog/catname.h"
27 #include "catalog/namespace.h"
28 #include "catalog/pg_database.h"
29 #include "catalog/pg_shadow.h"
30 #include "commands/trigger.h"
31 #include "mb/pg_wchar.h"
32 #include "miscadmin.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(void);
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, if we are in MULTIBYTE mode.
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         ScanKeyEntryInitialize(&key, 0, Anum_pg_database_datname,
96                                                    F_NAMEEQ, NameGetDatum(name));
97
98         pgdbscan = heap_beginscan(pgdbrel, SnapshotNow, 1, &key);
99
100         tup = heap_getnext(pgdbscan, ForwardScanDirection);
101         if (!HeapTupleIsValid(tup) ||
102                 tup->t_data->t_oid != MyDatabaseId)
103         {
104                 /* OOPS */
105                 heap_close(pgdbrel, AccessShareLock);
106
107                 /*
108                  * The only real problem I could have created is to load dirty
109                  * buffers for the dead database into shared buffer cache; if I
110                  * did, some other backend will eventually try to write them and
111                  * die in mdblindwrt.  Flush any such pages to forestall trouble.
112                  */
113                 DropBuffers(MyDatabaseId);
114                 /* Now I can commit hara-kiri with a clear conscience... */
115                 elog(FATAL, "Database \"%s\", OID %u, has disappeared from pg_database",
116                          name, MyDatabaseId);
117         }
118
119         /*
120          * Also check that the database is currently allowing connections.
121          */
122         dbform = (Form_pg_database) GETSTRUCT(tup);
123         if (!dbform->datallowconn)
124                 elog(FATAL, "Database \"%s\" is not currently accepting connections",
125                          name);
126
127         /*
128          * OK, we're golden.  Only other to-do item is to save the MULTIBYTE
129          * encoding info out of the pg_database tuple --- or complain, if we
130          * can't support it.
131          */
132 #ifdef MULTIBYTE
133         SetDatabaseEncoding(dbform->encoding);
134         /* If we have no other source of client_encoding, use server encoding */
135         SetConfigOption("client_encoding", GetDatabaseEncodingName(),
136                                         PGC_BACKEND, PGC_S_DEFAULT);
137 #else
138         if (dbform->encoding != PG_SQL_ASCII)
139                 elog(FATAL, "database was initialized with MULTIBYTE encoding %d,\n\tbut the backend was compiled without multibyte support.\n\tlooks like you need to initdb or recompile.",
140                          dbform->encoding);
141 #endif
142
143         /*
144          * Set up database-specific configuration variables.
145          */
146         if (IsUnderPostmaster)
147         {
148                 Datum           datum;
149                 bool            isnull;
150
151                 datum = heap_getattr(tup, Anum_pg_database_datconfig,
152                                                          RelationGetDescr(pgdbrel), &isnull);
153                 if (!isnull)
154                 {
155                         ArrayType *a = DatumGetArrayTypeP(datum);
156
157                         ProcessGUCArray(a, PGC_S_DATABASE);
158                 }
159         }
160
161         heap_endscan(pgdbscan);
162         heap_close(pgdbrel, AccessShareLock);
163 }
164
165
166
167 /* --------------------------------
168  *              InitCommunication
169  *
170  *              This routine initializes stuff needed for ipc, locking, etc.
171  *              it should be called something more informative.
172  * --------------------------------
173  */
174 static void
175 InitCommunication(void)
176 {
177         /*
178          * initialize shared memory and semaphores appropriately.
179          */
180         if (!IsUnderPostmaster)         /* postmaster already did this */
181         {
182                 /*
183                  * we're running a postgres backend by itself with no front end or
184                  * postmaster.  Create private "shmem" and semaphores.  Setting
185                  * MaxBackends = 16 is arbitrary.
186                  */
187                 CreateSharedMemoryAndSemaphores(true, 16, 0);
188         }
189 }
190
191
192 /*
193  * Early initialization of a backend (either standalone or under postmaster).
194  * This happens even before InitPostgres.
195  *
196  * If you're wondering why this is separate from InitPostgres at all:
197  * the critical distinction is that this stuff has to happen before we can
198  * run XLOG-related initialization, which is done before InitPostgres --- in
199  * fact, for cases such as checkpoint creation processes, InitPostgres may
200  * never be done at all.
201  */
202 void
203 BaseInit(void)
204 {
205         /*
206          * Attach to shared memory and semaphores, and initialize our
207          * input/output/debugging file descriptors.
208          */
209         InitCommunication();
210         DebugFileOpen();
211
212         /* Do local initialization of storage and buffer managers */
213         smgrinit();
214         InitBufferPoolAccess();
215         InitLocalBuffer();
216 }
217
218
219 /* --------------------------------
220  * InitPostgres
221  *              Initialize POSTGRES.
222  *
223  * Note:
224  *              Be very careful with the order of calls in the InitPostgres function.
225  * --------------------------------
226  */
227 void
228 InitPostgres(const char *dbname, const char *username)
229 {
230         bool            bootstrap = IsBootstrapProcessingMode();
231
232         /*
233          * Set up the global variables holding database name, id, and path.
234          *
235          * We take a shortcut in the bootstrap case, otherwise we have to look up
236          * the db name in pg_database.
237          */
238         SetDatabaseName(dbname);
239
240         if (bootstrap)
241         {
242                 MyDatabaseId = TemplateDbOid;
243                 SetDatabasePath(GetDatabasePath(MyDatabaseId));
244         }
245         else
246         {
247                 char       *fullpath,
248                                         datpath[MAXPGPATH];
249
250                 /*
251                  * Formerly we validated DataDir here, but now that's done
252                  * earlier.
253                  */
254
255                 /*
256                  * Find oid and path of the database we're about to open. Since
257                  * we're not yet up and running we have to use the hackish
258                  * GetRawDatabaseInfo.
259                  */
260                 GetRawDatabaseInfo(dbname, &MyDatabaseId, datpath);
261
262                 if (!OidIsValid(MyDatabaseId))
263                         elog(FATAL,
264                                  "Database \"%s\" does not exist in the system catalog.",
265                                  dbname);
266
267                 fullpath = GetDatabasePath(MyDatabaseId);
268
269                 /* Verify the database path */
270
271                 if (access(fullpath, F_OK) == -1)
272                         elog(FATAL, "Database \"%s\" does not exist.\n\t"
273                                  "The database subdirectory '%s' is missing.",
274                                  dbname, fullpath);
275
276                 ValidatePgVersion(fullpath);
277
278                 if (chdir(fullpath) == -1)
279                         elog(FATAL, "Unable to change directory to '%s': %m", fullpath);
280
281                 SetDatabasePath(fullpath);
282         }
283
284         /*
285          * Code after this point assumes we are in the proper directory!
286          */
287
288         /*
289          * Set up my per-backend PGPROC struct in shared memory.        (We need to
290          * know MyDatabaseId before we can do this, since it's entered into
291          * the PGPROC struct.)
292          */
293         InitProcess();
294
295         /*
296          * Initialize my entry in the shared-invalidation manager's array of
297          * per-backend data.  (Formerly this came before InitProcess, but now
298          * it must happen after, because it uses MyProc.)  Once I have done
299          * this, I am visible to other backends!
300          *
301          * Sets up MyBackendId, a unique backend identifier.
302          */
303         MyBackendId = InvalidBackendId;
304
305         InitBackendSharedInvalidationState();
306
307         if (MyBackendId > MaxBackends || MyBackendId <= 0)
308                 elog(FATAL, "InitPostgres: bad backend id %d", MyBackendId);
309
310         /*
311          * Initialize the transaction system override state.
312          */
313         AmiTransactionOverride(bootstrap);
314
315         /*
316          * Initialize the relation descriptor cache.  This must create
317          * at least the minimum set of "nailed-in" cache entries.  No
318          * catalog access happens here.
319          */
320         RelationCacheInitialize();
321
322         /*
323          * Initialize all the system catalog caches.  Note that no catalog
324          * access happens here; we only set up the cache structure.
325          */
326         InitCatalogCache();
327
328         /* Initialize portal manager */
329         EnablePortalManager();
330
331         /*
332          * Initialize the deferred trigger manager --- must happen before
333          * first transaction start.
334          */
335         DeferredTriggerInit();
336
337         /* start a new transaction here before access to db */
338         if (!bootstrap)
339                 StartTransactionCommand();
340
341         /*
342          * It's now possible to do real access to the system catalogs.
343          *
344          * Replace faked-up relcache entries with correct info.
345          */
346         RelationCacheInitializePhase2();
347
348         /*
349          * Figure out our postgres user id.  In standalone mode we use a fixed
350          * id, otherwise we figure it out from the authenticated user name.
351          */
352         if (bootstrap)
353                 InitializeSessionUserIdStandalone();
354         else if (!IsUnderPostmaster)
355         {
356                 InitializeSessionUserIdStandalone();
357                 if (!ThereIsAtLeastOneUser())
358                 {
359                         elog(WARNING, "There are currently no users defined in this database system.");
360                         elog(WARNING, "You should immediately run 'CREATE USER \"%s\" WITH SYSID %d CREATEUSER;'.",
361                                  username, BOOTSTRAP_USESYSID);
362                 }
363         }
364         else
365         {
366                 /* normal multiuser case */
367                 InitializeSessionUserId(username);
368         }
369
370         /*
371          * Unless we are bootstrapping, double-check that InitMyDatabaseInfo()
372          * got a correct result.  We can't do this until all the
373          * database-access infrastructure is up.
374          */
375         if (!bootstrap)
376                 ReverifyMyDatabase(dbname);
377
378         /*
379          * Final phase of relation cache startup: write a new cache file
380          * if necessary.  This is done after ReverifyMyDatabase to avoid
381          * writing a cache file into a dead database.
382          */
383         RelationCacheInitializePhase3();
384
385         /*
386          * Initialize various default states that can't be set up until
387          * we've selected the active user and done ReverifyMyDatabase.
388          */
389
390         /* set default namespace search path */
391         InitializeSearchPath();
392
393         /*
394          * Set up process-exit callback to do pre-shutdown cleanup.  This should
395          * be last because we want shmem_exit to call this routine before the exit
396          * callbacks that are registered by buffer manager, lock manager, etc.
397          * We need to run this code before we close down database access!
398          */
399         on_shmem_exit(ShutdownPostgres, 0);
400
401         /* close the transaction we started above */
402         if (!bootstrap)
403                 CommitTransactionCommand();
404 }
405
406 /*
407  * Backend-shutdown callback.  Do cleanup that we want to be sure happens
408  * before all the supporting modules begin to nail their doors shut via
409  * their own callbacks.  Note that because this has to be registered very
410  * late in startup, it will not get called if we suffer a failure *during*
411  * startup.
412  *
413  * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
414  * via separate callbacks that execute before this one.  We don't combine the
415  * callbacks because we still want this one to happen if the user-level
416  * cleanup fails.
417  */
418 static void
419 ShutdownPostgres(void)
420 {
421         /*
422          * These operations are really just a minimal subset of
423          * AbortTransaction(). We don't want to do any inessential cleanup,
424          * since that just raises the odds of failure --- but there's some
425          * stuff we need to do.
426          *
427          * Release any LW locks and buffer context locks we might be holding.
428          * This is a kluge to improve the odds that we won't get into a
429          * self-made stuck-lock scenario while trying to shut down.
430          */
431         LWLockReleaseAll();
432         AbortBufferIO();
433         UnlockBuffers();
434
435         /*
436          * In case a transaction is open, delete any files it created.  This
437          * has to happen before bufmgr shutdown, so having smgr register a
438          * callback for it wouldn't work.
439          */
440         smgrDoPendingDeletes(false);    /* delete as though aborting xact */
441 }
442
443
444
445 /*
446  * Returns true if at least one user is defined in this database cluster.
447  */
448 static bool
449 ThereIsAtLeastOneUser(void)
450 {
451         Relation        pg_shadow_rel;
452         TupleDesc       pg_shadow_dsc;
453         HeapScanDesc scan;
454         bool            result;
455
456         pg_shadow_rel = heap_openr(ShadowRelationName, AccessExclusiveLock);
457         pg_shadow_dsc = RelationGetDescr(pg_shadow_rel);
458
459         scan = heap_beginscan(pg_shadow_rel, SnapshotNow, 0, NULL);
460         result = (heap_getnext(scan, ForwardScanDirection) != NULL);
461
462         heap_endscan(scan);
463         heap_close(pg_shadow_rel, AccessExclusiveLock);
464
465         return result;
466 }