Line data Source code
1 : /*-------------------------------------------------------------------------
2 : *
3 : * postinit.c
4 : * postgres initialization utilities
5 : *
6 : * Portions Copyright (c) 1996-2023, PostgreSQL Global Development Group
7 : * Portions Copyright (c) 1994, Regents of the University of California
8 : *
9 : *
10 : * IDENTIFICATION
11 : * src/backend/utils/init/postinit.c
12 : *
13 : *
14 : *-------------------------------------------------------------------------
15 : */
16 : #include "postgres.h"
17 :
18 : #include <ctype.h>
19 : #include <fcntl.h>
20 : #include <unistd.h>
21 :
22 : #include "access/genam.h"
23 : #include "access/heapam.h"
24 : #include "access/htup_details.h"
25 : #include "access/session.h"
26 : #include "access/sysattr.h"
27 : #include "access/tableam.h"
28 : #include "access/xact.h"
29 : #include "access/xlog.h"
30 : #include "access/xloginsert.h"
31 : #include "catalog/catalog.h"
32 : #include "catalog/namespace.h"
33 : #include "catalog/pg_authid.h"
34 : #include "catalog/pg_collation.h"
35 : #include "catalog/pg_database.h"
36 : #include "catalog/pg_db_role_setting.h"
37 : #include "catalog/pg_tablespace.h"
38 : #include "libpq/auth.h"
39 : #include "libpq/libpq-be.h"
40 : #include "mb/pg_wchar.h"
41 : #include "miscadmin.h"
42 : #include "pgstat.h"
43 : #include "postmaster/autovacuum.h"
44 : #include "postmaster/postmaster.h"
45 : #include "replication/slot.h"
46 : #include "replication/walsender.h"
47 : #include "storage/bufmgr.h"
48 : #include "storage/fd.h"
49 : #include "storage/ipc.h"
50 : #include "storage/lmgr.h"
51 : #include "storage/proc.h"
52 : #include "storage/procarray.h"
53 : #include "storage/procsignal.h"
54 : #include "storage/sinvaladt.h"
55 : #include "storage/smgr.h"
56 : #include "storage/sync.h"
57 : #include "tcop/tcopprot.h"
58 : #include "utils/acl.h"
59 : #include "utils/builtins.h"
60 : #include "utils/fmgroids.h"
61 : #include "utils/guc_hooks.h"
62 : #include "utils/memutils.h"
63 : #include "utils/pg_locale.h"
64 : #include "utils/portal.h"
65 : #include "utils/ps_status.h"
66 : #include "utils/snapmgr.h"
67 : #include "utils/syscache.h"
68 : #include "utils/timeout.h"
69 :
70 : static HeapTuple GetDatabaseTuple(const char *dbname);
71 : static HeapTuple GetDatabaseTupleByOid(Oid dboid);
72 : static void PerformAuthentication(Port *port);
73 : static void CheckMyDatabase(const char *name, bool am_superuser, bool override_allow_connections);
74 : static void ShutdownPostgres(int code, Datum arg);
75 : static void StatementTimeoutHandler(void);
76 : static void LockTimeoutHandler(void);
77 : static void IdleInTransactionSessionTimeoutHandler(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 39518 : 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 39518 : 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 39518 : relation = table_open(DatabaseRelationId, AccessShareLock);
122 39518 : scan = systable_beginscan(relation, DatabaseNameIndexId,
123 : criticalSharedRelcachesBuilt,
124 : NULL,
125 : 1, key);
126 :
127 39518 : tuple = systable_getnext(scan);
128 :
129 : /* Must copy tuple before releasing buffer */
130 39518 : if (HeapTupleIsValid(tuple))
131 39496 : tuple = heap_copytuple(tuple);
132 :
133 : /* all done */
134 39518 : systable_endscan(scan);
135 39518 : table_close(relation, AccessShareLock);
136 :
137 39518 : return tuple;
138 : }
139 :
140 : /*
141 : * GetDatabaseTupleByOid -- as above, but search by database OID
142 : */
143 : static HeapTuple
144 3260 : 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 3260 : 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 3260 : relation = table_open(DatabaseRelationId, AccessShareLock);
165 3260 : scan = systable_beginscan(relation, DatabaseOidIndexId,
166 : criticalSharedRelcachesBuilt,
167 : NULL,
168 : 1, key);
169 :
170 3260 : tuple = systable_getnext(scan);
171 :
172 : /* Must copy tuple before releasing buffer */
173 3260 : if (HeapTupleIsValid(tuple))
174 3260 : tuple = heap_copytuple(tuple);
175 :
176 : /* all done */
177 3260 : systable_endscan(scan);
178 3260 : table_close(relation, AccessShareLock);
179 :
180 3260 : 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 18314 : PerformAuthentication(Port *port)
191 : {
192 : /* This should be set already, but let's make sure */
193 18314 : 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 18314 : enable_timeout_after(STATEMENT_TIMEOUT, AuthenticationTimeout * 1000);
241 :
242 : /*
243 : * Now perform authentication exchange.
244 : */
245 18314 : set_ps_display("authentication");
246 18314 : ClientAuthentication(port); /* might not return, if failure */
247 :
248 : /*
249 : * Done with authentication. Disable the timeout, and log if needed.
250 : */
251 18198 : disable_timeout(STATEMENT_TIMEOUT, false);
252 :
253 18198 : if (Log_connections)
254 : {
255 : StringInfoData logmsg;
256 :
257 490 : initStringInfo(&logmsg);
258 490 : if (am_walsender)
259 6 : appendStringInfo(&logmsg, _("replication connection authorized: user=%s"),
260 : port->user_name);
261 : else
262 484 : appendStringInfo(&logmsg, _("connection authorized: user=%s"),
263 : port->user_name);
264 490 : if (!am_walsender)
265 484 : appendStringInfo(&logmsg, _(" database=%s"), port->database_name);
266 :
267 490 : if (port->application_name != NULL)
268 490 : appendStringInfo(&logmsg, _(" application_name=%s"),
269 : port->application_name);
270 :
271 : #ifdef USE_SSL
272 490 : if (port->ssl_in_use)
273 156 : 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 490 : ereport(LOG, errmsg_internal("%s", logmsg.data));
300 490 : pfree(logmsg.data);
301 : }
302 :
303 18198 : set_ps_display("startup");
304 :
305 18198 : ClientAuthInProgress = false; /* client_min_messages is active now */
306 18198 : }
307 :
308 :
309 : /*
310 : * CheckMyDatabase -- fetch information from the pg_database entry for our DB
311 : */
312 : static void
313 21374 : 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 *iculocale;
322 :
323 : /* Fetch our pg_database row normally, via syscache */
324 21374 : tup = SearchSysCache1(DATABASEOID, ObjectIdGetDatum(MyDatabaseId));
325 21374 : if (!HeapTupleIsValid(tup))
326 0 : elog(ERROR, "cache lookup failed for database %u", MyDatabaseId);
327 21374 : dbform = (Form_pg_database) GETSTRUCT(tup);
328 :
329 : /* This recheck is strictly paranoia */
330 21374 : 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 21374 : if (IsUnderPostmaster && !IsAutoVacuumWorkerProcess())
348 : {
349 : /*
350 : * Check that the database is currently allowing connections.
351 : */
352 20732 : if (!dbform->datallowconn && !override_allow_connections)
353 0 : ereport(FATAL,
354 : (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
355 : errmsg("database \"%s\" is not currently accepting connections",
356 : name)));
357 :
358 : /*
359 : * Check privilege to connect to the database. (The am_superuser test
360 : * is redundant, but since we have the flag, might as well check it
361 : * and save a few cycles.)
362 : */
363 21122 : if (!am_superuser &&
364 390 : 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 20732 : 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 21374 : SetDatabaseEncoding(dbform->encoding);
395 : /* Record it as a GUC internal option, too */
396 21374 : 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 21374 : SetConfigOption("client_encoding", GetDatabaseEncodingName(),
400 : PGC_BACKEND, PGC_S_DYNAMIC_DEFAULT);
401 :
402 : /* assign locale variables */
403 21374 : datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datcollate);
404 21374 : collate = TextDatumGetCString(datum);
405 21374 : datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_datctype);
406 21374 : ctype = TextDatumGetCString(datum);
407 :
408 21374 : 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 21374 : 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 21374 : if (strcmp(ctype, "C") == 0 ||
423 18796 : strcmp(ctype, "POSIX") == 0)
424 2578 : database_ctype_is_c = true;
425 :
426 21374 : if (dbform->datlocprovider == COLLPROVIDER_ICU)
427 : {
428 : char *icurules;
429 :
430 21242 : datum = SysCacheGetAttrNotNull(DATABASEOID, tup, Anum_pg_database_daticulocale);
431 21242 : iculocale = TextDatumGetCString(datum);
432 :
433 21242 : datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_daticurules, &isnull);
434 21242 : if (!isnull)
435 0 : icurules = TextDatumGetCString(datum);
436 : else
437 21242 : icurules = NULL;
438 :
439 21242 : make_icu_collator(iculocale, icurules, &default_locale);
440 : }
441 : else
442 132 : iculocale = NULL;
443 :
444 21370 : default_locale.provider = dbform->datlocprovider;
445 :
446 : /*
447 : * Default locale is currently always deterministic. Nondeterministic
448 : * locales currently don't support pattern matching, which would break a
449 : * lot of things if applied globally.
450 : */
451 21370 : default_locale.deterministic = true;
452 :
453 : /*
454 : * Check collation version. See similar code in
455 : * pg_newlocale_from_collation(). Note that here we warn instead of error
456 : * in any case, so that we don't prevent connecting.
457 : */
458 21370 : datum = SysCacheGetAttr(DATABASEOID, tup, Anum_pg_database_datcollversion,
459 : &isnull);
460 21370 : if (!isnull)
461 : {
462 : char *actual_versionstr;
463 : char *collversionstr;
464 :
465 20736 : collversionstr = TextDatumGetCString(datum);
466 :
467 20736 : actual_versionstr = get_collation_actual_version(dbform->datlocprovider, dbform->datlocprovider == COLLPROVIDER_ICU ? iculocale : collate);
468 20736 : if (!actual_versionstr)
469 : /* should not happen */
470 0 : elog(WARNING,
471 : "database \"%s\" has no actual collation version, but a version was recorded",
472 : name);
473 20736 : else if (strcmp(actual_versionstr, collversionstr) != 0)
474 0 : ereport(WARNING,
475 : (errmsg("database \"%s\" has a collation version mismatch",
476 : name),
477 : errdetail("The database was created using collation version %s, "
478 : "but the operating system provides version %s.",
479 : collversionstr, actual_versionstr),
480 : errhint("Rebuild all objects in this database that use the default collation and run "
481 : "ALTER DATABASE %s REFRESH COLLATION VERSION, "
482 : "or build PostgreSQL with the right library version.",
483 : quote_identifier(name))));
484 : }
485 :
486 : /* Make the locale settings visible as GUC variables, too */
487 21370 : SetConfigOption("lc_collate", collate, PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
488 21370 : SetConfigOption("lc_ctype", ctype, PGC_INTERNAL, PGC_S_DYNAMIC_DEFAULT);
489 :
490 21370 : ReleaseSysCache(tup);
491 21370 : }
492 :
493 :
494 : /*
495 : * pg_split_opts -- split a string of options and append it to an argv array
496 : *
497 : * The caller is responsible for ensuring the argv array is large enough. The
498 : * maximum possible number of arguments added by this routine is
499 : * (strlen(optstr) + 1) / 2.
500 : *
501 : * Because some option values can contain spaces we allow escaping using
502 : * backslashes, with \\ representing a literal backslash.
503 : */
504 : void
505 5258 : pg_split_opts(char **argv, int *argcp, const char *optstr)
506 : {
507 : StringInfoData s;
508 :
509 5258 : initStringInfo(&s);
510 :
511 19162 : while (*optstr)
512 : {
513 13904 : bool last_was_escape = false;
514 :
515 13904 : resetStringInfo(&s);
516 :
517 : /* skip over leading space */
518 26562 : while (isspace((unsigned char) *optstr))
519 12658 : optstr++;
520 :
521 13904 : if (*optstr == '\0')
522 0 : break;
523 :
524 : /*
525 : * Parse a single option, stopping at the first space, unless it's
526 : * escaped.
527 : */
528 208708 : while (*optstr)
529 : {
530 203450 : if (isspace((unsigned char) *optstr) && !last_was_escape)
531 8646 : break;
532 :
533 194804 : if (!last_was_escape && *optstr == '\\')
534 18 : last_was_escape = true;
535 : else
536 : {
537 194786 : last_was_escape = false;
538 194786 : appendStringInfoChar(&s, *optstr);
539 : }
540 :
541 194804 : optstr++;
542 : }
543 :
544 : /* now store the option in the next argv[] position */
545 13904 : argv[(*argcp)++] = pstrdup(s.data);
546 : }
547 :
548 5258 : pfree(s.data);
549 5258 : }
550 :
551 : /*
552 : * Initialize MaxBackends value from config options.
553 : *
554 : * This must be called after modules have had the chance to alter GUCs in
555 : * shared_preload_libraries and before shared memory size is determined.
556 : *
557 : * Note that in EXEC_BACKEND environment, the value is passed down from
558 : * postmaster to subprocesses via BackendParameters in SubPostmasterMain; only
559 : * postmaster itself and processes not under postmaster control should call
560 : * this.
561 : */
562 : void
563 3634 : InitializeMaxBackends(void)
564 : {
565 : Assert(MaxBackends == 0);
566 :
567 : /* the extra unit accounts for the autovacuum launcher */
568 3634 : MaxBackends = MaxConnections + autovacuum_max_workers + 1 +
569 3634 : max_worker_processes + max_wal_senders;
570 :
571 : /* internal error because the values were all checked previously */
572 3634 : if (MaxBackends > MAX_BACKENDS)
573 0 : elog(ERROR, "too many backends configured");
574 3634 : }
575 :
576 : /*
577 : * GUC check_hook for max_connections
578 : */
579 : bool
580 8038 : check_max_connections(int *newval, void **extra, GucSource source)
581 : {
582 8038 : if (*newval + autovacuum_max_workers + 1 +
583 8038 : max_worker_processes + max_wal_senders > MAX_BACKENDS)
584 0 : return false;
585 8038 : return true;
586 : }
587 :
588 : /*
589 : * GUC check_hook for autovacuum_max_workers
590 : */
591 : bool
592 3698 : check_autovacuum_max_workers(int *newval, void **extra, GucSource source)
593 : {
594 3698 : if (MaxConnections + *newval + 1 +
595 3698 : max_worker_processes + max_wal_senders > MAX_BACKENDS)
596 0 : return false;
597 3698 : return true;
598 : }
599 :
600 : /*
601 : * GUC check_hook for max_worker_processes
602 : */
603 : bool
604 3698 : check_max_worker_processes(int *newval, void **extra, GucSource source)
605 : {
606 3698 : if (MaxConnections + autovacuum_max_workers + 1 +
607 3698 : *newval + max_wal_senders > MAX_BACKENDS)
608 0 : return false;
609 3698 : return true;
610 : }
611 :
612 : /*
613 : * GUC check_hook for max_wal_senders
614 : */
615 : bool
616 5376 : check_max_wal_senders(int *newval, void **extra, GucSource source)
617 : {
618 5376 : if (MaxConnections + autovacuum_max_workers + 1 +
619 5376 : max_worker_processes + *newval > MAX_BACKENDS)
620 0 : return false;
621 5376 : return true;
622 : }
623 :
624 : /*
625 : * Early initialization of a backend (either standalone or under postmaster).
626 : * This happens even before InitPostgres.
627 : *
628 : * This is separate from InitPostgres because it is also called by auxiliary
629 : * processes, such as the background writer process, which may not call
630 : * InitPostgres at all.
631 : */
632 : void
633 27546 : BaseInit(void)
634 : {
635 : Assert(MyProc != NULL);
636 :
637 : /*
638 : * Initialize our input/output/debugging file descriptors.
639 : */
640 27546 : DebugFileOpen();
641 :
642 : /*
643 : * Initialize file access. Done early so other subsystems can access
644 : * files.
645 : */
646 27546 : InitFileAccess();
647 :
648 : /*
649 : * Initialize statistics reporting. This needs to happen early to ensure
650 : * that pgstat's shutdown callback runs after the shutdown callbacks of
651 : * all subsystems that can produce stats (like e.g. transaction commits
652 : * can).
653 : */
654 27546 : pgstat_initialize();
655 :
656 : /* Do local initialization of storage and buffer managers */
657 27546 : InitSync();
658 27546 : smgrinit();
659 27546 : InitBufferPoolAccess();
660 :
661 : /*
662 : * Initialize temporary file access after pgstat, so that the temporary
663 : * file shutdown hook can report temporary file statistics.
664 : */
665 27546 : InitTemporaryFileAccess();
666 :
667 : /*
668 : * Initialize local buffers for WAL record construction, in case we ever
669 : * try to insert XLOG.
670 : */
671 27546 : InitXLogInsert();
672 :
673 : /*
674 : * Initialize replication slots after pgstat. The exit hook might need to
675 : * drop ephemeral slots, which in turn triggers stats reporting.
676 : */
677 27546 : ReplicationSlotInitialize();
678 27546 : }
679 :
680 :
681 : /* --------------------------------
682 : * InitPostgres
683 : * Initialize POSTGRES.
684 : *
685 : * Parameters:
686 : * in_dbname, dboid: specify database to connect to, as described below
687 : * username, useroid: specify role to connect as, as described below
688 : * load_session_libraries: TRUE to honor [session|local]_preload_libraries
689 : * override_allow_connections: TRUE to connect despite !datallowconn
690 : * out_dbname: optional output parameter, see below; pass NULL if not used
691 : *
692 : * The database can be specified by name, using the in_dbname parameter, or by
693 : * OID, using the dboid parameter. Specify NULL or InvalidOid respectively
694 : * for the unused parameter. If dboid is provided, the actual database
695 : * name can be returned to the caller in out_dbname. If out_dbname isn't
696 : * NULL, it must point to a buffer of size NAMEDATALEN.
697 : *
698 : * Similarly, the role can be passed by name, using the username parameter,
699 : * or by OID using the useroid parameter.
700 : *
701 : * In bootstrap mode the database and username parameters are NULL/InvalidOid.
702 : * The autovacuum launcher process doesn't specify these parameters either,
703 : * because it only goes far enough to be able to read pg_database; it doesn't
704 : * connect to any particular database. An autovacuum worker specifies a
705 : * database but not a username; conversely, a physical walsender specifies
706 : * username but not database.
707 : *
708 : * By convention, load_session_libraries should be passed as true in
709 : * "interactive" sessions (including standalone backends), but false in
710 : * background processes such as autovacuum. Note in particular that it
711 : * shouldn't be true in parallel worker processes; those have another
712 : * mechanism for replicating their leader's set of loaded libraries.
713 : *
714 : * We expect that InitProcess() was already called, so we already have a
715 : * PGPROC struct ... but it's not completely filled in yet.
716 : *
717 : * Note:
718 : * Be very careful with the order of calls in the InitPostgres function.
719 : * --------------------------------
720 : */
721 : void
722 24042 : InitPostgres(const char *in_dbname, Oid dboid,
723 : const char *username, Oid useroid,
724 : bool load_session_libraries,
725 : bool override_allow_connections,
726 : char *out_dbname)
727 : {
728 24042 : bool bootstrap = IsBootstrapProcessingMode();
729 : bool am_superuser;
730 : char *fullpath;
731 : char dbname[NAMEDATALEN];
732 24042 : int nfree = 0;
733 :
734 24042 : elog(DEBUG3, "InitPostgres");
735 :
736 : /*
737 : * Add my PGPROC struct to the ProcArray.
738 : *
739 : * Once I have done this, I am visible to other backends!
740 : */
741 24042 : InitProcessPhase2();
742 :
743 : /*
744 : * Initialize my entry in the shared-invalidation manager's array of
745 : * per-backend data.
746 : *
747 : * Sets up MyBackendId, a unique backend identifier.
748 : */
749 24042 : MyBackendId = InvalidBackendId;
750 :
751 24042 : SharedInvalBackendInit(false);
752 :
753 24042 : if (MyBackendId > MaxBackends || MyBackendId <= 0)
754 0 : elog(FATAL, "bad backend ID: %d", MyBackendId);
755 :
756 : /* Now that we have a BackendId, we can participate in ProcSignal */
757 24042 : ProcSignalInit(MyBackendId);
758 :
759 : /*
760 : * Also set up timeout handlers needed for backend operation. We need
761 : * these in every case except bootstrap.
762 : */
763 24042 : if (!bootstrap)
764 : {
765 23436 : RegisterTimeout(DEADLOCK_TIMEOUT, CheckDeadLockAlert);
766 23436 : RegisterTimeout(STATEMENT_TIMEOUT, StatementTimeoutHandler);
767 23436 : RegisterTimeout(LOCK_TIMEOUT, LockTimeoutHandler);
768 23436 : RegisterTimeout(IDLE_IN_TRANSACTION_SESSION_TIMEOUT,
769 : IdleInTransactionSessionTimeoutHandler);
770 23436 : RegisterTimeout(IDLE_SESSION_TIMEOUT, IdleSessionTimeoutHandler);
771 23436 : RegisterTimeout(CLIENT_CONNECTION_CHECK_TIMEOUT, ClientCheckTimeoutHandler);
772 23436 : RegisterTimeout(IDLE_STATS_UPDATE_TIMEOUT,
773 : IdleStatsUpdateTimeoutHandler);
774 : }
775 :
776 : /*
777 : * If this is either a bootstrap process or a standalone backend, start up
778 : * the XLOG machinery, and register to have it closed down at exit. In
779 : * other cases, the startup process is responsible for starting up the
780 : * XLOG machinery, and the checkpointer for closing it down.
781 : */
782 24042 : if (!IsUnderPostmaster)
783 : {
784 : /*
785 : * We don't yet have an aux-process resource owner, but StartupXLOG
786 : * and ShutdownXLOG will need one. Hence, create said resource owner
787 : * (and register a callback to clean it up after ShutdownXLOG runs).
788 : */
789 1230 : CreateAuxProcessResourceOwner();
790 :
791 1230 : StartupXLOG();
792 : /* Release (and warn about) any buffer pins leaked in StartupXLOG */
793 1230 : ReleaseAuxProcessResources(true);
794 : /* Reset CurrentResourceOwner to nothing for the moment */
795 1230 : CurrentResourceOwner = NULL;
796 :
797 : /*
798 : * Use before_shmem_exit() so that ShutdownXLOG() can rely on DSM
799 : * segments etc to work (which in turn is required for pgstats).
800 : */
801 1230 : before_shmem_exit(pgstat_before_server_shutdown, 0);
802 1230 : before_shmem_exit(ShutdownXLOG, 0);
803 : }
804 :
805 : /*
806 : * Initialize the relation cache and the system catalog caches. Note that
807 : * no catalog access happens here; we only set up the hashtable structure.
808 : * We must do this before starting a transaction because transaction abort
809 : * would try to touch these hashtables.
810 : */
811 24042 : RelationCacheInitialize();
812 24042 : InitCatalogCache();
813 24042 : InitPlanCache();
814 :
815 : /* Initialize portal manager */
816 24042 : EnablePortalManager();
817 :
818 : /* Initialize status reporting */
819 24042 : pgstat_beinit();
820 :
821 : /*
822 : * Load relcache entries for the shared system catalogs. This must create
823 : * at least entries for pg_database and catalogs used for authentication.
824 : */
825 24042 : RelationCacheInitializePhase2();
826 :
827 : /*
828 : * Set up process-exit callback to do pre-shutdown cleanup. This is the
829 : * one of the first before_shmem_exit callbacks we register; thus, this
830 : * will be one the last things we do before low-level modules like the
831 : * buffer manager begin to close down. We need to have this in place
832 : * before we begin our first transaction --- if we fail during the
833 : * initialization transaction, as is entirely possible, we need the
834 : * AbortTransaction call to clean up.
835 : */
836 24042 : before_shmem_exit(ShutdownPostgres, 0);
837 :
838 : /* The autovacuum launcher is done here */
839 24042 : if (IsAutoVacuumLauncherProcess())
840 : {
841 : /* report this backend in the PgBackendStatus array */
842 598 : pgstat_bestart();
843 :
844 1910 : return;
845 : }
846 :
847 : /*
848 : * Start a new transaction here before first access to db, and get a
849 : * snapshot. We don't have a use for the snapshot itself, but we're
850 : * interested in the secondary effect that it sets RecentGlobalXmin. (This
851 : * is critical for anything that reads heap pages, because HOT may decide
852 : * to prune them even if the process doesn't attempt to modify any
853 : * tuples.)
854 : *
855 : * FIXME: This comment is inaccurate / the code buggy. A snapshot that is
856 : * not pushed/active does not reliably prevent HOT pruning (->xmin could
857 : * e.g. be cleared when cache invalidations are processed).
858 : */
859 23444 : if (!bootstrap)
860 : {
861 : /* statement_timestamp must be set for timeouts to work correctly */
862 22838 : SetCurrentStatementStartTimestamp();
863 22838 : StartTransactionCommand();
864 :
865 : /*
866 : * transaction_isolation will have been set to the default by the
867 : * above. If the default is "serializable", and we are in hot
868 : * standby, we will fail if we don't change it to something lower.
869 : * Fortunately, "read committed" is plenty good enough.
870 : */
871 22838 : XactIsoLevel = XACT_READ_COMMITTED;
872 :
873 22838 : (void) GetTransactionSnapshot();
874 : }
875 :
876 : /*
877 : * Perform client authentication if necessary, then figure out our
878 : * postgres user ID, and see if we are a superuser.
879 : *
880 : * In standalone mode and in autovacuum worker processes, we use a fixed
881 : * ID, otherwise we figure it out from the authenticated user name.
882 : */
883 23444 : if (bootstrap || IsAutoVacuumWorkerProcess())
884 : {
885 624 : InitializeSessionUserIdStandalone();
886 624 : am_superuser = true;
887 : }
888 22820 : else if (!IsUnderPostmaster)
889 : {
890 624 : InitializeSessionUserIdStandalone();
891 624 : am_superuser = true;
892 624 : if (!ThereIsAtLeastOneRole())
893 0 : ereport(WARNING,
894 : (errcode(ERRCODE_UNDEFINED_OBJECT),
895 : errmsg("no roles are defined in this database system"),
896 : errhint("You should immediately run CREATE USER \"%s\" SUPERUSER;.",
897 : username != NULL ? username : "postgres")));
898 : }
899 22196 : else if (IsBackgroundWorker)
900 : {
901 3882 : if (username == NULL && !OidIsValid(useroid))
902 : {
903 640 : InitializeSessionUserIdStandalone();
904 640 : am_superuser = true;
905 : }
906 : else
907 : {
908 3242 : InitializeSessionUserId(username, useroid);
909 3240 : am_superuser = superuser();
910 : }
911 : }
912 : else
913 : {
914 : /* normal multiuser case */
915 : Assert(MyProcPort != NULL);
916 18314 : PerformAuthentication(MyProcPort);
917 18198 : InitializeSessionUserId(username, useroid);
918 : /* ensure that auth_method is actually valid, aka authn_id is not NULL */
919 18190 : if (MyClientConnectionInfo.authn_id)
920 200 : InitializeSystemUser(MyClientConnectionInfo.authn_id,
921 : hba_authname(MyClientConnectionInfo.auth_method));
922 18190 : am_superuser = superuser();
923 : }
924 :
925 : /*
926 : * Binary upgrades only allowed super-user connections
927 : */
928 23318 : if (IsBinaryUpgrade && !am_superuser)
929 : {
930 0 : ereport(FATAL,
931 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
932 : errmsg("must be superuser to connect in binary upgrade mode")));
933 : }
934 :
935 : /*
936 : * The last few connection slots are reserved for superusers and roles
937 : * with privileges of pg_use_reserved_connections. Replication
938 : * connections are drawn from slots reserved with max_wal_senders and are
939 : * not limited by max_connections, superuser_reserved_connections, or
940 : * reserved_connections.
941 : *
942 : * Note: At this point, the new backend has already claimed a proc struct,
943 : * so we must check whether the number of free slots is strictly less than
944 : * the reserved connection limits.
945 : */
946 23318 : if (!am_superuser && !am_walsender &&
947 394 : (SuperuserReservedConnections + ReservedConnections) > 0 &&
948 394 : !HaveNFreeProcs(SuperuserReservedConnections + ReservedConnections, &nfree))
949 : {
950 0 : if (nfree < SuperuserReservedConnections)
951 0 : ereport(FATAL,
952 : (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
953 : errmsg("remaining connection slots are reserved for roles with %s",
954 : "SUPERUSER")));
955 :
956 0 : if (!has_privs_of_role(GetUserId(), ROLE_PG_USE_RESERVED_CONNECTIONS))
957 0 : ereport(FATAL,
958 : (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
959 : errmsg("remaining connection slots are reserved for roles with privileges of the \"%s\" role",
960 : "pg_use_reserved_connections")));
961 : }
962 :
963 : /* Check replication permissions needed for walsender processes. */
964 23318 : if (am_walsender)
965 : {
966 : Assert(!bootstrap);
967 :
968 1662 : if (!has_rolreplication(GetUserId()))
969 0 : ereport(FATAL,
970 : (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
971 : errmsg("permission denied to start WAL sender"),
972 : errdetail("Only roles with the %s attribute may start a WAL sender process.",
973 : "REPLICATION")));
974 : }
975 :
976 : /*
977 : * If this is a plain walsender only supporting physical replication, we
978 : * don't want to connect to any particular database. Just finish the
979 : * backend startup by processing any options from the startup packet, and
980 : * we're done.
981 : */
982 23318 : if (am_walsender && !am_db_walsender)
983 : {
984 : /* process any options passed in the startup packet */
985 680 : if (MyProcPort != NULL)
986 680 : process_startup_options(MyProcPort, am_superuser);
987 :
988 : /* Apply PostAuthDelay as soon as we've read all options */
989 680 : if (PostAuthDelay > 0)
990 0 : pg_usleep(PostAuthDelay * 1000000L);
991 :
992 : /* initialize client encoding */
993 680 : InitializeClientEncoding();
994 :
995 : /* report this backend in the PgBackendStatus array */
996 680 : pgstat_bestart();
997 :
998 : /* close the transaction we started above */
999 680 : CommitTransactionCommand();
1000 :
1001 680 : return;
1002 : }
1003 :
1004 : /*
1005 : * Set up the global variables holding database id and default tablespace.
1006 : * But note we won't actually try to touch the database just yet.
1007 : *
1008 : * We take a shortcut in the bootstrap case, otherwise we have to look up
1009 : * the db's entry in pg_database.
1010 : */
1011 22638 : if (bootstrap)
1012 : {
1013 606 : MyDatabaseId = Template1DbOid;
1014 606 : MyDatabaseTableSpace = DEFAULTTABLESPACE_OID;
1015 : }
1016 22032 : else if (in_dbname != NULL)
1017 : {
1018 : HeapTuple tuple;
1019 : Form_pg_database dbform;
1020 :
1021 18140 : tuple = GetDatabaseTuple(in_dbname);
1022 18140 : if (!HeapTupleIsValid(tuple))
1023 22 : ereport(FATAL,
1024 : (errcode(ERRCODE_UNDEFINED_DATABASE),
1025 : errmsg("database \"%s\" does not exist", in_dbname)));
1026 18118 : dbform = (Form_pg_database) GETSTRUCT(tuple);
1027 18118 : MyDatabaseId = dbform->oid;
1028 18118 : MyDatabaseTableSpace = dbform->dattablespace;
1029 : /* take database name from the caller, just for paranoia */
1030 18118 : strlcpy(dbname, in_dbname, sizeof(dbname));
1031 : }
1032 3892 : else if (OidIsValid(dboid))
1033 : {
1034 : /* caller specified database by OID */
1035 : HeapTuple tuple;
1036 : Form_pg_database dbform;
1037 :
1038 3260 : tuple = GetDatabaseTupleByOid(dboid);
1039 3260 : if (!HeapTupleIsValid(tuple))
1040 0 : ereport(FATAL,
1041 : (errcode(ERRCODE_UNDEFINED_DATABASE),
1042 : errmsg("database %u does not exist", dboid)));
1043 3260 : dbform = (Form_pg_database) GETSTRUCT(tuple);
1044 3260 : MyDatabaseId = dbform->oid;
1045 3260 : MyDatabaseTableSpace = dbform->dattablespace;
1046 : Assert(MyDatabaseId == dboid);
1047 3260 : strlcpy(dbname, NameStr(dbform->datname), sizeof(dbname));
1048 : /* pass the database name back to the caller */
1049 3260 : if (out_dbname)
1050 18 : strcpy(out_dbname, dbname);
1051 : }
1052 : else
1053 : {
1054 : /*
1055 : * If this is a background worker not bound to any particular
1056 : * database, we're done now. Everything that follows only makes sense
1057 : * if we are bound to a specific database. We do need to close the
1058 : * transaction we started before returning.
1059 : */
1060 632 : if (!bootstrap)
1061 : {
1062 632 : pgstat_bestart();
1063 632 : CommitTransactionCommand();
1064 : }
1065 632 : return;
1066 : }
1067 :
1068 : /*
1069 : * Now, take a writer's lock on the database we are trying to connect to.
1070 : * If there is a concurrently running DROP DATABASE on that database, this
1071 : * will block us until it finishes (and has committed its update of
1072 : * pg_database).
1073 : *
1074 : * Note that the lock is not held long, only until the end of this startup
1075 : * transaction. This is OK since we will advertise our use of the
1076 : * database in the ProcArray before dropping the lock (in fact, that's the
1077 : * next thing to do). Anyone trying a DROP DATABASE after this point will
1078 : * see us in the array once they have the lock. Ordering is important for
1079 : * this because we don't want to advertise ourselves as being in this
1080 : * database until we have the lock; otherwise we create what amounts to a
1081 : * deadlock with CountOtherDBBackends().
1082 : *
1083 : * Note: use of RowExclusiveLock here is reasonable because we envision
1084 : * our session as being a concurrent writer of the database. If we had a
1085 : * way of declaring a session as being guaranteed-read-only, we could use
1086 : * AccessShareLock for such sessions and thereby not conflict against
1087 : * CREATE DATABASE.
1088 : */
1089 21984 : if (!bootstrap)
1090 21378 : LockSharedObject(DatabaseRelationId, MyDatabaseId, 0,
1091 : RowExclusiveLock);
1092 :
1093 : /*
1094 : * Now we can mark our PGPROC entry with the database ID.
1095 : *
1096 : * We assume this is an atomic store so no lock is needed; though actually
1097 : * things would work fine even if it weren't atomic. Anyone searching the
1098 : * ProcArray for this database's ID should hold the database lock, so they
1099 : * would not be executing concurrently with this store. A process looking
1100 : * for another database's ID could in theory see a chance match if it read
1101 : * a partially-updated databaseId value; but as long as all such searches
1102 : * wait and retry, as in CountOtherDBBackends(), they will certainly see
1103 : * the correct value on their next try.
1104 : */
1105 21984 : MyProc->databaseId = MyDatabaseId;
1106 :
1107 : /*
1108 : * We established a catalog snapshot while reading pg_authid and/or
1109 : * pg_database; but until we have set up MyDatabaseId, we won't react to
1110 : * incoming sinval messages for unshared catalogs, so we won't realize it
1111 : * if the snapshot has been invalidated. Assume it's no good anymore.
1112 : */
1113 21984 : InvalidateCatalogSnapshot();
1114 :
1115 : /*
1116 : * Recheck pg_database to make sure the target database hasn't gone away.
1117 : * If there was a concurrent DROP DATABASE, this ensures we will die
1118 : * cleanly without creating a mess.
1119 : */
1120 21984 : if (!bootstrap)
1121 : {
1122 : HeapTuple tuple;
1123 :
1124 21378 : tuple = GetDatabaseTuple(dbname);
1125 21378 : if (!HeapTupleIsValid(tuple) ||
1126 21378 : MyDatabaseId != ((Form_pg_database) GETSTRUCT(tuple))->oid ||
1127 21378 : MyDatabaseTableSpace != ((Form_pg_database) GETSTRUCT(tuple))->dattablespace)
1128 0 : ereport(FATAL,
1129 : (errcode(ERRCODE_UNDEFINED_DATABASE),
1130 : errmsg("database \"%s\" does not exist", dbname),
1131 : errdetail("It seems to have just been dropped or renamed.")));
1132 : }
1133 :
1134 : /*
1135 : * Now we should be able to access the database directory safely. Verify
1136 : * it's there and looks reasonable.
1137 : */
1138 21984 : fullpath = GetDatabasePath(MyDatabaseId, MyDatabaseTableSpace);
1139 :
1140 21984 : if (!bootstrap)
1141 : {
1142 21378 : if (access(fullpath, F_OK) == -1)
1143 : {
1144 0 : if (errno == ENOENT)
1145 0 : ereport(FATAL,
1146 : (errcode(ERRCODE_UNDEFINED_DATABASE),
1147 : errmsg("database \"%s\" does not exist",
1148 : dbname),
1149 : errdetail("The database subdirectory \"%s\" is missing.",
1150 : fullpath)));
1151 : else
1152 0 : ereport(FATAL,
1153 : (errcode_for_file_access(),
1154 : errmsg("could not access directory \"%s\": %m",
1155 : fullpath)));
1156 : }
1157 :
1158 21378 : ValidatePgVersion(fullpath);
1159 : }
1160 :
1161 21984 : SetDatabasePath(fullpath);
1162 21984 : pfree(fullpath);
1163 :
1164 : /*
1165 : * It's now possible to do real access to the system catalogs.
1166 : *
1167 : * Load relcache entries for the system catalogs. This must create at
1168 : * least the minimum set of "nailed-in" cache entries.
1169 : */
1170 21984 : RelationCacheInitializePhase3();
1171 :
1172 : /* set up ACL framework (so CheckMyDatabase can check permissions) */
1173 21980 : initialize_acl();
1174 :
1175 : /*
1176 : * Re-read the pg_database row for our database, check permissions and set
1177 : * up database-specific GUC settings. We can't do this until all the
1178 : * database-access infrastructure is up. (Also, it wants to know if the
1179 : * user is a superuser, so the above stuff has to happen first.)
1180 : */
1181 21980 : if (!bootstrap)
1182 21374 : CheckMyDatabase(dbname, am_superuser, override_allow_connections);
1183 :
1184 : /*
1185 : * Now process any command-line switches and any additional GUC variable
1186 : * settings passed in the startup packet. We couldn't do this before
1187 : * because we didn't know if client is a superuser.
1188 : */
1189 21976 : if (MyProcPort != NULL)
1190 17492 : process_startup_options(MyProcPort, am_superuser);
1191 :
1192 : /* Process pg_db_role_setting options */
1193 21976 : process_settings(MyDatabaseId, GetSessionUserId());
1194 :
1195 : /* Apply PostAuthDelay as soon as we've read all options */
1196 21974 : if (PostAuthDelay > 0)
1197 0 : pg_usleep(PostAuthDelay * 1000000L);
1198 :
1199 : /*
1200 : * Initialize various default states that can't be set up until we've
1201 : * selected the active user and gotten the right GUC settings.
1202 : */
1203 :
1204 : /* set default namespace search path */
1205 21974 : InitializeSearchPath();
1206 :
1207 : /* initialize client encoding */
1208 21974 : InitializeClientEncoding();
1209 :
1210 : /* Initialize this backend's session state. */
1211 21974 : InitializeSession();
1212 :
1213 : /*
1214 : * If this is an interactive session, load any libraries that should be
1215 : * preloaded at backend start. Since those are determined by GUCs, this
1216 : * can't happen until GUC settings are complete, but we want it to happen
1217 : * during the initial transaction in case anything that requires database
1218 : * access needs to be done.
1219 : */
1220 21974 : if (load_session_libraries)
1221 17130 : process_session_preload_libraries();
1222 :
1223 : /* report this backend in the PgBackendStatus array */
1224 21974 : if (!bootstrap)
1225 21368 : pgstat_bestart();
1226 :
1227 : /* close the transaction we started above */
1228 21974 : if (!bootstrap)
1229 21368 : CommitTransactionCommand();
1230 : }
1231 :
1232 : /*
1233 : * Process any command-line switches and any additional GUC variable
1234 : * settings passed in the startup packet.
1235 : */
1236 : static void
1237 18172 : process_startup_options(Port *port, bool am_superuser)
1238 : {
1239 : GucContext gucctx;
1240 : ListCell *gucopts;
1241 :
1242 18172 : gucctx = am_superuser ? PGC_SU_BACKEND : PGC_BACKEND;
1243 :
1244 : /*
1245 : * First process any command-line switches that were included in the
1246 : * startup packet, if we are in a regular backend.
1247 : */
1248 18172 : if (port->cmdline_options != NULL)
1249 : {
1250 : /*
1251 : * The maximum possible number of commandline arguments that could
1252 : * come from port->cmdline_options is (strlen + 1) / 2; see
1253 : * pg_split_opts().
1254 : */
1255 : char **av;
1256 : int maxac;
1257 : int ac;
1258 :
1259 5258 : maxac = 2 + (strlen(port->cmdline_options) + 1) / 2;
1260 :
1261 5258 : av = (char **) palloc(maxac * sizeof(char *));
1262 5258 : ac = 0;
1263 :
1264 5258 : av[ac++] = "postgres";
1265 :
1266 5258 : pg_split_opts(av, &ac, port->cmdline_options);
1267 :
1268 5258 : av[ac] = NULL;
1269 :
1270 : Assert(ac < maxac);
1271 :
1272 5258 : (void) process_postgres_switches(ac, av, gucctx, NULL);
1273 : }
1274 :
1275 : /*
1276 : * Process any additional GUC variable settings passed in startup packet.
1277 : * These are handled exactly like command-line variables.
1278 : */
1279 18172 : gucopts = list_head(port->guc_options);
1280 45538 : while (gucopts)
1281 : {
1282 : char *name;
1283 : char *value;
1284 :
1285 27366 : name = lfirst(gucopts);
1286 27366 : gucopts = lnext(port->guc_options, gucopts);
1287 :
1288 27366 : value = lfirst(gucopts);
1289 27366 : gucopts = lnext(port->guc_options, gucopts);
1290 :
1291 27366 : SetConfigOption(name, value, gucctx, PGC_S_CLIENT);
1292 : }
1293 18172 : }
1294 :
1295 : /*
1296 : * Load GUC settings from pg_db_role_setting.
1297 : *
1298 : * We try specific settings for the database/role combination, as well as
1299 : * general for this database and for this user.
1300 : */
1301 : static void
1302 21976 : process_settings(Oid databaseid, Oid roleid)
1303 : {
1304 : Relation relsetting;
1305 : Snapshot snapshot;
1306 :
1307 21976 : if (!IsUnderPostmaster)
1308 1226 : return;
1309 :
1310 20750 : relsetting = table_open(DbRoleSettingRelationId, AccessShareLock);
1311 :
1312 : /* read all the settings under the same snapshot for efficiency */
1313 20750 : snapshot = RegisterSnapshot(GetCatalogSnapshot(DbRoleSettingRelationId));
1314 :
1315 : /* Later settings are ignored if set earlier. */
1316 20750 : ApplySetting(snapshot, databaseid, roleid, relsetting, PGC_S_DATABASE_USER);
1317 20748 : ApplySetting(snapshot, InvalidOid, roleid, relsetting, PGC_S_USER);
1318 20748 : ApplySetting(snapshot, databaseid, InvalidOid, relsetting, PGC_S_DATABASE);
1319 20748 : ApplySetting(snapshot, InvalidOid, InvalidOid, relsetting, PGC_S_GLOBAL);
1320 :
1321 20748 : UnregisterSnapshot(snapshot);
1322 20748 : table_close(relsetting, AccessShareLock);
1323 : }
1324 :
1325 : /*
1326 : * Backend-shutdown callback. Do cleanup that we want to be sure happens
1327 : * before all the supporting modules begin to nail their doors shut via
1328 : * their own callbacks.
1329 : *
1330 : * User-level cleanup, such as temp-relation removal and UNLISTEN, happens
1331 : * via separate callbacks that execute before this one. We don't combine the
1332 : * callbacks because we still want this one to happen if the user-level
1333 : * cleanup fails.
1334 : */
1335 : static void
1336 24042 : ShutdownPostgres(int code, Datum arg)
1337 : {
1338 : /* Make sure we've killed any active transaction */
1339 24042 : AbortOutOfAnyTransaction();
1340 :
1341 : /*
1342 : * User locks are not released by transaction end, so be sure to release
1343 : * them explicitly.
1344 : */
1345 24042 : LockReleaseAll(USER_LOCKMETHOD, true);
1346 24042 : }
1347 :
1348 :
1349 : /*
1350 : * STATEMENT_TIMEOUT handler: trigger a query-cancel interrupt.
1351 : */
1352 : static void
1353 10 : StatementTimeoutHandler(void)
1354 : {
1355 10 : int sig = SIGINT;
1356 :
1357 : /*
1358 : * During authentication the timeout is used to deal with
1359 : * authentication_timeout - we want to quit in response to such timeouts.
1360 : */
1361 10 : if (ClientAuthInProgress)
1362 0 : sig = SIGTERM;
1363 :
1364 : #ifdef HAVE_SETSID
1365 : /* try to signal whole process group */
1366 10 : kill(-MyProcPid, sig);
1367 : #endif
1368 10 : kill(MyProcPid, sig);
1369 10 : }
1370 :
1371 : /*
1372 : * LOCK_TIMEOUT handler: trigger a query-cancel interrupt.
1373 : */
1374 : static void
1375 8 : LockTimeoutHandler(void)
1376 : {
1377 : #ifdef HAVE_SETSID
1378 : /* try to signal whole process group */
1379 8 : kill(-MyProcPid, SIGINT);
1380 : #endif
1381 8 : kill(MyProcPid, SIGINT);
1382 8 : }
1383 :
1384 : static void
1385 0 : IdleInTransactionSessionTimeoutHandler(void)
1386 : {
1387 0 : IdleInTransactionSessionTimeoutPending = true;
1388 0 : InterruptPending = true;
1389 0 : SetLatch(MyLatch);
1390 0 : }
1391 :
1392 : static void
1393 0 : IdleSessionTimeoutHandler(void)
1394 : {
1395 0 : IdleSessionTimeoutPending = true;
1396 0 : InterruptPending = true;
1397 0 : SetLatch(MyLatch);
1398 0 : }
1399 :
1400 : static void
1401 16 : IdleStatsUpdateTimeoutHandler(void)
1402 : {
1403 16 : IdleStatsUpdateTimeoutPending = true;
1404 16 : InterruptPending = true;
1405 16 : SetLatch(MyLatch);
1406 16 : }
1407 :
1408 : static void
1409 0 : ClientCheckTimeoutHandler(void)
1410 : {
1411 0 : CheckClientConnectionPending = true;
1412 0 : InterruptPending = true;
1413 0 : SetLatch(MyLatch);
1414 0 : }
1415 :
1416 : /*
1417 : * Returns true if at least one role is defined in this database cluster.
1418 : */
1419 : static bool
1420 624 : ThereIsAtLeastOneRole(void)
1421 : {
1422 : Relation pg_authid_rel;
1423 : TableScanDesc scan;
1424 : bool result;
1425 :
1426 624 : pg_authid_rel = table_open(AuthIdRelationId, AccessShareLock);
1427 :
1428 624 : scan = table_beginscan_catalog(pg_authid_rel, 0, NULL);
1429 624 : result = (heap_getnext(scan, ForwardScanDirection) != NULL);
1430 :
1431 624 : table_endscan(scan);
1432 624 : table_close(pg_authid_rel, AccessShareLock);
1433 :
1434 624 : return result;
1435 : }
|