OSDN Git Service

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