1 /*-------------------------------------------------------------------------
4 * postgres initialization utilities
6 * Portions Copyright (c) 1996-2023, 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/genam.h"
23 #include "access/heapam.h"
24 #include "access/htup_details.h"
25 #include "access/session.h"
26 #include "access/sysattr.h"
27 #include "access/tableam.h"
28 #include "access/xact.h"
29 #include "access/xlog.h"
30 #include "access/xloginsert.h"
31 #include "catalog/catalog.h"
32 #include "catalog/namespace.h"
33 #include "catalog/pg_authid.h"
34 #include "catalog/pg_collation.h"
35 #include "catalog/pg_database.h"
36 #include "catalog/pg_db_role_setting.h"
37 #include "catalog/pg_tablespace.h"
38 #include "libpq/auth.h"
39 #include "libpq/libpq-be.h"
40 #include "mb/pg_wchar.h"
41 #include "miscadmin.h"
43 #include "postmaster/autovacuum.h"
44 #include "postmaster/postmaster.h"
45 #include "replication/slot.h"
46 #include "replication/walsender.h"
47 #include "storage/bufmgr.h"
48 #include "storage/fd.h"
49 #include "storage/ipc.h"
50 #include "storage/lmgr.h"
51 #include "storage/proc.h"
52 #include "storage/procarray.h"
53 #include "storage/procsignal.h"
54 #include "storage/sinvaladt.h"
55 #include "storage/smgr.h"
56 #include "storage/sync.h"
57 #include "tcop/tcopprot.h"
58 #include "utils/acl.h"
59 #include "utils/builtins.h"
60 #include "utils/fmgroids.h"
61 #include "utils/guc_hooks.h"
62 #include "utils/memutils.h"
63 #include "utils/pg_locale.h"
64 #include "utils/portal.h"
65 #include "utils/ps_status.h"
66 #include "utils/snapmgr.h"
67 #include "utils/syscache.h"
68 #include "utils/timeout.h"
70 static HeapTuple
GetDatabaseTuple(const char *dbname
);
71 static HeapTuple
GetDatabaseTupleByOid(Oid dboid
);
72 static void PerformAuthentication(Port
*port
);
73 static void CheckMyDatabase(const char *name
, bool am_superuser
, bool override_allow_connections
);
74 static void ShutdownPostgres(int code
, Datum arg
);
75 static void StatementTimeoutHandler(void);
76 static void LockTimeoutHandler(void);
77 static void IdleInTransactionSessionTimeoutHandler(void);
78 static void IdleSessionTimeoutHandler(void);
79 static void IdleStatsUpdateTimeoutHandler(void);
80 static void ClientCheckTimeoutHandler(void);
81 static bool ThereIsAtLeastOneRole(void);
82 static void process_startup_options(Port
*port
, bool am_superuser
);
83 static void process_settings(Oid databaseid
, Oid roleid
);
86 /*** InitPostgres support ***/
90 * GetDatabaseTuple -- fetch the pg_database row for a database
92 * This is used during backend startup when we don't yet have any access to
93 * system catalogs in general. In the worst case, we can seqscan pg_database
94 * using nothing but the hard-wired descriptor that relcache.c creates for
95 * pg_database. In more typical cases, relcache.c was able to load
96 * descriptors for both pg_database and its indexes from the shared relcache
97 * cache file, and so we can do an indexscan. criticalSharedRelcachesBuilt
98 * tells whether we got the cached descriptors.
101 GetDatabaseTuple(const char *dbname
)
112 Anum_pg_database_datname
,
113 BTEqualStrategyNumber
, F_NAMEEQ
,
114 CStringGetDatum(dbname
));
117 * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
118 * built the critical shared relcache entries (i.e., we're starting up
119 * without a shared relcache cache file).
121 relation
= table_open(DatabaseRelationId
, AccessShareLock
);
122 scan
= systable_beginscan(relation
, DatabaseNameIndexId
,
123 criticalSharedRelcachesBuilt
,
127 tuple
= systable_getnext(scan
);
129 /* Must copy tuple before releasing buffer */
130 if (HeapTupleIsValid(tuple
))
131 tuple
= heap_copytuple(tuple
);
134 systable_endscan(scan
);
135 table_close(relation
, AccessShareLock
);
141 * GetDatabaseTupleByOid -- as above, but search by database OID
144 GetDatabaseTupleByOid(Oid dboid
)
155 Anum_pg_database_oid
,
156 BTEqualStrategyNumber
, F_OIDEQ
,
157 ObjectIdGetDatum(dboid
));
160 * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
161 * built the critical shared relcache entries (i.e., we're starting up
162 * without a shared relcache cache file).
164 relation
= table_open(DatabaseRelationId
, AccessShareLock
);
165 scan
= systable_beginscan(relation
, DatabaseOidIndexId
,
166 criticalSharedRelcachesBuilt
,
170 tuple
= systable_getnext(scan
);
172 /* Must copy tuple before releasing buffer */
173 if (HeapTupleIsValid(tuple
))
174 tuple
= heap_copytuple(tuple
);
177 systable_endscan(scan
);
178 table_close(relation
, AccessShareLock
);
185 * PerformAuthentication -- authenticate a remote client
187 * returns: nothing. Will not return at all if there's any failure.
190 PerformAuthentication(Port
*port
)
192 /* This should be set already, but let's make sure */
193 ClientAuthInProgress
= true; /* limit visibility of log messages */
196 * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
197 * etcetera from the postmaster, and have to load them ourselves.
199 * FIXME: [fork/exec] Ugh. Is there a way around this overhead?
204 * load_hba() and load_ident() want to work within the PostmasterContext,
205 * so create that if it doesn't exist (which it won't). We'll delete it
206 * again later, in PostgresMain.
208 if (PostmasterContext
== NULL
)
209 PostmasterContext
= AllocSetContextCreate(TopMemoryContext
,
211 ALLOCSET_DEFAULT_SIZES
);
216 * It makes no sense to continue if we fail to load the HBA file,
217 * since there is no way to connect to the database in this case.
220 /* translator: %s is a configuration file */
221 (errmsg("could not load %s", HbaFileName
)));
227 * It is ok to continue if we fail to load the IDENT file, although it
228 * means that you cannot log in using any of the authentication
229 * methods that need a user name mapping. load_ident() already logged
230 * the details of error to the log.
236 * Set up a timeout in case a buggy or malicious client fails to respond
237 * during authentication. Since we're inside a transaction and might do
238 * database access, we have to use the statement_timeout infrastructure.
240 enable_timeout_after(STATEMENT_TIMEOUT
, AuthenticationTimeout
* 1000);
243 * Now perform authentication exchange.
245 set_ps_display("authentication");
246 ClientAuthentication(port
); /* might not return, if failure */
249 * Done with authentication. Disable the timeout, and log if needed.
251 disable_timeout(STATEMENT_TIMEOUT
, false);
255 StringInfoData logmsg
;
257 initStringInfo(&logmsg
);
259 appendStringInfo(&logmsg
, _("replication connection authorized: user=%s"),
262 appendStringInfo(&logmsg
, _("connection authorized: user=%s"),
265 appendStringInfo(&logmsg
, _(" database=%s"), port
->database_name
);
267 if (port
->application_name
!= NULL
)
268 appendStringInfo(&logmsg
, _(" application_name=%s"),
269 port
->application_name
);
272 if (port
->ssl_in_use
)
273 appendStringInfo(&logmsg
, _(" SSL enabled (protocol=%s, cipher=%s, bits=%d)"),
274 be_tls_get_version(port
),
275 be_tls_get_cipher(port
),
276 be_tls_get_cipher_bits(port
));
281 const char *princ
= be_gssapi_get_princ(port
);
284 appendStringInfo(&logmsg
,
285 _(" GSS (authenticated=%s, encrypted=%s, delegated_credentials=%s, principal=%s)"),
286 be_gssapi_get_auth(port
) ? _("yes") : _("no"),
287 be_gssapi_get_enc(port
) ? _("yes") : _("no"),
288 be_gssapi_get_delegation(port
) ? _("yes") : _("no"),
291 appendStringInfo(&logmsg
,
292 _(" GSS (authenticated=%s, encrypted=%s, delegated_credentials=%s)"),
293 be_gssapi_get_auth(port
) ? _("yes") : _("no"),
294 be_gssapi_get_enc(port
) ? _("yes") : _("no"),
295 be_gssapi_get_delegation(port
) ? _("yes") : _("no"));
299 ereport(LOG
, errmsg_internal("%s", logmsg
.data
));
303 set_ps_display("startup");
305 ClientAuthInProgress
= false; /* client_min_messages is active now */
310 * CheckMyDatabase -- fetch information from the pg_database entry for our DB
313 CheckMyDatabase(const char *name
, bool am_superuser
, bool override_allow_connections
)
316 Form_pg_database dbform
;
323 /* Fetch our pg_database row normally, via syscache */
324 tup
= SearchSysCache1(DATABASEOID
, ObjectIdGetDatum(MyDatabaseId
));
325 if (!HeapTupleIsValid(tup
))
326 elog(ERROR
, "cache lookup failed for database %u", MyDatabaseId
);
327 dbform
= (Form_pg_database
) GETSTRUCT(tup
);
329 /* This recheck is strictly paranoia */
330 if (strcmp(name
, NameStr(dbform
->datname
)) != 0)
332 (errcode(ERRCODE_UNDEFINED_DATABASE
),
333 errmsg("database \"%s\" has disappeared from pg_database",
335 errdetail("Database OID %u now seems to belong to \"%s\".",
336 MyDatabaseId
, NameStr(dbform
->datname
))));
339 * Check permissions to connect to the database.
341 * These checks are not enforced when in standalone mode, so that there is
342 * a way to recover from disabling all access to all databases, for
343 * example "UPDATE pg_database SET datallowconn = false;".
345 * We do not enforce them for autovacuum worker processes either.
347 if (IsUnderPostmaster
&& !IsAutoVacuumWorkerProcess())
350 * Check that the database is currently allowing connections.
352 if (!dbform
->datallowconn
&& !override_allow_connections
)
354 (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE
),
355 errmsg("database \"%s\" is not currently accepting connections",
359 * Check privilege to connect to the database. (The am_superuser test
360 * is redundant, but since we have the flag, might as well check it
361 * and save a few cycles.)
364 object_aclcheck(DatabaseRelationId
, MyDatabaseId
, GetUserId(),
365 ACL_CONNECT
) != ACLCHECK_OK
)
367 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE
),
368 errmsg("permission denied for database \"%s\"", name
),
369 errdetail("User does not have CONNECT privilege.")));
372 * Check connection limit for this database.
374 * There is a race condition here --- we create our PGPROC before
375 * checking for other PGPROCs. If two backends did this at about the
376 * same time, they might both think they were over the limit, while
377 * ideally one should succeed and one fail. Getting that to work
378 * exactly seems more trouble than it is worth, however; instead we
379 * just document that the connection limit is approximate.
381 if (dbform
->datconnlimit
>= 0 &&
383 CountDBConnections(MyDatabaseId
) > dbform
->datconnlimit
)
385 (errcode(ERRCODE_TOO_MANY_CONNECTIONS
),
386 errmsg("too many connections for database \"%s\"",
391 * OK, we're golden. Next to-do item is to save the encoding info out of
392 * the pg_database tuple.
394 SetDatabaseEncoding(dbform
->encoding
);
395 /* Record it as a GUC internal option, too */
396 SetConfigOption("server_encoding", GetDatabaseEncodingName(),
397 PGC_INTERNAL
, PGC_S_DYNAMIC_DEFAULT
);
398 /* If we have no other source of client_encoding, use server encoding */
399 SetConfigOption("client_encoding", GetDatabaseEncodingName(),
400 PGC_BACKEND
, PGC_S_DYNAMIC_DEFAULT
);
402 /* assign locale variables */
403 datum
= SysCacheGetAttrNotNull(DATABASEOID
, tup
, Anum_pg_database_datcollate
);
404 collate
= TextDatumGetCString(datum
);
405 datum
= SysCacheGetAttrNotNull(DATABASEOID
, tup
, Anum_pg_database_datctype
);
406 ctype
= TextDatumGetCString(datum
);
408 if (pg_perm_setlocale(LC_COLLATE
, collate
) == NULL
)
410 (errmsg("database locale is incompatible with operating system"),
411 errdetail("The database was initialized with LC_COLLATE \"%s\", "
412 " which is not recognized by setlocale().", collate
),
413 errhint("Recreate the database with another locale or install the missing locale.")));
415 if (pg_perm_setlocale(LC_CTYPE
, ctype
) == NULL
)
417 (errmsg("database locale is incompatible with operating system"),
418 errdetail("The database was initialized with LC_CTYPE \"%s\", "
419 " which is not recognized by setlocale().", ctype
),
420 errhint("Recreate the database with another locale or install the missing locale.")));
422 if (strcmp(ctype
, "C") == 0 ||
423 strcmp(ctype
, "POSIX") == 0)
424 database_ctype_is_c
= true;
426 if (dbform
->datlocprovider
== COLLPROVIDER_ICU
)
430 datum
= SysCacheGetAttrNotNull(DATABASEOID
, tup
, Anum_pg_database_daticulocale
);
431 iculocale
= TextDatumGetCString(datum
);
433 datum
= SysCacheGetAttr(DATABASEOID
, tup
, Anum_pg_database_daticurules
, &isnull
);
435 icurules
= TextDatumGetCString(datum
);
439 make_icu_collator(iculocale
, icurules
, &default_locale
);
444 default_locale
.provider
= dbform
->datlocprovider
;
447 * Default locale is currently always deterministic. Nondeterministic
448 * locales currently don't support pattern matching, which would break a
449 * lot of things if applied globally.
451 default_locale
.deterministic
= true;
454 * Check collation version. See similar code in
455 * pg_newlocale_from_collation(). Note that here we warn instead of error
456 * in any case, so that we don't prevent connecting.
458 datum
= SysCacheGetAttr(DATABASEOID
, tup
, Anum_pg_database_datcollversion
,
462 char *actual_versionstr
;
463 char *collversionstr
;
465 collversionstr
= TextDatumGetCString(datum
);
467 actual_versionstr
= get_collation_actual_version(dbform
->datlocprovider
, dbform
->datlocprovider
== COLLPROVIDER_ICU
? iculocale
: collate
);
468 if (!actual_versionstr
)
469 /* should not happen */
471 "database \"%s\" has no actual collation version, but a version was recorded",
473 else if (strcmp(actual_versionstr
, collversionstr
) != 0)
475 (errmsg("database \"%s\" has a collation version mismatch",
477 errdetail("The database was created using collation version %s, "
478 "but the operating system provides version %s.",
479 collversionstr
, actual_versionstr
),
480 errhint("Rebuild all objects in this database that use the default collation and run "
481 "ALTER DATABASE %s REFRESH COLLATION VERSION, "
482 "or build PostgreSQL with the right library version.",
483 quote_identifier(name
))));
486 ReleaseSysCache(tup
);
491 * pg_split_opts -- split a string of options and append it to an argv array
493 * The caller is responsible for ensuring the argv array is large enough. The
494 * maximum possible number of arguments added by this routine is
495 * (strlen(optstr) + 1) / 2.
497 * Because some option values can contain spaces we allow escaping using
498 * backslashes, with \\ representing a literal backslash.
501 pg_split_opts(char **argv
, int *argcp
, const char *optstr
)
509 bool last_was_escape
= false;
513 /* skip over leading space */
514 while (isspace((unsigned char) *optstr
))
521 * Parse a single option, stopping at the first space, unless it's
526 if (isspace((unsigned char) *optstr
) && !last_was_escape
)
529 if (!last_was_escape
&& *optstr
== '\\')
530 last_was_escape
= true;
533 last_was_escape
= false;
534 appendStringInfoChar(&s
, *optstr
);
540 /* now store the option in the next argv[] position */
541 argv
[(*argcp
)++] = pstrdup(s
.data
);
548 * Initialize MaxBackends value from config options.
550 * This must be called after modules have had the chance to alter GUCs in
551 * shared_preload_libraries and before shared memory size is determined.
553 * Note that in EXEC_BACKEND environment, the value is passed down from
554 * postmaster to subprocesses via BackendParameters in SubPostmasterMain; only
555 * postmaster itself and processes not under postmaster control should call
559 InitializeMaxBackends(void)
561 Assert(MaxBackends
== 0);
563 /* the extra unit accounts for the autovacuum launcher */
564 MaxBackends
= MaxConnections
+ autovacuum_max_workers
+ 1 +
565 max_worker_processes
+ max_wal_senders
;
567 /* internal error because the values were all checked previously */
568 if (MaxBackends
> MAX_BACKENDS
)
569 elog(ERROR
, "too many backends configured");
573 * GUC check_hook for max_connections
576 check_max_connections(int *newval
, void **extra
, GucSource source
)
578 if (*newval
+ autovacuum_max_workers
+ 1 +
579 max_worker_processes
+ max_wal_senders
> MAX_BACKENDS
)
585 * GUC check_hook for autovacuum_max_workers
588 check_autovacuum_max_workers(int *newval
, void **extra
, GucSource source
)
590 if (MaxConnections
+ *newval
+ 1 +
591 max_worker_processes
+ max_wal_senders
> MAX_BACKENDS
)
597 * GUC check_hook for max_worker_processes
600 check_max_worker_processes(int *newval
, void **extra
, GucSource source
)
602 if (MaxConnections
+ autovacuum_max_workers
+ 1 +
603 *newval
+ max_wal_senders
> MAX_BACKENDS
)
609 * GUC check_hook for max_wal_senders
612 check_max_wal_senders(int *newval
, void **extra
, GucSource source
)
614 if (MaxConnections
+ autovacuum_max_workers
+ 1 +
615 max_worker_processes
+ *newval
> MAX_BACKENDS
)
621 * Early initialization of a backend (either standalone or under postmaster).
622 * This happens even before InitPostgres.
624 * This is separate from InitPostgres because it is also called by auxiliary
625 * processes, such as the background writer process, which may not call
626 * InitPostgres at all.
631 Assert(MyProc
!= NULL
);
634 * Initialize our input/output/debugging file descriptors.
639 * Initialize file access. Done early so other subsystems can access
645 * Initialize statistics reporting. This needs to happen early to ensure
646 * that pgstat's shutdown callback runs after the shutdown callbacks of
647 * all subsystems that can produce stats (like e.g. transaction commits
652 /* Do local initialization of storage and buffer managers */
655 InitBufferPoolAccess();
658 * Initialize temporary file access after pgstat, so that the temporary
659 * file shutdown hook can report temporary file statistics.
661 InitTemporaryFileAccess();
664 * Initialize local buffers for WAL record construction, in case we ever
665 * try to insert XLOG.
670 * Initialize replication slots after pgstat. The exit hook might need to
671 * drop ephemeral slots, which in turn triggers stats reporting.
673 ReplicationSlotInitialize();
677 /* --------------------------------
679 * Initialize POSTGRES.
682 * in_dbname, dboid: specify database to connect to, as described below
683 * username, useroid: specify role to connect as, as described below
684 * load_session_libraries: TRUE to honor [session|local]_preload_libraries
685 * override_allow_connections: TRUE to connect despite !datallowconn
686 * out_dbname: optional output parameter, see below; pass NULL if not used
688 * The database can be specified by name, using the in_dbname parameter, or by
689 * OID, using the dboid parameter. Specify NULL or InvalidOid respectively
690 * for the unused parameter. If dboid is provided, the actual database
691 * name can be returned to the caller in out_dbname. If out_dbname isn't
692 * NULL, it must point to a buffer of size NAMEDATALEN.
694 * Similarly, the role can be passed by name, using the username parameter,
695 * or by OID using the useroid parameter.
697 * In bootstrap mode the database and username parameters are NULL/InvalidOid.
698 * The autovacuum launcher process doesn't specify these parameters either,
699 * because it only goes far enough to be able to read pg_database; it doesn't
700 * connect to any particular database. An autovacuum worker specifies a
701 * database but not a username; conversely, a physical walsender specifies
702 * username but not database.
704 * By convention, load_session_libraries should be passed as true in
705 * "interactive" sessions (including standalone backends), but false in
706 * background processes such as autovacuum. Note in particular that it
707 * shouldn't be true in parallel worker processes; those have another
708 * mechanism for replicating their leader's set of loaded libraries.
710 * We expect that InitProcess() was already called, so we already have a
711 * PGPROC struct ... but it's not completely filled in yet.
714 * Be very careful with the order of calls in the InitPostgres function.
715 * --------------------------------
718 InitPostgres(const char *in_dbname
, Oid dboid
,
719 const char *username
, Oid useroid
,
720 bool load_session_libraries
,
721 bool override_allow_connections
,
724 bool bootstrap
= IsBootstrapProcessingMode();
727 char dbname
[NAMEDATALEN
];
730 elog(DEBUG3
, "InitPostgres");
733 * Add my PGPROC struct to the ProcArray.
735 * Once I have done this, I am visible to other backends!
740 * Initialize my entry in the shared-invalidation manager's array of
743 * Sets up MyBackendId, a unique backend identifier.
745 MyBackendId
= InvalidBackendId
;
747 SharedInvalBackendInit(false);
749 if (MyBackendId
> MaxBackends
|| MyBackendId
<= 0)
750 elog(FATAL
, "bad backend ID: %d", MyBackendId
);
752 /* Now that we have a BackendId, we can participate in ProcSignal */
753 ProcSignalInit(MyBackendId
);
756 * Also set up timeout handlers needed for backend operation. We need
757 * these in every case except bootstrap.
761 RegisterTimeout(DEADLOCK_TIMEOUT
, CheckDeadLockAlert
);
762 RegisterTimeout(STATEMENT_TIMEOUT
, StatementTimeoutHandler
);
763 RegisterTimeout(LOCK_TIMEOUT
, LockTimeoutHandler
);
764 RegisterTimeout(IDLE_IN_TRANSACTION_SESSION_TIMEOUT
,
765 IdleInTransactionSessionTimeoutHandler
);
766 RegisterTimeout(IDLE_SESSION_TIMEOUT
, IdleSessionTimeoutHandler
);
767 RegisterTimeout(CLIENT_CONNECTION_CHECK_TIMEOUT
, ClientCheckTimeoutHandler
);
768 RegisterTimeout(IDLE_STATS_UPDATE_TIMEOUT
,
769 IdleStatsUpdateTimeoutHandler
);
773 * If this is either a bootstrap process or a standalone backend, start up
774 * the XLOG machinery, and register to have it closed down at exit. In
775 * other cases, the startup process is responsible for starting up the
776 * XLOG machinery, and the checkpointer for closing it down.
778 if (!IsUnderPostmaster
)
781 * We don't yet have an aux-process resource owner, but StartupXLOG
782 * and ShutdownXLOG will need one. Hence, create said resource owner
783 * (and register a callback to clean it up after ShutdownXLOG runs).
785 CreateAuxProcessResourceOwner();
788 /* Release (and warn about) any buffer pins leaked in StartupXLOG */
789 ReleaseAuxProcessResources(true);
790 /* Reset CurrentResourceOwner to nothing for the moment */
791 CurrentResourceOwner
= NULL
;
794 * Use before_shmem_exit() so that ShutdownXLOG() can rely on DSM
795 * segments etc to work (which in turn is required for pgstats).
797 before_shmem_exit(pgstat_before_server_shutdown
, 0);
798 before_shmem_exit(ShutdownXLOG
, 0);
802 * Initialize the relation cache and the system catalog caches. Note that
803 * no catalog access happens here; we only set up the hashtable structure.
804 * We must do this before starting a transaction because transaction abort
805 * would try to touch these hashtables.
807 RelationCacheInitialize();
811 /* Initialize portal manager */
812 EnablePortalManager();
814 /* Initialize status reporting */
818 * Load relcache entries for the shared system catalogs. This must create
819 * at least entries for pg_database and catalogs used for authentication.
821 RelationCacheInitializePhase2();
824 * Set up process-exit callback to do pre-shutdown cleanup. This is the
825 * one of the first before_shmem_exit callbacks we register; thus, this
826 * will be one the last things we do before low-level modules like the
827 * buffer manager begin to close down. We need to have this in place
828 * before we begin our first transaction --- if we fail during the
829 * initialization transaction, as is entirely possible, we need the
830 * AbortTransaction call to clean up.
832 before_shmem_exit(ShutdownPostgres
, 0);
834 /* The autovacuum launcher is done here */
835 if (IsAutoVacuumLauncherProcess())
837 /* report this backend in the PgBackendStatus array */
844 * Start a new transaction here before first access to db, and get a
845 * snapshot. We don't have a use for the snapshot itself, but we're
846 * interested in the secondary effect that it sets RecentGlobalXmin. (This
847 * is critical for anything that reads heap pages, because HOT may decide
848 * to prune them even if the process doesn't attempt to modify any
851 * FIXME: This comment is inaccurate / the code buggy. A snapshot that is
852 * not pushed/active does not reliably prevent HOT pruning (->xmin could
853 * e.g. be cleared when cache invalidations are processed).
857 /* statement_timestamp must be set for timeouts to work correctly */
858 SetCurrentStatementStartTimestamp();
859 StartTransactionCommand();
862 * transaction_isolation will have been set to the default by the
863 * above. If the default is "serializable", and we are in hot
864 * standby, we will fail if we don't change it to something lower.
865 * Fortunately, "read committed" is plenty good enough.
867 XactIsoLevel
= XACT_READ_COMMITTED
;
869 (void) GetTransactionSnapshot();
873 * Perform client authentication if necessary, then figure out our
874 * postgres user ID, and see if we are a superuser.
876 * In standalone mode and in autovacuum worker processes, we use a fixed
877 * ID, otherwise we figure it out from the authenticated user name.
879 if (bootstrap
|| IsAutoVacuumWorkerProcess())
881 InitializeSessionUserIdStandalone();
884 else if (!IsUnderPostmaster
)
886 InitializeSessionUserIdStandalone();
888 if (!ThereIsAtLeastOneRole())
890 (errcode(ERRCODE_UNDEFINED_OBJECT
),
891 errmsg("no roles are defined in this database system"),
892 errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
893 username
!= NULL
? username
: "postgres")));
895 else if (IsBackgroundWorker
)
897 if (username
== NULL
&& !OidIsValid(useroid
))
899 InitializeSessionUserIdStandalone();
904 InitializeSessionUserId(username
, useroid
);
905 am_superuser
= superuser();
910 /* normal multiuser case */
911 Assert(MyProcPort
!= NULL
);
912 PerformAuthentication(MyProcPort
);
913 InitializeSessionUserId(username
, useroid
);
914 /* ensure that auth_method is actually valid, aka authn_id is not NULL */
915 if (MyClientConnectionInfo
.authn_id
)
916 InitializeSystemUser(MyClientConnectionInfo
.authn_id
,
917 hba_authname(MyClientConnectionInfo
.auth_method
));
918 am_superuser
= superuser();
922 * Binary upgrades only allowed super-user connections
924 if (IsBinaryUpgrade
&& !am_superuser
)
927 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE
),
928 errmsg("must be superuser to connect in binary upgrade mode")));
932 * The last few connection slots are reserved for superusers and roles
933 * with privileges of pg_use_reserved_connections. Replication
934 * connections are drawn from slots reserved with max_wal_senders and are
935 * not limited by max_connections, superuser_reserved_connections, or
936 * reserved_connections.
938 * Note: At this point, the new backend has already claimed a proc struct,
939 * so we must check whether the number of free slots is strictly less than
940 * the reserved connection limits.
942 if (!am_superuser
&& !am_walsender
&&
943 (SuperuserReservedConnections
+ ReservedConnections
) > 0 &&
944 !HaveNFreeProcs(SuperuserReservedConnections
+ ReservedConnections
, &nfree
))
946 if (nfree
< SuperuserReservedConnections
)
948 (errcode(ERRCODE_TOO_MANY_CONNECTIONS
),
949 errmsg("remaining connection slots are reserved for roles with the %s attribute",
952 if (!has_privs_of_role(GetUserId(), ROLE_PG_USE_RESERVED_CONNECTIONS
))
954 (errcode(ERRCODE_TOO_MANY_CONNECTIONS
),
955 errmsg("remaining connection slots are reserved for roles with privileges of the \"%s\" role",
956 "pg_use_reserved_connections")));
959 /* Check replication permissions needed for walsender processes. */
964 if (!has_rolreplication(GetUserId()))
966 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE
),
967 errmsg("permission denied to start WAL sender"),
968 errdetail("Only roles with the %s attribute may start a WAL sender process.",
973 * If this is a plain walsender only supporting physical replication, we
974 * don't want to connect to any particular database. Just finish the
975 * backend startup by processing any options from the startup packet, and
978 if (am_walsender
&& !am_db_walsender
)
980 /* process any options passed in the startup packet */
981 if (MyProcPort
!= NULL
)
982 process_startup_options(MyProcPort
, am_superuser
);
984 /* Apply PostAuthDelay as soon as we've read all options */
985 if (PostAuthDelay
> 0)
986 pg_usleep(PostAuthDelay
* 1000000L);
988 /* initialize client encoding */
989 InitializeClientEncoding();
991 /* report this backend in the PgBackendStatus array */
994 /* close the transaction we started above */
995 CommitTransactionCommand();
1001 * Set up the global variables holding database id and default tablespace.
1002 * But note we won't actually try to touch the database just yet.
1004 * We take a shortcut in the bootstrap case, otherwise we have to look up
1005 * the db's entry in pg_database.
1009 dboid
= Template1DbOid
;
1010 MyDatabaseTableSpace
= DEFAULTTABLESPACE_OID
;
1012 else if (in_dbname
!= NULL
)
1015 Form_pg_database dbform
;
1017 tuple
= GetDatabaseTuple(in_dbname
);
1018 if (!HeapTupleIsValid(tuple
))
1020 (errcode(ERRCODE_UNDEFINED_DATABASE
),
1021 errmsg("database \"%s\" does not exist", in_dbname
)));
1022 dbform
= (Form_pg_database
) GETSTRUCT(tuple
);
1023 dboid
= dbform
->oid
;
1025 else if (!OidIsValid(dboid
))
1028 * If this is a background worker not bound to any particular
1029 * database, we're done now. Everything that follows only makes sense
1030 * if we are bound to a specific database. We do need to close the
1031 * transaction we started before returning.
1036 CommitTransactionCommand();
1042 * Now, take a writer's lock on the database we are trying to connect to.
1043 * If there is a concurrently running DROP DATABASE on that database, this
1044 * will block us until it finishes (and has committed its update of
1047 * Note that the lock is not held long, only until the end of this startup
1048 * transaction. This is OK since we will advertise our use of the
1049 * database in the ProcArray before dropping the lock (in fact, that's the
1050 * next thing to do). Anyone trying a DROP DATABASE after this point will
1051 * see us in the array once they have the lock. Ordering is important for
1052 * this because we don't want to advertise ourselves as being in this
1053 * database until we have the lock; otherwise we create what amounts to a
1054 * deadlock with CountOtherDBBackends().
1056 * Note: use of RowExclusiveLock here is reasonable because we envision
1057 * our session as being a concurrent writer of the database. If we had a
1058 * way of declaring a session as being guaranteed-read-only, we could use
1059 * AccessShareLock for such sessions and thereby not conflict against
1063 LockSharedObject(DatabaseRelationId
, dboid
, 0, RowExclusiveLock
);
1066 * Recheck pg_database to make sure the target database hasn't gone away.
1067 * If there was a concurrent DROP DATABASE, this ensures we will die
1068 * cleanly without creating a mess.
1073 Form_pg_database datform
;
1075 tuple
= GetDatabaseTupleByOid(dboid
);
1076 if (HeapTupleIsValid(tuple
))
1077 datform
= (Form_pg_database
) GETSTRUCT(tuple
);
1079 if (!HeapTupleIsValid(tuple
) ||
1080 (in_dbname
&& namestrcmp(&datform
->datname
, in_dbname
)))
1084 (errcode(ERRCODE_UNDEFINED_DATABASE
),
1085 errmsg("database \"%s\" does not exist", in_dbname
),
1086 errdetail("It seems to have just been dropped or renamed.")));
1089 (errcode(ERRCODE_UNDEFINED_DATABASE
),
1090 errmsg("database %u does not exist", dboid
)));
1093 strlcpy(dbname
, NameStr(datform
->datname
), sizeof(dbname
));
1095 if (database_is_invalid_form(datform
))
1098 errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE
),
1099 errmsg("cannot connect to invalid database \"%s\"", dbname
),
1100 errhint("Use DROP DATABASE to drop invalid databases."));
1103 MyDatabaseTableSpace
= datform
->dattablespace
;
1104 /* pass the database name back to the caller */
1106 strcpy(out_dbname
, dbname
);
1110 * Now that we rechecked, we are certain to be connected to a database and
1111 * thus can set MyDatabaseId.
1113 * It is important that MyDatabaseId only be set once we are sure that the
1114 * target database can no longer be concurrently dropped or renamed. For
1115 * example, without this guarantee, pgstat_update_dbstats() could create
1116 * entries for databases that were just dropped in the pgstat shutdown
1117 * callback, which could confuse other code paths like the autovacuum
1120 MyDatabaseId
= dboid
;
1123 * Now we can mark our PGPROC entry with the database ID.
1125 * We assume this is an atomic store so no lock is needed; though actually
1126 * things would work fine even if it weren't atomic. Anyone searching the
1127 * ProcArray for this database's ID should hold the database lock, so they
1128 * would not be executing concurrently with this store. A process looking
1129 * for another database's ID could in theory see a chance match if it read
1130 * a partially-updated databaseId value; but as long as all such searches
1131 * wait and retry, as in CountOtherDBBackends(), they will certainly see
1132 * the correct value on their next try.
1134 MyProc
->databaseId
= MyDatabaseId
;
1137 * We established a catalog snapshot while reading pg_authid and/or
1138 * pg_database; but until we have set up MyDatabaseId, we won't react to
1139 * incoming sinval messages for unshared catalogs, so we won't realize it
1140 * if the snapshot has been invalidated. Assume it's no good anymore.
1142 InvalidateCatalogSnapshot();
1145 * Now we should be able to access the database directory safely. Verify
1146 * it's there and looks reasonable.
1148 fullpath
= GetDatabasePath(MyDatabaseId
, MyDatabaseTableSpace
);
1152 if (access(fullpath
, F_OK
) == -1)
1154 if (errno
== ENOENT
)
1156 (errcode(ERRCODE_UNDEFINED_DATABASE
),
1157 errmsg("database \"%s\" does not exist",
1159 errdetail("The database subdirectory \"%s\" is missing.",
1163 (errcode_for_file_access(),
1164 errmsg("could not access directory \"%s\": %m",
1168 ValidatePgVersion(fullpath
);
1171 SetDatabasePath(fullpath
);
1175 * It's now possible to do real access to the system catalogs.
1177 * Load relcache entries for the system catalogs. This must create at
1178 * least the minimum set of "nailed-in" cache entries.
1180 RelationCacheInitializePhase3();
1182 /* set up ACL framework (so CheckMyDatabase can check permissions) */
1186 * Re-read the pg_database row for our database, check permissions and set
1187 * up database-specific GUC settings. We can't do this until all the
1188 * database-access infrastructure is up. (Also, it wants to know if the
1189 * user is a superuser, so the above stuff has to happen first.)
1192 CheckMyDatabase(dbname
, am_superuser
, override_allow_connections
);
1195 * Now process any command-line switches and any additional GUC variable
1196 * settings passed in the startup packet. We couldn't do this before
1197 * because we didn't know if client is a superuser.
1199 if (MyProcPort
!= NULL
)
1200 process_startup_options(MyProcPort
, am_superuser
);
1202 /* Process pg_db_role_setting options */
1203 process_settings(MyDatabaseId
, GetSessionUserId());
1205 /* Apply PostAuthDelay as soon as we've read all options */
1206 if (PostAuthDelay
> 0)
1207 pg_usleep(PostAuthDelay
* 1000000L);
1210 * Initialize various default states that can't be set up until we've
1211 * selected the active user and gotten the right GUC settings.
1214 /* set default namespace search path */
1215 InitializeSearchPath();
1217 /* initialize client encoding */
1218 InitializeClientEncoding();
1220 /* Initialize this backend's session state. */
1221 InitializeSession();
1224 * If this is an interactive session, load any libraries that should be
1225 * preloaded at backend start. Since those are determined by GUCs, this
1226 * can't happen until GUC settings are complete, but we want it to happen
1227 * during the initial transaction in case anything that requires database
1228 * access needs to be done.
1230 if (load_session_libraries
)
1231 process_session_preload_libraries();
1233 /* report this backend in the PgBackendStatus array */
1237 /* close the transaction we started above */
1239 CommitTransactionCommand();
1243 * Process any command-line switches and any additional GUC variable
1244 * settings passed in the startup packet.
1247 process_startup_options(Port
*port
, bool am_superuser
)
1252 gucctx
= am_superuser
? PGC_SU_BACKEND
: PGC_BACKEND
;
1255 * First process any command-line switches that were included in the
1256 * startup packet, if we are in a regular backend.
1258 if (port
->cmdline_options
!= NULL
)
1261 * The maximum possible number of commandline arguments that could
1262 * come from port->cmdline_options is (strlen + 1) / 2; see
1269 maxac
= 2 + (strlen(port
->cmdline_options
) + 1) / 2;
1271 av
= (char **) palloc(maxac
* sizeof(char *));
1274 av
[ac
++] = "postgres";
1276 pg_split_opts(av
, &ac
, port
->cmdline_options
);
1282 (void) process_postgres_switches(ac
, av
, gucctx
, NULL
);
1286 * Process any additional GUC variable settings passed in startup packet.
1287 * These are handled exactly like command-line variables.
1289 gucopts
= list_head(port
->guc_options
);
1295 name
= lfirst(gucopts
);
1296 gucopts
= lnext(port
->guc_options
, gucopts
);
1298 value
= lfirst(gucopts
);
1299 gucopts
= lnext(port
->guc_options
, gucopts
);
1301 SetConfigOption(name
, value
, gucctx
, PGC_S_CLIENT
);
1306 * Load GUC settings from pg_db_role_setting.
1308 * We try specific settings for the database/role combination, as well as
1309 * general for this database and for this user.
1312 process_settings(Oid databaseid
, Oid roleid
)
1314 Relation relsetting
;
1317 if (!IsUnderPostmaster
)
1320 relsetting
= table_open(DbRoleSettingRelationId
, AccessShareLock
);
1322 /* read all the settings under the same snapshot for efficiency */
1323 snapshot
= RegisterSnapshot(GetCatalogSnapshot(DbRoleSettingRelationId
));
1325 /* Later settings are ignored if set earlier. */
1326 ApplySetting(snapshot
, databaseid
, roleid
, relsetting
, PGC_S_DATABASE_USER
);
1327 ApplySetting(snapshot
, InvalidOid
, roleid
, relsetting
, PGC_S_USER
);
1328 ApplySetting(snapshot
, databaseid
, InvalidOid
, relsetting
, PGC_S_DATABASE
);
1329 ApplySetting(snapshot
, InvalidOid
, InvalidOid
, relsetting
, PGC_S_GLOBAL
);
1331 UnregisterSnapshot(snapshot
);
1332 table_close(relsetting
, AccessShareLock
);
1336 * Backend-shutdown callback. Do cleanup that we want to be sure happens
1337 * before all the supporting modules begin to nail their doors shut via
1338 * their own callbacks.
1340 * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
1341 * via separate callbacks that execute before this one. We don't combine the
1342 * callbacks because we still want this one to happen if the user-level
1346 ShutdownPostgres(int code
, Datum arg
)
1348 /* Make sure we've killed any active transaction */
1349 AbortOutOfAnyTransaction();
1352 * User locks are not released by transaction end, so be sure to release
1355 LockReleaseAll(USER_LOCKMETHOD
, true);
1360 * STATEMENT_TIMEOUT handler: trigger a query-cancel interrupt.
1363 StatementTimeoutHandler(void)
1368 * During authentication the timeout is used to deal with
1369 * authentication_timeout - we want to quit in response to such timeouts.
1371 if (ClientAuthInProgress
)
1375 /* try to signal whole process group */
1376 kill(-MyProcPid
, sig
);
1378 kill(MyProcPid
, sig
);
1382 * LOCK_TIMEOUT handler: trigger a query-cancel interrupt.
1385 LockTimeoutHandler(void)
1388 /* try to signal whole process group */
1389 kill(-MyProcPid
, SIGINT
);
1391 kill(MyProcPid
, SIGINT
);
1395 IdleInTransactionSessionTimeoutHandler(void)
1397 IdleInTransactionSessionTimeoutPending
= true;
1398 InterruptPending
= true;
1403 IdleSessionTimeoutHandler(void)
1405 IdleSessionTimeoutPending
= true;
1406 InterruptPending
= true;
1411 IdleStatsUpdateTimeoutHandler(void)
1413 IdleStatsUpdateTimeoutPending
= true;
1414 InterruptPending
= true;
1419 ClientCheckTimeoutHandler(void)
1421 CheckClientConnectionPending
= true;
1422 InterruptPending
= true;
1427 * Returns true if at least one role is defined in this database cluster.
1430 ThereIsAtLeastOneRole(void)
1432 Relation pg_authid_rel
;
1436 pg_authid_rel
= table_open(AuthIdRelationId
, AccessShareLock
);
1438 scan
= table_beginscan_catalog(pg_authid_rel
, 0, NULL
);
1439 result
= (heap_getnext(scan
, ForwardScanDirection
) != NULL
);
1441 table_endscan(scan
);
1442 table_close(pg_authid_rel
, AccessShareLock
);