Add missing portage import in portage.locks.
[portage.git] / pym / portage / locks.py
1 # portage: Lock management code
2 # Copyright 2004-2010 Gentoo Foundation
3 # Distributed under the terms of the GNU General Public License v2
4
5 __all__ = ["lockdir", "unlockdir", "lockfile", "unlockfile", \
6         "hardlock_name", "hardlink_is_mine", "hardlink_lockfile", \
7         "unhardlink_lockfile", "hardlock_cleanup"]
8
9 import errno
10 import fcntl
11 import stat
12 import sys
13 import time
14
15 import portage
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 _
23
24 if sys.hexversion >= 0x3000000:
25         basestring = str
26
27 HARDLINK_FD = -2
28
29 # Used by emerge in order to disable the "waiting for lock" message
30 # so that it doesn't interfere with the status display.
31 _quiet = False
32
33 def lockdir(mydir):
34         return lockfile(mydir,wantnewlockfile=1)
35 def unlockdir(mylock):
36         return unlockfile(mylock)
37
38 def lockfile(mypath, wantnewlockfile=0, unlinkfile=0,
39         waiting_msg=None, flags=0):
40         """
41         If wantnewlockfile is True then this creates a lockfile in the parent
42         directory as the file: '.' + basename + '.portage_lockfile'.
43         """
44
45         if not mypath:
46                 raise InvalidData(_("Empty path given"))
47
48         if isinstance(mypath, basestring) and mypath[-1] == '/':
49                 mypath = mypath[:-1]
50
51         if hasattr(mypath, 'fileno'):
52                 mypath = mypath.fileno()
53         if isinstance(mypath, int):
54                 lockfilename    = mypath
55                 wantnewlockfile = 0
56                 unlinkfile      = 0
57         elif wantnewlockfile:
58                 base, tail = os.path.split(mypath)
59                 lockfilename = os.path.join(base, "." + tail + ".portage_lockfile")
60                 del base, tail
61                 unlinkfile   = 1
62         else:
63                 lockfilename = mypath
64
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)
70                 try:
71                         try:
72                                 myfd = os.open(lockfilename, os.O_CREAT|os.O_RDWR, 0o660)
73                         except OSError as e:
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)
79                                 else:
80                                         raise
81
82                         if not preexisting:
83                                 try:
84                                         if os.stat(lockfilename).st_gid != portage_gid:
85                                                 os.chown(lockfilename, -1, portage_gid)
86                                 except OSError as e:
87                                         if e.errno in (errno.ENOENT, errno.ESTALE):
88                                                 return lockfile(mypath,
89                                                         wantnewlockfile=wantnewlockfile,
90                                                         unlinkfile=unlinkfile, waiting_msg=waiting_msg,
91                                                         flags=flags)
92                                         else:
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()),
99                                                         noiselevel=-1)
100                 finally:
101                         os.umask(old_mask)
102
103         elif isinstance(mypath, int):
104                 myfd = mypath
105
106         else:
107                 raise ValueError(_("Unknown type passed in '%s': '%s'") % \
108                         (type(mypath), mypath))
109
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
113         try:
114                 fcntl.lockf(myfd,fcntl.LOCK_EX|fcntl.LOCK_NB)
115         except IOError as e:
116                 if "errno" not in dir(e):
117                         raise
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)
122
123                         global _quiet
124                         if _quiet:
125                                 out = None
126                         else:
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
131                                 else:
132                                         waiting_msg = _("waiting for lock on %s\n") % lockfilename
133                         if out is not None:
134                                 out.ebegin(waiting_msg)
135                         # try for the exclusive lock now.
136                         try:
137                                 fcntl.lockf(myfd, fcntl.LOCK_EX)
138                         except EnvironmentError as e:
139                                 if out is not None:
140                                         out.eend(1, str(e))
141                                 raise
142                         if out is not None:
143                                 out.eend(os.EX_OK)
144                 elif e.errno == errno.ENOLCK:
145                         # We're not allowed to lock on this FS.
146                         os.close(myfd)
147                         link_success = False
148                         if lockfilename == str(lockfilename):
149                                 if wantnewlockfile:
150                                         try:
151                                                 if os.stat(lockfilename)[stat.ST_NLINK] == 1:
152                                                         os.unlink(lockfilename)
153                                         except OSError:
154                                                 pass
155                                         link_success = hardlink_lockfile(lockfilename)
156                         if not link_success:
157                                 raise
158                         locking_method = None
159                         myfd = HARDLINK_FD
160                 else:
161                         raise
162
163                 
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...
167                 os.close(myfd)
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)
172
173         writemsg(str((lockfilename,myfd,unlinkfile))+"\n",1)
174         return (lockfilename,myfd,unlinkfile,locking_method)
175
176 def _fstat_nlink(fd):
177         """
178         @param fd: an open file descriptor
179         @type fd: Integer
180         @rtype: Integer
181         @return: the current number of hardlinks to the file
182         """
183         try:
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.
189                         return 0
190                 raise
191
192 def unlockfile(mytuple):
193
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
200         else:
201                 raise InvalidData
202
203         if(myfd == HARDLINK_FD):
204                 unhardlink_lockfile(lockfilename)
205                 return True
206         
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)
211                 if myfd is not None:
212                         os.close(myfd)
213                 return False
214
215         try:
216                 if myfd is None:
217                         myfd = os.open(lockfilename, os.O_WRONLY,0o660)
218                         unlinkfile = 1
219                 locking_method(myfd,fcntl.LOCK_UN)
220         except OSError:
221                 if isinstance(lockfilename, basestring):
222                         os.close(myfd)
223                 raise IOError(_("Failed to unlock file '%s'\n") % lockfilename)
224
225         try:
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.
231                 #time.sleep(0.0001)
232                 if unlinkfile:
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)
241                         else:
242                                 writemsg(_("lockfile does not exist '%s'\n") % lockfilename, 1)
243                                 os.close(myfd)
244                                 return False
245         except SystemExit:
246                 raise
247         except Exception as e:
248                 writemsg(_("Failed to get lock... someone took it.\n"), 1)
249                 writemsg(str(e)+"\n",1)
250
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):
255                 os.close(myfd)
256
257         return True
258
259
260
261
262 def hardlock_name(path):
263         return path+".hardlock-"+os.uname()[1]+"-"+str(os.getpid())
264
265 def hardlink_is_mine(link,lock):
266         try:
267                 return os.stat(link).st_nlink == 2
268         except OSError:
269                 return False
270
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.
278         """
279
280         start_time = time.time()
281         myhardlock = hardlock_name(lockfilename)
282         reported_waiting = False
283         
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)
287                 os.close(myfd)
288         
289                 if not os.path.exists(myhardlock):
290                         raise FileNotFound(
291                                 _("Created lockfile is missing: %(filename)s") % \
292                                 {"filename" : myhardlock})
293
294                 try:
295                         res = os.link(myhardlock, lockfilename)
296                 except OSError:
297                         pass
298
299                 if hardlink_is_mine(myhardlock, lockfilename):
300                         # We have the lock.
301                         if reported_waiting:
302                                 writemsg("\n", noiselevel=-1)
303                         return True
304
305                 if reported_waiting:
306                         writemsg(".", noiselevel=-1)
307                 else:
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)
314                 time.sleep(3)
315         
316         os.unlink(myhardlock)
317         return False
318
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.
323                 try:
324                         os.unlink(lockfilename)
325                 except OSError:
326                         pass
327         try:
328                 os.unlink(myhardlock)
329         except OSError:
330                 pass
331
332 def hardlock_cleanup(path, remove_all_locks=False):
333         mypid  = str(os.getpid())
334         myhost = os.uname()[1]
335         mydl = os.listdir(path)
336
337         results = []
338         mycount = 0
339
340         mylist = {}
341         for x in mydl:
342                 if os.path.isfile(path+"/"+x):
343                         parts = x.split(".hardlock-")
344                         if len(parts) == 2:
345                                 filename = parts[0]
346                                 hostpid  = parts[1].split("-")
347                                 host  = "-".join(hostpid[:-1])
348                                 pid   = hostpid[-1]
349                                 
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)
355
356                                 mycount += 1
357
358
359         results.append(_("Found %(count)s locks") % {"count":mycount})
360         
361         for x in mylist:
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 \
366                                  remove_all_locks:
367                                 for y in mylist[x]:
368                                         for z in mylist[x][y]:
369                                                 filename = path+"/"+x+".hardlock-"+y+"-"+z
370                                                 if filename == mylockname:
371                                                         continue
372                                                 try:
373                                                         # We're sweeping through, unlinking everyone's locks.
374                                                         os.unlink(filename)
375                                                         results.append(_("Unlinked: ") + filename)
376                                                 except OSError:
377                                                         pass
378                                 try:
379                                         os.unlink(path+"/"+x)
380                                         results.append(_("Unlinked: ") + path+"/"+x)
381                                         os.unlink(mylockname)
382                                         results.append(_("Unlinked: ") + mylockname)
383                                 except OSError:
384                                         pass
385                         else:
386                                 try:
387                                         os.unlink(mylockname)
388                                         results.append(_("Unlinked: ") + mylockname)
389                                 except OSError:
390                                         pass
391
392         return results
393