]> granicus.if.org Git - postgresql/blob - src/backend/utils/init/postinit.c
I really hope that I haven't missed anything in this one...
[postgresql] / src / backend / utils / init / postinit.c
1 /*-------------------------------------------------------------------------
2  *
3  * postinit.c--
4  *        postgres initialization utilities
5  *
6  * Copyright (c) 1994, Regents of the University of California
7  *
8  *
9  * IDENTIFICATION
10  *        $Header: /cvsroot/pgsql/src/backend/utils/init/postinit.c,v 1.31 1998/07/24 03:31:50 scrappy Exp $
11  *
12  * NOTES
13  *              InitPostgres() is the function called from PostgresMain
14  *              which does all non-trival initialization, mainly by calling
15  *              all the other initialization functions.  InitPostgres()
16  *              is only used within the "postgres" backend and so that routine
17  *              is in tcop/postgres.c  InitPostgres() is needed in cinterface.a
18  *              because things like the bootstrap backend program need it. Hence
19  *              you find that in this file...
20  *
21  *              If you feel the need to add more initialization code, it should be
22  *              done in InitPostgres() or someplace lower.      Do not start
23  *              putting stuff in PostgresMain - if you do then someone
24  *              will have to clean it up later, and it's not going to be me!
25  *              -cim 10/3/90
26  *
27  *-------------------------------------------------------------------------
28  */
29 #include <fcntl.h>
30 #include <stdio.h>
31 #include <string.h>
32 #include <sys/file.h>
33 #include <sys/types.h>
34 #include <math.h>
35 #include <unistd.h>
36
37 #include "postgres.h"
38 #include "version.h"
39
40 #include <storage/ipc.h>
41 #include <storage/backendid.h>
42 #include <storage/buf_internals.h>
43 #include <storage/smgr.h>
44 #include <storage/proc.h>
45 #include <utils/relcache.h>
46
47 #include "access/heapam.h"
48 #include "access/xact.h"
49 #include "storage/bufmgr.h"
50 #include "access/transam.h"             /* XXX dependency problem */
51 #include "utils/syscache.h"
52 #include "storage/bufpage.h"    /* for page layout, for
53                                                                  * InitMyDatabaseInfo() */
54 #include "storage/sinval.h"
55 #include "storage/sinvaladt.h"
56 #include "storage/lmgr.h"
57
58 #include "miscadmin.h"                  /* for global decls */
59 #include "utils/portal.h"               /* for EnablePortalManager, etc. */
60
61 #include "utils/exc.h"                  /* for EnableExceptionHandling, etc. */
62 #include "fmgr.h"                               /* for EnableDynamicFunctionManager, etc. */
63 #include "utils/elog.h"
64 #include "utils/palloc.h"
65 #include "utils/mcxt.h"                 /* for EnableMemoryContext, etc. */
66 #include "utils/inval.h"
67
68 #include "catalog/catname.h"
69 #ifdef MB
70 #include "catalog/pg_database_mb.h"
71 #include "mb/pg_wchar.h"
72 #else
73 #include "catalog/pg_database.h"
74 #endif
75
76 #include "libpq/libpq.h"
77
78 static void VerifySystemDatabase(void);
79 static void VerifyMyDatabase(void);
80 static void InitCommunication(void);
81 static void InitMyDatabaseInfo(char *name);
82 static void InitStdio(void);
83 static void InitUserid(void);
84
85 extern char *ExpandDatabasePath(char *name);
86 #ifdef MB
87 extern void GetRawDatabaseInfo(char *name, Oid *owner, Oid *db_id, char *path, int *encoding);
88 #else
89 extern void GetRawDatabaseInfo(char *name, Oid *owner, Oid *db_id, char *path);
90 #endif
91
92 static IPCKey PostgresIpcKey;
93
94 /* ----------------------------------------------------------------
95  *                                              InitPostgres support
96  * ----------------------------------------------------------------
97  */
98
99 /* --------------------------------
100  *      InitMyDatabaseInfo() -- Find and record the OID of the database we are
101  *                                                to open.
102  *
103  *              The database's oid forms half of the unique key for the system
104  *              caches and lock tables.  We therefore want it initialized before
105  *              we open any relations, since opening relations puts things in the
106  *              cache.  To get around this problem, this code opens and scans the
107  *              pg_database relation by hand.
108  *
109  *              This algorithm relies on the fact that first attribute in the
110  *              pg_database relation schema is the database name.  It also knows
111  *              about the internal format of tuples on disk and the length of
112  *              the datname attribute.  It knows the location of the pg_database
113  *              file.
114  *              Actually, the code looks as though it is using the pg_database
115  *              tuple definition to locate the database name, so the above statement
116  *              seems to be no longer correct. - thomas 1997-11-01
117  *
118  *              This code is called from InitPostgres(), before we chdir() to the
119  *              local database directory and before we open any relations.
120  *              Used to be called after the chdir(), but we now want to confirm
121  *              the location of the target database using pg_database info.
122  *              - thomas 1997-11-01
123  * --------------------------------
124  */
125 static void
126 InitMyDatabaseInfo(char *name)
127 {
128         Oid                     owner;
129         char       *path,
130                                 myPath[MAXPGPATH + 1];
131 #ifdef MB
132         int encoding;
133 #endif
134
135         SetDatabaseName(name);
136 #ifdef MB
137         GetRawDatabaseInfo(name, &owner, &MyDatabaseId, myPath, &encoding);
138 #else
139         GetRawDatabaseInfo(name, &owner, &MyDatabaseId, myPath);
140 #endif
141
142         if (!OidIsValid(MyDatabaseId))
143                 elog(FATAL,
144                          "Database %s does not exist in %s",
145                          DatabaseName,
146                          DatabaseRelationName);
147
148         path = ExpandDatabasePath(myPath);
149         SetDatabasePath(path);
150 #ifdef MB
151         SetDatabaseEncoding(encoding);
152 #endif
153
154         return;
155 }       /* InitMyDatabaseInfo() */
156
157
158 /*
159  * DoChdirAndInitDatabaseNameAndPath --
160  *              Set current directory to the database directory for the database
161  *              named <name>.
162  *              Also set global variables DatabasePath and DatabaseName to those
163  *              values.  Also check for proper version of database system and
164  *              database.  Exit program via elog() if anything doesn't check out.
165  *
166  * Arguments:
167  *              Path and name are invalid if it invalid as a string.
168  *              Path is "badly formatted" if it is not a string containing a path
169  *              to a writable directory.
170  *              Name is "badly formatted" if it contains more than 16 characters or if
171  *              it is a bad file name (e.g., it contains a '/' or an 8-bit character).
172  *
173  * Exceptions:
174  *              BadState if called more than once.
175  *              BadArg if both path and name are "badly formatted" or invalid.
176  *              BadArg if path and name are both "inconsistent" and valid.
177  *
178  *              This routine is inappropriate in bootstrap mode, since the directories
179  *              and version files need not exist yet if we're in bootstrap mode.
180  */
181 static void
182 VerifySystemDatabase()
183 {
184         char       *reason;
185
186         /* Failure reason returned by some function.  NULL if no failure */
187         int                     fd;
188         char            errormsg[1000];
189
190         errormsg[0] = '\0';
191
192         if ((fd = open(DataDir, O_RDONLY, 0)) == -1)
193                 sprintf(errormsg, "Database system does not exist.  "
194                                 "PGDATA directory '%s' not found.\n\tNormally, you "
195                                 "create a database system by running initdb.",
196                                 DataDir);
197         else
198         {
199                 close(fd);
200                 ValidatePgVersion(DataDir, &reason);
201                 if (reason != NULL)
202                         sprintf(errormsg,
203                                         "InitPostgres could not validate that the database"
204                                         " system version is compatible with this level of"
205                                         " Postgres.\n\tYou may need to run initdb to create"
206                                         " a new database system.\n\t%s", reason);
207         }
208         if (errormsg[0] != '\0')
209                 elog(FATAL, errormsg);
210         /* Above does not return */
211 }       /* VerifySystemDatabase() */
212
213
214 static void
215 VerifyMyDatabase()
216 {
217         const char         *name;
218         const char         *myPath;
219
220         /* Failure reason returned by some function.  NULL if no failure */
221         char       *reason;
222         int                     fd;
223         char            errormsg[1000];
224
225         name = DatabaseName;
226         myPath = DatabasePath;
227
228         if ((fd = open(myPath, O_RDONLY, 0)) == -1)
229                 sprintf(errormsg,
230                                 "Database '%s' does not exist."
231                         "\n\tWe know this because the directory '%s' does not exist."
232                                 "\n\tYou can create a database with the SQL command"
233                                 " CREATE DATABASE.\n\tTo see what databases exist,"
234                                 " look at the subdirectories of '%s/base/'.",
235                                 name, myPath, DataDir);
236         else
237         {
238                 close(fd);
239                 ValidatePgVersion(myPath, &reason);
240                 if (reason != NULL)
241                         sprintf(errormsg,
242                                         "InitPostgres could not validate that the database"
243                                         " version is compatible with this level of Postgres"
244                                         "\n\teven though the database system as a whole"
245                                         " appears to be at a compatible level."
246                                         "\n\tYou may need to recreate the database with SQL"
247                                         " commands DROP DATABASE and CREATE DATABASE."
248                                         "\n\t%s", reason);
249                 else
250                 {
251
252                         /*
253                          * The directories and PG_VERSION files are in order.
254                          */
255                         int                     rc;             /* return code from some function we call */
256
257 #ifdef FILEDEBUG
258                         printf("Try changing directory for database %s to %s\n", name, myPath);
259 #endif
260
261                         rc = chdir(myPath);
262                         if (rc < 0)
263                                 sprintf(errormsg,
264                                                 "InitPostgres unable to change "
265                                                 "current directory to '%s', errno = %s (%d).",
266                                                 myPath, strerror(errno), errno);
267                         else
268                                 errormsg[0] = '\0';
269                 }
270         }
271
272         if (errormsg[0] != '\0')
273                 elog(FATAL, errormsg);
274         /* Above does not return */
275 }       /* VerifyMyDatabase() */
276
277
278 /* --------------------------------
279  *              InitUserid
280  *
281  *              initializes crap associated with the user id.
282  * --------------------------------
283  */
284 static void
285 InitUserid()
286 {
287         setuid(geteuid());
288         SetUserId();
289 }
290
291 /* --------------------------------
292  *              InitCommunication
293  *
294  *              This routine initializes stuff needed for ipc, locking, etc.
295  *              it should be called something more informative.
296  *
297  * Note:
298  *              This does not set MyBackendId.  MyBackendTag is set, however.
299  * --------------------------------
300  */
301 static void
302 InitCommunication()
303 {
304         char       *postid;                     /* value of environment variable */
305         char       *postport;           /* value of environment variable */
306         char       *ipc_key;            /* value of environemnt variable */
307         IPCKey          key = 0;
308
309         /* ----------------
310          *      try and get the backend tag from POSTID
311          * ----------------
312          */
313         MyBackendId = -1;
314
315         postid = getenv("POSTID");
316         if (!PointerIsValid(postid))
317                 MyBackendTag = -1;
318         else
319         {
320                 MyBackendTag = atoi(postid);
321                 Assert(MyBackendTag >= 0);
322         }
323
324
325         ipc_key = getenv("IPC_KEY");
326         if (!PointerIsValid(ipc_key))
327                 key = -1;
328         else
329         {
330                 key = atoi(ipc_key);
331                 Assert(MyBackendTag >= 0);
332         }
333
334         postport = getenv("POSTPORT");
335
336         if (PointerIsValid(postport))
337         {
338                 if (MyBackendTag == -1)
339                         elog(FATAL, "InitCommunication: missing POSTID");
340
341                 /*
342                  * Enable this if you are trying to force the backend to run as if
343                  * it is running under the postmaster.
344                  *
345                  * This goto forces Postgres to attach to shared memory instead of
346                  * using malloc'ed memory (which is the normal behavior if run
347                  * directly).
348                  *
349                  * To enable emulation, run the following shell commands (in addition
350                  * to enabling this goto)
351                  *
352                  * % setenv POSTID 1 % setenv POSTPORT 4321 % setenv IPC_KEY 4321000
353                  * % postmaster & % kill -9 %1
354                  *
355                  * Upon doing this, Postmaster will have allocated the shared memory
356                  * resources that Postgres will attach to if you enable
357                  * EMULATE_UNDER_POSTMASTER.
358                  *
359                  * This comment may well age with time - it is current as of 8
360                  * January 1990
361                  *
362                  * Greg
363                  */
364
365 #ifdef EMULATE_UNDER_POSTMASTER
366
367                 goto forcesharedmemory;
368
369 #endif
370
371         }
372         else if (IsUnderPostmaster)
373         {
374                 elog(FATAL,
375                          "InitCommunication: under postmaster and POSTPORT not set");
376         }
377         else
378         {
379                 /* ----------------
380                  *      assume we're running a postgres backend by itself with
381                  *      no front end or postmaster.
382                  * ----------------
383                  */
384                 if (MyBackendTag == -1)
385                         MyBackendTag = 1;
386
387                 key = PrivateIPCKey;
388         }
389
390         /* ----------------
391          *      initialize shared memory and semaphores appropriately.
392          * ----------------
393          */
394 #ifdef EMULATE_UNDER_POSTMASTER
395
396 forcesharedmemory:
397
398 #endif
399
400     if (!IsUnderPostmaster) /* postmaster already did this */
401         {
402                 PostgresIpcKey = key;
403                 AttachSharedMemoryAndSemaphores(key);
404         }
405 }
406
407
408 /* --------------------------------
409  *              InitStdio
410  *
411  *              this routine consists of a bunch of code fragments
412  *              that used to be randomly scattered through cinit().
413  *              they all seem to do stuff associated with io.
414  * --------------------------------
415  */
416 static void
417 InitStdio()
418 {
419         DebugFileOpen();
420 }
421
422 /* --------------------------------
423  * InitPostgres --
424  *              Initialize POSTGRES.
425  *
426  * Note:
427  *              Be very careful with the order of calls in the InitPostgres function.
428  * --------------------------------
429  */
430 bool            PostgresIsInitialized = false;
431 extern int      NBuffers;
432
433 /*
434  *      this global is used by wei for testing his code, but must be declared
435  *      here rather than in postgres.c so that it's defined for cinterface.a
436  *      applications.
437  */
438
439 /*int   testFlag = 0;*/
440 int                     lockingOff = 0;
441
442 /*
443  */
444 void
445 InitPostgres(char *name)                /* database name */
446 {
447         bool            bootstrap;              /* true if BootstrapProcessing */
448
449         /* ----------------
450          *      see if we're running in BootstrapProcessing mode
451          * ----------------
452          */
453         bootstrap = IsBootstrapProcessingMode();
454
455         /* ----------------
456          *      turn on the exception handler.  Note: we cannot use elog, Assert,
457          *      AssertState, etc. until after exception handling is on.
458          * ----------------
459          */
460         EnableExceptionHandling(true);
461
462         /* ----------------
463          *      A stupid check to make sure we don't call this more than once.
464          *      But things like ReinitPostgres() get around this by just diddling
465          *      the PostgresIsInitialized flag.
466          * ----------------
467          */
468         AssertState(!PostgresIsInitialized);
469
470         /* ----------------
471          *      Memory system initialization.
472          *      (we may call palloc after EnableMemoryContext())
473          *
474          *      Note EnableMemoryContext() must happen before EnablePortalManager().
475          * ----------------
476          */
477         EnableMemoryContext(true);      /* initializes the "top context" */
478         EnablePortalManager(true);      /* memory for portal/transaction stuff */
479
480         /* ----------------
481          *      initialize the backend local portal stack used by
482          *      internal PQ function calls.  see src/lib/libpq/be-dumpdata.c
483          *      This is different from the "portal manager" so this goes here.
484          *      -cim 2/12/91
485          * ----------------
486          */
487         be_portalinit();
488
489         /* ----------------
490          *       attach to shared memory and semaphores, and initialize our
491          *       input/output/debugging file descriptors.
492          * ----------------
493          */
494         InitCommunication();
495         InitStdio();
496
497         /*
498          * initialize the local buffer manager
499          */
500         InitLocalBuffer();
501
502         if (!TransactionFlushEnabled())
503                 on_shmem_exit(FlushBufferPool, (caddr_t) NULL);
504
505         /* ----------------
506          *      initialize the database id used for system caches and lock tables
507          * ----------------
508          */
509         if (bootstrap)
510         {
511                 SetDatabasePath(ExpandDatabasePath(name));
512                 SetDatabaseName(name);
513                 LockDisable(true);
514         }
515         else
516         {
517                 VerifySystemDatabase();
518                 InitMyDatabaseInfo(name);
519                 VerifyMyDatabase();
520         }
521
522         /*
523          * ********************************
524          *
525          * code after this point assumes we are in the proper directory!
526          *
527          * So, how do we implement alternate locations for databases? There are
528          * two possible locations for tables and we need to look in
529          * DataDir/pg_database to find the true location of an individual
530          * database. We can brute-force it as done in InitMyDatabaseInfo(), or
531          * we can be patient and wait until we open pg_database gracefully.
532          * Will try that, but may not work... - thomas 1997-11-01 ********************************
533          *
534          */
535
536         /* Does not touch files (?) - thomas 1997-11-01 */
537         smgrinit();
538
539         /* ----------------
540          *      initialize the transaction system and the relation descriptor cache.
541          *      Note we have to make certain the lock manager is off while we do this.
542          * ----------------
543          */
544         AmiTransactionOverride(IsBootstrapProcessingMode());
545         LockDisable(true);
546
547         /*
548          * Part of the initialization processing done here sets a read lock on
549          * pg_log.      Since locking is disabled the set doesn't have intended
550          * effect of locking out writers, but this is ok, since we only lock
551          * it to examine AMI transaction status, and this is never written
552          * after initdb is done. -mer 15 June 1992
553          */
554         RelationInitialize();           /* pre-allocated reldescs created here */
555         InitializeTransactionSystem();          /* pg_log,etc init/crash recovery
556                                                                                  * here */
557
558         LockDisable(false);
559
560         /* ----------------
561          *      anyone knows what this does?  something having to do with
562          *      system catalog cache invalidation in the case of multiple
563          *      backends, I think -cim 10/3/90
564          *      Sets up MyBackendId a unique backend identifier.
565          * ----------------
566          */
567         InitSharedInvalidationState();
568
569         /* ----------------
570          * Set up a per backend process in shared memory.  Must be done after
571          * InitSharedInvalidationState() as it relies on MyBackendId being
572          * initialized already.  XXX -mer 11 Aug 1991
573          * ----------------
574          */
575         InitProcess(PostgresIpcKey);
576
577         if (MyBackendId > MaxBackendId || MyBackendId <= 0)
578         {
579                 elog(FATAL, "cinit2: bad backend id %d (%d)",
580                          MyBackendTag,
581                          MyBackendId);
582         }
583
584         /* ----------------
585          *      initialize the access methods.
586          *      Does not touch files (?) - thomas 1997-11-01
587          * ----------------
588          */
589         initam();
590
591         /* ----------------
592          *      initialize all the system catalog caches.
593          * ----------------
594          */
595         zerocaches();
596
597         /*
598          * Does not touch files since all routines are builtins (?) - thomas
599          * 1997-11-01
600          */
601         InitCatalogCache();
602
603         /* ----------------
604          *       set ourselves to the proper user id and figure out our postgres
605          *       user id.  If we ever add security so that we check for valid
606          *       postgres users, we might do it here.
607          * ----------------
608          */
609         InitUserid();
610
611         /* ----------------
612          *       initialize local data in cache invalidation stuff
613          * ----------------
614          */
615         if (!bootstrap)
616                 InitLocalInvalidateData();
617
618         /* ----------------
619          *      ok, all done, now let's make sure we don't do it again.
620          * ----------------
621          */
622         PostgresIsInitialized = true;
623 /*        on_shmem_exit(DestroyLocalRelList, (caddr_t) NULL); */
624
625         /* ----------------
626          *      Done with "InitPostgres", now change to NormalProcessing unless
627          *      we're in BootstrapProcessing mode.
628          * ----------------
629          */
630         if (!bootstrap)
631                 SetProcessingMode(NormalProcessing);
632 /*        if (testFlag || lockingOff) */
633         if (lockingOff)
634                 LockDisable(true);
635 }