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