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