PageRenderTime 56ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/src/backend/utils/init/postinit.c

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