1 /*-------------------------------------------------------------------------
4 * postgres initialization utilities
6 * Portions Copyright (c) 1996-2011, 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/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"
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"
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);
73 /*** InitPostgres support ***/
77 * GetDatabaseTuple -- fetch the pg_database row for a database
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.
88 GetDatabaseTuple(const char *dbname)
99 Anum_pg_database_datname,
100 BTEqualStrategyNumber, F_NAMEEQ,
101 CStringGetDatum(dbname));
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).
108 relation = heap_open(DatabaseRelationId, AccessShareLock);
109 scan = systable_beginscan(relation, DatabaseNameIndexId,
110 criticalSharedRelcachesBuilt,
114 tuple = systable_getnext(scan);
116 /* Must copy tuple before releasing buffer */
117 if (HeapTupleIsValid(tuple))
118 tuple = heap_copytuple(tuple);
121 systable_endscan(scan);
122 heap_close(relation, AccessShareLock);
128 * GetDatabaseTupleByOid -- as above, but search by database OID
131 GetDatabaseTupleByOid(Oid dboid)
142 ObjectIdAttributeNumber,
143 BTEqualStrategyNumber, F_OIDEQ,
144 ObjectIdGetDatum(dboid));
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).
151 relation = heap_open(DatabaseRelationId, AccessShareLock);
152 scan = systable_beginscan(relation, DatabaseOidIndexId,
153 criticalSharedRelcachesBuilt,
157 tuple = systable_getnext(scan);
159 /* Must copy tuple before releasing buffer */
160 if (HeapTupleIsValid(tuple))
161 tuple = heap_copytuple(tuple);
164 systable_endscan(scan);
165 heap_close(relation, AccessShareLock);
172 * PerformAuthentication -- authenticate a remote client
174 * returns: nothing. Will not return at all if there's any failure.
177 PerformAuthentication(Port *port)
179 /* This should be set already, but let's make sure */
180 ClientAuthInProgress = true; /* limit visibility of log messages */
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.
188 * FIXME: [fork/exec] Ugh. Is there a way around this overhead?
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.
198 (errmsg("could not load pg_hba.conf")));
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.
208 if (!enable_sig_alarm(AuthenticationTimeout * 1000, true))
209 elog(FATAL, "could not set timer for authorization timeout");
212 * Now perform authentication exchange.
214 ClientAuthentication(port); /* might not return, if failure */
217 * Done with authentication. Disable the timeout, and log if needed.
219 if (!disable_sig_alarm(true))
220 elog(FATAL, "could not disable timer for authorization timeout");
226 (errmsg("replication connection authorized: user=%s",
230 (errmsg("connection authorized: user=%s database=%s",
231 port->user_name, port->database_name)));
234 set_ps_display("startup", false);
236 ClientAuthInProgress = false; /* client_min_messages is active now */
241 * CheckMyDatabase -- fetch information from the pg_database entry for our DB
244 CheckMyDatabase(const char *name, bool am_superuser)
247 Form_pg_database dbform;
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);
257 /* This recheck is strictly paranoia */
258 if (strcmp(name, NameStr(dbform->datname)) != 0)
260 (errcode(ERRCODE_UNDEFINED_DATABASE),
261 errmsg("database \"%s\" has disappeared from pg_database",
263 errdetail("Database OID %u now seems to belong to \"%s\".",
264 MyDatabaseId, NameStr(dbform->datname))));
267 * Check permissions to connect to the database.
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;".
273 * We do not enforce them for autovacuum worker processes either.
275 if (IsUnderPostmaster && !IsAutoVacuumWorkerProcess())
278 * Check that the database is currently allowing connections.
280 if (!dbform->datallowconn)
282 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
283 errmsg("database \"%s\" is not currently accepting connections",
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.)
292 pg_database_aclcheck(MyDatabaseId, GetUserId(),
293 ACL_CONNECT) != ACLCHECK_OK)
295 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
296 errmsg("permission denied for database \"%s\"", name),
297 errdetail("User does not have CONNECT privilege.")));
300 * Check connection limit for this database.
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.
309 if (dbform->datconnlimit >= 0 &&
311 CountDBBackends(MyDatabaseId) > dbform->datconnlimit)
313 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
314 errmsg("too many connections for database \"%s\"",
319 * OK, we're golden. Next to-do item is to save the encoding info out of
320 * the pg_database tuple.
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);
330 /* assign locale variables */
331 collate = NameStr(dbform->datcollate);
332 ctype = NameStr(dbform->datctype);
334 if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
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.")));
341 if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
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.")));
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);
352 /* Use the right encoding in translated messages */
354 pg_bind_textdomain_codeset(textdomain(NULL));
357 ReleaseSysCache(tup);
362 /* --------------------------------
365 * This routine initializes stuff needed for ipc, locking, etc.
366 * it should be called something more informative.
367 * --------------------------------
370 InitCommunication(void)
373 * initialize shared memory and semaphores appropriately.
375 if (!IsUnderPostmaster) /* postmaster already did this */
378 * We're running a postgres bootstrap process or a standalone backend.
379 * Create private "shmem" and semaphores.
381 CreateSharedMemoryAndSemaphores(true, 0);
387 * pg_split_opts -- split a string of options and append it to an argv array
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.
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.
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...
401 pg_split_opts(char **argv, int *argcp, char *optstr)
405 while (isspace((unsigned char) *optstr))
409 argv[(*argcp)++] = optstr;
410 while (*optstr && !isspace((unsigned char) *optstr))
419 * Early initialization of a backend (either standalone or under postmaster).
420 * This happens even before InitPostgres.
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.
430 * Attach to shared memory and semaphores, and initialize our
431 * input/output/debugging file descriptors.
436 /* Do local initialization of file, storage and buffer managers */
439 InitBufferPoolAccess();
443 /* --------------------------------
445 * Initialize POSTGRES.
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.
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.
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.
461 * Be very careful with the order of calls in the InitPostgres function.
462 * --------------------------------
465 InitPostgres(const char *in_dbname, Oid dboid, const char *username,
468 bool bootstrap = IsBootstrapProcessingMode();
471 char dbname[NAMEDATALEN];
473 elog(DEBUG3, "InitPostgres");
476 * Add my PGPROC struct to the ProcArray.
478 * Once I have done this, I am visible to other backends!
483 * Initialize my entry in the shared-invalidation manager's array of
486 * Sets up MyBackendId, a unique backend identifier.
488 MyBackendId = InvalidBackendId;
490 SharedInvalBackendInit(false);
492 if (MyBackendId > MaxBackends || MyBackendId <= 0)
493 elog(FATAL, "bad backend ID: %d", MyBackendId);
495 /* Now that we have a BackendId, we can participate in ProcSignal */
496 ProcSignalInit(MyBackendId);
499 * bufmgr needs another initialization call too
501 InitBufferPoolBackend();
504 * Initialize local process's access to XLOG.
506 if (IsUnderPostmaster)
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
514 (void) RecoveryInProgress();
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
524 on_shmem_exit(ShutdownXLOG, 0);
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.
533 RelationCacheInitialize();
537 /* Initialize portal manager */
538 EnablePortalManager();
540 /* Initialize stats collection --- must happen before first xact */
545 * Load relcache entries for the shared system catalogs. This must create
546 * at least entries for pg_database and catalogs used for authentication.
548 RelationCacheInitializePhase2();
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.
559 on_shmem_exit(ShutdownPostgres, 0);
561 /* The autovacuum launcher is done here */
562 if (IsAutoVacuumLauncherProcess())
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
575 /* statement_timestamp must be set for timeouts to work correctly */
576 SetCurrentStatementStartTimestamp();
577 StartTransactionCommand();
578 (void) GetTransactionSnapshot();
582 * Perform client authentication if necessary, then figure out our
583 * postgres user ID, and see if we are a superuser.
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.
588 if (bootstrap || IsAutoVacuumWorkerProcess())
590 InitializeSessionUserIdStandalone();
593 else if (!IsUnderPostmaster)
595 InitializeSessionUserIdStandalone();
597 if (!ThereIsAtLeastOneRole())
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;.",
606 /* normal multiuser case */
607 Assert(MyProcPort != NULL);
608 PerformAuthentication(MyProcPort);
609 InitializeSessionUserId(username);
610 am_superuser = superuser();
614 * If we're trying to shut down, only superusers can connect, and new
615 * replication connections are not allowed.
617 if ((!am_superuser || am_walsender) &&
618 MyProcPort != NULL &&
619 MyProcPort->canAcceptConnections == CAC_WAITBACKUP)
623 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
624 errmsg("new replication connections are not allowed during database shutdown")));
627 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
628 errmsg("must be superuser to connect during database shutdown")));
632 * Binary upgrades only allowed super-user connections
634 if (IsBinaryUpgrade && !am_superuser)
637 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
638 errmsg("must be superuser to connect in binary upgrade mode")));
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
647 if ((!am_superuser || am_walsender) &&
648 ReservedBackends > 0 &&
649 !HaveNFreeProcs(ReservedBackends))
651 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
652 errmsg("remaining connection slots are reserved for non-replication superuser connections")));
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.
663 /* must have authenticated as a replication role */
664 if (!is_authenticated_user_replication_role())
666 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
667 errmsg("must be replication role to start walsender")));
669 /* process any options passed in the startup packet */
670 if (MyProcPort != NULL)
671 process_startup_options(MyProcPort, am_superuser);
673 /* Apply PostAuthDelay as soon as we've read all options */
674 if (PostAuthDelay > 0)
675 pg_usleep(PostAuthDelay * 1000000L);
677 /* initialize client encoding */
678 InitializeClientEncoding();
680 /* report this backend in the PgBackendStatus array */
683 /* close the transaction we started above */
684 CommitTransactionCommand();
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.
693 * We take a shortcut in the bootstrap case, otherwise we have to look up
694 * the db's entry in pg_database.
698 MyDatabaseId = TemplateDbOid;
699 MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
701 else if (in_dbname != NULL)
704 Form_pg_database dbform;
706 tuple = GetDatabaseTuple(in_dbname);
707 if (!HeapTupleIsValid(tuple))
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));
719 /* caller specified database by OID */
721 Form_pg_database dbform;
723 tuple = GetDatabaseTupleByOid(dboid);
724 if (!HeapTupleIsValid(tuple))
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 */
735 strcpy(out_dbname, dbname);
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;
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
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.
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
760 LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
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.
772 tuple = GetDatabaseTuple(dbname);
773 if (!HeapTupleIsValid(tuple) ||
774 MyDatabaseId != HeapTupleGetOid(tuple) ||
775 MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
777 (errcode(ERRCODE_UNDEFINED_DATABASE),
778 errmsg("database \"%s\" does not exist", dbname),
779 errdetail("It seems to have just been dropped or renamed.")));
783 * Now we should be able to access the database directory safely. Verify
784 * it's there and looks reasonable.
786 fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
790 if (access(fullpath, F_OK) == -1)
794 (errcode(ERRCODE_UNDEFINED_DATABASE),
795 errmsg("database \"%s\" does not exist",
797 errdetail("The database subdirectory \"%s\" is missing.",
801 (errcode_for_file_access(),
802 errmsg("could not access directory \"%s\": %m",
806 ValidatePgVersion(fullpath);
809 SetDatabasePath(fullpath);
812 * It's now possible to do real access to the system catalogs.
814 * Load relcache entries for the system catalogs. This must create at
815 * least the minimum set of "nailed-in" cache entries.
817 RelationCacheInitializePhase3();
819 /* set up ACL framework (so CheckMyDatabase can check permissions) */
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.)
829 CheckMyDatabase(dbname, am_superuser);
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.
836 if (MyProcPort != NULL)
837 process_startup_options(MyProcPort, am_superuser);
839 /* Process pg_db_role_setting options */
840 process_settings(MyDatabaseId, GetSessionUserId());
842 /* Apply PostAuthDelay as soon as we've read all options */
843 if (PostAuthDelay > 0)
844 pg_usleep(PostAuthDelay * 1000000L);
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.
851 /* set default namespace search path */
852 InitializeSearchPath();
854 /* initialize client encoding */
855 InitializeClientEncoding();
857 /* report this backend in the PgBackendStatus array */
861 /* close the transaction we started above */
863 CommitTransactionCommand();
867 * Process any command-line switches and any additional GUC variable
868 * settings passed in the startup packet.
871 process_startup_options(Port *port, bool am_superuser)
876 gucctx = am_superuser ? PGC_SUSET : PGC_BACKEND;
879 * First process any command-line switches that were included in the
880 * startup packet, if we are in a regular backend.
882 if (port->cmdline_options != NULL)
885 * The maximum possible number of commandline arguments that could
886 * come from port->cmdline_options is (strlen + 1) / 2; see
893 maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
895 av = (char **) palloc(maxac * sizeof(char *));
898 av[ac++] = "postgres";
900 /* Note this mangles port->cmdline_options */
901 pg_split_opts(av, &ac, port->cmdline_options);
907 (void) process_postgres_switches(ac, av, gucctx);
911 * Process any additional GUC variable settings passed in startup packet.
912 * These are handled exactly like command-line variables.
914 gucopts = list_head(port->guc_options);
920 name = lfirst(gucopts);
921 gucopts = lnext(gucopts);
923 value = lfirst(gucopts);
924 gucopts = lnext(gucopts);
926 SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
931 * Load GUC settings from pg_db_role_setting.
933 * We try specific settings for the database/role combination, as well as
934 * general for this database and for this user.
937 process_settings(Oid databaseid, Oid roleid)
941 if (!IsUnderPostmaster)
944 relsetting = heap_open(DbRoleSettingRelationId, AccessShareLock);
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);
951 heap_close(relsetting, AccessShareLock);
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.
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
965 ShutdownPostgres(int code, Datum arg)
967 /* Make sure we've killed any active transaction */
968 AbortOutOfAnyTransaction();
971 * User locks are not released by transaction end, so be sure to release
974 LockReleaseAll(USER_LOCKMETHOD, true);
979 * Returns true if at least one role is defined in this database cluster.
982 ThereIsAtLeastOneRole(void)
984 Relation pg_authid_rel;
988 pg_authid_rel = heap_open(AuthIdRelationId, AccessShareLock);
990 scan = heap_beginscan(pg_authid_rel, SnapshotNow, 0, NULL);
991 result = (heap_getnext(scan, ForwardScanDirection) != NULL);
994 heap_close(pg_authid_rel, AccessShareLock);