]> granicus.if.org Git - postgresql/blob - src/backend/utils/init/postinit.c
Get rid of unused variable 'address'.
[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.19 1997/11/18 07:58:10 vadim 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/tqual.h"
52 #include "utils/syscache.h"
53 #include "storage/bufpage.h"    /* for page layout, for 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
67 #include "catalog/catname.h"
68 #include "catalog/pg_database.h"
69
70 #include "port-protos.h"
71 #include "libpq/libpq-be.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         char       *name;
199         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                          * The directories and PG_VERSION files are in order.
234                          */
235                         int rc; /* return code from some function we call */
236
237 #ifdef FILEDEBUG
238 printf("Try changing directory for database %s to %s\n", name, myPath);
239 #endif
240
241                         rc = chdir(myPath);
242                         if (rc < 0)
243                                 sprintf(errormsg,
244                                         "InitPostgres unable to change "
245                                         "current directory to '%s', errno = %s (%d).",
246                                         myPath, strerror(errno), errno);
247                         else
248                                 errormsg[0] = '\0';
249                 }
250         }
251
252         if (errormsg[0] != '\0')
253                 elog(FATAL, errormsg);
254         /* Above does not return */
255 } /* VerifyMyDatabase() */
256
257
258 /* --------------------------------
259  *              InitUserid
260  *
261  *              initializes crap associated with the user id.
262  * --------------------------------
263  */
264 static void
265 InitUserid()
266 {
267         setuid(geteuid());
268         SetUserId();
269 }
270
271 /* --------------------------------
272  *              InitCommunication
273  *
274  *              This routine initializes stuff needed for ipc, locking, etc.
275  *              it should be called something more informative.
276  *
277  * Note:
278  *              This does not set MyBackendId.  MyBackendTag is set, however.
279  * --------------------------------
280  */
281 static void
282 InitCommunication()
283 {
284         char *postid;       /* value of environment variable */
285         char *postport;     /* value of environment variable */
286         char *ipc_key;       /* value of environemnt variable */
287         IPCKey          key = 0;
288
289         /* ----------------
290          *      try and get the backend tag from POSTID
291          * ----------------
292          */
293         MyBackendId = -1;
294
295         postid = getenv("POSTID");
296         if (!PointerIsValid(postid))
297         {
298                 MyBackendTag = -1;
299         }
300         else
301         {
302                 MyBackendTag = atoi(postid);
303                 Assert(MyBackendTag >= 0);
304         }
305
306
307         ipc_key = getenv("IPC_KEY");
308         if (!PointerIsValid(ipc_key)) {
309             key = -1;
310         } else {
311             key = atoi(ipc_key);
312             Assert(MyBackendTag >= 0);
313         }
314      
315         postport = getenv("POSTPORT");
316
317         if (PointerIsValid(postport))
318         {
319                 if (MyBackendTag == -1)
320                         elog(FATAL, "InitCommunication: missing POSTID");
321
322                 /*
323                  * Enable this if you are trying to force the backend to run as if
324                  * it is running under the postmaster.
325                  *
326                  * This goto forces Postgres to attach to shared memory instead of
327                  * using malloc'ed memory (which is the normal behavior if run
328                  * directly).
329                  *
330                  * To enable emulation, run the following shell commands (in addition
331                  * to enabling this goto)
332                  *
333                  * % setenv POSTID 1 
334                  * % setenv POSTPORT 4321 
335                  * % setenv IPC_KEY 4321000
336                  * % postmaster & 
337                  * % kill -9 %1
338                  *
339                  * Upon doing this, Postmaster will have allocated the shared memory
340                  * resources that Postgres will attach to if you enable
341                  * EMULATE_UNDER_POSTMASTER.
342                  *
343                  * This comment may well age with time - it is current as of 8
344                  * January 1990
345                  *
346                  * Greg
347                  */
348
349 #ifdef EMULATE_UNDER_POSTMASTER
350
351                 goto forcesharedmemory;
352
353 #endif
354
355         }
356         else if (IsUnderPostmaster)
357         {
358                 elog(FATAL,
359                          "InitCommunication: under postmaster and POSTPORT not set");
360         }
361         else
362         {
363                 /* ----------------
364                  *      assume we're running a postgres backend by itself with
365                  *      no front end or postmaster.
366                  * ----------------
367                  */
368                 if (MyBackendTag == -1)
369                 {
370                         MyBackendTag = 1;
371                 }
372
373                 key = PrivateIPCKey;
374         }
375
376         /* ----------------
377          *      initialize shared memory and semaphores appropriately.
378          * ----------------
379          */
380 #ifdef EMULATE_UNDER_POSTMASTER
381
382 forcesharedmemory:
383
384 #endif
385
386         PostgresIpcKey = key;
387         AttachSharedMemoryAndSemaphores(key);
388 }
389
390
391 /* --------------------------------
392  *              InitStdio
393  *
394  *              this routine consists of a bunch of code fragments
395  *              that used to be randomly scattered through cinit().
396  *              they all seem to do stuff associated with io.
397  * --------------------------------
398  */
399 static void
400 InitStdio()
401 {
402         DebugFileOpen();
403 }
404
405 /* --------------------------------
406  * InitPostgres --
407  *              Initialize POSTGRES.
408  *
409  * Note:
410  *              Be very careful with the order of calls in the InitPostgres function.
411  * --------------------------------
412  */
413 bool            PostgresIsInitialized = false;
414 extern int      NBuffers;
415
416 /*
417  *      this global is used by wei for testing his code, but must be declared
418  *      here rather than in postgres.c so that it's defined for cinterface.a
419  *      applications.
420  */
421
422 /*int   testFlag = 0;*/
423 int                     lockingOff = 0;
424
425 /*
426  */
427 void
428 InitPostgres(char *name)                /* database name */
429 {
430         bool            bootstrap;              /* true if BootstrapProcessing */
431
432         /* ----------------
433          *      see if we're running in BootstrapProcessing mode
434          * ----------------
435          */
436         bootstrap = IsBootstrapProcessingMode();
437
438         /* ----------------
439          *      turn on the exception handler.  Note: we cannot use elog, Assert,
440          *      AssertState, etc. until after exception handling is on.
441          * ----------------
442          */
443         EnableExceptionHandling(true);
444
445         /* ----------------
446          *      A stupid check to make sure we don't call this more than once.
447          *      But things like ReinitPostgres() get around this by just diddling
448          *      the PostgresIsInitialized flag.
449          * ----------------
450          */
451         AssertState(!PostgresIsInitialized);
452
453         /* ----------------
454          *      Memory system initialization.
455          *      (we may call palloc after EnableMemoryContext())
456          *
457          *      Note EnableMemoryContext() must happen before EnablePortalManager().
458          * ----------------
459          */
460         EnableMemoryContext(true);      /* initializes the "top context" */
461         EnablePortalManager(true);      /* memory for portal/transaction stuff */
462
463         /* ----------------
464          *      initialize the backend local portal stack used by
465          *      internal PQ function calls.  see src/lib/libpq/be-dumpdata.c
466          *      This is different from the "portal manager" so this goes here.
467          *      -cim 2/12/91
468          * ----------------
469          */
470         be_portalinit();
471
472         /* ----------------
473          *       attach to shared memory and semaphores, and initialize our
474          *       input/output/debugging file descriptors.
475          * ----------------
476          */
477         InitCommunication();
478         InitStdio();
479
480         /*
481          * initialize the local buffer manager
482          */
483         InitLocalBuffer();
484
485         if (!TransactionFlushEnabled())
486                 on_exitpg(FlushBufferPool, (caddr_t) NULL);
487
488         /* ----------------
489          *      initialize the database id used for system caches and lock tables
490          * ----------------
491          */
492         if (bootstrap)
493         {
494                 SetDatabasePath(ExpandDatabasePath(name));
495                 SetDatabaseName(name);
496                 LockDisable(true);
497         }
498         else
499         {
500                 VerifySystemDatabase();
501                 InitMyDatabaseInfo(name);
502                 VerifyMyDatabase();
503         }
504
505         /*
506          * ********************************
507          * code after this point assumes we are in the proper directory!
508          *
509          * So, how do we implement alternate locations for databases?
510          * There are two possible locations for tables and we need to look
511          * in DataDir/pg_database to find the true location of an
512          * individual database. We can brute-force it as done in
513          * InitMyDatabaseInfo(), or we can be patient and wait until we
514          * open pg_database gracefully. Will try that, but may not work...
515          * - thomas 1997-11-01
516          * ********************************
517          */
518
519         /*  Does not touch files (?) - thomas 1997-11-01 */
520         smgrinit();
521
522         /* ----------------
523          *      initialize the transaction system and the relation descriptor cache.
524          *      Note we have to make certain the lock manager is off while we do this.
525          * ----------------
526          */
527         AmiTransactionOverride(IsBootstrapProcessingMode());
528         LockDisable(true);
529
530         /*
531          * Part of the initialization processing done here sets a read lock on
532          * pg_log.      Since locking is disabled the set doesn't have intended
533          * effect of locking out writers, but this is ok, since we only lock
534          * it to examine AMI transaction status, and this is never written
535          * after initdb is done. -mer 15 June 1992
536          */
537         RelationInitialize();           /* pre-allocated reldescs created here */
538         InitializeTransactionSystem();  /* pg_log,etc init/crash recovery here */
539
540         LockDisable(false);
541
542         /* ----------------
543          *      anyone knows what this does?  something having to do with
544          *      system catalog cache invalidation in the case of multiple
545          *      backends, I think -cim 10/3/90
546          *      Sets up MyBackendId a unique backend identifier.
547          * ----------------
548          */
549         InitSharedInvalidationState();
550
551         /* ----------------
552          * Set up a per backend process in shared memory.  Must be done after
553          * InitSharedInvalidationState() as it relies on MyBackendId being
554          * initialized already.  XXX -mer 11 Aug 1991
555          * ----------------
556          */
557         InitProcess(PostgresIpcKey);
558
559         if (MyBackendId > MaxBackendId || MyBackendId <= 0)
560         {
561                 elog(FATAL, "cinit2: bad backend id %d (%d)",
562                          MyBackendTag,
563                          MyBackendId);
564         }
565
566         /* ----------------
567          *      initialize the access methods.
568          *  Does not touch files (?) - thomas 1997-11-01
569          * ----------------
570          */
571         initam();
572
573         /* ----------------
574          *      initialize all the system catalog caches.
575          * ----------------
576          */
577         zerocaches();
578         /*  Does not touch files since all routines are builtins (?)
579          *  - thomas 1997-11-01
580          */
581         InitCatalogCache();
582
583         /* ----------------
584          *       set ourselves to the proper user id and figure out our postgres
585          *       user id.  If we ever add security so that we check for valid
586          *       postgres users, we might do it here.
587          * ----------------
588          */
589         InitUserid();
590
591         /* ----------------
592          *      ok, all done, now let's make sure we don't do it again.
593          * ----------------
594          */
595         PostgresIsInitialized = true;
596 /*        on_exitpg(DestroyLocalRelList, (caddr_t) NULL); */
597
598         /* ----------------
599          *      Done with "InitPostgres", now change to NormalProcessing unless
600          *      we're in BootstrapProcessing mode.
601          * ----------------
602          */
603         if (!bootstrap)
604                 SetProcessingMode(NormalProcessing);
605 /*        if (testFlag || lockingOff) */
606         if (lockingOff)
607                 LockDisable(true);
608 }