LCOV - code coverage report
Current view: top level - src/backend/utils/init - postinit.c (source / functions) Hit Total Coverage
Test: PostgreSQL 14devel Lines: 264 300 88.0 %
Date: 2020-11-27 12:05:55 Functions: 15 16 93.8 %
Legend: Lines: hit not hit

          Line data    Source code
       1             : /*-------------------------------------------------------------------------
       2             :  *
       3             :  * postinit.c
       4             :  *    postgres initialization utilities
       5             :  *
       6             :  * Portions Copyright (c) 1996-2020, PostgreSQL Global Development Group
       7             :  * Portions Copyright (c) 1994, Regents of the University of California
       8             :  *
       9             :  *
      10             :  * IDENTIFICATION
      11             :  *    src/backend/utils/init/postinit.c
      12             :  *
      13             :  *
      14             :  *-------------------------------------------------------------------------
      15             :  */
      16             : #include "postgres.h"
      17             : 
      18             : #include <ctype.h>
      19             : #include <fcntl.h>
      20             : #include <unistd.h>
      21             : 
      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 "catalog/catalog.h"
      31             : #include "catalog/namespace.h"
      32             : #include "catalog/pg_authid.h"
      33             : #include "catalog/pg_database.h"
      34             : #include "catalog/pg_db_role_setting.h"
      35             : #include "catalog/pg_tablespace.h"
      36             : #include "libpq/auth.h"
      37             : #include "libpq/libpq-be.h"
      38             : #include "mb/pg_wchar.h"
      39             : #include "miscadmin.h"
      40             : #include "pgstat.h"
      41             : #include "postmaster/autovacuum.h"
      42             : #include "postmaster/postmaster.h"
      43             : #include "replication/walsender.h"
      44             : #include "storage/bufmgr.h"
      45             : #include "storage/fd.h"
      46             : #include "storage/ipc.h"
      47             : #include "storage/lmgr.h"
      48             : #include "storage/proc.h"
      49             : #include "storage/procarray.h"
      50             : #include "storage/procsignal.h"
      51             : #include "storage/sinvaladt.h"
      52             : #include "storage/smgr.h"
      53             : #include "storage/sync.h"
      54             : #include "tcop/tcopprot.h"
      55             : #include "utils/acl.h"
      56             : #include "utils/fmgroids.h"
      57             : #include "utils/guc.h"
      58             : #include "utils/memutils.h"
      59             : #include "utils/pg_locale.h"
      60             : #include "utils/portal.h"
      61             : #include "utils/ps_status.h"
      62             : #include "utils/snapmgr.h"
      63             : #include "utils/syscache.h"
      64             : #include "utils/timeout.h"
      65             : 
      66             : static HeapTuple GetDatabaseTuple(const char *dbname);
      67             : static HeapTuple GetDatabaseTupleByOid(Oid dboid);
      68             : static void PerformAuthentication(Port *port);
      69             : static void CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections);
      70             : static void InitCommunication(void);
      71             : static void ShutdownPostgres(int code, Datum arg);
      72             : static void StatementTimeoutHandler(void);
      73             : static void LockTimeoutHandler(void);
      74             : static void IdleInTransactionSessionTimeoutHandler(void);
      75             : static bool ThereIsAtLeastOneRole(void);
      76             : static void process_startup_options(Port *port, bool am_superuser);
      77             : static void process_settings(Oid databaseid, Oid roleid);
      78             : 
      79             : 
      80             : /*** InitPostgres support ***/
      81             : 
      82             : 
      83             : /*
      84             :  * GetDatabaseTuple -- fetch the pg_database row for a database
      85             :  *
      86             :  * This is used during backend startup when we don't yet have any access to
      87             :  * system catalogs in general.  In the worst case, we can seqscan pg_database
      88             :  * using nothing but the hard-wired descriptor that relcache.c creates for
      89             :  * pg_database.  In more typical cases, relcache.c was able to load
      90             :  * descriptors for both pg_database and its indexes from the shared relcache
      91             :  * cache file, and so we can do an indexscan.  criticalSharedRelcachesBuilt
      92             :  * tells whether we got the cached descriptors.
      93             :  */
      94             : static HeapTuple
      95       18798 : GetDatabaseTuple(const char *dbname)
      96             : {
      97             :     HeapTuple   tuple;
      98             :     Relation    relation;
      99             :     SysScanDesc scan;
     100             :     ScanKeyData key[1];
     101             : 
     102             :     /*
     103             :      * form a scan key
     104             :      */
     105       18798 :     ScanKeyInit(&key[0],
     106             :                 Anum_pg_database_datname,
     107             :                 BTEqualStrategyNumber, F_NAMEEQ,
     108             :                 CStringGetDatum(dbname));
     109             : 
     110             :     /*
     111             :      * Open pg_database and fetch a tuple.  Force heap scan if we haven't yet
     112             :      * built the critical shared relcache entries (i.e., we're starting up
     113             :      * without a shared relcache cache file).
     114             :      */
     115       18798 :     relation = table_open(DatabaseRelationId, AccessShareLock);
     116       18798 :     scan = systable_beginscan(relation, DatabaseNameIndexId,
     117             :                               criticalSharedRelcachesBuilt,
     118             :                               NULL,
     119             :                               1, key);
     120             : 
     121       18798 :     tuple = systable_getnext(scan);
     122             : 
     123             :     /* Must copy tuple before releasing buffer */
     124       18798 :     if (HeapTupleIsValid(tuple))
     125       18774 :         tuple = heap_copytuple(tuple);
     126             : 
     127             :     /* all done */
     128       18798 :     systable_endscan(scan);
     129       18798 :     table_close(relation, AccessShareLock);
     130             : 
     131       18798 :     return tuple;
     132             : }
     133             : 
     134             : /*
     135             :  * GetDatabaseTupleByOid -- as above, but search by database OID
     136             :  */
     137             : static HeapTuple
     138        1854 : GetDatabaseTupleByOid(Oid dboid)
     139             : {
     140             :     HeapTuple   tuple;
     141             :     Relation    relation;
     142             :     SysScanDesc scan;
     143             :     ScanKeyData key[1];
     144             : 
     145             :     /*
     146             :      * form a scan key
     147             :      */
     148        1854 :     ScanKeyInit(&key[0],
     149             :                 Anum_pg_database_oid,
     150             :                 BTEqualStrategyNumber, F_OIDEQ,
     151             :                 ObjectIdGetDatum(dboid));
     152             : 
     153             :     /*
     154             :      * Open pg_database and fetch a tuple.  Force heap scan if we haven't yet
     155             :      * built the critical shared relcache entries (i.e., we're starting up
     156             :      * without a shared relcache cache file).
     157             :      */
     158        1854 :     relation = table_open(DatabaseRelationId, AccessShareLock);
     159        1854 :     scan = systable_beginscan(relation, DatabaseOidIndexId,
     160             :                               criticalSharedRelcachesBuilt,
     161             :                               NULL,
     162             :                               1, key);
     163             : 
     164        1854 :     tuple = systable_getnext(scan);
     165             : 
     166             :     /* Must copy tuple before releasing buffer */
     167        1854 :     if (HeapTupleIsValid(tuple))
     168        1854 :         tuple = heap_copytuple(tuple);
     169             : 
     170             :     /* all done */
     171        1854 :     systable_endscan(scan);
     172        1854 :     table_close(relation, AccessShareLock);
     173             : 
     174        1854 :     return tuple;
     175             : }
     176             : 
     177             : 
     178             : /*
     179             :  * PerformAuthentication -- authenticate a remote client
     180             :  *
     181             :  * returns: nothing.  Will not return at all if there's any failure.
     182             :  */
     183             : static void
     184        8528 : PerformAuthentication(Port *port)
     185             : {
     186             :     /* This should be set already, but let's make sure */
     187        8528 :     ClientAuthInProgress = true;    /* limit visibility of log messages */
     188             : 
     189             :     /*
     190             :      * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
     191             :      * etcetera from the postmaster, and have to load them ourselves.
     192             :      *
     193             :      * FIXME: [fork/exec] Ugh.  Is there a way around this overhead?
     194             :      */
     195             : #ifdef EXEC_BACKEND
     196             : 
     197             :     /*
     198             :      * load_hba() and load_ident() want to work within the PostmasterContext,
     199             :      * so create that if it doesn't exist (which it won't).  We'll delete it
     200             :      * again later, in PostgresMain.
     201             :      */
     202             :     if (PostmasterContext == NULL)
     203             :         PostmasterContext = AllocSetContextCreate(TopMemoryContext,
     204             :                                                   "Postmaster",
     205             :                                                   ALLOCSET_DEFAULT_SIZES);
     206             : 
     207             :     if (!load_hba())
     208             :     {
     209             :         /*
     210             :          * It makes no sense to continue if we fail to load the HBA file,
     211             :          * since there is no way to connect to the database in this case.
     212             :          */
     213             :         ereport(FATAL,
     214             :                 (errmsg("could not load pg_hba.conf")));
     215             :     }
     216             : 
     217             :     if (!load_ident())
     218             :     {
     219             :         /*
     220             :          * It is ok to continue if we fail to load the IDENT file, although it
     221             :          * means that you cannot log in using any of the authentication
     222             :          * methods that need a user name mapping. load_ident() already logged
     223             :          * the details of error to the log.
     224             :          */
     225             :     }
     226             : #endif
     227             : 
     228             :     /*
     229             :      * Set up a timeout in case a buggy or malicious client fails to respond
     230             :      * during authentication.  Since we're inside a transaction and might do
     231             :      * database access, we have to use the statement_timeout infrastructure.
     232             :      */
     233        8528 :     enable_timeout_after(STATEMENT_TIMEOUT, AuthenticationTimeout * 1000);
     234             : 
     235             :     /*
     236             :      * Now perform authentication exchange.
     237             :      */
     238        8528 :     set_ps_display("authentication");
     239        8528 :     ClientAuthentication(port); /* might not return, if failure */
     240             : 
     241             :     /*
     242             :      * Done with authentication.  Disable the timeout, and log if needed.
     243             :      */
     244        8482 :     disable_timeout(STATEMENT_TIMEOUT, false);
     245             : 
     246        8482 :     if (Log_connections)
     247             :     {
     248          80 :         if (am_walsender)
     249             :         {
     250             : #ifdef USE_SSL
     251           0 :             if (port->ssl_in_use)
     252           0 :                 ereport(LOG,
     253             :                         (port->application_name != NULL
     254             :                          ? errmsg("replication connection authorized: user=%s application_name=%s SSL enabled (protocol=%s, cipher=%s, bits=%d, compression=%s)",
     255             :                                   port->user_name,
     256             :                                   port->application_name,
     257             :                                   be_tls_get_version(port),
     258             :                                   be_tls_get_cipher(port),
     259             :                                   be_tls_get_cipher_bits(port),
     260             :                                   be_tls_get_compression(port) ? _("on") : _("off"))
     261             :                          : errmsg("replication connection authorized: user=%s SSL enabled (protocol=%s, cipher=%s, bits=%d, compression=%s)",
     262             :                                   port->user_name,
     263             :                                   be_tls_get_version(port),
     264             :                                   be_tls_get_cipher(port),
     265             :                                   be_tls_get_cipher_bits(port),
     266             :                                   be_tls_get_compression(port) ? _("on") : _("off"))));
     267             :             else
     268             : #endif
     269           0 :                 ereport(LOG,
     270             :                         (port->application_name != NULL
     271             :                          ? errmsg("replication connection authorized: user=%s application_name=%s",
     272             :                                   port->user_name,
     273             :                                   port->application_name)
     274             :                          : errmsg("replication connection authorized: user=%s",
     275             :                                   port->user_name)));
     276             :         }
     277             :         else
     278             :         {
     279             : #ifdef USE_SSL
     280          80 :             if (port->ssl_in_use)
     281          64 :                 ereport(LOG,
     282             :                         (port->application_name != NULL
     283             :                          ? errmsg("connection authorized: user=%s database=%s application_name=%s SSL enabled (protocol=%s, cipher=%s, bits=%d, compression=%s)",
     284             :                                   port->user_name, port->database_name, port->application_name,
     285             :                                   be_tls_get_version(port),
     286             :                                   be_tls_get_cipher(port),
     287             :                                   be_tls_get_cipher_bits(port),
     288             :                                   be_tls_get_compression(port) ? _("on") : _("off"))
     289             :                          : errmsg("connection authorized: user=%s database=%s SSL enabled (protocol=%s, cipher=%s, bits=%d, compression=%s)",
     290             :                                   port->user_name, port->database_name,
     291             :                                   be_tls_get_version(port),
     292             :                                   be_tls_get_cipher(port),
     293             :                                   be_tls_get_cipher_bits(port),
     294             :                                   be_tls_get_compression(port) ? _("on") : _("off"))));
     295             :             else
     296             : #endif
     297          16 :                 ereport(LOG,
     298             :                         (port->application_name != NULL
     299             :                          ? errmsg("connection authorized: user=%s database=%s application_name=%s",
     300             :                                   port->user_name, port->database_name, port->application_name)
     301             :                          : errmsg("connection authorized: user=%s database=%s",
     302             :                                   port->user_name, port->database_name)));
     303             :         }
     304             :     }
     305             : 
     306        8482 :     set_ps_display("startup");
     307             : 
     308        8482 :     ClientAuthInProgress = false;   /* client_min_messages is active now */
     309        8482 : }
     310             : 
     311             : 
     312             : /*
     313             :  * CheckMyDatabase -- fetch information from the pg_database entry for our DB
     314             :  */
     315             : static void
     316       10314 : CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections)
     317             : {
     318             :     HeapTuple   tup;
     319             :     Form_pg_database dbform;
     320             :     char       *collate;
     321             :     char       *ctype;
     322             : 
     323             :     /* Fetch our pg_database row normally, via syscache */
     324       10314 :     tup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
     325       10314 :     if (!HeapTupleIsValid(tup))
     326           0 :         elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
     327       10314 :     dbform = (Form_pg_database) GETSTRUCT(tup);
     328             : 
     329             :     /* This recheck is strictly paranoia */
     330       10314 :     if (strcmp(name, NameStr(dbform->datname)) != 0)
     331           0 :         ereport(FATAL,
     332             :                 (errcode(ERRCODE_UNDEFINED_DATABASE),
     333             :                  errmsg("database \"%s\" has disappeared from pg_database",
     334             :                         name),
     335             :                  errdetail("Database OID %u now seems to belong to \"%s\".",
     336             :                            MyDatabaseId, NameStr(dbform->datname))));
     337             : 
     338             :     /*
     339             :      * Check permissions to connect to the database.
     340             :      *
     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;".
     344             :      *
     345             :      * We do not enforce them for autovacuum worker processes either.
     346             :      */
     347       10314 :     if (IsUnderPostmaster && !IsAutoVacuumWorkerProcess())
     348             :     {
     349             :         /*
     350             :          * Check that the database is currently allowing connections.
     351             :          */
     352        9846 :         if (!dbform->datallowconn && !override_allow_connections)
     353           0 :             ereport(FATAL,
     354             :                     (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
     355             :                      errmsg("database \"%s\" is not currently accepting connections",
     356             :                             name)));
     357             : 
     358             :         /*
     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.)
     362             :          */
     363       10012 :         if (!am_superuser &&
     364         166 :             pg_database_aclcheck(MyDatabaseId, GetUserId(),
     365             :                                  ACL_CONNECT) != ACLCHECK_OK)
     366           0 :             ereport(FATAL,
     367             :                     (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     368             :                      errmsg("permission denied for database \"%s\"", name),
     369             :                      errdetail("User does not have CONNECT privilege.")));
     370             : 
     371             :         /*
     372             :          * Check connection limit for this database.
     373             :          *
     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.
     380             :          */
     381        9846 :         if (dbform->datconnlimit >= 0 &&
     382           0 :             !am_superuser &&
     383           0 :             CountDBConnections(MyDatabaseId) > dbform->datconnlimit)
     384           0 :             ereport(FATAL,
     385             :                     (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
     386             :                      errmsg("too many connections for database \"%s\"",
     387             :                             name)));
     388             :     }
     389             : 
     390             :     /*
     391             :      * OK, we're golden.  Next to-do item is to save the encoding info out of
     392             :      * the pg_database tuple.
     393             :      */
     394       10314 :     SetDatabaseEncoding(dbform->encoding);
     395             :     /* Record it as a GUC internal option, too */
     396       10314 :     SetConfigOption("server_encoding", GetDatabaseEncodingName(),
     397             :                     PGC_INTERNAL, PGC_S_OVERRIDE);
     398             :     /* If we have no other source of client_encoding, use server encoding */
     399       10314 :     SetConfigOption("client_encoding", GetDatabaseEncodingName(),
     400             :                     PGC_BACKEND, PGC_S_DYNAMIC_DEFAULT);
     401             : 
     402             :     /* assign locale variables */
     403       10314 :     collate = NameStr(dbform->datcollate);
     404       10314 :     ctype = NameStr(dbform->datctype);
     405             : 
     406       10314 :     if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
     407           0 :         ereport(FATAL,
     408             :                 (errmsg("database locale is incompatible with operating system"),
     409             :                  errdetail("The database was initialized with LC_COLLATE \"%s\", "
     410             :                            " which is not recognized by setlocale().", collate),
     411             :                  errhint("Recreate the database with another locale or install the missing locale.")));
     412             : 
     413       10314 :     if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
     414           0 :         ereport(FATAL,
     415             :                 (errmsg("database locale is incompatible with operating system"),
     416             :                  errdetail("The database was initialized with LC_CTYPE \"%s\", "
     417             :                            " which is not recognized by setlocale().", ctype),
     418             :                  errhint("Recreate the database with another locale or install the missing locale.")));
     419             : 
     420             :     /* Make the locale settings visible as GUC variables, too */
     421       10314 :     SetConfigOption("lc_collate", collate, PGC_INTERNAL, PGC_S_OVERRIDE);
     422       10314 :     SetConfigOption("lc_ctype", ctype, PGC_INTERNAL, PGC_S_OVERRIDE);
     423             : 
     424       10314 :     check_strxfrm_bug();
     425             : 
     426       10314 :     ReleaseSysCache(tup);
     427       10314 : }
     428             : 
     429             : 
     430             : 
     431             : /* --------------------------------
     432             :  *      InitCommunication
     433             :  *
     434             :  *      This routine initializes stuff needed for ipc, locking, etc.
     435             :  *      it should be called something more informative.
     436             :  * --------------------------------
     437             :  */
     438             : static void
     439       15022 : InitCommunication(void)
     440             : {
     441             :     /*
     442             :      * initialize shared memory and semaphores appropriately.
     443             :      */
     444       15022 :     if (!IsUnderPostmaster)     /* postmaster already did this */
     445             :     {
     446             :         /*
     447             :          * We're running a postgres bootstrap process or a standalone backend,
     448             :          * so we need to set up shmem.
     449             :          */
     450        1604 :         CreateSharedMemoryAndSemaphores();
     451             :     }
     452       15020 : }
     453             : 
     454             : 
     455             : /*
     456             :  * pg_split_opts -- split a string of options and append it to an argv array
     457             :  *
     458             :  * The caller is responsible for ensuring the argv array is large enough.  The
     459             :  * maximum possible number of arguments added by this routine is
     460             :  * (strlen(optstr) + 1) / 2.
     461             :  *
     462             :  * Because some option values can contain spaces we allow escaping using
     463             :  * backslashes, with \\ representing a literal backslash.
     464             :  */
     465             : void
     466        3432 : pg_split_opts(char **argv, int *argcp, const char *optstr)
     467             : {
     468             :     StringInfoData s;
     469             : 
     470        3432 :     initStringInfo(&s);
     471             : 
     472       10246 :     while (*optstr)
     473             :     {
     474        6814 :         bool        last_was_escape = false;
     475             : 
     476        6814 :         resetStringInfo(&s);
     477             : 
     478             :         /* skip over leading space */
     479       13426 :         while (isspace((unsigned char) *optstr))
     480        6612 :             optstr++;
     481             : 
     482        6814 :         if (*optstr == '\0')
     483           0 :             break;
     484             : 
     485             :         /*
     486             :          * Parse a single option, stopping at the first space, unless it's
     487             :          * escaped.
     488             :          */
     489      117248 :         while (*optstr)
     490             :         {
     491      113816 :             if (isspace((unsigned char) *optstr) && !last_was_escape)
     492        3382 :                 break;
     493             : 
     494      110434 :             if (!last_was_escape && *optstr == '\\')
     495           0 :                 last_was_escape = true;
     496             :             else
     497             :             {
     498      110434 :                 last_was_escape = false;
     499      110434 :                 appendStringInfoChar(&s, *optstr);
     500             :             }
     501             : 
     502      110434 :             optstr++;
     503             :         }
     504             : 
     505             :         /* now store the option in the next argv[] position */
     506        6814 :         argv[(*argcp)++] = pstrdup(s.data);
     507             :     }
     508             : 
     509        3432 :     pfree(s.data);
     510        3432 : }
     511             : 
     512             : /*
     513             :  * Initialize MaxBackends value from config options.
     514             :  *
     515             :  * This must be called after modules have had the chance to register background
     516             :  * workers in shared_preload_libraries, and before shared memory size is
     517             :  * determined.
     518             :  *
     519             :  * Note that in EXEC_BACKEND environment, the value is passed down from
     520             :  * postmaster to subprocesses via BackendParameters in SubPostmasterMain; only
     521             :  * postmaster itself and processes not under postmaster control should call
     522             :  * this.
     523             :  */
     524             : void
     525        2372 : InitializeMaxBackends(void)
     526             : {
     527             :     Assert(MaxBackends == 0);
     528             : 
     529             :     /* the extra unit accounts for the autovacuum launcher */
     530        4744 :     MaxBackends = MaxConnections + autovacuum_max_workers + 1 +
     531        2372 :         max_worker_processes + max_wal_senders;
     532             : 
     533             :     /* internal error because the values were all checked previously */
     534        2372 :     if (MaxBackends > MAX_BACKENDS)
     535           0 :         elog(ERROR, "too many backends configured");
     536        2372 : }
     537             : 
     538             : /*
     539             :  * Early initialization of a backend (either standalone or under postmaster).
     540             :  * This happens even before InitPostgres.
     541             :  *
     542             :  * This is separate from InitPostgres because it is also called by auxiliary
     543             :  * processes, such as the background writer process, which may not call
     544             :  * InitPostgres at all.
     545             :  */
     546             : void
     547       15022 : BaseInit(void)
     548             : {
     549             :     /*
     550             :      * Attach to shared memory and semaphores, and initialize our
     551             :      * input/output/debugging file descriptors.
     552             :      */
     553       15022 :     InitCommunication();
     554       15020 :     DebugFileOpen();
     555             : 
     556             :     /* Do local initialization of file, storage and buffer managers */
     557       15020 :     InitFileAccess();
     558       15020 :     InitSync();
     559       15020 :     smgrinit();
     560       15020 :     InitBufferPoolAccess();
     561       15020 : }
     562             : 
     563             : 
     564             : /* --------------------------------
     565             :  * InitPostgres
     566             :  *      Initialize POSTGRES.
     567             :  *
     568             :  * The database can be specified by name, using the in_dbname parameter, or by
     569             :  * OID, using the dboid parameter.  In the latter case, the actual database
     570             :  * name can be returned to the caller in out_dbname.  If out_dbname isn't
     571             :  * NULL, it must point to a buffer of size NAMEDATALEN.
     572             :  *
     573             :  * Similarly, the username can be passed by name, using the username parameter,
     574             :  * or by OID using the useroid parameter.
     575             :  *
     576             :  * In bootstrap mode no parameters are used.  The autovacuum launcher process
     577             :  * doesn't use any parameters either, because it only goes far enough to be
     578             :  * able to read pg_database; it doesn't connect to any particular database.
     579             :  * In walsender mode only username is used.
     580             :  *
     581             :  * As of PostgreSQL 8.2, we expect InitProcess() was already called, so we
     582             :  * already have a PGPROC struct ... but it's not completely filled in yet.
     583             :  *
     584             :  * Note:
     585             :  *      Be very careful with the order of calls in the InitPostgres function.
     586             :  * --------------------------------
     587             :  */
     588             : void
     589       11990 : InitPostgres(const char *in_dbname, Oid dboid, const char *username,
     590             :              Oid useroid, char *out_dbname, bool override_allow_connections)
     591             : {
     592       11990 :     bool        bootstrap = IsBootstrapProcessingMode();
     593             :     bool        am_superuser;
     594             :     char       *fullpath;
     595             :     char        dbname[NAMEDATALEN];
     596             : 
     597       11990 :     elog(DEBUG3, "InitPostgres");
     598             : 
     599             :     /*
     600             :      * Add my PGPROC struct to the ProcArray.
     601             :      *
     602             :      * Once I have done this, I am visible to other backends!
     603             :      */
     604       11990 :     InitProcessPhase2();
     605             : 
     606             :     /*
     607             :      * Initialize my entry in the shared-invalidation manager's array of
     608             :      * per-backend data.
     609             :      *
     610             :      * Sets up MyBackendId, a unique backend identifier.
     611             :      */
     612       11990 :     MyBackendId = InvalidBackendId;
     613             : 
     614       11990 :     SharedInvalBackendInit(false);
     615             : 
     616       11990 :     if (MyBackendId > MaxBackends || MyBackendId <= 0)
     617           0 :         elog(FATAL, "bad backend ID: %d", MyBackendId);
     618             : 
     619             :     /* Now that we have a BackendId, we can participate in ProcSignal */
     620       11990 :     ProcSignalInit(MyBackendId);
     621             : 
     622             :     /*
     623             :      * Also set up timeout handlers needed for backend operation.  We need
     624             :      * these in every case except bootstrap.
     625             :      */
     626       11990 :     if (!bootstrap)
     627             :     {
     628       11594 :         RegisterTimeout(DEADLOCK_TIMEOUT, CheckDeadLockAlert);
     629       11594 :         RegisterTimeout(STATEMENT_TIMEOUT, StatementTimeoutHandler);
     630       11594 :         RegisterTimeout(LOCK_TIMEOUT, LockTimeoutHandler);
     631       11594 :         RegisterTimeout(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
     632             :                         IdleInTransactionSessionTimeoutHandler);
     633             :     }
     634             : 
     635             :     /*
     636             :      * bufmgr needs another initialization call too
     637             :      */
     638       11990 :     InitBufferPoolBackend();
     639             : 
     640             :     /*
     641             :      * Initialize local process's access to XLOG.
     642             :      */
     643       11990 :     if (IsUnderPostmaster)
     644             :     {
     645             :         /*
     646             :          * The postmaster already started the XLOG machinery, but we need to
     647             :          * call InitXLOGAccess(), if the system isn't in hot-standby mode.
     648             :          * This is handled by calling RecoveryInProgress and ignoring the
     649             :          * result.
     650             :          */
     651       11180 :         (void) RecoveryInProgress();
     652             :     }
     653             :     else
     654             :     {
     655             :         /*
     656             :          * We are either a bootstrap process or a standalone backend. Either
     657             :          * way, start up the XLOG machinery, and register to have it closed
     658             :          * down at exit.
     659             :          *
     660             :          * We don't yet have an aux-process resource owner, but StartupXLOG
     661             :          * and ShutdownXLOG will need one.  Hence, create said resource owner
     662             :          * (and register a callback to clean it up after ShutdownXLOG runs).
     663             :          */
     664         810 :         CreateAuxProcessResourceOwner();
     665             : 
     666         810 :         StartupXLOG();
     667             :         /* Release (and warn about) any buffer pins leaked in StartupXLOG */
     668         810 :         ReleaseAuxProcessResources(true);
     669             :         /* Reset CurrentResourceOwner to nothing for the moment */
     670         810 :         CurrentResourceOwner = NULL;
     671             : 
     672         810 :         on_shmem_exit(ShutdownXLOG, 0);
     673             :     }
     674             : 
     675             :     /*
     676             :      * Initialize the relation cache and the system catalog caches.  Note that
     677             :      * no catalog access happens here; we only set up the hashtable structure.
     678             :      * We must do this before starting a transaction because transaction abort
     679             :      * would try to touch these hashtables.
     680             :      */
     681       11990 :     RelationCacheInitialize();
     682       11990 :     InitCatalogCache();
     683       11990 :     InitPlanCache();
     684             : 
     685             :     /* Initialize portal manager */
     686       11990 :     EnablePortalManager();
     687             : 
     688             :     /* Initialize stats collection --- must happen before first xact */
     689       11990 :     if (!bootstrap)
     690       11594 :         pgstat_initialize();
     691             : 
     692             :     /*
     693             :      * Load relcache entries for the shared system catalogs.  This must create
     694             :      * at least entries for pg_database and catalogs used for authentication.
     695             :      */
     696       11990 :     RelationCacheInitializePhase2();
     697             : 
     698             :     /*
     699             :      * Set up process-exit callback to do pre-shutdown cleanup.  This is the
     700             :      * first before_shmem_exit callback we register; thus, this will be the
     701             :      * last thing we do before low-level modules like the buffer manager begin
     702             :      * to close down.  We need to have this in place before we begin our first
     703             :      * transaction --- if we fail during the initialization transaction, as is
     704             :      * entirely possible, we need the AbortTransaction call to clean up.
     705             :      */
     706       11990 :     before_shmem_exit(ShutdownPostgres, 0);
     707             : 
     708             :     /* The autovacuum launcher is done here */
     709       11990 :     if (IsAutoVacuumLauncherProcess())
     710             :     {
     711             :         /* report this backend in the PgBackendStatus array */
     712         388 :         pgstat_bestart();
     713             : 
     714        1208 :         return;
     715             :     }
     716             : 
     717             :     /*
     718             :      * Start a new transaction here before first access to db, and get a
     719             :      * snapshot.  We don't have a use for the snapshot itself, but we're
     720             :      * interested in the secondary effect that it sets RecentGlobalXmin. (This
     721             :      * is critical for anything that reads heap pages, because HOT may decide
     722             :      * to prune them even if the process doesn't attempt to modify any
     723             :      * tuples.)
     724             :      *
     725             :      * FIXME: This comment is inaccurate / the code buggy. A snapshot that is
     726             :      * not pushed/active does not reliably prevent HOT pruning (->xmin could
     727             :      * e.g. be cleared when cache invalidations are processed).
     728             :      */
     729       11602 :     if (!bootstrap)
     730             :     {
     731             :         /* statement_timestamp must be set for timeouts to work correctly */
     732       11206 :         SetCurrentStatementStartTimestamp();
     733       11206 :         StartTransactionCommand();
     734             : 
     735             :         /*
     736             :          * transaction_isolation will have been set to the default by the
     737             :          * above.  If the default is "serializable", and we are in hot
     738             :          * standby, we will fail if we don't change it to something lower.
     739             :          * Fortunately, "read committed" is plenty good enough.
     740             :          */
     741       11206 :         XactIsoLevel = XACT_READ_COMMITTED;
     742             : 
     743       11206 :         (void) GetTransactionSnapshot();
     744             :     }
     745             : 
     746             :     /*
     747             :      * Perform client authentication if necessary, then figure out our
     748             :      * postgres user ID, and see if we are a superuser.
     749             :      *
     750             :      * In standalone mode and in autovacuum worker processes, we use a fixed
     751             :      * ID, otherwise we figure it out from the authenticated user name.
     752             :      */
     753       11602 :     if (bootstrap || IsAutoVacuumWorkerProcess())
     754             :     {
     755         450 :         InitializeSessionUserIdStandalone();
     756         450 :         am_superuser = true;
     757             :     }
     758       11152 :     else if (!IsUnderPostmaster)
     759             :     {
     760         414 :         InitializeSessionUserIdStandalone();
     761         414 :         am_superuser = true;
     762         414 :         if (!ThereIsAtLeastOneRole())
     763           0 :             ereport(WARNING,
     764             :                     (errcode(ERRCODE_UNDEFINED_OBJECT),
     765             :                      errmsg("no roles are defined in this database system"),
     766             :                      errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
     767             :                              username != NULL ? username : "postgres")));
     768             :     }
     769       10738 :     else if (IsBackgroundWorker)
     770             :     {
     771        2210 :         if (username == NULL && !OidIsValid(useroid))
     772             :         {
     773         410 :             InitializeSessionUserIdStandalone();
     774         410 :             am_superuser = true;
     775             :         }
     776             :         else
     777             :         {
     778        1800 :             InitializeSessionUserId(username, useroid);
     779        1800 :             am_superuser = superuser();
     780             :         }
     781             :     }
     782             :     else
     783             :     {
     784             :         /* normal multiuser case */
     785             :         Assert(MyProcPort != NULL);
     786        8528 :         PerformAuthentication(MyProcPort);
     787        8482 :         InitializeSessionUserId(username, useroid);
     788        8480 :         am_superuser = superuser();
     789             :     }
     790             : 
     791             :     /*
     792             :      * If we're trying to shut down, only superusers can connect, and new
     793             :      * replication connections are not allowed.
     794             :      */
     795       11554 :     if ((!am_superuser || am_walsender) &&
     796         866 :         MyProcPort != NULL &&
     797         866 :         MyProcPort->canAcceptConnections == CAC_SUPERUSER)
     798             :     {
     799           0 :         if (am_walsender)
     800           0 :             ereport(FATAL,
     801             :                     (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     802             :                      errmsg("new replication connections are not allowed during database shutdown")));
     803             :         else
     804           0 :             ereport(FATAL,
     805             :                     (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     806             :                      errmsg("must be superuser to connect during database shutdown")));
     807             :     }
     808             : 
     809             :     /*
     810             :      * Binary upgrades only allowed super-user connections
     811             :      */
     812       11554 :     if (IsBinaryUpgrade && !am_superuser)
     813             :     {
     814           0 :         ereport(FATAL,
     815             :                 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     816             :                  errmsg("must be superuser to connect in binary upgrade mode")));
     817             :     }
     818             : 
     819             :     /*
     820             :      * The last few connection slots are reserved for superusers.  Replication
     821             :      * connections are drawn from slots reserved with max_wal_senders and not
     822             :      * limited by max_connections or superuser_reserved_connections.
     823             :      */
     824       11554 :     if (!am_superuser && !am_walsender &&
     825         174 :         ReservedBackends > 0 &&
     826         174 :         !HaveNFreeProcs(ReservedBackends))
     827           0 :         ereport(FATAL,
     828             :                 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
     829             :                  errmsg("remaining connection slots are reserved for non-replication superuser connections")));
     830             : 
     831             :     /* Check replication permissions needed for walsender processes. */
     832       11554 :     if (am_walsender)
     833             :     {
     834             :         Assert(!bootstrap);
     835             : 
     836         692 :         if (!superuser() && !has_rolreplication(GetUserId()))
     837           0 :             ereport(FATAL,
     838             :                     (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
     839             :                      errmsg("must be superuser or replication role to start walsender")));
     840             :     }
     841             : 
     842             :     /*
     843             :      * If this is a plain walsender only supporting physical replication, we
     844             :      * don't want to connect to any particular database. Just finish the
     845             :      * backend startup by processing any options from the startup packet, and
     846             :      * we're done.
     847             :      */
     848       11554 :     if (am_walsender && !am_db_walsender)
     849             :     {
     850             :         /* process any options passed in the startup packet */
     851         416 :         if (MyProcPort != NULL)
     852         416 :             process_startup_options(MyProcPort, am_superuser);
     853             : 
     854             :         /* Apply PostAuthDelay as soon as we've read all options */
     855         416 :         if (PostAuthDelay > 0)
     856           0 :             pg_usleep(PostAuthDelay * 1000000L);
     857             : 
     858             :         /* initialize client encoding */
     859         416 :         InitializeClientEncoding();
     860             : 
     861             :         /* report this backend in the PgBackendStatus array */
     862         416 :         pgstat_bestart();
     863             : 
     864             :         /* close the transaction we started above */
     865         416 :         CommitTransactionCommand();
     866             : 
     867         416 :         return;
     868             :     }
     869             : 
     870             :     /*
     871             :      * Set up the global variables holding database id and default tablespace.
     872             :      * But note we won't actually try to touch the database just yet.
     873             :      *
     874             :      * We take a shortcut in the bootstrap case, otherwise we have to look up
     875             :      * the db's entry in pg_database.
     876             :      */
     877       11138 :     if (bootstrap)
     878             :     {
     879         396 :         MyDatabaseId = TemplateDbOid;
     880         396 :         MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
     881             :     }
     882       10742 :     else if (in_dbname != NULL)
     883             :     {
     884             :         HeapTuple   tuple;
     885             :         Form_pg_database dbform;
     886             : 
     887        8484 :         tuple = GetDatabaseTuple(in_dbname);
     888        8484 :         if (!HeapTupleIsValid(tuple))
     889          24 :             ereport(FATAL,
     890             :                     (errcode(ERRCODE_UNDEFINED_DATABASE),
     891             :                      errmsg("database \"%s\" does not exist", in_dbname)));
     892        8460 :         dbform = (Form_pg_database) GETSTRUCT(tuple);
     893        8460 :         MyDatabaseId = dbform->oid;
     894        8460 :         MyDatabaseTableSpace = dbform->dattablespace;
     895             :         /* take database name from the caller, just for paranoia */
     896        8460 :         strlcpy(dbname, in_dbname, sizeof(dbname));
     897             :     }
     898        2258 :     else if (OidIsValid(dboid))
     899             :     {
     900             :         /* caller specified database by OID */
     901             :         HeapTuple   tuple;
     902             :         Form_pg_database dbform;
     903             : 
     904        1854 :         tuple = GetDatabaseTupleByOid(dboid);
     905        1854 :         if (!HeapTupleIsValid(tuple))
     906           0 :             ereport(FATAL,
     907             :                     (errcode(ERRCODE_UNDEFINED_DATABASE),
     908             :                      errmsg("database %u does not exist", dboid)));
     909        1854 :         dbform = (Form_pg_database) GETSTRUCT(tuple);
     910        1854 :         MyDatabaseId = dbform->oid;
     911        1854 :         MyDatabaseTableSpace = dbform->dattablespace;
     912             :         Assert(MyDatabaseId == dboid);
     913        1854 :         strlcpy(dbname, NameStr(dbform->datname), sizeof(dbname));
     914             :         /* pass the database name back to the caller */
     915        1854 :         if (out_dbname)
     916          54 :             strcpy(out_dbname, dbname);
     917             :     }
     918             :     else
     919             :     {
     920             :         /*
     921             :          * If this is a background worker not bound to any particular
     922             :          * database, we're done now.  Everything that follows only makes sense
     923             :          * if we are bound to a specific database.  We do need to close the
     924             :          * transaction we started before returning.
     925             :          */
     926         404 :         if (!bootstrap)
     927             :         {
     928         404 :             pgstat_bestart();
     929         404 :             CommitTransactionCommand();
     930             :         }
     931         404 :         return;
     932             :     }
     933             : 
     934             :     /*
     935             :      * Now, take a writer's lock on the database we are trying to connect to.
     936             :      * If there is a concurrently running DROP DATABASE on that database, this
     937             :      * will block us until it finishes (and has committed its update of
     938             :      * pg_database).
     939             :      *
     940             :      * Note that the lock is not held long, only until the end of this startup
     941             :      * transaction.  This is OK since we will advertise our use of the
     942             :      * database in the ProcArray before dropping the lock (in fact, that's the
     943             :      * next thing to do).  Anyone trying a DROP DATABASE after this point will
     944             :      * see us in the array once they have the lock.  Ordering is important for
     945             :      * this because we don't want to advertise ourselves as being in this
     946             :      * database until we have the lock; otherwise we create what amounts to a
     947             :      * deadlock with CountOtherDBBackends().
     948             :      *
     949             :      * Note: use of RowExclusiveLock here is reasonable because we envision
     950             :      * our session as being a concurrent writer of the database.  If we had a
     951             :      * way of declaring a session as being guaranteed-read-only, we could use
     952             :      * AccessShareLock for such sessions and thereby not conflict against
     953             :      * CREATE DATABASE.
     954             :      */
     955       10710 :     if (!bootstrap)
     956       10314 :         LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
     957             :                          RowExclusiveLock);
     958             : 
     959             :     /*
     960             :      * Now we can mark our PGPROC entry with the database ID.
     961             :      *
     962             :      * We assume this is an atomic store so no lock is needed; though actually
     963             :      * things would work fine even if it weren't atomic.  Anyone searching the
     964             :      * ProcArray for this database's ID should hold the database lock, so they
     965             :      * would not be executing concurrently with this store.  A process looking
     966             :      * for another database's ID could in theory see a chance match if it read
     967             :      * a partially-updated databaseId value; but as long as all such searches
     968             :      * wait and retry, as in CountOtherDBBackends(), they will certainly see
     969             :      * the correct value on their next try.
     970             :      */
     971       10710 :     MyProc->databaseId = MyDatabaseId;
     972             : 
     973             :     /*
     974             :      * We established a catalog snapshot while reading pg_authid and/or
     975             :      * pg_database; but until we have set up MyDatabaseId, we won't react to
     976             :      * incoming sinval messages for unshared catalogs, so we won't realize it
     977             :      * if the snapshot has been invalidated.  Assume it's no good anymore.
     978             :      */
     979       10710 :     InvalidateCatalogSnapshot();
     980             : 
     981             :     /*
     982             :      * Recheck pg_database to make sure the target database hasn't gone away.
     983             :      * If there was a concurrent DROP DATABASE, this ensures we will die
     984             :      * cleanly without creating a mess.
     985             :      */
     986       10710 :     if (!bootstrap)
     987             :     {
     988             :         HeapTuple   tuple;
     989             : 
     990       10314 :         tuple = GetDatabaseTuple(dbname);
     991       10314 :         if (!HeapTupleIsValid(tuple) ||
     992       10314 :             MyDatabaseId != ((Form_pg_database) GETSTRUCT(tuple))->oid ||
     993       10314 :             MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
     994           0 :             ereport(FATAL,
     995             :                     (errcode(ERRCODE_UNDEFINED_DATABASE),
     996             :                      errmsg("database \"%s\" does not exist", dbname),
     997             :                      errdetail("It seems to have just been dropped or renamed.")));
     998             :     }
     999             : 
    1000             :     /*
    1001             :      * Now we should be able to access the database directory safely. Verify
    1002             :      * it's there and looks reasonable.
    1003             :      */
    1004       10710 :     fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
    1005             : 
    1006       10710 :     if (!bootstrap)
    1007             :     {
    1008       10314 :         if (access(fullpath, F_OK) == -1)
    1009             :         {
    1010           0 :             if (errno == ENOENT)
    1011           0 :                 ereport(FATAL,
    1012             :                         (errcode(ERRCODE_UNDEFINED_DATABASE),
    1013             :                          errmsg("database \"%s\" does not exist",
    1014             :                                 dbname),
    1015             :                          errdetail("The database subdirectory \"%s\" is missing.",
    1016             :                                    fullpath)));
    1017             :             else
    1018           0 :                 ereport(FATAL,
    1019             :                         (errcode_for_file_access(),
    1020             :                          errmsg("could not access directory \"%s\": %m",
    1021             :                                 fullpath)));
    1022             :         }
    1023             : 
    1024       10314 :         ValidatePgVersion(fullpath);
    1025             :     }
    1026             : 
    1027       10710 :     SetDatabasePath(fullpath);
    1028             : 
    1029             :     /*
    1030             :      * It's now possible to do real access to the system catalogs.
    1031             :      *
    1032             :      * Load relcache entries for the system catalogs.  This must create at
    1033             :      * least the minimum set of "nailed-in" cache entries.
    1034             :      */
    1035       10710 :     RelationCacheInitializePhase3();
    1036             : 
    1037             :     /* set up ACL framework (so CheckMyDatabase can check permissions) */
    1038       10710 :     initialize_acl();
    1039             : 
    1040             :     /*
    1041             :      * Re-read the pg_database row for our database, check permissions and set
    1042             :      * up database-specific GUC settings.  We can't do this until all the
    1043             :      * database-access infrastructure is up.  (Also, it wants to know if the
    1044             :      * user is a superuser, so the above stuff has to happen first.)
    1045             :      */
    1046       10710 :     if (!bootstrap)
    1047       10314 :         CheckMyDatabase(dbname, am_superuser, override_allow_connections);
    1048             : 
    1049             :     /*
    1050             :      * Now process any command-line switches and any additional GUC variable
    1051             :      * settings passed in the startup packet.   We couldn't do this before
    1052             :      * because we didn't know if client is a superuser.
    1053             :      */
    1054       10710 :     if (MyProcPort != NULL)
    1055        8044 :         process_startup_options(MyProcPort, am_superuser);
    1056             : 
    1057             :     /* Process pg_db_role_setting options */
    1058       10710 :     process_settings(MyDatabaseId, GetSessionUserId());
    1059             : 
    1060             :     /* Apply PostAuthDelay as soon as we've read all options */
    1061       10710 :     if (PostAuthDelay > 0)
    1062           0 :         pg_usleep(PostAuthDelay * 1000000L);
    1063             : 
    1064             :     /*
    1065             :      * Initialize various default states that can't be set up until we've
    1066             :      * selected the active user and gotten the right GUC settings.
    1067             :      */
    1068             : 
    1069             :     /* set default namespace search path */
    1070       10710 :     InitializeSearchPath();
    1071             : 
    1072             :     /* initialize client encoding */
    1073       10710 :     InitializeClientEncoding();
    1074             : 
    1075             :     /* Initialize this backend's session state. */
    1076       10710 :     InitializeSession();
    1077             : 
    1078             :     /* report this backend in the PgBackendStatus array */
    1079       10710 :     if (!bootstrap)
    1080       10314 :         pgstat_bestart();
    1081             : 
    1082             :     /* close the transaction we started above */
    1083       10710 :     if (!bootstrap)
    1084       10314 :         CommitTransactionCommand();
    1085             : }
    1086             : 
    1087             : /*
    1088             :  * Process any command-line switches and any additional GUC variable
    1089             :  * settings passed in the startup packet.
    1090             :  */
    1091             : static void
    1092        8460 : process_startup_options(Port *port, bool am_superuser)
    1093             : {
    1094             :     GucContext  gucctx;
    1095             :     ListCell   *gucopts;
    1096             : 
    1097        8460 :     gucctx = am_superuser ? PGC_SU_BACKEND : PGC_BACKEND;
    1098             : 
    1099             :     /*
    1100             :      * First process any command-line switches that were included in the
    1101             :      * startup packet, if we are in a regular backend.
    1102             :      */
    1103        8460 :     if (port->cmdline_options != NULL)
    1104             :     {
    1105             :         /*
    1106             :          * The maximum possible number of commandline arguments that could
    1107             :          * come from port->cmdline_options is (strlen + 1) / 2; see
    1108             :          * pg_split_opts().
    1109             :          */
    1110             :         char      **av;
    1111             :         int         maxac;
    1112             :         int         ac;
    1113             : 
    1114        3432 :         maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
    1115             : 
    1116        3432 :         av = (char **) palloc(maxac * sizeof(char *));
    1117        3432 :         ac = 0;
    1118             : 
    1119        3432 :         av[ac++] = "postgres";
    1120             : 
    1121        3432 :         pg_split_opts(av, &ac, port->cmdline_options);
    1122             : 
    1123        3432 :         av[ac] = NULL;
    1124             : 
    1125             :         Assert(ac < maxac);
    1126             : 
    1127        3432 :         (void) process_postgres_switches(ac, av, gucctx, NULL);
    1128             :     }
    1129             : 
    1130             :     /*
    1131             :      * Process any additional GUC variable settings passed in startup packet.
    1132             :      * These are handled exactly like command-line variables.
    1133             :      */
    1134        8460 :     gucopts = list_head(port->guc_options);
    1135       24326 :     while (gucopts)
    1136             :     {
    1137             :         char       *name;
    1138             :         char       *value;
    1139             : 
    1140       15866 :         name = lfirst(gucopts);
    1141       15866 :         gucopts = lnext(port->guc_options, gucopts);
    1142             : 
    1143       15866 :         value = lfirst(gucopts);
    1144       15866 :         gucopts = lnext(port->guc_options, gucopts);
    1145             : 
    1146       15866 :         SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
    1147             :     }
    1148        8460 : }
    1149             : 
    1150             : /*
    1151             :  * Load GUC settings from pg_db_role_setting.
    1152             :  *
    1153             :  * We try specific settings for the database/role combination, as well as
    1154             :  * general for this database and for this user.
    1155             :  */
    1156             : static void
    1157       10710 : process_settings(Oid databaseid, Oid roleid)
    1158             : {
    1159             :     Relation    relsetting;
    1160             :     Snapshot    snapshot;
    1161             : 
    1162       10710 :     if (!IsUnderPostmaster)
    1163         810 :         return;
    1164             : 
    1165        9900 :     relsetting = table_open(DbRoleSettingRelationId, AccessShareLock);
    1166             : 
    1167             :     /* read all the settings under the same snapshot for efficiency */
    1168        9900 :     snapshot = RegisterSnapshot(GetCatalogSnapshot(DbRoleSettingRelationId));
    1169             : 
    1170             :     /* Later settings are ignored if set earlier. */
    1171        9900 :     ApplySetting(snapshot, databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
    1172        9900 :     ApplySetting(snapshot, InvalidOid, roleid, relsetting, PGC_S_USER);
    1173        9900 :     ApplySetting(snapshot, databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
    1174        9900 :     ApplySetting(snapshot, InvalidOid, InvalidOid, relsetting, PGC_S_GLOBAL);
    1175             : 
    1176        9900 :     UnregisterSnapshot(snapshot);
    1177        9900 :     table_close(relsetting, AccessShareLock);
    1178             : }
    1179             : 
    1180             : /*
    1181             :  * Backend-shutdown callback.  Do cleanup that we want to be sure happens
    1182             :  * before all the supporting modules begin to nail their doors shut via
    1183             :  * their own callbacks.
    1184             :  *
    1185             :  * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
    1186             :  * via separate callbacks that execute before this one.  We don't combine the
    1187             :  * callbacks because we still want this one to happen if the user-level
    1188             :  * cleanup fails.
    1189             :  */
    1190             : static void
    1191       11990 : ShutdownPostgres(int code, Datum arg)
    1192             : {
    1193             :     /* Make sure we've killed any active transaction */
    1194       11990 :     AbortOutOfAnyTransaction();
    1195             : 
    1196             :     /*
    1197             :      * User locks are not released by transaction end, so be sure to release
    1198             :      * them explicitly.
    1199             :      */
    1200       11990 :     LockReleaseAll(USER_LOCKMETHOD, true);
    1201       11990 : }
    1202             : 
    1203             : 
    1204             : /*
    1205             :  * STATEMENT_TIMEOUT handler: trigger a query-cancel interrupt.
    1206             :  */
    1207             : static void
    1208          10 : StatementTimeoutHandler(void)
    1209             : {
    1210          10 :     int         sig = SIGINT;
    1211             : 
    1212             :     /*
    1213             :      * During authentication the timeout is used to deal with
    1214             :      * authentication_timeout - we want to quit in response to such timeouts.
    1215             :      */
    1216          10 :     if (ClientAuthInProgress)
    1217           0 :         sig = SIGTERM;
    1218             : 
    1219             : #ifdef HAVE_SETSID
    1220             :     /* try to signal whole process group */
    1221          10 :     kill(-MyProcPid, sig);
    1222             : #endif
    1223          10 :     kill(MyProcPid, sig);
    1224          10 : }
    1225             : 
    1226             : /*
    1227             :  * LOCK_TIMEOUT handler: trigger a query-cancel interrupt.
    1228             :  */
    1229             : static void
    1230           8 : LockTimeoutHandler(void)
    1231             : {
    1232             : #ifdef HAVE_SETSID
    1233             :     /* try to signal whole process group */
    1234           8 :     kill(-MyProcPid, SIGINT);
    1235             : #endif
    1236           8 :     kill(MyProcPid, SIGINT);
    1237           8 : }
    1238             : 
    1239             : static void
    1240           0 : IdleInTransactionSessionTimeoutHandler(void)
    1241             : {
    1242           0 :     IdleInTransactionSessionTimeoutPending = true;
    1243           0 :     InterruptPending = true;
    1244           0 :     SetLatch(MyLatch);
    1245           0 : }
    1246             : 
    1247             : /*
    1248             :  * Returns true if at least one role is defined in this database cluster.
    1249             :  */
    1250             : static bool
    1251         414 : ThereIsAtLeastOneRole(void)
    1252             : {
    1253             :     Relation    pg_authid_rel;
    1254             :     TableScanDesc scan;
    1255             :     bool        result;
    1256             : 
    1257         414 :     pg_authid_rel = table_open(AuthIdRelationId, AccessShareLock);
    1258             : 
    1259         414 :     scan = table_beginscan_catalog(pg_authid_rel, 0, NULL);
    1260         414 :     result = (heap_getnext(scan, ForwardScanDirection) != NULL);
    1261             : 
    1262         414 :     table_endscan(scan);
    1263         414 :     table_close(pg_authid_rel, AccessShareLock);
    1264             : 
    1265         414 :     return result;
    1266             : }

Generated by: LCOV version 1.13