~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/bundle/serializer/v4.py

(jameinel) Allow 'bzr serve' to interpret SIGHUP as a graceful shutdown.
 (bug #795025) (John A Meinel)

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2007 Canonical Ltd
 
1
# Copyright (C) 2007-2010 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
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
14
# along with this program; if not, write to the Free Software
15
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
from cStringIO import StringIO
18
18
import bz2
22
22
    diff,
23
23
    errors,
24
24
    iterablefile,
 
25
    lru_cache,
25
26
    multiparent,
26
27
    osutils,
27
28
    pack,
28
29
    revision as _mod_revision,
 
30
    serializer,
29
31
    trace,
30
 
    xml_serializer,
 
32
    ui,
 
33
    versionedfile as _mod_versionedfile,
31
34
    )
32
 
from bzrlib.bundle import bundle_data, serializer
33
 
from bzrlib.util import bencode
 
35
from bzrlib.bundle import bundle_data, serializer as bundle_serializer
 
36
from bzrlib.i18n import gettext, ngettext
 
37
from bzrlib import bencode
 
38
 
 
39
 
 
40
class _MPDiffInventoryGenerator(_mod_versionedfile._MPDiffGenerator):
 
41
    """Generate Inventory diffs serialized inventories."""
 
42
 
 
43
    def __init__(self, repo, inventory_keys):
 
44
        super(_MPDiffInventoryGenerator, self).__init__(repo.inventories,
 
45
            inventory_keys)
 
46
        self.repo = repo
 
47
        self.sha1s = {}
 
48
 
 
49
    def iter_diffs(self):
 
50
        """Compute the diffs one at a time."""
 
51
        # This is instead of compute_diffs() since we guarantee our ordering of
 
52
        # inventories, we don't have to do any buffering
 
53
        self._find_needed_keys()
 
54
        # We actually use a slightly different ordering. We grab all of the
 
55
        # parents first, and then grab the ordered requests.
 
56
        needed_ids = [k[-1] for k in self.present_parents]
 
57
        needed_ids.extend([k[-1] for k in self.ordered_keys])
 
58
        inv_to_str = self.repo._serializer.write_inventory_to_string
 
59
        for inv in self.repo.iter_inventories(needed_ids):
 
60
            revision_id = inv.revision_id
 
61
            key = (revision_id,)
 
62
            if key in self.present_parents:
 
63
                # Not a key we will transmit, which is a shame, since because
 
64
                # of that bundles don't work with stacked branches
 
65
                parent_ids = None
 
66
            else:
 
67
                parent_ids = [k[-1] for k in self.parent_map[key]]
 
68
            as_bytes = inv_to_str(inv)
 
69
            self._process_one_record(key, (as_bytes,))
 
70
            if parent_ids is None:
 
71
                continue
 
72
            diff = self.diffs.pop(key)
 
73
            sha1 = osutils.sha_string(as_bytes)
 
74
            yield revision_id, parent_ids, sha1, diff
34
75
 
35
76
 
36
77
class BundleWriter(object):
54
95
 
55
96
    def begin(self):
56
97
        """Start writing the bundle"""
57
 
        self._fileobj.write(serializer._get_bundle_header(
58
 
            serializer.v4_string))
 
98
        self._fileobj.write(bundle_serializer._get_bundle_header(
 
99
            bundle_serializer.v4_string))
59
100
        self._fileobj.write('#\n')
60
101
        self._container.begin()
61
102
 
218
259
            yield (bytes, metadata) + self.decode_name(names[0][0])
219
260
 
220
261
 
221
 
class BundleSerializerV4(serializer.BundleSerializer):
 
262
class BundleSerializerV4(bundle_serializer.BundleSerializer):
222
263
    """Implement the high-level bundle interface"""
223
264
 
224
265
    def write(self, repository, revision_ids, forced_bases, fileobj):
250
291
    @staticmethod
251
292
    def get_source_serializer(info):
252
293
        """Retrieve the serializer for a given info object"""
253
 
        return xml_serializer.format_registry.get(info['serializer'])
 
294
        return serializer.format_registry.get(info['serializer'])
254
295
 
255
296
 
256
297
class BundleWriteOperation(object):
270
311
        self.repository = repository
271
312
        bundle = BundleWriter(fileobj)
272
313
        self.bundle = bundle
273
 
        self.base_ancestry = set(repository.get_ancestry(base,
274
 
                                                         topo_sorted=False))
275
314
        if revision_ids is not None:
276
315
            self.revision_ids = revision_ids
277
316
        else:
278
 
            revision_ids = set(repository.get_ancestry(target,
279
 
                                                       topo_sorted=False))
280
 
            self.revision_ids = revision_ids.difference(self.base_ancestry)
 
317
            graph = repository.get_graph()
 
318
            revision_ids = graph.find_unique_ancestors(target, [base])
 
319
            # Strip ghosts
 
320
            parents = graph.get_parent_map(revision_ids)
 
321
            self.revision_ids = [r for r in revision_ids if r in parents]
281
322
        self.revision_keys = set([(revid,) for revid in self.revision_ids])
282
323
 
283
324
    def do_write(self):
284
325
        """Write all data to the bundle"""
285
 
        trace.note('Bundling %d revision(s).', len(self.revision_ids))
 
326
        trace.note(ngettext('Bundling %d revision.', 'Bundling %d revisions.',
 
327
                            len(self.revision_ids)), len(self.revision_ids))
286
328
        self.repository.lock_read()
287
329
        try:
288
330
            self.bundle.begin()
315
357
    def write_revisions(self):
316
358
        """Write bundle records for all revisions and signatures"""
317
359
        inv_vf = self.repository.inventories
318
 
        revision_order = [key[-1] for key in multiparent.topo_iter_keys(inv_vf,
319
 
            self.revision_keys)]
 
360
        topological_order = [key[-1] for key in multiparent.topo_iter_keys(
 
361
                                inv_vf, self.revision_keys)]
 
362
        revision_order = topological_order
320
363
        if self.target is not None and self.target in self.revision_ids:
 
364
            # Make sure the target revision is always the last entry
 
365
            revision_order = list(topological_order)
321
366
            revision_order.remove(self.target)
322
367
            revision_order.append(self.target)
323
 
        self._add_mp_records_keys('inventory', inv_vf, [(revid,) for revid in revision_order])
 
368
        if self.repository._serializer.support_altered_by_hack:
 
369
            # Repositories that support_altered_by_hack means that
 
370
            # inventories.make_mpdiffs() contains all the data about the tree
 
371
            # shape. Formats without support_altered_by_hack require
 
372
            # chk_bytes/etc, so we use a different code path.
 
373
            self._add_mp_records_keys('inventory', inv_vf,
 
374
                                      [(revid,) for revid in topological_order])
 
375
        else:
 
376
            # Inventories should always be added in pure-topological order, so
 
377
            # that we can apply the mpdiff for the child to the parent texts.
 
378
            self._add_inventory_mpdiffs_from_serializer(topological_order)
 
379
        self._add_revision_texts(revision_order)
 
380
 
 
381
    def _add_inventory_mpdiffs_from_serializer(self, revision_order):
 
382
        """Generate mpdiffs by serializing inventories.
 
383
 
 
384
        The current repository only has part of the tree shape information in
 
385
        the 'inventories' vf. So we use serializer.write_inventory_to_string to
 
386
        get a 'full' representation of the tree shape, and then generate
 
387
        mpdiffs on that data stream. This stream can then be reconstructed on
 
388
        the other side.
 
389
        """
 
390
        inventory_key_order = [(r,) for r in revision_order]
 
391
        generator = _MPDiffInventoryGenerator(self.repository,
 
392
                                              inventory_key_order)
 
393
        for revision_id, parent_ids, sha1, diff in generator.iter_diffs():
 
394
            text = ''.join(diff.to_patch())
 
395
            self.bundle.add_multiparent_record(text, sha1, parent_ids,
 
396
                                               'inventory', revision_id, None)
 
397
 
 
398
    def _add_revision_texts(self, revision_order):
324
399
        parent_map = self.repository.get_parent_map(revision_order)
325
 
        for revision_id in revision_order:
 
400
        revision_to_str = self.repository._serializer.write_revision_to_string
 
401
        revisions = self.repository.get_revisions(revision_order)
 
402
        for revision in revisions:
 
403
            revision_id = revision.revision_id
326
404
            parents = parent_map.get(revision_id, None)
327
 
            revision_text = self.repository.get_revision_xml(revision_id)
 
405
            revision_text = revision_to_str(revision)
328
406
            self.bundle.add_fulltext_record(revision_text, parents,
329
407
                                       'revision', revision_id)
330
408
            try:
455
533
 
456
534
    def install(self):
457
535
        """Perform the installation.
458
 
        
 
536
 
459
537
        Must be called with the Repository locked.
460
538
        """
461
539
        self._repository.start_write_group()
540
618
            vf_records.append((key, parents, meta['sha1'], d_func(text)))
541
619
        versionedfile.add_mpdiffs(vf_records)
542
620
 
 
621
    def _get_parent_inventory_texts(self, inventory_text_cache,
 
622
                                    inventory_cache, parent_ids):
 
623
        cached_parent_texts = {}
 
624
        remaining_parent_ids = []
 
625
        for parent_id in parent_ids:
 
626
            p_text = inventory_text_cache.get(parent_id, None)
 
627
            if p_text is None:
 
628
                remaining_parent_ids.append(parent_id)
 
629
            else:
 
630
                cached_parent_texts[parent_id] = p_text
 
631
        ghosts = ()
 
632
        # TODO: Use inventory_cache to grab inventories we already have in
 
633
        #       memory
 
634
        if remaining_parent_ids:
 
635
            # first determine what keys are actually present in the local
 
636
            # inventories object (don't use revisions as they haven't been
 
637
            # installed yet.)
 
638
            parent_keys = [(r,) for r in remaining_parent_ids]
 
639
            present_parent_map = self._repository.inventories.get_parent_map(
 
640
                                        parent_keys)
 
641
            present_parent_ids = []
 
642
            ghosts = set()
 
643
            for p_id in remaining_parent_ids:
 
644
                if (p_id,) in present_parent_map:
 
645
                    present_parent_ids.append(p_id)
 
646
                else:
 
647
                    ghosts.add(p_id)
 
648
            to_string = self._source_serializer.write_inventory_to_string
 
649
            for parent_inv in self._repository.iter_inventories(
 
650
                                    present_parent_ids):
 
651
                p_text = to_string(parent_inv)
 
652
                inventory_cache[parent_inv.revision_id] = parent_inv
 
653
                cached_parent_texts[parent_inv.revision_id] = p_text
 
654
                inventory_text_cache[parent_inv.revision_id] = p_text
 
655
 
 
656
        parent_texts = [cached_parent_texts[parent_id]
 
657
                        for parent_id in parent_ids
 
658
                         if parent_id not in ghosts]
 
659
        return parent_texts
 
660
 
543
661
    def _install_inventory_records(self, records):
544
 
        if self._info['serializer'] == self._repository._serializer.format_num:
 
662
        if (self._info['serializer'] == self._repository._serializer.format_num
 
663
            and self._repository._serializer.support_altered_by_hack):
545
664
            return self._install_mp_records_keys(self._repository.inventories,
546
665
                records)
547
 
        for key, metadata, bytes in records:
548
 
            revision_id = key[-1]
549
 
            parent_ids = metadata['parents']
550
 
            parents = [self._repository.get_inventory(p)
551
 
                       for p in parent_ids]
552
 
            p_texts = [self._source_serializer.write_inventory_to_string(p)
553
 
                       for p in parents]
554
 
            target_lines = multiparent.MultiParent.from_patch(bytes).to_lines(
555
 
                p_texts)
556
 
            sha1 = osutils.sha_strings(target_lines)
557
 
            if sha1 != metadata['sha1']:
558
 
                raise errors.BadBundle("Can't convert to target format")
559
 
            target_inv = self._source_serializer.read_inventory_from_string(
560
 
                ''.join(target_lines))
561
 
            self._handle_root(target_inv, parent_ids)
562
 
            try:
563
 
                self._repository.add_inventory(revision_id, target_inv,
564
 
                                               parent_ids)
565
 
            except errors.UnsupportedInventoryKind:
566
 
                raise errors.IncompatibleRevision(repr(self._repository))
 
666
        # Use a 10MB text cache, since these are string xml inventories. Note
 
667
        # that 10MB is fairly small for large projects (a single inventory can
 
668
        # be >5MB). Another possibility is to cache 10-20 inventory texts
 
669
        # instead
 
670
        inventory_text_cache = lru_cache.LRUSizeCache(10*1024*1024)
 
671
        # Also cache the in-memory representation. This allows us to create
 
672
        # inventory deltas to apply rather than calling add_inventory from
 
673
        # scratch each time.
 
674
        inventory_cache = lru_cache.LRUCache(10)
 
675
        pb = ui.ui_factory.nested_progress_bar()
 
676
        try:
 
677
            num_records = len(records)
 
678
            for idx, (key, metadata, bytes) in enumerate(records):
 
679
                pb.update('installing inventory', idx, num_records)
 
680
                revision_id = key[-1]
 
681
                parent_ids = metadata['parents']
 
682
                # Note: This assumes the local ghosts are identical to the
 
683
                #       ghosts in the source, as the Bundle serialization
 
684
                #       format doesn't record ghosts.
 
685
                p_texts = self._get_parent_inventory_texts(inventory_text_cache,
 
686
                                                           inventory_cache,
 
687
                                                           parent_ids)
 
688
                # Why does to_lines() take strings as the source, it seems that
 
689
                # it would have to cast to a list of lines, which we get back
 
690
                # as lines and then cast back to a string.
 
691
                target_lines = multiparent.MultiParent.from_patch(bytes
 
692
                            ).to_lines(p_texts)
 
693
                inv_text = ''.join(target_lines)
 
694
                del target_lines
 
695
                sha1 = osutils.sha_string(inv_text)
 
696
                if sha1 != metadata['sha1']:
 
697
                    raise errors.BadBundle("Can't convert to target format")
 
698
                # Add this to the cache so we don't have to extract it again.
 
699
                inventory_text_cache[revision_id] = inv_text
 
700
                target_inv = self._source_serializer.read_inventory_from_string(
 
701
                    inv_text)
 
702
                self._handle_root(target_inv, parent_ids)
 
703
                parent_inv = None
 
704
                if parent_ids:
 
705
                    parent_inv = inventory_cache.get(parent_ids[0], None)
 
706
                try:
 
707
                    if parent_inv is None:
 
708
                        self._repository.add_inventory(revision_id, target_inv,
 
709
                                                       parent_ids)
 
710
                    else:
 
711
                        delta = target_inv._make_delta(parent_inv)
 
712
                        self._repository.add_inventory_by_delta(parent_ids[0],
 
713
                            delta, revision_id, parent_ids)
 
714
                except errors.UnsupportedInventoryKind:
 
715
                    raise errors.IncompatibleRevision(repr(self._repository))
 
716
                inventory_cache[revision_id] = target_inv
 
717
        finally:
 
718
            pb.finished()
567
719
 
568
720
    def _handle_root(self, target_inv, parent_ids):
569
721
        revision_id = target_inv.revision_id