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