1 /*-------------------------------------------------------------------------
4 * postgres initialization utilities
6 * Portions Copyright (c) 1996-2017, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/utils/init/postinit.c
14 *-------------------------------------------------------------------------
22 #include "access/heapam.h"
23 #include "access/htup_details.h"
24 #include "access/session.h"
25 #include "access/sysattr.h"
26 #include "access/xact.h"
27 #include "access/xlog.h"
28 #include "catalog/catalog.h"
29 #include "catalog/indexing.h"
30 #include "catalog/namespace.h"
31 #include "catalog/pg_authid.h"
32 #include "catalog/pg_database.h"
33 #include "catalog/pg_db_role_setting.h"
34 #include "catalog/pg_tablespace.h"
35 #include "libpq/auth.h"
36 #include "libpq/libpq-be.h"
37 #include "mb/pg_wchar.h"
38 #include "miscadmin.h"
40 #include "postmaster/autovacuum.h"
41 #include "postmaster/postmaster.h"
42 #include "replication/walsender.h"
43 #include "storage/bufmgr.h"
44 #include "storage/fd.h"
45 #include "storage/ipc.h"
46 #include "storage/lmgr.h"
47 #include "storage/procarray.h"
48 #include "storage/procsignal.h"
49 #include "storage/proc.h"
50 #include "storage/sinvaladt.h"
51 #include "storage/smgr.h"
52 #include "tcop/tcopprot.h"
53 #include "utils/acl.h"
54 #include "utils/fmgroids.h"
55 #include "utils/guc.h"
56 #include "utils/memutils.h"
57 #include "utils/pg_locale.h"
58 #include "utils/portal.h"
59 #include "utils/ps_status.h"
60 #include "utils/snapmgr.h"
61 #include "utils/syscache.h"
62 #include "utils/timeout.h"
63 #include "utils/tqual.h"
66 static HeapTuple GetDatabaseTuple(const char *dbname);
67 static HeapTuple GetDatabaseTupleByOid(Oid dboid);
68 static void PerformAuthentication(Port *port);
69 static void CheckMyDatabase(const char *name, bool am_superuser);
70 static void InitCommunication(void);
71 static void ShutdownPostgres(int code, Datum arg);
72 static void StatementTimeoutHandler(void);
73 static void LockTimeoutHandler(void);
74 static void IdleInTransactionSessionTimeoutHandler(void);
75 static bool ThereIsAtLeastOneRole(void);
76 static void process_startup_options(Port *port, bool am_superuser);
77 static void process_settings(Oid databaseid, Oid roleid);
80 /*** InitPostgres support ***/
84 * GetDatabaseTuple -- fetch the pg_database row for a database
86 * This is used during backend startup when we don't yet have any access to
87 * system catalogs in general. In the worst case, we can seqscan pg_database
88 * using nothing but the hard-wired descriptor that relcache.c creates for
89 * pg_database. In more typical cases, relcache.c was able to load
90 * descriptors for both pg_database and its indexes from the shared relcache
91 * cache file, and so we can do an indexscan. criticalSharedRelcachesBuilt
92 * tells whether we got the cached descriptors.
95 GetDatabaseTuple(const char *dbname)
106 Anum_pg_database_datname,
107 BTEqualStrategyNumber, F_NAMEEQ,
108 CStringGetDatum(dbname));
111 * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
112 * built the critical shared relcache entries (i.e., we're starting up
113 * without a shared relcache cache file).
115 relation = heap_open(DatabaseRelationId, AccessShareLock);
116 scan = systable_beginscan(relation, DatabaseNameIndexId,
117 criticalSharedRelcachesBuilt,
121 tuple = systable_getnext(scan);
123 /* Must copy tuple before releasing buffer */
124 if (HeapTupleIsValid(tuple))
125 tuple = heap_copytuple(tuple);
128 systable_endscan(scan);
129 heap_close(relation, AccessShareLock);
135 * GetDatabaseTupleByOid -- as above, but search by database OID
138 GetDatabaseTupleByOid(Oid dboid)
149 ObjectIdAttributeNumber,
150 BTEqualStrategyNumber, F_OIDEQ,
151 ObjectIdGetDatum(dboid));
154 * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
155 * built the critical shared relcache entries (i.e., we're starting up
156 * without a shared relcache cache file).
158 relation = heap_open(DatabaseRelationId, AccessShareLock);
159 scan = systable_beginscan(relation, DatabaseOidIndexId,
160 criticalSharedRelcachesBuilt,
164 tuple = systable_getnext(scan);
166 /* Must copy tuple before releasing buffer */
167 if (HeapTupleIsValid(tuple))
168 tuple = heap_copytuple(tuple);
171 systable_endscan(scan);
172 heap_close(relation, AccessShareLock);
179 * PerformAuthentication -- authenticate a remote client
181 * returns: nothing. Will not return at all if there's any failure.
184 PerformAuthentication(Port *port)
186 /* This should be set already, but let's make sure */
187 ClientAuthInProgress = true; /* limit visibility of log messages */
190 * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
191 * etcetera from the postmaster, and have to load them ourselves.
193 * FIXME: [fork/exec] Ugh. Is there a way around this overhead?
198 * load_hba() and load_ident() want to work within the PostmasterContext,
199 * so create that if it doesn't exist (which it won't). We'll delete it
200 * again later, in PostgresMain.
202 if (PostmasterContext == NULL)
203 PostmasterContext = AllocSetContextCreate(TopMemoryContext,
205 ALLOCSET_DEFAULT_SIZES);
210 * It makes no sense to continue if we fail to load the HBA file,
211 * since there is no way to connect to the database in this case.
214 (errmsg("could not load pg_hba.conf")));
220 * It is ok to continue if we fail to load the IDENT file, although it
221 * means that you cannot log in using any of the authentication
222 * methods that need a user name mapping. load_ident() already logged
223 * the details of error to the log.
229 * Set up a timeout in case a buggy or malicious client fails to respond
230 * during authentication. Since we're inside a transaction and might do
231 * database access, we have to use the statement_timeout infrastructure.
233 enable_timeout_after(STATEMENT_TIMEOUT, AuthenticationTimeout * 1000);
236 * Now perform authentication exchange.
238 ClientAuthentication(port); /* might not return, if failure */
241 * Done with authentication. Disable the timeout, and log if needed.
243 disable_timeout(STATEMENT_TIMEOUT, false);
250 if (port->ssl_in_use)
252 (errmsg("replication connection authorized: user=%s SSL enabled (protocol=%s, cipher=%s, compression=%s)",
253 port->user_name, SSL_get_version(port->ssl), SSL_get_cipher(port->ssl),
254 SSL_get_current_compression(port->ssl) ? _("on") : _("off"))));
258 (errmsg("replication connection authorized: user=%s",
264 if (port->ssl_in_use)
266 (errmsg("connection authorized: user=%s database=%s SSL enabled (protocol=%s, cipher=%s, compression=%s)",
267 port->user_name, port->database_name, SSL_get_version(port->ssl), SSL_get_cipher(port->ssl),
268 SSL_get_current_compression(port->ssl) ? _("on") : _("off"))));
272 (errmsg("connection authorized: user=%s database=%s",
273 port->user_name, port->database_name)));
277 set_ps_display("startup", false);
279 ClientAuthInProgress = false; /* client_min_messages is active now */
284 * CheckMyDatabase -- fetch information from the pg_database entry for our DB
287 CheckMyDatabase(const char *name, bool am_superuser)
290 Form_pg_database dbform;
294 /* Fetch our pg_database row normally, via syscache */
295 tup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
296 if (!HeapTupleIsValid(tup))
297 elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
298 dbform = (Form_pg_database) GETSTRUCT(tup);
300 /* This recheck is strictly paranoia */
301 if (strcmp(name, NameStr(dbform->datname)) != 0)
303 (errcode(ERRCODE_UNDEFINED_DATABASE),
304 errmsg("database \"%s\" has disappeared from pg_database",
306 errdetail("Database OID %u now seems to belong to \"%s\".",
307 MyDatabaseId, NameStr(dbform->datname))));
310 * Check permissions to connect to the database.
312 * These checks are not enforced when in standalone mode, so that there is
313 * a way to recover from disabling all access to all databases, for
314 * example "UPDATE pg_database SET datallowconn = false;".
316 * We do not enforce them for autovacuum worker processes either.
318 if (IsUnderPostmaster && !IsAutoVacuumWorkerProcess())
321 * Check that the database is currently allowing connections.
323 if (!dbform->datallowconn)
325 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
326 errmsg("database \"%s\" is not currently accepting connections",
330 * Check privilege to connect to the database. (The am_superuser test
331 * is redundant, but since we have the flag, might as well check it
332 * and save a few cycles.)
335 pg_database_aclcheck(MyDatabaseId, GetUserId(),
336 ACL_CONNECT) != ACLCHECK_OK)
338 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
339 errmsg("permission denied for database \"%s\"", name),
340 errdetail("User does not have CONNECT privilege.")));
343 * Check connection limit for this database.
345 * There is a race condition here --- we create our PGPROC before
346 * checking for other PGPROCs. If two backends did this at about the
347 * same time, they might both think they were over the limit, while
348 * ideally one should succeed and one fail. Getting that to work
349 * exactly seems more trouble than it is worth, however; instead we
350 * just document that the connection limit is approximate.
352 if (dbform->datconnlimit >= 0 &&
354 CountDBConnections(MyDatabaseId) > dbform->datconnlimit)
356 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
357 errmsg("too many connections for database \"%s\"",
362 * OK, we're golden. Next to-do item is to save the encoding info out of
363 * the pg_database tuple.
365 SetDatabaseEncoding(dbform->encoding);
366 /* Record it as a GUC internal option, too */
367 SetConfigOption("server_encoding", GetDatabaseEncodingName(),
368 PGC_INTERNAL, PGC_S_OVERRIDE);
369 /* If we have no other source of client_encoding, use server encoding */
370 SetConfigOption("client_encoding", GetDatabaseEncodingName(),
371 PGC_BACKEND, PGC_S_DYNAMIC_DEFAULT);
373 /* assign locale variables */
374 collate = NameStr(dbform->datcollate);
375 ctype = NameStr(dbform->datctype);
377 if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
379 (errmsg("database locale is incompatible with operating system"),
380 errdetail("The database was initialized with LC_COLLATE \"%s\", "
381 " which is not recognized by setlocale().", collate),
382 errhint("Recreate the database with another locale or install the missing locale.")));
384 if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
386 (errmsg("database locale is incompatible with operating system"),
387 errdetail("The database was initialized with LC_CTYPE \"%s\", "
388 " which is not recognized by setlocale().", ctype),
389 errhint("Recreate the database with another locale or install the missing locale.")));
391 /* Make the locale settings visible as GUC variables, too */
392 SetConfigOption("lc_collate", collate, PGC_INTERNAL, PGC_S_OVERRIDE);
393 SetConfigOption("lc_ctype", ctype, PGC_INTERNAL, PGC_S_OVERRIDE);
397 ReleaseSysCache(tup);
402 /* --------------------------------
405 * This routine initializes stuff needed for ipc, locking, etc.
406 * it should be called something more informative.
407 * --------------------------------
410 InitCommunication(void)
413 * initialize shared memory and semaphores appropriately.
415 if (!IsUnderPostmaster) /* postmaster already did this */
418 * We're running a postgres bootstrap process or a standalone backend.
419 * Create private "shmem" and semaphores.
421 CreateSharedMemoryAndSemaphores(true, 0);
427 * pg_split_opts -- split a string of options and append it to an argv array
429 * The caller is responsible for ensuring the argv array is large enough. The
430 * maximum possible number of arguments added by this routine is
431 * (strlen(optstr) + 1) / 2.
433 * Because some option values can contain spaces we allow escaping using
434 * backslashes, with \\ representing a literal backslash.
437 pg_split_opts(char **argv, int *argcp, const char *optstr)
445 bool last_was_escape = false;
449 /* skip over leading space */
450 while (isspace((unsigned char) *optstr))
457 * Parse a single option, stopping at the first space, unless it's
462 if (isspace((unsigned char) *optstr) && !last_was_escape)
465 if (!last_was_escape && *optstr == '\\')
466 last_was_escape = true;
469 last_was_escape = false;
470 appendStringInfoChar(&s, *optstr);
476 /* now store the option in the next argv[] position */
477 argv[(*argcp)++] = pstrdup(s.data);
484 * Initialize MaxBackends value from config options.
486 * This must be called after modules have had the chance to register background
487 * workers in shared_preload_libraries, and before shared memory size is
490 * Note that in EXEC_BACKEND environment, the value is passed down from
491 * postmaster to subprocesses via BackendParameters in SubPostmasterMain; only
492 * postmaster itself and processes not under postmaster control should call
496 InitializeMaxBackends(void)
498 Assert(MaxBackends == 0);
500 /* the extra unit accounts for the autovacuum launcher */
501 MaxBackends = MaxConnections + autovacuum_max_workers + 1 +
502 max_worker_processes;
504 /* internal error because the values were all checked previously */
505 if (MaxBackends > MAX_BACKENDS)
506 elog(ERROR, "too many backends configured");
510 * Early initialization of a backend (either standalone or under postmaster).
511 * This happens even before InitPostgres.
513 * This is separate from InitPostgres because it is also called by auxiliary
514 * processes, such as the background writer process, which may not call
515 * InitPostgres at all.
521 * Attach to shared memory and semaphores, and initialize our
522 * input/output/debugging file descriptors.
527 /* Do local initialization of file, storage and buffer managers */
530 InitBufferPoolAccess();
534 /* --------------------------------
536 * Initialize POSTGRES.
538 * The database can be specified by name, using the in_dbname parameter, or by
539 * OID, using the dboid parameter. In the latter case, the actual database
540 * name can be returned to the caller in out_dbname. If out_dbname isn't
541 * NULL, it must point to a buffer of size NAMEDATALEN.
543 * Similarly, the username can be passed by name, using the username parameter,
544 * or by OID using the useroid parameter.
546 * In bootstrap mode no parameters are used. The autovacuum launcher process
547 * doesn't use any parameters either, because it only goes far enough to be
548 * able to read pg_database; it doesn't connect to any particular database.
549 * In walsender mode only username is used.
551 * As of PostgreSQL 8.2, we expect InitProcess() was already called, so we
552 * already have a PGPROC struct ... but it's not completely filled in yet.
555 * Be very careful with the order of calls in the InitPostgres function.
556 * --------------------------------
559 InitPostgres(const char *in_dbname, Oid dboid, const char *username,
560 Oid useroid, char *out_dbname)
562 bool bootstrap = IsBootstrapProcessingMode();
565 char dbname[NAMEDATALEN];
567 elog(DEBUG3, "InitPostgres");
570 * Add my PGPROC struct to the ProcArray.
572 * Once I have done this, I am visible to other backends!
577 * Initialize my entry in the shared-invalidation manager's array of
580 * Sets up MyBackendId, a unique backend identifier.
582 MyBackendId = InvalidBackendId;
584 SharedInvalBackendInit(false);
586 if (MyBackendId > MaxBackends || MyBackendId <= 0)
587 elog(FATAL, "bad backend ID: %d", MyBackendId);
589 /* Now that we have a BackendId, we can participate in ProcSignal */
590 ProcSignalInit(MyBackendId);
593 * Also set up timeout handlers needed for backend operation. We need
594 * these in every case except bootstrap.
598 RegisterTimeout(DEADLOCK_TIMEOUT, CheckDeadLockAlert);
599 RegisterTimeout(STATEMENT_TIMEOUT, StatementTimeoutHandler);
600 RegisterTimeout(LOCK_TIMEOUT, LockTimeoutHandler);
601 RegisterTimeout(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
602 IdleInTransactionSessionTimeoutHandler);
606 * bufmgr needs another initialization call too
608 InitBufferPoolBackend();
611 * Initialize local process's access to XLOG.
613 if (IsUnderPostmaster)
616 * The postmaster already started the XLOG machinery, but we need to
617 * call InitXLOGAccess(), if the system isn't in hot-standby mode.
618 * This is handled by calling RecoveryInProgress and ignoring the
621 (void) RecoveryInProgress();
626 * We are either a bootstrap process or a standalone backend. Either
627 * way, start up the XLOG machinery, and register to have it closed
631 on_shmem_exit(ShutdownXLOG, 0);
635 * Initialize the relation cache and the system catalog caches. Note that
636 * no catalog access happens here; we only set up the hashtable structure.
637 * We must do this before starting a transaction because transaction abort
638 * would try to touch these hashtables.
640 RelationCacheInitialize();
644 /* Initialize portal manager */
645 EnablePortalManager();
647 /* Initialize stats collection --- must happen before first xact */
652 * Load relcache entries for the shared system catalogs. This must create
653 * at least entries for pg_database and catalogs used for authentication.
655 RelationCacheInitializePhase2();
658 * Set up process-exit callback to do pre-shutdown cleanup. This is the
659 * first before_shmem_exit callback we register; thus, this will be the
660 * last thing we do before low-level modules like the buffer manager begin
661 * to close down. We need to have this in place before we begin our first
662 * transaction --- if we fail during the initialization transaction, as is
663 * entirely possible, we need the AbortTransaction call to clean up.
665 before_shmem_exit(ShutdownPostgres, 0);
667 /* The autovacuum launcher is done here */
668 if (IsAutoVacuumLauncherProcess())
670 /* report this backend in the PgBackendStatus array */
677 * Start a new transaction here before first access to db, and get a
678 * snapshot. We don't have a use for the snapshot itself, but we're
679 * interested in the secondary effect that it sets RecentGlobalXmin. (This
680 * is critical for anything that reads heap pages, because HOT may decide
681 * to prune them even if the process doesn't attempt to modify any
686 /* statement_timestamp must be set for timeouts to work correctly */
687 SetCurrentStatementStartTimestamp();
688 StartTransactionCommand();
691 * transaction_isolation will have been set to the default by the
692 * above. If the default is "serializable", and we are in hot
693 * standby, we will fail if we don't change it to something lower.
694 * Fortunately, "read committed" is plenty good enough.
696 XactIsoLevel = XACT_READ_COMMITTED;
698 (void) GetTransactionSnapshot();
702 * Perform client authentication if necessary, then figure out our
703 * postgres user ID, and see if we are a superuser.
705 * In standalone mode and in autovacuum worker processes, we use a fixed
706 * ID, otherwise we figure it out from the authenticated user name.
708 if (bootstrap || IsAutoVacuumWorkerProcess())
710 InitializeSessionUserIdStandalone();
713 else if (!IsUnderPostmaster)
715 InitializeSessionUserIdStandalone();
717 if (!ThereIsAtLeastOneRole())
719 (errcode(ERRCODE_UNDEFINED_OBJECT),
720 errmsg("no roles are defined in this database system"),
721 errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
722 username != NULL ? username : "postgres")));
724 else if (IsBackgroundWorker)
726 if (username == NULL && !OidIsValid(useroid))
728 InitializeSessionUserIdStandalone();
733 InitializeSessionUserId(username, useroid);
734 am_superuser = superuser();
739 /* normal multiuser case */
740 Assert(MyProcPort != NULL);
741 PerformAuthentication(MyProcPort);
742 InitializeSessionUserId(username, useroid);
743 am_superuser = superuser();
747 * If we're trying to shut down, only superusers can connect, and new
748 * replication connections are not allowed.
750 if ((!am_superuser || am_walsender) &&
751 MyProcPort != NULL &&
752 MyProcPort->canAcceptConnections == CAC_WAITBACKUP)
756 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
757 errmsg("new replication connections are not allowed during database shutdown")));
760 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
761 errmsg("must be superuser to connect during database shutdown")));
765 * Binary upgrades only allowed super-user connections
767 if (IsBinaryUpgrade && !am_superuser)
770 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
771 errmsg("must be superuser to connect in binary upgrade mode")));
775 * The last few connections slots are reserved for superusers. Although
776 * replication connections currently require superuser privileges, we
777 * don't allow them to consume the reserved slots, which are intended for
780 if ((!am_superuser || am_walsender) &&
781 ReservedBackends > 0 &&
782 !HaveNFreeProcs(ReservedBackends))
784 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
785 errmsg("remaining connection slots are reserved for non-replication superuser connections")));
787 /* Check replication permissions needed for walsender processes. */
792 if (!superuser() && !has_rolreplication(GetUserId()))
794 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
795 errmsg("must be superuser or replication role to start walsender")));
799 * If this is a plain walsender only supporting physical replication, we
800 * don't want to connect to any particular database. Just finish the
801 * backend startup by processing any options from the startup packet, and
804 if (am_walsender && !am_db_walsender)
806 /* process any options passed in the startup packet */
807 if (MyProcPort != NULL)
808 process_startup_options(MyProcPort, am_superuser);
810 /* Apply PostAuthDelay as soon as we've read all options */
811 if (PostAuthDelay > 0)
812 pg_usleep(PostAuthDelay * 1000000L);
814 /* initialize client encoding */
815 InitializeClientEncoding();
817 /* report this backend in the PgBackendStatus array */
820 /* close the transaction we started above */
821 CommitTransactionCommand();
827 * Set up the global variables holding database id and default tablespace.
828 * But note we won't actually try to touch the database just yet.
830 * We take a shortcut in the bootstrap case, otherwise we have to look up
831 * the db's entry in pg_database.
835 MyDatabaseId = TemplateDbOid;
836 MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
838 else if (in_dbname != NULL)
841 Form_pg_database dbform;
843 tuple = GetDatabaseTuple(in_dbname);
844 if (!HeapTupleIsValid(tuple))
846 (errcode(ERRCODE_UNDEFINED_DATABASE),
847 errmsg("database \"%s\" does not exist", in_dbname)));
848 dbform = (Form_pg_database) GETSTRUCT(tuple);
849 MyDatabaseId = HeapTupleGetOid(tuple);
850 MyDatabaseTableSpace = dbform->dattablespace;
851 /* take database name from the caller, just for paranoia */
852 strlcpy(dbname, in_dbname, sizeof(dbname));
854 else if (OidIsValid(dboid))
856 /* caller specified database by OID */
858 Form_pg_database dbform;
860 tuple = GetDatabaseTupleByOid(dboid);
861 if (!HeapTupleIsValid(tuple))
863 (errcode(ERRCODE_UNDEFINED_DATABASE),
864 errmsg("database %u does not exist", dboid)));
865 dbform = (Form_pg_database) GETSTRUCT(tuple);
866 MyDatabaseId = HeapTupleGetOid(tuple);
867 MyDatabaseTableSpace = dbform->dattablespace;
868 Assert(MyDatabaseId == dboid);
869 strlcpy(dbname, NameStr(dbform->datname), sizeof(dbname));
870 /* pass the database name back to the caller */
872 strcpy(out_dbname, dbname);
877 * If this is a background worker not bound to any particular
878 * database, we're done now. Everything that follows only makes sense
879 * if we are bound to a specific database. We do need to close the
880 * transaction we started before returning.
885 CommitTransactionCommand();
891 * Now, take a writer's lock on the database we are trying to connect to.
892 * If there is a concurrently running DROP DATABASE on that database, this
893 * will block us until it finishes (and has committed its update of
896 * Note that the lock is not held long, only until the end of this startup
897 * transaction. This is OK since we will advertise our use of the
898 * database in the ProcArray before dropping the lock (in fact, that's the
899 * next thing to do). Anyone trying a DROP DATABASE after this point will
900 * see us in the array once they have the lock. Ordering is important for
901 * this because we don't want to advertise ourselves as being in this
902 * database until we have the lock; otherwise we create what amounts to a
903 * deadlock with CountOtherDBBackends().
905 * Note: use of RowExclusiveLock here is reasonable because we envision
906 * our session as being a concurrent writer of the database. If we had a
907 * way of declaring a session as being guaranteed-read-only, we could use
908 * AccessShareLock for such sessions and thereby not conflict against
912 LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
916 * Now we can mark our PGPROC entry with the database ID.
918 * We assume this is an atomic store so no lock is needed; though actually
919 * things would work fine even if it weren't atomic. Anyone searching the
920 * ProcArray for this database's ID should hold the database lock, so they
921 * would not be executing concurrently with this store. A process looking
922 * for another database's ID could in theory see a chance match if it read
923 * a partially-updated databaseId value; but as long as all such searches
924 * wait and retry, as in CountOtherDBBackends(), they will certainly see
925 * the correct value on their next try.
927 MyProc->databaseId = MyDatabaseId;
930 * We established a catalog snapshot while reading pg_authid and/or
931 * pg_database; but until we have set up MyDatabaseId, we won't react to
932 * incoming sinval messages for unshared catalogs, so we won't realize it
933 * if the snapshot has been invalidated. Assume it's no good anymore.
935 InvalidateCatalogSnapshot();
938 * Recheck pg_database to make sure the target database hasn't gone away.
939 * If there was a concurrent DROP DATABASE, this ensures we will die
940 * cleanly without creating a mess.
946 tuple = GetDatabaseTuple(dbname);
947 if (!HeapTupleIsValid(tuple) ||
948 MyDatabaseId != HeapTupleGetOid(tuple) ||
949 MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
951 (errcode(ERRCODE_UNDEFINED_DATABASE),
952 errmsg("database \"%s\" does not exist", dbname),
953 errdetail("It seems to have just been dropped or renamed.")));
957 * Now we should be able to access the database directory safely. Verify
958 * it's there and looks reasonable.
960 fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
964 if (access(fullpath, F_OK) == -1)
968 (errcode(ERRCODE_UNDEFINED_DATABASE),
969 errmsg("database \"%s\" does not exist",
971 errdetail("The database subdirectory \"%s\" is missing.",
975 (errcode_for_file_access(),
976 errmsg("could not access directory \"%s\": %m",
980 ValidatePgVersion(fullpath);
983 SetDatabasePath(fullpath);
986 * It's now possible to do real access to the system catalogs.
988 * Load relcache entries for the system catalogs. This must create at
989 * least the minimum set of "nailed-in" cache entries.
991 RelationCacheInitializePhase3();
993 /* set up ACL framework (so CheckMyDatabase can check permissions) */
997 * Re-read the pg_database row for our database, check permissions and set
998 * up database-specific GUC settings. We can't do this until all the
999 * database-access infrastructure is up. (Also, it wants to know if the
1000 * user is a superuser, so the above stuff has to happen first.)
1003 CheckMyDatabase(dbname, am_superuser);
1006 * Now process any command-line switches and any additional GUC variable
1007 * settings passed in the startup packet. We couldn't do this before
1008 * because we didn't know if client is a superuser.
1010 if (MyProcPort != NULL)
1011 process_startup_options(MyProcPort, am_superuser);
1013 /* Process pg_db_role_setting options */
1014 process_settings(MyDatabaseId, GetSessionUserId());
1016 /* Apply PostAuthDelay as soon as we've read all options */
1017 if (PostAuthDelay > 0)
1018 pg_usleep(PostAuthDelay * 1000000L);
1021 * Initialize various default states that can't be set up until we've
1022 * selected the active user and gotten the right GUC settings.
1025 /* set default namespace search path */
1026 InitializeSearchPath();
1028 /* initialize client encoding */
1029 InitializeClientEncoding();
1031 /* Initialize this backend's session state. */
1032 InitializeSession();
1034 /* report this backend in the PgBackendStatus array */
1038 /* close the transaction we started above */
1040 CommitTransactionCommand();
1044 * Process any command-line switches and any additional GUC variable
1045 * settings passed in the startup packet.
1048 process_startup_options(Port *port, bool am_superuser)
1053 gucctx = am_superuser ? PGC_SU_BACKEND : PGC_BACKEND;
1056 * First process any command-line switches that were included in the
1057 * startup packet, if we are in a regular backend.
1059 if (port->cmdline_options != NULL)
1062 * The maximum possible number of commandline arguments that could
1063 * come from port->cmdline_options is (strlen + 1) / 2; see
1070 maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
1072 av = (char **) palloc(maxac * sizeof(char *));
1075 av[ac++] = "postgres";
1077 pg_split_opts(av, &ac, port->cmdline_options);
1083 (void) process_postgres_switches(ac, av, gucctx, NULL);
1087 * Process any additional GUC variable settings passed in startup packet.
1088 * These are handled exactly like command-line variables.
1090 gucopts = list_head(port->guc_options);
1096 name = lfirst(gucopts);
1097 gucopts = lnext(gucopts);
1099 value = lfirst(gucopts);
1100 gucopts = lnext(gucopts);
1102 SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
1107 * Load GUC settings from pg_db_role_setting.
1109 * We try specific settings for the database/role combination, as well as
1110 * general for this database and for this user.
1113 process_settings(Oid databaseid, Oid roleid)
1115 Relation relsetting;
1118 if (!IsUnderPostmaster)
1121 relsetting = heap_open(DbRoleSettingRelationId, AccessShareLock);
1123 /* read all the settings under the same snapshot for efficiency */
1124 snapshot = RegisterSnapshot(GetCatalogSnapshot(DbRoleSettingRelationId));
1126 /* Later settings are ignored if set earlier. */
1127 ApplySetting(snapshot, databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
1128 ApplySetting(snapshot, InvalidOid, roleid, relsetting, PGC_S_USER);
1129 ApplySetting(snapshot, databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
1130 ApplySetting(snapshot, InvalidOid, InvalidOid, relsetting, PGC_S_GLOBAL);
1132 UnregisterSnapshot(snapshot);
1133 heap_close(relsetting, AccessShareLock);
1137 * Backend-shutdown callback. Do cleanup that we want to be sure happens
1138 * before all the supporting modules begin to nail their doors shut via
1139 * their own callbacks.
1141 * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
1142 * via separate callbacks that execute before this one. We don't combine the
1143 * callbacks because we still want this one to happen if the user-level
1147 ShutdownPostgres(int code, Datum arg)
1149 /* Make sure we've killed any active transaction */
1150 AbortOutOfAnyTransaction();
1153 * User locks are not released by transaction end, so be sure to release
1156 LockReleaseAll(USER_LOCKMETHOD, true);
1161 * STATEMENT_TIMEOUT handler: trigger a query-cancel interrupt.
1164 StatementTimeoutHandler(void)
1169 * During authentication the timeout is used to deal with
1170 * authentication_timeout - we want to quit in response to such timeouts.
1172 if (ClientAuthInProgress)
1176 /* try to signal whole process group */
1177 kill(-MyProcPid, sig);
1179 kill(MyProcPid, sig);
1183 * LOCK_TIMEOUT handler: trigger a query-cancel interrupt.
1186 LockTimeoutHandler(void)
1189 /* try to signal whole process group */
1190 kill(-MyProcPid, SIGINT);
1192 kill(MyProcPid, SIGINT);
1196 IdleInTransactionSessionTimeoutHandler(void)
1198 IdleInTransactionSessionTimeoutPending = true;
1199 InterruptPending = true;
1204 * Returns true if at least one role is defined in this database cluster.
1207 ThereIsAtLeastOneRole(void)
1209 Relation pg_authid_rel;
1213 pg_authid_rel = heap_open(AuthIdRelationId, AccessShareLock);
1215 scan = heap_beginscan_catalog(pg_authid_rel, 0, NULL);
1216 result = (heap_getnext(scan, ForwardScanDirection) != NULL);
1219 heap_close(pg_authid_rel, AccessShareLock);