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 "replication/walsender.h"
40 #include "storage/bufmgr.h"
41 #include "storage/fd.h"
42 #include "storage/ipc.h"
43 #include "storage/lmgr.h"
44 #include "storage/proc.h"
45 #include "storage/procarray.h"
46 #include "storage/procsignal.h"
47 #include "storage/sinvaladt.h"
48 #include "storage/smgr.h"
49 #include "tcop/tcopprot.h"
50 #include "utils/acl.h"
51 #include "utils/fmgroids.h"
52 #include "utils/guc.h"
53 #include "utils/pg_locale.h"
54 #include "utils/portal.h"
55 #include "utils/ps_status.h"
56 #include "utils/snapmgr.h"
57 #include "utils/syscache.h"
58 #include "utils/tqual.h"
61 static HeapTuple GetDatabaseTuple(const char *dbname);
62 static HeapTuple GetDatabaseTupleByOid(Oid dboid);
63 static void PerformAuthentication(Port *port);
64 static void CheckMyDatabase(const char *name, bool am_superuser);
65 static void InitCommunication(void);
66 static void ShutdownPostgres(int code, Datum arg);
67 static bool ThereIsAtLeastOneRole(void);
68 static void process_startup_options(Port *port, bool am_superuser);
69 static void process_settings(Oid databaseid, Oid roleid);
72 /*** InitPostgres support ***/
76 * GetDatabaseTuple -- fetch the pg_database row for a database
78 * This is used during backend startup when we don't yet have any access to
79 * system catalogs in general. In the worst case, we can seqscan pg_database
80 * using nothing but the hard-wired descriptor that relcache.c creates for
81 * pg_database. In more typical cases, relcache.c was able to load
82 * descriptors for both pg_database and its indexes from the shared relcache
83 * cache file, and so we can do an indexscan. criticalSharedRelcachesBuilt
84 * tells whether we got the cached descriptors.
87 GetDatabaseTuple(const char *dbname)
98 Anum_pg_database_datname,
99 BTEqualStrategyNumber, F_NAMEEQ,
100 CStringGetDatum(dbname));
103 * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
104 * built the critical shared relcache entries (i.e., we're starting up
105 * without a shared relcache cache file).
107 relation = heap_open(DatabaseRelationId, AccessShareLock);
108 scan = systable_beginscan(relation, DatabaseNameIndexId,
109 criticalSharedRelcachesBuilt,
113 tuple = systable_getnext(scan);
115 /* Must copy tuple before releasing buffer */
116 if (HeapTupleIsValid(tuple))
117 tuple = heap_copytuple(tuple);
120 systable_endscan(scan);
121 heap_close(relation, AccessShareLock);
127 * GetDatabaseTupleByOid -- as above, but search by database OID
130 GetDatabaseTupleByOid(Oid dboid)
141 ObjectIdAttributeNumber,
142 BTEqualStrategyNumber, F_OIDEQ,
143 ObjectIdGetDatum(dboid));
146 * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
147 * built the critical shared relcache entries (i.e., we're starting up
148 * without a shared relcache cache file).
150 relation = heap_open(DatabaseRelationId, AccessShareLock);
151 scan = systable_beginscan(relation, DatabaseOidIndexId,
152 criticalSharedRelcachesBuilt,
156 tuple = systable_getnext(scan);
158 /* Must copy tuple before releasing buffer */
159 if (HeapTupleIsValid(tuple))
160 tuple = heap_copytuple(tuple);
163 systable_endscan(scan);
164 heap_close(relation, AccessShareLock);
171 * PerformAuthentication -- authenticate a remote client
173 * returns: nothing. Will not return at all if there's any failure.
176 PerformAuthentication(Port *port)
178 /* This should be set already, but let's make sure */
179 ClientAuthInProgress = true; /* limit visibility of log messages */
182 * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
183 * etcetera from the postmaster, and have to load them ourselves. Note we
184 * are loading them into the startup transaction's memory context, not
185 * PostmasterContext, but that shouldn't matter.
187 * FIXME: [fork/exec] Ugh. Is there a way around this overhead?
193 * It makes no sense to continue if we fail to load the HBA file,
194 * since there is no way to connect to the database in this case.
197 (errmsg("could not load pg_hba.conf")));
203 * Set up a timeout in case a buggy or malicious client fails to respond
204 * during authentication. Since we're inside a transaction and might do
205 * database access, we have to use the statement_timeout infrastructure.
207 if (!enable_sig_alarm(AuthenticationTimeout * 1000, true))
208 elog(FATAL, "could not set timer for authorization timeout");
211 * Now perform authentication exchange.
213 ClientAuthentication(port); /* might not return, if failure */
216 * Done with authentication. Disable the timeout, and log if needed.
218 if (!disable_sig_alarm(true))
219 elog(FATAL, "could not disable timer for authorization timeout");
225 (errmsg("replication connection authorized: user=%s",
229 (errmsg("connection authorized: user=%s database=%s",
230 port->user_name, port->database_name)));
233 set_ps_display("startup", false);
235 ClientAuthInProgress = false; /* client_min_messages is active now */
240 * CheckMyDatabase -- fetch information from the pg_database entry for our DB
243 CheckMyDatabase(const char *name, bool am_superuser)
246 Form_pg_database dbform;
250 /* Fetch our pg_database row normally, via syscache */
251 tup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
252 if (!HeapTupleIsValid(tup))
253 elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
254 dbform = (Form_pg_database) GETSTRUCT(tup);
256 /* This recheck is strictly paranoia */
257 if (strcmp(name, NameStr(dbform->datname)) != 0)
259 (errcode(ERRCODE_UNDEFINED_DATABASE),
260 errmsg("database \"%s\" has disappeared from pg_database",
262 errdetail("Database OID %u now seems to belong to \"%s\".",
263 MyDatabaseId, NameStr(dbform->datname))));
266 * Check permissions to connect to the database.
268 * These checks are not enforced when in standalone mode, so that there is
269 * a way to recover from disabling all access to all databases, for
270 * example "UPDATE pg_database SET datallowconn = false;".
272 * We do not enforce them for autovacuum worker processes either.
274 if (IsUnderPostmaster && !IsAutoVacuumWorkerProcess())
277 * Check that the database is currently allowing connections.
279 if (!dbform->datallowconn)
281 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
282 errmsg("database \"%s\" is not currently accepting connections",
286 * Check privilege to connect to the database. (The am_superuser test
287 * is redundant, but since we have the flag, might as well check it
288 * and save a few cycles.)
291 pg_database_aclcheck(MyDatabaseId, GetUserId(),
292 ACL_CONNECT) != ACLCHECK_OK)
294 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
295 errmsg("permission denied for database \"%s\"", name),
296 errdetail("User does not have CONNECT privilege.")));
299 * Check connection limit for this database.
301 * There is a race condition here --- we create our PGPROC before
302 * checking for other PGPROCs. If two backends did this at about the
303 * same time, they might both think they were over the limit, while
304 * ideally one should succeed and one fail. Getting that to work
305 * exactly seems more trouble than it is worth, however; instead we
306 * just document that the connection limit is approximate.
308 if (dbform->datconnlimit >= 0 &&
310 CountDBBackends(MyDatabaseId) > dbform->datconnlimit)
312 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
313 errmsg("too many connections for database \"%s\"",
318 * OK, we're golden. Next to-do item is to save the encoding info out of
319 * the pg_database tuple.
321 SetDatabaseEncoding(dbform->encoding);
322 /* Record it as a GUC internal option, too */
323 SetConfigOption("server_encoding", GetDatabaseEncodingName(),
324 PGC_INTERNAL, PGC_S_OVERRIDE);
325 /* If we have no other source of client_encoding, use server encoding */
326 SetConfigOption("client_encoding", GetDatabaseEncodingName(),
327 PGC_BACKEND, PGC_S_DYNAMIC_DEFAULT);
329 /* assign locale variables */
330 collate = NameStr(dbform->datcollate);
331 ctype = NameStr(dbform->datctype);
333 if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
335 (errmsg("database locale is incompatible with operating system"),
336 errdetail("The database was initialized with LC_COLLATE \"%s\", "
337 " which is not recognized by setlocale().", collate),
338 errhint("Recreate the database with another locale or install the missing locale.")));
340 if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
342 (errmsg("database locale is incompatible with operating system"),
343 errdetail("The database was initialized with LC_CTYPE \"%s\", "
344 " which is not recognized by setlocale().", ctype),
345 errhint("Recreate the database with another locale or install the missing locale.")));
347 /* Make the locale settings visible as GUC variables, too */
348 SetConfigOption("lc_collate", collate, PGC_INTERNAL, PGC_S_OVERRIDE);
349 SetConfigOption("lc_ctype", ctype, PGC_INTERNAL, PGC_S_OVERRIDE);
351 /* Use the right encoding in translated messages */
353 pg_bind_textdomain_codeset(textdomain(NULL));
356 ReleaseSysCache(tup);
361 /* --------------------------------
364 * This routine initializes stuff needed for ipc, locking, etc.
365 * it should be called something more informative.
366 * --------------------------------
369 InitCommunication(void)
372 * initialize shared memory and semaphores appropriately.
374 if (!IsUnderPostmaster) /* postmaster already did this */
377 * We're running a postgres bootstrap process or a standalone backend.
378 * Create private "shmem" and semaphores.
380 CreateSharedMemoryAndSemaphores(true, 0);
386 * pg_split_opts -- split a string of options and append it to an argv array
388 * NB: the input string is destructively modified! Also, caller is responsible
389 * for ensuring the argv array is large enough. The maximum possible number
390 * of arguments added by this routine is (strlen(optstr) + 1) / 2.
392 * Since no current POSTGRES arguments require any quoting characters,
393 * we can use the simple-minded tactic of assuming each set of space-
394 * delimited characters is a separate argv element.
396 * If you don't like that, well, we *used* to pass the whole option string
397 * as ONE argument to execl(), which was even less intelligent...
400 pg_split_opts(char **argv, int *argcp, char *optstr)
404 while (isspace((unsigned char) *optstr))
408 argv[(*argcp)++] = optstr;
409 while (*optstr && !isspace((unsigned char) *optstr))
418 * Early initialization of a backend (either standalone or under postmaster).
419 * This happens even before InitPostgres.
421 * This is separate from InitPostgres because it is also called by auxiliary
422 * processes, such as the background writer process, which may not call
423 * InitPostgres at all.
429 * Attach to shared memory and semaphores, and initialize our
430 * input/output/debugging file descriptors.
435 /* Do local initialization of file, storage and buffer managers */
438 InitBufferPoolAccess();
442 /* --------------------------------
444 * Initialize POSTGRES.
446 * The database can be specified by name, using the in_dbname parameter, or by
447 * OID, using the dboid parameter. In the latter case, the actual database
448 * name can be returned to the caller in out_dbname. If out_dbname isn't
449 * NULL, it must point to a buffer of size NAMEDATALEN.
451 * In bootstrap mode no parameters are used. The autovacuum launcher process
452 * doesn't use any parameters either, because it only goes far enough to be
453 * able to read pg_database; it doesn't connect to any particular database.
454 * In walsender mode only username is used.
456 * As of PostgreSQL 8.2, we expect InitProcess() was already called, so we
457 * already have a PGPROC struct ... but it's not completely filled in yet.
460 * Be very careful with the order of calls in the InitPostgres function.
461 * --------------------------------
464 InitPostgres(const char *in_dbname, Oid dboid, const char *username,
467 bool bootstrap = IsBootstrapProcessingMode();
470 char dbname[NAMEDATALEN];
472 elog(DEBUG3, "InitPostgres");
475 * Add my PGPROC struct to the ProcArray.
477 * Once I have done this, I am visible to other backends!
482 * Initialize my entry in the shared-invalidation manager's array of
485 * Sets up MyBackendId, a unique backend identifier.
487 MyBackendId = InvalidBackendId;
489 SharedInvalBackendInit(false);
491 if (MyBackendId > MaxBackends || MyBackendId <= 0)
492 elog(FATAL, "bad backend ID: %d", MyBackendId);
494 /* Now that we have a BackendId, we can participate in ProcSignal */
495 ProcSignalInit(MyBackendId);
498 * bufmgr needs another initialization call too
500 InitBufferPoolBackend();
503 * Initialize local process's access to XLOG.
505 if (IsUnderPostmaster)
508 * The postmaster already started the XLOG machinery, but we need to
509 * call InitXLOGAccess(), if the system isn't in hot-standby mode.
510 * This is handled by calling RecoveryInProgress and ignoring the
513 (void) RecoveryInProgress();
518 * We are either a bootstrap process or a standalone backend. Either
519 * way, start up the XLOG machinery, and register to have it closed
523 on_shmem_exit(ShutdownXLOG, 0);
527 * Initialize the relation cache and the system catalog caches. Note that
528 * no catalog access happens here; we only set up the hashtable structure.
529 * We must do this before starting a transaction because transaction abort
530 * would try to touch these hashtables.
532 RelationCacheInitialize();
536 /* Initialize portal manager */
537 EnablePortalManager();
539 /* Initialize stats collection --- must happen before first xact */
544 * Load relcache entries for the shared system catalogs. This must create
545 * at least entries for pg_database and catalogs used for authentication.
547 RelationCacheInitializePhase2();
550 * Set up process-exit callback to do pre-shutdown cleanup. This has to
551 * be after we've initialized all the low-level modules like the buffer
552 * manager, because during shutdown this has to run before the low-level
553 * modules start to close down. On the other hand, we want it in place
554 * before we begin our first transaction --- if we fail during the
555 * initialization transaction, as is entirely possible, we need the
556 * AbortTransaction call to clean up.
558 on_shmem_exit(ShutdownPostgres, 0);
560 /* The autovacuum launcher is done here */
561 if (IsAutoVacuumLauncherProcess())
565 * Start a new transaction here before first access to db, and get a
566 * snapshot. We don't have a use for the snapshot itself, but we're
567 * interested in the secondary effect that it sets RecentGlobalXmin. (This
568 * is critical for anything that reads heap pages, because HOT may decide
569 * to prune them even if the process doesn't attempt to modify any
574 /* statement_timestamp must be set for timeouts to work correctly */
575 SetCurrentStatementStartTimestamp();
576 StartTransactionCommand();
577 (void) GetTransactionSnapshot();
581 * Perform client authentication if necessary, then figure out our
582 * postgres user ID, and see if we are a superuser.
584 * In standalone mode and in autovacuum worker processes, we use a fixed
585 * ID, otherwise we figure it out from the authenticated user name.
587 if (bootstrap || IsAutoVacuumWorkerProcess())
589 InitializeSessionUserIdStandalone();
592 else if (!IsUnderPostmaster)
594 InitializeSessionUserIdStandalone();
596 if (!ThereIsAtLeastOneRole())
598 (errcode(ERRCODE_UNDEFINED_OBJECT),
599 errmsg("no roles are defined in this database system"),
600 errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
605 /* normal multiuser case */
606 Assert(MyProcPort != NULL);
607 PerformAuthentication(MyProcPort);
608 InitializeSessionUserId(username);
609 am_superuser = superuser();
613 * If we're trying to shut down, only superusers can connect, and new
614 * replication connections are not allowed.
616 if ((!am_superuser || am_walsender) &&
617 MyProcPort != NULL &&
618 MyProcPort->canAcceptConnections == CAC_WAITBACKUP)
622 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
623 errmsg("new replication connections are not allowed during database shutdown")));
626 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
627 errmsg("must be superuser to connect during database shutdown")));
631 * Binary upgrades only allowed super-user connections
633 if (IsBinaryUpgrade && !am_superuser)
636 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
637 errmsg("must be superuser to connect in binary upgrade mode")));
641 * The last few connections slots are reserved for superusers. Although
642 * replication connections currently require superuser privileges, we
643 * don't allow them to consume the reserved slots, which are intended for
646 if ((!am_superuser || am_walsender) &&
647 ReservedBackends > 0 &&
648 !HaveNFreeProcs(ReservedBackends))
650 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
651 errmsg("remaining connection slots are reserved for non-replication superuser connections")));
654 * If walsender, we don't want to connect to any particular database. Just
655 * finish the backend startup by processing any options from the startup
656 * packet, and we're done.
662 /* must have authenticated as a replication role */
663 if (!is_authenticated_user_replication_role())
665 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
666 errmsg("must be replication role to start walsender")));
668 /* process any options passed in the startup packet */
669 if (MyProcPort != NULL)
670 process_startup_options(MyProcPort, am_superuser);
672 /* Apply PostAuthDelay as soon as we've read all options */
673 if (PostAuthDelay > 0)
674 pg_usleep(PostAuthDelay * 1000000L);
676 /* initialize client encoding */
677 InitializeClientEncoding();
679 /* report this backend in the PgBackendStatus array */
682 /* close the transaction we started above */
683 CommitTransactionCommand();
689 * Set up the global variables holding database id and default tablespace.
690 * But note we won't actually try to touch the database just yet.
692 * We take a shortcut in the bootstrap case, otherwise we have to look up
693 * the db's entry in pg_database.
697 MyDatabaseId = TemplateDbOid;
698 MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
700 else if (in_dbname != NULL)
703 Form_pg_database dbform;
705 tuple = GetDatabaseTuple(in_dbname);
706 if (!HeapTupleIsValid(tuple))
708 (errcode(ERRCODE_UNDEFINED_DATABASE),
709 errmsg("database \"%s\" does not exist", in_dbname)));
710 dbform = (Form_pg_database) GETSTRUCT(tuple);
711 MyDatabaseId = HeapTupleGetOid(tuple);
712 MyDatabaseTableSpace = dbform->dattablespace;
713 /* take database name from the caller, just for paranoia */
714 strlcpy(dbname, in_dbname, sizeof(dbname));
718 /* caller specified database by OID */
720 Form_pg_database dbform;
722 tuple = GetDatabaseTupleByOid(dboid);
723 if (!HeapTupleIsValid(tuple))
725 (errcode(ERRCODE_UNDEFINED_DATABASE),
726 errmsg("database %u does not exist", dboid)));
727 dbform = (Form_pg_database) GETSTRUCT(tuple);
728 MyDatabaseId = HeapTupleGetOid(tuple);
729 MyDatabaseTableSpace = dbform->dattablespace;
730 Assert(MyDatabaseId == dboid);
731 strlcpy(dbname, NameStr(dbform->datname), sizeof(dbname));
732 /* pass the database name back to the caller */
734 strcpy(out_dbname, dbname);
737 /* Now we can mark our PGPROC entry with the database ID */
738 /* (We assume this is an atomic store so no lock is needed) */
739 MyProc->databaseId = MyDatabaseId;
742 * Now, take a writer's lock on the database we are trying to connect to.
743 * If there is a concurrently running DROP DATABASE on that database, this
744 * will block us until it finishes (and has committed its update of
747 * Note that the lock is not held long, only until the end of this startup
748 * transaction. This is OK since we are already advertising our use of
749 * the database in the PGPROC array; anyone trying a DROP DATABASE after
750 * this point will see us there.
752 * Note: use of RowExclusiveLock here is reasonable because we envision
753 * our session as being a concurrent writer of the database. If we had a
754 * way of declaring a session as being guaranteed-read-only, we could use
755 * AccessShareLock for such sessions and thereby not conflict against
759 LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
763 * Recheck pg_database to make sure the target database hasn't gone away.
764 * If there was a concurrent DROP DATABASE, this ensures we will die
765 * cleanly without creating a mess.
771 tuple = GetDatabaseTuple(dbname);
772 if (!HeapTupleIsValid(tuple) ||
773 MyDatabaseId != HeapTupleGetOid(tuple) ||
774 MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
776 (errcode(ERRCODE_UNDEFINED_DATABASE),
777 errmsg("database \"%s\" does not exist", dbname),
778 errdetail("It seems to have just been dropped or renamed.")));
782 * Now we should be able to access the database directory safely. Verify
783 * it's there and looks reasonable.
785 fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
789 if (access(fullpath, F_OK) == -1)
793 (errcode(ERRCODE_UNDEFINED_DATABASE),
794 errmsg("database \"%s\" does not exist",
796 errdetail("The database subdirectory \"%s\" is missing.",
800 (errcode_for_file_access(),
801 errmsg("could not access directory \"%s\": %m",
805 ValidatePgVersion(fullpath);
808 SetDatabasePath(fullpath);
811 * It's now possible to do real access to the system catalogs.
813 * Load relcache entries for the system catalogs. This must create at
814 * least the minimum set of "nailed-in" cache entries.
816 RelationCacheInitializePhase3();
818 /* set up ACL framework (so CheckMyDatabase can check permissions) */
822 * Re-read the pg_database row for our database, check permissions and set
823 * up database-specific GUC settings. We can't do this until all the
824 * database-access infrastructure is up. (Also, it wants to know if the
825 * user is a superuser, so the above stuff has to happen first.)
828 CheckMyDatabase(dbname, am_superuser);
831 * Now process any command-line switches and any additional GUC variable
832 * settings passed in the startup packet. We couldn't do this before
833 * because we didn't know if client is a superuser.
835 if (MyProcPort != NULL)
836 process_startup_options(MyProcPort, am_superuser);
838 /* Process pg_db_role_setting options */
839 process_settings(MyDatabaseId, GetSessionUserId());
841 /* Apply PostAuthDelay as soon as we've read all options */
842 if (PostAuthDelay > 0)
843 pg_usleep(PostAuthDelay * 1000000L);
846 * Initialize various default states that can't be set up until we've
847 * selected the active user and gotten the right GUC settings.
850 /* set default namespace search path */
851 InitializeSearchPath();
853 /* initialize client encoding */
854 InitializeClientEncoding();
856 /* report this backend in the PgBackendStatus array */
860 /* close the transaction we started above */
862 CommitTransactionCommand();
866 * Process any command-line switches and any additional GUC variable
867 * settings passed in the startup packet.
870 process_startup_options(Port *port, bool am_superuser)
875 gucctx = am_superuser ? PGC_SUSET : PGC_BACKEND;
878 * First process any command-line switches that were included in the
879 * startup packet, if we are in a regular backend.
881 if (port->cmdline_options != NULL)
884 * The maximum possible number of commandline arguments that could
885 * come from port->cmdline_options is (strlen + 1) / 2; see
892 maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
894 av = (char **) palloc(maxac * sizeof(char *));
897 av[ac++] = "postgres";
899 /* Note this mangles port->cmdline_options */
900 pg_split_opts(av, &ac, port->cmdline_options);
906 (void) process_postgres_switches(ac, av, gucctx);
910 * Process any additional GUC variable settings passed in startup packet.
911 * These are handled exactly like command-line variables.
913 gucopts = list_head(port->guc_options);
919 name = lfirst(gucopts);
920 gucopts = lnext(gucopts);
922 value = lfirst(gucopts);
923 gucopts = lnext(gucopts);
925 SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
930 * Load GUC settings from pg_db_role_setting.
932 * We try specific settings for the database/role combination, as well as
933 * general for this database and for this user.
936 process_settings(Oid databaseid, Oid roleid)
940 if (!IsUnderPostmaster)
943 relsetting = heap_open(DbRoleSettingRelationId, AccessShareLock);
945 /* Later settings are ignored if set earlier. */
946 ApplySetting(databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
947 ApplySetting(InvalidOid, roleid, relsetting, PGC_S_USER);
948 ApplySetting(databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
950 heap_close(relsetting, AccessShareLock);
954 * Backend-shutdown callback. Do cleanup that we want to be sure happens
955 * before all the supporting modules begin to nail their doors shut via
956 * their own callbacks.
958 * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
959 * via separate callbacks that execute before this one. We don't combine the
960 * callbacks because we still want this one to happen if the user-level
964 ShutdownPostgres(int code, Datum arg)
966 /* Make sure we've killed any active transaction */
967 AbortOutOfAnyTransaction();
970 * User locks are not released by transaction end, so be sure to release
973 LockReleaseAll(USER_LOCKMETHOD, true);
978 * Returns true if at least one role is defined in this database cluster.
981 ThereIsAtLeastOneRole(void)
983 Relation pg_authid_rel;
987 pg_authid_rel = heap_open(AuthIdRelationId, AccessShareLock);
989 scan = heap_beginscan(pg_authid_rel, SnapshotNow, 0, NULL);
990 result = (heap_getnext(scan, ForwardScanDirection) != NULL);
993 heap_close(pg_authid_rel, AccessShareLock);