Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * postinit.c
4 : * postgres initialization utilities
5 : *
6 : * Portions Copyright (c) 1996-2024, 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/tableam.h"
27 : #include "access/xact.h"
28 : #include "access/xlog.h"
29 : #include "access/xloginsert.h"
30 : #include "catalog/namespace.h"
31 : #include "catalog/pg_authid.h"
32 : #include "catalog/pg_collation.h"
33 : #include "catalog/pg_database.h"
34 : #include "catalog/pg_db_role_setting.h"
35 : #include "catalog/pg_tablespace.h"
36 : #include "libpq/auth.h"
37 : #include "libpq/libpq-be.h"
38 : #include "mb/pg_wchar.h"
39 : #include "miscadmin.h"
40 : #include "pgstat.h"
41 : #include "postmaster/autovacuum.h"
42 : #include "postmaster/postmaster.h"
43 : #include "replication/slot.h"
44 : #include "replication/slotsync.h"
45 : #include "replication/walsender.h"
46 : #include "storage/bufmgr.h"
47 : #include "storage/fd.h"
48 : #include "storage/ipc.h"
49 : #include "storage/lmgr.h"
50 : #include "storage/proc.h"
51 : #include "storage/procarray.h"
52 : #include "storage/procsignal.h"
53 : #include "storage/sinvaladt.h"
54 : #include "storage/smgr.h"
55 : #include "storage/sync.h"
56 : #include "tcop/tcopprot.h"
57 : #include "utils/acl.h"
58 : #include "utils/builtins.h"
59 : #include "utils/fmgroids.h"
60 : #include "utils/guc_hooks.h"
61 : #include "utils/memutils.h"
62 : #include "utils/pg_locale.h"
63 : #include "utils/portal.h"
64 : #include "utils/ps_status.h"
65 : #include "utils/snapmgr.h"
66 : #include "utils/syscache.h"
67 : #include "utils/timeout.h"
68 :
69 : static HeapTuple GetDatabaseTuple(const char *dbname);
70 : static HeapTuple GetDatabaseTupleByOid(Oid dboid);
71 : static void PerformAuthentication(Port *port);
72 : static void CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections);
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 void TransactionTimeoutHandler(void);
78 : static void IdleSessionTimeoutHandler(void);
79 : static void IdleStatsUpdateTimeoutHandler(void);
80 : static void ClientCheckTimeoutHandler(void);
81 : static bool ThereIsAtLeastOneRole(void);
82 : static void process_startup_options(Port *port, bool am_superuser);
83 : static void process_settings(Oid databaseid, Oid roleid);
84 :
85 :
86 : /*** InitPostgres support ***/
87 :
88 :
89 : /*
90 : * GetDatabaseTuple -- fetch the pg_database row for a database
91 : *
92 : * This is used during backend startup when we don't yet have any access to
93 : * system catalogs in general. In the worst case, we can seqscan pg_database
94 : * using nothing but the hard-wired descriptor that relcache.c creates for
95 : * pg_database. In more typical cases, relcache.c was able to load
96 : * descriptors for both pg_database and its indexes from the shared relcache
97 : * cache file, and so we can do an indexscan. criticalSharedRelcachesBuilt
98 : * tells whether we got the cached descriptors.
99 : */
100 : static HeapTuple
101 20280 : GetDatabaseTuple(const char *dbname)
102 : {
103 : HeapTuple tuple;
104 : Relation relation;
105 : SysScanDesc scan;
106 : ScanKeyData key[1];
107 :
108 : /*
109 : * form a scan key
110 : */
111 20280 : ScanKeyInit(&key[0],
112 : Anum_pg_database_datname,
113 : BTEqualStrategyNumber, F_NAMEEQ,
114 : CStringGetDatum(dbname));
115 :
116 : /*
117 : * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
118 : * built the critical shared relcache entries (i.e., we're starting up
119 : * without a shared relcache cache file).
120 : */
121 20280 : relation = table_open(DatabaseRelationId, AccessShareLock);
122 20280 : scan = systable_beginscan(relation, DatabaseNameIndexId,
123 : criticalSharedRelcachesBuilt,
124 : NULL,
125 : 1, key);
126 :
127 20280 : tuple = systable_getnext(scan);
128 :
129 : /* Must copy tuple before releasing buffer */
130 20280 : if (HeapTupleIsValid(tuple))
131 20262 : tuple = heap_copytuple(tuple);
132 :
133 : /* all done */
134 20280 : systable_endscan(scan);
135 20280 : table_close(relation, AccessShareLock);
136 :
137 20280 : return tuple;
138 : }
139 :
140 : /*
141 : * GetDatabaseTupleByOid -- as above, but search by database OID
142 : */
143 : static HeapTuple
144 23666 : GetDatabaseTupleByOid(Oid dboid)
145 : {
146 : HeapTuple tuple;
147 : Relation relation;
148 : SysScanDesc scan;
149 : ScanKeyData key[1];
150 :
151 : /*
152 : * form a scan key
153 : */
154 23666 : ScanKeyInit(&key[0],
155 : Anum_pg_database_oid,
156 : BTEqualStrategyNumber, F_OIDEQ,
157 : ObjectIdGetDatum(dboid));
158 :
159 : /*
160 : * Open pg_database and fetch a tuple. Force heap scan if we haven't yet
161 : * built the critical shared relcache entries (i.e., we're starting up
162 : * without a shared relcache cache file).
163 : */
164 23666 : relation = table_open(DatabaseRelationId, AccessShareLock);
165 23666 : scan = systable_beginscan(relation, DatabaseOidIndexId,
166 : criticalSharedRelcachesBuilt,
167 : NULL,
168 : 1, key);
169 :
170 23666 : tuple = systable_getnext(scan);
171 :
172 : /* Must copy tuple before releasing buffer */
173 23666 : if (HeapTupleIsValid(tuple))
174 23666 : tuple = heap_copytuple(tuple);
175 :
176 : /* all done */
177 23666 : systable_endscan(scan);
178 23666 : table_close(relation, AccessShareLock);
179 :
180 23666 : return tuple;
181 : }
182 :
183 :
184 : /*
185 : * PerformAuthentication -- authenticate a remote client
186 : *
187 : * returns: nothing. Will not return at all if there's any failure.
188 : */
189 : static void
190 21138 : PerformAuthentication(Port *port)
191 : {
192 : /* This should be set already, but let's make sure */
193 21138 : ClientAuthInProgress = true; /* limit visibility of log messages */
194 :
195 : /*
196 : * In EXEC_BACKEND case, we didn't inherit the contents of pg_hba.conf
197 : * etcetera from the postmaster, and have to load them ourselves.
198 : *
199 : * FIXME: [fork/exec] Ugh. Is there a way around this overhead?
200 : */
201 : #ifdef EXEC_BACKEND
202 :
203 : /*
204 : * load_hba() and load_ident() want to work within the PostmasterContext,
205 : * so create that if it doesn't exist (which it won't). We'll delete it
206 : * again later, in PostgresMain.
207 : */
208 : if (PostmasterContext == NULL)
209 : PostmasterContext = AllocSetContextCreate(TopMemoryContext,
210 : "Postmaster",
211 : ALLOCSET_DEFAULT_SIZES);
212 :
213 : if (!load_hba())
214 : {
215 : /*
216 : * It makes no sense to continue if we fail to load the HBA file,
217 : * since there is no way to connect to the database in this case.
218 : */
219 : ereport(FATAL,
220 : /* translator: %s is a configuration file */
221 : (errmsg("could not load %s", HbaFileName)));
222 : }
223 :
224 : if (!load_ident())
225 : {
226 : /*
227 : * It is ok to continue if we fail to load the IDENT file, although it
228 : * means that you cannot log in using any of the authentication
229 : * methods that need a user name mapping. load_ident() already logged
230 : * the details of error to the log.
231 : */
232 : }
233 : #endif
234 :
235 : /*
236 : * Set up a timeout in case a buggy or malicious client fails to respond
237 : * during authentication. Since we're inside a transaction and might do
238 : * database access, we have to use the statement_timeout infrastructure.
239 : */
240 21138 : enable_timeout_after(STATEMENT_TIMEOUT, AuthenticationTimeout * 1000);
241 :
242 : /*
243 : * Now perform authentication exchange.
244 : */
245 21138 : set_ps_display("authentication");
246 21138 : ClientAuthentication(port); /* might not return, if failure */
247 :
248 : /*
249 : * Done with authentication. Disable the timeout, and log if needed.
250 : */
251 21018 : disable_timeout(STATEMENT_TIMEOUT, false);
252 :
253 21018 : if (Log_connections)
254 : {
255 : StringInfoData logmsg;
256 :
257 518 : initStringInfo(&logmsg);
258 518 : if (am_walsender)
259 6 : appendStringInfo(&logmsg, _("replication connection authorized: user=%s"),
260 : port->user_name);
261 : else
262 512 : appendStringInfo(&logmsg, _("connection authorized: user=%s"),
263 : port->user_name);
264 518 : if (!am_walsender)
265 512 : appendStringInfo(&logmsg, _(" database=%s"), port->database_name);
266 :
267 518 : if (port->application_name != NULL)
268 518 : appendStringInfo(&logmsg, _(" application_name=%s"),
269 : port->application_name);
270 :
271 : #ifdef USE_SSL
272 518 : if (port->ssl_in_use)
273 154 : appendStringInfo(&logmsg, _(" SSL enabled (protocol=%s, cipher=%s, bits=%d)"),
274 : be_tls_get_version(port),
275 : be_tls_get_cipher(port),
276 : be_tls_get_cipher_bits(port));
277 : #endif
278 : #ifdef ENABLE_GSS
279 : if (port->gss)
280 : {
281 : const char *princ = be_gssapi_get_princ(port);
282 :
283 : if (princ)
284 : appendStringInfo(&logmsg,
285 : _(" GSS (authenticated=%s, encrypted=%s, delegated_credentials=%s, principal=%s)"),
286 : be_gssapi_get_auth(port) ? _("yes") : _("no"),
287 : be_gssapi_get_enc(port) ? _("yes") : _("no"),
288 : be_gssapi_get_delegation(port) ? _("yes") : _("no"),
289 : princ);
290 : else
291 : appendStringInfo(&logmsg,
292 : _(" GSS (authenticated=%s, encrypted=%s, delegated_credentials=%s)"),
293 : be_gssapi_get_auth(port) ? _("yes") : _("no"),
294 : be_gssapi_get_enc(port) ? _("yes") : _("no"),
295 : be_gssapi_get_delegation(port) ? _("yes") : _("no"));
296 : }
297 : #endif
298 :
299 518 : ereport(LOG, errmsg_internal("%s", logmsg.data));
300 518 : pfree(logmsg.data);
301 : }
302 :
303 21018 : set_ps_display("startup");
304 :
305 21018 : ClientAuthInProgress = false; /* client_min_messages is active now */
306 21018 : }
307 :
308 :
309 : /*
310 : * CheckMyDatabase -- fetch information from the pg_database entry for our DB
311 : */
312 : static void
313 23646 : CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections)
314 : {
315 : HeapTuple tup;
316 : Form_pg_database dbform;
317 : Datum datum;
318 : bool isnull;
319 : char *collate;
320 : char *ctype;
321 : char *datlocale;
322 :
323 : /* Fetch our pg_database row normally, via syscache */
324 23646 : tup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
325 23646 : if (!HeapTupleIsValid(tup))
326 0 : elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
327 23646 : dbform = (Form_pg_database) GETSTRUCT(tup);
328 :
329 : /* This recheck is strictly paranoia */
330 23646 : if (strcmp(name, NameStr(dbform->datname)) != 0)
331 0 : ereport(FATAL,
332 : (errcode(ERRCODE_UNDEFINED_DATABASE),
333 : errmsg("database \"%s\" has disappeared from pg_database",
334 : name),
335 : errdetail("Database OID %u now seems to belong to \"%s\".",
336 : MyDatabaseId, NameStr(dbform->datname))));
337 :
338 : /*
339 : * Check permissions to connect to the database.
340 : *
341 : * These checks are not enforced when in standalone mode, so that there is
342 : * a way to recover from disabling all access to all databases, for
343 : * example "UPDATE pg_database SET datallowconn = false;".
344 : *
345 : * We do not enforce them for autovacuum worker processes either.
346 : */
347 23646 : if (IsUnderPostmaster && !AmAutoVacuumWorkerProcess())
348 : {
349 : /*
350 : * Check that the database is currently allowing connections.
351 : */
352 23530 : if (!dbform->datallowconn && !override_allow_connections)
353 2 : ereport(FATAL,
354 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
355 : errmsg("database \"%s\" is not currently accepting connections",
356 : name)));
357 :
358 : /*
359 : * Check privilege to connect to the database. (The am_superuser test
360 : * is redundant, but since we have the flag, might as well check it
361 : * and save a few cycles.)
362 : */
363 23954 : if (!am_superuser &&
364 426 : object_aclcheck(DatabaseRelationId, MyDatabaseId, GetUserId(),
365 : ACL_CONNECT) != ACLCHECK_OK)
366 0 : ereport(FATAL,
367 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
368 : errmsg("permission denied for database \"%s\"", name),
369 : errdetail("User does not have CONNECT privilege.")));
370 :
371 : /*
372 : * Check connection limit for this database.
373 : *
374 : * There is a race condition here --- we create our PGPROC before
375 : * checking for other PGPROCs. If two backends did this at about the
376 : * same time, they might both think they were over the limit, while
377 : * ideally one should succeed and one fail. Getting that to work
378 : * exactly seems more trouble than it is worth, however; instead we
379 : * just document that the connection limit is approximate.
380 : */
381 23528 : if (dbform->datconnlimit >= 0 &&
382 0 : !am_superuser &&
383 0 : CountDBConnections(MyDatabaseId) > dbform->datconnlimit)
384 0 : ereport(FATAL,
385 : (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
386 : errmsg("too many connections for database \"%s\"",
387 : name)));
388 : }
389 :
390 : /*
391 : * OK, we're golden. Next to-do item is to save the encoding info out of
392 : * the pg_database tuple.
393 : */
394 23644 : SetDatabaseEncoding(dbform->encoding);
395 : /* Record it as a GUC internal option, too */
396 23644 : SetConfigOption("server_encoding", GetDatabaseEncodingName(),
397 : PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
398 : /* If we have no other source of client_encoding, use server encoding */
399 23644 : SetConfigOption("client_encoding", GetDatabaseEncodingName(),
400 : PGC_BACKEND, PGC_S_DYNAMIC_DEFAULT);
401 :
402 : /* assign locale variables */
403 23644 : datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datcollate);
404 23644 : collate = TextDatumGetCString(datum);
405 23644 : datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datctype);
406 23644 : ctype = TextDatumGetCString(datum);
407 :
408 23644 : if (pg_perm_setlocale(LC_COLLATE, collate) == NULL)
409 0 : ereport(FATAL,
410 : (errmsg("database locale is incompatible with operating system"),
411 : errdetail("The database was initialized with LC_COLLATE \"%s\", "
412 : " which is not recognized by setlocale().", collate),
413 : errhint("Recreate the database with another locale or install the missing locale.")));
414 :
415 23644 : if (pg_perm_setlocale(LC_CTYPE, ctype) == NULL)
416 0 : ereport(FATAL,
417 : (errmsg("database locale is incompatible with operating system"),
418 : errdetail("The database was initialized with LC_CTYPE \"%s\", "
419 : " which is not recognized by setlocale().", ctype),
420 : errhint("Recreate the database with another locale or install the missing locale.")));
421 :
422 23644 : if (strcmp(ctype, "C") == 0 ||
423 20884 : strcmp(ctype, "POSIX") == 0)
424 2760 : database_ctype_is_c = true;
425 :
426 23644 : if (dbform->datlocprovider == COLLPROVIDER_BUILTIN)
427 : {
428 1700 : datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datlocale);
429 1700 : datlocale = TextDatumGetCString(datum);
430 :
431 1700 : builtin_validate_locale(dbform->encoding, datlocale);
432 :
433 1700 : default_locale.info.builtin.locale = MemoryContextStrdup(
434 : TopMemoryContext, datlocale);
435 : }
436 21944 : else if (dbform->datlocprovider == COLLPROVIDER_ICU)
437 : {
438 : char *icurules;
439 :
440 26 : datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datlocale);
441 26 : datlocale = TextDatumGetCString(datum);
442 :
443 26 : datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_daticurules, &isnull);
444 26 : if (!isnull)
445 0 : icurules = TextDatumGetCString(datum);
446 : else
447 26 : icurules = NULL;
448 :
449 26 : make_icu_collator(datlocale, icurules, &default_locale);
450 : }
451 : else
452 21918 : datlocale = NULL;
453 :
454 23640 : default_locale.provider = dbform->datlocprovider;
455 :
456 : /*
457 : * Default locale is currently always deterministic. Nondeterministic
458 : * locales currently don't support pattern matching, which would break a
459 : * lot of things if applied globally.
460 : */
461 23640 : default_locale.deterministic = true;
462 :
463 : /*
464 : * Check collation version. See similar code in
465 : * pg_newlocale_from_collation(). Note that here we warn instead of error
466 : * in any case, so that we don't prevent connecting.
467 : */
468 23640 : datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_datcollversion,
469 : &isnull);
470 23640 : if (!isnull)
471 : {
472 : char *actual_versionstr;
473 : char *collversionstr;
474 : char *locale;
475 :
476 22538 : collversionstr = TextDatumGetCString(datum);
477 :
478 22538 : if (dbform->datlocprovider == COLLPROVIDER_LIBC)
479 20832 : locale = collate;
480 : else
481 1706 : locale = datlocale;
482 :
483 22538 : actual_versionstr = get_collation_actual_version(dbform->datlocprovider, locale);
484 22538 : if (!actual_versionstr)
485 : /* should not happen */
486 0 : elog(WARNING,
487 : "database \"%s\" has no actual collation version, but a version was recorded",
488 : name);
489 22538 : else if (strcmp(actual_versionstr, collversionstr) != 0)
490 0 : ereport(WARNING,
491 : (errmsg("database \"%s\" has a collation version mismatch",
492 : name),
493 : errdetail("The database was created using collation version %s, "
494 : "but the operating system provides version %s.",
495 : collversionstr, actual_versionstr),
496 : errhint("Rebuild all objects in this database that use the default collation and run "
497 : "ALTER DATABASE %s REFRESH COLLATION VERSION, "
498 : "or build PostgreSQL with the right library version.",
499 : quote_identifier(name))));
500 : }
501 :
502 23640 : ReleaseSysCache(tup);
503 23640 : }
504 :
505 :
506 : /*
507 : * pg_split_opts -- split a string of options and append it to an argv array
508 : *
509 : * The caller is responsible for ensuring the argv array is large enough. The
510 : * maximum possible number of arguments added by this routine is
511 : * (strlen(optstr) + 1) / 2.
512 : *
513 : * Because some option values can contain spaces we allow escaping using
514 : * backslashes, with \\ representing a literal backslash.
515 : */
516 : void
517 6090 : pg_split_opts(char **argv, int *argcp, const char *optstr)
518 : {
519 : StringInfoData s;
520 :
521 6090 : initStringInfo(&s);
522 :
523 22206 : while (*optstr)
524 : {
525 16116 : bool last_was_escape = false;
526 :
527 16116 : resetStringInfo(&s);
528 :
529 : /* skip over leading space */
530 30310 : while (isspace((unsigned char) *optstr))
531 14194 : optstr++;
532 :
533 16116 : if (*optstr == '\0')
534 0 : break;
535 :
536 : /*
537 : * Parse a single option, stopping at the first space, unless it's
538 : * escaped.
539 : */
540 244208 : while (*optstr)
541 : {
542 238118 : if (isspace((unsigned char) *optstr) && !last_was_escape)
543 10026 : break;
544 :
545 228092 : if (!last_was_escape && *optstr == '\\')
546 28 : last_was_escape = true;
547 : else
548 : {
549 228064 : last_was_escape = false;
550 228064 : appendStringInfoChar(&s, *optstr);
551 : }
552 :
553 228092 : optstr++;
554 : }
555 :
556 : /* now store the option in the next argv[] position */
557 16116 : argv[(*argcp)++] = pstrdup(s.data);
558 : }
559 :
560 6090 : pfree(s.data);
561 6090 : }
562 :
563 : /*
564 : * Initialize MaxBackends value from config options.
565 : *
566 : * This must be called after modules have had the chance to alter GUCs in
567 : * shared_preload_libraries and before shared memory size is determined.
568 : *
569 : * Note that in EXEC_BACKEND environment, the value is passed down from
570 : * postmaster to subprocesses via BackendParameters in SubPostmasterMain; only
571 : * postmaster itself and processes not under postmaster control should call
572 : * this.
573 : */
574 : void
575 1788 : InitializeMaxBackends(void)
576 : {
577 : Assert(MaxBackends == 0);
578 :
579 : /* the extra unit accounts for the autovacuum launcher */
580 1788 : MaxBackends = MaxConnections + autovacuum_max_workers + 1 +
581 1788 : max_worker_processes + max_wal_senders;
582 :
583 1788 : if (MaxBackends > MAX_BACKENDS)
584 0 : ereport(ERROR,
585 : (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
586 : errmsg("too many server processes configured"),
587 : errdetail("\"max_connections\" (%d) plus \"autovacuum_max_workers\" (%d) plus \"max_worker_processes\" (%d) plus \"max_wal_senders\" (%d) must be less than %d.",
588 : MaxConnections, autovacuum_max_workers,
589 : max_worker_processes, max_wal_senders,
590 : MAX_BACKENDS)));
591 1788 : }
592 :
593 : /*
594 : * Early initialization of a backend (either standalone or under postmaster).
595 : * This happens even before InitPostgres.
596 : *
597 : * This is separate from InitPostgres because it is also called by auxiliary
598 : * processes, such as the background writer process, which may not call
599 : * InitPostgres at all.
600 : */
601 : void
602 30316 : BaseInit(void)
603 : {
604 : Assert(MyProc != NULL);
605 :
606 : /*
607 : * Initialize our input/output/debugging file descriptors.
608 : */
609 30316 : DebugFileOpen();
610 :
611 : /*
612 : * Initialize file access. Done early so other subsystems can access
613 : * files.
614 : */
615 30316 : InitFileAccess();
616 :
617 : /*
618 : * Initialize statistics reporting. This needs to happen early to ensure
619 : * that pgstat's shutdown callback runs after the shutdown callbacks of
620 : * all subsystems that can produce stats (like e.g. transaction commits
621 : * can).
622 : */
623 30316 : pgstat_initialize();
624 :
625 : /* Do local initialization of storage and buffer managers */
626 30316 : InitSync();
627 30316 : smgrinit();
628 30316 : InitBufferPoolAccess();
629 :
630 : /*
631 : * Initialize temporary file access after pgstat, so that the temporary
632 : * file shutdown hook can report temporary file statistics.
633 : */
634 30316 : InitTemporaryFileAccess();
635 :
636 : /*
637 : * Initialize local buffers for WAL record construction, in case we ever
638 : * try to insert XLOG.
639 : */
640 30316 : InitXLogInsert();
641 :
642 : /*
643 : * Initialize replication slots after pgstat. The exit hook might need to
644 : * drop ephemeral slots, which in turn triggers stats reporting.
645 : */
646 30316 : ReplicationSlotInitialize();
647 30316 : }
648 :
649 :
650 : /* --------------------------------
651 : * InitPostgres
652 : * Initialize POSTGRES.
653 : *
654 : * Parameters:
655 : * in_dbname, dboid: specify database to connect to, as described below
656 : * username, useroid: specify role to connect as, as described below
657 : * flags:
658 : * - INIT_PG_LOAD_SESSION_LIBS to honor [session|local]_preload_libraries.
659 : * - INIT_PG_OVERRIDE_ALLOW_CONNS to connect despite !datallowconn.
660 : * - INIT_PG_OVERRIDE_ROLE_LOGIN to connect despite !rolcanlogin.
661 : * out_dbname: optional output parameter, see below; pass NULL if not used
662 : *
663 : * The database can be specified by name, using the in_dbname parameter, or by
664 : * OID, using the dboid parameter. Specify NULL or InvalidOid respectively
665 : * for the unused parameter. If dboid is provided, the actual database
666 : * name can be returned to the caller in out_dbname. If out_dbname isn't
667 : * NULL, it must point to a buffer of size NAMEDATALEN.
668 : *
669 : * Similarly, the role can be passed by name, using the username parameter,
670 : * or by OID using the useroid parameter.
671 : *
672 : * In bootstrap mode the database and username parameters are NULL/InvalidOid.
673 : * The autovacuum launcher process doesn't specify these parameters either,
674 : * because it only goes far enough to be able to read pg_database; it doesn't
675 : * connect to any particular database. An autovacuum worker specifies a
676 : * database but not a username; conversely, a physical walsender specifies
677 : * username but not database.
678 : *
679 : * By convention, INIT_PG_LOAD_SESSION_LIBS should be passed in "flags" in
680 : * "interactive" sessions (including standalone backends), but not in
681 : * background processes such as autovacuum. Note in particular that it
682 : * shouldn't be true in parallel worker processes; those have another
683 : * mechanism for replicating their leader's set of loaded libraries.
684 : *
685 : * We expect that InitProcess() was already called, so we already have a
686 : * PGPROC struct ... but it's not completely filled in yet.
687 : *
688 : * Note:
689 : * Be very careful with the order of calls in the InitPostgres function.
690 : * --------------------------------
691 : */
692 : void
693 26074 : InitPostgres(const char *in_dbname, Oid dboid,
694 : const char *username, Oid useroid,
695 : bits32 flags,
696 : char *out_dbname)
697 : {
698 26074 : bool bootstrap = IsBootstrapProcessingMode();
699 : bool am_superuser;
700 : char *fullpath;
701 : char dbname[NAMEDATALEN];
702 26074 : int nfree = 0;
703 :
704 26074 : elog(DEBUG3, "InitPostgres");
705 :
706 : /*
707 : * Add my PGPROC struct to the ProcArray.
708 : *
709 : * Once I have done this, I am visible to other backends!
710 : */
711 26074 : InitProcessPhase2();
712 :
713 : /*
714 : * Initialize my entry in the shared-invalidation manager's array of
715 : * per-backend data.
716 : */
717 26074 : SharedInvalBackendInit(false);
718 :
719 26074 : ProcSignalInit();
720 :
721 : /*
722 : * Also set up timeout handlers needed for backend operation. We need
723 : * these in every case except bootstrap.
724 : */
725 26074 : if (!bootstrap)
726 : {
727 25994 : RegisterTimeout(DEADLOCK_TIMEOUT, CheckDeadLockAlert);
728 25994 : RegisterTimeout(STATEMENT_TIMEOUT, StatementTimeoutHandler);
729 25994 : RegisterTimeout(LOCK_TIMEOUT, LockTimeoutHandler);
730 25994 : RegisterTimeout(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
731 : IdleInTransactionSessionTimeoutHandler);
732 25994 : RegisterTimeout(TRANSACTION_TIMEOUT, TransactionTimeoutHandler);
733 25994 : RegisterTimeout(IDLE_SESSION_TIMEOUT, IdleSessionTimeoutHandler);
734 25994 : RegisterTimeout(CLIENT_CONNECTION_CHECK_TIMEOUT, ClientCheckTimeoutHandler);
735 25994 : RegisterTimeout(IDLE_STATS_UPDATE_TIMEOUT,
736 : IdleStatsUpdateTimeoutHandler);
737 : }
738 :
739 : /*
740 : * If this is either a bootstrap process or a standalone backend, start up
741 : * the XLOG machinery, and register to have it closed down at exit. In
742 : * other cases, the startup process is responsible for starting up the
743 : * XLOG machinery, and the checkpointer for closing it down.
744 : */
745 26074 : if (!IsUnderPostmaster)
746 : {
747 : /*
748 : * We don't yet have an aux-process resource owner, but StartupXLOG
749 : * and ShutdownXLOG will need one. Hence, create said resource owner
750 : * (and register a callback to clean it up after ShutdownXLOG runs).
751 : */
752 178 : CreateAuxProcessResourceOwner();
753 :
754 178 : StartupXLOG();
755 : /* Release (and warn about) any buffer pins leaked in StartupXLOG */
756 178 : ReleaseAuxProcessResources(true);
757 : /* Reset CurrentResourceOwner to nothing for the moment */
758 178 : CurrentResourceOwner = NULL;
759 :
760 : /*
761 : * Use before_shmem_exit() so that ShutdownXLOG() can rely on DSM
762 : * segments etc to work (which in turn is required for pgstats).
763 : */
764 178 : before_shmem_exit(pgstat_before_server_shutdown, 0);
765 178 : before_shmem_exit(ShutdownXLOG, 0);
766 : }
767 :
768 : /*
769 : * Initialize the relation cache and the system catalog caches. Note that
770 : * no catalog access happens here; we only set up the hashtable structure.
771 : * We must do this before starting a transaction because transaction abort
772 : * would try to touch these hashtables.
773 : */
774 26074 : RelationCacheInitialize();
775 26074 : InitCatalogCache();
776 26074 : InitPlanCache();
777 :
778 : /* Initialize portal manager */
779 26074 : EnablePortalManager();
780 :
781 : /* Initialize status reporting */
782 26074 : pgstat_beinit();
783 :
784 : /*
785 : * Load relcache entries for the shared system catalogs. This must create
786 : * at least entries for pg_database and catalogs used for authentication.
787 : */
788 26074 : RelationCacheInitializePhase2();
789 :
790 : /*
791 : * Set up process-exit callback to do pre-shutdown cleanup. This is the
792 : * one of the first before_shmem_exit callbacks we register; thus, this
793 : * will be one the last things we do before low-level modules like the
794 : * buffer manager begin to close down. We need to have this in place
795 : * before we begin our first transaction --- if we fail during the
796 : * initialization transaction, as is entirely possible, we need the
797 : * AbortTransaction call to clean up.
798 : */
799 26074 : before_shmem_exit(ShutdownPostgres, 0);
800 :
801 : /* The autovacuum launcher is done here */
802 26074 : if (AmAutoVacuumLauncherProcess())
803 : {
804 : /* report this backend in the PgBackendStatus array */
805 650 : pgstat_bestart();
806 :
807 2180 : return;
808 : }
809 :
810 : /*
811 : * Start a new transaction here before first access to db, and get a
812 : * snapshot. We don't have a use for the snapshot itself, but we're
813 : * interested in the secondary effect that it sets RecentGlobalXmin. (This
814 : * is critical for anything that reads heap pages, because HOT may decide
815 : * to prune them even if the process doesn't attempt to modify any
816 : * tuples.)
817 : *
818 : * FIXME: This comment is inaccurate / the code buggy. A snapshot that is
819 : * not pushed/active does not reliably prevent HOT pruning (->xmin could
820 : * e.g. be cleared when cache invalidations are processed).
821 : */
822 25424 : if (!bootstrap)
823 : {
824 : /* statement_timestamp must be set for timeouts to work correctly */
825 25344 : SetCurrentStatementStartTimestamp();
826 25344 : StartTransactionCommand();
827 :
828 : /*
829 : * transaction_isolation will have been set to the default by the
830 : * above. If the default is "serializable", and we are in hot
831 : * standby, we will fail if we don't change it to something lower.
832 : * Fortunately, "read committed" is plenty good enough.
833 : */
834 25344 : XactIsoLevel = XACT_READ_COMMITTED;
835 :
836 25344 : (void) GetTransactionSnapshot();
837 : }
838 :
839 : /*
840 : * Perform client authentication if necessary, then figure out our
841 : * postgres user ID, and see if we are a superuser.
842 : *
843 : * In standalone mode, autovacuum worker processes and slot sync worker
844 : * process, we use a fixed ID, otherwise we figure it out from the
845 : * authenticated user name.
846 : */
847 25424 : if (bootstrap || AmAutoVacuumWorkerProcess() || AmLogicalSlotSyncWorkerProcess())
848 : {
849 106 : InitializeSessionUserIdStandalone();
850 106 : am_superuser = true;
851 : }
852 25318 : else if (!IsUnderPostmaster)
853 : {
854 98 : InitializeSessionUserIdStandalone();
855 98 : am_superuser = true;
856 98 : if (!ThereIsAtLeastOneRole())
857 0 : ereport(WARNING,
858 : (errcode(ERRCODE_UNDEFINED_OBJECT),
859 : errmsg("no roles are defined in this database system"),
860 : errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
861 : username != NULL ? username : "postgres")));
862 : }
863 25220 : else if (AmBackgroundWorkerProcess())
864 : {
865 4082 : if (username == NULL && !OidIsValid(useroid))
866 : {
867 698 : InitializeSessionUserIdStandalone();
868 698 : am_superuser = true;
869 : }
870 : else
871 : {
872 3384 : InitializeSessionUserId(username, useroid,
873 3384 : (flags & INIT_PG_OVERRIDE_ROLE_LOGIN) != 0);
874 3382 : am_superuser = superuser();
875 : }
876 : }
877 : else
878 : {
879 : /* normal multiuser case */
880 : Assert(MyProcPort != NULL);
881 21138 : PerformAuthentication(MyProcPort);
882 21018 : InitializeSessionUserId(username, useroid, false);
883 : /* ensure that auth_method is actually valid, aka authn_id is not NULL */
884 21010 : if (MyClientConnectionInfo.authn_id)
885 208 : InitializeSystemUser(MyClientConnectionInfo.authn_id,
886 : hba_authname(MyClientConnectionInfo.auth_method));
887 21010 : am_superuser = superuser();
888 : }
889 :
890 : /*
891 : * Binary upgrades only allowed super-user connections
892 : */
893 25294 : if (IsBinaryUpgrade && !am_superuser)
894 : {
895 0 : ereport(FATAL,
896 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
897 : errmsg("must be superuser to connect in binary upgrade mode")));
898 : }
899 :
900 : /*
901 : * The last few connection slots are reserved for superusers and roles
902 : * with privileges of pg_use_reserved_connections. Replication
903 : * connections are drawn from slots reserved with max_wal_senders and are
904 : * not limited by max_connections, superuser_reserved_connections, or
905 : * reserved_connections.
906 : *
907 : * Note: At this point, the new backend has already claimed a proc struct,
908 : * so we must check whether the number of free slots is strictly less than
909 : * the reserved connection limits.
910 : */
911 25294 : if (!am_superuser && !am_walsender &&
912 424 : (SuperuserReservedConnections + ReservedConnections) > 0 &&
913 424 : !HaveNFreeProcs(SuperuserReservedConnections + ReservedConnections, &nfree))
914 : {
915 0 : if (nfree < SuperuserReservedConnections)
916 0 : ereport(FATAL,
917 : (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
918 : errmsg("remaining connection slots are reserved for roles with the %s attribute",
919 : "SUPERUSER")));
920 :
921 0 : if (!has_privs_of_role(GetUserId(), ROLE_PG_USE_RESERVED_CONNECTIONS))
922 0 : ereport(FATAL,
923 : (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
924 : errmsg("remaining connection slots are reserved for roles with privileges of the \"%s\" role",
925 : "pg_use_reserved_connections")));
926 : }
927 :
928 : /* Check replication permissions needed for walsender processes. */
929 25294 : if (am_walsender)
930 : {
931 : Assert(!bootstrap);
932 :
933 1974 : if (!has_rolreplication(GetUserId()))
934 0 : ereport(FATAL,
935 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
936 : errmsg("permission denied to start WAL sender"),
937 : errdetail("Only roles with the %s attribute may start a WAL sender process.",
938 : "REPLICATION")));
939 : }
940 :
941 : /*
942 : * If this is a plain walsender only supporting physical replication, we
943 : * don't want to connect to any particular database. Just finish the
944 : * backend startup by processing any options from the startup packet, and
945 : * we're done.
946 : */
947 25294 : if (am_walsender && !am_db_walsender)
948 : {
949 : /* process any options passed in the startup packet */
950 836 : if (MyProcPort != NULL)
951 836 : process_startup_options(MyProcPort, am_superuser);
952 :
953 : /* Apply PostAuthDelay as soon as we've read all options */
954 836 : if (PostAuthDelay > 0)
955 0 : pg_usleep(PostAuthDelay * 1000000L);
956 :
957 : /* initialize client encoding */
958 836 : InitializeClientEncoding();
959 :
960 : /* report this backend in the PgBackendStatus array */
961 836 : pgstat_bestart();
962 :
963 : /* close the transaction we started above */
964 836 : CommitTransactionCommand();
965 :
966 836 : return;
967 : }
968 :
969 : /*
970 : * Set up the global variables holding database id and default tablespace.
971 : * But note we won't actually try to touch the database just yet.
972 : *
973 : * We take a shortcut in the bootstrap case, otherwise we have to look up
974 : * the db's entry in pg_database.
975 : */
976 24458 : if (bootstrap)
977 : {
978 80 : dboid = Template1DbOid;
979 80 : MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
980 : }
981 24378 : else if (in_dbname != NULL)
982 : {
983 : HeapTuple tuple;
984 : Form_pg_database dbform;
985 :
986 20280 : tuple = GetDatabaseTuple(in_dbname);
987 20280 : if (!HeapTupleIsValid(tuple))
988 18 : ereport(FATAL,
989 : (errcode(ERRCODE_UNDEFINED_DATABASE),
990 : errmsg("database \"%s\" does not exist", in_dbname)));
991 20262 : dbform = (Form_pg_database) GETSTRUCT(tuple);
992 20262 : dboid = dbform->oid;
993 : }
994 4098 : else if (!OidIsValid(dboid))
995 : {
996 : /*
997 : * If this is a background worker not bound to any particular
998 : * database, we're done now. Everything that follows only makes sense
999 : * if we are bound to a specific database. We do need to close the
1000 : * transaction we started before returning.
1001 : */
1002 694 : if (!bootstrap)
1003 : {
1004 694 : pgstat_bestart();
1005 694 : CommitTransactionCommand();
1006 : }
1007 694 : return;
1008 : }
1009 :
1010 : /*
1011 : * Now, take a writer's lock on the database we are trying to connect to.
1012 : * If there is a concurrently running DROP DATABASE on that database, this
1013 : * will block us until it finishes (and has committed its update of
1014 : * pg_database).
1015 : *
1016 : * Note that the lock is not held long, only until the end of this startup
1017 : * transaction. This is OK since we will advertise our use of the
1018 : * database in the ProcArray before dropping the lock (in fact, that's the
1019 : * next thing to do). Anyone trying a DROP DATABASE after this point will
1020 : * see us in the array once they have the lock. Ordering is important for
1021 : * this because we don't want to advertise ourselves as being in this
1022 : * database until we have the lock; otherwise we create what amounts to a
1023 : * deadlock with CountOtherDBBackends().
1024 : *
1025 : * Note: use of RowExclusiveLock here is reasonable because we envision
1026 : * our session as being a concurrent writer of the database. If we had a
1027 : * way of declaring a session as being guaranteed-read-only, we could use
1028 : * AccessShareLock for such sessions and thereby not conflict against
1029 : * CREATE DATABASE.
1030 : */
1031 23746 : if (!bootstrap)
1032 23666 : LockSharedObject(DatabaseRelationId, dboid, 0, RowExclusiveLock);
1033 :
1034 : /*
1035 : * Recheck pg_database to make sure the target database hasn't gone away.
1036 : * If there was a concurrent DROP DATABASE, this ensures we will die
1037 : * cleanly without creating a mess.
1038 : */
1039 23746 : if (!bootstrap)
1040 : {
1041 : HeapTuple tuple;
1042 : Form_pg_database datform;
1043 :
1044 23666 : tuple = GetDatabaseTupleByOid(dboid);
1045 23666 : if (HeapTupleIsValid(tuple))
1046 23666 : datform = (Form_pg_database) GETSTRUCT(tuple);
1047 :
1048 23666 : if (!HeapTupleIsValid(tuple) ||
1049 20262 : (in_dbname && namestrcmp(&datform->datname, in_dbname)))
1050 : {
1051 0 : if (in_dbname)
1052 0 : ereport(FATAL,
1053 : (errcode(ERRCODE_UNDEFINED_DATABASE),
1054 : errmsg("database \"%s\" does not exist", in_dbname),
1055 : errdetail("It seems to have just been dropped or renamed.")));
1056 : else
1057 0 : ereport(FATAL,
1058 : (errcode(ERRCODE_UNDEFINED_DATABASE),
1059 : errmsg("database %u does not exist", dboid)));
1060 : }
1061 :
1062 23666 : strlcpy(dbname, NameStr(datform->datname), sizeof(dbname));
1063 :
1064 23666 : if (database_is_invalid_form(datform))
1065 : {
1066 14 : ereport(FATAL,
1067 : errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
1068 : errmsg("cannot connect to invalid database \"%s\"", dbname),
1069 : errhint("Use DROP DATABASE to drop invalid databases."));
1070 : }
1071 :
1072 23652 : MyDatabaseTableSpace = datform->dattablespace;
1073 23652 : MyDatabaseHasLoginEventTriggers = datform->dathasloginevt;
1074 : /* pass the database name back to the caller */
1075 23652 : if (out_dbname)
1076 18 : strcpy(out_dbname, dbname);
1077 : }
1078 :
1079 : /*
1080 : * Now that we rechecked, we are certain to be connected to a database and
1081 : * thus can set MyDatabaseId.
1082 : *
1083 : * It is important that MyDatabaseId only be set once we are sure that the
1084 : * target database can no longer be concurrently dropped or renamed. For
1085 : * example, without this guarantee, pgstat_update_dbstats() could create
1086 : * entries for databases that were just dropped in the pgstat shutdown
1087 : * callback, which could confuse other code paths like the autovacuum
1088 : * scheduler.
1089 : */
1090 23732 : MyDatabaseId = dboid;
1091 :
1092 : /*
1093 : * Now we can mark our PGPROC entry with the database ID.
1094 : *
1095 : * We assume this is an atomic store so no lock is needed; though actually
1096 : * things would work fine even if it weren't atomic. Anyone searching the
1097 : * ProcArray for this database's ID should hold the database lock, so they
1098 : * would not be executing concurrently with this store. A process looking
1099 : * for another database's ID could in theory see a chance match if it read
1100 : * a partially-updated databaseId value; but as long as all such searches
1101 : * wait and retry, as in CountOtherDBBackends(), they will certainly see
1102 : * the correct value on their next try.
1103 : */
1104 23732 : MyProc->databaseId = MyDatabaseId;
1105 :
1106 : /*
1107 : * We established a catalog snapshot while reading pg_authid and/or
1108 : * pg_database; but until we have set up MyDatabaseId, we won't react to
1109 : * incoming sinval messages for unshared catalogs, so we won't realize it
1110 : * if the snapshot has been invalidated. Assume it's no good anymore.
1111 : */
1112 23732 : InvalidateCatalogSnapshot();
1113 :
1114 : /*
1115 : * Now we should be able to access the database directory safely. Verify
1116 : * it's there and looks reasonable.
1117 : */
1118 23732 : fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
1119 :
1120 23732 : if (!bootstrap)
1121 : {
1122 23652 : if (access(fullpath, F_OK) == -1)
1123 : {
1124 0 : if (errno == ENOENT)
1125 0 : ereport(FATAL,
1126 : (errcode(ERRCODE_UNDEFINED_DATABASE),
1127 : errmsg("database \"%s\" does not exist",
1128 : dbname),
1129 : errdetail("The database subdirectory \"%s\" is missing.",
1130 : fullpath)));
1131 : else
1132 0 : ereport(FATAL,
1133 : (errcode_for_file_access(),
1134 : errmsg("could not access directory \"%s\": %m",
1135 : fullpath)));
1136 : }
1137 :
1138 23652 : ValidatePgVersion(fullpath);
1139 : }
1140 :
1141 23732 : SetDatabasePath(fullpath);
1142 23732 : pfree(fullpath);
1143 :
1144 : /*
1145 : * It's now possible to do real access to the system catalogs.
1146 : *
1147 : * Load relcache entries for the system catalogs. This must create at
1148 : * least the minimum set of "nailed-in" cache entries.
1149 : */
1150 23732 : RelationCacheInitializePhase3();
1151 :
1152 : /* set up ACL framework (so CheckMyDatabase can check permissions) */
1153 23726 : initialize_acl();
1154 :
1155 : /*
1156 : * Re-read the pg_database row for our database, check permissions and set
1157 : * up database-specific GUC settings. We can't do this until all the
1158 : * database-access infrastructure is up. (Also, it wants to know if the
1159 : * user is a superuser, so the above stuff has to happen first.)
1160 : */
1161 23726 : if (!bootstrap)
1162 23646 : CheckMyDatabase(dbname, am_superuser,
1163 23646 : (flags & INIT_PG_OVERRIDE_ALLOW_CONNS) != 0);
1164 :
1165 : /*
1166 : * Now process any command-line switches and any additional GUC variable
1167 : * settings passed in the startup packet. We couldn't do this before
1168 : * because we didn't know if client is a superuser.
1169 : */
1170 23720 : if (MyProcPort != NULL)
1171 20142 : process_startup_options(MyProcPort, am_superuser);
1172 :
1173 : /* Process pg_db_role_setting options */
1174 23720 : process_settings(MyDatabaseId, GetSessionUserId());
1175 :
1176 : /* Apply PostAuthDelay as soon as we've read all options */
1177 23718 : if (PostAuthDelay > 0)
1178 0 : pg_usleep(PostAuthDelay * 1000000L);
1179 :
1180 : /*
1181 : * Initialize various default states that can't be set up until we've
1182 : * selected the active user and gotten the right GUC settings.
1183 : */
1184 :
1185 : /* set default namespace search path */
1186 23718 : InitializeSearchPath();
1187 :
1188 : /* initialize client encoding */
1189 23718 : InitializeClientEncoding();
1190 :
1191 : /* Initialize this backend's session state. */
1192 23718 : InitializeSession();
1193 :
1194 : /*
1195 : * If this is an interactive session, load any libraries that should be
1196 : * preloaded at backend start. Since those are determined by GUCs, this
1197 : * can't happen until GUC settings are complete, but we want it to happen
1198 : * during the initial transaction in case anything that requires database
1199 : * access needs to be done.
1200 : */
1201 23718 : if ((flags & INIT_PG_LOAD_SESSION_LIBS) != 0)
1202 19098 : process_session_preload_libraries();
1203 :
1204 : /* report this backend in the PgBackendStatus array */
1205 23718 : if (!bootstrap)
1206 23638 : pgstat_bestart();
1207 :
1208 : /* close the transaction we started above */
1209 23718 : if (!bootstrap)
1210 23638 : CommitTransactionCommand();
1211 : }
1212 :
1213 : /*
1214 : * Process any command-line switches and any additional GUC variable
1215 : * settings passed in the startup packet.
1216 : */
1217 : static void
1218 20978 : process_startup_options(Port *port, bool am_superuser)
1219 : {
1220 : GucContext gucctx;
1221 : ListCell *gucopts;
1222 :
1223 20978 : gucctx = am_superuser ? PGC_SU_BACKEND : PGC_BACKEND;
1224 :
1225 : /*
1226 : * First process any command-line switches that were included in the
1227 : * startup packet, if we are in a regular backend.
1228 : */
1229 20978 : if (port->cmdline_options != NULL)
1230 : {
1231 : /*
1232 : * The maximum possible number of commandline arguments that could
1233 : * come from port->cmdline_options is (strlen + 1) / 2; see
1234 : * pg_split_opts().
1235 : */
1236 : char **av;
1237 : int maxac;
1238 : int ac;
1239 :
1240 6090 : maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
1241 :
1242 6090 : av = (char **) palloc(maxac * sizeof(char *));
1243 6090 : ac = 0;
1244 :
1245 6090 : av[ac++] = "postgres";
1246 :
1247 6090 : pg_split_opts(av, &ac, port->cmdline_options);
1248 :
1249 6090 : av[ac] = NULL;
1250 :
1251 : Assert(ac < maxac);
1252 :
1253 6090 : (void) process_postgres_switches(ac, av, gucctx, NULL);
1254 : }
1255 :
1256 : /*
1257 : * Process any additional GUC variable settings passed in startup packet.
1258 : * These are handled exactly like command-line variables.
1259 : */
1260 20978 : gucopts = list_head(port->guc_options);
1261 51618 : while (gucopts)
1262 : {
1263 : char *name;
1264 : char *value;
1265 :
1266 30640 : name = lfirst(gucopts);
1267 30640 : gucopts = lnext(port->guc_options, gucopts);
1268 :
1269 30640 : value = lfirst(gucopts);
1270 30640 : gucopts = lnext(port->guc_options, gucopts);
1271 :
1272 30640 : SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
1273 : }
1274 20978 : }
1275 :
1276 : /*
1277 : * Load GUC settings from pg_db_role_setting.
1278 : *
1279 : * We try specific settings for the database/role combination, as well as
1280 : * general for this database and for this user.
1281 : */
1282 : static void
1283 23720 : process_settings(Oid databaseid, Oid roleid)
1284 : {
1285 : Relation relsetting;
1286 : Snapshot snapshot;
1287 :
1288 23720 : if (!IsUnderPostmaster)
1289 174 : return;
1290 :
1291 23546 : relsetting = table_open(DbRoleSettingRelationId, AccessShareLock);
1292 :
1293 : /* read all the settings under the same snapshot for efficiency */
1294 23546 : snapshot = RegisterSnapshot(GetCatalogSnapshot(DbRoleSettingRelationId));
1295 :
1296 : /* Later settings are ignored if set earlier. */
1297 23546 : ApplySetting(snapshot, databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
1298 23544 : ApplySetting(snapshot, InvalidOid, roleid, relsetting, PGC_S_USER);
1299 23544 : ApplySetting(snapshot, databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
1300 23544 : ApplySetting(snapshot, InvalidOid, InvalidOid, relsetting, PGC_S_GLOBAL);
1301 :
1302 23544 : UnregisterSnapshot(snapshot);
1303 23544 : table_close(relsetting, AccessShareLock);
1304 : }
1305 :
1306 : /*
1307 : * Backend-shutdown callback. Do cleanup that we want to be sure happens
1308 : * before all the supporting modules begin to nail their doors shut via
1309 : * their own callbacks.
1310 : *
1311 : * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
1312 : * via separate callbacks that execute before this one. We don't combine the
1313 : * callbacks because we still want this one to happen if the user-level
1314 : * cleanup fails.
1315 : */
1316 : static void
1317 26074 : ShutdownPostgres(int code, Datum arg)
1318 : {
1319 : /* Make sure we've killed any active transaction */
1320 26074 : AbortOutOfAnyTransaction();
1321 :
1322 : /*
1323 : * User locks are not released by transaction end, so be sure to release
1324 : * them explicitly.
1325 : */
1326 26074 : LockReleaseAll(USER_LOCKMETHOD, true);
1327 26074 : }
1328 :
1329 :
1330 : /*
1331 : * STATEMENT_TIMEOUT handler: trigger a query-cancel interrupt.
1332 : */
1333 : static void
1334 12 : StatementTimeoutHandler(void)
1335 : {
1336 12 : int sig = SIGINT;
1337 :
1338 : /*
1339 : * During authentication the timeout is used to deal with
1340 : * authentication_timeout - we want to quit in response to such timeouts.
1341 : */
1342 12 : if (ClientAuthInProgress)
1343 0 : sig = SIGTERM;
1344 :
1345 : #ifdef HAVE_SETSID
1346 : /* try to signal whole process group */
1347 12 : kill(-MyProcPid, sig);
1348 : #endif
1349 12 : kill(MyProcPid, sig);
1350 12 : }
1351 :
1352 : /*
1353 : * LOCK_TIMEOUT handler: trigger a query-cancel interrupt.
1354 : */
1355 : static void
1356 8 : LockTimeoutHandler(void)
1357 : {
1358 : #ifdef HAVE_SETSID
1359 : /* try to signal whole process group */
1360 8 : kill(-MyProcPid, SIGINT);
1361 : #endif
1362 8 : kill(MyProcPid, SIGINT);
1363 8 : }
1364 :
1365 : static void
1366 0 : TransactionTimeoutHandler(void)
1367 : {
1368 0 : TransactionTimeoutPending = true;
1369 0 : InterruptPending = true;
1370 0 : SetLatch(MyLatch);
1371 0 : }
1372 :
1373 : static void
1374 0 : IdleInTransactionSessionTimeoutHandler(void)
1375 : {
1376 0 : IdleInTransactionSessionTimeoutPending = true;
1377 0 : InterruptPending = true;
1378 0 : SetLatch(MyLatch);
1379 0 : }
1380 :
1381 : static void
1382 0 : IdleSessionTimeoutHandler(void)
1383 : {
1384 0 : IdleSessionTimeoutPending = true;
1385 0 : InterruptPending = true;
1386 0 : SetLatch(MyLatch);
1387 0 : }
1388 :
1389 : static void
1390 16 : IdleStatsUpdateTimeoutHandler(void)
1391 : {
1392 16 : IdleStatsUpdateTimeoutPending = true;
1393 16 : InterruptPending = true;
1394 16 : SetLatch(MyLatch);
1395 16 : }
1396 :
1397 : static void
1398 0 : ClientCheckTimeoutHandler(void)
1399 : {
1400 0 : CheckClientConnectionPending = true;
1401 0 : InterruptPending = true;
1402 0 : SetLatch(MyLatch);
1403 0 : }
1404 :
1405 : /*
1406 : * Returns true if at least one role is defined in this database cluster.
1407 : */
1408 : static bool
1409 98 : ThereIsAtLeastOneRole(void)
1410 : {
1411 : Relation pg_authid_rel;
1412 : TableScanDesc scan;
1413 : bool result;
1414 :
1415 98 : pg_authid_rel = table_open(AuthIdRelationId, AccessShareLock);
1416 :
1417 98 : scan = table_beginscan_catalog(pg_authid_rel, 0, NULL);
1418 98 : result = (heap_getnext(scan, ForwardScanDirection) != NULL);
1419 :
1420 98 : table_endscan(scan);
1421 98 : table_close(pg_authid_rel, AccessShareLock);
1422 :
1423 98 : return result;
1424 : }
|