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 * 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 enable_timeout_after(STATEMENT_TIMEOUT, AuthenticationTimeout * 1000);
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 disable_timeout(STATEMENT_TIMEOUT, false);
224 (errmsg("replication connection authorized: user=%s",
228 (errmsg("connection authorized: user=%s database=%s",
229 port->user_name, port->database_name)));
232 set_ps_display("startup", false);
234 ClientAuthInProgress = false; /* client_min_messages is active now */
239 * CheckMyDatabase -- fetch information from the pg_database entry for our DB
242 CheckMyDatabase(const char *name, bool am_superuser)
245 Form_pg_database dbform;
249 /* Fetch our pg_database row normally, via syscache */
250 tup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
251 if (!HeapTupleIsValid(tup))
252 elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
253 dbform = (Form_pg_database) GETSTRUCT(tup);
255 /* This recheck is strictly paranoia */
256 if (strcmp(name, NameStr(dbform->datname)) != 0)
258 (errcode(ERRCODE_UNDEFINED_DATABASE),
259 errmsg("database \"%s\" has disappeared from pg_database",
261 errdetail("Database OID %u now seems to belong to \"%s\".",
262 MyDatabaseId, NameStr(dbform->datname))));
265 * Check permissions to connect to the database.
267 * These checks are not enforced when in standalone mode, so that there is
268 * a way to recover from disabling all access to all databases, for
269 * example "UPDATE pg_database SET datallowconn = false;".
271 * We do not enforce them for autovacuum worker processes either.
273 if (IsUnderPostmaster && !IsAutoVacuumWorkerProcess())
276 * Check that the database is currently allowing connections.
278 if (!dbform->datallowconn)
280 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
281 errmsg("database \"%s\" is not currently accepting connections",
285 * Check privilege to connect to the database. (The am_superuser test
286 * is redundant, but since we have the flag, might as well check it
287 * and save a few cycles.)
290 pg_database_aclcheck(MyDatabaseId, GetUserId(),
291 ACL_CONNECT) != ACLCHECK_OK)
293 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
294 errmsg("permission denied for database \"%s\"", name),
295 errdetail("User does not have CONNECT privilege.")));
298 * Check connection limit for this database.
300 * There is a race condition here --- we create our PGPROC before
301 * checking for other PGPROCs. If two backends did this at about the
302 * same time, they might both think they were over the limit, while
303 * ideally one should succeed and one fail. Getting that to work
304 * exactly seems more trouble than it is worth, however; instead we
305 * just document that the connection limit is approximate.
307 if (dbform->datconnlimit >= 0 &&
309 CountDBBackends(MyDatabaseId) > dbform->datconnlimit)
311 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
312 errmsg("too many connections for database \"%s\"",
317 * OK, we're golden. Next to-do item is to save the encoding info out of
318 * the pg_database tuple.
320 SetDatabaseEncoding(dbform->encoding);
321 /* Record it as a GUC internal option, too */
322 SetConfigOption("server_encoding", GetDatabaseEncodingName(),
323 PGC_INTERNAL, PGC_S_OVERRIDE);
324 /* If we have no other source of client_encoding, use server encoding */
325 SetConfigOption("client_encoding", GetDatabaseEncodingName(),
326 PGC_BACKEND, PGC_S_DYNAMIC_DEFAULT);
328 /* assign locale variables */
329 collate = NameStr(dbform->datcollate);
330 ctype = NameStr(dbform->datctype);
332 if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
334 (errmsg("database locale is incompatible with operating system"),
335 errdetail("The database was initialized with LC_COLLATE \"%s\", "
336 " which is not recognized by setlocale().", collate),
337 errhint("Recreate the database with another locale or install the missing locale.")));
339 if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
341 (errmsg("database locale is incompatible with operating system"),
342 errdetail("The database was initialized with LC_CTYPE \"%s\", "
343 " which is not recognized by setlocale().", ctype),
344 errhint("Recreate the database with another locale or install the missing locale.")));
346 /* Make the locale settings visible as GUC variables, too */
347 SetConfigOption("lc_collate", collate, PGC_INTERNAL, PGC_S_OVERRIDE);
348 SetConfigOption("lc_ctype", ctype, PGC_INTERNAL, PGC_S_OVERRIDE);
350 /* Use the right encoding in translated messages */
352 pg_bind_textdomain_codeset(textdomain(NULL));
355 ReleaseSysCache(tup);
360 /* --------------------------------
363 * This routine initializes stuff needed for ipc, locking, etc.
364 * it should be called something more informative.
365 * --------------------------------
368 InitCommunication(void)
371 * initialize shared memory and semaphores appropriately.
373 if (!IsUnderPostmaster) /* postmaster already did this */
376 * We're running a postgres bootstrap process or a standalone backend.
377 * Create private "shmem" and semaphores.
379 CreateSharedMemoryAndSemaphores(true, 0);
385 * pg_split_opts -- split a string of options and append it to an argv array
387 * NB: the input string is destructively modified! Also, caller is responsible
388 * for ensuring the argv array is large enough. The maximum possible number
389 * of arguments added by this routine is (strlen(optstr) + 1) / 2.
391 * Since no current POSTGRES arguments require any quoting characters,
392 * we can use the simple-minded tactic of assuming each set of space-
393 * delimited characters is a separate argv element.
395 * If you don't like that, well, we *used* to pass the whole option string
396 * as ONE argument to execl(), which was even less intelligent...
399 pg_split_opts(char **argv, int *argcp, char *optstr)
403 while (isspace((unsigned char) *optstr))
407 argv[(*argcp)++] = optstr;
408 while (*optstr && !isspace((unsigned char) *optstr))
417 * Early initialization of a backend (either standalone or under postmaster).
418 * This happens even before InitPostgres.
420 * This is separate from InitPostgres because it is also called by auxiliary
421 * processes, such as the background writer process, which may not call
422 * InitPostgres at all.
428 * Attach to shared memory and semaphores, and initialize our
429 * input/output/debugging file descriptors.
434 /* Do local initialization of file, storage and buffer managers */
437 InitBufferPoolAccess();
441 /* --------------------------------
443 * Initialize POSTGRES.
445 * The database can be specified by name, using the in_dbname parameter, or by
446 * OID, using the dboid parameter. In the latter case, the actual database
447 * name can be returned to the caller in out_dbname. If out_dbname isn't
448 * NULL, it must point to a buffer of size NAMEDATALEN.
450 * In bootstrap mode no parameters are used. The autovacuum launcher process
451 * doesn't use any parameters either, because it only goes far enough to be
452 * able to read pg_database; it doesn't connect to any particular database.
453 * In walsender mode only username is used.
455 * As of PostgreSQL 8.2, we expect InitProcess() was already called, so we
456 * already have a PGPROC struct ... but it's not completely filled in yet.
459 * Be very careful with the order of calls in the InitPostgres function.
460 * --------------------------------
463 InitPostgres(const char *in_dbname, Oid dboid, const char *username,
466 bool bootstrap = IsBootstrapProcessingMode();
469 char dbname[NAMEDATALEN];
471 elog(DEBUG3, "InitPostgres");
474 * Add my PGPROC struct to the ProcArray.
476 * Once I have done this, I am visible to other backends!
481 * Initialize my entry in the shared-invalidation manager's array of
484 * Sets up MyBackendId, a unique backend identifier.
486 MyBackendId = InvalidBackendId;
488 SharedInvalBackendInit(false);
490 if (MyBackendId > MaxBackends || MyBackendId <= 0)
491 elog(FATAL, "bad backend ID: %d", MyBackendId);
493 /* Now that we have a BackendId, we can participate in ProcSignal */
494 ProcSignalInit(MyBackendId);
497 * Also set up timeout handlers needed for backend operation. We need
498 * these in every case except bootstrap.
502 RegisterTimeout(DEADLOCK_TIMEOUT, CheckDeadLock);
503 RegisterTimeout(STATEMENT_TIMEOUT, StatementTimeoutHandler);
507 * bufmgr needs another initialization call too
509 InitBufferPoolBackend();
512 * Initialize local process's access to XLOG.
514 if (IsUnderPostmaster)
517 * The postmaster already started the XLOG machinery, but we need to
518 * call InitXLOGAccess(), if the system isn't in hot-standby mode.
519 * This is handled by calling RecoveryInProgress and ignoring the
522 (void) RecoveryInProgress();
527 * We are either a bootstrap process or a standalone backend. Either
528 * way, start up the XLOG machinery, and register to have it closed
532 on_shmem_exit(ShutdownXLOG, 0);
536 * Initialize the relation cache and the system catalog caches. Note that
537 * no catalog access happens here; we only set up the hashtable structure.
538 * We must do this before starting a transaction because transaction abort
539 * would try to touch these hashtables.
541 RelationCacheInitialize();
545 /* Initialize portal manager */
546 EnablePortalManager();
548 /* Initialize stats collection --- must happen before first xact */
553 * Load relcache entries for the shared system catalogs. This must create
554 * at least entries for pg_database and catalogs used for authentication.
556 RelationCacheInitializePhase2();
559 * Set up process-exit callback to do pre-shutdown cleanup. This has to
560 * be after we've initialized all the low-level modules like the buffer
561 * manager, because during shutdown this has to run before the low-level
562 * modules start to close down. On the other hand, we want it in place
563 * before we begin our first transaction --- if we fail during the
564 * initialization transaction, as is entirely possible, we need the
565 * AbortTransaction call to clean up.
567 on_shmem_exit(ShutdownPostgres, 0);
569 /* The autovacuum launcher is done here */
570 if (IsAutoVacuumLauncherProcess())
574 * Start a new transaction here before first access to db, and get a
575 * snapshot. We don't have a use for the snapshot itself, but we're
576 * interested in the secondary effect that it sets RecentGlobalXmin. (This
577 * is critical for anything that reads heap pages, because HOT may decide
578 * to prune them even if the process doesn't attempt to modify any
583 /* statement_timestamp must be set for timeouts to work correctly */
584 SetCurrentStatementStartTimestamp();
585 StartTransactionCommand();
588 * transaction_isolation will have been set to the default by the
589 * above. If the default is "serializable", and we are in hot
590 * standby, we will fail if we don't change it to something lower.
591 * Fortunately, "read committed" is plenty good enough.
593 XactIsoLevel = XACT_READ_COMMITTED;
595 (void) GetTransactionSnapshot();
599 * Perform client authentication if necessary, then figure out our
600 * postgres user ID, and see if we are a superuser.
602 * In standalone mode and in autovacuum worker processes, we use a fixed
603 * ID, otherwise we figure it out from the authenticated user name.
605 if (bootstrap || IsAutoVacuumWorkerProcess())
607 InitializeSessionUserIdStandalone();
610 else if (!IsUnderPostmaster)
612 InitializeSessionUserIdStandalone();
614 if (!ThereIsAtLeastOneRole())
616 (errcode(ERRCODE_UNDEFINED_OBJECT),
617 errmsg("no roles are defined in this database system"),
618 errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
623 /* normal multiuser case */
624 Assert(MyProcPort != NULL);
625 PerformAuthentication(MyProcPort);
626 InitializeSessionUserId(username);
627 am_superuser = superuser();
631 * If we're trying to shut down, only superusers can connect, and new
632 * replication connections are not allowed.
634 if ((!am_superuser || am_walsender) &&
635 MyProcPort != NULL &&
636 MyProcPort->canAcceptConnections == CAC_WAITBACKUP)
640 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
641 errmsg("new replication connections are not allowed during database shutdown")));
644 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
645 errmsg("must be superuser to connect during database shutdown")));
649 * Binary upgrades only allowed super-user connections
651 if (IsBinaryUpgrade && !am_superuser)
654 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
655 errmsg("must be superuser to connect in binary upgrade mode")));
659 * The last few connections slots are reserved for superusers. Although
660 * replication connections currently require superuser privileges, we
661 * don't allow them to consume the reserved slots, which are intended for
664 if ((!am_superuser || am_walsender) &&
665 ReservedBackends > 0 &&
666 !HaveNFreeProcs(ReservedBackends))
668 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
669 errmsg("remaining connection slots are reserved for non-replication superuser connections")));
672 * If walsender, we don't want to connect to any particular database. Just
673 * finish the backend startup by processing any options from the startup
674 * packet, and we're done.
680 if (!superuser() && !is_authenticated_user_replication_role())
682 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
683 errmsg("must be superuser or replication role to start walsender")));
685 /* process any options passed in the startup packet */
686 if (MyProcPort != NULL)
687 process_startup_options(MyProcPort, am_superuser);
689 /* Apply PostAuthDelay as soon as we've read all options */
690 if (PostAuthDelay > 0)
691 pg_usleep(PostAuthDelay * 1000000L);
693 /* initialize client encoding */
694 InitializeClientEncoding();
696 /* report this backend in the PgBackendStatus array */
699 /* close the transaction we started above */
700 CommitTransactionCommand();
706 * Set up the global variables holding database id and default tablespace.
707 * But note we won't actually try to touch the database just yet.
709 * We take a shortcut in the bootstrap case, otherwise we have to look up
710 * the db's entry in pg_database.
714 MyDatabaseId = TemplateDbOid;
715 MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
717 else if (in_dbname != NULL)
720 Form_pg_database dbform;
722 tuple = GetDatabaseTuple(in_dbname);
723 if (!HeapTupleIsValid(tuple))
725 (errcode(ERRCODE_UNDEFINED_DATABASE),
726 errmsg("database \"%s\" does not exist", in_dbname)));
727 dbform = (Form_pg_database) GETSTRUCT(tuple);
728 MyDatabaseId = HeapTupleGetOid(tuple);
729 MyDatabaseTableSpace = dbform->dattablespace;
730 /* take database name from the caller, just for paranoia */
731 strlcpy(dbname, in_dbname, sizeof(dbname));
735 /* caller specified database by OID */
737 Form_pg_database dbform;
739 tuple = GetDatabaseTupleByOid(dboid);
740 if (!HeapTupleIsValid(tuple))
742 (errcode(ERRCODE_UNDEFINED_DATABASE),
743 errmsg("database %u does not exist", dboid)));
744 dbform = (Form_pg_database) GETSTRUCT(tuple);
745 MyDatabaseId = HeapTupleGetOid(tuple);
746 MyDatabaseTableSpace = dbform->dattablespace;
747 Assert(MyDatabaseId == dboid);
748 strlcpy(dbname, NameStr(dbform->datname), sizeof(dbname));
749 /* pass the database name back to the caller */
751 strcpy(out_dbname, dbname);
754 /* Now we can mark our PGPROC entry with the database ID */
755 /* (We assume this is an atomic store so no lock is needed) */
756 MyProc->databaseId = MyDatabaseId;
759 * Now, take a writer's lock on the database we are trying to connect to.
760 * If there is a concurrently running DROP DATABASE on that database, this
761 * will block us until it finishes (and has committed its update of
764 * Note that the lock is not held long, only until the end of this startup
765 * transaction. This is OK since we are already advertising our use of
766 * the database in the PGPROC array; anyone trying a DROP DATABASE after
767 * this point will see us there.
769 * Note: use of RowExclusiveLock here is reasonable because we envision
770 * our session as being a concurrent writer of the database. If we had a
771 * way of declaring a session as being guaranteed-read-only, we could use
772 * AccessShareLock for such sessions and thereby not conflict against
776 LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
780 * Recheck pg_database to make sure the target database hasn't gone away.
781 * If there was a concurrent DROP DATABASE, this ensures we will die
782 * cleanly without creating a mess.
788 tuple = GetDatabaseTuple(dbname);
789 if (!HeapTupleIsValid(tuple) ||
790 MyDatabaseId != HeapTupleGetOid(tuple) ||
791 MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
793 (errcode(ERRCODE_UNDEFINED_DATABASE),
794 errmsg("database \"%s\" does not exist", dbname),
795 errdetail("It seems to have just been dropped or renamed.")));
799 * Now we should be able to access the database directory safely. Verify
800 * it's there and looks reasonable.
802 fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
806 if (access(fullpath, F_OK) == -1)
810 (errcode(ERRCODE_UNDEFINED_DATABASE),
811 errmsg("database \"%s\" does not exist",
813 errdetail("The database subdirectory \"%s\" is missing.",
817 (errcode_for_file_access(),
818 errmsg("could not access directory \"%s\": %m",
822 ValidatePgVersion(fullpath);
825 SetDatabasePath(fullpath);
828 * It's now possible to do real access to the system catalogs.
830 * Load relcache entries for the system catalogs. This must create at
831 * least the minimum set of "nailed-in" cache entries.
833 RelationCacheInitializePhase3();
835 /* set up ACL framework (so CheckMyDatabase can check permissions) */
839 * Re-read the pg_database row for our database, check permissions and set
840 * up database-specific GUC settings. We can't do this until all the
841 * database-access infrastructure is up. (Also, it wants to know if the
842 * user is a superuser, so the above stuff has to happen first.)
845 CheckMyDatabase(dbname, am_superuser);
848 * Now process any command-line switches and any additional GUC variable
849 * settings passed in the startup packet. We couldn't do this before
850 * because we didn't know if client is a superuser.
852 if (MyProcPort != NULL)
853 process_startup_options(MyProcPort, am_superuser);
855 /* Process pg_db_role_setting options */
856 process_settings(MyDatabaseId, GetSessionUserId());
858 /* Apply PostAuthDelay as soon as we've read all options */
859 if (PostAuthDelay > 0)
860 pg_usleep(PostAuthDelay * 1000000L);
863 * Initialize various default states that can't be set up until we've
864 * selected the active user and gotten the right GUC settings.
867 /* set default namespace search path */
868 InitializeSearchPath();
870 /* initialize client encoding */
871 InitializeClientEncoding();
873 /* report this backend in the PgBackendStatus array */
877 /* close the transaction we started above */
879 CommitTransactionCommand();
883 * Process any command-line switches and any additional GUC variable
884 * settings passed in the startup packet.
887 process_startup_options(Port *port, bool am_superuser)
892 gucctx = am_superuser ? PGC_SUSET : PGC_BACKEND;
895 * First process any command-line switches that were included in the
896 * startup packet, if we are in a regular backend.
898 if (port->cmdline_options != NULL)
901 * The maximum possible number of commandline arguments that could
902 * come from port->cmdline_options is (strlen + 1) / 2; see
909 maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
911 av = (char **) palloc(maxac * sizeof(char *));
914 av[ac++] = "postgres";
916 /* Note this mangles port->cmdline_options */
917 pg_split_opts(av, &ac, port->cmdline_options);
923 (void) process_postgres_switches(ac, av, gucctx);
927 * Process any additional GUC variable settings passed in startup packet.
928 * These are handled exactly like command-line variables.
930 gucopts = list_head(port->guc_options);
936 name = lfirst(gucopts);
937 gucopts = lnext(gucopts);
939 value = lfirst(gucopts);
940 gucopts = lnext(gucopts);
942 SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
947 * Load GUC settings from pg_db_role_setting.
949 * We try specific settings for the database/role combination, as well as
950 * general for this database and for this user.
953 process_settings(Oid databaseid, Oid roleid)
957 if (!IsUnderPostmaster)
960 relsetting = heap_open(DbRoleSettingRelationId, AccessShareLock);
962 /* Later settings are ignored if set earlier. */
963 ApplySetting(databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
964 ApplySetting(InvalidOid, roleid, relsetting, PGC_S_USER);
965 ApplySetting(databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
967 heap_close(relsetting, AccessShareLock);
971 * Backend-shutdown callback. Do cleanup that we want to be sure happens
972 * before all the supporting modules begin to nail their doors shut via
973 * their own callbacks.
975 * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
976 * via separate callbacks that execute before this one. We don't combine the
977 * callbacks because we still want this one to happen if the user-level
981 ShutdownPostgres(int code, Datum arg)
983 /* Make sure we've killed any active transaction */
984 AbortOutOfAnyTransaction();
987 * User locks are not released by transaction end, so be sure to release
990 LockReleaseAll(USER_LOCKMETHOD, true);
995 * STATEMENT_TIMEOUT handler: trigger a query-cancel interrupt.
998 StatementTimeoutHandler(void)
1001 /* try to signal whole process group */
1002 kill(-MyProcPid, SIGINT);
1004 kill(MyProcPid, SIGINT);
1009 * Returns true if at least one role is defined in this database cluster.
1012 ThereIsAtLeastOneRole(void)
1014 Relation pg_authid_rel;
1018 pg_authid_rel = heap_open(AuthIdRelationId, AccessShareLock);
1020 scan = heap_beginscan(pg_authid_rel, SnapshotNow, 0, NULL);
1021 result = (heap_getnext(scan, ForwardScanDirection) != NULL);
1024 heap_close(pg_authid_rel, AccessShareLock);