1 /*-------------------------------------------------------------------------
4 * miscellaneous initialization support stuff
6 * Portions Copyright (c) 1996-2005, 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.153 2006/01/05 10:07:46 petere 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 "libpq/libpq-be.h"
34 #include "miscadmin.h"
35 #include "postmaster/autovacuum.h"
36 #include "storage/fd.h"
37 #include "storage/ipc.h"
38 #include "storage/pg_shmem.h"
39 #include "storage/proc.h"
40 #include "storage/procarray.h"
41 #include "utils/builtins.h"
42 #include "utils/guc.h"
43 #include "utils/lsyscache.h"
44 #include "utils/syscache.h"
47 #define DIRECTORY_LOCK_FILE "postmaster.pid"
49 ProcessingMode Mode = InitProcessing;
51 /* Note: we rely on this to initialize as zeroes */
52 static char socketLockFile[MAXPGPATH];
55 /* ----------------------------------------------------------------
56 * ignoring system indexes support stuff
58 * NOTE: "ignoring system indexes" means we do not use the system indexes
59 * for lookups (either in hardwired catalog accesses or in planner-generated
60 * plans). We do, however, still update the indexes when a catalog
61 * modification is made.
62 * ----------------------------------------------------------------
65 bool IgnoreSystemIndexes = false;
67 /* ----------------------------------------------------------------
68 * system index reindexing support
70 * When we are busy reindexing a system index, this code provides support
71 * for preventing catalog lookups from using that index.
72 * ----------------------------------------------------------------
75 static Oid currentlyReindexedHeap = InvalidOid;
76 static Oid currentlyReindexedIndex = InvalidOid;
79 * ReindexIsProcessingHeap
80 * True if heap specified by OID is currently being reindexed.
83 ReindexIsProcessingHeap(Oid heapOid)
85 return heapOid == currentlyReindexedHeap;
89 * ReindexIsProcessingIndex
90 * True if index specified by OID is currently being reindexed.
93 ReindexIsProcessingIndex(Oid indexOid)
95 return indexOid == currentlyReindexedIndex;
99 * SetReindexProcessing
100 * Set flag that specified heap/index are being reindexed.
103 SetReindexProcessing(Oid heapOid, Oid indexOid)
105 Assert(OidIsValid(heapOid) && OidIsValid(indexOid));
106 /* Reindexing is not re-entrant. */
107 if (OidIsValid(currentlyReindexedIndex))
108 elog(ERROR, "cannot reindex while reindexing");
109 currentlyReindexedHeap = heapOid;
110 currentlyReindexedIndex = indexOid;
114 * ResetReindexProcessing
115 * Unset reindexing status.
118 ResetReindexProcessing(void)
120 currentlyReindexedHeap = InvalidOid;
121 currentlyReindexedIndex = InvalidOid;
124 /* ----------------------------------------------------------------
125 * database path / name support stuff
126 * ----------------------------------------------------------------
130 SetDatabasePath(const char *path)
137 /* use strdup since this is done before memory contexts are set up */
140 DatabasePath = strdup(path);
141 AssertState(DatabasePath);
146 * Set data directory, but make sure it's an absolute path. Use this,
147 * never set DataDir directly.
150 SetDataDir(const char *dir)
156 /* If presented path is relative, convert to absolute */
157 new = make_absolute_path(dir);
165 * Change working directory to DataDir. Most of the postmaster and backend
166 * code assumes that we are in DataDir so it can use relative paths to access
167 * stuff in and under the data directory. For convenience during path
168 * setup, however, we don't force the chdir to occur during SetDataDir.
171 ChangeToDataDir(void)
173 AssertState(DataDir);
175 if (chdir(DataDir) < 0)
177 (errcode_for_file_access(),
178 errmsg("could not change directory to \"%s\": %m",
183 * If the given pathname isn't already absolute, make it so, interpreting
184 * it relative to the current working directory.
186 * Also canonicalizes the path. The result is always a malloc'd copy.
188 * Note: interpretation of relative-path arguments during postmaster startup
189 * should happen before doing ChangeToDataDir(), else the user will probably
190 * not like the results.
193 make_absolute_path(const char *path)
197 /* Returning null for null input is convenient for some callers */
201 if (!is_absolute_path(path))
209 buf = malloc(buflen);
212 (errcode(ERRCODE_OUT_OF_MEMORY),
213 errmsg("out of memory")));
215 if (getcwd(buf, buflen))
217 else if (errno == ERANGE)
226 elog(FATAL, "could not get current working directory: %m");
230 new = malloc(strlen(buf) + strlen(path) + 2);
233 (errcode(ERRCODE_OUT_OF_MEMORY),
234 errmsg("out of memory")));
235 sprintf(new, "%s/%s", buf, path);
243 (errcode(ERRCODE_OUT_OF_MEMORY),
244 errmsg("out of memory")));
247 /* Make sure punctuation is canonical, too */
248 canonicalize_path(new);
254 /* ----------------------------------------------------------------
257 * We have to track several different values associated with the concept
260 * AuthenticatedUserId is determined at connection start and never changes.
262 * SessionUserId is initially the same as AuthenticatedUserId, but can be
263 * changed by SET SESSION AUTHORIZATION (if AuthenticatedUserIsSuperuser).
264 * This is the ID reported by the SESSION_USER SQL function.
266 * OuterUserId is the current user ID in effect at the "outer level" (outside
267 * any transaction or function). This is initially the same as SessionUserId,
268 * but can be changed by SET ROLE to any role that SessionUserId is a
269 * member of. We store this mainly so that AtAbort_UserId knows what to
270 * reset CurrentUserId to.
272 * CurrentUserId is the current effective user ID; this is the one to use
273 * for all normal permissions-checking purposes. At outer level this will
274 * be the same as OuterUserId, but it changes during calls to SECURITY
275 * DEFINER functions, as well as locally in some specialized commands.
276 * ----------------------------------------------------------------
278 static Oid AuthenticatedUserId = InvalidOid;
279 static Oid SessionUserId = InvalidOid;
280 static Oid OuterUserId = InvalidOid;
281 static Oid CurrentUserId = InvalidOid;
283 /* We also have to remember the superuser state of some of these levels */
284 static bool AuthenticatedUserIsSuperuser = false;
285 static bool SessionUserIsSuperuser = false;
287 /* We also remember if a SET ROLE is currently active */
288 static bool SetRoleIsActive = false;
292 * GetUserId/SetUserId - get/set the current effective user ID.
297 AssertState(OidIsValid(CurrentUserId));
298 return CurrentUserId;
303 SetUserId(Oid userid)
305 AssertArg(OidIsValid(userid));
306 CurrentUserId = userid;
311 * GetOuterUserId/SetOuterUserId - get/set the outer-level user ID.
316 AssertState(OidIsValid(OuterUserId));
322 SetOuterUserId(Oid userid)
324 AssertArg(OidIsValid(userid));
325 OuterUserId = userid;
327 /* We force the effective user ID to match, too */
328 CurrentUserId = userid;
333 * GetSessionUserId/SetSessionUserId - get/set the session user ID.
336 GetSessionUserId(void)
338 AssertState(OidIsValid(SessionUserId));
339 return SessionUserId;
344 SetSessionUserId(Oid userid, bool is_superuser)
346 AssertArg(OidIsValid(userid));
347 SessionUserId = userid;
348 SessionUserIsSuperuser = is_superuser;
349 SetRoleIsActive = false;
351 /* We force the effective user IDs to match, too */
352 OuterUserId = userid;
353 CurrentUserId = userid;
358 * Initialize user identity during normal backend startup
361 InitializeSessionUserId(const char *rolename)
364 Form_pg_authid rform;
370 * Don't do scans if we're bootstrapping, none of the system catalogs
371 * exist yet, and they should be owned by postgres anyway.
373 AssertState(!IsBootstrapProcessingMode());
376 AssertState(!OidIsValid(AuthenticatedUserId));
378 roleTup = SearchSysCache(AUTHNAME,
379 PointerGetDatum(rolename),
381 if (!HeapTupleIsValid(roleTup))
383 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
384 errmsg("role \"%s\" does not exist", rolename)));
386 rform = (Form_pg_authid) GETSTRUCT(roleTup);
387 roleid = HeapTupleGetOid(roleTup);
389 AuthenticatedUserId = roleid;
390 AuthenticatedUserIsSuperuser = rform->rolsuper;
392 /* This sets OuterUserId/CurrentUserId too */
393 SetSessionUserId(roleid, AuthenticatedUserIsSuperuser);
395 /* Also mark our PGPROC entry with the authenticated user id */
396 /* (We assume this is an atomic store so no lock is needed) */
397 MyProc->roleId = roleid;
400 * These next checks are not enforced when in standalone mode, so that
401 * there is a way to recover from sillinesses like "UPDATE pg_authid SET
402 * rolcanlogin = false;".
404 * We do not enforce them for the autovacuum process either.
406 if (IsUnderPostmaster && !IsAutoVacuumProcess())
409 * Is role allowed to login at all?
411 if (!rform->rolcanlogin)
413 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION),
414 errmsg("role \"%s\" is not permitted to log in",
418 * Check connection limit for this role.
420 * There is a race condition here --- we create our PGPROC before
421 * checking for other PGPROCs. If two backends did this at about the
422 * same time, they might both think they were over the limit, while
423 * ideally one should succeed and one fail. Getting that to work
424 * exactly seems more trouble than it is worth, however; instead we
425 * just document that the connection limit is approximate.
427 if (rform->rolconnlimit >= 0 &&
428 !AuthenticatedUserIsSuperuser &&
429 CountUserBackends(roleid) > rform->rolconnlimit)
431 (errcode(ERRCODE_TOO_MANY_CONNECTIONS),
432 errmsg("too many connections for role \"%s\"",
436 /* Record username and superuser status as GUC settings too */
437 SetConfigOption("session_authorization", rolename,
438 PGC_BACKEND, PGC_S_OVERRIDE);
439 SetConfigOption("is_superuser",
440 AuthenticatedUserIsSuperuser ? "on" : "off",
441 PGC_INTERNAL, PGC_S_OVERRIDE);
444 * Set up user-specific configuration variables. This is a good place to
445 * do it so we don't have to read pg_authid twice during session startup.
447 datum = SysCacheGetAttr(AUTHNAME, roleTup,
448 Anum_pg_authid_rolconfig, &isnull);
451 ArrayType *a = DatumGetArrayTypeP(datum);
453 ProcessGUCArray(a, PGC_S_USER);
456 ReleaseSysCache(roleTup);
461 * Initialize user identity during special backend startup
464 InitializeSessionUserIdStandalone(void)
466 /* This function should only be called in a single-user backend. */
467 AssertState(!IsUnderPostmaster || IsAutoVacuumProcess());
470 AssertState(!OidIsValid(AuthenticatedUserId));
472 AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
473 AuthenticatedUserIsSuperuser = true;
475 SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
480 * Reset effective userid during AbortTransaction
482 * This is essentially SetUserId(GetOuterUserId()), but without the Asserts.
483 * The reason is that if a backend's InitPostgres transaction fails (eg,
484 * because an invalid user name was given), we have to be able to get through
485 * AbortTransaction without asserting.
490 CurrentUserId = OuterUserId;
495 * Change session auth ID while running
497 * Only a superuser may set auth ID to something other than himself. Note
498 * that in case of multiple SETs in a single session, the original userid's
499 * superuserness is what matters. But we set the GUC variable is_superuser
500 * to indicate whether the *current* session userid is a superuser.
502 * Note: this is not an especially clean place to do the permission check.
503 * It's OK because the check does not require catalog access and can't
504 * fail during an end-of-transaction GUC reversion, but we may someday
505 * have to push it up into assign_session_authorization.
508 SetSessionAuthorization(Oid userid, bool is_superuser)
510 /* Must have authenticated already, else can't make permission check */
511 AssertState(OidIsValid(AuthenticatedUserId));
513 if (userid != AuthenticatedUserId &&
514 !AuthenticatedUserIsSuperuser)
516 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
517 errmsg("permission denied to set session authorization")));
519 SetSessionUserId(userid, is_superuser);
521 SetConfigOption("is_superuser",
522 is_superuser ? "on" : "off",
523 PGC_INTERNAL, PGC_S_OVERRIDE);
527 * Report current role id
528 * This follows the semantics of SET ROLE, ie return the outer-level ID
529 * not the current effective ID, and return InvalidOid when the setting
530 * is logically SET ROLE NONE.
533 GetCurrentRoleId(void)
542 * Change Role ID while running (SET ROLE)
544 * If roleid is InvalidOid, we are doing SET ROLE NONE: revert to the
545 * session user authorization. In this case the is_superuser argument
548 * When roleid is not InvalidOid, the caller must have checked whether
549 * the session user has permission to become that role. (We cannot check
550 * here because this routine must be able to execute in a failed transaction
551 * to restore a prior value of the ROLE GUC variable.)
554 SetCurrentRoleId(Oid roleid, bool is_superuser)
557 * Get correct info if it's SET ROLE NONE
559 * If SessionUserId hasn't been set yet, just do nothing --- the eventual
560 * SetSessionUserId call will fix everything. This is needed since we
561 * will get called during GUC initialization.
563 if (!OidIsValid(roleid))
565 if (!OidIsValid(SessionUserId))
568 roleid = SessionUserId;
569 is_superuser = SessionUserIsSuperuser;
571 SetRoleIsActive = false;
574 SetRoleIsActive = true;
576 SetOuterUserId(roleid);
578 SetConfigOption("is_superuser",
579 is_superuser ? "on" : "off",
580 PGC_INTERNAL, PGC_S_OVERRIDE);
585 * Get user name from user oid
588 GetUserNameFromId(Oid roleid)
593 tuple = SearchSysCache(AUTHOID,
594 ObjectIdGetDatum(roleid),
596 if (!HeapTupleIsValid(tuple))
598 (errcode(ERRCODE_UNDEFINED_OBJECT),
599 errmsg("invalid role OID: %u", roleid)));
601 result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
603 ReleaseSysCache(tuple);
608 /*-------------------------------------------------------------------------
609 * Interlock-file support
611 * These routines are used to create both a data-directory lockfile
612 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
613 * Both kinds of files contain the same info:
615 * Owning process' PID
616 * Data directory path
618 * By convention, the owning process' PID is negated if it is a standalone
619 * backend rather than a postmaster. This is just for informational purposes.
620 * The path is also just for informational purposes (so that a socket lockfile
621 * can be more easily traced to the associated postmaster).
623 * A data-directory lockfile can optionally contain a third line, containing
624 * the key and ID for the shared memory block used by this postmaster.
626 * On successful lockfile creation, a proc_exit callback to remove the
627 * lockfile is automatically created.
628 *-------------------------------------------------------------------------
632 * proc_exit callback to remove a lockfile.
635 UnlinkLockFile(int status, Datum filename)
637 char *fname = (char *) DatumGetPointer(filename);
641 if (unlink(fname) != 0)
643 /* Should we complain if the unlink fails? */
652 * filename is the name of the lockfile to create.
653 * amPostmaster is used to determine how to encode the output PID.
654 * isDDLock and refName are used to determine what error message to produce.
657 CreateLockFile(const char *filename, bool amPostmaster,
658 bool isDDLock, const char *refName)
661 char buffer[MAXPGPATH + 100];
666 pid_t my_pid = getpid();
669 * We need a loop here because of race conditions. But don't loop forever
670 * (for example, a non-writable $PGDATA directory might cause a failure
671 * that won't go away). 100 tries seems like plenty.
673 for (ntries = 0;; ntries++)
676 * Try to create the lock file --- O_EXCL makes this atomic.
678 * Think not to make the file protection weaker than 0600. See
681 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
683 break; /* Success; exit the retry loop */
686 * Couldn't create the pid file. Probably it already exists.
688 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
690 (errcode_for_file_access(),
691 errmsg("could not create lock file \"%s\": %m",
695 * Read the file to get the old owner's PID. Note race condition
696 * here: file might have been deleted since we tried to create it.
698 fd = open(filename, O_RDONLY, 0600);
702 continue; /* race condition; try again */
704 (errcode_for_file_access(),
705 errmsg("could not open lock file \"%s\": %m",
708 if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
710 (errcode_for_file_access(),
711 errmsg("could not read lock file \"%s\": %m",
716 encoded_pid = atoi(buffer);
718 /* if pid < 0, the pid is for postgres, not postmaster */
719 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
722 elog(FATAL, "bogus data in lock file \"%s\": \"%s\"",
726 * Check to see if the other process still exists
728 * If the PID in the lockfile is our own PID or our parent's PID, then
729 * the file must be stale (probably left over from a previous system
730 * boot cycle). We need this test because of the likelihood that a
731 * reboot will assign exactly the same PID as we had in the previous
732 * reboot. Also, if there is just one more process launch in this
733 * reboot than in the previous one, the lockfile might mention our
734 * parent's PID. We can reject that since we'd never be launched
735 * directly by a competing postmaster. We can't detect grandparent
736 * processes unfortunately, but if the init script is written
737 * carefully then all but the immediate parent shell will be
738 * root-owned processes and so the kill test will fail with EPERM.
740 * We can treat the EPERM-error case as okay because that error
741 * implies that the existing process has a different userid than we
742 * do, which means it cannot be a competing postmaster. A postmaster
743 * cannot successfully attach to a data directory owned by a userid
744 * other than its own. (This is now checked directly in
745 * checkDataDir(), but has been true for a long time because of the
746 * restriction that the data directory isn't group- or
747 * world-accessible.) Also, since we create the lockfiles mode 600,
748 * we'd have failed above if the lockfile belonged to another userid
749 * --- which means that whatever process kill() is reporting about
750 * isn't the one that made the lockfile. (NOTE: this last
751 * consideration is the only one that keeps us from blowing away a
752 * Unix socket file belonging to an instance of Postgres being run by
753 * someone else, at least on machines where /tmp hasn't got a
756 * Windows hasn't got getppid(), but doesn't need it since it's not
757 * using real kill() either...
759 * Normally kill() will fail with ESRCH if the given PID doesn't
762 if (other_pid != my_pid
764 && other_pid != getppid()
768 if (kill(other_pid, 0) == 0 ||
769 (errno != ESRCH && errno != EPERM))
771 /* lockfile belongs to a live process */
773 (errcode(ERRCODE_LOCK_FILE_EXISTS),
774 errmsg("lock file \"%s\" already exists",
778 errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
779 (int) other_pid, refName) :
780 errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
781 (int) other_pid, refName)) :
783 errhint("Is another postgres (PID %d) using socket file \"%s\"?",
784 (int) other_pid, refName) :
785 errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
786 (int) other_pid, refName))));
791 * No, the creating process did not exist. However, it could be that
792 * the postmaster crashed (or more likely was kill -9'd by a clueless
793 * admin) but has left orphan backends behind. Check for this by
794 * looking to see if there is an associated shmem segment that is
803 ptr = strchr(buffer, '\n');
805 (ptr = strchr(ptr + 1, '\n')) != NULL)
808 if (sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
810 if (PGSharedMemoryIsInUse(id1, id2))
812 (errcode(ERRCODE_LOCK_FILE_EXISTS),
813 errmsg("pre-existing shared memory block "
814 "(key %lu, ID %lu) is still in use",
816 errhint("If you're sure there are no old "
817 "server processes still running, remove "
818 "the shared memory block with "
819 "the command \"ipcclean\", \"ipcrm\", "
820 "or just delete the file \"%s\".",
827 * Looks like nobody's home. Unlink the file and try again to create
828 * it. Need a loop because of possible race condition against other
831 if (unlink(filename) < 0)
833 (errcode_for_file_access(),
834 errmsg("could not remove old lock file \"%s\": %m",
836 errhint("The file seems accidentally left over, but "
837 "it could not be removed. Please remove the file "
838 "by hand and try again.")));
842 * Successfully created the file, now fill it.
844 snprintf(buffer, sizeof(buffer), "%d\n%s\n",
845 amPostmaster ? (int) my_pid : -((int) my_pid),
848 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
850 int save_errno = errno;
854 /* if write didn't set errno, assume problem is no disk space */
855 errno = save_errno ? save_errno : ENOSPC;
857 (errcode_for_file_access(),
858 errmsg("could not write lock file \"%s\": %m", filename)));
862 int save_errno = errno;
867 (errcode_for_file_access(),
868 errmsg("could not write lock file \"%s\": %m", filename)));
872 * Arrange for automatic removal of lockfile at proc_exit.
874 on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
878 * Create the data directory lockfile.
880 * When this is called, we must have already switched the working
881 * directory to DataDir, so we can just use a relative path. This
882 * helps ensure that we are locking the directory we should be.
885 CreateDataDirLockFile(bool amPostmaster)
887 CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, true, DataDir);
891 * Create a lockfile for the specified Unix socket file.
894 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
896 char lockfile[MAXPGPATH];
898 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
899 CreateLockFile(lockfile, amPostmaster, false, socketfile);
900 /* Save name of lockfile for TouchSocketLockFile */
901 strcpy(socketLockFile, lockfile);
905 * TouchSocketLockFile -- mark socket lock file as recently accessed
907 * This routine should be called every so often to ensure that the lock file
908 * has a recent mod or access date. That saves it
909 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
910 * (Another reason we should never have put the socket file in /tmp...)
913 TouchSocketLockFile(void)
915 /* Do nothing if we did not create a socket... */
916 if (socketLockFile[0] != '\0')
919 * utime() is POSIX standard, utimes() is a common alternative; if we
920 * have neither, fall back to actually reading the file (which only
921 * sets the access time not mod time, but that should be enough in
922 * most cases). In all paths, we ignore errors.
925 utime(socketLockFile, NULL);
926 #else /* !HAVE_UTIME */
928 utimes(socketLockFile, NULL);
929 #else /* !HAVE_UTIMES */
933 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
936 read(fd, buffer, sizeof(buffer));
939 #endif /* HAVE_UTIMES */
940 #endif /* HAVE_UTIME */
945 * Append information about a shared memory segment to the data directory
948 * This may be called multiple times in the life of a postmaster, if we
949 * delete and recreate shmem due to backend crash. Therefore, be prepared
950 * to overwrite existing information. (As of 7.1, a postmaster only creates
951 * one shm seg at a time; but for the purposes here, if we did have more than
952 * one then any one of them would do anyway.)
955 RecordSharedMemoryInLockFile(unsigned long id1, unsigned long id2)
962 fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
966 (errcode_for_file_access(),
967 errmsg("could not open file \"%s\": %m",
968 DIRECTORY_LOCK_FILE)));
971 len = read(fd, buffer, sizeof(buffer) - 100);
975 (errcode_for_file_access(),
976 errmsg("could not read from file \"%s\": %m",
977 DIRECTORY_LOCK_FILE)));
984 * Skip over first two lines (PID and path).
986 ptr = strchr(buffer, '\n');
988 (ptr = strchr(ptr + 1, '\n')) == NULL)
990 elog(LOG, "bogus data in \"%s\"", DIRECTORY_LOCK_FILE);
997 * Append key information. Format to try to keep it the same length
998 * always (trailing junk won't hurt, but might confuse humans).
1000 sprintf(ptr, "%9lu %9lu\n", id1, id2);
1003 * And rewrite the data. Since we write in a single kernel call, this
1004 * update should appear atomic to onlookers.
1006 len = strlen(buffer);
1008 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
1009 (int) write(fd, buffer, len) != len)
1011 /* if write didn't set errno, assume problem is no disk space */
1015 (errcode_for_file_access(),
1016 errmsg("could not write to file \"%s\": %m",
1017 DIRECTORY_LOCK_FILE)));
1024 (errcode_for_file_access(),
1025 errmsg("could not write to file \"%s\": %m",
1026 DIRECTORY_LOCK_FILE)));
1031 /*-------------------------------------------------------------------------
1032 * Version checking support
1033 *-------------------------------------------------------------------------
1037 * Determine whether the PG_VERSION file in directory `path' indicates
1038 * a data version compatible with the version of this program.
1040 * If compatible, return. Otherwise, ereport(FATAL).
1043 ValidatePgVersion(const char *path)
1045 char full_path[MAXPGPATH];
1053 const char *version_string = PG_VERSION;
1055 my_major = strtol(version_string, &endptr, 10);
1057 my_minor = strtol(endptr + 1, NULL, 10);
1059 snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1061 file = AllocateFile(full_path, "r");
1064 if (errno == ENOENT)
1066 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1067 errmsg("\"%s\" is not a valid data directory",
1069 errdetail("File \"%s\" is missing.", full_path)));
1072 (errcode_for_file_access(),
1073 errmsg("could not open file \"%s\": %m", full_path)));
1076 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
1079 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1080 errmsg("\"%s\" is not a valid data directory",
1082 errdetail("File \"%s\" does not contain valid data.",
1084 errhint("You may need to initdb.")));
1088 if (my_major != file_major || my_minor != file_minor)
1090 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1091 errmsg("database files are incompatible with server"),
1092 errdetail("The data directory was initialized by PostgreSQL version %ld.%ld, "
1093 "which is not compatible with this version %s.",
1094 file_major, file_minor, version_string)));
1097 /*-------------------------------------------------------------------------
1098 * Library preload support
1099 *-------------------------------------------------------------------------
1102 typedef void (*func_ptr) ();
1105 * process any libraries that should be preloaded and
1106 * optionally pre-initialized
1109 process_preload_libraries(char *preload_libraries_string)
1115 if (preload_libraries_string == NULL)
1118 /* Need a modifiable copy of string */
1119 rawstring = pstrdup(preload_libraries_string);
1121 /* Parse string into list of identifiers */
1122 if (!SplitIdentifierString(rawstring, ',', &elemlist))
1124 /* syntax error in list */
1126 list_free(elemlist);
1128 (errcode(ERRCODE_SYNTAX_ERROR),
1129 errmsg("invalid list syntax for parameter \"preload_libraries\"")));
1133 foreach(l, elemlist)
1135 char *tok = (char *) lfirst(l);
1136 char *sep = strstr(tok, ":");
1137 char *filename = NULL;
1138 char *funcname = NULL;
1144 * a colon separator implies there is an initialization function
1145 * that we need to run in addition to loading the library
1147 size_t filename_len = sep - tok;
1148 size_t funcname_len = strlen(tok) - filename_len - 1;
1150 filename = (char *) palloc(filename_len + 1);
1151 memcpy(filename, tok, filename_len);
1152 filename[filename_len] = '\0';
1154 funcname = (char *) palloc(funcname_len + 1);
1155 strcpy(funcname, sep + 1);
1160 * no separator -- just load the library
1162 filename = pstrdup(tok);
1166 canonicalize_path(filename);
1167 initfunc = (func_ptr) load_external_function(filename, funcname,
1174 (errmsg("preloaded library \"%s\" with initialization function \"%s\"",
1175 filename, funcname)));
1178 (errmsg("preloaded library \"%s\"",
1187 list_free(elemlist);