1 /*-------------------------------------------------------------------------
4 * miscellaneous initialization support stuff
6 * Portions Copyright (c) 1996-2007, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
11 * $PostgreSQL: pgsql/src/backend/utils/init/miscinit.c,v 1.164 2007/09/11 00:06:42 tgl Exp $
13 *-------------------------------------------------------------------------
17 #include <sys/param.h>
26 #include <netinet/in.h>
27 #include <arpa/inet.h>
32 #include "catalog/pg_authid.h"
33 #include "miscadmin.h"
34 #include "postmaster/autovacuum.h"
35 #include "storage/fd.h"
36 #include "storage/ipc.h"
37 #include "storage/pg_shmem.h"
38 #include "storage/proc.h"
39 #include "storage/procarray.h"
40 #include "utils/builtins.h"
41 #include "utils/guc.h"
42 #include "utils/syscache.h"
45 #define DIRECTORY_LOCK_FILE "postmaster.pid"
47 ProcessingMode Mode = InitProcessing;
49 /* Note: we rely on this to initialize as zeroes */
50 static char socketLockFile[MAXPGPATH];
53 /* ----------------------------------------------------------------
54 * ignoring system indexes support stuff
56 * NOTE: "ignoring system indexes" means we do not use the system indexes
57 * for lookups (either in hardwired catalog accesses or in planner-generated
58 * plans). We do, however, still update the indexes when a catalog
59 * modification is made.
60 * ----------------------------------------------------------------
63 bool IgnoreSystemIndexes = false;
65 /* ----------------------------------------------------------------
66 * system index reindexing support
68 * When we are busy reindexing a system index, this code provides support
69 * for preventing catalog lookups from using that index.
70 * ----------------------------------------------------------------
73 static Oid currentlyReindexedHeap = InvalidOid;
74 static Oid currentlyReindexedIndex = InvalidOid;
77 * ReindexIsProcessingHeap
78 * True if heap specified by OID is currently being reindexed.
81 ReindexIsProcessingHeap(Oid heapOid)
83 return heapOid == currentlyReindexedHeap;
87 * ReindexIsProcessingIndex
88 * True if index specified by OID is currently being reindexed.
91 ReindexIsProcessingIndex(Oid indexOid)
93 return indexOid == currentlyReindexedIndex;
97 * SetReindexProcessing
98 * Set flag that specified heap/index are being reindexed.
101 SetReindexProcessing(Oid heapOid, Oid indexOid)
103 Assert(OidIsValid(heapOid) && OidIsValid(indexOid));
104 /* Reindexing is not re-entrant. */
105 if (OidIsValid(currentlyReindexedIndex))
106 elog(ERROR, "cannot reindex while reindexing");
107 currentlyReindexedHeap = heapOid;
108 currentlyReindexedIndex = indexOid;
112 * ResetReindexProcessing
113 * Unset reindexing status.
116 ResetReindexProcessing(void)
118 currentlyReindexedHeap = InvalidOid;
119 currentlyReindexedIndex = InvalidOid;
122 /* ----------------------------------------------------------------
123 * database path / name support stuff
124 * ----------------------------------------------------------------
128 SetDatabasePath(const char *path)
135 /* use strdup since this is done before memory contexts are set up */
138 DatabasePath = strdup(path);
139 AssertState(DatabasePath);
144 * Set data directory, but make sure it's an absolute path. Use this,
145 * never set DataDir directly.
148 SetDataDir(const char *dir)
154 /* If presented path is relative, convert to absolute */
155 new = make_absolute_path(dir);
163 * Change working directory to DataDir. Most of the postmaster and backend
164 * code assumes that we are in DataDir so it can use relative paths to access
165 * stuff in and under the data directory. For convenience during path
166 * setup, however, we don't force the chdir to occur during SetDataDir.
169 ChangeToDataDir(void)
171 AssertState(DataDir);
173 if (chdir(DataDir) < 0)
175 (errcode_for_file_access(),
176 errmsg("could not change directory to \"%s\": %m",
181 * If the given pathname isn't already absolute, make it so, interpreting
182 * it relative to the current working directory.
184 * Also canonicalizes the path. The result is always a malloc'd copy.
186 * Note: interpretation of relative-path arguments during postmaster startup
187 * should happen before doing ChangeToDataDir(), else the user will probably
188 * not like the results.
191 make_absolute_path(const char *path)
195 /* Returning null for null input is convenient for some callers */
199 if (!is_absolute_path(path))
207 buf = malloc(buflen);
210 (errcode(ERRCODE_OUT_OF_MEMORY),
211 errmsg("out of memory")));
213 if (getcwd(buf, buflen))
215 else if (errno == ERANGE)
224 elog(FATAL, "could not get current working directory: %m");
228 new = malloc(strlen(buf) + strlen(path) + 2);
231 (errcode(ERRCODE_OUT_OF_MEMORY),
232 errmsg("out of memory")));
233 sprintf(new, "%s/%s", buf, path);
241 (errcode(ERRCODE_OUT_OF_MEMORY),
242 errmsg("out of memory")));
245 /* Make sure punctuation is canonical, too */
246 canonicalize_path(new);
252 /* ----------------------------------------------------------------
255 * We have to track several different values associated with the concept
258 * AuthenticatedUserId is determined at connection start and never changes.
260 * SessionUserId is initially the same as AuthenticatedUserId, but can be
261 * changed by SET SESSION AUTHORIZATION (if AuthenticatedUserIsSuperuser).
262 * This is the ID reported by the SESSION_USER SQL function.
264 * OuterUserId is the current user ID in effect at the "outer level" (outside
265 * any transaction or function). This is initially the same as SessionUserId,
266 * but can be changed by SET ROLE to any role that SessionUserId is a
267 * member of. We store this mainly so that AtAbort_UserId knows what to
268 * reset CurrentUserId to.
270 * CurrentUserId is the current effective user ID; this is the one to use
271 * for all normal permissions-checking purposes. At outer level this will
272 * be the same as OuterUserId, but it changes during calls to SECURITY
273 * DEFINER functions, as well as locally in some specialized commands.
274 * ----------------------------------------------------------------
276 static Oid AuthenticatedUserId = InvalidOid;
277 static Oid SessionUserId = InvalidOid;
278 static Oid OuterUserId = InvalidOid;
279 static Oid CurrentUserId = InvalidOid;
281 /* We also have to remember the superuser state of some of these levels */
282 static bool AuthenticatedUserIsSuperuser = false;
283 static bool SessionUserIsSuperuser = false;
285 /* We also remember if a SET ROLE is currently active */
286 static bool SetRoleIsActive = false;
290 * GetUserId/SetUserId - get/set the current effective user ID.
295 AssertState(OidIsValid(CurrentUserId));
296 return CurrentUserId;
301 SetUserId(Oid userid)
303 AssertArg(OidIsValid(userid));
304 CurrentUserId = userid;
309 * GetOuterUserId/SetOuterUserId - get/set the outer-level user ID.
314 AssertState(OidIsValid(OuterUserId));
320 SetOuterUserId(Oid userid)
322 AssertArg(OidIsValid(userid));
323 OuterUserId = userid;
325 /* We force the effective user ID to match, too */
326 CurrentUserId = userid;
331 * GetSessionUserId/SetSessionUserId - get/set the session user ID.
334 GetSessionUserId(void)
336 AssertState(OidIsValid(SessionUserId));
337 return SessionUserId;
342 SetSessionUserId(Oid userid, bool is_superuser)
344 AssertArg(OidIsValid(userid));
345 SessionUserId = userid;
346 SessionUserIsSuperuser = is_superuser;
347 SetRoleIsActive = false;
349 /* We force the effective user IDs to match, too */
350 OuterUserId = userid;
351 CurrentUserId = userid;
356 * Initialize user identity during normal backend startup
359 InitializeSessionUserId(const char *rolename)
362 Form_pg_authid rform;
368 * Don't do scans if we're bootstrapping, none of the system catalogs
369 * exist yet, and they should be owned by postgres anyway.
371 AssertState(!IsBootstrapProcessingMode());
374 AssertState(!OidIsValid(AuthenticatedUserId));
376 roleTup = SearchSysCache(AUTHNAME,
377 PointerGetDatum(rolename),
379 if (!HeapTupleIsValid(roleTup))
381 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
382 errmsg("role \"%s\" does not exist", rolename)));
384 rform = (Form_pg_authid) GETSTRUCT(roleTup);
385 roleid = HeapTupleGetOid(roleTup);
387 AuthenticatedUserId = roleid;
388 AuthenticatedUserIsSuperuser = rform->rolsuper;
390 /* This sets OuterUserId/CurrentUserId too */
391 SetSessionUserId(roleid, AuthenticatedUserIsSuperuser);
393 /* Also mark our PGPROC entry with the authenticated user id */
394 /* (We assume this is an atomic store so no lock is needed) */
395 MyProc->roleId = roleid;
398 * These next checks are not enforced when in standalone mode, so that
399 * there is a way to recover from sillinesses like "UPDATE pg_authid SET
400 * rolcanlogin = false;".
402 * We do not enforce them for the autovacuum process either.
404 if (IsUnderPostmaster && !IsAutoVacuumWorkerProcess())
407 * Is role allowed to login at all?
409 if (!rform->rolcanlogin)
411 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
412 errmsg("role \"%s\" is not permitted to log in",
416 * Check connection limit for this role.
418 * There is a race condition here --- we create our PGPROC before
419 * checking for other PGPROCs. If two backends did this at about the
420 * same time, they might both think they were over the limit, while
421 * ideally one should succeed and one fail. Getting that to work
422 * exactly seems more trouble than it is worth, however; instead we
423 * just document that the connection limit is approximate.
425 if (rform->rolconnlimit >= 0 &&
426 !AuthenticatedUserIsSuperuser &&
427 CountUserBackends(roleid) > rform->rolconnlimit)
429 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
430 errmsg("too many connections for role \"%s\"",
434 /* Record username and superuser status as GUC settings too */
435 SetConfigOption("session_authorization", rolename,
436 PGC_BACKEND, PGC_S_OVERRIDE);
437 SetConfigOption("is_superuser",
438 AuthenticatedUserIsSuperuser ? "on" : "off",
439 PGC_INTERNAL, PGC_S_OVERRIDE);
442 * Set up user-specific configuration variables. This is a good place to
443 * do it so we don't have to read pg_authid twice during session startup.
445 datum = SysCacheGetAttr(AUTHNAME, roleTup,
446 Anum_pg_authid_rolconfig, &isnull);
449 ArrayType *a = DatumGetArrayTypeP(datum);
452 * We process all the options at SUSET level. We assume that the
453 * right to insert an option into pg_authid was checked when it was
456 ProcessGUCArray(a, PGC_SUSET, PGC_S_USER, GUC_ACTION_SET);
459 ReleaseSysCache(roleTup);
464 * Initialize user identity during special backend startup
467 InitializeSessionUserIdStandalone(void)
469 /* This function should only be called in a single-user backend. */
470 AssertState(!IsUnderPostmaster || IsAutoVacuumWorkerProcess());
473 AssertState(!OidIsValid(AuthenticatedUserId));
475 AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
476 AuthenticatedUserIsSuperuser = true;
478 SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
483 * Reset effective userid during AbortTransaction
485 * This is essentially SetUserId(GetOuterUserId()), but without the Asserts.
486 * The reason is that if a backend's InitPostgres transaction fails (eg,
487 * because an invalid user name was given), we have to be able to get through
488 * AbortTransaction without asserting.
493 CurrentUserId = OuterUserId;
498 * Change session auth ID while running
500 * Only a superuser may set auth ID to something other than himself. Note
501 * that in case of multiple SETs in a single session, the original userid's
502 * superuserness is what matters. But we set the GUC variable is_superuser
503 * to indicate whether the *current* session userid is a superuser.
505 * Note: this is not an especially clean place to do the permission check.
506 * It's OK because the check does not require catalog access and can't
507 * fail during an end-of-transaction GUC reversion, but we may someday
508 * have to push it up into assign_session_authorization.
511 SetSessionAuthorization(Oid userid, bool is_superuser)
513 /* Must have authenticated already, else can't make permission check */
514 AssertState(OidIsValid(AuthenticatedUserId));
516 if (userid != AuthenticatedUserId &&
517 !AuthenticatedUserIsSuperuser)
519 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
520 errmsg("permission denied to set session authorization")));
522 SetSessionUserId(userid, is_superuser);
524 SetConfigOption("is_superuser",
525 is_superuser ? "on" : "off",
526 PGC_INTERNAL, PGC_S_OVERRIDE);
530 * Report current role id
531 * This follows the semantics of SET ROLE, ie return the outer-level ID
532 * not the current effective ID, and return InvalidOid when the setting
533 * is logically SET ROLE NONE.
536 GetCurrentRoleId(void)
545 * Change Role ID while running (SET ROLE)
547 * If roleid is InvalidOid, we are doing SET ROLE NONE: revert to the
548 * session user authorization. In this case the is_superuser argument
551 * When roleid is not InvalidOid, the caller must have checked whether
552 * the session user has permission to become that role. (We cannot check
553 * here because this routine must be able to execute in a failed transaction
554 * to restore a prior value of the ROLE GUC variable.)
557 SetCurrentRoleId(Oid roleid, bool is_superuser)
560 * Get correct info if it's SET ROLE NONE
562 * If SessionUserId hasn't been set yet, just do nothing --- the eventual
563 * SetSessionUserId call will fix everything. This is needed since we
564 * will get called during GUC initialization.
566 if (!OidIsValid(roleid))
568 if (!OidIsValid(SessionUserId))
571 roleid = SessionUserId;
572 is_superuser = SessionUserIsSuperuser;
574 SetRoleIsActive = false;
577 SetRoleIsActive = true;
579 SetOuterUserId(roleid);
581 SetConfigOption("is_superuser",
582 is_superuser ? "on" : "off",
583 PGC_INTERNAL, PGC_S_OVERRIDE);
588 * Get user name from user oid
591 GetUserNameFromId(Oid roleid)
596 tuple = SearchSysCache(AUTHOID,
597 ObjectIdGetDatum(roleid),
599 if (!HeapTupleIsValid(tuple))
601 (errcode(ERRCODE_UNDEFINED_OBJECT),
602 errmsg("invalid role OID: %u", roleid)));
604 result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
606 ReleaseSysCache(tuple);
611 /*-------------------------------------------------------------------------
612 * Interlock-file support
614 * These routines are used to create both a data-directory lockfile
615 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
616 * Both kinds of files contain the same info:
618 * Owning process' PID
619 * Data directory path
621 * By convention, the owning process' PID is negated if it is a standalone
622 * backend rather than a postmaster. This is just for informational purposes.
623 * The path is also just for informational purposes (so that a socket lockfile
624 * can be more easily traced to the associated postmaster).
626 * A data-directory lockfile can optionally contain a third line, containing
627 * the key and ID for the shared memory block used by this postmaster.
629 * On successful lockfile creation, a proc_exit callback to remove the
630 * lockfile is automatically created.
631 *-------------------------------------------------------------------------
635 * proc_exit callback to remove a lockfile.
638 UnlinkLockFile(int status, Datum filename)
640 char *fname = (char *) DatumGetPointer(filename);
644 if (unlink(fname) != 0)
646 /* Should we complain if the unlink fails? */
655 * filename is the name of the lockfile to create.
656 * amPostmaster is used to determine how to encode the output PID.
657 * isDDLock and refName are used to determine what error message to produce.
660 CreateLockFile(const char *filename, bool amPostmaster,
661 bool isDDLock, const char *refName)
664 char buffer[MAXPGPATH + 100];
669 pid_t my_pid = getpid();
672 * We need a loop here because of race conditions. But don't loop forever
673 * (for example, a non-writable $PGDATA directory might cause a failure
674 * that won't go away). 100 tries seems like plenty.
676 for (ntries = 0;; ntries++)
679 * Try to create the lock file --- O_EXCL makes this atomic.
681 * Think not to make the file protection weaker than 0600. See
684 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
686 break; /* Success; exit the retry loop */
689 * Couldn't create the pid file. Probably it already exists.
691 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
693 (errcode_for_file_access(),
694 errmsg("could not create lock file \"%s\": %m",
698 * Read the file to get the old owner's PID. Note race condition
699 * here: file might have been deleted since we tried to create it.
701 fd = open(filename, O_RDONLY, 0600);
705 continue; /* race condition; try again */
707 (errcode_for_file_access(),
708 errmsg("could not open lock file \"%s\": %m",
711 if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
713 (errcode_for_file_access(),
714 errmsg("could not read lock file \"%s\": %m",
719 encoded_pid = atoi(buffer);
721 /* if pid < 0, the pid is for postgres, not postmaster */
722 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
725 elog(FATAL, "bogus data in lock file \"%s\": \"%s\"",
729 * Check to see if the other process still exists
731 * If the PID in the lockfile is our own PID or our parent's PID, then
732 * the file must be stale (probably left over from a previous system
733 * boot cycle). We need this test because of the likelihood that a
734 * reboot will assign exactly the same PID as we had in the previous
735 * reboot. Also, if there is just one more process launch in this
736 * reboot than in the previous one, the lockfile might mention our
737 * parent's PID. We can reject that since we'd never be launched
738 * directly by a competing postmaster. We can't detect grandparent
739 * processes unfortunately, but if the init script is written
740 * carefully then all but the immediate parent shell will be
741 * root-owned processes and so the kill test will fail with EPERM.
743 * We can treat the EPERM-error case as okay because that error
744 * implies that the existing process has a different userid than we
745 * do, which means it cannot be a competing postmaster. A postmaster
746 * cannot successfully attach to a data directory owned by a userid
747 * other than its own. (This is now checked directly in
748 * checkDataDir(), but has been true for a long time because of the
749 * restriction that the data directory isn't group- or
750 * world-accessible.) Also, since we create the lockfiles mode 600,
751 * we'd have failed above if the lockfile belonged to another userid
752 * --- which means that whatever process kill() is reporting about
753 * isn't the one that made the lockfile. (NOTE: this last
754 * consideration is the only one that keeps us from blowing away a
755 * Unix socket file belonging to an instance of Postgres being run by
756 * someone else, at least on machines where /tmp hasn't got a
759 * Windows hasn't got getppid(), but doesn't need it since it's not
760 * using real kill() either...
762 * Normally kill() will fail with ESRCH if the given PID doesn't
765 if (other_pid != my_pid
767 && other_pid != getppid()
771 if (kill(other_pid, 0) == 0 ||
772 (errno != ESRCH && errno != EPERM))
774 /* lockfile belongs to a live process */
776 (errcode(ERRCODE_LOCK_FILE_EXISTS),
777 errmsg("lock file \"%s\" already exists",
781 errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
782 (int) other_pid, refName) :
783 errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
784 (int) other_pid, refName)) :
786 errhint("Is another postgres (PID %d) using socket file \"%s\"?",
787 (int) other_pid, refName) :
788 errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
789 (int) other_pid, refName))));
794 * No, the creating process did not exist. However, it could be that
795 * the postmaster crashed (or more likely was kill -9'd by a clueless
796 * admin) but has left orphan backends behind. Check for this by
797 * looking to see if there is an associated shmem segment that is
806 ptr = strchr(buffer, '\n');
808 (ptr = strchr(ptr + 1, '\n')) != NULL)
811 if (sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
813 if (PGSharedMemoryIsInUse(id1, id2))
815 (errcode(ERRCODE_LOCK_FILE_EXISTS),
816 errmsg("pre-existing shared memory block "
817 "(key %lu, ID %lu) is still in use",
819 errhint("If you're sure there are no old "
820 "server processes still running, remove "
821 "the shared memory block with "
822 "the command \"ipcclean\", \"ipcrm\", "
823 "or just delete the file \"%s\".",
830 * Looks like nobody's home. Unlink the file and try again to create
831 * it. Need a loop because of possible race condition against other
834 if (unlink(filename) < 0)
836 (errcode_for_file_access(),
837 errmsg("could not remove old lock file \"%s\": %m",
839 errhint("The file seems accidentally left over, but "
840 "it could not be removed. Please remove the file "
841 "by hand and try again.")));
845 * Successfully created the file, now fill it.
847 snprintf(buffer, sizeof(buffer), "%d\n%s\n",
848 amPostmaster ? (int) my_pid : -((int) my_pid),
851 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
853 int save_errno = errno;
857 /* if write didn't set errno, assume problem is no disk space */
858 errno = save_errno ? save_errno : ENOSPC;
860 (errcode_for_file_access(),
861 errmsg("could not write lock file \"%s\": %m", filename)));
865 int save_errno = errno;
870 (errcode_for_file_access(),
871 errmsg("could not write lock file \"%s\": %m", filename)));
875 * Arrange for automatic removal of lockfile at proc_exit.
877 on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
881 * Create the data directory lockfile.
883 * When this is called, we must have already switched the working
884 * directory to DataDir, so we can just use a relative path. This
885 * helps ensure that we are locking the directory we should be.
888 CreateDataDirLockFile(bool amPostmaster)
890 CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, true, DataDir);
894 * Create a lockfile for the specified Unix socket file.
897 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
899 char lockfile[MAXPGPATH];
901 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
902 CreateLockFile(lockfile, amPostmaster, false, socketfile);
903 /* Save name of lockfile for TouchSocketLockFile */
904 strcpy(socketLockFile, lockfile);
908 * TouchSocketLockFile -- mark socket lock file as recently accessed
910 * This routine should be called every so often to ensure that the lock file
911 * has a recent mod or access date. That saves it
912 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
913 * (Another reason we should never have put the socket file in /tmp...)
916 TouchSocketLockFile(void)
918 /* Do nothing if we did not create a socket... */
919 if (socketLockFile[0] != '\0')
922 * utime() is POSIX standard, utimes() is a common alternative; if we
923 * have neither, fall back to actually reading the file (which only
924 * sets the access time not mod time, but that should be enough in
925 * most cases). In all paths, we ignore errors.
928 utime(socketLockFile, NULL);
929 #else /* !HAVE_UTIME */
931 utimes(socketLockFile, NULL);
932 #else /* !HAVE_UTIMES */
936 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
939 read(fd, buffer, sizeof(buffer));
942 #endif /* HAVE_UTIMES */
943 #endif /* HAVE_UTIME */
948 * Append information about a shared memory segment to the data directory
951 * This may be called multiple times in the life of a postmaster, if we
952 * delete and recreate shmem due to backend crash. Therefore, be prepared
953 * to overwrite existing information. (As of 7.1, a postmaster only creates
954 * one shm seg at a time; but for the purposes here, if we did have more than
955 * one then any one of them would do anyway.)
958 RecordSharedMemoryInLockFile(unsigned long id1, unsigned long id2)
965 fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
969 (errcode_for_file_access(),
970 errmsg("could not open file \"%s\": %m",
971 DIRECTORY_LOCK_FILE)));
974 len = read(fd, buffer, sizeof(buffer) - 100);
978 (errcode_for_file_access(),
979 errmsg("could not read from file \"%s\": %m",
980 DIRECTORY_LOCK_FILE)));
987 * Skip over first two lines (PID and path).
989 ptr = strchr(buffer, '\n');
991 (ptr = strchr(ptr + 1, '\n')) == NULL)
993 elog(LOG, "bogus data in \"%s\"", DIRECTORY_LOCK_FILE);
1000 * Append key information. Format to try to keep it the same length
1001 * always (trailing junk won't hurt, but might confuse humans).
1003 sprintf(ptr, "%9lu %9lu\n", id1, id2);
1006 * And rewrite the data. Since we write in a single kernel call, this
1007 * update should appear atomic to onlookers.
1009 len = strlen(buffer);
1011 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
1012 (int) write(fd, buffer, len) != len)
1014 /* if write didn't set errno, assume problem is no disk space */
1018 (errcode_for_file_access(),
1019 errmsg("could not write to file \"%s\": %m",
1020 DIRECTORY_LOCK_FILE)));
1027 (errcode_for_file_access(),
1028 errmsg("could not write to file \"%s\": %m",
1029 DIRECTORY_LOCK_FILE)));
1034 /*-------------------------------------------------------------------------
1035 * Version checking support
1036 *-------------------------------------------------------------------------
1040 * Determine whether the PG_VERSION file in directory `path' indicates
1041 * a data version compatible with the version of this program.
1043 * If compatible, return. Otherwise, ereport(FATAL).
1046 ValidatePgVersion(const char *path)
1048 char full_path[MAXPGPATH];
1056 const char *version_string = PG_VERSION;
1058 my_major = strtol(version_string, &endptr, 10);
1060 my_minor = strtol(endptr + 1, NULL, 10);
1062 snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1064 file = AllocateFile(full_path, "r");
1067 if (errno == ENOENT)
1069 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1070 errmsg("\"%s\" is not a valid data directory",
1072 errdetail("File \"%s\" is missing.", full_path)));
1075 (errcode_for_file_access(),
1076 errmsg("could not open file \"%s\": %m", full_path)));
1079 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
1082 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1083 errmsg("\"%s\" is not a valid data directory",
1085 errdetail("File \"%s\" does not contain valid data.",
1087 errhint("You might need to initdb.")));
1091 if (my_major != file_major || my_minor != file_minor)
1093 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1094 errmsg("database files are incompatible with server"),
1095 errdetail("The data directory was initialized by PostgreSQL version %ld.%ld, "
1096 "which is not compatible with this version %s.",
1097 file_major, file_minor, version_string)));
1100 /*-------------------------------------------------------------------------
1101 * Library preload support
1102 *-------------------------------------------------------------------------
1106 * GUC variables: lists of library names to be preloaded at postmaster
1107 * start and at backend start
1109 char *shared_preload_libraries_string = NULL;
1110 char *local_preload_libraries_string = NULL;
1113 * load the shared libraries listed in 'libraries'
1115 * 'gucname': name of GUC variable, for error reports
1116 * 'restricted': if true, force libraries to be in $libdir/plugins/
1119 load_libraries(const char *libraries, const char *gucname, bool restricted)
1125 if (libraries == NULL || libraries[0] == '\0')
1126 return; /* nothing to do */
1128 /* Need a modifiable copy of string */
1129 rawstring = pstrdup(libraries);
1131 /* Parse string into list of identifiers */
1132 if (!SplitIdentifierString(rawstring, ',', &elemlist))
1134 /* syntax error in list */
1136 list_free(elemlist);
1138 (errcode(ERRCODE_SYNTAX_ERROR),
1139 errmsg("invalid list syntax in parameter \"%s\"",
1144 foreach(l, elemlist)
1146 char *tok = (char *) lfirst(l);
1149 filename = pstrdup(tok);
1150 canonicalize_path(filename);
1151 /* If restricting, insert $libdir/plugins if not mentioned already */
1152 if (restricted && first_dir_separator(filename) == NULL)
1156 expanded = palloc(strlen("$libdir/plugins/") + strlen(filename) + 1);
1157 strcpy(expanded, "$libdir/plugins/");
1158 strcat(expanded, filename);
1160 filename = expanded;
1162 load_file(filename, restricted);
1164 (errmsg("loaded library \"%s\"", filename)));
1169 list_free(elemlist);
1173 * process any libraries that should be preloaded at postmaster start
1176 process_shared_preload_libraries(void)
1178 load_libraries(shared_preload_libraries_string,
1179 "shared_preload_libraries",
1184 * process any libraries that should be preloaded at backend start
1187 process_local_preload_libraries(void)
1189 load_libraries(local_preload_libraries_string,
1190 "local_preload_libraries",