1 /*-------------------------------------------------------------------------
4 * miscellaneous initialization support stuff
6 * Portions Copyright (c) 1996-2015, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * src/backend/utils/init/miscinit.c
13 *-------------------------------------------------------------------------
17 #include <sys/param.h>
23 #include <sys/types.h>
28 #include <netinet/in.h>
29 #include <arpa/inet.h>
34 #include "access/htup_details.h"
35 #include "catalog/pg_authid.h"
36 #include "mb/pg_wchar.h"
37 #include "miscadmin.h"
38 #include "postmaster/autovacuum.h"
39 #include "postmaster/postmaster.h"
40 #include "storage/fd.h"
41 #include "storage/ipc.h"
42 #include "storage/latch.h"
43 #include "storage/pg_shmem.h"
44 #include "storage/proc.h"
45 #include "storage/procarray.h"
46 #include "utils/builtins.h"
47 #include "utils/guc.h"
48 #include "utils/memutils.h"
49 #include "utils/syscache.h"
52 #define DIRECTORY_LOCK_FILE "postmaster.pid"
54 ProcessingMode Mode = InitProcessing;
56 /* List of lock files to be removed at proc exit */
57 static List *lock_files = NIL;
59 static Latch LocalLatchData;
61 /* ----------------------------------------------------------------
62 * ignoring system indexes support stuff
64 * NOTE: "ignoring system indexes" means we do not use the system indexes
65 * for lookups (either in hardwired catalog accesses or in planner-generated
66 * plans). We do, however, still update the indexes when a catalog
67 * modification is made.
68 * ----------------------------------------------------------------
71 bool IgnoreSystemIndexes = false;
74 /* ----------------------------------------------------------------
75 * database path / name support stuff
76 * ----------------------------------------------------------------
80 SetDatabasePath(const char *path)
82 /* This should happen only once per process */
83 Assert(!DatabasePath);
84 DatabasePath = MemoryContextStrdup(TopMemoryContext, path);
88 * Set data directory, but make sure it's an absolute path. Use this,
89 * never set DataDir directly.
92 SetDataDir(const char *dir)
98 /* If presented path is relative, convert to absolute */
99 new = make_absolute_path(dir);
107 * Change working directory to DataDir. Most of the postmaster and backend
108 * code assumes that we are in DataDir so it can use relative paths to access
109 * stuff in and under the data directory. For convenience during path
110 * setup, however, we don't force the chdir to occur during SetDataDir.
113 ChangeToDataDir(void)
115 AssertState(DataDir);
117 if (chdir(DataDir) < 0)
119 (errcode_for_file_access(),
120 errmsg("could not change directory to \"%s\": %m",
125 /* ----------------------------------------------------------------
128 * We have to track several different values associated with the concept
131 * AuthenticatedUserId is determined at connection start and never changes.
133 * SessionUserId is initially the same as AuthenticatedUserId, but can be
134 * changed by SET SESSION AUTHORIZATION (if AuthenticatedUserIsSuperuser).
135 * This is the ID reported by the SESSION_USER SQL function.
137 * OuterUserId is the current user ID in effect at the "outer level" (outside
138 * any transaction or function). This is initially the same as SessionUserId,
139 * but can be changed by SET ROLE to any role that SessionUserId is a
140 * member of. (XXX rename to something like CurrentRoleId?)
142 * CurrentUserId is the current effective user ID; this is the one to use
143 * for all normal permissions-checking purposes. At outer level this will
144 * be the same as OuterUserId, but it changes during calls to SECURITY
145 * DEFINER functions, as well as locally in some specialized commands.
147 * SecurityRestrictionContext holds flags indicating reason(s) for changing
148 * CurrentUserId. In some cases we need to lock down operations that are
149 * not directly controlled by privilege settings, and this provides a
150 * convenient way to do it.
151 * ----------------------------------------------------------------
153 static Oid AuthenticatedUserId = InvalidOid;
154 static Oid SessionUserId = InvalidOid;
155 static Oid OuterUserId = InvalidOid;
156 static Oid CurrentUserId = InvalidOid;
158 /* We also have to remember the superuser state of some of these levels */
159 static bool AuthenticatedUserIsSuperuser = false;
160 static bool SessionUserIsSuperuser = false;
162 static int SecurityRestrictionContext = 0;
164 /* We also remember if a SET ROLE is currently active */
165 static bool SetRoleIsActive = false;
168 * Initialize the basic environment for a postmaster child
170 * Should be called as early as possible after the child's startup.
173 InitPostmasterChild(void)
175 IsUnderPostmaster = true; /* we are a postmaster subprocess now */
177 MyProcPid = getpid(); /* reset MyProcPid */
179 MyStartTime = time(NULL); /* set our start time in case we call elog */
182 * make sure stderr is in binary mode before anything can possibly be
183 * written to it, in case it's actually the syslogger pipe, so the pipe
184 * chunking protocol isn't disturbed. Non-logpipe data gets translated on
185 * redirection (e.g. via pg_ctl -l) anyway.
188 _setmode(fileno(stderr), _O_BINARY);
191 /* We don't want the postmaster's proc_exit() handlers */
194 /* Initialize process-local latch support */
195 InitializeLatchSupport();
196 MyLatch = &LocalLatchData;
200 * If possible, make this process a group leader, so that the postmaster
201 * can signal any child processes too. Not all processes will have
202 * children, but for consistency we make all postmaster child processes do
207 elog(FATAL, "setsid() failed: %m");
212 * Initialize the basic environment for a standalone process.
214 * argv0 has to be suitable to find the program's executable.
217 InitStandaloneProcess(const char *argv0)
219 Assert(!IsPostmasterEnvironment);
221 MyProcPid = getpid(); /* reset MyProcPid */
223 MyStartTime = time(NULL); /* set our start time in case we call elog */
225 /* Initialize process-local latch support */
226 InitializeLatchSupport();
227 MyLatch = &LocalLatchData;
230 /* Compute paths, no postmaster to inherit from */
231 if (my_exec_path[0] == '\0')
233 if (find_my_exec(argv0, my_exec_path) < 0)
234 elog(FATAL, "%s: could not locate my own executable path",
238 if (pkglib_path[0] == '\0')
239 get_pkglib_path(my_exec_path, pkglib_path);
243 SwitchToSharedLatch(void)
245 Assert(MyLatch == &LocalLatchData);
246 Assert(MyProc != NULL);
248 MyLatch = &MyProc->procLatch;
251 * Set the shared latch as the local one might have been set. This
252 * shouldn't normally be necessary as code is supposed to check the
253 * condition before waiting for the latch, but a bit care can't hurt.
259 SwitchBackToLocalLatch(void)
261 Assert(MyLatch != &LocalLatchData);
262 Assert(MyProc != NULL && MyLatch == &MyProc->procLatch);
264 MyLatch = &LocalLatchData;
269 * GetUserId - get the current effective user ID.
271 * Note: there's no SetUserId() anymore; use SetUserIdAndSecContext().
276 AssertState(OidIsValid(CurrentUserId));
277 return CurrentUserId;
282 * GetOuterUserId/SetOuterUserId - get/set the outer-level user ID.
287 AssertState(OidIsValid(OuterUserId));
293 SetOuterUserId(Oid userid)
295 AssertState(SecurityRestrictionContext == 0);
296 AssertArg(OidIsValid(userid));
297 OuterUserId = userid;
299 /* We force the effective user ID to match, too */
300 CurrentUserId = userid;
305 * GetSessionUserId/SetSessionUserId - get/set the session user ID.
308 GetSessionUserId(void)
310 AssertState(OidIsValid(SessionUserId));
311 return SessionUserId;
316 SetSessionUserId(Oid userid, bool is_superuser)
318 AssertState(SecurityRestrictionContext == 0);
319 AssertArg(OidIsValid(userid));
320 SessionUserId = userid;
321 SessionUserIsSuperuser = is_superuser;
322 SetRoleIsActive = false;
324 /* We force the effective user IDs to match, too */
325 OuterUserId = userid;
326 CurrentUserId = userid;
330 * GetAuthenticatedUserId - get the authenticated user ID
333 GetAuthenticatedUserId(void)
335 AssertState(OidIsValid(AuthenticatedUserId));
336 return AuthenticatedUserId;
341 * GetUserIdAndSecContext/SetUserIdAndSecContext - get/set the current user ID
342 * and the SecurityRestrictionContext flags.
344 * Currently there are three valid bits in SecurityRestrictionContext:
346 * SECURITY_LOCAL_USERID_CHANGE indicates that we are inside an operation
347 * that is temporarily changing CurrentUserId via these functions. This is
348 * needed to indicate that the actual value of CurrentUserId is not in sync
349 * with guc.c's internal state, so SET ROLE has to be disallowed.
351 * SECURITY_RESTRICTED_OPERATION indicates that we are inside an operation
352 * that does not wish to trust called user-defined functions at all. This
353 * bit prevents not only SET ROLE, but various other changes of session state
354 * that normally is unprotected but might possibly be used to subvert the
355 * calling session later. An example is replacing an existing prepared
356 * statement with new code, which will then be executed with the outer
357 * session's permissions when the prepared statement is next used. Since
358 * these restrictions are fairly draconian, we apply them only in contexts
359 * where the called functions are really supposed to be side-effect-free
360 * anyway, such as VACUUM/ANALYZE/REINDEX.
362 * SECURITY_NOFORCE_RLS indicates that we are inside an operation which should
363 * ignore the FORCE ROW LEVEL SECURITY per-table indication. This is used to
364 * ensure that FORCE RLS does not mistakenly break referential integrity
365 * checks. Note that this is intentionally only checked when running as the
366 * owner of the table (which should always be the case for referential
369 * Unlike GetUserId, GetUserIdAndSecContext does *not* Assert that the current
370 * value of CurrentUserId is valid; nor does SetUserIdAndSecContext require
371 * the new value to be valid. In fact, these routines had better not
372 * ever throw any kind of error. This is because they are used by
373 * StartTransaction and AbortTransaction to save/restore the settings,
374 * and during the first transaction within a backend, the value to be saved
375 * and perhaps restored is indeed invalid. We have to be able to get
376 * through AbortTransaction without asserting in case InitPostgres fails.
379 GetUserIdAndSecContext(Oid *userid, int *sec_context)
381 *userid = CurrentUserId;
382 *sec_context = SecurityRestrictionContext;
386 SetUserIdAndSecContext(Oid userid, int sec_context)
388 CurrentUserId = userid;
389 SecurityRestrictionContext = sec_context;
394 * InLocalUserIdChange - are we inside a local change of CurrentUserId?
397 InLocalUserIdChange(void)
399 return (SecurityRestrictionContext & SECURITY_LOCAL_USERID_CHANGE) != 0;
403 * InSecurityRestrictedOperation - are we inside a security-restricted command?
406 InSecurityRestrictedOperation(void)
408 return (SecurityRestrictionContext & SECURITY_RESTRICTED_OPERATION) != 0;
412 * InNoForceRLSOperation - are we ignoring FORCE ROW LEVEL SECURITY ?
415 InNoForceRLSOperation(void)
417 return (SecurityRestrictionContext & SECURITY_NOFORCE_RLS) != 0;
422 * These are obsolete versions of Get/SetUserIdAndSecContext that are
423 * only provided for bug-compatibility with some rather dubious code in
424 * pljava. We allow the userid to be set, but only when not inside a
425 * security restriction context.
428 GetUserIdAndContext(Oid *userid, bool *sec_def_context)
430 *userid = CurrentUserId;
431 *sec_def_context = InLocalUserIdChange();
435 SetUserIdAndContext(Oid userid, bool sec_def_context)
437 /* We throw the same error SET ROLE would. */
438 if (InSecurityRestrictedOperation())
440 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
441 errmsg("cannot set parameter \"%s\" within security-restricted operation",
443 CurrentUserId = userid;
445 SecurityRestrictionContext |= SECURITY_LOCAL_USERID_CHANGE;
447 SecurityRestrictionContext &= ~SECURITY_LOCAL_USERID_CHANGE;
452 * Check whether specified role has explicit REPLICATION privilege
455 has_rolreplication(Oid roleid)
460 utup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
461 if (HeapTupleIsValid(utup))
463 result = ((Form_pg_authid) GETSTRUCT(utup))->rolreplication;
464 ReleaseSysCache(utup);
470 * Initialize user identity during normal backend startup
473 InitializeSessionUserId(const char *rolename, Oid roleid)
476 Form_pg_authid rform;
479 * Don't do scans if we're bootstrapping, none of the system catalogs
480 * exist yet, and they should be owned by postgres anyway.
482 AssertState(!IsBootstrapProcessingMode());
485 AssertState(!OidIsValid(AuthenticatedUserId));
487 if (rolename != NULL)
488 roleTup = SearchSysCache1(AUTHNAME, PointerGetDatum(rolename));
490 roleTup = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
491 if (!HeapTupleIsValid(roleTup))
493 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
494 errmsg("role \"%s\" does not exist", rolename)));
496 rform = (Form_pg_authid) GETSTRUCT(roleTup);
497 roleid = HeapTupleGetOid(roleTup);
499 AuthenticatedUserId = roleid;
500 AuthenticatedUserIsSuperuser = rform->rolsuper;
502 /* This sets OuterUserId/CurrentUserId too */
503 SetSessionUserId(roleid, AuthenticatedUserIsSuperuser);
505 /* Also mark our PGPROC entry with the authenticated user id */
506 /* (We assume this is an atomic store so no lock is needed) */
507 MyProc->roleId = roleid;
510 * These next checks are not enforced when in standalone mode, so that
511 * there is a way to recover from sillinesses like "UPDATE pg_authid SET
512 * rolcanlogin = false;".
514 if (IsUnderPostmaster)
517 * Is role allowed to login at all?
519 if (!rform->rolcanlogin)
521 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
522 errmsg("role \"%s\" is not permitted to log in",
526 * Check connection limit for this role.
528 * There is a race condition here --- we create our PGPROC before
529 * checking for other PGPROCs. If two backends did this at about the
530 * same time, they might both think they were over the limit, while
531 * ideally one should succeed and one fail. Getting that to work
532 * exactly seems more trouble than it is worth, however; instead we
533 * just document that the connection limit is approximate.
535 if (rform->rolconnlimit >= 0 &&
536 !AuthenticatedUserIsSuperuser &&
537 CountUserBackends(roleid) > rform->rolconnlimit)
539 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
540 errmsg("too many connections for role \"%s\"",
544 /* Record username and superuser status as GUC settings too */
545 SetConfigOption("session_authorization", rolename,
546 PGC_BACKEND, PGC_S_OVERRIDE);
547 SetConfigOption("is_superuser",
548 AuthenticatedUserIsSuperuser ? "on" : "off",
549 PGC_INTERNAL, PGC_S_OVERRIDE);
551 ReleaseSysCache(roleTup);
556 * Initialize user identity during special backend startup
559 InitializeSessionUserIdStandalone(void)
562 * This function should only be called in single-user mode, in autovacuum
563 * workers, and in background workers.
565 AssertState(!IsUnderPostmaster || IsAutoVacuumWorkerProcess() || IsBackgroundWorker);
568 AssertState(!OidIsValid(AuthenticatedUserId));
570 AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
571 AuthenticatedUserIsSuperuser = true;
573 SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
578 * Change session auth ID while running
580 * Only a superuser may set auth ID to something other than himself. Note
581 * that in case of multiple SETs in a single session, the original userid's
582 * superuserness is what matters. But we set the GUC variable is_superuser
583 * to indicate whether the *current* session userid is a superuser.
585 * Note: this is not an especially clean place to do the permission check.
586 * It's OK because the check does not require catalog access and can't
587 * fail during an end-of-transaction GUC reversion, but we may someday
588 * have to push it up into assign_session_authorization.
591 SetSessionAuthorization(Oid userid, bool is_superuser)
593 /* Must have authenticated already, else can't make permission check */
594 AssertState(OidIsValid(AuthenticatedUserId));
596 if (userid != AuthenticatedUserId &&
597 !AuthenticatedUserIsSuperuser)
599 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
600 errmsg("permission denied to set session authorization")));
602 SetSessionUserId(userid, is_superuser);
604 SetConfigOption("is_superuser",
605 is_superuser ? "on" : "off",
606 PGC_INTERNAL, PGC_S_OVERRIDE);
610 * Report current role id
611 * This follows the semantics of SET ROLE, ie return the outer-level ID
612 * not the current effective ID, and return InvalidOid when the setting
613 * is logically SET ROLE NONE.
616 GetCurrentRoleId(void)
625 * Change Role ID while running (SET ROLE)
627 * If roleid is InvalidOid, we are doing SET ROLE NONE: revert to the
628 * session user authorization. In this case the is_superuser argument
631 * When roleid is not InvalidOid, the caller must have checked whether
632 * the session user has permission to become that role. (We cannot check
633 * here because this routine must be able to execute in a failed transaction
634 * to restore a prior value of the ROLE GUC variable.)
637 SetCurrentRoleId(Oid roleid, bool is_superuser)
640 * Get correct info if it's SET ROLE NONE
642 * If SessionUserId hasn't been set yet, just do nothing --- the eventual
643 * SetSessionUserId call will fix everything. This is needed since we
644 * will get called during GUC initialization.
646 if (!OidIsValid(roleid))
648 if (!OidIsValid(SessionUserId))
651 roleid = SessionUserId;
652 is_superuser = SessionUserIsSuperuser;
654 SetRoleIsActive = false;
657 SetRoleIsActive = true;
659 SetOuterUserId(roleid);
661 SetConfigOption("is_superuser",
662 is_superuser ? "on" : "off",
663 PGC_INTERNAL, PGC_S_OVERRIDE);
668 * Get user name from user oid, returns NULL for nonexistent roleid if noerr
672 GetUserNameFromId(Oid roleid, bool noerr)
677 tuple = SearchSysCache1(AUTHOID, ObjectIdGetDatum(roleid));
678 if (!HeapTupleIsValid(tuple))
682 (errcode(ERRCODE_UNDEFINED_OBJECT),
683 errmsg("invalid role OID: %u", roleid)));
688 result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
689 ReleaseSysCache(tuple);
695 /*-------------------------------------------------------------------------
696 * Interlock-file support
698 * These routines are used to create both a data-directory lockfile
699 * ($DATADIR/postmaster.pid) and Unix-socket-file lockfiles ($SOCKFILE.lock).
700 * Both kinds of files contain the same info initially, although we can add
701 * more information to a data-directory lockfile after it's created, using
702 * AddToDataDirLockFile(). See miscadmin.h for documentation of the contents
703 * of these lockfiles.
705 * On successful lockfile creation, a proc_exit callback to remove the
706 * lockfile is automatically created.
707 *-------------------------------------------------------------------------
711 * proc_exit callback to remove lockfiles.
714 UnlinkLockFiles(int status, Datum arg)
718 foreach(l, lock_files)
720 char *curfile = (char *) lfirst(l);
723 /* Should we complain if the unlink fails? */
725 /* Since we're about to exit, no need to reclaim storage */
732 * filename is the path name of the lockfile to create.
733 * amPostmaster is used to determine how to encode the output PID.
734 * socketDir is the Unix socket directory path to include (possibly empty).
735 * isDDLock and refName are used to determine what error message to produce.
738 CreateLockFile(const char *filename, bool amPostmaster,
739 const char *socketDir,
740 bool isDDLock, const char *refName)
743 char buffer[MAXPGPATH * 2 + 256];
754 * If the PID in the lockfile is our own PID or our parent's or
755 * grandparent's PID, then the file must be stale (probably left over from
756 * a previous system boot cycle). We need to check this because of the
757 * likelihood that a reboot will assign exactly the same PID as we had in
758 * the previous reboot, or one that's only one or two counts larger and
759 * hence the lockfile's PID now refers to an ancestor shell process. We
760 * allow pg_ctl to pass down its parent shell PID (our grandparent PID)
761 * via the environment variable PG_GRANDPARENT_PID; this is so that
762 * launching the postmaster via pg_ctl can be just as reliable as
763 * launching it directly. There is no provision for detecting
764 * further-removed ancestor processes, but if the init script is written
765 * carefully then all but the immediate parent shell will be root-owned
766 * processes and so the kill test will fail with EPERM. Note that we
767 * cannot get a false negative this way, because an existing postmaster
768 * would surely never launch a competing postmaster or pg_ctl process
774 my_p_pid = getppid();
778 * Windows hasn't got getppid(), but doesn't need it since it's not using
779 * real kill() either...
784 envvar = getenv("PG_GRANDPARENT_PID");
786 my_gp_pid = atoi(envvar);
791 * We need a loop here because of race conditions. But don't loop forever
792 * (for example, a non-writable $PGDATA directory might cause a failure
793 * that won't go away). 100 tries seems like plenty.
795 for (ntries = 0;; ntries++)
798 * Try to create the lock file --- O_EXCL makes this atomic.
800 * Think not to make the file protection weaker than 0600. See
803 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
805 break; /* Success; exit the retry loop */
808 * Couldn't create the pid file. Probably it already exists.
810 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
812 (errcode_for_file_access(),
813 errmsg("could not create lock file \"%s\": %m",
817 * Read the file to get the old owner's PID. Note race condition
818 * here: file might have been deleted since we tried to create it.
820 fd = open(filename, O_RDONLY, 0600);
824 continue; /* race condition; try again */
826 (errcode_for_file_access(),
827 errmsg("could not open lock file \"%s\": %m",
830 if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
832 (errcode_for_file_access(),
833 errmsg("could not read lock file \"%s\": %m",
840 (errcode(ERRCODE_LOCK_FILE_EXISTS),
841 errmsg("lock file \"%s\" is empty", filename),
842 errhint("Either another server is starting, or the lock file is the remnant of a previous server startup crash.")));
846 encoded_pid = atoi(buffer);
848 /* if pid < 0, the pid is for postgres, not postmaster */
849 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
852 elog(FATAL, "bogus data in lock file \"%s\": \"%s\"",
856 * Check to see if the other process still exists
858 * Per discussion above, my_pid, my_p_pid, and my_gp_pid can be
859 * ignored as false matches.
861 * Normally kill() will fail with ESRCH if the given PID doesn't
864 * We can treat the EPERM-error case as okay because that error
865 * implies that the existing process has a different userid than we
866 * do, which means it cannot be a competing postmaster. A postmaster
867 * cannot successfully attach to a data directory owned by a userid
868 * other than its own. (This is now checked directly in
869 * checkDataDir(), but has been true for a long time because of the
870 * restriction that the data directory isn't group- or
871 * world-accessible.) Also, since we create the lockfiles mode 600,
872 * we'd have failed above if the lockfile belonged to another userid
873 * --- which means that whatever process kill() is reporting about
874 * isn't the one that made the lockfile. (NOTE: this last
875 * consideration is the only one that keeps us from blowing away a
876 * Unix socket file belonging to an instance of Postgres being run by
877 * someone else, at least on machines where /tmp hasn't got a
880 if (other_pid != my_pid && other_pid != my_p_pid &&
881 other_pid != my_gp_pid)
883 if (kill(other_pid, 0) == 0 ||
884 (errno != ESRCH && errno != EPERM))
886 /* lockfile belongs to a live process */
888 (errcode(ERRCODE_LOCK_FILE_EXISTS),
889 errmsg("lock file \"%s\" already exists",
893 errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
894 (int) other_pid, refName) :
895 errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
896 (int) other_pid, refName)) :
898 errhint("Is another postgres (PID %d) using socket file \"%s\"?",
899 (int) other_pid, refName) :
900 errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
901 (int) other_pid, refName))));
906 * No, the creating process did not exist. However, it could be that
907 * the postmaster crashed (or more likely was kill -9'd by a clueless
908 * admin) but has left orphan backends behind. Check for this by
909 * looking to see if there is an associated shmem segment that is
912 * Note: because postmaster.pid is written in multiple steps, we might
913 * not find the shmem ID values in it; we can't treat that as an
923 for (lineno = 1; lineno < LOCK_FILE_LINE_SHMEM_KEY; lineno++)
925 if ((ptr = strchr(ptr, '\n')) == NULL)
931 sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
933 if (PGSharedMemoryIsInUse(id1, id2))
935 (errcode(ERRCODE_LOCK_FILE_EXISTS),
936 errmsg("pre-existing shared memory block "
937 "(key %lu, ID %lu) is still in use",
939 errhint("If you're sure there are no old "
940 "server processes still running, remove "
941 "the shared memory block "
942 "or just delete the file \"%s\".",
948 * Looks like nobody's home. Unlink the file and try again to create
949 * it. Need a loop because of possible race condition against other
952 if (unlink(filename) < 0)
954 (errcode_for_file_access(),
955 errmsg("could not remove old lock file \"%s\": %m",
957 errhint("The file seems accidentally left over, but "
958 "it could not be removed. Please remove the file "
959 "by hand and try again.")));
963 * Successfully created the file, now fill it. See comment in miscadmin.h
964 * about the contents. Note that we write the same first five lines into
965 * both datadir and socket lockfiles; although more stuff may get added to
966 * the datadir lockfile later.
968 snprintf(buffer, sizeof(buffer), "%d\n%s\n%ld\n%d\n%s\n",
969 amPostmaster ? (int) my_pid : -((int) my_pid),
976 * In a standalone backend, the next line (LOCK_FILE_LINE_LISTEN_ADDR)
977 * will never receive data, so fill it in as empty now.
979 if (isDDLock && !amPostmaster)
980 strlcat(buffer, "\n", sizeof(buffer));
983 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
985 int save_errno = errno;
989 /* if write didn't set errno, assume problem is no disk space */
990 errno = save_errno ? save_errno : ENOSPC;
992 (errcode_for_file_access(),
993 errmsg("could not write lock file \"%s\": %m", filename)));
995 if (pg_fsync(fd) != 0)
997 int save_errno = errno;
1003 (errcode_for_file_access(),
1004 errmsg("could not write lock file \"%s\": %m", filename)));
1008 int save_errno = errno;
1013 (errcode_for_file_access(),
1014 errmsg("could not write lock file \"%s\": %m", filename)));
1018 * Arrange to unlink the lock file(s) at proc_exit. If this is the first
1019 * one, set up the on_proc_exit function to do it; then add this lock file
1020 * to the list of files to unlink.
1022 if (lock_files == NIL)
1023 on_proc_exit(UnlinkLockFiles, 0);
1026 * Use lcons so that the lock files are unlinked in reverse order of
1027 * creation; this is critical!
1029 lock_files = lcons(pstrdup(filename), lock_files);
1033 * Create the data directory lockfile.
1035 * When this is called, we must have already switched the working
1036 * directory to DataDir, so we can just use a relative path. This
1037 * helps ensure that we are locking the directory we should be.
1039 * Note that the socket directory path line is initially written as empty.
1040 * postmaster.c will rewrite it upon creating the first Unix socket.
1043 CreateDataDirLockFile(bool amPostmaster)
1045 CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, "", true, DataDir);
1049 * Create a lockfile for the specified Unix socket file.
1052 CreateSocketLockFile(const char *socketfile, bool amPostmaster,
1053 const char *socketDir)
1055 char lockfile[MAXPGPATH];
1057 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
1058 CreateLockFile(lockfile, amPostmaster, socketDir, false, socketfile);
1062 * TouchSocketLockFiles -- mark socket lock files as recently accessed
1064 * This routine should be called every so often to ensure that the socket
1065 * lock files have a recent mod or access date. That saves them
1066 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
1067 * (Another reason we should never have put the socket file in /tmp...)
1070 TouchSocketLockFiles(void)
1074 foreach(l, lock_files)
1076 char *socketLockFile = (char *) lfirst(l);
1078 /* No need to touch the data directory lock file, we trust */
1079 if (strcmp(socketLockFile, DIRECTORY_LOCK_FILE) == 0)
1083 * utime() is POSIX standard, utimes() is a common alternative; if we
1084 * have neither, fall back to actually reading the file (which only
1085 * sets the access time not mod time, but that should be enough in
1086 * most cases). In all paths, we ignore errors.
1089 utime(socketLockFile, NULL);
1090 #else /* !HAVE_UTIME */
1092 utimes(socketLockFile, NULL);
1093 #else /* !HAVE_UTIMES */
1097 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
1100 read(fd, buffer, sizeof(buffer));
1103 #endif /* HAVE_UTIMES */
1104 #endif /* HAVE_UTIME */
1110 * Add (or replace) a line in the data directory lock file.
1111 * The given string should not include a trailing newline.
1113 * Note: because we don't truncate the file, if we were to rewrite a line
1114 * with less data than it had before, there would be garbage after the last
1115 * line. We don't ever actually do that, so not worth adding another kernel
1116 * call to cover the possibility.
1119 AddToDataDirLockFile(int target_line, const char *str)
1126 char srcbuffer[BLCKSZ];
1127 char destbuffer[BLCKSZ];
1129 fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1133 (errcode_for_file_access(),
1134 errmsg("could not open file \"%s\": %m",
1135 DIRECTORY_LOCK_FILE)));
1138 len = read(fd, srcbuffer, sizeof(srcbuffer) - 1);
1142 (errcode_for_file_access(),
1143 errmsg("could not read from file \"%s\": %m",
1144 DIRECTORY_LOCK_FILE)));
1148 srcbuffer[len] = '\0';
1151 * Advance over lines we are not supposed to rewrite, then copy them to
1155 for (lineno = 1; lineno < target_line; lineno++)
1157 if ((srcptr = strchr(srcptr, '\n')) == NULL)
1159 elog(LOG, "incomplete data in \"%s\": found only %d newlines while trying to add line %d",
1160 DIRECTORY_LOCK_FILE, lineno - 1, target_line);
1166 memcpy(destbuffer, srcbuffer, srcptr - srcbuffer);
1167 destptr = destbuffer + (srcptr - srcbuffer);
1170 * Write or rewrite the target line.
1172 snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s\n", str);
1173 destptr += strlen(destptr);
1176 * If there are more lines in the old file, append them to destbuffer.
1178 if ((srcptr = strchr(srcptr, '\n')) != NULL)
1181 snprintf(destptr, destbuffer + sizeof(destbuffer) - destptr, "%s",
1186 * And rewrite the data. Since we write in a single kernel call, this
1187 * update should appear atomic to onlookers.
1189 len = strlen(destbuffer);
1191 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
1192 (int) write(fd, destbuffer, len) != len)
1194 /* if write didn't set errno, assume problem is no disk space */
1198 (errcode_for_file_access(),
1199 errmsg("could not write to file \"%s\": %m",
1200 DIRECTORY_LOCK_FILE)));
1204 if (pg_fsync(fd) != 0)
1207 (errcode_for_file_access(),
1208 errmsg("could not write to file \"%s\": %m",
1209 DIRECTORY_LOCK_FILE)));
1214 (errcode_for_file_access(),
1215 errmsg("could not write to file \"%s\": %m",
1216 DIRECTORY_LOCK_FILE)));
1222 * Recheck that the data directory lock file still exists with expected
1223 * content. Return TRUE if the lock file appears OK, FALSE if it isn't.
1225 * We call this periodically in the postmaster. The idea is that if the
1226 * lock file has been removed or replaced by another postmaster, we should
1227 * do a panic database shutdown. Therefore, we should return TRUE if there
1228 * is any doubt: we do not want to cause a panic shutdown unnecessarily.
1229 * Transient failures like EINTR or ENFILE should not cause us to fail.
1230 * (If there really is something wrong, we'll detect it on a future recheck.)
1233 RecheckDataDirLockFile(void)
1238 char buffer[BLCKSZ];
1240 fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
1244 * There are many foreseeable false-positive error conditions. For
1245 * safety, fail only on enumerated clearly-something-is-wrong
1254 (errcode_for_file_access(),
1255 errmsg("could not open file \"%s\": %m",
1256 DIRECTORY_LOCK_FILE)));
1259 /* non-fatal, at least for now */
1261 (errcode_for_file_access(),
1262 errmsg("could not open file \"%s\": %m; continuing anyway",
1263 DIRECTORY_LOCK_FILE)));
1267 len = read(fd, buffer, sizeof(buffer) - 1);
1271 (errcode_for_file_access(),
1272 errmsg("could not read from file \"%s\": %m",
1273 DIRECTORY_LOCK_FILE)));
1275 return true; /* treat read failure as nonfatal */
1279 file_pid = atol(buffer);
1280 if (file_pid == getpid())
1281 return true; /* all is well */
1283 /* Trouble: someone's overwritten the lock file */
1285 (errmsg("lock file \"%s\" contains wrong PID: %ld instead of %ld",
1286 DIRECTORY_LOCK_FILE, file_pid, (long) getpid())));
1291 /*-------------------------------------------------------------------------
1292 * Version checking support
1293 *-------------------------------------------------------------------------
1297 * Determine whether the PG_VERSION file in directory `path' indicates
1298 * a data version compatible with the version of this program.
1300 * If compatible, return. Otherwise, ereport(FATAL).
1303 ValidatePgVersion(const char *path)
1305 char full_path[MAXPGPATH];
1313 const char *version_string = PG_VERSION;
1315 my_major = strtol(version_string, &endptr, 10);
1317 my_minor = strtol(endptr + 1, NULL, 10);
1319 snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1321 file = AllocateFile(full_path, "r");
1324 if (errno == ENOENT)
1326 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1327 errmsg("\"%s\" is not a valid data directory",
1329 errdetail("File \"%s\" is missing.", full_path)));
1332 (errcode_for_file_access(),
1333 errmsg("could not open file \"%s\": %m", full_path)));
1336 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
1339 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1340 errmsg("\"%s\" is not a valid data directory",
1342 errdetail("File \"%s\" does not contain valid data.",
1344 errhint("You might need to initdb.")));
1348 if (my_major != file_major || my_minor != file_minor)
1350 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1351 errmsg("database files are incompatible with server"),
1352 errdetail("The data directory was initialized by PostgreSQL version %ld.%ld, "
1353 "which is not compatible with this version %s.",
1354 file_major, file_minor, version_string)));
1357 /*-------------------------------------------------------------------------
1358 * Library preload support
1359 *-------------------------------------------------------------------------
1363 * GUC variables: lists of library names to be preloaded at postmaster
1364 * start and at backend start
1366 char *session_preload_libraries_string = NULL;
1367 char *shared_preload_libraries_string = NULL;
1368 char *local_preload_libraries_string = NULL;
1370 /* Flag telling that we are loading shared_preload_libraries */
1371 bool process_shared_preload_libraries_in_progress = false;
1374 * load the shared libraries listed in 'libraries'
1376 * 'gucname': name of GUC variable, for error reports
1377 * 'restricted': if true, force libraries to be in $libdir/plugins/
1380 load_libraries(const char *libraries, const char *gucname, bool restricted)
1386 if (libraries == NULL || libraries[0] == '\0')
1387 return; /* nothing to do */
1389 /* Need a modifiable copy of string */
1390 rawstring = pstrdup(libraries);
1392 /* Parse string into list of identifiers */
1393 if (!SplitIdentifierString(rawstring, ',', &elemlist))
1395 /* syntax error in list */
1397 list_free(elemlist);
1399 (errcode(ERRCODE_SYNTAX_ERROR),
1400 errmsg("invalid list syntax in parameter \"%s\"",
1405 foreach(l, elemlist)
1407 char *tok = (char *) lfirst(l);
1410 filename = pstrdup(tok);
1411 canonicalize_path(filename);
1412 /* If restricting, insert $libdir/plugins if not mentioned already */
1413 if (restricted && first_dir_separator(filename) == NULL)
1417 expanded = psprintf("$libdir/plugins/%s", filename);
1419 filename = expanded;
1421 load_file(filename, restricted);
1423 (errmsg("loaded library \"%s\"", filename)));
1428 list_free(elemlist);
1432 * process any libraries that should be preloaded at postmaster start
1435 process_shared_preload_libraries(void)
1437 process_shared_preload_libraries_in_progress = true;
1438 load_libraries(shared_preload_libraries_string,
1439 "shared_preload_libraries",
1441 process_shared_preload_libraries_in_progress = false;
1445 * process any libraries that should be preloaded at backend start
1448 process_session_preload_libraries(void)
1450 load_libraries(session_preload_libraries_string,
1451 "session_preload_libraries",
1453 load_libraries(local_preload_libraries_string,
1454 "local_preload_libraries",
1459 pg_bindtextdomain(const char *domain)
1462 if (my_exec_path[0] != '\0')
1464 char locale_path[MAXPGPATH];
1466 get_locale_path(my_exec_path, locale_path);
1467 bindtextdomain(domain, locale_path);
1468 pg_bind_textdomain_codeset(domain);