~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/smart/repository.py

  • Committer: John Arbash Meinel
  • Date: 2009-03-27 22:29:55 UTC
  • mto: (3735.39.2 clean)
  • mto: This revision was merged to the branch mainline in revision 4280.
  • Revision ID: john@arbash-meinel.com-20090327222955-utifmfm888zerixt
Implement apply_delta_to_source which doesn't have to malloc another string.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006-2010 Canonical Ltd
 
1
# Copyright (C) 2006, 2007 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
19
19
import bz2
20
20
import os
21
21
import Queue
 
22
import struct
22
23
import sys
 
24
import tarfile
23
25
import tempfile
24
26
import threading
25
27
 
26
28
from bzrlib import (
27
 
    bencode,
28
29
    errors,
29
30
    graph,
30
31
    osutils,
31
32
    pack,
32
 
    ui,
33
 
    versionedfile,
34
33
    )
35
34
from bzrlib.bzrdir import BzrDir
36
35
from bzrlib.smart.request import (
39
38
    SuccessfulSmartServerResponse,
40
39
    )
41
40
from bzrlib.repository import _strip_NULL_ghosts, network_format_registry
42
 
from bzrlib.recordcounter import RecordCounter
43
41
from bzrlib import revision as _mod_revision
44
 
from bzrlib.versionedfile import (
45
 
    NetworkRecordStream,
46
 
    record_to_fulltext_bytes,
47
 
    )
 
42
from bzrlib.util import bencode
 
43
from bzrlib.versionedfile import NetworkRecordStream, record_to_fulltext_bytes
48
44
 
49
45
 
50
46
class SmartServerRepositoryRequest(SmartServerRequest):
75
71
        # is expected)
76
72
        return None
77
73
 
78
 
    def recreate_search(self, repository, search_bytes, discard_excess=False):
79
 
        """Recreate a search from its serialised form.
80
 
 
81
 
        :param discard_excess: If True, and the search refers to data we don't
82
 
            have, just silently accept that fact - the verb calling
83
 
            recreate_search trusts that clients will look for missing things
84
 
            they expected and get it from elsewhere.
85
 
        """
 
74
    def recreate_search(self, repository, search_bytes):
86
75
        lines = search_bytes.split('\n')
87
76
        if lines[0] == 'ancestry-of':
88
77
            heads = lines[1:]
89
78
            search_result = graph.PendingAncestryResult(heads, repository)
90
79
            return search_result, None
91
80
        elif lines[0] == 'search':
92
 
            return self.recreate_search_from_recipe(repository, lines[1:],
93
 
                discard_excess=discard_excess)
 
81
            return self.recreate_search_from_recipe(repository, lines[1:])
94
82
        else:
95
83
            return (None, FailedSmartServerResponse(('BadSearch',)))
96
84
 
97
 
    def recreate_search_from_recipe(self, repository, lines,
98
 
        discard_excess=False):
99
 
        """Recreate a specific revision search (vs a from-tip search).
100
 
 
101
 
        :param discard_excess: If True, and the search refers to data we don't
102
 
            have, just silently accept that fact - the verb calling
103
 
            recreate_search trusts that clients will look for missing things
104
 
            they expected and get it from elsewhere.
105
 
        """
 
85
    def recreate_search_from_recipe(self, repository, lines):
106
86
        start_keys = set(lines[0].split(' '))
107
87
        exclude_keys = set(lines[1].split(' '))
108
88
        revision_count = int(lines[2])
117
97
                    break
118
98
                search.stop_searching_any(exclude_keys.intersection(next_revs))
119
99
            search_result = search.get_result()
120
 
            if (not discard_excess and
121
 
                search_result.get_recipe()[3] != revision_count):
 
100
            if search_result.get_recipe()[3] != revision_count:
122
101
                # we got back a different amount of data than expected, this
123
102
                # gets reported as NoSuchRevision, because less revisions
124
103
                # indicates missing revisions, and more should never happen as
288
267
        return SuccessfulSmartServerResponse(('ok', ), '\n'.join(lines))
289
268
 
290
269
 
291
 
class SmartServerRepositoryGetRevIdForRevno(SmartServerRepositoryReadLocked):
292
 
 
293
 
    def do_readlocked_repository_request(self, repository, revno,
294
 
            known_pair):
295
 
        """Find the revid for a given revno, given a known revno/revid pair.
296
 
        
297
 
        New in 1.17.
298
 
        """
299
 
        try:
300
 
            found_flag, result = repository.get_rev_id_for_revno(revno, known_pair)
301
 
        except errors.RevisionNotPresent, err:
302
 
            if err.revision_id != known_pair[1]:
303
 
                raise AssertionError(
304
 
                    'get_rev_id_for_revno raised RevisionNotPresent for '
305
 
                    'non-initial revision: ' + err.revision_id)
306
 
            return FailedSmartServerResponse(
307
 
                ('nosuchrevision', err.revision_id))
308
 
        if found_flag:
309
 
            return SuccessfulSmartServerResponse(('ok', result))
310
 
        else:
311
 
            earliest_revno, earliest_revid = result
312
 
            return SuccessfulSmartServerResponse(
313
 
                ('history-incomplete', earliest_revno, earliest_revid))
314
 
 
315
 
 
316
270
class SmartServerRequestHasRevision(SmartServerRepositoryRequest):
317
271
 
318
272
    def do_repository_request(self, repository, revision_id):
393
347
        if token == '':
394
348
            token = None
395
349
        try:
396
 
            token = repository.lock_write(token=token).repository_token
 
350
            token = repository.lock_write(token=token)
397
351
        except errors.LockContention, e:
398
352
            return FailedSmartServerResponse(('LockContention',))
399
353
        except errors.UnlockableTransport:
419
373
            repository.
420
374
        """
421
375
        self._to_format = network_format_registry.get(to_network_name)
422
 
        if self._should_fake_unknown():
423
 
            return FailedSmartServerResponse(
424
 
                ('UnknownMethod', 'Repository.get_stream'))
425
376
        return None # Signal that we want a body.
426
377
 
427
 
    def _should_fake_unknown(self):
428
 
        """Return True if we should return UnknownMethod to the client.
429
 
        
430
 
        This is a workaround for bugs in pre-1.19 clients that claim to
431
 
        support receiving streams of CHK repositories.  The pre-1.19 client
432
 
        expects inventory records to be serialized in the format defined by
433
 
        to_network_name, but in pre-1.19 (at least) that format definition
434
 
        tries to use the xml5 serializer, which does not correctly handle
435
 
        rich-roots.  After 1.19 the client can also accept inventory-deltas
436
 
        (which avoids this issue), and those clients will use the
437
 
        Repository.get_stream_1.19 verb instead of this one.
438
 
        So: if this repository is CHK, and the to_format doesn't match,
439
 
        we should just fake an UnknownSmartMethod error so that the client
440
 
        will fallback to VFS, rather than sending it a stream we know it
441
 
        cannot handle.
442
 
        """
443
 
        from_format = self._repository._format
444
 
        to_format = self._to_format
445
 
        if not from_format.supports_chks:
446
 
            # Source not CHK: that's ok
447
 
            return False
448
 
        if (to_format.supports_chks and
449
 
            from_format.repository_class is to_format.repository_class and
450
 
            from_format._serializer == to_format._serializer):
451
 
            # Source is CHK, but target matches: that's ok
452
 
            # (e.g. 2a->2a, or CHK2->2a)
453
 
            return False
454
 
        # Source is CHK, and target is not CHK or incompatible CHK.  We can't
455
 
        # generate a compatible stream.
456
 
        return True
457
 
 
458
378
    def do_body(self, body_bytes):
459
379
        repository = self._repository
460
380
        repository.lock_read()
461
381
        try:
462
 
            search_result, error = self.recreate_search(repository, body_bytes,
463
 
                discard_excess=True)
 
382
            search_result, error = self.recreate_search(repository, body_bytes)
464
383
            if error is not None:
465
384
                repository.unlock()
466
385
                return error
490
409
            repository.unlock()
491
410
 
492
411
 
493
 
class SmartServerRepositoryGetStream_1_19(SmartServerRepositoryGetStream):
494
 
 
495
 
    def _should_fake_unknown(self):
496
 
        """Returns False; we don't need to workaround bugs in 1.19+ clients."""
497
 
        return False
498
 
 
499
 
 
500
412
def _stream_to_byte_stream(stream, src_format):
501
413
    """Convert a record stream to a self delimited byte stream."""
502
414
    pack_writer = pack.ContainerSerialiser()
506
418
        for record in substream:
507
419
            if record.storage_kind in ('chunked', 'fulltext'):
508
420
                serialised = record_to_fulltext_bytes(record)
509
 
            elif record.storage_kind == 'inventory-delta':
510
 
                serialised = record_to_inventory_delta_bytes(record)
511
 
            elif record.storage_kind == 'absent':
512
 
                raise ValueError("Absent factory for %s" % (record.key,))
513
421
            else:
514
422
                serialised = record.get_bytes_as(record.storage_kind)
515
423
            if serialised:
520
428
    yield pack_writer.end()
521
429
 
522
430
 
523
 
class _ByteStreamDecoder(object):
524
 
    """Helper for _byte_stream_to_stream.
525
 
 
526
 
    The expected usage of this class is via the function _byte_stream_to_stream
527
 
    which creates a _ByteStreamDecoder, pops off the stream format and then
528
 
    yields the output of record_stream(), the main entry point to
529
 
    _ByteStreamDecoder.
530
 
 
531
 
    Broadly this class has to unwrap two layers of iterators:
532
 
    (type, substream)
533
 
    (substream details)
534
 
 
535
 
    This is complicated by wishing to return type, iterator_for_type, but
536
 
    getting the data for iterator_for_type when we find out type: we can't
537
 
    simply pass a generator down to the NetworkRecordStream parser, instead
538
 
    we have a little local state to seed each NetworkRecordStream instance,
539
 
    and gather the type that we'll be yielding.
540
 
 
541
 
    :ivar byte_stream: The byte stream being decoded.
542
 
    :ivar stream_decoder: A pack parser used to decode the bytestream
543
 
    :ivar current_type: The current type, used to join adjacent records of the
544
 
        same type into a single stream.
545
 
    :ivar first_bytes: The first bytes to give the next NetworkRecordStream.
 
431
def _byte_stream_to_stream(byte_stream):
 
432
    """Convert a byte stream into a format and a stream.
 
433
 
 
434
    :param byte_stream: A bytes iterator, as output by _stream_to_byte_stream.
 
435
    :return: (RepositoryFormat, stream_generator)
546
436
    """
547
 
 
548
 
    def __init__(self, byte_stream, record_counter):
549
 
        """Create a _ByteStreamDecoder."""
550
 
        self.stream_decoder = pack.ContainerPushParser()
551
 
        self.current_type = None
552
 
        self.first_bytes = None
553
 
        self.byte_stream = byte_stream
554
 
        self._record_counter = record_counter
555
 
        self.key_count = 0
556
 
 
557
 
    def iter_stream_decoder(self):
558
 
        """Iterate the contents of the pack from stream_decoder."""
559
 
        # dequeue pending items
560
 
        for record in self.stream_decoder.read_pending_records():
561
 
            yield record
562
 
        # Pull bytes of the wire, decode them to records, yield those records.
563
 
        for bytes in self.byte_stream:
564
 
            self.stream_decoder.accept_bytes(bytes)
565
 
            for record in self.stream_decoder.read_pending_records():
566
 
                yield record
567
 
 
568
 
    def iter_substream_bytes(self):
569
 
        if self.first_bytes is not None:
570
 
            yield self.first_bytes
571
 
            # If we run out of pack records, single the outer layer to stop.
572
 
            self.first_bytes = None
573
 
        for record in self.iter_pack_records:
 
437
    stream_decoder = pack.ContainerPushParser()
 
438
    def record_stream():
 
439
        """Closure to return the substreams."""
 
440
        # May have fully parsed records already.
 
441
        for record in stream_decoder.read_pending_records():
574
442
            record_names, record_bytes = record
575
443
            record_name, = record_names
576
444
            substream_type = record_name[0]
577
 
            if substream_type != self.current_type:
578
 
                # end of a substream, seed the next substream.
579
 
                self.current_type = substream_type
580
 
                self.first_bytes = record_bytes
581
 
                return
582
 
            yield record_bytes
583
 
 
584
 
    def record_stream(self):
585
 
        """Yield substream_type, substream from the byte stream."""
586
 
        def wrap_and_count(pb, rc, substream):
587
 
            """Yield records from stream while showing progress."""
588
 
            counter = 0
589
 
            if rc:
590
 
                if self.current_type != 'revisions' and self.key_count != 0:
591
 
                    # As we know the number of revisions now (in self.key_count)
592
 
                    # we can setup and use record_counter (rc).
593
 
                    if not rc.is_initialized():
594
 
                        rc.setup(self.key_count, self.key_count)
595
 
            for record in substream.read():
596
 
                if rc:
597
 
                    if rc.is_initialized() and counter == rc.STEP:
598
 
                        rc.increment(counter)
599
 
                        pb.update('Estimate', rc.current, rc.max)
600
 
                        counter = 0
601
 
                    if self.current_type == 'revisions':
602
 
                        # Total records is proportional to number of revs
603
 
                        # to fetch. With remote, we used self.key_count to
604
 
                        # track the number of revs. Once we have the revs
605
 
                        # counts in self.key_count, the progress bar changes
606
 
                        # from 'Estimating..' to 'Estimate' above.
607
 
                        self.key_count += 1
608
 
                        if counter == rc.STEP:
609
 
                            pb.update('Estimating..', self.key_count)
610
 
                            counter = 0
611
 
                counter += 1
612
 
                yield record
613
 
 
614
 
        self.seed_state()
615
 
        pb = ui.ui_factory.nested_progress_bar()
616
 
        rc = self._record_counter
617
 
        # Make and consume sub generators, one per substream type:
618
 
        while self.first_bytes is not None:
619
 
            substream = NetworkRecordStream(self.iter_substream_bytes())
620
 
            # after substream is fully consumed, self.current_type is set to
621
 
            # the next type, and self.first_bytes is set to the matching bytes.
622
 
            yield self.current_type, wrap_and_count(pb, rc, substream)
623
 
        if rc:
624
 
            pb.update('Done', rc.max, rc.max)
625
 
        pb.finished()
626
 
 
627
 
    def seed_state(self):
628
 
        """Prepare the _ByteStreamDecoder to decode from the pack stream."""
629
 
        # Set a single generator we can use to get data from the pack stream.
630
 
        self.iter_pack_records = self.iter_stream_decoder()
631
 
        # Seed the very first subiterator with content; after this each one
632
 
        # seeds the next.
633
 
        list(self.iter_substream_bytes())
634
 
 
635
 
 
636
 
def _byte_stream_to_stream(byte_stream, record_counter=None):
637
 
    """Convert a byte stream into a format and a stream.
638
 
 
639
 
    :param byte_stream: A bytes iterator, as output by _stream_to_byte_stream.
640
 
    :return: (RepositoryFormat, stream_generator)
641
 
    """
642
 
    decoder = _ByteStreamDecoder(byte_stream, record_counter)
 
445
            substream = NetworkRecordStream([record_bytes])
 
446
            yield substream_type, substream.read()
 
447
        for bytes in byte_stream:
 
448
            stream_decoder.accept_bytes(bytes)
 
449
            for record in stream_decoder.read_pending_records():
 
450
                record_names, record_bytes = record
 
451
                record_name, = record_names
 
452
                substream_type = record_name[0]
 
453
                substream = NetworkRecordStream([record_bytes])
 
454
                yield substream_type, substream.read()
643
455
    for bytes in byte_stream:
644
 
        decoder.stream_decoder.accept_bytes(bytes)
645
 
        for record in decoder.stream_decoder.read_pending_records(max=1):
 
456
        stream_decoder.accept_bytes(bytes)
 
457
        for record in stream_decoder.read_pending_records(max=1):
646
458
            record_names, src_format_name = record
647
459
            src_format = network_format_registry.get(src_format_name)
648
 
            return src_format, decoder.record_stream()
 
460
            return src_format, record_stream()
649
461
 
650
462
 
651
463
class SmartServerRepositoryUnlock(SmartServerRepositoryRequest):
711
523
            temp.close()
712
524
 
713
525
    def _tarball_of_dir(self, dirname, compression, ofile):
714
 
        import tarfile
715
526
        filename = os.path.basename(ofile.name)
716
527
        tarball = tarfile.open(fileobj=ofile, name=filename,
717
528
            mode='w|' + compression)
795
606
            return SuccessfulSmartServerResponse(('ok', ))
796
607
 
797
608
 
798
 
class SmartServerRepositoryInsertStream_1_19(SmartServerRepositoryInsertStreamLocked):
799
 
    """Insert a record stream from a RemoteSink into a repository.
800
 
 
801
 
    Same as SmartServerRepositoryInsertStreamLocked, except:
802
 
     - the lock token argument is optional
803
 
     - servers that implement this verb accept 'inventory-delta' records in the
804
 
       stream.
805
 
 
806
 
    New in 1.19.
807
 
    """
808
 
 
809
 
    def do_repository_request(self, repository, resume_tokens, lock_token=None):
810
 
        """StreamSink.insert_stream for a remote repository."""
811
 
        SmartServerRepositoryInsertStreamLocked.do_repository_request(
812
 
            self, repository, resume_tokens, lock_token)
813
 
 
814
 
 
815
609
class SmartServerRepositoryInsertStream(SmartServerRepositoryInsertStreamLocked):
816
610
    """Insert a record stream from a RemoteSink into an unlocked repository.
817
611