1 /*-------------------------------------------------------------------------
4 * miscellaneous initialization support stuff
6 * Portions Copyright (c) 1996-2009, PostgreSQL Global Development Group
7 * Portions Copyright (c) 1994, Regents of the University of California
13 *-------------------------------------------------------------------------
17 #include <sys/param.h>
26 #include <netinet/in.h>
27 #include <arpa/inet.h>
32 #include "catalog/pg_authid.h"
33 #include "mb/pg_wchar.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/syscache.h"
46 #define DIRECTORY_LOCK_FILE "postmaster.pid"
48 ProcessingMode Mode
= InitProcessing
;
50 /* Note: we rely on this to initialize as zeroes */
51 static char socketLockFile
[MAXPGPATH
];
54 /* ----------------------------------------------------------------
55 * ignoring system indexes support stuff
57 * NOTE: "ignoring system indexes" means we do not use the system indexes
58 * for lookups (either in hardwired catalog accesses or in planner-generated
59 * plans). We do, however, still update the indexes when a catalog
60 * modification is made.
61 * ----------------------------------------------------------------
64 bool IgnoreSystemIndexes
= false;
66 /* ----------------------------------------------------------------
67 * system index reindexing support
69 * When we are busy reindexing a system index, this code provides support
70 * for preventing catalog lookups from using that index.
71 * ----------------------------------------------------------------
74 static Oid currentlyReindexedHeap
= InvalidOid
;
75 static Oid currentlyReindexedIndex
= InvalidOid
;
78 * ReindexIsProcessingHeap
79 * True if heap specified by OID is currently being reindexed.
82 ReindexIsProcessingHeap(Oid heapOid
)
84 return heapOid
== currentlyReindexedHeap
;
88 * ReindexIsProcessingIndex
89 * True if index specified by OID is currently being reindexed.
92 ReindexIsProcessingIndex(Oid indexOid
)
94 return indexOid
== currentlyReindexedIndex
;
98 * SetReindexProcessing
99 * Set flag that specified heap/index are being reindexed.
102 SetReindexProcessing(Oid heapOid
, Oid indexOid
)
104 Assert(OidIsValid(heapOid
) && OidIsValid(indexOid
));
105 /* Reindexing is not re-entrant. */
106 if (OidIsValid(currentlyReindexedIndex
))
107 elog(ERROR
, "cannot reindex while reindexing");
108 currentlyReindexedHeap
= heapOid
;
109 currentlyReindexedIndex
= indexOid
;
113 * ResetReindexProcessing
114 * Unset reindexing status.
117 ResetReindexProcessing(void)
119 currentlyReindexedHeap
= InvalidOid
;
120 currentlyReindexedIndex
= InvalidOid
;
123 /* ----------------------------------------------------------------
124 * database path / name support stuff
125 * ----------------------------------------------------------------
129 SetDatabasePath(const char *path
)
136 /* use strdup since this is done before memory contexts are set up */
139 DatabasePath
= strdup(path
);
140 AssertState(DatabasePath
);
145 * Set data directory, but make sure it's an absolute path. Use this,
146 * never set DataDir directly.
149 SetDataDir(const char *dir
)
155 /* If presented path is relative, convert to absolute */
156 new = make_absolute_path(dir
);
164 * Change working directory to DataDir. Most of the postmaster and backend
165 * code assumes that we are in DataDir so it can use relative paths to access
166 * stuff in and under the data directory. For convenience during path
167 * setup, however, we don't force the chdir to occur during SetDataDir.
170 ChangeToDataDir(void)
172 AssertState(DataDir
);
174 if (chdir(DataDir
) < 0)
176 (errcode_for_file_access(),
177 errmsg("could not change directory to \"%s\": %m",
182 * If the given pathname isn't already absolute, make it so, interpreting
183 * it relative to the current working directory.
185 * Also canonicalizes the path. The result is always a malloc'd copy.
187 * Note: interpretation of relative-path arguments during postmaster startup
188 * should happen before doing ChangeToDataDir(), else the user will probably
189 * not like the results.
192 make_absolute_path(const char *path
)
196 /* Returning null for null input is convenient for some callers */
200 if (!is_absolute_path(path
))
208 buf
= malloc(buflen
);
211 (errcode(ERRCODE_OUT_OF_MEMORY
),
212 errmsg("out of memory")));
214 if (getcwd(buf
, buflen
))
216 else if (errno
== ERANGE
)
225 elog(FATAL
, "could not get current working directory: %m");
229 new = malloc(strlen(buf
) + strlen(path
) + 2);
232 (errcode(ERRCODE_OUT_OF_MEMORY
),
233 errmsg("out of memory")));
234 sprintf(new, "%s/%s", buf
, path
);
242 (errcode(ERRCODE_OUT_OF_MEMORY
),
243 errmsg("out of memory")));
246 /* Make sure punctuation is canonical, too */
247 canonicalize_path(new);
253 /* ----------------------------------------------------------------
256 * We have to track several different values associated with the concept
259 * AuthenticatedUserId is determined at connection start and never changes.
261 * SessionUserId is initially the same as AuthenticatedUserId, but can be
262 * changed by SET SESSION AUTHORIZATION (if AuthenticatedUserIsSuperuser).
263 * This is the ID reported by the SESSION_USER SQL function.
265 * OuterUserId is the current user ID in effect at the "outer level" (outside
266 * any transaction or function). This is initially the same as SessionUserId,
267 * but can be changed by SET ROLE to any role that SessionUserId is a
268 * member of. (XXX rename to something like CurrentRoleId?)
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.
275 * SecurityDefinerContext is TRUE if we are within a SECURITY DEFINER function
276 * or another context that temporarily changes CurrentUserId.
277 * ----------------------------------------------------------------
279 static Oid AuthenticatedUserId
= InvalidOid
;
280 static Oid SessionUserId
= InvalidOid
;
281 static Oid OuterUserId
= InvalidOid
;
282 static Oid CurrentUserId
= InvalidOid
;
284 /* We also have to remember the superuser state of some of these levels */
285 static bool AuthenticatedUserIsSuperuser
= false;
286 static bool SessionUserIsSuperuser
= false;
288 static bool SecurityDefinerContext
= false;
290 /* We also remember if a SET ROLE is currently active */
291 static bool SetRoleIsActive
= false;
295 * GetUserId - get the current effective user ID.
297 * Note: there's no SetUserId() anymore; use SetUserIdAndContext().
302 AssertState(OidIsValid(CurrentUserId
));
303 return CurrentUserId
;
308 * GetOuterUserId/SetOuterUserId - get/set the outer-level user ID.
313 AssertState(OidIsValid(OuterUserId
));
319 SetOuterUserId(Oid userid
)
321 AssertState(!SecurityDefinerContext
);
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 AssertState(!SecurityDefinerContext
);
345 AssertArg(OidIsValid(userid
));
346 SessionUserId
= userid
;
347 SessionUserIsSuperuser
= is_superuser
;
348 SetRoleIsActive
= false;
350 /* We force the effective user IDs to match, too */
351 OuterUserId
= userid
;
352 CurrentUserId
= userid
;
357 * GetUserIdAndContext/SetUserIdAndContext - get/set the current user ID
358 * and the SecurityDefinerContext flag.
360 * Unlike GetUserId, GetUserIdAndContext does *not* Assert that the current
361 * value of CurrentUserId is valid; nor does SetUserIdAndContext require
362 * the new value to be valid. In fact, these routines had better not
363 * ever throw any kind of error. This is because they are used by
364 * StartTransaction and AbortTransaction to save/restore the settings,
365 * and during the first transaction within a backend, the value to be saved
366 * and perhaps restored is indeed invalid. We have to be able to get
367 * through AbortTransaction without asserting in case InitPostgres fails.
370 GetUserIdAndContext(Oid
*userid
, bool *sec_def_context
)
372 *userid
= CurrentUserId
;
373 *sec_def_context
= SecurityDefinerContext
;
377 SetUserIdAndContext(Oid userid
, bool sec_def_context
)
379 CurrentUserId
= userid
;
380 SecurityDefinerContext
= sec_def_context
;
385 * InSecurityDefinerContext - are we inside a SECURITY DEFINER context?
388 InSecurityDefinerContext(void)
390 return SecurityDefinerContext
;
395 * Initialize user identity during normal backend startup
398 InitializeSessionUserId(const char *rolename
)
401 Form_pg_authid rform
;
407 * Don't do scans if we're bootstrapping, none of the system catalogs
408 * exist yet, and they should be owned by postgres anyway.
410 AssertState(!IsBootstrapProcessingMode());
413 AssertState(!OidIsValid(AuthenticatedUserId
));
415 roleTup
= SearchSysCache(AUTHNAME
,
416 PointerGetDatum(rolename
),
418 if (!HeapTupleIsValid(roleTup
))
420 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION
),
421 errmsg("role \"%s\" does not exist", rolename
)));
423 rform
= (Form_pg_authid
) GETSTRUCT(roleTup
);
424 roleid
= HeapTupleGetOid(roleTup
);
426 AuthenticatedUserId
= roleid
;
427 AuthenticatedUserIsSuperuser
= rform
->rolsuper
;
429 /* This sets OuterUserId/CurrentUserId too */
430 SetSessionUserId(roleid
, AuthenticatedUserIsSuperuser
);
432 /* Also mark our PGPROC entry with the authenticated user id */
433 /* (We assume this is an atomic store so no lock is needed) */
434 MyProc
->roleId
= roleid
;
437 * These next checks are not enforced when in standalone mode, so that
438 * there is a way to recover from sillinesses like "UPDATE pg_authid SET
439 * rolcanlogin = false;".
441 * We do not enforce them for the autovacuum process either.
443 if (IsUnderPostmaster
&& !IsAutoVacuumWorkerProcess())
446 * Is role allowed to login at all?
448 if (!rform
->rolcanlogin
)
450 (errcode(ERRCODE_INVALID_AUTHORIZATION_SPECIFICATION
),
451 errmsg("role \"%s\" is not permitted to log in",
455 * Check connection limit for this role.
457 * There is a race condition here --- we create our PGPROC before
458 * checking for other PGPROCs. If two backends did this at about the
459 * same time, they might both think they were over the limit, while
460 * ideally one should succeed and one fail. Getting that to work
461 * exactly seems more trouble than it is worth, however; instead we
462 * just document that the connection limit is approximate.
464 if (rform
->rolconnlimit
>= 0 &&
465 !AuthenticatedUserIsSuperuser
&&
466 CountUserBackends(roleid
) > rform
->rolconnlimit
)
468 (errcode(ERRCODE_TOO_MANY_CONNECTIONS
),
469 errmsg("too many connections for role \"%s\"",
473 /* Record username and superuser status as GUC settings too */
474 SetConfigOption("session_authorization", rolename
,
475 PGC_BACKEND
, PGC_S_OVERRIDE
);
476 SetConfigOption("is_superuser",
477 AuthenticatedUserIsSuperuser
? "on" : "off",
478 PGC_INTERNAL
, PGC_S_OVERRIDE
);
481 * Set up user-specific configuration variables. This is a good place to
482 * do it so we don't have to read pg_authid twice during session startup.
484 datum
= SysCacheGetAttr(AUTHNAME
, roleTup
,
485 Anum_pg_authid_rolconfig
, &isnull
);
488 ArrayType
*a
= DatumGetArrayTypeP(datum
);
491 * We process all the options at SUSET level. We assume that the
492 * right to insert an option into pg_authid was checked when it was
495 ProcessGUCArray(a
, PGC_SUSET
, PGC_S_USER
, GUC_ACTION_SET
);
498 ReleaseSysCache(roleTup
);
503 * Initialize user identity during special backend startup
506 InitializeSessionUserIdStandalone(void)
508 /* This function should only be called in a single-user backend. */
509 AssertState(!IsUnderPostmaster
|| IsAutoVacuumWorkerProcess());
512 AssertState(!OidIsValid(AuthenticatedUserId
));
514 AuthenticatedUserId
= BOOTSTRAP_SUPERUSERID
;
515 AuthenticatedUserIsSuperuser
= true;
517 SetSessionUserId(BOOTSTRAP_SUPERUSERID
, true);
522 * Change session auth ID while running
524 * Only a superuser may set auth ID to something other than himself. Note
525 * that in case of multiple SETs in a single session, the original userid's
526 * superuserness is what matters. But we set the GUC variable is_superuser
527 * to indicate whether the *current* session userid is a superuser.
529 * Note: this is not an especially clean place to do the permission check.
530 * It's OK because the check does not require catalog access and can't
531 * fail during an end-of-transaction GUC reversion, but we may someday
532 * have to push it up into assign_session_authorization.
535 SetSessionAuthorization(Oid userid
, bool is_superuser
)
537 /* Must have authenticated already, else can't make permission check */
538 AssertState(OidIsValid(AuthenticatedUserId
));
540 if (userid
!= AuthenticatedUserId
&&
541 !AuthenticatedUserIsSuperuser
)
543 (errcode(ERRCODE_INSUFFICIENT_PRIVILEGE
),
544 errmsg("permission denied to set session authorization")));
546 SetSessionUserId(userid
, is_superuser
);
548 SetConfigOption("is_superuser",
549 is_superuser
? "on" : "off",
550 PGC_INTERNAL
, PGC_S_OVERRIDE
);
554 * Report current role id
555 * This follows the semantics of SET ROLE, ie return the outer-level ID
556 * not the current effective ID, and return InvalidOid when the setting
557 * is logically SET ROLE NONE.
560 GetCurrentRoleId(void)
569 * Change Role ID while running (SET ROLE)
571 * If roleid is InvalidOid, we are doing SET ROLE NONE: revert to the
572 * session user authorization. In this case the is_superuser argument
575 * When roleid is not InvalidOid, the caller must have checked whether
576 * the session user has permission to become that role. (We cannot check
577 * here because this routine must be able to execute in a failed transaction
578 * to restore a prior value of the ROLE GUC variable.)
581 SetCurrentRoleId(Oid roleid
, bool is_superuser
)
584 * Get correct info if it's SET ROLE NONE
586 * If SessionUserId hasn't been set yet, just do nothing --- the eventual
587 * SetSessionUserId call will fix everything. This is needed since we
588 * will get called during GUC initialization.
590 if (!OidIsValid(roleid
))
592 if (!OidIsValid(SessionUserId
))
595 roleid
= SessionUserId
;
596 is_superuser
= SessionUserIsSuperuser
;
598 SetRoleIsActive
= false;
601 SetRoleIsActive
= true;
603 SetOuterUserId(roleid
);
605 SetConfigOption("is_superuser",
606 is_superuser
? "on" : "off",
607 PGC_INTERNAL
, PGC_S_OVERRIDE
);
612 * Get user name from user oid
615 GetUserNameFromId(Oid roleid
)
620 tuple
= SearchSysCache(AUTHOID
,
621 ObjectIdGetDatum(roleid
),
623 if (!HeapTupleIsValid(tuple
))
625 (errcode(ERRCODE_UNDEFINED_OBJECT
),
626 errmsg("invalid role OID: %u", roleid
)));
628 result
= pstrdup(NameStr(((Form_pg_authid
) GETSTRUCT(tuple
))->rolname
));
630 ReleaseSysCache(tuple
);
635 /*-------------------------------------------------------------------------
636 * Interlock-file support
638 * These routines are used to create both a data-directory lockfile
639 * ($DATADIR/postmaster.pid) and a Unix-socket-file lockfile ($SOCKFILE.lock).
640 * Both kinds of files contain the same info:
642 * Owning process' PID
643 * Data directory path
645 * By convention, the owning process' PID is negated if it is a standalone
646 * backend rather than a postmaster. This is just for informational purposes.
647 * The path is also just for informational purposes (so that a socket lockfile
648 * can be more easily traced to the associated postmaster).
650 * A data-directory lockfile can optionally contain a third line, containing
651 * the key and ID for the shared memory block used by this postmaster.
653 * On successful lockfile creation, a proc_exit callback to remove the
654 * lockfile is automatically created.
655 *-------------------------------------------------------------------------
659 * proc_exit callback to remove a lockfile.
662 UnlinkLockFile(int status
, Datum filename
)
664 char *fname
= (char *) DatumGetPointer(filename
);
668 if (unlink(fname
) != 0)
670 /* Should we complain if the unlink fails? */
679 * filename is the name of the lockfile to create.
680 * amPostmaster is used to determine how to encode the output PID.
681 * isDDLock and refName are used to determine what error message to produce.
684 CreateLockFile(const char *filename
, bool amPostmaster
,
685 bool isDDLock
, const char *refName
)
688 char buffer
[MAXPGPATH
+ 100];
693 pid_t my_pid
= getpid();
696 * We need a loop here because of race conditions. But don't loop forever
697 * (for example, a non-writable $PGDATA directory might cause a failure
698 * that won't go away). 100 tries seems like plenty.
700 for (ntries
= 0;; ntries
++)
703 * Try to create the lock file --- O_EXCL makes this atomic.
705 * Think not to make the file protection weaker than 0600. See
708 fd
= open(filename
, O_RDWR
| O_CREAT
| O_EXCL
, 0600);
710 break; /* Success; exit the retry loop */
713 * Couldn't create the pid file. Probably it already exists.
715 if ((errno
!= EEXIST
&& errno
!= EACCES
) || ntries
> 100)
717 (errcode_for_file_access(),
718 errmsg("could not create lock file \"%s\": %m",
722 * Read the file to get the old owner's PID. Note race condition
723 * here: file might have been deleted since we tried to create it.
725 fd
= open(filename
, O_RDONLY
, 0600);
729 continue; /* race condition; try again */
731 (errcode_for_file_access(),
732 errmsg("could not open lock file \"%s\": %m",
735 if ((len
= read(fd
, buffer
, sizeof(buffer
) - 1)) < 0)
737 (errcode_for_file_access(),
738 errmsg("could not read lock file \"%s\": %m",
743 encoded_pid
= atoi(buffer
);
745 /* if pid < 0, the pid is for postgres, not postmaster */
746 other_pid
= (pid_t
) (encoded_pid
< 0 ? -encoded_pid
: encoded_pid
);
749 elog(FATAL
, "bogus data in lock file \"%s\": \"%s\"",
753 * Check to see if the other process still exists
755 * If the PID in the lockfile is our own PID or our parent's PID, then
756 * the file must be stale (probably left over from a previous system
757 * boot cycle). We need this test because of the likelihood that a
758 * reboot will assign exactly the same PID as we had in the previous
759 * reboot. Also, if there is just one more process launch in this
760 * reboot than in the previous one, the lockfile might mention our
761 * parent's PID. We can reject that since we'd never be launched
762 * directly by a competing postmaster. We can't detect grandparent
763 * processes unfortunately, but if the init script is written
764 * carefully then all but the immediate parent shell will be
765 * root-owned processes and so the kill test will fail with EPERM.
767 * We can treat the EPERM-error case as okay because that error
768 * implies that the existing process has a different userid than we
769 * do, which means it cannot be a competing postmaster. A postmaster
770 * cannot successfully attach to a data directory owned by a userid
771 * other than its own. (This is now checked directly in
772 * checkDataDir(), but has been true for a long time because of the
773 * restriction that the data directory isn't group- or
774 * world-accessible.) Also, since we create the lockfiles mode 600,
775 * we'd have failed above if the lockfile belonged to another userid
776 * --- which means that whatever process kill() is reporting about
777 * isn't the one that made the lockfile. (NOTE: this last
778 * consideration is the only one that keeps us from blowing away a
779 * Unix socket file belonging to an instance of Postgres being run by
780 * someone else, at least on machines where /tmp hasn't got a
783 * Windows hasn't got getppid(), but doesn't need it since it's not
784 * using real kill() either...
786 * Normally kill() will fail with ESRCH if the given PID doesn't
789 if (other_pid
!= my_pid
791 && other_pid
!= getppid()
795 if (kill(other_pid
, 0) == 0 ||
796 (errno
!= ESRCH
&& errno
!= EPERM
))
798 /* lockfile belongs to a live process */
800 (errcode(ERRCODE_LOCK_FILE_EXISTS
),
801 errmsg("lock file \"%s\" already exists",
805 errhint("Is another postgres (PID %d) running in data directory \"%s\"?",
806 (int) other_pid
, refName
) :
807 errhint("Is another postmaster (PID %d) running in data directory \"%s\"?",
808 (int) other_pid
, refName
)) :
810 errhint("Is another postgres (PID %d) using socket file \"%s\"?",
811 (int) other_pid
, refName
) :
812 errhint("Is another postmaster (PID %d) using socket file \"%s\"?",
813 (int) other_pid
, refName
))));
818 * No, the creating process did not exist. However, it could be that
819 * the postmaster crashed (or more likely was kill -9'd by a clueless
820 * admin) but has left orphan backends behind. Check for this by
821 * looking to see if there is an associated shmem segment that is
830 ptr
= strchr(buffer
, '\n');
832 (ptr
= strchr(ptr
+ 1, '\n')) != NULL
)
835 if (sscanf(ptr
, "%lu %lu", &id1
, &id2
) == 2)
837 if (PGSharedMemoryIsInUse(id1
, id2
))
839 (errcode(ERRCODE_LOCK_FILE_EXISTS
),
840 errmsg("pre-existing shared memory block "
841 "(key %lu, ID %lu) is still in use",
843 errhint("If you're sure there are no old "
844 "server processes still running, remove "
845 "the shared memory block "
846 "or just delete the file \"%s\".",
853 * Looks like nobody's home. Unlink the file and try again to create
854 * it. Need a loop because of possible race condition against other
857 if (unlink(filename
) < 0)
859 (errcode_for_file_access(),
860 errmsg("could not remove old lock file \"%s\": %m",
862 errhint("The file seems accidentally left over, but "
863 "it could not be removed. Please remove the file "
864 "by hand and try again.")));
868 * Successfully created the file, now fill it.
870 snprintf(buffer
, sizeof(buffer
), "%d\n%s\n",
871 amPostmaster
? (int) my_pid
: -((int) my_pid
),
874 if (write(fd
, buffer
, strlen(buffer
)) != strlen(buffer
))
876 int save_errno
= errno
;
880 /* if write didn't set errno, assume problem is no disk space */
881 errno
= save_errno
? save_errno
: ENOSPC
;
883 (errcode_for_file_access(),
884 errmsg("could not write lock file \"%s\": %m", filename
)));
888 int save_errno
= errno
;
893 (errcode_for_file_access(),
894 errmsg("could not write lock file \"%s\": %m", filename
)));
898 * Arrange for automatic removal of lockfile at proc_exit.
900 on_proc_exit(UnlinkLockFile
, PointerGetDatum(strdup(filename
)));
904 * Create the data directory lockfile.
906 * When this is called, we must have already switched the working
907 * directory to DataDir, so we can just use a relative path. This
908 * helps ensure that we are locking the directory we should be.
911 CreateDataDirLockFile(bool amPostmaster
)
913 CreateLockFile(DIRECTORY_LOCK_FILE
, amPostmaster
, true, DataDir
);
917 * Create a lockfile for the specified Unix socket file.
920 CreateSocketLockFile(const char *socketfile
, bool amPostmaster
)
922 char lockfile
[MAXPGPATH
];
924 snprintf(lockfile
, sizeof(lockfile
), "%s.lock", socketfile
);
925 CreateLockFile(lockfile
, amPostmaster
, false, socketfile
);
926 /* Save name of lockfile for TouchSocketLockFile */
927 strcpy(socketLockFile
, lockfile
);
931 * TouchSocketLockFile -- mark socket lock file as recently accessed
933 * This routine should be called every so often to ensure that the lock file
934 * has a recent mod or access date. That saves it
935 * from being removed by overenthusiastic /tmp-directory-cleaner daemons.
936 * (Another reason we should never have put the socket file in /tmp...)
939 TouchSocketLockFile(void)
941 /* Do nothing if we did not create a socket... */
942 if (socketLockFile
[0] != '\0')
945 * utime() is POSIX standard, utimes() is a common alternative; if we
946 * have neither, fall back to actually reading the file (which only
947 * sets the access time not mod time, but that should be enough in
948 * most cases). In all paths, we ignore errors.
951 utime(socketLockFile
, NULL
);
952 #else /* !HAVE_UTIME */
954 utimes(socketLockFile
, NULL
);
955 #else /* !HAVE_UTIMES */
959 fd
= open(socketLockFile
, O_RDONLY
| PG_BINARY
, 0);
962 read(fd
, buffer
, sizeof(buffer
));
965 #endif /* HAVE_UTIMES */
966 #endif /* HAVE_UTIME */
971 * Append information about a shared memory segment to the data directory
974 * This may be called multiple times in the life of a postmaster, if we
975 * delete and recreate shmem due to backend crash. Therefore, be prepared
976 * to overwrite existing information. (As of 7.1, a postmaster only creates
977 * one shm seg at a time; but for the purposes here, if we did have more than
978 * one then any one of them would do anyway.)
981 RecordSharedMemoryInLockFile(unsigned long id1
, unsigned long id2
)
988 fd
= open(DIRECTORY_LOCK_FILE
, O_RDWR
| PG_BINARY
, 0);
992 (errcode_for_file_access(),
993 errmsg("could not open file \"%s\": %m",
994 DIRECTORY_LOCK_FILE
)));
997 len
= read(fd
, buffer
, sizeof(buffer
) - 100);
1001 (errcode_for_file_access(),
1002 errmsg("could not read from file \"%s\": %m",
1003 DIRECTORY_LOCK_FILE
)));
1010 * Skip over first two lines (PID and path).
1012 ptr
= strchr(buffer
, '\n');
1014 (ptr
= strchr(ptr
+ 1, '\n')) == NULL
)
1016 elog(LOG
, "bogus data in \"%s\"", DIRECTORY_LOCK_FILE
);
1023 * Append key information. Format to try to keep it the same length
1024 * always (trailing junk won't hurt, but might confuse humans).
1026 sprintf(ptr
, "%9lu %9lu\n", id1
, id2
);
1029 * And rewrite the data. Since we write in a single kernel call, this
1030 * update should appear atomic to onlookers.
1032 len
= strlen(buffer
);
1034 if (lseek(fd
, (off_t
) 0, SEEK_SET
) != 0 ||
1035 (int) write(fd
, buffer
, len
) != len
)
1037 /* if write didn't set errno, assume problem is no disk space */
1041 (errcode_for_file_access(),
1042 errmsg("could not write to file \"%s\": %m",
1043 DIRECTORY_LOCK_FILE
)));
1050 (errcode_for_file_access(),
1051 errmsg("could not write to file \"%s\": %m",
1052 DIRECTORY_LOCK_FILE
)));
1057 /*-------------------------------------------------------------------------
1058 * Version checking support
1059 *-------------------------------------------------------------------------
1063 * Determine whether the PG_VERSION file in directory `path' indicates
1064 * a data version compatible with the version of this program.
1066 * If compatible, return. Otherwise, ereport(FATAL).
1069 ValidatePgVersion(const char *path
)
1071 char full_path
[MAXPGPATH
];
1079 const char *version_string
= PG_VERSION
;
1081 my_major
= strtol(version_string
, &endptr
, 10);
1083 my_minor
= strtol(endptr
+ 1, NULL
, 10);
1085 snprintf(full_path
, sizeof(full_path
), "%s/PG_VERSION", path
);
1087 file
= AllocateFile(full_path
, "r");
1090 if (errno
== ENOENT
)
1092 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
1093 errmsg("\"%s\" is not a valid data directory",
1095 errdetail("File \"%s\" is missing.", full_path
)));
1098 (errcode_for_file_access(),
1099 errmsg("could not open file \"%s\": %m", full_path
)));
1102 ret
= fscanf(file
, "%ld.%ld", &file_major
, &file_minor
);
1105 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
1106 errmsg("\"%s\" is not a valid data directory",
1108 errdetail("File \"%s\" does not contain valid data.",
1110 errhint("You might need to initdb.")));
1114 if (my_major
!= file_major
|| my_minor
!= file_minor
)
1116 (errcode(ERRCODE_INVALID_PARAMETER_VALUE
),
1117 errmsg("database files are incompatible with server"),
1118 errdetail("The data directory was initialized by PostgreSQL version %ld.%ld, "
1119 "which is not compatible with this version %s.",
1120 file_major
, file_minor
, version_string
)));
1123 /*-------------------------------------------------------------------------
1124 * Library preload support
1125 *-------------------------------------------------------------------------
1129 * GUC variables: lists of library names to be preloaded at postmaster
1130 * start and at backend start
1132 char *shared_preload_libraries_string
= NULL
;
1133 char *local_preload_libraries_string
= NULL
;
1135 /* Flag telling that we are loading shared_preload_libraries */
1136 bool process_shared_preload_libraries_in_progress
= false;
1139 * load the shared libraries listed in 'libraries'
1141 * 'gucname': name of GUC variable, for error reports
1142 * 'restricted': if true, force libraries to be in $libdir/plugins/
1145 load_libraries(const char *libraries
, const char *gucname
, bool restricted
)
1152 if (libraries
== NULL
|| libraries
[0] == '\0')
1153 return; /* nothing to do */
1155 /* Need a modifiable copy of string */
1156 rawstring
= pstrdup(libraries
);
1158 /* Parse string into list of identifiers */
1159 if (!SplitIdentifierString(rawstring
, ',', &elemlist
))
1161 /* syntax error in list */
1163 list_free(elemlist
);
1165 (errcode(ERRCODE_SYNTAX_ERROR
),
1166 errmsg("invalid list syntax in parameter \"%s\"",
1172 * Choose notice level: avoid repeat messages when re-loading a library
1173 * that was preloaded into the postmaster. (Only possible in EXEC_BACKEND
1177 if (IsUnderPostmaster
&& process_shared_preload_libraries_in_progress
)
1183 foreach(l
, elemlist
)
1185 char *tok
= (char *) lfirst(l
);
1188 filename
= pstrdup(tok
);
1189 canonicalize_path(filename
);
1190 /* If restricting, insert $libdir/plugins if not mentioned already */
1191 if (restricted
&& first_dir_separator(filename
) == NULL
)
1195 expanded
= palloc(strlen("$libdir/plugins/") + strlen(filename
) + 1);
1196 strcpy(expanded
, "$libdir/plugins/");
1197 strcat(expanded
, filename
);
1199 filename
= expanded
;
1201 load_file(filename
, restricted
);
1203 (errmsg("loaded library \"%s\"", filename
)));
1208 list_free(elemlist
);
1212 * process any libraries that should be preloaded at postmaster start
1215 process_shared_preload_libraries(void)
1217 process_shared_preload_libraries_in_progress
= true;
1218 load_libraries(shared_preload_libraries_string
,
1219 "shared_preload_libraries",
1221 process_shared_preload_libraries_in_progress
= false;
1225 * process any libraries that should be preloaded at backend start
1228 process_local_preload_libraries(void)
1230 load_libraries(local_preload_libraries_string
,
1231 "local_preload_libraries",
1236 pg_bindtextdomain(const char *domain
)
1239 if (my_exec_path
[0] != '\0')
1241 char locale_path
[MAXPGPATH
];
1243 get_locale_path(my_exec_path
, locale_path
);
1244 bindtextdomain(domain
, locale_path
);
1245 pg_bind_textdomain_codeset(domain
);