~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/smart/repository.py

  • Committer: Jelmer Vernooij
  • Date: 2012-02-20 14:15:25 UTC
  • mto: (6471.1.4 iter-child-entries)
  • mto: This revision was merged to the branch mainline in revision 6472.
  • Revision ID: jelmer@samba.org-20120220141525-9azkfei62st8yc7w
Use inventories directly in fewer places.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006, 2007, 2010 Canonical Ltd
 
1
# Copyright (C) 2006-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
14
14
# along with this program; if not, write to the Free Software
15
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
 
"""Server-side repository related request implmentations."""
 
17
"""Server-side repository related request implementations."""
 
18
 
 
19
from __future__ import absolute_import
18
20
 
19
21
import bz2
20
22
import os
22
24
import sys
23
25
import tempfile
24
26
import threading
 
27
import zlib
25
28
 
26
29
from bzrlib import (
27
30
    bencode,
28
31
    errors,
29
 
    graph,
 
32
    estimate_compressed_size,
 
33
    inventory as _mod_inventory,
 
34
    inventory_delta,
30
35
    osutils,
31
36
    pack,
 
37
    trace,
32
38
    ui,
33
 
    versionedfile,
 
39
    vf_search,
34
40
    )
35
41
from bzrlib.bzrdir import BzrDir
36
42
from bzrlib.smart.request import (
41
47
from bzrlib.repository import _strip_NULL_ghosts, network_format_registry
42
48
from bzrlib import revision as _mod_revision
43
49
from bzrlib.versionedfile import (
 
50
    ChunkedContentFactory,
44
51
    NetworkRecordStream,
45
52
    record_to_fulltext_bytes,
46
53
    )
82
89
            recreate_search trusts that clients will look for missing things
83
90
            they expected and get it from elsewhere.
84
91
        """
 
92
        if search_bytes == 'everything':
 
93
            return vf_search.EverythingResult(repository), None
85
94
        lines = search_bytes.split('\n')
86
95
        if lines[0] == 'ancestry-of':
87
96
            heads = lines[1:]
88
 
            search_result = graph.PendingAncestryResult(heads, repository)
 
97
            search_result = vf_search.PendingAncestryResult(heads, repository)
89
98
            return search_result, None
90
99
        elif lines[0] == 'search':
91
100
            return self.recreate_search_from_recipe(repository, lines[1:],
115
124
                except StopIteration:
116
125
                    break
117
126
                search.stop_searching_any(exclude_keys.intersection(next_revs))
118
 
            search_result = search.get_result()
119
 
            if (not discard_excess and
120
 
                search_result.get_recipe()[3] != revision_count):
 
127
            (started_keys, excludes, included_keys) = search.get_state()
 
128
            if (not discard_excess and len(included_keys) != revision_count):
121
129
                # we got back a different amount of data than expected, this
122
130
                # gets reported as NoSuchRevision, because less revisions
123
131
                # indicates missing revisions, and more should never happen as
124
132
                # the excludes list considers ghosts and ensures that ghost
125
133
                # filling races are not a problem.
126
134
                return (None, FailedSmartServerResponse(('NoSuchRevision',)))
 
135
            search_result = vf_search.SearchResult(started_keys, excludes,
 
136
                len(included_keys), included_keys)
127
137
            return (search_result, None)
128
138
        finally:
129
139
            repository.unlock()
141
151
            repository.unlock()
142
152
 
143
153
 
 
154
class SmartServerRepositoryBreakLock(SmartServerRepositoryRequest):
 
155
    """Break a repository lock."""
 
156
 
 
157
    def do_repository_request(self, repository):
 
158
        repository.break_lock()
 
159
        return SuccessfulSmartServerResponse(('ok', ))
 
160
 
 
161
 
 
162
_lsprof_count = 0
 
163
 
144
164
class SmartServerRepositoryGetParentMap(SmartServerRepositoryRequest):
145
165
    """Bzr 1.2+ - get parent data for revisions during a graph search."""
146
166
 
179
199
        finally:
180
200
            repository.unlock()
181
201
 
182
 
    def _do_repository_request(self, body_bytes):
183
 
        repository = self._repository
184
 
        revision_ids = set(self._revision_ids)
185
 
        include_missing = 'include-missing:' in revision_ids
186
 
        if include_missing:
187
 
            revision_ids.remove('include-missing:')
188
 
        body_lines = body_bytes.split('\n')
189
 
        search_result, error = self.recreate_search_from_recipe(
190
 
            repository, body_lines)
191
 
        if error is not None:
192
 
            return error
193
 
        # TODO might be nice to start up the search again; but thats not
194
 
        # written or tested yet.
195
 
        client_seen_revs = set(search_result.get_keys())
196
 
        # Always include the requested ids.
197
 
        client_seen_revs.difference_update(revision_ids)
198
 
        lines = []
199
 
        repo_graph = repository.get_graph()
 
202
    def _expand_requested_revs(self, repo_graph, revision_ids, client_seen_revs,
 
203
                               include_missing, max_size=65536):
200
204
        result = {}
201
205
        queried_revs = set()
202
 
        size_so_far = 0
 
206
        estimator = estimate_compressed_size.ZLibEstimator(max_size)
203
207
        next_revs = revision_ids
204
208
        first_loop_done = False
205
209
        while next_revs:
227
231
                    # add parents to the result
228
232
                    result[encoded_id] = parents
229
233
                    # Approximate the serialized cost of this revision_id.
230
 
                    size_so_far += 2 + len(encoded_id) + sum(map(len, parents))
 
234
                    line = '%s %s\n' % (encoded_id, ' '.join(parents))
 
235
                    estimator.add_content(line)
231
236
            # get all the directly asked for parents, and then flesh out to
232
237
            # 64K (compressed) or so. We do one level of depth at a time to
233
238
            # stay in sync with the client. The 250000 magic number is
234
239
            # estimated compression ratio taken from bzr.dev itself.
235
 
            if self.no_extra_results or (
236
 
                first_loop_done and size_so_far > 250000):
 
240
            if self.no_extra_results or (first_loop_done and estimator.full()):
 
241
                trace.mutter('size: %d, z_size: %d'
 
242
                             % (estimator._uncompressed_size_added,
 
243
                                estimator._compressed_size_added))
237
244
                next_revs = set()
238
245
                break
239
246
            # don't query things we've already queried
240
 
            next_revs.difference_update(queried_revs)
 
247
            next_revs = next_revs.difference(queried_revs)
241
248
            first_loop_done = True
 
249
        return result
 
250
 
 
251
    def _do_repository_request(self, body_bytes):
 
252
        repository = self._repository
 
253
        revision_ids = set(self._revision_ids)
 
254
        include_missing = 'include-missing:' in revision_ids
 
255
        if include_missing:
 
256
            revision_ids.remove('include-missing:')
 
257
        body_lines = body_bytes.split('\n')
 
258
        search_result, error = self.recreate_search_from_recipe(
 
259
            repository, body_lines)
 
260
        if error is not None:
 
261
            return error
 
262
        # TODO might be nice to start up the search again; but thats not
 
263
        # written or tested yet.
 
264
        client_seen_revs = set(search_result.get_keys())
 
265
        # Always include the requested ids.
 
266
        client_seen_revs.difference_update(revision_ids)
 
267
 
 
268
        repo_graph = repository.get_graph()
 
269
        result = self._expand_requested_revs(repo_graph, revision_ids,
 
270
                                             client_seen_revs, include_missing)
242
271
 
243
272
        # sorting trivially puts lexographically similar revision ids together.
244
273
        # Compression FTW.
 
274
        lines = []
245
275
        for revision, parents in sorted(result.items()):
246
276
            lines.append(' '.join((revision, ) + tuple(parents)))
247
277
 
312
342
                ('history-incomplete', earliest_revno, earliest_revid))
313
343
 
314
344
 
 
345
class SmartServerRepositoryGetSerializerFormat(SmartServerRepositoryRequest):
 
346
 
 
347
    def do_repository_request(self, repository):
 
348
        """Return the serializer format for this repository.
 
349
 
 
350
        New in 2.5.0.
 
351
 
 
352
        :param repository: The repository to query
 
353
        :return: A smart server response ('ok', FORMAT)
 
354
        """
 
355
        serializer = repository.get_serializer_format()
 
356
        return SuccessfulSmartServerResponse(('ok', serializer))
 
357
 
 
358
 
315
359
class SmartServerRequestHasRevision(SmartServerRepositoryRequest):
316
360
 
317
361
    def do_repository_request(self, repository, revision_id):
319
363
 
320
364
        :param repository: The repository to query in.
321
365
        :param revision_id: The utf8 encoded revision_id to lookup.
322
 
        :return: A smart server response of ('ok', ) if the revision is
323
 
            present.
 
366
        :return: A smart server response of ('yes', ) if the revision is
 
367
            present. ('no', ) if it is missing.
324
368
        """
325
369
        if repository.has_revision(revision_id):
326
370
            return SuccessfulSmartServerResponse(('yes', ))
328
372
            return SuccessfulSmartServerResponse(('no', ))
329
373
 
330
374
 
 
375
class SmartServerRequestHasSignatureForRevisionId(
 
376
        SmartServerRepositoryRequest):
 
377
 
 
378
    def do_repository_request(self, repository, revision_id):
 
379
        """Return ok if a signature is present for a revision.
 
380
 
 
381
        Introduced in bzr 2.5.0.
 
382
 
 
383
        :param repository: The repository to query in.
 
384
        :param revision_id: The utf8 encoded revision_id to lookup.
 
385
        :return: A smart server response of ('yes', ) if a
 
386
            signature for the revision is present,
 
387
            ('no', ) if it is missing.
 
388
        """
 
389
        try:
 
390
            if repository.has_signature_for_revision_id(revision_id):
 
391
                return SuccessfulSmartServerResponse(('yes', ))
 
392
            else:
 
393
                return SuccessfulSmartServerResponse(('no', ))
 
394
        except errors.NoSuchRevision:
 
395
            return FailedSmartServerResponse(
 
396
                ('nosuchrevision', revision_id))
 
397
 
 
398
 
331
399
class SmartServerRepositoryGatherStats(SmartServerRepositoryRequest):
332
400
 
333
401
    def do_repository_request(self, repository, revid, committers):
353
421
            decoded_committers = True
354
422
        else:
355
423
            decoded_committers = None
356
 
        stats = repository.gather_stats(decoded_revision_id, decoded_committers)
 
424
        try:
 
425
            stats = repository.gather_stats(decoded_revision_id,
 
426
                decoded_committers)
 
427
        except errors.NoSuchRevision:
 
428
            return FailedSmartServerResponse(('nosuchrevision', revid))
357
429
 
358
430
        body = ''
359
431
        if stats.has_key('committers'):
370
442
        return SuccessfulSmartServerResponse(('ok', ), body)
371
443
 
372
444
 
 
445
class SmartServerRepositoryGetRevisionSignatureText(
 
446
        SmartServerRepositoryRequest):
 
447
    """Return the signature text of a revision.
 
448
 
 
449
    New in 2.5.
 
450
    """
 
451
 
 
452
    def do_repository_request(self, repository, revision_id):
 
453
        """Return the result of repository.get_signature_text().
 
454
 
 
455
        :param repository: The repository to query in.
 
456
        :return: A smart server response of with the signature text as
 
457
            body.
 
458
        """
 
459
        try:
 
460
            text = repository.get_signature_text(revision_id)
 
461
        except errors.NoSuchRevision, err:
 
462
            return FailedSmartServerResponse(
 
463
                ('nosuchrevision', err.revision))
 
464
        return SuccessfulSmartServerResponse(('ok', ), text)
 
465
 
 
466
 
373
467
class SmartServerRepositoryIsShared(SmartServerRepositoryRequest):
374
468
 
375
469
    def do_repository_request(self, repository):
385
479
            return SuccessfulSmartServerResponse(('no', ))
386
480
 
387
481
 
 
482
class SmartServerRepositoryMakeWorkingTrees(SmartServerRepositoryRequest):
 
483
 
 
484
    def do_repository_request(self, repository):
 
485
        """Return the result of repository.make_working_trees().
 
486
 
 
487
        Introduced in bzr 2.5.0.
 
488
 
 
489
        :param repository: The repository to query in.
 
490
        :return: A smart server response of ('yes', ) if the repository uses
 
491
            working trees, and ('no', ) if it is not.
 
492
        """
 
493
        if repository.make_working_trees():
 
494
            return SuccessfulSmartServerResponse(('yes', ))
 
495
        else:
 
496
            return SuccessfulSmartServerResponse(('no', ))
 
497
 
 
498
 
388
499
class SmartServerRepositoryLockWrite(SmartServerRepositoryRequest):
389
500
 
390
501
    def do_repository_request(self, repository, token=''):
392
503
        if token == '':
393
504
            token = None
394
505
        try:
395
 
            token = repository.lock_write(token=token)
 
506
            token = repository.lock_write(token=token).repository_token
396
507
        except errors.LockContention, e:
397
508
            return FailedSmartServerResponse(('LockContention',))
398
509
        except errors.UnlockableTransport:
413
524
    def do_repository_request(self, repository, to_network_name):
414
525
        """Get a stream for inserting into a to_format repository.
415
526
 
 
527
        The request body is 'search_bytes', a description of the revisions
 
528
        being requested.
 
529
 
 
530
        In 2.3 this verb added support for search_bytes == 'everything'.  Older
 
531
        implementations will respond with a BadSearch error, and clients should
 
532
        catch this and fallback appropriately.
 
533
 
416
534
        :param repository: The repository to stream from.
417
535
        :param to_network_name: The network name of the format of the target
418
536
            repository.
490
608
 
491
609
 
492
610
class SmartServerRepositoryGetStream_1_19(SmartServerRepositoryGetStream):
 
611
    """The same as Repository.get_stream, but will return stream CHK formats to
 
612
    clients.
 
613
 
 
614
    See SmartServerRepositoryGetStream._should_fake_unknown.
 
615
    
 
616
    New in 1.19.
 
617
    """
493
618
 
494
619
    def _should_fake_unknown(self):
495
620
        """Returns False; we don't need to workaround bugs in 1.19+ clients."""
502
627
    yield pack_writer.begin()
503
628
    yield pack_writer.bytes_record(src_format.network_name(), '')
504
629
    for substream_type, substream in stream:
505
 
        if substream_type == 'inventory-deltas':
506
 
            # This doesn't feel like the ideal place to issue this warning;
507
 
            # however we don't want to do it in the Repository that's
508
 
            # generating the stream, because that might be on the server.
509
 
            # Instead we try to observe it as the stream goes by.
510
 
            ui.ui_factory.warn_cross_format_fetch(src_format,
511
 
                '(remote)')
512
630
        for record in substream:
513
631
            if record.storage_kind in ('chunked', 'fulltext'):
514
632
                serialised = record_to_fulltext_bytes(record)
515
 
            elif record.storage_kind == 'inventory-delta':
516
 
                serialised = record_to_inventory_delta_bytes(record)
517
633
            elif record.storage_kind == 'absent':
518
634
                raise ValueError("Absent factory for %s" % (record.key,))
519
635
            else:
551
667
    :ivar first_bytes: The first bytes to give the next NetworkRecordStream.
552
668
    """
553
669
 
554
 
    def __init__(self, byte_stream):
 
670
    def __init__(self, byte_stream, record_counter):
555
671
        """Create a _ByteStreamDecoder."""
556
672
        self.stream_decoder = pack.ContainerPushParser()
557
673
        self.current_type = None
558
674
        self.first_bytes = None
559
675
        self.byte_stream = byte_stream
 
676
        self._record_counter = record_counter
 
677
        self.key_count = 0
560
678
 
561
679
    def iter_stream_decoder(self):
562
680
        """Iterate the contents of the pack from stream_decoder."""
587
705
 
588
706
    def record_stream(self):
589
707
        """Yield substream_type, substream from the byte stream."""
 
708
        def wrap_and_count(pb, rc, substream):
 
709
            """Yield records from stream while showing progress."""
 
710
            counter = 0
 
711
            if rc:
 
712
                if self.current_type != 'revisions' and self.key_count != 0:
 
713
                    # As we know the number of revisions now (in self.key_count)
 
714
                    # we can setup and use record_counter (rc).
 
715
                    if not rc.is_initialized():
 
716
                        rc.setup(self.key_count, self.key_count)
 
717
            for record in substream.read():
 
718
                if rc:
 
719
                    if rc.is_initialized() and counter == rc.STEP:
 
720
                        rc.increment(counter)
 
721
                        pb.update('Estimate', rc.current, rc.max)
 
722
                        counter = 0
 
723
                    if self.current_type == 'revisions':
 
724
                        # Total records is proportional to number of revs
 
725
                        # to fetch. With remote, we used self.key_count to
 
726
                        # track the number of revs. Once we have the revs
 
727
                        # counts in self.key_count, the progress bar changes
 
728
                        # from 'Estimating..' to 'Estimate' above.
 
729
                        self.key_count += 1
 
730
                        if counter == rc.STEP:
 
731
                            pb.update('Estimating..', self.key_count)
 
732
                            counter = 0
 
733
                counter += 1
 
734
                yield record
 
735
 
590
736
        self.seed_state()
 
737
        pb = ui.ui_factory.nested_progress_bar()
 
738
        rc = self._record_counter
591
739
        # Make and consume sub generators, one per substream type:
592
740
        while self.first_bytes is not None:
593
741
            substream = NetworkRecordStream(self.iter_substream_bytes())
594
742
            # after substream is fully consumed, self.current_type is set to
595
743
            # the next type, and self.first_bytes is set to the matching bytes.
596
 
            yield self.current_type, substream.read()
 
744
            yield self.current_type, wrap_and_count(pb, rc, substream)
 
745
        if rc:
 
746
            pb.update('Done', rc.max, rc.max)
 
747
        pb.finished()
597
748
 
598
749
    def seed_state(self):
599
750
        """Prepare the _ByteStreamDecoder to decode from the pack stream."""
604
755
        list(self.iter_substream_bytes())
605
756
 
606
757
 
607
 
def _byte_stream_to_stream(byte_stream):
 
758
def _byte_stream_to_stream(byte_stream, record_counter=None):
608
759
    """Convert a byte stream into a format and a stream.
609
760
 
610
761
    :param byte_stream: A bytes iterator, as output by _stream_to_byte_stream.
611
762
    :return: (RepositoryFormat, stream_generator)
612
763
    """
613
 
    decoder = _ByteStreamDecoder(byte_stream)
 
764
    decoder = _ByteStreamDecoder(byte_stream, record_counter)
614
765
    for bytes in byte_stream:
615
766
        decoder.stream_decoder.accept_bytes(bytes)
616
767
        for record in decoder.stream_decoder.read_pending_records(max=1):
631
782
        return SuccessfulSmartServerResponse(('ok',))
632
783
 
633
784
 
 
785
class SmartServerRepositoryGetPhysicalLockStatus(SmartServerRepositoryRequest):
 
786
    """Get the physical lock status for a repository.
 
787
 
 
788
    New in 2.5.
 
789
    """
 
790
 
 
791
    def do_repository_request(self, repository):
 
792
        if repository.get_physical_lock_status():
 
793
            return SuccessfulSmartServerResponse(('yes', ))
 
794
        else:
 
795
            return SuccessfulSmartServerResponse(('no', ))
 
796
 
 
797
 
634
798
class SmartServerRepositorySetMakeWorkingTrees(SmartServerRepositoryRequest):
635
799
 
636
800
    def do_repository_request(self, repository, str_bool_new_value):
799
963
        self.do_insert_stream_request(repository, resume_tokens)
800
964
 
801
965
 
 
966
class SmartServerRepositoryAddSignatureText(SmartServerRepositoryRequest):
 
967
    """Add a revision signature text.
 
968
 
 
969
    New in 2.5.
 
970
    """
 
971
 
 
972
    def do_repository_request(self, repository, lock_token, revision_id,
 
973
            *write_group_tokens):
 
974
        """Add a revision signature text.
 
975
 
 
976
        :param repository: Repository to operate on
 
977
        :param lock_token: Lock token
 
978
        :param revision_id: Revision for which to add signature
 
979
        :param write_group_tokens: Write group tokens
 
980
        """
 
981
        self._lock_token = lock_token
 
982
        self._revision_id = revision_id
 
983
        self._write_group_tokens = write_group_tokens
 
984
        return None
 
985
 
 
986
    def do_body(self, body_bytes):
 
987
        """Add a signature text.
 
988
 
 
989
        :param body_bytes: GPG signature text
 
990
        :return: SuccessfulSmartServerResponse with arguments 'ok' and
 
991
            the list of new write group tokens.
 
992
        """
 
993
        self._repository.lock_write(token=self._lock_token)
 
994
        try:
 
995
            self._repository.resume_write_group(self._write_group_tokens)
 
996
            try:
 
997
                self._repository.add_signature_text(self._revision_id,
 
998
                    body_bytes)
 
999
            finally:
 
1000
                new_write_group_tokens = self._repository.suspend_write_group()
 
1001
        finally:
 
1002
            self._repository.unlock()
 
1003
        return SuccessfulSmartServerResponse(
 
1004
            ('ok', ) + tuple(new_write_group_tokens))
 
1005
 
 
1006
 
 
1007
class SmartServerRepositoryStartWriteGroup(SmartServerRepositoryRequest):
 
1008
    """Start a write group.
 
1009
 
 
1010
    New in 2.5.
 
1011
    """
 
1012
 
 
1013
    def do_repository_request(self, repository, lock_token):
 
1014
        """Start a write group."""
 
1015
        repository.lock_write(token=lock_token)
 
1016
        try:
 
1017
            repository.start_write_group()
 
1018
            try:
 
1019
                tokens = repository.suspend_write_group()
 
1020
            except errors.UnsuspendableWriteGroup:
 
1021
                return FailedSmartServerResponse(('UnsuspendableWriteGroup',))
 
1022
        finally:
 
1023
            repository.unlock()
 
1024
        return SuccessfulSmartServerResponse(('ok', tokens))
 
1025
 
 
1026
 
 
1027
class SmartServerRepositoryCommitWriteGroup(SmartServerRepositoryRequest):
 
1028
    """Commit a write group.
 
1029
 
 
1030
    New in 2.5.
 
1031
    """
 
1032
 
 
1033
    def do_repository_request(self, repository, lock_token,
 
1034
            write_group_tokens):
 
1035
        """Commit a write group."""
 
1036
        repository.lock_write(token=lock_token)
 
1037
        try:
 
1038
            try:
 
1039
                repository.resume_write_group(write_group_tokens)
 
1040
            except errors.UnresumableWriteGroup, e:
 
1041
                return FailedSmartServerResponse(
 
1042
                    ('UnresumableWriteGroup', e.write_groups, e.reason))
 
1043
            try:
 
1044
                repository.commit_write_group()
 
1045
            except:
 
1046
                write_group_tokens = repository.suspend_write_group()
 
1047
                # FIXME JRV 2011-11-19: What if the write_group_tokens
 
1048
                # have changed?
 
1049
                raise
 
1050
        finally:
 
1051
            repository.unlock()
 
1052
        return SuccessfulSmartServerResponse(('ok', ))
 
1053
 
 
1054
 
 
1055
class SmartServerRepositoryAbortWriteGroup(SmartServerRepositoryRequest):
 
1056
    """Abort a write group.
 
1057
 
 
1058
    New in 2.5.
 
1059
    """
 
1060
 
 
1061
    def do_repository_request(self, repository, lock_token, write_group_tokens):
 
1062
        """Abort a write group."""
 
1063
        repository.lock_write(token=lock_token)
 
1064
        try:
 
1065
            try:
 
1066
                repository.resume_write_group(write_group_tokens)
 
1067
            except errors.UnresumableWriteGroup, e:
 
1068
                return FailedSmartServerResponse(
 
1069
                    ('UnresumableWriteGroup', e.write_groups, e.reason))
 
1070
                repository.abort_write_group()
 
1071
        finally:
 
1072
            repository.unlock()
 
1073
        return SuccessfulSmartServerResponse(('ok', ))
 
1074
 
 
1075
 
 
1076
class SmartServerRepositoryCheckWriteGroup(SmartServerRepositoryRequest):
 
1077
    """Check that a write group is still valid.
 
1078
 
 
1079
    New in 2.5.
 
1080
    """
 
1081
 
 
1082
    def do_repository_request(self, repository, lock_token, write_group_tokens):
 
1083
        """Abort a write group."""
 
1084
        repository.lock_write(token=lock_token)
 
1085
        try:
 
1086
            try:
 
1087
                repository.resume_write_group(write_group_tokens)
 
1088
            except errors.UnresumableWriteGroup, e:
 
1089
                return FailedSmartServerResponse(
 
1090
                    ('UnresumableWriteGroup', e.write_groups, e.reason))
 
1091
            else:
 
1092
                repository.suspend_write_group()
 
1093
        finally:
 
1094
            repository.unlock()
 
1095
        return SuccessfulSmartServerResponse(('ok', ))
 
1096
 
 
1097
 
 
1098
class SmartServerRepositoryAllRevisionIds(SmartServerRepositoryRequest):
 
1099
    """Retrieve all of the revision ids in a repository.
 
1100
 
 
1101
    New in 2.5.
 
1102
    """
 
1103
 
 
1104
    def do_repository_request(self, repository):
 
1105
        revids = repository.all_revision_ids()
 
1106
        return SuccessfulSmartServerResponse(("ok", ), "\n".join(revids))
 
1107
 
 
1108
 
 
1109
class SmartServerRepositoryReconcile(SmartServerRepositoryRequest):
 
1110
    """Reconcile a repository.
 
1111
 
 
1112
    New in 2.5.
 
1113
    """
 
1114
 
 
1115
    def do_repository_request(self, repository, lock_token):
 
1116
        try:
 
1117
            repository.lock_write(token=lock_token)
 
1118
        except errors.TokenLockingNotSupported, e:
 
1119
            return FailedSmartServerResponse(
 
1120
                ('TokenLockingNotSupported', ))
 
1121
        try:
 
1122
            reconciler = repository.reconcile()
 
1123
        finally:
 
1124
            repository.unlock()
 
1125
        body = [
 
1126
            "garbage_inventories: %d\n" % reconciler.garbage_inventories,
 
1127
            "inconsistent_parents: %d\n" % reconciler.inconsistent_parents,
 
1128
            ]
 
1129
        return SuccessfulSmartServerResponse(('ok', ), "".join(body))
 
1130
 
 
1131
 
 
1132
class SmartServerRepositoryPack(SmartServerRepositoryRequest):
 
1133
    """Pack a repository.
 
1134
 
 
1135
    New in 2.5.
 
1136
    """
 
1137
 
 
1138
    def do_repository_request(self, repository, lock_token, clean_obsolete_packs):
 
1139
        self._repository = repository
 
1140
        self._lock_token = lock_token
 
1141
        if clean_obsolete_packs == 'True':
 
1142
            self._clean_obsolete_packs = True
 
1143
        else:
 
1144
            self._clean_obsolete_packs = False
 
1145
        return None
 
1146
 
 
1147
    def do_body(self, body_bytes):
 
1148
        if body_bytes == "":
 
1149
            hint = None
 
1150
        else:
 
1151
            hint = body_bytes.splitlines()
 
1152
        self._repository.lock_write(token=self._lock_token)
 
1153
        try:
 
1154
            self._repository.pack(hint, self._clean_obsolete_packs)
 
1155
        finally:
 
1156
            self._repository.unlock()
 
1157
        return SuccessfulSmartServerResponse(("ok", ), )
 
1158
 
 
1159
 
 
1160
class SmartServerRepositoryIterFilesBytes(SmartServerRepositoryRequest):
 
1161
    """Iterate over the contents of files.
 
1162
 
 
1163
    The client sends a list of desired files to stream, one
 
1164
    per line, and as tuples of file id and revision, separated by
 
1165
    \0.
 
1166
 
 
1167
    The server replies with a stream. Each entry is preceded by a header,
 
1168
    which can either be:
 
1169
 
 
1170
    * "ok\x00IDX\n" where IDX is the index of the entry in the desired files
 
1171
        list sent by the client. This header is followed by the contents of
 
1172
        the file, bzip2-compressed.
 
1173
    * "absent\x00FILEID\x00REVISION\x00IDX" to indicate a text is missing.
 
1174
        The client can then raise an appropriate RevisionNotPresent error
 
1175
        or check its fallback repositories.
 
1176
 
 
1177
    New in 2.5.
 
1178
    """
 
1179
 
 
1180
    def body_stream(self, repository, desired_files):
 
1181
        self._repository.lock_read()
 
1182
        try:
 
1183
            text_keys = {}
 
1184
            for i, key in enumerate(desired_files):
 
1185
                text_keys[key] = i
 
1186
            for record in repository.texts.get_record_stream(text_keys,
 
1187
                    'unordered', True):
 
1188
                identifier = text_keys[record.key]
 
1189
                if record.storage_kind == 'absent':
 
1190
                    yield "absent\0%s\0%s\0%d\n" % (record.key[0],
 
1191
                        record.key[1], identifier)
 
1192
                    # FIXME: Way to abort early?
 
1193
                    continue
 
1194
                yield "ok\0%d\n" % identifier
 
1195
                compressor = zlib.compressobj()
 
1196
                for bytes in record.get_bytes_as('chunked'):
 
1197
                    data = compressor.compress(bytes)
 
1198
                    if data:
 
1199
                        yield data
 
1200
                data = compressor.flush()
 
1201
                if data:
 
1202
                    yield data
 
1203
        finally:
 
1204
            self._repository.unlock()
 
1205
 
 
1206
    def do_body(self, body_bytes):
 
1207
        desired_files = [
 
1208
            tuple(l.split("\0")) for l in body_bytes.splitlines()]
 
1209
        return SuccessfulSmartServerResponse(('ok', ),
 
1210
            body_stream=self.body_stream(self._repository, desired_files))
 
1211
 
 
1212
    def do_repository_request(self, repository):
 
1213
        # Signal that we want a body
 
1214
        return None
 
1215
 
 
1216
 
 
1217
class SmartServerRepositoryIterRevisions(SmartServerRepositoryRequest):
 
1218
    """Stream a list of revisions.
 
1219
 
 
1220
    The client sends a list of newline-separated revision ids in the
 
1221
    body of the request and the server replies with the serializer format,
 
1222
    and a stream of bzip2-compressed revision texts (using the specified
 
1223
    serializer format).
 
1224
 
 
1225
    Any revisions the server does not have are omitted from the stream.
 
1226
 
 
1227
    New in 2.5.
 
1228
    """
 
1229
 
 
1230
    def do_repository_request(self, repository):
 
1231
        self._repository = repository
 
1232
        # Signal there is a body
 
1233
        return None
 
1234
 
 
1235
    def do_body(self, body_bytes):
 
1236
        revision_ids = body_bytes.split("\n")
 
1237
        return SuccessfulSmartServerResponse(
 
1238
            ('ok', self._repository.get_serializer_format()),
 
1239
            body_stream=self.body_stream(self._repository, revision_ids))
 
1240
 
 
1241
    def body_stream(self, repository, revision_ids):
 
1242
        self._repository.lock_read()
 
1243
        try:
 
1244
            for record in repository.revisions.get_record_stream(
 
1245
                [(revid,) for revid in revision_ids], 'unordered', True):
 
1246
                if record.storage_kind == 'absent':
 
1247
                    continue
 
1248
                yield zlib.compress(record.get_bytes_as('fulltext'))
 
1249
        finally:
 
1250
            self._repository.unlock()
 
1251
 
 
1252
 
 
1253
class SmartServerRepositoryGetInventories(SmartServerRepositoryRequest):
 
1254
    """Get the inventory deltas for a set of revision ids.
 
1255
 
 
1256
    This accepts a list of revision ids, and then sends a chain
 
1257
    of deltas for the inventories of those revisions. The first
 
1258
    revision will be empty.
 
1259
 
 
1260
    The server writes back zlibbed serialized inventory deltas,
 
1261
    in the ordering specified. The base for each delta is the
 
1262
    inventory generated by the previous delta.
 
1263
 
 
1264
    New in 2.5.
 
1265
    """
 
1266
 
 
1267
    def _inventory_delta_stream(self, repository, ordering, revids):
 
1268
        prev_inv = _mod_inventory.Inventory(root_id=None,
 
1269
            revision_id=_mod_revision.NULL_REVISION)
 
1270
        serializer = inventory_delta.InventoryDeltaSerializer(
 
1271
            repository.supports_rich_root(),
 
1272
            repository._format.supports_tree_reference)
 
1273
        repository.lock_read()
 
1274
        try:
 
1275
            for inv, revid in repository._iter_inventories(revids, ordering):
 
1276
                if inv is None:
 
1277
                    continue
 
1278
                inv_delta = inv._make_delta(prev_inv)
 
1279
                lines = serializer.delta_to_lines(
 
1280
                    prev_inv.revision_id, inv.revision_id, inv_delta)
 
1281
                yield ChunkedContentFactory(inv.revision_id, None, None, lines)
 
1282
                prev_inv = inv
 
1283
        finally:
 
1284
            repository.unlock()
 
1285
 
 
1286
    def body_stream(self, repository, ordering, revids):
 
1287
        substream = self._inventory_delta_stream(repository,
 
1288
            ordering, revids)
 
1289
        return _stream_to_byte_stream([('inventory-deltas', substream)],
 
1290
            repository._format)
 
1291
 
 
1292
    def do_body(self, body_bytes):
 
1293
        return SuccessfulSmartServerResponse(('ok', ),
 
1294
            body_stream=self.body_stream(self._repository, self._ordering,
 
1295
                body_bytes.splitlines()))
 
1296
 
 
1297
    def do_repository_request(self, repository, ordering):
 
1298
        if ordering == 'unordered':
 
1299
            # inventory deltas for a topologically sorted stream
 
1300
            # are likely to be smaller
 
1301
            ordering = 'topological'
 
1302
        self._ordering = ordering
 
1303
        # Signal that we want a body
 
1304
        return None