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

Generated by: LCOV version 1.13