/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/lockdir.py

  • Committer: John Arbash Meinel
  • Date: 2006-10-06 05:53:44 UTC
  • mfrom: (2063 +trunk)
  • mto: This revision was merged to the branch mainline in revision 2071.
  • Revision ID: john@arbash-meinel.com-20061006055344-e73b97b7c6ca6e72
[merge] bzr.dev 2063

Show diffs side-by-side

added added

removed removed

Lines of Context:
96
96
 
97
97
import os
98
98
import time
99
 
from StringIO import StringIO
 
99
from cStringIO import StringIO
100
100
 
 
101
from bzrlib import (
 
102
    errors,
 
103
    )
101
104
import bzrlib.config
102
105
from bzrlib.errors import (
103
106
        DirectoryNotEmpty,
111
114
        ResourceBusy,
112
115
        UnlockableTransport,
113
116
        )
114
 
from bzrlib.trace import mutter
 
117
from bzrlib.trace import mutter, note
115
118
from bzrlib.transport import Transport
116
 
from bzrlib.osutils import rand_chars
117
 
from bzrlib.rio import RioWriter, read_stanza, Stanza
 
119
from bzrlib.osutils import rand_chars, format_delta
 
120
from bzrlib.rio import read_stanza, Stanza
 
121
 
118
122
 
119
123
# XXX: At the moment there is no consideration of thread safety on LockDir
120
124
# objects.  This should perhaps be updated - e.g. if two threads try to take a
130
134
# TODO: Make sure to pass the right file and directory mode bits to all
131
135
# files/dirs created.
132
136
 
 
137
 
133
138
_DEFAULT_TIMEOUT_SECONDS = 300
134
 
_DEFAULT_POLL_SECONDS = 0.5
 
139
_DEFAULT_POLL_SECONDS = 1.0
 
140
 
135
141
 
136
142
class LockDir(object):
137
143
    """Write-lock guarding access to data."""
160
166
        self._dir_modebits = dir_modebits
161
167
        self.nonce = rand_chars(20)
162
168
 
 
169
        self._report_function = note
 
170
 
163
171
    def __repr__(self):
164
172
        return '%s(%s%s)' % (self.__class__.__name__,
165
173
                             self.transport.base,
200
208
                # After creating the lock directory, try again
201
209
                self.transport.mkdir(tmpname)
202
210
 
203
 
            sio = StringIO()
204
 
            self._prepare_info(sio)
205
 
            sio.seek(0)
206
 
            # append will create a new file; we use append rather than put
207
 
            # because we don't want to write to a temporary file and rename
208
 
            # into place, because that's going to happen to the whole
209
 
            # directory
210
 
            self.transport.append_file(tmpname + self.__INFO_NAME, sio)
 
211
            info_bytes = self._prepare_info()
 
212
            # We use put_file_non_atomic because we just created a new unique
 
213
            # directory so we don't have to worry about files existing there.
 
214
            # We'll rename the whole directory into place to get atomic
 
215
            # properties
 
216
            self.transport.put_bytes_non_atomic(tmpname + self.__INFO_NAME,
 
217
                                                info_bytes)
211
218
 
212
219
            self.transport.rename(tmpname, self._held_dir)
213
220
            self._lock_held = True
244
251
        self._check_not_locked()
245
252
        holder_info = self.peek()
246
253
        if holder_info is not None:
247
 
            if bzrlib.ui.ui_factory.get_boolean(
248
 
                "Break lock %s held by %s@%s [process #%s]" % (
249
 
                    self.transport,
250
 
                    holder_info["user"],
251
 
                    holder_info["hostname"],
252
 
                    holder_info["pid"])):
 
254
            lock_info = '\n'.join(self._format_lock_info(holder_info))
 
255
            if bzrlib.ui.ui_factory.get_boolean("Break %s" % lock_info):
253
256
                self.force_break(holder_info)
254
257
        
255
258
    def force_break(self, dead_holder_info):
336
339
        except NoSuchFile, e:
337
340
            return None
338
341
 
339
 
    def _prepare_info(self, outf):
 
342
    def _prepare_info(self):
340
343
        """Write information about a pending lock to a temporary file.
341
344
        """
342
345
        import socket
343
346
        # XXX: is creating this here inefficient?
344
347
        config = bzrlib.config.GlobalConfig()
 
348
        try:
 
349
            user = config.user_email()
 
350
        except errors.NoEmailInUsername:
 
351
            user = config.username()
345
352
        s = Stanza(hostname=socket.gethostname(),
346
353
                   pid=str(os.getpid()),
347
354
                   start_time=str(int(time.time())),
348
355
                   nonce=self.nonce,
349
 
                   user=config.user_email(),
 
356
                   user=user,
350
357
                   )
351
 
        RioWriter(outf).write_stanza(s)
 
358
        return s.to_string()
352
359
 
353
360
    def _parse_info(self, info_file):
354
361
        return read_stanza(info_file.readlines()).as_dict()
355
362
 
356
 
    def wait_lock(self, timeout=_DEFAULT_TIMEOUT_SECONDS,
357
 
                  poll=_DEFAULT_POLL_SECONDS):
 
363
    def wait_lock(self, timeout=None, poll=None):
358
364
        """Wait a certain period for a lock.
359
365
 
360
366
        If the lock can be acquired within the bounded time, it
363
369
        approximately `timeout` seconds.  (It may be a bit more if
364
370
        a transport operation takes a long time to complete.)
365
371
        """
 
372
        if timeout is None:
 
373
            timeout = _DEFAULT_TIMEOUT_SECONDS
 
374
        if poll is None:
 
375
            poll = _DEFAULT_POLL_SECONDS
 
376
 
366
377
        # XXX: the transport interface doesn't let us guard 
367
378
        # against operations there taking a long time.
368
379
        deadline = time.time() + timeout
 
380
        deadline_str = None
 
381
        last_info = None
369
382
        while True:
370
383
            try:
371
384
                self.attempt_lock()
372
385
                return
373
386
            except LockContention:
374
387
                pass
 
388
            new_info = self.peek()
 
389
            mutter('last_info: %s, new info: %s', last_info, new_info)
 
390
            if new_info is not None and new_info != last_info:
 
391
                if last_info is None:
 
392
                    start = 'Unable to obtain'
 
393
                else:
 
394
                    start = 'Lock owner changed for'
 
395
                last_info = new_info
 
396
                formatted_info = self._format_lock_info(new_info)
 
397
                if deadline_str is None:
 
398
                    deadline_str = time.strftime('%H:%M:%S',
 
399
                                                 time.localtime(deadline))
 
400
                self._report_function('%s %s\n'
 
401
                                      '%s\n' # held by
 
402
                                      '%s\n' # locked ... ago
 
403
                                      'Will continue to try until %s\n',
 
404
                                      start,
 
405
                                      formatted_info[0],
 
406
                                      formatted_info[1],
 
407
                                      formatted_info[2],
 
408
                                      deadline_str)
 
409
 
375
410
            if time.time() + poll < deadline:
376
411
                time.sleep(poll)
377
412
            else:
379
414
 
380
415
    def lock_write(self):
381
416
        """Wait for and acquire the lock."""
382
 
        self.attempt_lock()
 
417
        self.wait_lock()
383
418
 
384
419
    def lock_read(self):
385
420
        """Compatibility-mode shared lock.
409
444
            else:
410
445
                raise LockContention(self)
411
446
 
 
447
    def _format_lock_info(self, info):
 
448
        """Turn the contents of peek() into something for the user"""
 
449
        lock_url = self.transport.abspath(self.path)
 
450
        delta = time.time() - int(info['start_time'])
 
451
        return [
 
452
            'lock %s' % (lock_url,),
 
453
            'held by %(user)s on host %(hostname)s [process #%(pid)s]' % info,
 
454
            'locked %s' % (format_delta(delta),),
 
455
            ]
 
456