OSDN Git Service

Add operator strategy and comparison-value datatype fields to ScanKey.
[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-2003, 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.128 2003/11/09 21:30:37 tgl 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_type.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.
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,
96                                                    Anum_pg_database_datname,
97                                                    BTEqualStrategyNumber, F_NAMEEQ,
98                                                    NameGetDatum(name), NAMEOID);
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  * Note:
225  *              Be very careful with the order of calls in the InitPostgres function.
226  * --------------------------------
227  */
228 void
229 InitPostgres(const char *dbname, const char *username)
230 {
231         bool            bootstrap = IsBootstrapProcessingMode();
232
233         /*
234          * Set up the global variables holding database id and path.
235          *
236          * We take a shortcut in the bootstrap case, otherwise we have to look up
237          * the db name in pg_database.
238          */
239         if (bootstrap)
240         {
241                 MyDatabaseId = TemplateDbOid;
242                 SetDatabasePath(GetDatabasePath(MyDatabaseId));
243         }
244         else
245         {
246                 char       *fullpath,
247                                         datpath[MAXPGPATH];
248
249                 /*
250                  * Formerly we validated DataDir here, but now that's done
251                  * earlier.
252                  */
253
254                 /*
255                  * Find oid and path of the database we're about to open. Since
256                  * we're not yet up and running we have to use the hackish
257                  * GetRawDatabaseInfo.
258                  */
259                 GetRawDatabaseInfo(dbname, &MyDatabaseId, datpath);
260
261                 if (!OidIsValid(MyDatabaseId))
262                         ereport(FATAL,
263                                         (errcode(ERRCODE_UNDEFINED_DATABASE),
264                                          errmsg("database \"%s\" does not exist",
265                                                         dbname)));
266
267                 fullpath = GetDatabasePath(MyDatabaseId);
268
269                 /* Verify the database path */
270
271                 if (access(fullpath, F_OK) == -1)
272                 {
273                         if (errno == ENOENT)
274                                 ereport(FATAL,
275                                                 (errcode(ERRCODE_UNDEFINED_DATABASE),
276                                                  errmsg("database \"%s\" does not exist",
277                                                                 dbname),
278                                 errdetail("The database subdirectory \"%s\" is missing.",
279                                                   fullpath)));
280                         else
281                                 ereport(FATAL,
282                                                 (errcode_for_file_access(),
283                                                  errmsg("could not access directory \"%s\": %m",
284                                                                 fullpath)));
285                 }
286
287                 ValidatePgVersion(fullpath);
288
289                 if (chdir(fullpath) == -1)
290                         ereport(FATAL,
291                                         (errcode_for_file_access(),
292                                          errmsg("could not change directory to \"%s\": %m",
293                                                         fullpath)));
294
295                 SetDatabasePath(fullpath);
296         }
297
298         /*
299          * Code after this point assumes we are in the proper directory!
300          */
301
302         /*
303          * Set up my per-backend PGPROC struct in shared memory.        (We need
304          * to know MyDatabaseId before we can do this, since it's entered into
305          * the PGPROC struct.)
306          */
307         InitProcess();
308
309         /*
310          * Initialize my entry in the shared-invalidation manager's array of
311          * per-backend data.  (Formerly this came before InitProcess, but now
312          * it must happen after, because it uses MyProc.)  Once I have done
313          * this, I am visible to other backends!
314          *
315          * Sets up MyBackendId, a unique backend identifier.
316          */
317         MyBackendId = InvalidBackendId;
318
319         InitBackendSharedInvalidationState();
320
321         if (MyBackendId > MaxBackends || MyBackendId <= 0)
322                 elog(FATAL, "bad backend id: %d", MyBackendId);
323
324         /*
325          * Initialize the transaction system override state.
326          */
327         AmiTransactionOverride(bootstrap);
328
329         /*
330          * Initialize the relation descriptor cache.  This must create at
331          * least the minimum set of "nailed-in" cache entries.  No catalog
332          * access happens here.
333          */
334         RelationCacheInitialize();
335
336         /*
337          * Initialize all the system catalog caches.  Note that no catalog
338          * access happens here; we only set up the cache structure.
339          */
340         InitCatalogCache();
341
342         /* Initialize portal manager */
343         EnablePortalManager();
344
345         /*
346          * Initialize the deferred trigger manager --- must happen before
347          * first transaction start.
348          */
349         DeferredTriggerInit();
350
351         /* start a new transaction here before access to db */
352         if (!bootstrap)
353                 StartTransactionCommand();
354
355         /*
356          * It's now possible to do real access to the system catalogs.
357          *
358          * Replace faked-up relcache entries with correct info.
359          */
360         RelationCacheInitializePhase2();
361
362         /*
363          * Figure out our postgres user id.  In standalone mode we use a fixed
364          * id, otherwise we figure it out from the authenticated user name.
365          */
366         if (bootstrap)
367                 InitializeSessionUserIdStandalone();
368         else if (!IsUnderPostmaster)
369         {
370                 InitializeSessionUserIdStandalone();
371                 if (!ThereIsAtLeastOneUser())
372                         ereport(WARNING,
373                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
374                                   errmsg("no users are defined in this database system"),
375                                          errhint("You should immediately run CREATE USER \"%s\" WITH SYSID %d CREATEUSER;.",
376                                                          username, BOOTSTRAP_USESYSID)));
377         }
378         else
379         {
380                 /* normal multiuser case */
381                 InitializeSessionUserId(username);
382         }
383
384         /*
385          * Unless we are bootstrapping, double-check that InitMyDatabaseInfo()
386          * got a correct result.  We can't do this until all the
387          * database-access infrastructure is up.
388          */
389         if (!bootstrap)
390                 ReverifyMyDatabase(dbname);
391
392         /*
393          * Final phase of relation cache startup: write a new cache file if
394          * necessary.  This is done after ReverifyMyDatabase to avoid writing
395          * a cache file into a dead database.
396          */
397         RelationCacheInitializePhase3();
398
399         /*
400          * Check a normal user hasn't connected to a superuser reserved slot.
401          * We can't do this till after we've read the user information, and we
402          * must do it inside a transaction since checking superuserness may
403          * require database access.  The superuser check is probably the most
404          * expensive part; don't do it until necessary.
405          */
406         if (ReservedBackends > 0 &&
407                 CountEmptyBackendSlots() < ReservedBackends &&
408                 !superuser())
409                 ereport(FATAL,
410                                 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
411                                  errmsg("connection limit exceeded for non-superusers")));
412
413         /*
414          * Initialize various default states that can't be set up until we've
415          * selected the active user and done ReverifyMyDatabase.
416          */
417
418         /* set default namespace search path */
419         InitializeSearchPath();
420
421         /* initialize client encoding */
422         InitializeClientEncoding();
423
424         /*
425          * Now all default states are fully set up.  Report them to client if
426          * appropriate.
427          */
428         BeginReportingGUCOptions();
429
430         /*
431          * Set up process-exit callback to do pre-shutdown cleanup.  This
432          * should be last because we want shmem_exit to call this routine
433          * before the exit callbacks that are registered by buffer manager,
434          * lock manager, etc. We need to run this code before we close down
435          * database access!
436          */
437         on_shmem_exit(ShutdownPostgres, 0);
438
439         /* close the transaction we started above */
440         if (!bootstrap)
441                 CommitTransactionCommand();
442 }
443
444 /*
445  * Backend-shutdown callback.  Do cleanup that we want to be sure happens
446  * before all the supporting modules begin to nail their doors shut via
447  * their own callbacks.  Note that because this has to be registered very
448  * late in startup, it will not get called if we suffer a failure *during*
449  * startup.
450  *
451  * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
452  * via separate callbacks that execute before this one.  We don't combine the
453  * callbacks because we still want this one to happen if the user-level
454  * cleanup fails.
455  */
456 static void
457 ShutdownPostgres(void)
458 {
459         /*
460          * These operations are really just a minimal subset of
461          * AbortTransaction(). We don't want to do any inessential cleanup,
462          * since that just raises the odds of failure --- but there's some
463          * stuff we need to do.
464          *
465          * Release any LW locks and buffer context locks we might be holding.
466          * This is a kluge to improve the odds that we won't get into a
467          * self-made stuck-lock scenario while trying to shut down.
468          */
469         LWLockReleaseAll();
470         AbortBufferIO();
471         UnlockBuffers();
472
473         /*
474          * In case a transaction is open, delete any files it created.  This
475          * has to happen before bufmgr shutdown, so having smgr register a
476          * callback for it wouldn't work.
477          */
478         smgrDoPendingDeletes(false);    /* delete as though aborting xact */
479 }
480
481
482
483 /*
484  * Returns true if at least one user is defined in this database cluster.
485  */
486 static bool
487 ThereIsAtLeastOneUser(void)
488 {
489         Relation        pg_shadow_rel;
490         TupleDesc       pg_shadow_dsc;
491         HeapScanDesc scan;
492         bool            result;
493
494         pg_shadow_rel = heap_openr(ShadowRelationName, AccessExclusiveLock);
495         pg_shadow_dsc = RelationGetDescr(pg_shadow_rel);
496
497         scan = heap_beginscan(pg_shadow_rel, SnapshotNow, 0, NULL);
498         result = (heap_getnext(scan, ForwardScanDirection) != NULL);
499
500         heap_endscan(scan);
501         heap_close(pg_shadow_rel, AccessExclusiveLock);
502
503         return result;
504 }