1 # portage: Lock management code
2 # Copyright 2004-2010 Gentoo Foundation
3 # Distributed under the terms of the GNU General Public License v2
5 __all__ = ["lockdir", "unlockdir", "lockfile", "unlockfile", \
6 "hardlock_name", "hardlink_is_mine", "hardlink_lockfile", \
7 "unhardlink_lockfile", "hardlock_cleanup"]
15 from portage import os
16 from portage.const import PORTAGE_BIN_PATH
17 from portage.exception import DirectoryNotFound, FileNotFound, \
18 InvalidData, TryAgain, OperationNotPermitted, PermissionDenied
19 from portage.data import portage_gid
20 from portage.util import writemsg
21 from portage.localization import _
23 if sys.hexversion >= 0x3000000:
28 # Used by emerge in order to disable the "waiting for lock" message
29 # so that it doesn't interfere with the status display.
33 return lockfile(mydir,wantnewlockfile=1)
34 def unlockdir(mylock):
35 return unlockfile(mylock)
37 def lockfile(mypath, wantnewlockfile=0, unlinkfile=0,
38 waiting_msg=None, flags=0):
40 If wantnewlockfile is True then this creates a lockfile in the parent
41 directory as the file: '.' + basename + '.portage_lockfile'.
45 raise InvalidData(_("Empty path given"))
47 if isinstance(mypath, basestring) and mypath[-1] == '/':
50 if hasattr(mypath, 'fileno'):
51 mypath = mypath.fileno()
52 if isinstance(mypath, int):
57 base, tail = os.path.split(mypath)
58 lockfilename = os.path.join(base, "." + tail + ".portage_lockfile")
64 if isinstance(mypath, basestring):
65 if not os.path.exists(os.path.dirname(mypath)):
66 raise DirectoryNotFound(os.path.dirname(mypath))
67 preexisting = os.path.exists(lockfilename)
68 old_mask = os.umask(000)
71 myfd = os.open(lockfilename, os.O_CREAT|os.O_RDWR, 0o660)
73 func_call = "open('%s')" % lockfilename
74 if e.errno == OperationNotPermitted.errno:
75 raise OperationNotPermitted(func_call)
76 elif e.errno == PermissionDenied.errno:
77 raise PermissionDenied(func_call)
83 if os.stat(lockfilename).st_gid != portage_gid:
84 os.chown(lockfilename, -1, portage_gid)
86 if e.errno in (errno.ENOENT, errno.ESTALE):
87 return lockfile(mypath,
88 wantnewlockfile=wantnewlockfile,
89 unlinkfile=unlinkfile, waiting_msg=waiting_msg,
92 writemsg("%s: chown('%s', -1, %d)\n" % \
93 (e, lockfilename, portage_gid), noiselevel=-1)
94 writemsg(_("Cannot chown a lockfile: '%s'\n") % \
95 lockfilename, noiselevel=-1)
96 writemsg(_("Group IDs of current user: %s\n") % \
97 " ".join(str(n) for n in os.getgroups()),
102 elif isinstance(mypath, int):
106 raise ValueError(_("Unknown type passed in '%s': '%s'") % \
107 (type(mypath), mypath))
109 # try for a non-blocking lock, if it's held, throw a message
110 # we're waiting on lockfile and use a blocking attempt.
111 locking_method = fcntl.lockf
113 fcntl.lockf(myfd,fcntl.LOCK_EX|fcntl.LOCK_NB)
115 if "errno" not in dir(e):
117 if e.errno in (errno.EACCES, errno.EAGAIN):
118 # resource temp unavailable; eg, someone beat us to the lock.
119 if flags & os.O_NONBLOCK:
120 raise TryAgain(mypath)
126 out = portage.output.EOutput()
127 if waiting_msg is None:
128 if isinstance(mypath, int):
129 waiting_msg = _("waiting for lock on fd %i") % myfd
131 waiting_msg = _("waiting for lock on %s\n") % lockfilename
133 out.ebegin(waiting_msg)
134 # try for the exclusive lock now.
136 fcntl.lockf(myfd, fcntl.LOCK_EX)
137 except EnvironmentError as e:
143 elif e.errno == errno.ENOLCK:
144 # We're not allowed to lock on this FS.
147 if lockfilename == str(lockfilename):
150 if os.stat(lockfilename)[stat.ST_NLINK] == 1:
151 os.unlink(lockfilename)
154 link_success = hardlink_lockfile(lockfilename)
157 locking_method = None
163 if isinstance(lockfilename, basestring) and \
164 myfd != HARDLINK_FD and _fstat_nlink(myfd) == 0:
165 # The file was deleted on us... Keep trying to make one...
167 writemsg(_("lockfile recurse\n"), 1)
168 lockfilename, myfd, unlinkfile, locking_method = lockfile(
169 mypath, wantnewlockfile=wantnewlockfile, unlinkfile=unlinkfile,
170 waiting_msg=waiting_msg, flags=flags)
172 writemsg(str((lockfilename,myfd,unlinkfile))+"\n",1)
173 return (lockfilename,myfd,unlinkfile,locking_method)
175 def _fstat_nlink(fd):
177 @param fd: an open file descriptor
180 @return: the current number of hardlinks to the file
183 return os.fstat(fd).st_nlink
184 except EnvironmentError as e:
185 if e.errno in (errno.ENOENT, errno.ESTALE):
186 # Some filesystems such as CIFS return
187 # ENOENT which means st_nlink == 0.
191 def unlockfile(mytuple):
193 #XXX: Compatability hack.
194 if len(mytuple) == 3:
195 lockfilename,myfd,unlinkfile = mytuple
196 locking_method = fcntl.flock
197 elif len(mytuple) == 4:
198 lockfilename,myfd,unlinkfile,locking_method = mytuple
202 if(myfd == HARDLINK_FD):
203 unhardlink_lockfile(lockfilename)
206 # myfd may be None here due to myfd = mypath in lockfile()
207 if isinstance(lockfilename, basestring) and \
208 not os.path.exists(lockfilename):
209 writemsg(_("lockfile does not exist '%s'\n") % lockfilename,1)
216 myfd = os.open(lockfilename, os.O_WRONLY,0o660)
218 locking_method(myfd,fcntl.LOCK_UN)
220 if isinstance(lockfilename, basestring):
222 raise IOError(_("Failed to unlock file '%s'\n") % lockfilename)
225 # This sleep call was added to allow other processes that are
226 # waiting for a lock to be able to grab it before it is deleted.
227 # lockfile() already accounts for this situation, however, and
228 # the sleep here adds more time than is saved overall, so am
229 # commenting until it is proved necessary.
232 locking_method(myfd,fcntl.LOCK_EX|fcntl.LOCK_NB)
233 # We won the lock, so there isn't competition for it.
234 # We can safely delete the file.
235 writemsg(_("Got the lockfile...\n"), 1)
236 if _fstat_nlink(myfd) == 1:
237 os.unlink(lockfilename)
238 writemsg(_("Unlinked lockfile...\n"), 1)
239 locking_method(myfd,fcntl.LOCK_UN)
241 writemsg(_("lockfile does not exist '%s'\n") % lockfilename, 1)
246 except Exception as e:
247 writemsg(_("Failed to get lock... someone took it.\n"), 1)
248 writemsg(str(e)+"\n",1)
250 # why test lockfilename? because we may have been handed an
251 # fd originally, and the caller might not like having their
252 # open fd closed automatically on them.
253 if isinstance(lockfilename, basestring):
261 def hardlock_name(path):
262 return path+".hardlock-"+os.uname()[1]+"-"+str(os.getpid())
264 def hardlink_is_mine(link,lock):
266 return os.stat(link).st_nlink == 2
270 def hardlink_lockfile(lockfilename, max_wait=14400):
271 """Does the NFS, hardlink shuffle to ensure locking on the disk.
272 We create a PRIVATE lockfile, that is just a placeholder on the disk.
273 Then we HARDLINK the real lockfile to that private file.
274 If our file can 2 references, then we have the lock. :)
275 Otherwise we lather, rise, and repeat.
276 We default to a 4 hour timeout.
279 start_time = time.time()
280 myhardlock = hardlock_name(lockfilename)
281 reported_waiting = False
283 while(time.time() < (start_time + max_wait)):
284 # We only need it to exist.
285 myfd = os.open(myhardlock, os.O_CREAT|os.O_RDWR,0o660)
288 if not os.path.exists(myhardlock):
290 _("Created lockfile is missing: %(filename)s") % \
291 {"filename" : myhardlock})
294 res = os.link(myhardlock, lockfilename)
298 if hardlink_is_mine(myhardlock, lockfilename):
301 writemsg("\n", noiselevel=-1)
305 writemsg(".", noiselevel=-1)
307 reported_waiting = True
308 msg = _("\nWaiting on (hardlink) lockfile: (one '.' per 3 seconds)\n"
309 "%(bin_path)s/clean_locks can fix stuck locks.\n"
310 "Lockfile: %(lockfilename)s\n") % \
311 {"bin_path": PORTAGE_BIN_PATH, "lockfilename": lockfilename}
312 writemsg(msg, noiselevel=-1)
315 os.unlink(myhardlock)
318 def unhardlink_lockfile(lockfilename):
319 myhardlock = hardlock_name(lockfilename)
320 if hardlink_is_mine(myhardlock, lockfilename):
321 # Make sure not to touch lockfilename unless we really have a lock.
323 os.unlink(lockfilename)
327 os.unlink(myhardlock)
331 def hardlock_cleanup(path, remove_all_locks=False):
332 mypid = str(os.getpid())
333 myhost = os.uname()[1]
334 mydl = os.listdir(path)
341 if os.path.isfile(path+"/"+x):
342 parts = x.split(".hardlock-")
345 hostpid = parts[1].split("-")
346 host = "-".join(hostpid[:-1])
349 if filename not in mylist:
350 mylist[filename] = {}
351 if host not in mylist[filename]:
352 mylist[filename][host] = []
353 mylist[filename][host].append(pid)
358 results.append(_("Found %(count)s locks") % {"count":mycount})
361 if myhost in mylist[x] or remove_all_locks:
362 mylockname = hardlock_name(path+"/"+x)
363 if hardlink_is_mine(mylockname, path+"/"+x) or \
364 not os.path.exists(path+"/"+x) or \
367 for z in mylist[x][y]:
368 filename = path+"/"+x+".hardlock-"+y+"-"+z
369 if filename == mylockname:
372 # We're sweeping through, unlinking everyone's locks.
374 results.append(_("Unlinked: ") + filename)
378 os.unlink(path+"/"+x)
379 results.append(_("Unlinked: ") + path+"/"+x)
380 os.unlink(mylockname)
381 results.append(_("Unlinked: ") + mylockname)
386 os.unlink(mylockname)
387 results.append(_("Unlinked: ") + mylockname)