PageRenderTime 62ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

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

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