1 # portage: Lock management code
2 # Copyright 2004 Gentoo Foundation
3 # Distributed under the terms of the GNU General Public License v2
7 import errno, os, stat, time, types
8 from portage.exception import InvalidData, DirectoryNotFound, FileNotFound
9 from portage.data import portage_gid
10 from portage.util import writemsg
11 from portage.localization import _
16 return lockfile(mydir,wantnewlockfile=1)
17 def unlockdir(mylock):
18 return unlockfile(mylock)
20 def lockfile(mypath, wantnewlockfile=0, unlinkfile=0, waiting_msg=None):
21 """Creates all dirs upto, the given dir. Creates a lockfile
22 for the given directory as the file: directoryname+'.portage_lockfile'."""
26 raise InvalidData("Empty path given")
28 if type(mypath) == types.StringType and mypath[-1] == '/':
31 if type(mypath) == types.FileType:
32 mypath = mypath.fileno()
33 if type(mypath) == types.IntType:
38 base, tail = os.path.split(mypath)
39 lockfilename = os.path.join(base, "." + tail + ".portage_lockfile")
45 if type(mypath) == types.StringType:
46 if not os.path.exists(os.path.dirname(mypath)):
47 raise DirectoryNotFound(os.path.dirname(mypath))
48 if not os.path.exists(lockfilename):
49 old_mask=os.umask(000)
50 myfd = os.open(lockfilename, os.O_CREAT|os.O_RDWR,0660)
52 if os.stat(lockfilename).st_gid != portage_gid:
53 os.chown(lockfilename,os.getuid(),portage_gid)
55 if e[0] == 2: # No such file or directory
56 return lockfile(mypath, wantnewlockfile=wantnewlockfile,
57 unlinkfile=unlinkfile, waiting_msg=waiting_msg)
59 writemsg("Cannot chown a lockfile. This could cause inconvenience later.\n");
62 myfd = os.open(lockfilename, os.O_CREAT|os.O_RDWR,0660)
64 elif type(mypath) == types.IntType:
68 raise ValueError("Unknown type passed in '%s': '%s'" % \
69 (type(mypath), mypath))
71 # try for a non-blocking lock, if it's held, throw a message
72 # we're waiting on lockfile and use a blocking attempt.
73 locking_method = fcntl.lockf
75 fcntl.lockf(myfd,fcntl.LOCK_EX|fcntl.LOCK_NB)
77 if "errno" not in dir(e):
79 if e.errno in (errno.EACCES, errno.EAGAIN):
80 # resource temp unavailable; eg, someone beat us to the lock.
81 if waiting_msg is None:
82 if isinstance(mypath, int):
83 print "waiting for lock on fd %i" % myfd
85 print "waiting for lock on %s" % lockfilename
88 # try for the exclusive lock now.
89 fcntl.lockf(myfd,fcntl.LOCK_EX)
90 elif e.errno == errno.ENOLCK:
91 # We're not allowed to lock on this FS.
94 if lockfilename == str(lockfilename):
97 if os.stat(lockfilename)[stat.ST_NLINK] == 1:
98 os.unlink(lockfilename)
101 link_success = hardlink_lockfile(lockfilename)
104 locking_method = None
110 if type(lockfilename) == types.StringType and \
111 myfd != HARDLINK_FD and _fstat_nlink(myfd) == 0:
112 # The file was deleted on us... Keep trying to make one...
114 writemsg("lockfile recurse\n",1)
115 lockfilename, myfd, unlinkfile, locking_method = lockfile(
116 mypath, wantnewlockfile=wantnewlockfile, unlinkfile=unlinkfile,
117 waiting_msg=waiting_msg)
119 writemsg(str((lockfilename,myfd,unlinkfile))+"\n",1)
120 return (lockfilename,myfd,unlinkfile,locking_method)
122 def _fstat_nlink(fd):
124 @param fd: an open file descriptor
127 @return: the current number of hardlinks to the file
130 return os.fstat(fd).st_nlink
131 except EnvironmentError, e:
132 if e.errno == errno.ENOENT:
133 # Some filesystems such as CIFS return
134 # ENOENT which means st_nlink == 0.
138 def unlockfile(mytuple):
141 #XXX: Compatability hack.
142 if len(mytuple) == 3:
143 lockfilename,myfd,unlinkfile = mytuple
144 locking_method = fcntl.flock
145 elif len(mytuple) == 4:
146 lockfilename,myfd,unlinkfile,locking_method = mytuple
150 if(myfd == HARDLINK_FD):
151 unhardlink_lockfile(lockfilename)
154 # myfd may be None here due to myfd = mypath in lockfile()
155 if type(lockfilename) == types.StringType and not os.path.exists(lockfilename):
156 writemsg("lockfile does not exist '%s'\n" % lockfilename,1)
163 myfd = os.open(lockfilename, os.O_WRONLY,0660)
165 locking_method(myfd,fcntl.LOCK_UN)
167 if type(lockfilename) == types.StringType:
169 raise IOError("Failed to unlock file '%s'\n" % lockfilename)
172 # This sleep call was added to allow other processes that are
173 # waiting for a lock to be able to grab it before it is deleted.
174 # lockfile() already accounts for this situation, however, and
175 # the sleep here adds more time than is saved overall, so am
176 # commenting until it is proved necessary.
179 locking_method(myfd,fcntl.LOCK_EX|fcntl.LOCK_NB)
180 # We won the lock, so there isn't competition for it.
181 # We can safely delete the file.
182 writemsg("Got the lockfile...\n",1)
183 if _fstat_nlink(myfd) == 1:
184 os.unlink(lockfilename)
185 writemsg("Unlinked lockfile...\n",1)
186 locking_method(myfd,fcntl.LOCK_UN)
188 writemsg("lockfile does not exist '%s'\n" % lockfilename,1)
192 writemsg("Failed to get lock... someone took it.\n",1)
193 writemsg(str(e)+"\n",1)
195 # why test lockfilename? because we may have been handed an
196 # fd originally, and the caller might not like having their
197 # open fd closed automatically on them.
198 if type(lockfilename) == types.StringType:
206 def hardlock_name(path):
207 return path+".hardlock-"+os.uname()[1]+"-"+str(os.getpid())
209 def hardlink_is_mine(link,lock):
211 return os.stat(link).st_nlink == 2
215 def hardlink_lockfile(lockfilename, max_wait=14400):
216 """Does the NFS, hardlink shuffle to ensure locking on the disk.
217 We create a PRIVATE lockfile, that is just a placeholder on the disk.
218 Then we HARDLINK the real lockfile to that private file.
219 If our file can 2 references, then we have the lock. :)
220 Otherwise we lather, rise, and repeat.
221 We default to a 4 hour timeout.
224 start_time = time.time()
225 myhardlock = hardlock_name(lockfilename)
226 reported_waiting = False
228 while(time.time() < (start_time + max_wait)):
229 # We only need it to exist.
230 myfd = os.open(myhardlock, os.O_CREAT|os.O_RDWR,0660)
233 if not os.path.exists(myhardlock):
235 _("Created lockfile is missing: %(filename)s") % \
236 {"filename" : myhardlock})
239 res = os.link(myhardlock, lockfilename)
243 if hardlink_is_mine(myhardlock, lockfilename):
252 reported_waiting = True
253 from portage.const import PORTAGE_BIN_PATH
255 print "Waiting on (hardlink) lockfile: (one '.' per 3 seconds)"
256 print "This is a feature to prevent distfiles corruption."
257 print "%s/clean_locks can fix stuck locks." % PORTAGE_BIN_PATH
258 print "Lockfile: " + lockfilename
261 os.unlink(myhardlock)
264 def unhardlink_lockfile(lockfilename):
265 myhardlock = hardlock_name(lockfilename)
266 if hardlink_is_mine(myhardlock, lockfilename):
267 # Make sure not to touch lockfilename unless we really have a lock.
269 os.unlink(lockfilename)
273 os.unlink(myhardlock)
277 def hardlock_cleanup(path, remove_all_locks=False):
278 mypid = str(os.getpid())
279 myhost = os.uname()[1]
280 mydl = os.listdir(path)
287 if os.path.isfile(path+"/"+x):
288 parts = x.split(".hardlock-")
291 hostpid = parts[1].split("-")
292 host = "-".join(hostpid[:-1])
295 if filename not in mylist:
296 mylist[filename] = {}
297 if host not in mylist[filename]:
298 mylist[filename][host] = []
299 mylist[filename][host].append(pid)
304 results.append("Found %(count)s locks" % {"count":mycount})
307 if myhost in mylist[x] or remove_all_locks:
308 mylockname = hardlock_name(path+"/"+x)
309 if hardlink_is_mine(mylockname, path+"/"+x) or \
310 not os.path.exists(path+"/"+x) or \
313 for z in mylist[x][y]:
314 filename = path+"/"+x+".hardlock-"+y+"-"+z
315 if filename == mylockname:
318 # We're sweeping through, unlinking everyone's locks.
320 results.append(_("Unlinked: ") + filename)
324 os.unlink(path+"/"+x)
325 results.append(_("Unlinked: ") + path+"/"+x)
326 os.unlink(mylockname)
327 results.append(_("Unlinked: ") + mylockname)
332 os.unlink(mylockname)
333 results.append(_("Unlinked: ") + mylockname)