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"]
16 from portage import os
17 from portage.const import PORTAGE_BIN_PATH
18 from portage.exception import DirectoryNotFound, FileNotFound, \
19 InvalidData, TryAgain, OperationNotPermitted, PermissionDenied
20 from portage.data import portage_gid
21 from portage.util import writemsg
22 from portage.localization import _
24 if sys.hexversion >= 0x3000000:
29 # Used by emerge in order to disable the "waiting for lock" message
30 # so that it doesn't interfere with the status display.
34 return lockfile(mydir,wantnewlockfile=1)
35 def unlockdir(mylock):
36 return unlockfile(mylock)
38 def lockfile(mypath, wantnewlockfile=0, unlinkfile=0,
39 waiting_msg=None, flags=0):
41 If wantnewlockfile is True then this creates a lockfile in the parent
42 directory as the file: '.' + basename + '.portage_lockfile'.
46 raise InvalidData(_("Empty path given"))
48 if isinstance(mypath, basestring) and mypath[-1] == '/':
51 if hasattr(mypath, 'fileno'):
52 mypath = mypath.fileno()
53 if isinstance(mypath, int):
58 base, tail = os.path.split(mypath)
59 lockfilename = os.path.join(base, "." + tail + ".portage_lockfile")
65 if isinstance(mypath, basestring):
66 if not os.path.exists(os.path.dirname(mypath)):
67 raise DirectoryNotFound(os.path.dirname(mypath))
68 preexisting = os.path.exists(lockfilename)
69 old_mask = os.umask(000)
72 myfd = os.open(lockfilename, os.O_CREAT|os.O_RDWR, 0o660)
74 func_call = "open('%s')" % lockfilename
75 if e.errno == OperationNotPermitted.errno:
76 raise OperationNotPermitted(func_call)
77 elif e.errno == PermissionDenied.errno:
78 raise PermissionDenied(func_call)
84 if os.stat(lockfilename).st_gid != portage_gid:
85 os.chown(lockfilename, -1, portage_gid)
87 if e.errno in (errno.ENOENT, errno.ESTALE):
88 return lockfile(mypath,
89 wantnewlockfile=wantnewlockfile,
90 unlinkfile=unlinkfile, waiting_msg=waiting_msg,
93 writemsg("%s: chown('%s', -1, %d)\n" % \
94 (e, lockfilename, portage_gid), noiselevel=-1)
95 writemsg(_("Cannot chown a lockfile: '%s'\n") % \
96 lockfilename, noiselevel=-1)
97 writemsg(_("Group IDs of current user: %s\n") % \
98 " ".join(str(n) for n in os.getgroups()),
103 elif isinstance(mypath, int):
107 raise ValueError(_("Unknown type passed in '%s': '%s'") % \
108 (type(mypath), mypath))
110 # try for a non-blocking lock, if it's held, throw a message
111 # we're waiting on lockfile and use a blocking attempt.
112 locking_method = fcntl.lockf
114 fcntl.lockf(myfd,fcntl.LOCK_EX|fcntl.LOCK_NB)
116 if "errno" not in dir(e):
118 if e.errno in (errno.EACCES, errno.EAGAIN):
119 # resource temp unavailable; eg, someone beat us to the lock.
120 if flags & os.O_NONBLOCK:
121 raise TryAgain(mypath)
127 out = portage.output.EOutput()
128 if waiting_msg is None:
129 if isinstance(mypath, int):
130 waiting_msg = _("waiting for lock on fd %i") % myfd
132 waiting_msg = _("waiting for lock on %s\n") % lockfilename
134 out.ebegin(waiting_msg)
135 # try for the exclusive lock now.
137 fcntl.lockf(myfd, fcntl.LOCK_EX)
138 except EnvironmentError as e:
144 elif e.errno == errno.ENOLCK:
145 # We're not allowed to lock on this FS.
148 if lockfilename == str(lockfilename):
151 if os.stat(lockfilename)[stat.ST_NLINK] == 1:
152 os.unlink(lockfilename)
155 link_success = hardlink_lockfile(lockfilename)
158 locking_method = None
164 if isinstance(lockfilename, basestring) and \
165 myfd != HARDLINK_FD and _fstat_nlink(myfd) == 0:
166 # The file was deleted on us... Keep trying to make one...
168 writemsg(_("lockfile recurse\n"), 1)
169 lockfilename, myfd, unlinkfile, locking_method = lockfile(
170 mypath, wantnewlockfile=wantnewlockfile, unlinkfile=unlinkfile,
171 waiting_msg=waiting_msg, flags=flags)
173 writemsg(str((lockfilename,myfd,unlinkfile))+"\n",1)
174 return (lockfilename,myfd,unlinkfile,locking_method)
176 def _fstat_nlink(fd):
178 @param fd: an open file descriptor
181 @return: the current number of hardlinks to the file
184 return os.fstat(fd).st_nlink
185 except EnvironmentError as e:
186 if e.errno in (errno.ENOENT, errno.ESTALE):
187 # Some filesystems such as CIFS return
188 # ENOENT which means st_nlink == 0.
192 def unlockfile(mytuple):
194 #XXX: Compatability hack.
195 if len(mytuple) == 3:
196 lockfilename,myfd,unlinkfile = mytuple
197 locking_method = fcntl.flock
198 elif len(mytuple) == 4:
199 lockfilename,myfd,unlinkfile,locking_method = mytuple
203 if(myfd == HARDLINK_FD):
204 unhardlink_lockfile(lockfilename)
207 # myfd may be None here due to myfd = mypath in lockfile()
208 if isinstance(lockfilename, basestring) and \
209 not os.path.exists(lockfilename):
210 writemsg(_("lockfile does not exist '%s'\n") % lockfilename,1)
217 myfd = os.open(lockfilename, os.O_WRONLY,0o660)
219 locking_method(myfd,fcntl.LOCK_UN)
221 if isinstance(lockfilename, basestring):
223 raise IOError(_("Failed to unlock file '%s'\n") % lockfilename)
226 # This sleep call was added to allow other processes that are
227 # waiting for a lock to be able to grab it before it is deleted.
228 # lockfile() already accounts for this situation, however, and
229 # the sleep here adds more time than is saved overall, so am
230 # commenting until it is proved necessary.
233 locking_method(myfd,fcntl.LOCK_EX|fcntl.LOCK_NB)
234 # We won the lock, so there isn't competition for it.
235 # We can safely delete the file.
236 writemsg(_("Got the lockfile...\n"), 1)
237 if _fstat_nlink(myfd) == 1:
238 os.unlink(lockfilename)
239 writemsg(_("Unlinked lockfile...\n"), 1)
240 locking_method(myfd,fcntl.LOCK_UN)
242 writemsg(_("lockfile does not exist '%s'\n") % lockfilename, 1)
247 except Exception as e:
248 writemsg(_("Failed to get lock... someone took it.\n"), 1)
249 writemsg(str(e)+"\n",1)
251 # why test lockfilename? because we may have been handed an
252 # fd originally, and the caller might not like having their
253 # open fd closed automatically on them.
254 if isinstance(lockfilename, basestring):
262 def hardlock_name(path):
263 return path+".hardlock-"+os.uname()[1]+"-"+str(os.getpid())
265 def hardlink_is_mine(link,lock):
267 return os.stat(link).st_nlink == 2
271 def hardlink_lockfile(lockfilename, max_wait=14400):
272 """Does the NFS, hardlink shuffle to ensure locking on the disk.
273 We create a PRIVATE lockfile, that is just a placeholder on the disk.
274 Then we HARDLINK the real lockfile to that private file.
275 If our file can 2 references, then we have the lock. :)
276 Otherwise we lather, rise, and repeat.
277 We default to a 4 hour timeout.
280 start_time = time.time()
281 myhardlock = hardlock_name(lockfilename)
282 reported_waiting = False
284 while(time.time() < (start_time + max_wait)):
285 # We only need it to exist.
286 myfd = os.open(myhardlock, os.O_CREAT|os.O_RDWR,0o660)
289 if not os.path.exists(myhardlock):
291 _("Created lockfile is missing: %(filename)s") % \
292 {"filename" : myhardlock})
295 res = os.link(myhardlock, lockfilename)
299 if hardlink_is_mine(myhardlock, lockfilename):
302 writemsg("\n", noiselevel=-1)
306 writemsg(".", noiselevel=-1)
308 reported_waiting = True
309 msg = _("\nWaiting on (hardlink) lockfile: (one '.' per 3 seconds)\n"
310 "%(bin_path)s/clean_locks can fix stuck locks.\n"
311 "Lockfile: %(lockfilename)s\n") % \
312 {"bin_path": PORTAGE_BIN_PATH, "lockfilename": lockfilename}
313 writemsg(msg, noiselevel=-1)
316 os.unlink(myhardlock)
319 def unhardlink_lockfile(lockfilename):
320 myhardlock = hardlock_name(lockfilename)
321 if hardlink_is_mine(myhardlock, lockfilename):
322 # Make sure not to touch lockfilename unless we really have a lock.
324 os.unlink(lockfilename)
328 os.unlink(myhardlock)
332 def hardlock_cleanup(path, remove_all_locks=False):
333 mypid = str(os.getpid())
334 myhost = os.uname()[1]
335 mydl = os.listdir(path)
342 if os.path.isfile(path+"/"+x):
343 parts = x.split(".hardlock-")
346 hostpid = parts[1].split("-")
347 host = "-".join(hostpid[:-1])
350 if filename not in mylist:
351 mylist[filename] = {}
352 if host not in mylist[filename]:
353 mylist[filename][host] = []
354 mylist[filename][host].append(pid)
359 results.append(_("Found %(count)s locks") % {"count":mycount})
362 if myhost in mylist[x] or remove_all_locks:
363 mylockname = hardlock_name(path+"/"+x)
364 if hardlink_is_mine(mylockname, path+"/"+x) or \
365 not os.path.exists(path+"/"+x) or \
368 for z in mylist[x][y]:
369 filename = path+"/"+x+".hardlock-"+y+"-"+z
370 if filename == mylockname:
373 # We're sweeping through, unlinking everyone's locks.
375 results.append(_("Unlinked: ") + filename)
379 os.unlink(path+"/"+x)
380 results.append(_("Unlinked: ") + path+"/"+x)
381 os.unlink(mylockname)
382 results.append(_("Unlinked: ") + mylockname)
387 os.unlink(mylockname)
388 results.append(_("Unlinked: ") + mylockname)