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