1 /*-------------------------------------------------------------------------
4 * miscellaneous initialization support stuff
6 * Portions Copyright (c) 1996-2006, 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.158 2006/08/16 04:32:48 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 && !IsAutoVacuumProcess())
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);
451 ProcessGUCArray(a, PGC_S_USER);
454 ReleaseSysCache(roleTup);
459 * Initialize user identity during special backend startup
462 InitializeSessionUserIdStandalone(void)
464 /* This function should only be called in a single-user backend. */
465 AssertState(!IsUnderPostmaster || IsAutoVacuumProcess());
468 AssertState(!OidIsValid(AuthenticatedUserId));
470 AuthenticatedUserId = BOOTSTRAP_SUPERUSERID;
471 AuthenticatedUserIsSuperuser = true;
473 SetSessionUserId(BOOTSTRAP_SUPERUSERID, true);
478 * Reset effective userid during AbortTransaction
480 * This is essentially SetUserId(GetOuterUserId()), but without the Asserts.
481 * The reason is that if a backend's InitPostgres transaction fails (eg,
482 * because an invalid user name was given), we have to be able to get through
483 * AbortTransaction without asserting.
488 CurrentUserId = OuterUserId;
493 * Change session auth ID while running
495 * Only a superuser may set auth ID to something other than himself. Note
496 * that in case of multiple SETs in a single session, the original userid's
497 * superuserness is what matters. But we set the GUC variable is_superuser
498 * to indicate whether the *current* session userid is a superuser.
500 * Note: this is not an especially clean place to do the permission check.
501 * It's OK because the check does not require catalog access and can't
502 * fail during an end-of-transaction GUC reversion, but we may someday
503 * have to push it up into assign_session_authorization.
506 SetSessionAuthorization(Oid userid, bool is_superuser)
508 /* Must have authenticated already, else can't make permission check */
509 AssertState(OidIsValid(AuthenticatedUserId));
511 if (userid != AuthenticatedUserId &&
512 !AuthenticatedUserIsSuperuser)
514 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE),
515 errmsg("permission denied to set session authorization")));
517 SetSessionUserId(userid, is_superuser);
519 SetConfigOption("is_superuser",
520 is_superuser ? "on" : "off",
521 PGC_INTERNAL, PGC_S_OVERRIDE);
525 * Report current role id
526 * This follows the semantics of SET ROLE, ie return the outer-level ID
527 * not the current effective ID, and return InvalidOid when the setting
528 * is logically SET ROLE NONE.
531 GetCurrentRoleId(void)
540 * Change Role ID while running (SET ROLE)
542 * If roleid is InvalidOid, we are doing SET ROLE NONE: revert to the
543 * session user authorization. In this case the is_superuser argument
546 * When roleid is not InvalidOid, the caller must have checked whether
547 * the session user has permission to become that role. (We cannot check
548 * here because this routine must be able to execute in a failed transaction
549 * to restore a prior value of the ROLE GUC variable.)
552 SetCurrentRoleId(Oid roleid, bool is_superuser)
555 * Get correct info if it's SET ROLE NONE
557 * If SessionUserId hasn't been set yet, just do nothing --- the eventual
558 * SetSessionUserId call will fix everything. This is needed since we
559 * will get called during GUC initialization.
561 if (!OidIsValid(roleid))
563 if (!OidIsValid(SessionUserId))
566 roleid = SessionUserId;
567 is_superuser = SessionUserIsSuperuser;
569 SetRoleIsActive = false;
572 SetRoleIsActive = true;
574 SetOuterUserId(roleid);
576 SetConfigOption("is_superuser",
577 is_superuser ? "on" : "off",
578 PGC_INTERNAL, PGC_S_OVERRIDE);
583 * Get user name from user oid
586 GetUserNameFromId(Oid roleid)
591 tuple = SearchSysCache(AUTHOID,
592 ObjectIdGetDatum(roleid),
594 if (!HeapTupleIsValid(tuple))
596 (errcode(ERRCODE_UNDEFINED_OBJECT),
597 errmsg("invalid role OID: %u", roleid)));
599 result = pstrdup(NameStr(((Form_pg_authid) GETSTRUCT(tuple))->rolname));
601 ReleaseSysCache(tuple);
606 /*-------------------------------------------------------------------------
607 * Interlock-file support
609 * These routines are used to create both a data-directory lockfile
610 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
611 * Both kinds of files contain the same info:
613 * Owning process' PID
614 * Data directory path
616 * By convention, the owning process' PID is negated if it is a standalone
617 * backend rather than a postmaster. This is just for informational purposes.
618 * The path is also just for informational purposes (so that a socket lockfile
619 * can be more easily traced to the associated postmaster).
621 * A data-directory lockfile can optionally contain a third line, containing
622 * the key and ID for the shared memory block used by this postmaster.
624 * On successful lockfile creation, a proc_exit callback to remove the
625 * lockfile is automatically created.
626 *-------------------------------------------------------------------------
630 * proc_exit callback to remove a lockfile.
633 UnlinkLockFile(int status, Datum filename)
635 char *fname = (char *) DatumGetPointer(filename);
639 if (unlink(fname) != 0)
641 /* Should we complain if the unlink fails? */
650 * filename is the name of the lockfile to create.
651 * amPostmaster is used to determine how to encode the output PID.
652 * isDDLock and refName are used to determine what error message to produce.
655 CreateLockFile(const char *filename, bool amPostmaster,
656 bool isDDLock, const char *refName)
659 char buffer[MAXPGPATH + 100];
664 pid_t my_pid = getpid();
667 * We need a loop here because of race conditions. But don't loop forever
668 * (for example, a non-writable $PGDATA directory might cause a failure
669 * that won't go away). 100 tries seems like plenty.
671 for (ntries = 0;; ntries++)
674 * Try to create the lock file --- O_EXCL makes this atomic.
676 * Think not to make the file protection weaker than 0600. See
679 fd = open(filename, O_RDWR | O_CREAT | O_EXCL, 0600);
681 break; /* Success; exit the retry loop */
684 * Couldn't create the pid file. Probably it already exists.
686 if ((errno != EEXIST && errno != EACCES) || ntries > 100)
688 (errcode_for_file_access(),
689 errmsg("could not create lock file \"%s\": %m",
693 * Read the file to get the old owner's PID. Note race condition
694 * here: file might have been deleted since we tried to create it.
696 fd = open(filename, O_RDONLY, 0600);
700 continue; /* race condition; try again */
702 (errcode_for_file_access(),
703 errmsg("could not open lock file \"%s\": %m",
706 if ((len = read(fd, buffer, sizeof(buffer) - 1)) < 0)
708 (errcode_for_file_access(),
709 errmsg("could not read lock file \"%s\": %m",
714 encoded_pid = atoi(buffer);
716 /* if pid < 0, the pid is for postgres, not postmaster */
717 other_pid = (pid_t) (encoded_pid < 0 ? -encoded_pid : encoded_pid);
720 elog(FATAL, "bogus data in lock file \"%s\": \"%s\"",
724 * Check to see if the other process still exists
726 * If the PID in the lockfile is our own PID or our parent's PID, then
727 * the file must be stale (probably left over from a previous system
728 * boot cycle). We need this test because of the likelihood that a
729 * reboot will assign exactly the same PID as we had in the previous
730 * reboot. Also, if there is just one more process launch in this
731 * reboot than in the previous one, the lockfile might mention our
732 * parent's PID. We can reject that since we'd never be launched
733 * directly by a competing postmaster. We can't detect grandparent
734 * processes unfortunately, but if the init script is written
735 * carefully then all but the immediate parent shell will be
736 * root-owned processes and so the kill test will fail with EPERM.
738 * We can treat the EPERM-error case as okay because that error
739 * implies that the existing process has a different userid than we
740 * do, which means it cannot be a competing postmaster. A postmaster
741 * cannot successfully attach to a data directory owned by a userid
742 * other than its own. (This is now checked directly in
743 * checkDataDir(), but has been true for a long time because of the
744 * restriction that the data directory isn't group- or
745 * world-accessible.) Also, since we create the lockfiles mode 600,
746 * we'd have failed above if the lockfile belonged to another userid
747 * --- which means that whatever process kill() is reporting about
748 * isn't the one that made the lockfile. (NOTE: this last
749 * consideration is the only one that keeps us from blowing away a
750 * Unix socket file belonging to an instance of Postgres being run by
751 * someone else, at least on machines where /tmp hasn't got a
754 * Windows hasn't got getppid(), but doesn't need it since it's not
755 * using real kill() either...
757 * Normally kill() will fail with ESRCH if the given PID doesn't
760 if (other_pid != my_pid
762 && other_pid != getppid()
766 if (kill(other_pid, 0) == 0 ||
767 (errno != ESRCH && errno != EPERM))
769 /* lockfile belongs to a live process */
771 (errcode(ERRCODE_LOCK_FILE_EXISTS),
772 errmsg("lock file \"%s\" already exists",
776 errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
777 (int) other_pid, refName) :
778 errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
779 (int) other_pid, refName)) :
781 errhint("Is another postgres (PID %d) using socket file \"%s\"?",
782 (int) other_pid, refName) :
783 errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
784 (int) other_pid, refName))));
789 * No, the creating process did not exist. However, it could be that
790 * the postmaster crashed (or more likely was kill -9'd by a clueless
791 * admin) but has left orphan backends behind. Check for this by
792 * looking to see if there is an associated shmem segment that is
801 ptr = strchr(buffer, '\n');
803 (ptr = strchr(ptr + 1, '\n')) != NULL)
806 if (sscanf(ptr, "%lu %lu", &id1, &id2) == 2)
808 if (PGSharedMemoryIsInUse(id1, id2))
810 (errcode(ERRCODE_LOCK_FILE_EXISTS),
811 errmsg("pre-existing shared memory block "
812 "(key %lu, ID %lu) is still in use",
814 errhint("If you're sure there are no old "
815 "server processes still running, remove "
816 "the shared memory block with "
817 "the command \"ipcclean\", \"ipcrm\", "
818 "or just delete the file \"%s\".",
825 * Looks like nobody's home. Unlink the file and try again to create
826 * it. Need a loop because of possible race condition against other
829 if (unlink(filename) < 0)
831 (errcode_for_file_access(),
832 errmsg("could not remove old lock file \"%s\": %m",
834 errhint("The file seems accidentally left over, but "
835 "it could not be removed. Please remove the file "
836 "by hand and try again.")));
840 * Successfully created the file, now fill it.
842 snprintf(buffer, sizeof(buffer), "%d\n%s\n",
843 amPostmaster ? (int) my_pid : -((int) my_pid),
846 if (write(fd, buffer, strlen(buffer)) != strlen(buffer))
848 int save_errno = errno;
852 /* if write didn't set errno, assume problem is no disk space */
853 errno = save_errno ? save_errno : ENOSPC;
855 (errcode_for_file_access(),
856 errmsg("could not write lock file \"%s\": %m", filename)));
860 int save_errno = errno;
865 (errcode_for_file_access(),
866 errmsg("could not write lock file \"%s\": %m", filename)));
870 * Arrange for automatic removal of lockfile at proc_exit.
872 on_proc_exit(UnlinkLockFile, PointerGetDatum(strdup(filename)));
876 * Create the data directory lockfile.
878 * When this is called, we must have already switched the working
879 * directory to DataDir, so we can just use a relative path. This
880 * helps ensure that we are locking the directory we should be.
883 CreateDataDirLockFile(bool amPostmaster)
885 CreateLockFile(DIRECTORY_LOCK_FILE, amPostmaster, true, DataDir);
889 * Create a lockfile for the specified Unix socket file.
892 CreateSocketLockFile(const char *socketfile, bool amPostmaster)
894 char lockfile[MAXPGPATH];
896 snprintf(lockfile, sizeof(lockfile), "%s.lock", socketfile);
897 CreateLockFile(lockfile, amPostmaster, false, socketfile);
898 /* Save name of lockfile for TouchSocketLockFile */
899 strcpy(socketLockFile, lockfile);
903 * TouchSocketLockFile -- mark socket lock file as recently accessed
905 * This routine should be called every so often to ensure that the lock file
906 * has a recent mod or access date. That saves it
907 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
908 * (Another reason we should never have put the socket file in /tmp...)
911 TouchSocketLockFile(void)
913 /* Do nothing if we did not create a socket... */
914 if (socketLockFile[0] != '\0')
917 * utime() is POSIX standard, utimes() is a common alternative; if we
918 * have neither, fall back to actually reading the file (which only
919 * sets the access time not mod time, but that should be enough in
920 * most cases). In all paths, we ignore errors.
923 utime(socketLockFile, NULL);
924 #else /* !HAVE_UTIME */
926 utimes(socketLockFile, NULL);
927 #else /* !HAVE_UTIMES */
931 fd = open(socketLockFile, O_RDONLY | PG_BINARY, 0);
934 read(fd, buffer, sizeof(buffer));
937 #endif /* HAVE_UTIMES */
938 #endif /* HAVE_UTIME */
943 * Append information about a shared memory segment to the data directory
946 * This may be called multiple times in the life of a postmaster, if we
947 * delete and recreate shmem due to backend crash. Therefore, be prepared
948 * to overwrite existing information. (As of 7.1, a postmaster only creates
949 * one shm seg at a time; but for the purposes here, if we did have more than
950 * one then any one of them would do anyway.)
953 RecordSharedMemoryInLockFile(unsigned long id1, unsigned long id2)
960 fd = open(DIRECTORY_LOCK_FILE, O_RDWR | PG_BINARY, 0);
964 (errcode_for_file_access(),
965 errmsg("could not open file \"%s\": %m",
966 DIRECTORY_LOCK_FILE)));
969 len = read(fd, buffer, sizeof(buffer) - 100);
973 (errcode_for_file_access(),
974 errmsg("could not read from file \"%s\": %m",
975 DIRECTORY_LOCK_FILE)));
982 * Skip over first two lines (PID and path).
984 ptr = strchr(buffer, '\n');
986 (ptr = strchr(ptr + 1, '\n')) == NULL)
988 elog(LOG, "bogus data in \"%s\"", DIRECTORY_LOCK_FILE);
995 * Append key information. Format to try to keep it the same length
996 * always (trailing junk won't hurt, but might confuse humans).
998 sprintf(ptr, "%9lu %9lu\n", id1, id2);
1001 * And rewrite the data. Since we write in a single kernel call, this
1002 * update should appear atomic to onlookers.
1004 len = strlen(buffer);
1006 if (lseek(fd, (off_t) 0, SEEK_SET) != 0 ||
1007 (int) write(fd, buffer, len) != len)
1009 /* if write didn't set errno, assume problem is no disk space */
1013 (errcode_for_file_access(),
1014 errmsg("could not write to file \"%s\": %m",
1015 DIRECTORY_LOCK_FILE)));
1022 (errcode_for_file_access(),
1023 errmsg("could not write to file \"%s\": %m",
1024 DIRECTORY_LOCK_FILE)));
1029 /*-------------------------------------------------------------------------
1030 * Version checking support
1031 *-------------------------------------------------------------------------
1035 * Determine whether the PG_VERSION file in directory `path' indicates
1036 * a data version compatible with the version of this program.
1038 * If compatible, return. Otherwise, ereport(FATAL).
1041 ValidatePgVersion(const char *path)
1043 char full_path[MAXPGPATH];
1051 const char *version_string = PG_VERSION;
1053 my_major = strtol(version_string, &endptr, 10);
1055 my_minor = strtol(endptr + 1, NULL, 10);
1057 snprintf(full_path, sizeof(full_path), "%s/PG_VERSION", path);
1059 file = AllocateFile(full_path, "r");
1062 if (errno == ENOENT)
1064 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1065 errmsg("\"%s\" is not a valid data directory",
1067 errdetail("File \"%s\" is missing.", full_path)));
1070 (errcode_for_file_access(),
1071 errmsg("could not open file \"%s\": %m", full_path)));
1074 ret = fscanf(file, "%ld.%ld", &file_major, &file_minor);
1077 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1078 errmsg("\"%s\" is not a valid data directory",
1080 errdetail("File \"%s\" does not contain valid data.",
1082 errhint("You may need to initdb.")));
1086 if (my_major != file_major || my_minor != file_minor)
1088 (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
1089 errmsg("database files are incompatible with server"),
1090 errdetail("The data directory was initialized by PostgreSQL version %ld.%ld, "
1091 "which is not compatible with this version %s.",
1092 file_major, file_minor, version_string)));
1095 /*-------------------------------------------------------------------------
1096 * Library preload support
1097 *-------------------------------------------------------------------------
1101 * GUC variables: lists of library names to be preloaded at postmaster
1102 * start and at backend start
1104 char *shared_preload_libraries_string = NULL;
1105 char *local_preload_libraries_string = NULL;
1108 * load the shared libraries listed in 'libraries'
1110 * 'gucname': name of GUC variable, for error reports
1111 * 'restricted': if true, force libraries to be in $libdir/plugins/
1114 load_libraries(const char *libraries, const char *gucname, bool restricted)
1120 if (libraries == NULL || libraries[0] == '\0')
1121 return; /* nothing to do */
1123 /* Need a modifiable copy of string */
1124 rawstring = pstrdup(libraries);
1126 /* Parse string into list of identifiers */
1127 if (!SplitIdentifierString(rawstring, ',', &elemlist))
1129 /* syntax error in list */
1131 list_free(elemlist);
1133 (errcode(ERRCODE_SYNTAX_ERROR),
1134 errmsg("invalid list syntax in parameter \"%s\"",
1139 foreach(l, elemlist)
1141 char *tok = (char *) lfirst(l);
1144 filename = pstrdup(tok);
1145 canonicalize_path(filename);
1146 /* If restricting, insert $libdir/plugins if not mentioned already */
1147 if (restricted && first_dir_separator(filename) == NULL)
1151 expanded = palloc(strlen("$libdir/plugins/") + strlen(filename) + 1);
1152 strcpy(expanded, "$libdir/plugins/");
1153 strcat(expanded, filename);
1155 filename = expanded;
1157 load_file(filename, restricted);
1159 (errmsg("loaded library \"%s\"", filename)));
1164 list_free(elemlist);
1168 * process any libraries that should be preloaded at postmaster start
1171 process_shared_preload_libraries(void)
1173 load_libraries(shared_preload_libraries_string,
1174 "shared_preload_libraries",
1179 * process any libraries that should be preloaded at backend start
1182 process_local_preload_libraries(void)
1184 load_libraries(local_preload_libraries_string,
1185 "local_preload_libraries",