~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/smart/repository.py

  • Committer: Jelmer Vernooij
  • Date: 2012-01-27 19:05:43 UTC
  • mto: This revision was merged to the branch mainline in revision 6450.
  • Revision ID: jelmer@samba.org-20120127190543-vk350mv4a0c7aug2
Fix weave test.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2006, 2007 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
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
16
 
 
17
 
"""Server-side repository related request implmentations."""
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 
16
 
 
17
"""Server-side repository related request implementations."""
 
18
 
 
19
from __future__ import absolute_import
18
20
 
19
21
import bz2
20
 
from cStringIO import StringIO
21
22
import os
 
23
import Queue
22
24
import sys
23
25
import tempfile
24
 
import tarfile
 
26
import threading
 
27
import zlib
25
28
 
26
 
from bzrlib import errors
 
29
from bzrlib import (
 
30
    bencode,
 
31
    errors,
 
32
    estimate_compressed_size,
 
33
    inventory as _mod_inventory,
 
34
    inventory_delta,
 
35
    osutils,
 
36
    pack,
 
37
    trace,
 
38
    ui,
 
39
    vf_search,
 
40
    )
27
41
from bzrlib.bzrdir import BzrDir
28
 
from bzrlib.pack import ContainerSerialiser
29
42
from bzrlib.smart.request import (
30
43
    FailedSmartServerResponse,
31
44
    SmartServerRequest,
32
45
    SuccessfulSmartServerResponse,
33
46
    )
34
 
from bzrlib.repository import _strip_NULL_ghosts
 
47
from bzrlib.repository import _strip_NULL_ghosts, network_format_registry
35
48
from bzrlib import revision as _mod_revision
 
49
from bzrlib.versionedfile import (
 
50
    ChunkedContentFactory,
 
51
    NetworkRecordStream,
 
52
    record_to_fulltext_bytes,
 
53
    )
36
54
 
37
55
 
38
56
class SmartServerRepositoryRequest(SmartServerRequest):
40
58
 
41
59
    def do(self, path, *args):
42
60
        """Execute a repository request.
43
 
        
 
61
 
44
62
        All Repository requests take a path to the repository as their first
45
63
        argument.  The repository must be at the exact path given by the
46
64
        client - no searching is done.
63
81
        # is expected)
64
82
        return None
65
83
 
66
 
    def recreate_search(self, repository, recipe_bytes):
67
 
        lines = recipe_bytes.split('\n')
 
84
    def recreate_search(self, repository, search_bytes, discard_excess=False):
 
85
        """Recreate a search from its serialised form.
 
86
 
 
87
        :param discard_excess: If True, and the search refers to data we don't
 
88
            have, just silently accept that fact - the verb calling
 
89
            recreate_search trusts that clients will look for missing things
 
90
            they expected and get it from elsewhere.
 
91
        """
 
92
        if search_bytes == 'everything':
 
93
            return vf_search.EverythingResult(repository), None
 
94
        lines = search_bytes.split('\n')
 
95
        if lines[0] == 'ancestry-of':
 
96
            heads = lines[1:]
 
97
            search_result = vf_search.PendingAncestryResult(heads, repository)
 
98
            return search_result, None
 
99
        elif lines[0] == 'search':
 
100
            return self.recreate_search_from_recipe(repository, lines[1:],
 
101
                discard_excess=discard_excess)
 
102
        else:
 
103
            return (None, FailedSmartServerResponse(('BadSearch',)))
 
104
 
 
105
    def recreate_search_from_recipe(self, repository, lines,
 
106
        discard_excess=False):
 
107
        """Recreate a specific revision search (vs a from-tip search).
 
108
 
 
109
        :param discard_excess: If True, and the search refers to data we don't
 
110
            have, just silently accept that fact - the verb calling
 
111
            recreate_search trusts that clients will look for missing things
 
112
            they expected and get it from elsewhere.
 
113
        """
68
114
        start_keys = set(lines[0].split(' '))
69
115
        exclude_keys = set(lines[1].split(' '))
70
116
        revision_count = int(lines[2])
78
124
                except StopIteration:
79
125
                    break
80
126
                search.stop_searching_any(exclude_keys.intersection(next_revs))
81
 
            search_result = search.get_result()
82
 
            if search_result.get_recipe()[2] != revision_count:
 
127
            (started_keys, excludes, included_keys) = search.get_state()
 
128
            if (not discard_excess and len(included_keys) != revision_count):
83
129
                # we got back a different amount of data than expected, this
84
130
                # gets reported as NoSuchRevision, because less revisions
85
131
                # indicates missing revisions, and more should never happen as
86
132
                # the excludes list considers ghosts and ensures that ghost
87
133
                # filling races are not a problem.
88
134
                return (None, FailedSmartServerResponse(('NoSuchRevision',)))
89
 
            return (search, None)
 
135
            search_result = vf_search.SearchResult(started_keys, excludes,
 
136
                len(included_keys), included_keys)
 
137
            return (search_result, None)
90
138
        finally:
91
139
            repository.unlock()
92
140
 
103
151
            repository.unlock()
104
152
 
105
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
 
106
164
class SmartServerRepositoryGetParentMap(SmartServerRepositoryRequest):
107
165
    """Bzr 1.2+ - get parent data for revisions during a graph search."""
108
 
    
 
166
 
 
167
    no_extra_results = False
 
168
 
109
169
    def do_repository_request(self, repository, *revision_ids):
110
170
        """Get parent details for some revisions.
111
 
        
 
171
 
112
172
        All the parents for revision_ids are returned. Additionally up to 64KB
113
173
        of additional parent data found by performing a breadth first search
114
174
        from revision_ids is returned. The verb takes a body containing the
115
175
        current search state, see do_body for details.
116
176
 
 
177
        If 'include-missing:' is in revision_ids, ghosts encountered in the
 
178
        graph traversal for getting parent data are included in the result with
 
179
        a prefix of 'missing:'.
 
180
 
117
181
        :param repository: The repository to query in.
118
182
        :param revision_ids: The utf8 encoded revision_id to answer for.
119
183
        """
135
199
        finally:
136
200
            repository.unlock()
137
201
 
138
 
    def _do_repository_request(self, body_bytes):
139
 
        repository = self._repository
140
 
        revision_ids = set(self._revision_ids)
141
 
        search, error = self.recreate_search(repository, body_bytes)
142
 
        if error is not None:
143
 
            return error
144
 
        # TODO might be nice to start up the search again; but thats not
145
 
        # written or tested yet.
146
 
        client_seen_revs = set(search.get_result().get_keys())
147
 
        # Always include the requested ids.
148
 
        client_seen_revs.difference_update(revision_ids)
149
 
        lines = []
150
 
        repo_graph = repository.get_graph()
 
202
    def _expand_requested_revs(self, repo_graph, revision_ids, client_seen_revs,
 
203
                               include_missing, max_size=65536):
151
204
        result = {}
152
205
        queried_revs = set()
153
 
        size_so_far = 0
 
206
        estimator = estimate_compressed_size.ZLibEstimator(max_size)
154
207
        next_revs = revision_ids
155
208
        first_loop_done = False
156
209
        while next_revs:
157
210
            queried_revs.update(next_revs)
158
211
            parent_map = repo_graph.get_parent_map(next_revs)
 
212
            current_revs = next_revs
159
213
            next_revs = set()
160
 
            for revision_id, parents in parent_map.iteritems():
161
 
                # adjust for the wire
162
 
                if parents == (_mod_revision.NULL_REVISION,):
163
 
                    parents = ()
164
 
                # prepare the next query
165
 
                next_revs.update(parents)
166
 
                if revision_id not in client_seen_revs:
 
214
            for revision_id in current_revs:
 
215
                missing_rev = False
 
216
                parents = parent_map.get(revision_id)
 
217
                if parents is not None:
 
218
                    # adjust for the wire
 
219
                    if parents == (_mod_revision.NULL_REVISION,):
 
220
                        parents = ()
 
221
                    # prepare the next query
 
222
                    next_revs.update(parents)
 
223
                    encoded_id = revision_id
 
224
                else:
 
225
                    missing_rev = True
 
226
                    encoded_id = "missing:" + revision_id
 
227
                    parents = []
 
228
                if (revision_id not in client_seen_revs and
 
229
                    (not missing_rev or include_missing)):
167
230
                    # Client does not have this revision, give it to it.
168
231
                    # add parents to the result
169
 
                    result[revision_id] = parents
 
232
                    result[encoded_id] = parents
170
233
                    # Approximate the serialized cost of this revision_id.
171
 
                    size_so_far += 2 + len(revision_id) + sum(map(len, parents))
 
234
                    line = '%s %s\n' % (encoded_id, ' '.join(parents))
 
235
                    estimator.add_content(line)
172
236
            # get all the directly asked for parents, and then flesh out to
173
237
            # 64K (compressed) or so. We do one level of depth at a time to
174
238
            # stay in sync with the client. The 250000 magic number is
175
239
            # estimated compression ratio taken from bzr.dev itself.
176
 
            if 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))
177
244
                next_revs = set()
178
245
                break
179
246
            # don't query things we've already queried
180
 
            next_revs.difference_update(queried_revs)
 
247
            next_revs = next_revs.difference(queried_revs)
181
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)
182
271
 
183
272
        # sorting trivially puts lexographically similar revision ids together.
184
273
        # Compression FTW.
 
274
        lines = []
185
275
        for revision, parents in sorted(result.items()):
186
276
            lines.append(' '.join((revision, ) + tuple(parents)))
187
277
 
190
280
 
191
281
 
192
282
class SmartServerRepositoryGetRevisionGraph(SmartServerRepositoryReadLocked):
193
 
    
 
283
 
194
284
    def do_readlocked_repository_request(self, repository, revision_id):
195
285
        """Return the result of repository.get_revision_graph(revision_id).
196
286
 
197
287
        Deprecated as of bzr 1.4, but supported for older clients.
198
 
        
 
288
 
199
289
        :param repository: The repository to query in.
200
290
        :param revision_id: The utf8 encoded revision_id to get a graph from.
201
291
        :return: A smart server response where the body contains an utf8
227
317
        return SuccessfulSmartServerResponse(('ok', ), '\n'.join(lines))
228
318
 
229
319
 
230
 
class SmartServerRepositoryGraphHeads(SmartServerRepositoryRequest):
 
320
class SmartServerRepositoryGetRevIdForRevno(SmartServerRepositoryReadLocked):
231
321
 
232
 
    def do_repository_request(self, repository, *keys):
233
 
        repository.lock_read()
 
322
    def do_readlocked_repository_request(self, repository, revno,
 
323
            known_pair):
 
324
        """Find the revid for a given revno, given a known revno/revid pair.
 
325
        
 
326
        New in 1.17.
 
327
        """
234
328
        try:
235
 
            graph = repository.get_graph()
236
 
            heads = tuple(graph.heads(keys))
237
 
        finally:
238
 
            repository.unlock()
239
 
        return SuccessfulSmartServerResponse(heads)
 
329
            found_flag, result = repository.get_rev_id_for_revno(revno, known_pair)
 
330
        except errors.RevisionNotPresent, err:
 
331
            if err.revision_id != known_pair[1]:
 
332
                raise AssertionError(
 
333
                    'get_rev_id_for_revno raised RevisionNotPresent for '
 
334
                    'non-initial revision: ' + err.revision_id)
 
335
            return FailedSmartServerResponse(
 
336
                ('nosuchrevision', err.revision_id))
 
337
        if found_flag:
 
338
            return SuccessfulSmartServerResponse(('ok', result))
 
339
        else:
 
340
            earliest_revno, earliest_revid = result
 
341
            return SuccessfulSmartServerResponse(
 
342
                ('history-incomplete', earliest_revno, earliest_revid))
 
343
 
 
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))
240
357
 
241
358
 
242
359
class SmartServerRequestHasRevision(SmartServerRepositoryRequest):
246
363
 
247
364
        :param repository: The repository to query in.
248
365
        :param revision_id: The utf8 encoded revision_id to lookup.
249
 
        :return: A smart server response of ('ok', ) if the revision is
250
 
            present.
 
366
        :return: A smart server response of ('yes', ) if the revision is
 
367
            present. ('no', ) if it is missing.
251
368
        """
252
369
        if repository.has_revision(revision_id):
253
370
            return SuccessfulSmartServerResponse(('yes', ))
255
372
            return SuccessfulSmartServerResponse(('no', ))
256
373
 
257
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
 
258
399
class SmartServerRepositoryGatherStats(SmartServerRepositoryRequest):
259
400
 
260
401
    def do_repository_request(self, repository, revid, committers):
269
410
              firstrev: 1234.230 0
270
411
              latestrev: 345.700 3600
271
412
              revisions: 2
272
 
              size:45
273
413
 
274
414
              But containing only fields returned by the gather_stats() call
275
415
        """
281
421
            decoded_committers = True
282
422
        else:
283
423
            decoded_committers = None
284
 
        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))
285
429
 
286
430
        body = ''
287
431
        if stats.has_key('committers'):
298
442
        return SuccessfulSmartServerResponse(('ok', ), body)
299
443
 
300
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
 
301
467
class SmartServerRepositoryIsShared(SmartServerRepositoryRequest):
302
468
 
303
469
    def do_repository_request(self, repository):
313
479
            return SuccessfulSmartServerResponse(('no', ))
314
480
 
315
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
 
316
499
class SmartServerRepositoryLockWrite(SmartServerRepositoryRequest):
317
500
 
318
501
    def do_repository_request(self, repository, token=''):
320
503
        if token == '':
321
504
            token = None
322
505
        try:
323
 
            token = repository.lock_write(token=token)
 
506
            token = repository.lock_write(token=token).repository_token
324
507
        except errors.LockContention, e:
325
508
            return FailedSmartServerResponse(('LockContention',))
326
509
        except errors.UnlockableTransport:
336
519
        return SuccessfulSmartServerResponse(('ok', token))
337
520
 
338
521
 
 
522
class SmartServerRepositoryGetStream(SmartServerRepositoryRequest):
 
523
 
 
524
    def do_repository_request(self, repository, to_network_name):
 
525
        """Get a stream for inserting into a to_format repository.
 
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
 
 
534
        :param repository: The repository to stream from.
 
535
        :param to_network_name: The network name of the format of the target
 
536
            repository.
 
537
        """
 
538
        self._to_format = network_format_registry.get(to_network_name)
 
539
        if self._should_fake_unknown():
 
540
            return FailedSmartServerResponse(
 
541
                ('UnknownMethod', 'Repository.get_stream'))
 
542
        return None # Signal that we want a body.
 
543
 
 
544
    def _should_fake_unknown(self):
 
545
        """Return True if we should return UnknownMethod to the client.
 
546
        
 
547
        This is a workaround for bugs in pre-1.19 clients that claim to
 
548
        support receiving streams of CHK repositories.  The pre-1.19 client
 
549
        expects inventory records to be serialized in the format defined by
 
550
        to_network_name, but in pre-1.19 (at least) that format definition
 
551
        tries to use the xml5 serializer, which does not correctly handle
 
552
        rich-roots.  After 1.19 the client can also accept inventory-deltas
 
553
        (which avoids this issue), and those clients will use the
 
554
        Repository.get_stream_1.19 verb instead of this one.
 
555
        So: if this repository is CHK, and the to_format doesn't match,
 
556
        we should just fake an UnknownSmartMethod error so that the client
 
557
        will fallback to VFS, rather than sending it a stream we know it
 
558
        cannot handle.
 
559
        """
 
560
        from_format = self._repository._format
 
561
        to_format = self._to_format
 
562
        if not from_format.supports_chks:
 
563
            # Source not CHK: that's ok
 
564
            return False
 
565
        if (to_format.supports_chks and
 
566
            from_format.repository_class is to_format.repository_class and
 
567
            from_format._serializer == to_format._serializer):
 
568
            # Source is CHK, but target matches: that's ok
 
569
            # (e.g. 2a->2a, or CHK2->2a)
 
570
            return False
 
571
        # Source is CHK, and target is not CHK or incompatible CHK.  We can't
 
572
        # generate a compatible stream.
 
573
        return True
 
574
 
 
575
    def do_body(self, body_bytes):
 
576
        repository = self._repository
 
577
        repository.lock_read()
 
578
        try:
 
579
            search_result, error = self.recreate_search(repository, body_bytes,
 
580
                discard_excess=True)
 
581
            if error is not None:
 
582
                repository.unlock()
 
583
                return error
 
584
            source = repository._get_source(self._to_format)
 
585
            stream = source.get_stream(search_result)
 
586
        except Exception:
 
587
            exc_info = sys.exc_info()
 
588
            try:
 
589
                # On non-error, unlocking is done by the body stream handler.
 
590
                repository.unlock()
 
591
            finally:
 
592
                raise exc_info[0], exc_info[1], exc_info[2]
 
593
        return SuccessfulSmartServerResponse(('ok',),
 
594
            body_stream=self.body_stream(stream, repository))
 
595
 
 
596
    def body_stream(self, stream, repository):
 
597
        byte_stream = _stream_to_byte_stream(stream, repository._format)
 
598
        try:
 
599
            for bytes in byte_stream:
 
600
                yield bytes
 
601
        except errors.RevisionNotPresent, e:
 
602
            # This shouldn't be able to happen, but as we don't buffer
 
603
            # everything it can in theory happen.
 
604
            repository.unlock()
 
605
            yield FailedSmartServerResponse(('NoSuchRevision', e.revision_id))
 
606
        else:
 
607
            repository.unlock()
 
608
 
 
609
 
 
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
    """
 
618
 
 
619
    def _should_fake_unknown(self):
 
620
        """Returns False; we don't need to workaround bugs in 1.19+ clients."""
 
621
        return False
 
622
 
 
623
 
 
624
def _stream_to_byte_stream(stream, src_format):
 
625
    """Convert a record stream to a self delimited byte stream."""
 
626
    pack_writer = pack.ContainerSerialiser()
 
627
    yield pack_writer.begin()
 
628
    yield pack_writer.bytes_record(src_format.network_name(), '')
 
629
    for substream_type, substream in stream:
 
630
        for record in substream:
 
631
            if record.storage_kind in ('chunked', 'fulltext'):
 
632
                serialised = record_to_fulltext_bytes(record)
 
633
            elif record.storage_kind == 'absent':
 
634
                raise ValueError("Absent factory for %s" % (record.key,))
 
635
            else:
 
636
                serialised = record.get_bytes_as(record.storage_kind)
 
637
            if serialised:
 
638
                # Some streams embed the whole stream into the wire
 
639
                # representation of the first record, which means that
 
640
                # later records have no wire representation: we skip them.
 
641
                yield pack_writer.bytes_record(serialised, [(substream_type,)])
 
642
    yield pack_writer.end()
 
643
 
 
644
 
 
645
class _ByteStreamDecoder(object):
 
646
    """Helper for _byte_stream_to_stream.
 
647
 
 
648
    The expected usage of this class is via the function _byte_stream_to_stream
 
649
    which creates a _ByteStreamDecoder, pops off the stream format and then
 
650
    yields the output of record_stream(), the main entry point to
 
651
    _ByteStreamDecoder.
 
652
 
 
653
    Broadly this class has to unwrap two layers of iterators:
 
654
    (type, substream)
 
655
    (substream details)
 
656
 
 
657
    This is complicated by wishing to return type, iterator_for_type, but
 
658
    getting the data for iterator_for_type when we find out type: we can't
 
659
    simply pass a generator down to the NetworkRecordStream parser, instead
 
660
    we have a little local state to seed each NetworkRecordStream instance,
 
661
    and gather the type that we'll be yielding.
 
662
 
 
663
    :ivar byte_stream: The byte stream being decoded.
 
664
    :ivar stream_decoder: A pack parser used to decode the bytestream
 
665
    :ivar current_type: The current type, used to join adjacent records of the
 
666
        same type into a single stream.
 
667
    :ivar first_bytes: The first bytes to give the next NetworkRecordStream.
 
668
    """
 
669
 
 
670
    def __init__(self, byte_stream, record_counter):
 
671
        """Create a _ByteStreamDecoder."""
 
672
        self.stream_decoder = pack.ContainerPushParser()
 
673
        self.current_type = None
 
674
        self.first_bytes = None
 
675
        self.byte_stream = byte_stream
 
676
        self._record_counter = record_counter
 
677
        self.key_count = 0
 
678
 
 
679
    def iter_stream_decoder(self):
 
680
        """Iterate the contents of the pack from stream_decoder."""
 
681
        # dequeue pending items
 
682
        for record in self.stream_decoder.read_pending_records():
 
683
            yield record
 
684
        # Pull bytes of the wire, decode them to records, yield those records.
 
685
        for bytes in self.byte_stream:
 
686
            self.stream_decoder.accept_bytes(bytes)
 
687
            for record in self.stream_decoder.read_pending_records():
 
688
                yield record
 
689
 
 
690
    def iter_substream_bytes(self):
 
691
        if self.first_bytes is not None:
 
692
            yield self.first_bytes
 
693
            # If we run out of pack records, single the outer layer to stop.
 
694
            self.first_bytes = None
 
695
        for record in self.iter_pack_records:
 
696
            record_names, record_bytes = record
 
697
            record_name, = record_names
 
698
            substream_type = record_name[0]
 
699
            if substream_type != self.current_type:
 
700
                # end of a substream, seed the next substream.
 
701
                self.current_type = substream_type
 
702
                self.first_bytes = record_bytes
 
703
                return
 
704
            yield record_bytes
 
705
 
 
706
    def record_stream(self):
 
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
 
 
736
        self.seed_state()
 
737
        pb = ui.ui_factory.nested_progress_bar()
 
738
        rc = self._record_counter
 
739
        # Make and consume sub generators, one per substream type:
 
740
        while self.first_bytes is not None:
 
741
            substream = NetworkRecordStream(self.iter_substream_bytes())
 
742
            # after substream is fully consumed, self.current_type is set to
 
743
            # the next type, and self.first_bytes is set to the matching bytes.
 
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()
 
748
 
 
749
    def seed_state(self):
 
750
        """Prepare the _ByteStreamDecoder to decode from the pack stream."""
 
751
        # Set a single generator we can use to get data from the pack stream.
 
752
        self.iter_pack_records = self.iter_stream_decoder()
 
753
        # Seed the very first subiterator with content; after this each one
 
754
        # seeds the next.
 
755
        list(self.iter_substream_bytes())
 
756
 
 
757
 
 
758
def _byte_stream_to_stream(byte_stream, record_counter=None):
 
759
    """Convert a byte stream into a format and a stream.
 
760
 
 
761
    :param byte_stream: A bytes iterator, as output by _stream_to_byte_stream.
 
762
    :return: (RepositoryFormat, stream_generator)
 
763
    """
 
764
    decoder = _ByteStreamDecoder(byte_stream, record_counter)
 
765
    for bytes in byte_stream:
 
766
        decoder.stream_decoder.accept_bytes(bytes)
 
767
        for record in decoder.stream_decoder.read_pending_records(max=1):
 
768
            record_names, src_format_name = record
 
769
            src_format = network_format_registry.get(src_format_name)
 
770
            return src_format, decoder.record_stream()
 
771
 
 
772
 
339
773
class SmartServerRepositoryUnlock(SmartServerRepositoryRequest):
340
774
 
341
775
    def do_repository_request(self, repository, token):
348
782
        return SuccessfulSmartServerResponse(('ok',))
349
783
 
350
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
 
 
798
class SmartServerRepositorySetMakeWorkingTrees(SmartServerRepositoryRequest):
 
799
 
 
800
    def do_repository_request(self, repository, str_bool_new_value):
 
801
        if str_bool_new_value == 'True':
 
802
            new_value = True
 
803
        else:
 
804
            new_value = False
 
805
        repository.set_make_working_trees(new_value)
 
806
        return SuccessfulSmartServerResponse(('ok',))
 
807
 
 
808
 
351
809
class SmartServerRepositoryTarball(SmartServerRepositoryRequest):
352
810
    """Get the raw repository files as a tarball.
353
811
 
354
812
    The returned tarball contains a .bzr control directory which in turn
355
813
    contains a repository.
356
 
    
357
 
    This takes one parameter, compression, which currently must be 
 
814
 
 
815
    This takes one parameter, compression, which currently must be
358
816
    "", "gz", or "bz2".
359
817
 
360
818
    This is used to implement the Repository.copy_content_into operation.
361
819
    """
362
820
 
363
821
    def do_repository_request(self, repository, compression):
364
 
        from bzrlib import osutils
365
 
        repo_transport = repository.control_files._transport
366
822
        tmp_dirname, tmp_repo = self._copy_to_tempdir(repository)
367
823
        try:
368
824
            controldir_name = tmp_dirname + '/.bzr'
371
827
            osutils.rmtree(tmp_dirname)
372
828
 
373
829
    def _copy_to_tempdir(self, from_repo):
374
 
        tmp_dirname = tempfile.mkdtemp(prefix='tmpbzrclone')
 
830
        tmp_dirname = osutils.mkdtemp(prefix='tmpbzrclone')
375
831
        tmp_bzrdir = from_repo.bzrdir._format.initialize(tmp_dirname)
376
832
        tmp_repo = from_repo._format.initialize(tmp_bzrdir)
377
833
        from_repo.copy_content_into(tmp_repo)
384
840
            # all finished; write the tempfile out to the network
385
841
            temp.seek(0)
386
842
            return SuccessfulSmartServerResponse(('ok',), temp.read())
387
 
            # FIXME: Don't read the whole thing into memory here; rather stream it
388
 
            # out from the file onto the network. mbp 20070411
 
843
            # FIXME: Don't read the whole thing into memory here; rather stream
 
844
            # it out from the file onto the network. mbp 20070411
389
845
        finally:
390
846
            temp.close()
391
847
 
392
848
    def _tarball_of_dir(self, dirname, compression, ofile):
 
849
        import tarfile
393
850
        filename = os.path.basename(ofile.name)
394
851
        tarball = tarfile.open(fileobj=ofile, name=filename,
395
852
            mode='w|' + compression)
408
865
            tarball.close()
409
866
 
410
867
 
411
 
class SmartServerRepositoryStreamKnitDataForRevisions(SmartServerRepositoryRequest):
412
 
    """Bzr <= 1.1 streaming pull, buffers all data on server."""
413
 
 
414
 
    def do_repository_request(self, repository, *revision_ids):
415
 
        repository.lock_read()
416
 
        try:
417
 
            return self._do_repository_request(repository, revision_ids)
418
 
        finally:
419
 
            repository.unlock()
420
 
 
421
 
    def _do_repository_request(self, repository, revision_ids):
422
 
        stream = repository.get_data_stream_for_search(
423
 
            repository.revision_ids_to_search_result(set(revision_ids)))
424
 
        buffer = StringIO()
425
 
        pack = ContainerSerialiser()
426
 
        buffer.write(pack.begin())
427
 
        try:
428
 
            for name_tuple, bytes in stream:
429
 
                buffer.write(pack.bytes_record(bytes, [name_tuple]))
430
 
        except errors.RevisionNotPresent, e:
431
 
            return FailedSmartServerResponse(('NoSuchRevision', e.revision_id))
432
 
        buffer.write(pack.end())
433
 
        return SuccessfulSmartServerResponse(('ok',), buffer.getvalue())
434
 
 
435
 
 
436
 
class SmartServerRepositoryStreamRevisionsChunked(SmartServerRepositoryRequest):
437
 
    """Bzr 1.1+ streaming pull."""
 
868
class SmartServerRepositoryInsertStreamLocked(SmartServerRepositoryRequest):
 
869
    """Insert a record stream from a RemoteSink into a repository.
 
870
 
 
871
    This gets bytes pushed to it by the network infrastructure and turns that
 
872
    into a bytes iterator using a thread. That is then processed by
 
873
    _byte_stream_to_stream.
 
874
 
 
875
    New in 1.14.
 
876
    """
 
877
 
 
878
    def do_repository_request(self, repository, resume_tokens, lock_token):
 
879
        """StreamSink.insert_stream for a remote repository."""
 
880
        repository.lock_write(token=lock_token)
 
881
        self.do_insert_stream_request(repository, resume_tokens)
 
882
 
 
883
    def do_insert_stream_request(self, repository, resume_tokens):
 
884
        tokens = [token for token in resume_tokens.split(' ') if token]
 
885
        self.tokens = tokens
 
886
        self.repository = repository
 
887
        self.queue = Queue.Queue()
 
888
        self.insert_thread = threading.Thread(target=self._inserter_thread)
 
889
        self.insert_thread.start()
 
890
 
 
891
    def do_chunk(self, body_stream_chunk):
 
892
        self.queue.put(body_stream_chunk)
 
893
 
 
894
    def _inserter_thread(self):
 
895
        try:
 
896
            src_format, stream = _byte_stream_to_stream(
 
897
                self.blocking_byte_stream())
 
898
            self.insert_result = self.repository._get_sink().insert_stream(
 
899
                stream, src_format, self.tokens)
 
900
            self.insert_ok = True
 
901
        except:
 
902
            self.insert_exception = sys.exc_info()
 
903
            self.insert_ok = False
 
904
 
 
905
    def blocking_byte_stream(self):
 
906
        while True:
 
907
            bytes = self.queue.get()
 
908
            if bytes is StopIteration:
 
909
                return
 
910
            else:
 
911
                yield bytes
 
912
 
 
913
    def do_end(self):
 
914
        self.queue.put(StopIteration)
 
915
        if self.insert_thread is not None:
 
916
            self.insert_thread.join()
 
917
        if not self.insert_ok:
 
918
            exc_info = self.insert_exception
 
919
            raise exc_info[0], exc_info[1], exc_info[2]
 
920
        write_group_tokens, missing_keys = self.insert_result
 
921
        if write_group_tokens or missing_keys:
 
922
            # bzip needed? missing keys should typically be a small set.
 
923
            # Should this be a streaming body response ?
 
924
            missing_keys = sorted(missing_keys)
 
925
            bytes = bencode.bencode((write_group_tokens, missing_keys))
 
926
            self.repository.unlock()
 
927
            return SuccessfulSmartServerResponse(('missing-basis', bytes))
 
928
        else:
 
929
            self.repository.unlock()
 
930
            return SuccessfulSmartServerResponse(('ok', ))
 
931
 
 
932
 
 
933
class SmartServerRepositoryInsertStream_1_19(SmartServerRepositoryInsertStreamLocked):
 
934
    """Insert a record stream from a RemoteSink into a repository.
 
935
 
 
936
    Same as SmartServerRepositoryInsertStreamLocked, except:
 
937
     - the lock token argument is optional
 
938
     - servers that implement this verb accept 'inventory-delta' records in the
 
939
       stream.
 
940
 
 
941
    New in 1.19.
 
942
    """
 
943
 
 
944
    def do_repository_request(self, repository, resume_tokens, lock_token=None):
 
945
        """StreamSink.insert_stream for a remote repository."""
 
946
        SmartServerRepositoryInsertStreamLocked.do_repository_request(
 
947
            self, repository, resume_tokens, lock_token)
 
948
 
 
949
 
 
950
class SmartServerRepositoryInsertStream(SmartServerRepositoryInsertStreamLocked):
 
951
    """Insert a record stream from a RemoteSink into an unlocked repository.
 
952
 
 
953
    This is the same as SmartServerRepositoryInsertStreamLocked, except it
 
954
    takes no lock_tokens; i.e. it works with an unlocked (or lock-free, e.g.
 
955
    like pack format) repository.
 
956
 
 
957
    New in 1.13.
 
958
    """
 
959
 
 
960
    def do_repository_request(self, repository, resume_tokens):
 
961
        """StreamSink.insert_stream for a remote repository."""
 
962
        repository.lock_write()
 
963
        self.do_insert_stream_request(repository, resume_tokens)
 
964
 
 
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
438
985
 
439
986
    def do_body(self, body_bytes):
440
 
        repository = self._repository
441
 
        repository.lock_read()
442
 
        try:
443
 
            search, error = self.recreate_search(repository, body_bytes)
444
 
            if error is not None:
445
 
                repository.unlock()
446
 
                return error
447
 
            stream = repository.get_data_stream_for_search(search.get_result())
448
 
        except Exception:
449
 
            # On non-error, unlocking is done by the body stream handler.
 
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:
450
1023
            repository.unlock()
451
 
            raise
452
 
        return SuccessfulSmartServerResponse(('ok',),
453
 
            body_stream=self.body_stream(stream, repository))
454
 
 
455
 
    def body_stream(self, stream, repository):
456
 
        pack = ContainerSerialiser()
457
 
        yield pack.begin()
 
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)
458
1037
        try:
459
1038
            try:
460
 
                for name_tuple, bytes in stream:
461
 
                    yield pack.bytes_record(bytes, [name_tuple])
 
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()
462
1045
            except:
463
 
                # Undo the lock_read that that happens once the iterator from
464
 
                # get_data_stream is started.
465
 
                repository.unlock()
 
1046
                write_group_tokens = repository.suspend_write_group()
 
1047
                # FIXME JRV 2011-11-19: What if the write_group_tokens
 
1048
                # have changed?
466
1049
                raise
467
 
        except errors.RevisionNotPresent, e:
468
 
            # This shouldn't be able to happen, but as we don't buffer
469
 
            # everything it can in theory happen.
470
 
            repository.unlock()
471
 
            yield FailedSmartServerResponse(('NoSuchRevision', e.revision_id))
472
 
        else:
473
 
            repository.unlock()
474
 
            pack.end()
475
 
 
 
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