1 /*-------------------------------------------------------------------------
4 * postgres initialization utilities
6 * Portions Copyright (c) 1996-2012, 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/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"
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"
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);
75 /*** InitPostgres support ***/
79 * GetDatabaseTuple -- fetch the pg_database row for a database
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.
90 GetDatabaseTuple(const char *dbname)
101 Anum_pg_database_datname,
102 BTEqualStrategyNumber, F_NAMEEQ,
103 CStringGetDatum(dbname));
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).
110 relation = heap_open(DatabaseRelationId, AccessShareLock);
111 scan = systable_beginscan(relation, DatabaseNameIndexId,
112 criticalSharedRelcachesBuilt,
116 tuple = systable_getnext(scan);
118 /* Must copy tuple before releasing buffer */
119 if (HeapTupleIsValid(tuple))
120 tuple = heap_copytuple(tuple);
123 systable_endscan(scan);
124 heap_close(relation, AccessShareLock);
130 * GetDatabaseTupleByOid -- as above, but search by database OID
133 GetDatabaseTupleByOid(Oid dboid)
144 ObjectIdAttributeNumber,
145 BTEqualStrategyNumber, F_OIDEQ,
146 ObjectIdGetDatum(dboid));
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).
153 relation = heap_open(DatabaseRelationId, AccessShareLock);
154 scan = systable_beginscan(relation, DatabaseOidIndexId,
155 criticalSharedRelcachesBuilt,
159 tuple = systable_getnext(scan);
161 /* Must copy tuple before releasing buffer */
162 if (HeapTupleIsValid(tuple))
163 tuple = heap_copytuple(tuple);
166 systable_endscan(scan);
167 heap_close(relation, AccessShareLock);
174 * PerformAuthentication -- authenticate a remote client
176 * returns: nothing. Will not return at all if there's any failure.
179 PerformAuthentication(Port *port)
181 /* This should be set already, but let's make sure */
182 ClientAuthInProgress = true; /* limit visibility of log messages */
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.
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 * 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.
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.
217 enable_timeout_after(STATEMENT_TIMEOUT, AuthenticationTimeout * 1000);
220 * Now perform authentication exchange.
222 ClientAuthentication(port); /* might not return, if failure */
225 * Done with authentication. Disable the timeout, and log if needed.
227 disable_timeout(STATEMENT_TIMEOUT, false);
233 (errmsg("replication connection authorized: user=%s",
237 (errmsg("connection authorized: user=%s database=%s",
238 port->user_name, port->database_name)));
241 set_ps_display("startup", false);
243 ClientAuthInProgress = false; /* client_min_messages is active now */
248 * CheckMyDatabase -- fetch information from the pg_database entry for our DB
251 CheckMyDatabase(const char *name, bool am_superuser)
254 Form_pg_database dbform;
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);
264 /* This recheck is strictly paranoia */
265 if (strcmp(name, NameStr(dbform->datname)) != 0)
267 (errcode(ERRCODE_UNDEFINED_DATABASE),
268 errmsg("database \"%s\" has disappeared from pg_database",
270 errdetail("Database OID %u now seems to belong to \"%s\".",
271 MyDatabaseId, NameStr(dbform->datname))));
274 * Check permissions to connect to the database.
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;".
280 * We do not enforce them for autovacuum worker processes either.
282 if (IsUnderPostmaster && !IsAutoVacuumWorkerProcess())
285 * Check that the database is currently allowing connections.
287 if (!dbform->datallowconn)
289 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
290 errmsg("database \"%s\" is not currently accepting connections",
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.)
299 pg_database_aclcheck(MyDatabaseId, GetUserId(),
300 ACL_CONNECT) != ACLCHECK_OK)
302 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
303 errmsg("permission denied for database \"%s\"", name),
304 errdetail("User does not have CONNECT privilege.")));
307 * Check connection limit for this database.
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.
316 if (dbform->datconnlimit >= 0 &&
318 CountDBBackends(MyDatabaseId) > dbform->datconnlimit)
320 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
321 errmsg("too many connections for database \"%s\"",
326 * OK, we're golden. Next to-do item is to save the encoding info out of
327 * the pg_database tuple.
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);
337 /* assign locale variables */
338 collate = NameStr(dbform->datcollate);
339 ctype = NameStr(dbform->datctype);
341 if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
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.")));
348 if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
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.")));
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);
359 /* Use the right encoding in translated messages */
361 pg_bind_textdomain_codeset(textdomain(NULL));
364 ReleaseSysCache(tup);
369 /* --------------------------------
372 * This routine initializes stuff needed for ipc, locking, etc.
373 * it should be called something more informative.
374 * --------------------------------
377 InitCommunication(void)
380 * initialize shared memory and semaphores appropriately.
382 if (!IsUnderPostmaster) /* postmaster already did this */
385 * We're running a postgres bootstrap process or a standalone backend.
386 * Create private "shmem" and semaphores.
388 CreateSharedMemoryAndSemaphores(true, 0);
394 * pg_split_opts -- split a string of options and append it to an argv array
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.
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.
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...
408 pg_split_opts(char **argv, int *argcp, char *optstr)
412 while (isspace((unsigned char) *optstr))
416 argv[(*argcp)++] = optstr;
417 while (*optstr && !isspace((unsigned char) *optstr))
426 * Early initialization of a backend (either standalone or under postmaster).
427 * This happens even before InitPostgres.
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.
437 * Attach to shared memory and semaphores, and initialize our
438 * input/output/debugging file descriptors.
443 /* Do local initialization of file, storage and buffer managers */
446 InitBufferPoolAccess();
450 /* --------------------------------
452 * Initialize POSTGRES.
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.
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.
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.
468 * Be very careful with the order of calls in the InitPostgres function.
469 * --------------------------------
472 InitPostgres(const char *in_dbname, Oid dboid, const char *username,
475 bool bootstrap = IsBootstrapProcessingMode();
478 char dbname[NAMEDATALEN];
480 elog(DEBUG3, "InitPostgres");
483 * Add my PGPROC struct to the ProcArray.
485 * Once I have done this, I am visible to other backends!
490 * Initialize my entry in the shared-invalidation manager's array of
493 * Sets up MyBackendId, a unique backend identifier.
495 MyBackendId = InvalidBackendId;
497 SharedInvalBackendInit(false);
499 if (MyBackendId > MaxBackends || MyBackendId <= 0)
500 elog(FATAL, "bad backend ID: %d", MyBackendId);
502 /* Now that we have a BackendId, we can participate in ProcSignal */
503 ProcSignalInit(MyBackendId);
506 * Also set up timeout handlers needed for backend operation. We need
507 * these in every case except bootstrap.
511 RegisterTimeout(DEADLOCK_TIMEOUT, CheckDeadLock);
512 RegisterTimeout(STATEMENT_TIMEOUT, StatementTimeoutHandler);
516 * bufmgr needs another initialization call too
518 InitBufferPoolBackend();
521 * Initialize local process's access to XLOG.
523 if (IsUnderPostmaster)
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
531 (void) RecoveryInProgress();
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
541 on_shmem_exit(ShutdownXLOG, 0);
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.
550 RelationCacheInitialize();
554 /* Initialize portal manager */
555 EnablePortalManager();
557 /* Initialize stats collection --- must happen before first xact */
562 * Load relcache entries for the shared system catalogs. This must create
563 * at least entries for pg_database and catalogs used for authentication.
565 RelationCacheInitializePhase2();
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.
576 on_shmem_exit(ShutdownPostgres, 0);
578 /* The autovacuum launcher is done here */
579 if (IsAutoVacuumLauncherProcess())
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
592 /* statement_timestamp must be set for timeouts to work correctly */
593 SetCurrentStatementStartTimestamp();
594 StartTransactionCommand();
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.
602 XactIsoLevel = XACT_READ_COMMITTED;
604 (void) GetTransactionSnapshot();
608 * Perform client authentication if necessary, then figure out our
609 * postgres user ID, and see if we are a superuser.
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.
614 if (bootstrap || IsAutoVacuumWorkerProcess())
616 InitializeSessionUserIdStandalone();
619 else if (!IsUnderPostmaster)
621 InitializeSessionUserIdStandalone();
623 if (!ThereIsAtLeastOneRole())
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;.",
630 else if (IsBackgroundWorker)
632 if (username == NULL)
634 InitializeSessionUserIdStandalone();
639 InitializeSessionUserId(username);
640 am_superuser = superuser();
645 /* normal multiuser case */
646 Assert(MyProcPort != NULL);
647 PerformAuthentication(MyProcPort);
648 InitializeSessionUserId(username);
649 am_superuser = superuser();
653 * If we're trying to shut down, only superusers can connect, and new
654 * replication connections are not allowed.
656 if ((!am_superuser || am_walsender) &&
657 MyProcPort != NULL &&
658 MyProcPort->canAcceptConnections == CAC_WAITBACKUP)
662 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
663 errmsg("new replication connections are not allowed during database shutdown")));
666 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
667 errmsg("must be superuser to connect during database shutdown")));
671 * Binary upgrades only allowed super-user connections
673 if (IsBinaryUpgrade && !am_superuser)
676 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
677 errmsg("must be superuser to connect in binary upgrade mode")));
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
686 if ((!am_superuser || am_walsender) &&
687 ReservedBackends > 0 &&
688 !HaveNFreeProcs(ReservedBackends))
690 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
691 errmsg("remaining connection slots are reserved for non-replication superuser connections")));
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.
702 if (!superuser() && !is_authenticated_user_replication_role())
704 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
705 errmsg("must be superuser or replication role to start walsender")));
707 /* process any options passed in the startup packet */
708 if (MyProcPort != NULL)
709 process_startup_options(MyProcPort, am_superuser);
711 /* Apply PostAuthDelay as soon as we've read all options */
712 if (PostAuthDelay > 0)
713 pg_usleep(PostAuthDelay * 1000000L);
715 /* initialize client encoding */
716 InitializeClientEncoding();
718 /* report this backend in the PgBackendStatus array */
721 /* close the transaction we started above */
722 CommitTransactionCommand();
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.
731 * We take a shortcut in the bootstrap case, otherwise we have to look up
732 * the db's entry in pg_database.
736 MyDatabaseId = TemplateDbOid;
737 MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
739 else if (in_dbname != NULL)
742 Form_pg_database dbform;
744 tuple = GetDatabaseTuple(in_dbname);
745 if (!HeapTupleIsValid(tuple))
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));
757 /* caller specified database by OID */
759 Form_pg_database dbform;
761 tuple = GetDatabaseTupleByOid(dboid);
762 if (!HeapTupleIsValid(tuple))
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 */
773 strcpy(out_dbname, dbname);
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;
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
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.
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
798 LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
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.
810 tuple = GetDatabaseTuple(dbname);
811 if (!HeapTupleIsValid(tuple) ||
812 MyDatabaseId != HeapTupleGetOid(tuple) ||
813 MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
815 (errcode(ERRCODE_UNDEFINED_DATABASE),
816 errmsg("database \"%s\" does not exist", dbname),
817 errdetail("It seems to have just been dropped or renamed.")));
821 * Now we should be able to access the database directory safely. Verify
822 * it's there and looks reasonable.
824 fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
828 if (access(fullpath, F_OK) == -1)
832 (errcode(ERRCODE_UNDEFINED_DATABASE),
833 errmsg("database \"%s\" does not exist",
835 errdetail("The database subdirectory \"%s\" is missing.",
839 (errcode_for_file_access(),
840 errmsg("could not access directory \"%s\": %m",
844 ValidatePgVersion(fullpath);
847 SetDatabasePath(fullpath);
850 * It's now possible to do real access to the system catalogs.
852 * Load relcache entries for the system catalogs. This must create at
853 * least the minimum set of "nailed-in" cache entries.
855 RelationCacheInitializePhase3();
857 /* set up ACL framework (so CheckMyDatabase can check permissions) */
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.)
867 CheckMyDatabase(dbname, am_superuser);
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.
874 if (MyProcPort != NULL)
875 process_startup_options(MyProcPort, am_superuser);
877 /* Process pg_db_role_setting options */
878 process_settings(MyDatabaseId, GetSessionUserId());
880 /* Apply PostAuthDelay as soon as we've read all options */
881 if (PostAuthDelay > 0)
882 pg_usleep(PostAuthDelay * 1000000L);
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.
889 /* set default namespace search path */
890 InitializeSearchPath();
892 /* initialize client encoding */
893 InitializeClientEncoding();
895 /* report this backend in the PgBackendStatus array */
899 /* close the transaction we started above */
901 CommitTransactionCommand();
905 * Process any command-line switches and any additional GUC variable
906 * settings passed in the startup packet.
909 process_startup_options(Port *port, bool am_superuser)
914 gucctx = am_superuser ? PGC_SUSET : PGC_BACKEND;
917 * First process any command-line switches that were included in the
918 * startup packet, if we are in a regular backend.
920 if (port->cmdline_options != NULL)
923 * The maximum possible number of commandline arguments that could
924 * come from port->cmdline_options is (strlen + 1) / 2; see
931 maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
933 av = (char **) palloc(maxac * sizeof(char *));
936 av[ac++] = "postgres";
938 /* Note this mangles port->cmdline_options */
939 pg_split_opts(av, &ac, port->cmdline_options);
945 (void) process_postgres_switches(ac, av, gucctx);
949 * Process any additional GUC variable settings passed in startup packet.
950 * These are handled exactly like command-line variables.
952 gucopts = list_head(port->guc_options);
958 name = lfirst(gucopts);
959 gucopts = lnext(gucopts);
961 value = lfirst(gucopts);
962 gucopts = lnext(gucopts);
964 SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
969 * Load GUC settings from pg_db_role_setting.
971 * We try specific settings for the database/role combination, as well as
972 * general for this database and for this user.
975 process_settings(Oid databaseid, Oid roleid)
979 if (!IsUnderPostmaster)
982 relsetting = heap_open(DbRoleSettingRelationId, AccessShareLock);
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);
989 heap_close(relsetting, AccessShareLock);
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.
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
1003 ShutdownPostgres(int code, Datum arg)
1005 /* Make sure we've killed any active transaction */
1006 AbortOutOfAnyTransaction();
1009 * User locks are not released by transaction end, so be sure to release
1012 LockReleaseAll(USER_LOCKMETHOD, true);
1017 * STATEMENT_TIMEOUT handler: trigger a query-cancel interrupt.
1020 StatementTimeoutHandler(void)
1023 /* try to signal whole process group */
1024 kill(-MyProcPid, SIGINT);
1026 kill(MyProcPid, SIGINT);
1031 * Returns true if at least one role is defined in this database cluster.
1034 ThereIsAtLeastOneRole(void)
1036 Relation pg_authid_rel;
1040 pg_authid_rel = heap_open(AuthIdRelationId, AccessShareLock);
1042 scan = heap_beginscan(pg_authid_rel, SnapshotNow, 0, NULL);
1043 result = (heap_getnext(scan, ForwardScanDirection) != NULL);
1046 heap_close(pg_authid_rel, AccessShareLock);