]> granicus.if.org Git - postgresql/blob - src/backend/utils/init/postinit.c
Process options from the startup packed in walsender. Only few options
[postgresql] / src / backend / utils / init / postinit.c
1 /*-------------------------------------------------------------------------
2  *
3  * postinit.c
4  *        postgres initialization utilities
5  *
6  * Portions Copyright (c) 1996-2010, PostgreSQL Global Development Group
7  * Portions Copyright (c) 1994, Regents of the University of California
8  *
9  *
10  * IDENTIFICATION
11  *        $PostgreSQL: pgsql/src/backend/utils/init/postinit.c,v 1.214 2010/09/13 09:00:30 heikki Exp $
12  *
13  *
14  *-------------------------------------------------------------------------
15  */
16 #include "postgres.h"
17
18 #include <ctype.h>
19 #include <fcntl.h>
20 #include <unistd.h>
21
22 #include "access/heapam.h"
23 #include "access/sysattr.h"
24 #include "access/xact.h"
25 #include "catalog/catalog.h"
26 #include "catalog/indexing.h"
27 #include "catalog/namespace.h"
28 #include "catalog/pg_authid.h"
29 #include "catalog/pg_database.h"
30 #include "catalog/pg_db_role_setting.h"
31 #include "catalog/pg_tablespace.h"
32 #include "libpq/auth.h"
33 #include "libpq/libpq-be.h"
34 #include "mb/pg_wchar.h"
35 #include "miscadmin.h"
36 #include "pgstat.h"
37 #include "postmaster/autovacuum.h"
38 #include "postmaster/postmaster.h"
39 #include "replication/walsender.h"
40 #include "storage/bufmgr.h"
41 #include "storage/fd.h"
42 #include "storage/ipc.h"
43 #include "storage/lmgr.h"
44 #include "storage/proc.h"
45 #include "storage/procarray.h"
46 #include "storage/procsignal.h"
47 #include "storage/sinvaladt.h"
48 #include "storage/smgr.h"
49 #include "tcop/tcopprot.h"
50 #include "utils/acl.h"
51 #include "utils/fmgroids.h"
52 #include "utils/guc.h"
53 #include "utils/pg_locale.h"
54 #include "utils/portal.h"
55 #include "utils/ps_status.h"
56 #include "utils/snapmgr.h"
57 #include "utils/syscache.h"
58 #include "utils/tqual.h"
59
60
61 static HeapTuple GetDatabaseTuple(const char *dbname);
62 static HeapTuple GetDatabaseTupleByOid(Oid dboid);
63 static void PerformAuthentication(Port *port);
64 static void CheckMyDatabase(const char *name, bool am_superuser);
65 static void InitCommunication(void);
66 static void ShutdownPostgres(int code, Datum arg);
67 static bool ThereIsAtLeastOneRole(void);
68 static void process_startup_options(Port *port, bool am_superuser);
69 static void process_settings(Oid databaseid, Oid roleid);
70
71
72 /*** InitPostgres support ***/
73
74
75 /*
76  * GetDatabaseTuple -- fetch the pg_database row for a database
77  *
78  * This is used during backend startup when we don't yet have any access to
79  * system catalogs in general.  In the worst case, we can seqscan pg_database
80  * using nothing but the hard-wired descriptor that relcache.c creates for
81  * pg_database.  In more typical cases, relcache.c was able to load
82  * descriptors for both pg_database and its indexes from the shared relcache
83  * cache file, and so we can do an indexscan.  criticalSharedRelcachesBuilt
84  * tells whether we got the cached descriptors.
85  */
86 static HeapTuple
87 GetDatabaseTuple(const char *dbname)
88 {
89         HeapTuple       tuple;
90         Relation        relation;
91         SysScanDesc scan;
92         ScanKeyData key[1];
93
94         /*
95          * form a scan key
96          */
97         ScanKeyInit(&key[0],
98                                 Anum_pg_database_datname,
99                                 BTEqualStrategyNumber, F_NAMEEQ,
100                                 CStringGetDatum(dbname));
101
102         /*
103          * Open pg_database and fetch a tuple.  Force heap scan if we haven't yet
104          * built the critical shared relcache entries (i.e., we're starting up
105          * without a shared relcache cache file).
106          */
107         relation = heap_open(DatabaseRelationId, AccessShareLock);
108         scan = systable_beginscan(relation, DatabaseNameIndexId,
109                                                           criticalSharedRelcachesBuilt,
110                                                           SnapshotNow,
111                                                           1, key);
112
113         tuple = systable_getnext(scan);
114
115         /* Must copy tuple before releasing buffer */
116         if (HeapTupleIsValid(tuple))
117                 tuple = heap_copytuple(tuple);
118
119         /* all done */
120         systable_endscan(scan);
121         heap_close(relation, AccessShareLock);
122
123         return tuple;
124 }
125
126 /*
127  * GetDatabaseTupleByOid -- as above, but search by database OID
128  */
129 static HeapTuple
130 GetDatabaseTupleByOid(Oid dboid)
131 {
132         HeapTuple       tuple;
133         Relation        relation;
134         SysScanDesc scan;
135         ScanKeyData key[1];
136
137         /*
138          * form a scan key
139          */
140         ScanKeyInit(&key[0],
141                                 ObjectIdAttributeNumber,
142                                 BTEqualStrategyNumber, F_OIDEQ,
143                                 ObjectIdGetDatum(dboid));
144
145         /*
146          * Open pg_database and fetch a tuple.  Force heap scan if we haven't yet
147          * built the critical shared relcache entries (i.e., we're starting up
148          * without a shared relcache cache file).
149          */
150         relation = heap_open(DatabaseRelationId, AccessShareLock);
151         scan = systable_beginscan(relation, DatabaseOidIndexId,
152                                                           criticalSharedRelcachesBuilt,
153                                                           SnapshotNow,
154                                                           1, key);
155
156         tuple = systable_getnext(scan);
157
158         /* Must copy tuple before releasing buffer */
159         if (HeapTupleIsValid(tuple))
160                 tuple = heap_copytuple(tuple);
161
162         /* all done */
163         systable_endscan(scan);
164         heap_close(relation, AccessShareLock);
165
166         return tuple;
167 }
168
169
170 /*
171  * PerformAuthentication -- authenticate a remote client
172  *
173  * returns: nothing.  Will not return at all if there's any failure.
174  */
175 static void
176 PerformAuthentication(Port *port)
177 {
178         /* This should be set already, but let's make sure */
179         ClientAuthInProgress = true;    /* limit visibility of log messages */
180
181         /*
182          * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
183          * etcetera from the postmaster, and have to load them ourselves.  Note we
184          * are loading them into the startup transaction's memory context, not
185          * PostmasterContext, but that shouldn't matter.
186          *
187          * FIXME: [fork/exec] Ugh.      Is there a way around this overhead?
188          */
189 #ifdef EXEC_BACKEND
190         if (!load_hba())
191         {
192                 /*
193                  * It makes no sense to continue if we fail to load the HBA file,
194                  * since there is no way to connect to the database in this case.
195                  */
196                 ereport(FATAL,
197                                 (errmsg("could not load pg_hba.conf")));
198         }
199         load_ident();
200 #endif
201
202         /*
203          * Set up a timeout in case a buggy or malicious client fails to respond
204          * during authentication.  Since we're inside a transaction and might do
205          * database access, we have to use the statement_timeout infrastructure.
206          */
207         if (!enable_sig_alarm(AuthenticationTimeout * 1000, true))
208                 elog(FATAL, "could not set timer for authorization timeout");
209
210         /*
211          * Now perform authentication exchange.
212          */
213         ClientAuthentication(port); /* might not return, if failure */
214
215         /*
216          * Done with authentication.  Disable the timeout, and log if needed.
217          */
218         if (!disable_sig_alarm(true))
219                 elog(FATAL, "could not disable timer for authorization timeout");
220
221         /*
222          * Log connection for streaming replication even if Log_connections
223          * disabled.
224          */
225         if (am_walsender)
226         {
227                 if (port->remote_port[0])
228                         ereport(LOG,
229                                         (errmsg("replication connection authorized: user=%s host=%s port=%s",
230                                                         port->user_name,
231                                                         port->remote_host,
232                                                         port->remote_port)));
233                 else
234                         ereport(LOG,
235                                 (errmsg("replication connection authorized: user=%s host=%s",
236                                                 port->user_name,
237                                                 port->remote_host)));
238         }
239         else if (Log_connections)
240                 ereport(LOG,
241                                 (errmsg("connection authorized: user=%s database=%s",
242                                                 port->user_name, port->database_name)));
243
244         set_ps_display("startup", false);
245
246         ClientAuthInProgress = false;           /* client_min_messages is active now */
247 }
248
249
250 /*
251  * CheckMyDatabase -- fetch information from the pg_database entry for our DB
252  */
253 static void
254 CheckMyDatabase(const char *name, bool am_superuser)
255 {
256         HeapTuple       tup;
257         Form_pg_database dbform;
258         char       *collate;
259         char       *ctype;
260
261         /* Fetch our pg_database row normally, via syscache */
262         tup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
263         if (!HeapTupleIsValid(tup))
264                 elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
265         dbform = (Form_pg_database) GETSTRUCT(tup);
266
267         /* This recheck is strictly paranoia */
268         if (strcmp(name, NameStr(dbform->datname)) != 0)
269                 ereport(FATAL,
270                                 (errcode(ERRCODE_UNDEFINED_DATABASE),
271                                  errmsg("database \"%s\" has disappeared from pg_database",
272                                                 name),
273                                  errdetail("Database OID %u now seems to belong to \"%s\".",
274                                                    MyDatabaseId, NameStr(dbform->datname))));
275
276         /*
277          * Check permissions to connect to the database.
278          *
279          * These checks are not enforced when in standalone mode, so that there is
280          * a way to recover from disabling all access to all databases, for
281          * example "UPDATE pg_database SET datallowconn = false;".
282          *
283          * We do not enforce them for autovacuum worker processes either.
284          */
285         if (IsUnderPostmaster && !IsAutoVacuumWorkerProcess())
286         {
287                 /*
288                  * Check that the database is currently allowing connections.
289                  */
290                 if (!dbform->datallowconn)
291                         ereport(FATAL,
292                                         (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
293                          errmsg("database \"%s\" is not currently accepting connections",
294                                         name)));
295
296                 /*
297                  * Check privilege to connect to the database.  (The am_superuser test
298                  * is redundant, but since we have the flag, might as well check it
299                  * and save a few cycles.)
300                  */
301                 if (!am_superuser &&
302                         pg_database_aclcheck(MyDatabaseId, GetUserId(),
303                                                                  ACL_CONNECT) != ACLCHECK_OK)
304                         ereport(FATAL,
305                                         (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
306                                          errmsg("permission denied for database \"%s\"", name),
307                                          errdetail("User does not have CONNECT privilege.")));
308
309                 /*
310                  * Check connection limit for this database.
311                  *
312                  * There is a race condition here --- we create our PGPROC before
313                  * checking for other PGPROCs.  If two backends did this at about the
314                  * same time, they might both think they were over the limit, while
315                  * ideally one should succeed and one fail.  Getting that to work
316                  * exactly seems more trouble than it is worth, however; instead we
317                  * just document that the connection limit is approximate.
318                  */
319                 if (dbform->datconnlimit >= 0 &&
320                         !am_superuser &&
321                         CountDBBackends(MyDatabaseId) > dbform->datconnlimit)
322                         ereport(FATAL,
323                                         (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
324                                          errmsg("too many connections for database \"%s\"",
325                                                         name)));
326         }
327
328         /*
329          * OK, we're golden.  Next to-do item is to save the encoding info out of
330          * the pg_database tuple.
331          */
332         SetDatabaseEncoding(dbform->encoding);
333         /* Record it as a GUC internal option, too */
334         SetConfigOption("server_encoding", GetDatabaseEncodingName(),
335                                         PGC_INTERNAL, PGC_S_OVERRIDE);
336         /* If we have no other source of client_encoding, use server encoding */
337         SetConfigOption("client_encoding", GetDatabaseEncodingName(),
338                                         PGC_BACKEND, PGC_S_DEFAULT);
339
340         /* assign locale variables */
341         collate = NameStr(dbform->datcollate);
342         ctype = NameStr(dbform->datctype);
343
344         if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
345                 ereport(FATAL,
346                         (errmsg("database locale is incompatible with operating system"),
347                          errdetail("The database was initialized with LC_COLLATE \"%s\", "
348                                            " which is not recognized by setlocale().", collate),
349                          errhint("Recreate the database with another locale or install the missing locale.")));
350
351         if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
352                 ereport(FATAL,
353                         (errmsg("database locale is incompatible with operating system"),
354                          errdetail("The database was initialized with LC_CTYPE \"%s\", "
355                                            " which is not recognized by setlocale().", ctype),
356                          errhint("Recreate the database with another locale or install the missing locale.")));
357
358         /* Make the locale settings visible as GUC variables, too */
359         SetConfigOption("lc_collate", collate, PGC_INTERNAL, PGC_S_OVERRIDE);
360         SetConfigOption("lc_ctype", ctype, PGC_INTERNAL, PGC_S_OVERRIDE);
361
362         /* Use the right encoding in translated messages */
363 #ifdef ENABLE_NLS
364         pg_bind_textdomain_codeset(textdomain(NULL));
365 #endif
366
367         ReleaseSysCache(tup);
368 }
369
370
371
372 /* --------------------------------
373  *              InitCommunication
374  *
375  *              This routine initializes stuff needed for ipc, locking, etc.
376  *              it should be called something more informative.
377  * --------------------------------
378  */
379 static void
380 InitCommunication(void)
381 {
382         /*
383          * initialize shared memory and semaphores appropriately.
384          */
385         if (!IsUnderPostmaster)         /* postmaster already did this */
386         {
387                 /*
388                  * We're running a postgres bootstrap process or a standalone backend.
389                  * Create private "shmem" and semaphores.
390                  */
391                 CreateSharedMemoryAndSemaphores(true, 0);
392         }
393 }
394
395
396 /*
397  * pg_split_opts -- split a string of options and append it to an argv array
398  *
399  * NB: the input string is destructively modified!      Also, caller is responsible
400  * for ensuring the argv array is large enough.  The maximum possible number
401  * of arguments added by this routine is (strlen(optstr) + 1) / 2.
402  *
403  * Since no current POSTGRES arguments require any quoting characters,
404  * we can use the simple-minded tactic of assuming each set of space-
405  * delimited characters is a separate argv element.
406  *
407  * If you don't like that, well, we *used* to pass the whole option string
408  * as ONE argument to execl(), which was even less intelligent...
409  */
410 void
411 pg_split_opts(char **argv, int *argcp, char *optstr)
412 {
413         while (*optstr)
414         {
415                 while (isspace((unsigned char) *optstr))
416                         optstr++;
417                 if (*optstr == '\0')
418                         break;
419                 argv[(*argcp)++] = optstr;
420                 while (*optstr && !isspace((unsigned char) *optstr))
421                         optstr++;
422                 if (*optstr)
423                         *optstr++ = '\0';
424         }
425 }
426
427
428 /*
429  * Early initialization of a backend (either standalone or under postmaster).
430  * This happens even before InitPostgres.
431  *
432  * This is separate from InitPostgres because it is also called by auxiliary
433  * processes, such as the background writer process, which may not call
434  * InitPostgres at all.
435  */
436 void
437 BaseInit(void)
438 {
439         /*
440          * Attach to shared memory and semaphores, and initialize our
441          * input/output/debugging file descriptors.
442          */
443         InitCommunication();
444         DebugFileOpen();
445
446         /* Do local initialization of file, storage and buffer managers */
447         InitFileAccess();
448         smgrinit();
449         InitBufferPoolAccess();
450 }
451
452
453 /* --------------------------------
454  * InitPostgres
455  *              Initialize POSTGRES.
456  *
457  * The database can be specified by name, using the in_dbname parameter, or by
458  * OID, using the dboid parameter.      In the latter case, the actual database
459  * name can be returned to the caller in out_dbname.  If out_dbname isn't
460  * NULL, it must point to a buffer of size NAMEDATALEN.
461  *
462  * In bootstrap mode no parameters are used.  The autovacuum launcher process
463  * doesn't use any parameters either, because it only goes far enough to be
464  * able to read pg_database; it doesn't connect to any particular database.
465  * In walsender mode only username is used.
466  *
467  * As of PostgreSQL 8.2, we expect InitProcess() was already called, so we
468  * already have a PGPROC struct ... but it's not completely filled in yet.
469  *
470  * Note:
471  *              Be very careful with the order of calls in the InitPostgres function.
472  * --------------------------------
473  */
474 void
475 InitPostgres(const char *in_dbname, Oid dboid, const char *username,
476                          char *out_dbname)
477 {
478         bool            bootstrap = IsBootstrapProcessingMode();
479         bool            am_superuser;
480         char       *fullpath;
481         char            dbname[NAMEDATALEN];
482
483         elog(DEBUG3, "InitPostgres");
484
485         /*
486          * Add my PGPROC struct to the ProcArray.
487          *
488          * Once I have done this, I am visible to other backends!
489          */
490         InitProcessPhase2();
491
492         /*
493          * Initialize my entry in the shared-invalidation manager's array of
494          * per-backend data.
495          *
496          * Sets up MyBackendId, a unique backend identifier.
497          */
498         MyBackendId = InvalidBackendId;
499
500         SharedInvalBackendInit(false);
501
502         if (MyBackendId > MaxBackends || MyBackendId <= 0)
503                 elog(FATAL, "bad backend id: %d", MyBackendId);
504
505         /* Now that we have a BackendId, we can participate in ProcSignal */
506         ProcSignalInit(MyBackendId);
507
508         /*
509          * bufmgr needs another initialization call too
510          */
511         InitBufferPoolBackend();
512
513         /*
514          * Initialize local process's access to XLOG.
515          */
516         if (IsUnderPostmaster)
517         {
518                 /*
519                  * The postmaster already started the XLOG machinery, but we need to
520                  * call InitXLOGAccess(), if the system isn't in hot-standby mode.
521                  * This is handled by calling RecoveryInProgress and ignoring the
522                  * result.
523                  */
524                 (void) RecoveryInProgress();
525         }
526         else
527         {
528                 /*
529                  * We are either a bootstrap process or a standalone backend. Either
530                  * way, start up the XLOG machinery, and register to have it closed
531                  * down at exit.
532                  */
533                 StartupXLOG();
534                 on_shmem_exit(ShutdownXLOG, 0);
535         }
536
537         /*
538          * Initialize the relation cache and the system catalog caches.  Note that
539          * no catalog access happens here; we only set up the hashtable structure.
540          * We must do this before starting a transaction because transaction abort
541          * would try to touch these hashtables.
542          */
543         RelationCacheInitialize();
544         InitCatalogCache();
545         InitPlanCache();
546
547         /* Initialize portal manager */
548         EnablePortalManager();
549
550         /* Initialize stats collection --- must happen before first xact */
551         if (!bootstrap)
552                 pgstat_initialize();
553
554         /*
555          * Load relcache entries for the shared system catalogs.  This must create
556          * at least entries for pg_database and catalogs used for authentication.
557          */
558         RelationCacheInitializePhase2();
559
560         /*
561          * Set up process-exit callback to do pre-shutdown cleanup.  This has to
562          * be after we've initialized all the low-level modules like the buffer
563          * manager, because during shutdown this has to run before the low-level
564          * modules start to close down.  On the other hand, we want it in place
565          * before we begin our first transaction --- if we fail during the
566          * initialization transaction, as is entirely possible, we need the
567          * AbortTransaction call to clean up.
568          */
569         on_shmem_exit(ShutdownPostgres, 0);
570
571         /* The autovacuum launcher is done here */
572         if (IsAutoVacuumLauncherProcess())
573                 return;
574
575         /*
576          * Start a new transaction here before first access to db, and get a
577          * snapshot.  We don't have a use for the snapshot itself, but we're
578          * interested in the secondary effect that it sets RecentGlobalXmin. (This
579          * is critical for anything that reads heap pages, because HOT may decide
580          * to prune them even if the process doesn't attempt to modify any
581          * tuples.)
582          */
583         if (!bootstrap)
584         {
585                 StartTransactionCommand();
586                 (void) GetTransactionSnapshot();
587         }
588
589         /*
590          * Perform client authentication if necessary, then figure out our
591          * postgres user ID, and see if we are a superuser.
592          *
593          * In standalone mode and in autovacuum worker processes, we use a fixed
594          * ID, otherwise we figure it out from the authenticated user name.
595          */
596         if (bootstrap || IsAutoVacuumWorkerProcess())
597         {
598                 InitializeSessionUserIdStandalone();
599                 am_superuser = true;
600         }
601         else if (!IsUnderPostmaster)
602         {
603                 InitializeSessionUserIdStandalone();
604                 am_superuser = true;
605                 if (!ThereIsAtLeastOneRole())
606                         ereport(WARNING,
607                                         (errcode(ERRCODE_UNDEFINED_OBJECT),
608                                          errmsg("no roles are defined in this database system"),
609                                          errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
610                                                          username)));
611         }
612         else
613         {
614                 /* normal multiuser case */
615                 Assert(MyProcPort != NULL);
616                 PerformAuthentication(MyProcPort);
617                 InitializeSessionUserId(username);
618                 am_superuser = superuser();
619         }
620
621         /*
622          * If we're trying to shut down, only superusers can connect, and new
623          * replication connections are not allowed.
624          */
625         if ((!am_superuser || am_walsender) &&
626                 MyProcPort != NULL &&
627                 MyProcPort->canAcceptConnections == CAC_WAITBACKUP)
628         {
629                 if (am_walsender)
630                         ereport(FATAL,
631                                         (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
632                                          errmsg("new replication connections are not allowed during database shutdown")));
633                 else
634                         ereport(FATAL,
635                                         (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
636                         errmsg("must be superuser to connect during database shutdown")));
637         }
638
639         /*
640          * The last few connections slots are reserved for superusers. Although
641          * replication connections currently require superuser privileges, we
642          * don't allow them to consume the reserved slots, which are intended for
643          * interactive use.
644          */
645         if ((!am_superuser || am_walsender) &&
646                 ReservedBackends > 0 &&
647                 !HaveNFreeProcs(ReservedBackends))
648                 ereport(FATAL,
649                                 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
650                                  errmsg("remaining connection slots are reserved for non-replication superuser connections")));
651
652         /*
653          * If walsender, we don't want to connect to any particular database.
654          * Just finish the backend startup by processing any options from the
655          * startup packet, and we're done.
656          */
657         if (am_walsender)
658         {
659                 Assert(!bootstrap);
660
661                 /* must have authenticated as a superuser */
662                 if (!am_superuser)
663                         ereport(FATAL,
664                                         (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
665                                          errmsg("must be superuser to start walsender")));
666
667                 /* process any options passed in the startup packet */
668                 if (MyProcPort != NULL)
669                         process_startup_options(MyProcPort, am_superuser);
670
671                 /* Apply PostAuthDelay as soon as we've read all options */
672                 if (PostAuthDelay > 0)
673                         pg_usleep(PostAuthDelay * 1000000L);
674
675                 /* initialize client encoding */
676                 InitializeClientEncoding();
677
678                 /* report this backend in the PgBackendStatus array */
679                 pgstat_bestart();
680
681                 /* close the transaction we started above */
682                 CommitTransactionCommand();
683
684                 return;
685         }
686
687         /*
688          * Set up the global variables holding database id and default tablespace.
689          * But note we won't actually try to touch the database just yet.
690          *
691          * We take a shortcut in the bootstrap case, otherwise we have to look up
692          * the db's entry in pg_database.
693          */
694         if (bootstrap)
695         {
696                 MyDatabaseId = TemplateDbOid;
697                 MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
698         }
699         else if (in_dbname != NULL)
700         {
701                 HeapTuple       tuple;
702                 Form_pg_database dbform;
703
704                 tuple = GetDatabaseTuple(in_dbname);
705                 if (!HeapTupleIsValid(tuple))
706                         ereport(FATAL,
707                                         (errcode(ERRCODE_UNDEFINED_DATABASE),
708                                          errmsg("database \"%s\" does not exist", in_dbname)));
709                 dbform = (Form_pg_database) GETSTRUCT(tuple);
710                 MyDatabaseId = HeapTupleGetOid(tuple);
711                 MyDatabaseTableSpace = dbform->dattablespace;
712                 /* take database name from the caller, just for paranoia */
713                 strlcpy(dbname, in_dbname, sizeof(dbname));
714         }
715         else
716         {
717                 /* caller specified database by OID */
718                 HeapTuple       tuple;
719                 Form_pg_database dbform;
720
721                 tuple = GetDatabaseTupleByOid(dboid);
722                 if (!HeapTupleIsValid(tuple))
723                         ereport(FATAL,
724                                         (errcode(ERRCODE_UNDEFINED_DATABASE),
725                                          errmsg("database %u does not exist", dboid)));
726                 dbform = (Form_pg_database) GETSTRUCT(tuple);
727                 MyDatabaseId = HeapTupleGetOid(tuple);
728                 MyDatabaseTableSpace = dbform->dattablespace;
729                 Assert(MyDatabaseId == dboid);
730                 strlcpy(dbname, NameStr(dbform->datname), sizeof(dbname));
731                 /* pass the database name back to the caller */
732                 if (out_dbname)
733                         strcpy(out_dbname, dbname);
734         }
735
736         /* Now we can mark our PGPROC entry with the database ID */
737         /* (We assume this is an atomic store so no lock is needed) */
738         MyProc->databaseId = MyDatabaseId;
739
740         /*
741          * Now, take a writer's lock on the database we are trying to connect to.
742          * If there is a concurrently running DROP DATABASE on that database, this
743          * will block us until it finishes (and has committed its update of
744          * pg_database).
745          *
746          * Note that the lock is not held long, only until the end of this startup
747          * transaction.  This is OK since we are already advertising our use of
748          * the database in the PGPROC array; anyone trying a DROP DATABASE after
749          * this point will see us there.
750          *
751          * Note: use of RowExclusiveLock here is reasonable because we envision
752          * our session as being a concurrent writer of the database.  If we had a
753          * way of declaring a session as being guaranteed-read-only, we could use
754          * AccessShareLock for such sessions and thereby not conflict against
755          * CREATE DATABASE.
756          */
757         if (!bootstrap)
758                 LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
759                                                  RowExclusiveLock);
760
761         /*
762          * Recheck pg_database to make sure the target database hasn't gone away.
763          * If there was a concurrent DROP DATABASE, this ensures we will die
764          * cleanly without creating a mess.
765          */
766         if (!bootstrap)
767         {
768                 HeapTuple       tuple;
769
770                 tuple = GetDatabaseTuple(dbname);
771                 if (!HeapTupleIsValid(tuple) ||
772                         MyDatabaseId != HeapTupleGetOid(tuple) ||
773                         MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
774                         ereport(FATAL,
775                                         (errcode(ERRCODE_UNDEFINED_DATABASE),
776                                          errmsg("database \"%s\" does not exist", dbname),
777                            errdetail("It seems to have just been dropped or renamed.")));
778         }
779
780         /*
781          * Now we should be able to access the database directory safely. Verify
782          * it's there and looks reasonable.
783          */
784         fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
785
786         if (!bootstrap)
787         {
788                 if (access(fullpath, F_OK) == -1)
789                 {
790                         if (errno == ENOENT)
791                                 ereport(FATAL,
792                                                 (errcode(ERRCODE_UNDEFINED_DATABASE),
793                                                  errmsg("database \"%s\" does not exist",
794                                                                 dbname),
795                                         errdetail("The database subdirectory \"%s\" is missing.",
796                                                           fullpath)));
797                         else
798                                 ereport(FATAL,
799                                                 (errcode_for_file_access(),
800                                                  errmsg("could not access directory \"%s\": %m",
801                                                                 fullpath)));
802                 }
803
804                 ValidatePgVersion(fullpath);
805         }
806
807         SetDatabasePath(fullpath);
808
809         /*
810          * It's now possible to do real access to the system catalogs.
811          *
812          * Load relcache entries for the system catalogs.  This must create at
813          * least the minimum set of "nailed-in" cache entries.
814          */
815         RelationCacheInitializePhase3();
816
817         /* set up ACL framework (so CheckMyDatabase can check permissions) */
818         initialize_acl();
819
820         /*
821          * Re-read the pg_database row for our database, check permissions and set
822          * up database-specific GUC settings.  We can't do this until all the
823          * database-access infrastructure is up.  (Also, it wants to know if the
824          * user is a superuser, so the above stuff has to happen first.)
825          */
826         if (!bootstrap)
827                 CheckMyDatabase(dbname, am_superuser);
828
829         /*
830          * Now process any command-line switches and any additional GUC variable
831          * settings passed in the startup packet.       We couldn't do this before
832          * because we didn't know if client is a superuser.
833          */
834         if (MyProcPort != NULL)
835                 process_startup_options(MyProcPort, am_superuser);
836
837         /* Process pg_db_role_setting options */
838         process_settings(MyDatabaseId, GetSessionUserId());
839
840         /* Apply PostAuthDelay as soon as we've read all options */
841         if (PostAuthDelay > 0)
842                 pg_usleep(PostAuthDelay * 1000000L);
843
844         /*
845          * Initialize various default states that can't be set up until we've
846          * selected the active user and gotten the right GUC settings.
847          */
848
849         /* set default namespace search path */
850         InitializeSearchPath();
851
852         /* initialize client encoding */
853         InitializeClientEncoding();
854
855         /* report this backend in the PgBackendStatus array */
856         if (!bootstrap)
857                 pgstat_bestart();
858
859         /* close the transaction we started above */
860         if (!bootstrap)
861                 CommitTransactionCommand();
862 }
863
864 /*
865  * Process any command-line switches and any additional GUC variable
866  * settings passed in the startup packet.
867  */
868 static void
869 process_startup_options(Port *port, bool am_superuser)
870 {
871         GucContext      gucctx;
872         ListCell   *gucopts;
873
874         gucctx = am_superuser ? PGC_SUSET : PGC_BACKEND;
875
876         /*
877          * First process any command-line switches that were included in the
878          * startup packet, if we are in a regular backend.
879          */
880         if (port->cmdline_options != NULL)
881         {
882                 /*
883                  * The maximum possible number of commandline arguments that could
884                  * come from port->cmdline_options is (strlen + 1) / 2; see
885                  * pg_split_opts().
886                  */
887                 char      **av;
888                 int                     maxac;
889                 int                     ac;
890
891                 maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
892
893                 av = (char **) palloc(maxac * sizeof(char *));
894                 ac = 0;
895
896                 av[ac++] = "postgres";
897
898                 /* Note this mangles port->cmdline_options */
899                 pg_split_opts(av, &ac, port->cmdline_options);
900
901                 av[ac] = NULL;
902
903                 Assert(ac < maxac);
904
905                 (void) process_postgres_switches(ac, av, gucctx);
906         }
907
908         /*
909          * Process any additional GUC variable settings passed in startup packet.
910          * These are handled exactly like command-line variables.
911          */
912         gucopts = list_head(port->guc_options);
913         while (gucopts)
914         {
915                 char       *name;
916                 char       *value;
917
918                 name = lfirst(gucopts);
919                 gucopts = lnext(gucopts);
920
921                 value = lfirst(gucopts);
922                 gucopts = lnext(gucopts);
923
924                 SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
925         }
926 }
927
928 /*
929  * Load GUC settings from pg_db_role_setting.
930  *
931  * We try specific settings for the database/role combination, as well as
932  * general for this database and for this user.
933  */
934 static void
935 process_settings(Oid databaseid, Oid roleid)
936 {
937         Relation        relsetting;
938
939         if (!IsUnderPostmaster)
940                 return;
941
942         relsetting = heap_open(DbRoleSettingRelationId, AccessShareLock);
943
944         /* Later settings are ignored if set earlier. */
945         ApplySetting(databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
946         ApplySetting(InvalidOid, roleid, relsetting, PGC_S_USER);
947         ApplySetting(databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
948
949         heap_close(relsetting, AccessShareLock);
950 }
951
952 /*
953  * Backend-shutdown callback.  Do cleanup that we want to be sure happens
954  * before all the supporting modules begin to nail their doors shut via
955  * their own callbacks.
956  *
957  * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
958  * via separate callbacks that execute before this one.  We don't combine the
959  * callbacks because we still want this one to happen if the user-level
960  * cleanup fails.
961  */
962 static void
963 ShutdownPostgres(int code, Datum arg)
964 {
965         /* Make sure we've killed any active transaction */
966         AbortOutOfAnyTransaction();
967
968         /*
969          * User locks are not released by transaction end, so be sure to release
970          * them explicitly.
971          */
972         LockReleaseAll(USER_LOCKMETHOD, true);
973 }
974
975
976 /*
977  * Returns true if at least one role is defined in this database cluster.
978  */
979 static bool
980 ThereIsAtLeastOneRole(void)
981 {
982         Relation        pg_authid_rel;
983         HeapScanDesc scan;
984         bool            result;
985
986         pg_authid_rel = heap_open(AuthIdRelationId, AccessShareLock);
987
988         scan = heap_beginscan(pg_authid_rel, SnapshotNow, 0, NULL);
989         result = (heap_getnext(scan, ForwardScanDirection) != NULL);
990
991         heap_endscan(scan);
992         heap_close(pg_authid_rel, AccessShareLock);
993
994         return result;
995 }