~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/repofmt/pack_repo.py

  • Committer: Vincent Ladeuil
  • Date: 2007-11-24 14:20:59 UTC
  • mto: (3928.1.1 bzr.integration)
  • mto: This revision was merged to the branch mainline in revision 3929.
  • Revision ID: v.ladeuil+lp@free.fr-20071124142059-2114qtsgfdv8g9p1
Ssl files needed for the test https server.

* bzrlib/tests/ssl_certs/create_ssls.py: 
Script to create the ssl keys and certificates.

* bzrlib/tests/ssl_certs/server.crt: 
Server certificate signed by the certificate authority.

* bzrlib/tests/ssl_certs/server.csr: 
Server certificate signing request.

* bzrlib/tests/ssl_certs/server_without_pass.key: 
Server key usable without password.

* bzrlib/tests/ssl_certs/server_with_pass.key: 
Server key.

* bzrlib/tests/ssl_certs/ca.key: 
Certificate authority private key.

* bzrlib/tests/ssl_certs/ca.crt: 
Certificate authority certificate.

* bzrlib/tests/ssl_certs/__init__.py: 
Provide access to ssl files (keys and certificates). 

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# Copyright (C) 2005, 2006, 2007 Canonical Ltd
 
2
#
 
3
# This program is free software; you can redistribute it and/or modify
 
4
# it under the terms of the GNU General Public License as published by
 
5
# the Free Software Foundation; either version 2 of the License, or
 
6
# (at your option) any later version.
 
7
#
 
8
# This program is distributed in the hope that it will be useful,
 
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
11
# GNU General Public License for more details.
 
12
#
 
13
# You should have received a copy of the GNU General Public License
 
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
from bzrlib.lazy_import import lazy_import
 
18
lazy_import(globals(), """
 
19
from itertools import izip
 
20
import math
 
21
import time
 
22
 
 
23
from bzrlib import (
 
24
        debug,
 
25
        osutils,
 
26
        pack,
 
27
        ui,
 
28
        )
 
29
from bzrlib.index import (
 
30
    CombinedGraphIndex,
 
31
    InMemoryGraphIndex,
 
32
    GraphIndex,
 
33
    GraphIndexBuilder,
 
34
    GraphIndexPrefixAdapter,
 
35
    )
 
36
from bzrlib.knit import KnitGraphIndex, _PackAccess, _KnitData
 
37
from bzrlib.pack import ContainerWriter
 
38
from bzrlib.store import revision
 
39
""")
 
40
from bzrlib import (
 
41
    bzrdir,
 
42
    deprecated_graph,
 
43
    errors,
 
44
    knit,
 
45
    lockable_files,
 
46
    lockdir,
 
47
    osutils,
 
48
    transactions,
 
49
    xml5,
 
50
    xml7,
 
51
    )
 
52
 
 
53
from bzrlib.decorators import needs_read_lock, needs_write_lock
 
54
from bzrlib.repofmt.knitrepo import KnitRepository
 
55
from bzrlib.repository import (
 
56
    CommitBuilder,
 
57
    MetaDirRepository,
 
58
    MetaDirRepositoryFormat,
 
59
    RootCommitBuilder,
 
60
    )
 
61
import bzrlib.revision as _mod_revision
 
62
from bzrlib.store.revision.knit import KnitRevisionStore
 
63
from bzrlib.store.versioned import VersionedFileStore
 
64
from bzrlib.trace import mutter, note, warning
 
65
 
 
66
 
 
67
class PackCommitBuilder(CommitBuilder):
 
68
    """A subclass of CommitBuilder to add texts with pack semantics.
 
69
    
 
70
    Specifically this uses one knit object rather than one knit object per
 
71
    added text, reducing memory and object pressure.
 
72
    """
 
73
 
 
74
    def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
 
75
        return self.repository._pack_collection._add_text_to_weave(file_id,
 
76
            self._new_revision_id, new_lines, parents, nostore_sha,
 
77
            self.random_revid)
 
78
 
 
79
 
 
80
class PackRootCommitBuilder(RootCommitBuilder):
 
81
    """A subclass of RootCommitBuilder to add texts with pack semantics.
 
82
    
 
83
    Specifically this uses one knit object rather than one knit object per
 
84
    added text, reducing memory and object pressure.
 
85
    """
 
86
 
 
87
    def _add_text_to_weave(self, file_id, new_lines, parents, nostore_sha):
 
88
        return self.repository._pack_collection._add_text_to_weave(file_id,
 
89
            self._new_revision_id, new_lines, parents, nostore_sha,
 
90
            self.random_revid)
 
91
 
 
92
 
 
93
class Pack(object):
 
94
    """An in memory proxy for a pack and its indices.
 
95
 
 
96
    This is a base class that is not directly used, instead the classes
 
97
    ExistingPack and NewPack are used.
 
98
    """
 
99
 
 
100
    def __init__(self, revision_index, inventory_index, text_index,
 
101
        signature_index):
 
102
        """Create a pack instance.
 
103
 
 
104
        :param revision_index: A GraphIndex for determining what revisions are
 
105
            present in the Pack and accessing the locations of their texts.
 
106
        :param inventory_index: A GraphIndex for determining what inventories are
 
107
            present in the Pack and accessing the locations of their
 
108
            texts/deltas.
 
109
        :param text_index: A GraphIndex for determining what file texts
 
110
            are present in the pack and accessing the locations of their
 
111
            texts/deltas (via (fileid, revisionid) tuples).
 
112
        :param revision_index: A GraphIndex for determining what signatures are
 
113
            present in the Pack and accessing the locations of their texts.
 
114
        """
 
115
        self.revision_index = revision_index
 
116
        self.inventory_index = inventory_index
 
117
        self.text_index = text_index
 
118
        self.signature_index = signature_index
 
119
 
 
120
    def access_tuple(self):
 
121
        """Return a tuple (transport, name) for the pack content."""
 
122
        return self.pack_transport, self.file_name()
 
123
 
 
124
    def file_name(self):
 
125
        """Get the file name for the pack on disk."""
 
126
        return self.name + '.pack'
 
127
 
 
128
    def get_revision_count(self):
 
129
        return self.revision_index.key_count()
 
130
 
 
131
    def inventory_index_name(self, name):
 
132
        """The inv index is the name + .iix."""
 
133
        return self.index_name('inventory', name)
 
134
 
 
135
    def revision_index_name(self, name):
 
136
        """The revision index is the name + .rix."""
 
137
        return self.index_name('revision', name)
 
138
 
 
139
    def signature_index_name(self, name):
 
140
        """The signature index is the name + .six."""
 
141
        return self.index_name('signature', name)
 
142
 
 
143
    def text_index_name(self, name):
 
144
        """The text index is the name + .tix."""
 
145
        return self.index_name('text', name)
 
146
 
 
147
 
 
148
class ExistingPack(Pack):
 
149
    """An in memory proxy for an existing .pack and its disk indices."""
 
150
 
 
151
    def __init__(self, pack_transport, name, revision_index, inventory_index,
 
152
        text_index, signature_index):
 
153
        """Create an ExistingPack object.
 
154
 
 
155
        :param pack_transport: The transport where the pack file resides.
 
156
        :param name: The name of the pack on disk in the pack_transport.
 
157
        """
 
158
        Pack.__init__(self, revision_index, inventory_index, text_index,
 
159
            signature_index)
 
160
        self.name = name
 
161
        self.pack_transport = pack_transport
 
162
        assert None not in (revision_index, inventory_index, text_index,
 
163
            signature_index, name, pack_transport)
 
164
 
 
165
    def __eq__(self, other):
 
166
        return self.__dict__ == other.__dict__
 
167
 
 
168
    def __ne__(self, other):
 
169
        return not self.__eq__(other)
 
170
 
 
171
    def __repr__(self):
 
172
        return "<bzrlib.repofmt.pack_repo.Pack object at 0x%x, %s, %s" % (
 
173
            id(self), self.transport, self.name)
 
174
 
 
175
 
 
176
class NewPack(Pack):
 
177
    """An in memory proxy for a pack which is being created."""
 
178
 
 
179
    # A map of index 'type' to the file extension and position in the
 
180
    # index_sizes array.
 
181
    index_definitions = {
 
182
        'revision': ('.rix', 0),
 
183
        'inventory': ('.iix', 1),
 
184
        'text': ('.tix', 2),
 
185
        'signature': ('.six', 3),
 
186
        }
 
187
 
 
188
    def __init__(self, upload_transport, index_transport, pack_transport,
 
189
        upload_suffix=''):
 
190
        """Create a NewPack instance.
 
191
 
 
192
        :param upload_transport: A writable transport for the pack to be
 
193
            incrementally uploaded to.
 
194
        :param index_transport: A writable transport for the pack's indices to
 
195
            be written to when the pack is finished.
 
196
        :param pack_transport: A writable transport for the pack to be renamed
 
197
            to when the upload is complete. This *must* be the same as
 
198
            upload_transport.clone('../packs').
 
199
        :param upload_suffix: An optional suffix to be given to any temporary
 
200
            files created during the pack creation. e.g '.autopack'
 
201
        """
 
202
        # The relative locations of the packs are constrained, but all are
 
203
        # passed in because the caller has them, so as to avoid object churn.
 
204
        Pack.__init__(self,
 
205
            # Revisions: parents list, no text compression.
 
206
            InMemoryGraphIndex(reference_lists=1),
 
207
            # Inventory: We want to map compression only, but currently the
 
208
            # knit code hasn't been updated enough to understand that, so we
 
209
            # have a regular 2-list index giving parents and compression
 
210
            # source.
 
211
            InMemoryGraphIndex(reference_lists=2),
 
212
            # Texts: compression and per file graph, for all fileids - so two
 
213
            # reference lists and two elements in the key tuple.
 
214
            InMemoryGraphIndex(reference_lists=2, key_elements=2),
 
215
            # Signatures: Just blobs to store, no compression, no parents
 
216
            # listing.
 
217
            InMemoryGraphIndex(reference_lists=0),
 
218
            )
 
219
        # where should the new pack be opened
 
220
        self.upload_transport = upload_transport
 
221
        # where are indices written out to
 
222
        self.index_transport = index_transport
 
223
        # where is the pack renamed to when it is finished?
 
224
        self.pack_transport = pack_transport
 
225
        # tracks the content written to the .pack file.
 
226
        self._hash = osutils.md5()
 
227
        # a four-tuple with the length in bytes of the indices, once the pack
 
228
        # is finalised. (rev, inv, text, sigs)
 
229
        self.index_sizes = None
 
230
        # How much data to cache when writing packs. Note that this is not
 
231
        # synchronised with reads, because it's not in the transport layer, so
 
232
        # is not safe unless the client knows it won't be reading from the pack
 
233
        # under creation.
 
234
        self._cache_limit = 0
 
235
        # the temporary pack file name.
 
236
        self.random_name = osutils.rand_chars(20) + upload_suffix
 
237
        # when was this pack started ?
 
238
        self.start_time = time.time()
 
239
        # open an output stream for the data added to the pack.
 
240
        self.write_stream = self.upload_transport.open_write_stream(
 
241
            self.random_name)
 
242
        if 'pack' in debug.debug_flags:
 
243
            mutter('%s: create_pack: pack stream open: %s%s t+%6.3fs',
 
244
                time.ctime(), self.upload_transport.base, self.random_name,
 
245
                time.time() - self.start_time)
 
246
        # A list of byte sequences to be written to the new pack, and the 
 
247
        # aggregate size of them.  Stored as a list rather than separate 
 
248
        # variables so that the _write_data closure below can update them.
 
249
        self._buffer = [[], 0]
 
250
        # create a callable for adding data 
 
251
        #
 
252
        # robertc says- this is a closure rather than a method on the object
 
253
        # so that the variables are locals, and faster than accessing object
 
254
        # members.
 
255
        def _write_data(bytes, flush=False, _buffer=self._buffer,
 
256
            _write=self.write_stream.write, _update=self._hash.update):
 
257
            _buffer[0].append(bytes)
 
258
            _buffer[1] += len(bytes)
 
259
            # buffer cap
 
260
            if _buffer[1] > self._cache_limit or flush:
 
261
                bytes = ''.join(_buffer[0])
 
262
                _write(bytes)
 
263
                _update(bytes)
 
264
                _buffer[:] = [[], 0]
 
265
        # expose this on self, for the occasion when clients want to add data.
 
266
        self._write_data = _write_data
 
267
        # a pack writer object to serialise pack records.
 
268
        self._writer = pack.ContainerWriter(self._write_data)
 
269
        self._writer.begin()
 
270
        # what state is the pack in? (open, finished, aborted)
 
271
        self._state = 'open'
 
272
 
 
273
    def abort(self):
 
274
        """Cancel creating this pack."""
 
275
        self._state = 'aborted'
 
276
        self.write_stream.close()
 
277
        # Remove the temporary pack file.
 
278
        self.upload_transport.delete(self.random_name)
 
279
        # The indices have no state on disk.
 
280
 
 
281
    def access_tuple(self):
 
282
        """Return a tuple (transport, name) for the pack content."""
 
283
        assert self._state in ('open', 'finished')
 
284
        if self._state == 'finished':
 
285
            return Pack.access_tuple(self)
 
286
        else:
 
287
            return self.upload_transport, self.random_name
 
288
 
 
289
    def data_inserted(self):
 
290
        """True if data has been added to this pack."""
 
291
        return bool(self.get_revision_count() or
 
292
            self.inventory_index.key_count() or
 
293
            self.text_index.key_count() or
 
294
            self.signature_index.key_count())
 
295
 
 
296
    def finish(self):
 
297
        """Finish the new pack.
 
298
 
 
299
        This:
 
300
         - finalises the content
 
301
         - assigns a name (the md5 of the content, currently)
 
302
         - writes out the associated indices
 
303
         - renames the pack into place.
 
304
         - stores the index size tuple for the pack in the index_sizes
 
305
           attribute.
 
306
        """
 
307
        self._writer.end()
 
308
        if self._buffer[1]:
 
309
            self._write_data('', flush=True)
 
310
        self.name = self._hash.hexdigest()
 
311
        # write indices
 
312
        # XXX: It'd be better to write them all to temporary names, then
 
313
        # rename them all into place, so that the window when only some are
 
314
        # visible is smaller.  On the other hand none will be seen until
 
315
        # they're in the names list.
 
316
        self.index_sizes = [None, None, None, None]
 
317
        self._write_index('revision', self.revision_index, 'revision')
 
318
        self._write_index('inventory', self.inventory_index, 'inventory')
 
319
        self._write_index('text', self.text_index, 'file texts')
 
320
        self._write_index('signature', self.signature_index,
 
321
            'revision signatures')
 
322
        self.write_stream.close()
 
323
        # Note that this will clobber an existing pack with the same name,
 
324
        # without checking for hash collisions. While this is undesirable this
 
325
        # is something that can be rectified in a subsequent release. One way
 
326
        # to rectify it may be to leave the pack at the original name, writing
 
327
        # its pack-names entry as something like 'HASH: index-sizes
 
328
        # temporary-name'. Allocate that and check for collisions, if it is
 
329
        # collision free then rename it into place. If clients know this scheme
 
330
        # they can handle missing-file errors by:
 
331
        #  - try for HASH.pack
 
332
        #  - try for temporary-name
 
333
        #  - refresh the pack-list to see if the pack is now absent
 
334
        self.upload_transport.rename(self.random_name,
 
335
                '../packs/' + self.name + '.pack')
 
336
        self._state = 'finished'
 
337
        if 'pack' in debug.debug_flags:
 
338
            # XXX: size might be interesting?
 
339
            mutter('%s: create_pack: pack renamed into place: %s%s->%s%s t+%6.3fs',
 
340
                time.ctime(), self.upload_transport.base, self.random_name,
 
341
                self.pack_transport, self.name,
 
342
                time.time() - self.start_time)
 
343
 
 
344
    def index_name(self, index_type, name):
 
345
        """Get the disk name of an index type for pack name 'name'."""
 
346
        return name + NewPack.index_definitions[index_type][0]
 
347
 
 
348
    def index_offset(self, index_type):
 
349
        """Get the position in a index_size array for a given index type."""
 
350
        return NewPack.index_definitions[index_type][1]
 
351
 
 
352
    def _replace_index_with_readonly(self, index_type):
 
353
        setattr(self, index_type + '_index',
 
354
            GraphIndex(self.index_transport,
 
355
                self.index_name(index_type, self.name),
 
356
                self.index_sizes[self.index_offset(index_type)]))
 
357
 
 
358
    def set_write_cache_size(self, size):
 
359
        self._cache_limit = size
 
360
 
 
361
    def _write_index(self, index_type, index, label):
 
362
        """Write out an index.
 
363
 
 
364
        :param index_type: The type of index to write - e.g. 'revision'.
 
365
        :param index: The index object to serialise.
 
366
        :param label: What label to give the index e.g. 'revision'.
 
367
        """
 
368
        index_name = self.index_name(index_type, self.name)
 
369
        self.index_sizes[self.index_offset(index_type)] = \
 
370
            self.index_transport.put_file(index_name, index.finish())
 
371
        if 'pack' in debug.debug_flags:
 
372
            # XXX: size might be interesting?
 
373
            mutter('%s: create_pack: wrote %s index: %s%s t+%6.3fs',
 
374
                time.ctime(), label, self.upload_transport.base,
 
375
                self.random_name, time.time() - self.start_time)
 
376
        # Replace the writable index on this object with a readonly, 
 
377
        # presently unloaded index. We should alter
 
378
        # the index layer to make its finish() error if add_node is
 
379
        # subsequently used. RBC
 
380
        self._replace_index_with_readonly(index_type)
 
381
 
 
382
 
 
383
class AggregateIndex(object):
 
384
    """An aggregated index for the RepositoryPackCollection.
 
385
 
 
386
    AggregateIndex is reponsible for managing the PackAccess object,
 
387
    Index-To-Pack mapping, and all indices list for a specific type of index
 
388
    such as 'revision index'.
 
389
 
 
390
    A CombinedIndex provides an index on a single key space built up
 
391
    from several on-disk indices.  The AggregateIndex builds on this 
 
392
    to provide a knit access layer, and allows having up to one writable
 
393
    index within the collection.
 
394
    """
 
395
    # XXX: Probably 'can be written to' could/should be separated from 'acts
 
396
    # like a knit index' -- mbp 20071024
 
397
 
 
398
    def __init__(self):
 
399
        """Create an AggregateIndex."""
 
400
        self.index_to_pack = {}
 
401
        self.combined_index = CombinedGraphIndex([])
 
402
        self.knit_access = _PackAccess(self.index_to_pack)
 
403
 
 
404
    def replace_indices(self, index_to_pack, indices):
 
405
        """Replace the current mappings with fresh ones.
 
406
 
 
407
        This should probably not be used eventually, rather incremental add and
 
408
        removal of indices. It has been added during refactoring of existing
 
409
        code.
 
410
 
 
411
        :param index_to_pack: A mapping from index objects to
 
412
            (transport, name) tuples for the pack file data.
 
413
        :param indices: A list of indices.
 
414
        """
 
415
        # refresh the revision pack map dict without replacing the instance.
 
416
        self.index_to_pack.clear()
 
417
        self.index_to_pack.update(index_to_pack)
 
418
        # XXX: API break - clearly a 'replace' method would be good?
 
419
        self.combined_index._indices[:] = indices
 
420
        # the current add nodes callback for the current writable index if
 
421
        # there is one.
 
422
        self.add_callback = None
 
423
 
 
424
    def add_index(self, index, pack):
 
425
        """Add index to the aggregate, which is an index for Pack pack.
 
426
 
 
427
        Future searches on the aggregate index will seach this new index
 
428
        before all previously inserted indices.
 
429
        
 
430
        :param index: An Index for the pack.
 
431
        :param pack: A Pack instance.
 
432
        """
 
433
        # expose it to the index map
 
434
        self.index_to_pack[index] = pack.access_tuple()
 
435
        # put it at the front of the linear index list
 
436
        self.combined_index.insert_index(0, index)
 
437
 
 
438
    def add_writable_index(self, index, pack):
 
439
        """Add an index which is able to have data added to it.
 
440
 
 
441
        There can be at most one writable index at any time.  Any
 
442
        modifications made to the knit are put into this index.
 
443
        
 
444
        :param index: An index from the pack parameter.
 
445
        :param pack: A Pack instance.
 
446
        """
 
447
        assert self.add_callback is None, \
 
448
            "%s already has a writable index through %s" % \
 
449
            (self, self.add_callback)
 
450
        # allow writing: queue writes to a new index
 
451
        self.add_index(index, pack)
 
452
        # Updates the index to packs mapping as a side effect,
 
453
        self.knit_access.set_writer(pack._writer, index, pack.access_tuple())
 
454
        self.add_callback = index.add_nodes
 
455
 
 
456
    def clear(self):
 
457
        """Reset all the aggregate data to nothing."""
 
458
        self.knit_access.set_writer(None, None, (None, None))
 
459
        self.index_to_pack.clear()
 
460
        del self.combined_index._indices[:]
 
461
        self.add_callback = None
 
462
 
 
463
    def remove_index(self, index, pack):
 
464
        """Remove index from the indices used to answer queries.
 
465
        
 
466
        :param index: An index from the pack parameter.
 
467
        :param pack: A Pack instance.
 
468
        """
 
469
        del self.index_to_pack[index]
 
470
        self.combined_index._indices.remove(index)
 
471
        if (self.add_callback is not None and
 
472
            getattr(index, 'add_nodes', None) == self.add_callback):
 
473
            self.add_callback = None
 
474
            self.knit_access.set_writer(None, None, (None, None))
 
475
 
 
476
 
 
477
class Packer(object):
 
478
    """Create a pack from packs."""
 
479
 
 
480
    def __init__(self, pack_collection, packs, suffix, revision_ids=None):
 
481
        """Create a Packer.
 
482
 
 
483
        :param pack_collection: A RepositoryPackCollection object where the
 
484
            new pack is being written to.
 
485
        :param packs: The packs to combine.
 
486
        :param suffix: The suffix to use on the temporary files for the pack.
 
487
        :param revision_ids: Revision ids to limit the pack to.
 
488
        """
 
489
        self.packs = packs
 
490
        self.suffix = suffix
 
491
        self.revision_ids = revision_ids
 
492
        self._pack_collection = pack_collection
 
493
 
 
494
    def pack(self, pb=None):
 
495
        """Create a new pack by reading data from other packs.
 
496
 
 
497
        This does little more than a bulk copy of data. One key difference
 
498
        is that data with the same item key across multiple packs is elided
 
499
        from the output. The new pack is written into the current pack store
 
500
        along with its indices, and the name added to the pack names. The 
 
501
        source packs are not altered and are not required to be in the current
 
502
        pack collection.
 
503
 
 
504
        :param pb: An optional progress bar to use. A nested bar is created if
 
505
            this is None.
 
506
        :return: A Pack object, or None if nothing was copied.
 
507
        """
 
508
        # open a pack - using the same name as the last temporary file
 
509
        # - which has already been flushed, so its safe.
 
510
        # XXX: - duplicate code warning with start_write_group; fix before
 
511
        #      considering 'done'.
 
512
        if self._pack_collection._new_pack is not None:
 
513
            raise errors.BzrError('call to create_pack_from_packs while '
 
514
                'another pack is being written.')
 
515
        if self.revision_ids is not None:
 
516
            if len(self.revision_ids) == 0:
 
517
                # silly fetch request.
 
518
                return None
 
519
            else:
 
520
                self.revision_ids = frozenset(self.revision_ids)
 
521
        if pb is None:
 
522
            self.pb = ui.ui_factory.nested_progress_bar()
 
523
        else:
 
524
            self.pb = pb
 
525
        try:
 
526
            return self._create_pack_from_packs()
 
527
        finally:
 
528
            if pb is None:
 
529
                self.pb.finished()
 
530
 
 
531
    def open_pack(self):
 
532
        """Open a pack for the pack we are creating."""
 
533
        return NewPack(self._pack_collection._upload_transport,
 
534
            self._pack_collection._index_transport,
 
535
            self._pack_collection._pack_transport, upload_suffix=self.suffix)
 
536
 
 
537
    def _create_pack_from_packs(self):
 
538
        self.pb.update("Opening pack", 0, 5)
 
539
        new_pack = self.open_pack()
 
540
        # buffer data - we won't be reading-back during the pack creation and
 
541
        # this makes a significant difference on sftp pushes.
 
542
        new_pack.set_write_cache_size(1024*1024)
 
543
        if 'pack' in debug.debug_flags:
 
544
            plain_pack_list = ['%s%s' % (a_pack.pack_transport.base, a_pack.name)
 
545
                for a_pack in self.packs]
 
546
            if self.revision_ids is not None:
 
547
                rev_count = len(self.revision_ids)
 
548
            else:
 
549
                rev_count = 'all'
 
550
            mutter('%s: create_pack: creating pack from source packs: '
 
551
                '%s%s %s revisions wanted %s t=0',
 
552
                time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
 
553
                plain_pack_list, rev_count)
 
554
        # select revisions
 
555
        if self.revision_ids:
 
556
            revision_keys = [(revision_id,) for revision_id in self.revision_ids]
 
557
        else:
 
558
            revision_keys = None
 
559
 
 
560
        # select revision keys
 
561
        revision_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
 
562
            self.packs, 'revision_index')[0]
 
563
        revision_nodes = self._pack_collection._index_contents(revision_index_map, revision_keys)
 
564
        # copy revision keys and adjust values
 
565
        self.pb.update("Copying revision texts", 1)
 
566
        list(self._copy_nodes_graph(revision_nodes, revision_index_map,
 
567
            new_pack._writer, new_pack.revision_index))
 
568
        if 'pack' in debug.debug_flags:
 
569
            mutter('%s: create_pack: revisions copied: %s%s %d items t+%6.3fs',
 
570
                time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
 
571
                new_pack.revision_index.key_count(),
 
572
                time.time() - new_pack.start_time)
 
573
        # select inventory keys
 
574
        inv_keys = revision_keys # currently the same keyspace, and note that
 
575
        # querying for keys here could introduce a bug where an inventory item
 
576
        # is missed, so do not change it to query separately without cross
 
577
        # checking like the text key check below.
 
578
        inventory_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
 
579
            self.packs, 'inventory_index')[0]
 
580
        inv_nodes = self._pack_collection._index_contents(inventory_index_map, inv_keys)
 
581
        # copy inventory keys and adjust values
 
582
        # XXX: Should be a helper function to allow different inv representation
 
583
        # at this point.
 
584
        self.pb.update("Copying inventory texts", 2)
 
585
        inv_lines = self._copy_nodes_graph(inv_nodes, inventory_index_map,
 
586
            new_pack._writer, new_pack.inventory_index, output_lines=True)
 
587
        if self.revision_ids:
 
588
            fileid_revisions = self._pack_collection.repo._find_file_ids_from_xml_inventory_lines(
 
589
                inv_lines, self.revision_ids)
 
590
            text_filter = []
 
591
            for fileid, file_revids in fileid_revisions.iteritems():
 
592
                text_filter.extend(
 
593
                    [(fileid, file_revid) for file_revid in file_revids])
 
594
        else:
 
595
            # eat the iterator to cause it to execute.
 
596
            list(inv_lines)
 
597
            text_filter = None
 
598
        if 'pack' in debug.debug_flags:
 
599
            mutter('%s: create_pack: inventories copied: %s%s %d items t+%6.3fs',
 
600
                time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
 
601
                new_pack.inventory_index.key_count(),
 
602
                time.time() - new_pack.start_time)
 
603
        # select text keys
 
604
        text_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
 
605
            self.packs, 'text_index')[0]
 
606
        text_nodes = self._pack_collection._index_contents(text_index_map, text_filter)
 
607
        if text_filter is not None:
 
608
            # We could return the keys copied as part of the return value from
 
609
            # _copy_nodes_graph but this doesn't work all that well with the
 
610
            # need to get line output too, so we check separately, and as we're
 
611
            # going to buffer everything anyway, we check beforehand, which
 
612
            # saves reading knit data over the wire when we know there are
 
613
            # mising records.
 
614
            text_nodes = set(text_nodes)
 
615
            present_text_keys = set(_node[1] for _node in text_nodes)
 
616
            missing_text_keys = set(text_filter) - present_text_keys
 
617
            if missing_text_keys:
 
618
                # TODO: raise a specific error that can handle many missing
 
619
                # keys.
 
620
                a_missing_key = missing_text_keys.pop()
 
621
                raise errors.RevisionNotPresent(a_missing_key[1],
 
622
                    a_missing_key[0])
 
623
        # copy text keys and adjust values
 
624
        self.pb.update("Copying content texts", 3)
 
625
        list(self._copy_nodes_graph(text_nodes, text_index_map,
 
626
            new_pack._writer, new_pack.text_index))
 
627
        if 'pack' in debug.debug_flags:
 
628
            mutter('%s: create_pack: file texts copied: %s%s %d items t+%6.3fs',
 
629
                time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
 
630
                new_pack.text_index.key_count(),
 
631
                time.time() - new_pack.start_time)
 
632
        # select signature keys
 
633
        signature_filter = revision_keys # same keyspace
 
634
        signature_index_map = self._pack_collection._packs_list_to_pack_map_and_index_list(
 
635
            self.packs, 'signature_index')[0]
 
636
        signature_nodes = self._pack_collection._index_contents(signature_index_map,
 
637
            signature_filter)
 
638
        # copy signature keys and adjust values
 
639
        self.pb.update("Copying signature texts", 4)
 
640
        self._copy_nodes(signature_nodes, signature_index_map, new_pack._writer,
 
641
            new_pack.signature_index)
 
642
        if 'pack' in debug.debug_flags:
 
643
            mutter('%s: create_pack: revision signatures copied: %s%s %d items t+%6.3fs',
 
644
                time.ctime(), self._pack_collection._upload_transport.base, new_pack.random_name,
 
645
                new_pack.signature_index.key_count(),
 
646
                time.time() - new_pack.start_time)
 
647
        if not new_pack.data_inserted():
 
648
            new_pack.abort()
 
649
            return None
 
650
        self.pb.update("Finishing pack", 5)
 
651
        new_pack.finish()
 
652
        self._pack_collection.allocate(new_pack)
 
653
        return new_pack
 
654
 
 
655
    def _copy_nodes(self, nodes, index_map, writer, write_index):
 
656
        """Copy knit nodes between packs with no graph references."""
 
657
        pb = ui.ui_factory.nested_progress_bar()
 
658
        try:
 
659
            return self._do_copy_nodes(nodes, index_map, writer,
 
660
                write_index, pb)
 
661
        finally:
 
662
            pb.finished()
 
663
 
 
664
    def _do_copy_nodes(self, nodes, index_map, writer, write_index, pb):
 
665
        # for record verification
 
666
        knit_data = _KnitData(None)
 
667
        # plan a readv on each source pack:
 
668
        # group by pack
 
669
        nodes = sorted(nodes)
 
670
        # how to map this into knit.py - or knit.py into this?
 
671
        # we don't want the typical knit logic, we want grouping by pack
 
672
        # at this point - perhaps a helper library for the following code 
 
673
        # duplication points?
 
674
        request_groups = {}
 
675
        for index, key, value in nodes:
 
676
            if index not in request_groups:
 
677
                request_groups[index] = []
 
678
            request_groups[index].append((key, value))
 
679
        record_index = 0
 
680
        pb.update("Copied record", record_index, len(nodes))
 
681
        for index, items in request_groups.iteritems():
 
682
            pack_readv_requests = []
 
683
            for key, value in items:
 
684
                # ---- KnitGraphIndex.get_position
 
685
                bits = value[1:].split(' ')
 
686
                offset, length = int(bits[0]), int(bits[1])
 
687
                pack_readv_requests.append((offset, length, (key, value[0])))
 
688
            # linear scan up the pack
 
689
            pack_readv_requests.sort()
 
690
            # copy the data
 
691
            transport, path = index_map[index]
 
692
            reader = pack.make_readv_reader(transport, path,
 
693
                [offset[0:2] for offset in pack_readv_requests])
 
694
            for (names, read_func), (_1, _2, (key, eol_flag)) in \
 
695
                izip(reader.iter_records(), pack_readv_requests):
 
696
                raw_data = read_func(None)
 
697
                # check the header only
 
698
                df, _ = knit_data._parse_record_header(key[-1], raw_data)
 
699
                df.close()
 
700
                pos, size = writer.add_bytes_record(raw_data, names)
 
701
                write_index.add_node(key, eol_flag + "%d %d" % (pos, size))
 
702
                pb.update("Copied record", record_index)
 
703
                record_index += 1
 
704
 
 
705
    def _copy_nodes_graph(self, nodes, index_map, writer, write_index,
 
706
        output_lines=False):
 
707
        """Copy knit nodes between packs.
 
708
 
 
709
        :param output_lines: Return lines present in the copied data as
 
710
            an iterator of line,version_id.
 
711
        """
 
712
        pb = ui.ui_factory.nested_progress_bar()
 
713
        try:
 
714
            return self._do_copy_nodes_graph(nodes, index_map, writer,
 
715
                write_index, output_lines, pb)
 
716
        finally:
 
717
            pb.finished()
 
718
 
 
719
    def _do_copy_nodes_graph(self, nodes, index_map, writer, write_index,
 
720
        output_lines, pb):
 
721
        # for record verification
 
722
        knit_data = _KnitData(None)
 
723
        # for line extraction when requested (inventories only)
 
724
        if output_lines:
 
725
            factory = knit.KnitPlainFactory()
 
726
        # plan a readv on each source pack:
 
727
        # group by pack
 
728
        nodes = sorted(nodes)
 
729
        # how to map this into knit.py - or knit.py into this?
 
730
        # we don't want the typical knit logic, we want grouping by pack
 
731
        # at this point - perhaps a helper library for the following code 
 
732
        # duplication points?
 
733
        request_groups = {}
 
734
        record_index = 0
 
735
        pb.update("Copied record", record_index, len(nodes))
 
736
        for index, key, value, references in nodes:
 
737
            if index not in request_groups:
 
738
                request_groups[index] = []
 
739
            request_groups[index].append((key, value, references))
 
740
        for index, items in request_groups.iteritems():
 
741
            pack_readv_requests = []
 
742
            for key, value, references in items:
 
743
                # ---- KnitGraphIndex.get_position
 
744
                bits = value[1:].split(' ')
 
745
                offset, length = int(bits[0]), int(bits[1])
 
746
                pack_readv_requests.append((offset, length, (key, value[0], references)))
 
747
            # linear scan up the pack
 
748
            pack_readv_requests.sort()
 
749
            # copy the data
 
750
            transport, path = index_map[index]
 
751
            reader = pack.make_readv_reader(transport, path,
 
752
                [offset[0:2] for offset in pack_readv_requests])
 
753
            for (names, read_func), (_1, _2, (key, eol_flag, references)) in \
 
754
                izip(reader.iter_records(), pack_readv_requests):
 
755
                raw_data = read_func(None)
 
756
                version_id = key[-1]
 
757
                if output_lines:
 
758
                    # read the entire thing
 
759
                    content, _ = knit_data._parse_record(version_id, raw_data)
 
760
                    if len(references[-1]) == 0:
 
761
                        line_iterator = factory.get_fulltext_content(content)
 
762
                    else:
 
763
                        line_iterator = factory.get_linedelta_content(content)
 
764
                    for line in line_iterator:
 
765
                        yield line, version_id
 
766
                else:
 
767
                    # check the header only
 
768
                    df, _ = knit_data._parse_record_header(version_id, raw_data)
 
769
                    df.close()
 
770
                pos, size = writer.add_bytes_record(raw_data, names)
 
771
                write_index.add_node(key, eol_flag + "%d %d" % (pos, size), references)
 
772
                pb.update("Copied record", record_index)
 
773
                record_index += 1
 
774
 
 
775
 
 
776
class ReconcilePacker(Packer):
 
777
    """A packer which regenerates indices etc as it copies.
 
778
    
 
779
    This is used by ``bzr reconcile`` to cause parent text pointers to be
 
780
    regenerated.
 
781
    """
 
782
 
 
783
 
 
784
class RepositoryPackCollection(object):
 
785
    """Management of packs within a repository."""
 
786
 
 
787
    def __init__(self, repo, transport, index_transport, upload_transport,
 
788
                 pack_transport):
 
789
        """Create a new RepositoryPackCollection.
 
790
 
 
791
        :param transport: Addresses the repository base directory 
 
792
            (typically .bzr/repository/).
 
793
        :param index_transport: Addresses the directory containing indices.
 
794
        :param upload_transport: Addresses the directory into which packs are written
 
795
            while they're being created.
 
796
        :param pack_transport: Addresses the directory of existing complete packs.
 
797
        """
 
798
        self.repo = repo
 
799
        self.transport = transport
 
800
        self._index_transport = index_transport
 
801
        self._upload_transport = upload_transport
 
802
        self._pack_transport = pack_transport
 
803
        self._suffix_offsets = {'.rix': 0, '.iix': 1, '.tix': 2, '.six': 3}
 
804
        self.packs = []
 
805
        # name:Pack mapping
 
806
        self._packs_by_name = {}
 
807
        # the previous pack-names content
 
808
        self._packs_at_load = None
 
809
        # when a pack is being created by this object, the state of that pack.
 
810
        self._new_pack = None
 
811
        # aggregated revision index data
 
812
        self.revision_index = AggregateIndex()
 
813
        self.inventory_index = AggregateIndex()
 
814
        self.text_index = AggregateIndex()
 
815
        self.signature_index = AggregateIndex()
 
816
 
 
817
    def add_pack_to_memory(self, pack):
 
818
        """Make a Pack object available to the repository to satisfy queries.
 
819
        
 
820
        :param pack: A Pack object.
 
821
        """
 
822
        assert pack.name not in self._packs_by_name
 
823
        self.packs.append(pack)
 
824
        self._packs_by_name[pack.name] = pack
 
825
        self.revision_index.add_index(pack.revision_index, pack)
 
826
        self.inventory_index.add_index(pack.inventory_index, pack)
 
827
        self.text_index.add_index(pack.text_index, pack)
 
828
        self.signature_index.add_index(pack.signature_index, pack)
 
829
        
 
830
    def _add_text_to_weave(self, file_id, revision_id, new_lines, parents,
 
831
        nostore_sha, random_revid):
 
832
        file_id_index = GraphIndexPrefixAdapter(
 
833
            self.text_index.combined_index,
 
834
            (file_id, ), 1,
 
835
            add_nodes_callback=self.text_index.add_callback)
 
836
        self.repo._text_knit._index._graph_index = file_id_index
 
837
        self.repo._text_knit._index._add_callback = file_id_index.add_nodes
 
838
        return self.repo._text_knit.add_lines_with_ghosts(
 
839
            revision_id, parents, new_lines, nostore_sha=nostore_sha,
 
840
            random_id=random_revid, check_content=False)[0:2]
 
841
 
 
842
    def all_packs(self):
 
843
        """Return a list of all the Pack objects this repository has.
 
844
 
 
845
        Note that an in-progress pack being created is not returned.
 
846
 
 
847
        :return: A list of Pack objects for all the packs in the repository.
 
848
        """
 
849
        result = []
 
850
        for name in self.names():
 
851
            result.append(self.get_pack_by_name(name))
 
852
        return result
 
853
 
 
854
    def autopack(self):
 
855
        """Pack the pack collection incrementally.
 
856
        
 
857
        This will not attempt global reorganisation or recompression,
 
858
        rather it will just ensure that the total number of packs does
 
859
        not grow without bound. It uses the _max_pack_count method to
 
860
        determine if autopacking is needed, and the pack_distribution
 
861
        method to determine the number of revisions in each pack.
 
862
 
 
863
        If autopacking takes place then the packs name collection will have
 
864
        been flushed to disk - packing requires updating the name collection
 
865
        in synchronisation with certain steps. Otherwise the names collection
 
866
        is not flushed.
 
867
 
 
868
        :return: True if packing took place.
 
869
        """
 
870
        # XXX: Should not be needed when the management of indices is sane.
 
871
        total_revisions = self.revision_index.combined_index.key_count()
 
872
        total_packs = len(self._names)
 
873
        if self._max_pack_count(total_revisions) >= total_packs:
 
874
            return False
 
875
        # XXX: the following may want to be a class, to pack with a given
 
876
        # policy.
 
877
        mutter('Auto-packing repository %s, which has %d pack files, '
 
878
            'containing %d revisions into %d packs.', self, total_packs,
 
879
            total_revisions, self._max_pack_count(total_revisions))
 
880
        # determine which packs need changing
 
881
        pack_distribution = self.pack_distribution(total_revisions)
 
882
        existing_packs = []
 
883
        for pack in self.all_packs():
 
884
            revision_count = pack.get_revision_count()
 
885
            if revision_count == 0:
 
886
                # revision less packs are not generated by normal operation,
 
887
                # only by operations like sign-my-commits, and thus will not
 
888
                # tend to grow rapdily or without bound like commit containing
 
889
                # packs do - leave them alone as packing them really should
 
890
                # group their data with the relevant commit, and that may
 
891
                # involve rewriting ancient history - which autopack tries to
 
892
                # avoid. Alternatively we could not group the data but treat
 
893
                # each of these as having a single revision, and thus add 
 
894
                # one revision for each to the total revision count, to get
 
895
                # a matching distribution.
 
896
                continue
 
897
            existing_packs.append((revision_count, pack))
 
898
        pack_operations = self.plan_autopack_combinations(
 
899
            existing_packs, pack_distribution)
 
900
        self._execute_pack_operations(pack_operations)
 
901
        return True
 
902
 
 
903
    def _execute_pack_operations(self, pack_operations):
 
904
        """Execute a series of pack operations.
 
905
 
 
906
        :param pack_operations: A list of [revision_count, packs_to_combine].
 
907
        :return: None.
 
908
        """
 
909
        for revision_count, packs in pack_operations:
 
910
            # we may have no-ops from the setup logic
 
911
            if len(packs) == 0:
 
912
                continue
 
913
            Packer(self, packs, '.autopack').pack()
 
914
            for pack in packs:
 
915
                self._remove_pack_from_memory(pack)
 
916
        # record the newly available packs and stop advertising the old
 
917
        # packs
 
918
        self._save_pack_names(clear_obsolete_packs=True)
 
919
        # Move the old packs out of the way now they are no longer referenced.
 
920
        for revision_count, packs in pack_operations:
 
921
            self._obsolete_packs(packs)
 
922
 
 
923
    def lock_names(self):
 
924
        """Acquire the mutex around the pack-names index.
 
925
        
 
926
        This cannot be used in the middle of a read-only transaction on the
 
927
        repository.
 
928
        """
 
929
        self.repo.control_files.lock_write()
 
930
 
 
931
    def pack(self):
 
932
        """Pack the pack collection totally."""
 
933
        self.ensure_loaded()
 
934
        total_packs = len(self._names)
 
935
        if total_packs < 2:
 
936
            return
 
937
        total_revisions = self.revision_index.combined_index.key_count()
 
938
        # XXX: the following may want to be a class, to pack with a given
 
939
        # policy.
 
940
        mutter('Packing repository %s, which has %d pack files, '
 
941
            'containing %d revisions into 1 packs.', self, total_packs,
 
942
            total_revisions)
 
943
        # determine which packs need changing
 
944
        pack_distribution = [1]
 
945
        pack_operations = [[0, []]]
 
946
        for pack in self.all_packs():
 
947
            revision_count = pack.get_revision_count()
 
948
            pack_operations[-1][0] += revision_count
 
949
            pack_operations[-1][1].append(pack)
 
950
        self._execute_pack_operations(pack_operations)
 
951
 
 
952
    def plan_autopack_combinations(self, existing_packs, pack_distribution):
 
953
        """Plan a pack operation.
 
954
 
 
955
        :param existing_packs: The packs to pack. (A list of (revcount, Pack)
 
956
            tuples).
 
957
        :param pack_distribution: A list with the number of revisions desired
 
958
            in each pack.
 
959
        """
 
960
        if len(existing_packs) <= len(pack_distribution):
 
961
            return []
 
962
        existing_packs.sort(reverse=True)
 
963
        pack_operations = [[0, []]]
 
964
        # plan out what packs to keep, and what to reorganise
 
965
        while len(existing_packs):
 
966
            # take the largest pack, and if its less than the head of the
 
967
            # distribution chart we will include its contents in the new pack for
 
968
            # that position. If its larger, we remove its size from the
 
969
            # distribution chart
 
970
            next_pack_rev_count, next_pack = existing_packs.pop(0)
 
971
            if next_pack_rev_count >= pack_distribution[0]:
 
972
                # this is already packed 'better' than this, so we can
 
973
                # not waste time packing it.
 
974
                while next_pack_rev_count > 0:
 
975
                    next_pack_rev_count -= pack_distribution[0]
 
976
                    if next_pack_rev_count >= 0:
 
977
                        # more to go
 
978
                        del pack_distribution[0]
 
979
                    else:
 
980
                        # didn't use that entire bucket up
 
981
                        pack_distribution[0] = -next_pack_rev_count
 
982
            else:
 
983
                # add the revisions we're going to add to the next output pack
 
984
                pack_operations[-1][0] += next_pack_rev_count
 
985
                # allocate this pack to the next pack sub operation
 
986
                pack_operations[-1][1].append(next_pack)
 
987
                if pack_operations[-1][0] >= pack_distribution[0]:
 
988
                    # this pack is used up, shift left.
 
989
                    del pack_distribution[0]
 
990
                    pack_operations.append([0, []])
 
991
        
 
992
        return pack_operations
 
993
 
 
994
    def ensure_loaded(self):
 
995
        # NB: if you see an assertion error here, its probably access against
 
996
        # an unlocked repo. Naughty.
 
997
        assert self.repo.is_locked()
 
998
        if self._names is None:
 
999
            self._names = {}
 
1000
            self._packs_at_load = set()
 
1001
            for index, key, value in self._iter_disk_pack_index():
 
1002
                name = key[0]
 
1003
                self._names[name] = self._parse_index_sizes(value)
 
1004
                self._packs_at_load.add((key, value))
 
1005
        # populate all the metadata.
 
1006
        self.all_packs()
 
1007
 
 
1008
    def _parse_index_sizes(self, value):
 
1009
        """Parse a string of index sizes."""
 
1010
        return tuple([int(digits) for digits in value.split(' ')])
 
1011
 
 
1012
    def get_pack_by_name(self, name):
 
1013
        """Get a Pack object by name.
 
1014
 
 
1015
        :param name: The name of the pack - e.g. '123456'
 
1016
        :return: A Pack object.
 
1017
        """
 
1018
        try:
 
1019
            return self._packs_by_name[name]
 
1020
        except KeyError:
 
1021
            rev_index = self._make_index(name, '.rix')
 
1022
            inv_index = self._make_index(name, '.iix')
 
1023
            txt_index = self._make_index(name, '.tix')
 
1024
            sig_index = self._make_index(name, '.six')
 
1025
            result = ExistingPack(self._pack_transport, name, rev_index,
 
1026
                inv_index, txt_index, sig_index)
 
1027
            self.add_pack_to_memory(result)
 
1028
            return result
 
1029
 
 
1030
    def allocate(self, a_new_pack):
 
1031
        """Allocate name in the list of packs.
 
1032
 
 
1033
        :param a_new_pack: A NewPack instance to be added to the collection of
 
1034
            packs for this repository.
 
1035
        """
 
1036
        self.ensure_loaded()
 
1037
        if a_new_pack.name in self._names:
 
1038
            # a collision with the packs we know about (not the only possible
 
1039
            # collision, see NewPack.finish() for some discussion). Remove our
 
1040
            # prior reference to it.
 
1041
            self._remove_pack_from_memory(a_new_pack)
 
1042
        self._names[a_new_pack.name] = tuple(a_new_pack.index_sizes)
 
1043
        self.add_pack_to_memory(a_new_pack)
 
1044
 
 
1045
    def _iter_disk_pack_index(self):
 
1046
        """Iterate over the contents of the pack-names index.
 
1047
        
 
1048
        This is used when loading the list from disk, and before writing to
 
1049
        detect updates from others during our write operation.
 
1050
        :return: An iterator of the index contents.
 
1051
        """
 
1052
        return GraphIndex(self.transport, 'pack-names', None
 
1053
                ).iter_all_entries()
 
1054
 
 
1055
    def _make_index(self, name, suffix):
 
1056
        size_offset = self._suffix_offsets[suffix]
 
1057
        index_name = name + suffix
 
1058
        index_size = self._names[name][size_offset]
 
1059
        return GraphIndex(
 
1060
            self._index_transport, index_name, index_size)
 
1061
 
 
1062
    def _max_pack_count(self, total_revisions):
 
1063
        """Return the maximum number of packs to use for total revisions.
 
1064
        
 
1065
        :param total_revisions: The total number of revisions in the
 
1066
            repository.
 
1067
        """
 
1068
        if not total_revisions:
 
1069
            return 1
 
1070
        digits = str(total_revisions)
 
1071
        result = 0
 
1072
        for digit in digits:
 
1073
            result += int(digit)
 
1074
        return result
 
1075
 
 
1076
    def names(self):
 
1077
        """Provide an order to the underlying names."""
 
1078
        return sorted(self._names.keys())
 
1079
 
 
1080
    def _obsolete_packs(self, packs):
 
1081
        """Move a number of packs which have been obsoleted out of the way.
 
1082
 
 
1083
        Each pack and its associated indices are moved out of the way.
 
1084
 
 
1085
        Note: for correctness this function should only be called after a new
 
1086
        pack names index has been written without these pack names, and with
 
1087
        the names of packs that contain the data previously available via these
 
1088
        packs.
 
1089
 
 
1090
        :param packs: The packs to obsolete.
 
1091
        :param return: None.
 
1092
        """
 
1093
        for pack in packs:
 
1094
            pack.pack_transport.rename(pack.file_name(),
 
1095
                '../obsolete_packs/' + pack.file_name())
 
1096
            # TODO: Probably needs to know all possible indices for this pack
 
1097
            # - or maybe list the directory and move all indices matching this
 
1098
            # name whether we recognize it or not?
 
1099
            for suffix in ('.iix', '.six', '.tix', '.rix'):
 
1100
                self._index_transport.rename(pack.name + suffix,
 
1101
                    '../obsolete_packs/' + pack.name + suffix)
 
1102
 
 
1103
    def pack_distribution(self, total_revisions):
 
1104
        """Generate a list of the number of revisions to put in each pack.
 
1105
 
 
1106
        :param total_revisions: The total number of revisions in the
 
1107
            repository.
 
1108
        """
 
1109
        if total_revisions == 0:
 
1110
            return [0]
 
1111
        digits = reversed(str(total_revisions))
 
1112
        result = []
 
1113
        for exponent, count in enumerate(digits):
 
1114
            size = 10 ** exponent
 
1115
            for pos in range(int(count)):
 
1116
                result.append(size)
 
1117
        return list(reversed(result))
 
1118
 
 
1119
    def _pack_tuple(self, name):
 
1120
        """Return a tuple with the transport and file name for a pack name."""
 
1121
        return self._pack_transport, name + '.pack'
 
1122
 
 
1123
    def _remove_pack_from_memory(self, pack):
 
1124
        """Remove pack from the packs accessed by this repository.
 
1125
        
 
1126
        Only affects memory state, until self._save_pack_names() is invoked.
 
1127
        """
 
1128
        self._names.pop(pack.name)
 
1129
        self._packs_by_name.pop(pack.name)
 
1130
        self._remove_pack_indices(pack)
 
1131
 
 
1132
    def _remove_pack_indices(self, pack):
 
1133
        """Remove the indices for pack from the aggregated indices."""
 
1134
        self.revision_index.remove_index(pack.revision_index, pack)
 
1135
        self.inventory_index.remove_index(pack.inventory_index, pack)
 
1136
        self.text_index.remove_index(pack.text_index, pack)
 
1137
        self.signature_index.remove_index(pack.signature_index, pack)
 
1138
 
 
1139
    def reset(self):
 
1140
        """Clear all cached data."""
 
1141
        # cached revision data
 
1142
        self.repo._revision_knit = None
 
1143
        self.revision_index.clear()
 
1144
        # cached signature data
 
1145
        self.repo._signature_knit = None
 
1146
        self.signature_index.clear()
 
1147
        # cached file text data
 
1148
        self.text_index.clear()
 
1149
        self.repo._text_knit = None
 
1150
        # cached inventory data
 
1151
        self.inventory_index.clear()
 
1152
        # remove the open pack
 
1153
        self._new_pack = None
 
1154
        # information about packs.
 
1155
        self._names = None
 
1156
        self.packs = []
 
1157
        self._packs_by_name = {}
 
1158
        self._packs_at_load = None
 
1159
 
 
1160
    def _make_index_map(self, index_suffix):
 
1161
        """Return information on existing indices.
 
1162
 
 
1163
        :param suffix: Index suffix added to pack name.
 
1164
 
 
1165
        :returns: (pack_map, indices) where indices is a list of GraphIndex 
 
1166
        objects, and pack_map is a mapping from those objects to the 
 
1167
        pack tuple they describe.
 
1168
        """
 
1169
        # TODO: stop using this; it creates new indices unnecessarily.
 
1170
        self.ensure_loaded()
 
1171
        suffix_map = {'.rix': 'revision_index',
 
1172
            '.six': 'signature_index',
 
1173
            '.iix': 'inventory_index',
 
1174
            '.tix': 'text_index',
 
1175
        }
 
1176
        return self._packs_list_to_pack_map_and_index_list(self.all_packs(),
 
1177
            suffix_map[index_suffix])
 
1178
 
 
1179
    def _packs_list_to_pack_map_and_index_list(self, packs, index_attribute):
 
1180
        """Convert a list of packs to an index pack map and index list.
 
1181
 
 
1182
        :param packs: The packs list to process.
 
1183
        :param index_attribute: The attribute that the desired index is found
 
1184
            on.
 
1185
        :return: A tuple (map, list) where map contains the dict from
 
1186
            index:pack_tuple, and lsit contains the indices in the same order
 
1187
            as the packs list.
 
1188
        """
 
1189
        indices = []
 
1190
        pack_map = {}
 
1191
        for pack in packs:
 
1192
            index = getattr(pack, index_attribute)
 
1193
            indices.append(index)
 
1194
            pack_map[index] = (pack.pack_transport, pack.file_name())
 
1195
        return pack_map, indices
 
1196
 
 
1197
    def _index_contents(self, pack_map, key_filter=None):
 
1198
        """Get an iterable of the index contents from a pack_map.
 
1199
 
 
1200
        :param pack_map: A map from indices to pack details.
 
1201
        :param key_filter: An optional filter to limit the
 
1202
            keys returned.
 
1203
        """
 
1204
        indices = [index for index in pack_map.iterkeys()]
 
1205
        all_index = CombinedGraphIndex(indices)
 
1206
        if key_filter is None:
 
1207
            return all_index.iter_all_entries()
 
1208
        else:
 
1209
            return all_index.iter_entries(key_filter)
 
1210
 
 
1211
    def _unlock_names(self):
 
1212
        """Release the mutex around the pack-names index."""
 
1213
        self.repo.control_files.unlock()
 
1214
 
 
1215
    def _save_pack_names(self, clear_obsolete_packs=False):
 
1216
        """Save the list of packs.
 
1217
 
 
1218
        This will take out the mutex around the pack names list for the
 
1219
        duration of the method call. If concurrent updates have been made, a
 
1220
        three-way merge between the current list and the current in memory list
 
1221
        is performed.
 
1222
 
 
1223
        :param clear_obsolete_packs: If True, clear out the contents of the
 
1224
            obsolete_packs directory.
 
1225
        """
 
1226
        self.lock_names()
 
1227
        try:
 
1228
            builder = GraphIndexBuilder()
 
1229
            # load the disk nodes across
 
1230
            disk_nodes = set()
 
1231
            for index, key, value in self._iter_disk_pack_index():
 
1232
                disk_nodes.add((key, value))
 
1233
            # do a two-way diff against our original content
 
1234
            current_nodes = set()
 
1235
            for name, sizes in self._names.iteritems():
 
1236
                current_nodes.add(
 
1237
                    ((name, ), ' '.join(str(size) for size in sizes)))
 
1238
            deleted_nodes = self._packs_at_load - current_nodes
 
1239
            new_nodes = current_nodes - self._packs_at_load
 
1240
            disk_nodes.difference_update(deleted_nodes)
 
1241
            disk_nodes.update(new_nodes)
 
1242
            # TODO: handle same-name, index-size-changes here - 
 
1243
            # e.g. use the value from disk, not ours, *unless* we're the one
 
1244
            # changing it.
 
1245
            for key, value in disk_nodes:
 
1246
                builder.add_node(key, value)
 
1247
            self.transport.put_file('pack-names', builder.finish())
 
1248
            # move the baseline forward
 
1249
            self._packs_at_load = disk_nodes
 
1250
            # now clear out the obsolete packs directory
 
1251
            if clear_obsolete_packs:
 
1252
                self.transport.clone('obsolete_packs').delete_multi(
 
1253
                    self.transport.list_dir('obsolete_packs'))
 
1254
        finally:
 
1255
            self._unlock_names()
 
1256
        # synchronise the memory packs list with what we just wrote:
 
1257
        new_names = dict(disk_nodes)
 
1258
        # drop no longer present nodes
 
1259
        for pack in self.all_packs():
 
1260
            if (pack.name,) not in new_names:
 
1261
                self._remove_pack_from_memory(pack)
 
1262
        # add new nodes/refresh existing ones
 
1263
        for key, value in disk_nodes:
 
1264
            name = key[0]
 
1265
            sizes = self._parse_index_sizes(value)
 
1266
            if name in self._names:
 
1267
                # existing
 
1268
                if sizes != self._names[name]:
 
1269
                    # the pack for name has had its indices replaced - rare but
 
1270
                    # important to handle. XXX: probably can never happen today
 
1271
                    # because the three-way merge code above does not handle it
 
1272
                    # - you may end up adding the same key twice to the new
 
1273
                    # disk index because the set values are the same, unless
 
1274
                    # the only index shows up as deleted by the set difference
 
1275
                    # - which it may. Until there is a specific test for this,
 
1276
                    # assume its broken. RBC 20071017.
 
1277
                    self._remove_pack_from_memory(self.get_pack_by_name(name))
 
1278
                    self._names[name] = sizes
 
1279
                    self.get_pack_by_name(name)
 
1280
            else:
 
1281
                # new
 
1282
                self._names[name] = sizes
 
1283
                self.get_pack_by_name(name)
 
1284
 
 
1285
    def _start_write_group(self):
 
1286
        # Do not permit preparation for writing if we're not in a 'write lock'.
 
1287
        if not self.repo.is_write_locked():
 
1288
            raise errors.NotWriteLocked(self)
 
1289
        self._new_pack = NewPack(self._upload_transport, self._index_transport,
 
1290
            self._pack_transport, upload_suffix='.pack')
 
1291
        # allow writing: queue writes to a new index
 
1292
        self.revision_index.add_writable_index(self._new_pack.revision_index,
 
1293
            self._new_pack)
 
1294
        self.inventory_index.add_writable_index(self._new_pack.inventory_index,
 
1295
            self._new_pack)
 
1296
        self.text_index.add_writable_index(self._new_pack.text_index,
 
1297
            self._new_pack)
 
1298
        self.signature_index.add_writable_index(self._new_pack.signature_index,
 
1299
            self._new_pack)
 
1300
 
 
1301
        # reused revision and signature knits may need updating
 
1302
        #
 
1303
        # "Hysterical raisins. client code in bzrlib grabs those knits outside
 
1304
        # of write groups and then mutates it inside the write group."
 
1305
        if self.repo._revision_knit is not None:
 
1306
            self.repo._revision_knit._index._add_callback = \
 
1307
                self.revision_index.add_callback
 
1308
        if self.repo._signature_knit is not None:
 
1309
            self.repo._signature_knit._index._add_callback = \
 
1310
                self.signature_index.add_callback
 
1311
        # create a reused knit object for text addition in commit.
 
1312
        self.repo._text_knit = self.repo.weave_store.get_weave_or_empty(
 
1313
            'all-texts', None)
 
1314
 
 
1315
    def _abort_write_group(self):
 
1316
        # FIXME: just drop the transient index.
 
1317
        # forget what names there are
 
1318
        self._new_pack.abort()
 
1319
        self._remove_pack_indices(self._new_pack)
 
1320
        self._new_pack = None
 
1321
        self.repo._text_knit = None
 
1322
 
 
1323
    def _commit_write_group(self):
 
1324
        self._remove_pack_indices(self._new_pack)
 
1325
        if self._new_pack.data_inserted():
 
1326
            # get all the data to disk and read to use
 
1327
            self._new_pack.finish()
 
1328
            self.allocate(self._new_pack)
 
1329
            self._new_pack = None
 
1330
            if not self.autopack():
 
1331
                # when autopack takes no steps, the names list is still
 
1332
                # unsaved.
 
1333
                self._save_pack_names()
 
1334
        else:
 
1335
            self._new_pack.abort()
 
1336
            self._new_pack = None
 
1337
        self.repo._text_knit = None
 
1338
 
 
1339
 
 
1340
class KnitPackRevisionStore(KnitRevisionStore):
 
1341
    """An object to adapt access from RevisionStore's to use KnitPacks.
 
1342
 
 
1343
    This class works by replacing the original RevisionStore.
 
1344
    We need to do this because the KnitPackRevisionStore is less
 
1345
    isolated in its layering - it uses services from the repo.
 
1346
    """
 
1347
 
 
1348
    def __init__(self, repo, transport, revisionstore):
 
1349
        """Create a KnitPackRevisionStore on repo with revisionstore.
 
1350
 
 
1351
        This will store its state in the Repository, use the
 
1352
        indices to provide a KnitGraphIndex,
 
1353
        and at the end of transactions write new indices.
 
1354
        """
 
1355
        KnitRevisionStore.__init__(self, revisionstore.versioned_file_store)
 
1356
        self.repo = repo
 
1357
        self._serializer = revisionstore._serializer
 
1358
        self.transport = transport
 
1359
 
 
1360
    def get_revision_file(self, transaction):
 
1361
        """Get the revision versioned file object."""
 
1362
        if getattr(self.repo, '_revision_knit', None) is not None:
 
1363
            return self.repo._revision_knit
 
1364
        self.repo._pack_collection.ensure_loaded()
 
1365
        add_callback = self.repo._pack_collection.revision_index.add_callback
 
1366
        # setup knit specific objects
 
1367
        knit_index = KnitGraphIndex(
 
1368
            self.repo._pack_collection.revision_index.combined_index,
 
1369
            add_callback=add_callback)
 
1370
        self.repo._revision_knit = knit.KnitVersionedFile(
 
1371
            'revisions', self.transport.clone('..'),
 
1372
            self.repo.control_files._file_mode,
 
1373
            create=False, access_mode=self.repo._access_mode(),
 
1374
            index=knit_index, delta=False, factory=knit.KnitPlainFactory(),
 
1375
            access_method=self.repo._pack_collection.revision_index.knit_access)
 
1376
        return self.repo._revision_knit
 
1377
 
 
1378
    def get_signature_file(self, transaction):
 
1379
        """Get the signature versioned file object."""
 
1380
        if getattr(self.repo, '_signature_knit', None) is not None:
 
1381
            return self.repo._signature_knit
 
1382
        self.repo._pack_collection.ensure_loaded()
 
1383
        add_callback = self.repo._pack_collection.signature_index.add_callback
 
1384
        # setup knit specific objects
 
1385
        knit_index = KnitGraphIndex(
 
1386
            self.repo._pack_collection.signature_index.combined_index,
 
1387
            add_callback=add_callback, parents=False)
 
1388
        self.repo._signature_knit = knit.KnitVersionedFile(
 
1389
            'signatures', self.transport.clone('..'),
 
1390
            self.repo.control_files._file_mode,
 
1391
            create=False, access_mode=self.repo._access_mode(),
 
1392
            index=knit_index, delta=False, factory=knit.KnitPlainFactory(),
 
1393
            access_method=self.repo._pack_collection.signature_index.knit_access)
 
1394
        return self.repo._signature_knit
 
1395
 
 
1396
 
 
1397
class KnitPackTextStore(VersionedFileStore):
 
1398
    """Presents a TextStore abstraction on top of packs.
 
1399
 
 
1400
    This class works by replacing the original VersionedFileStore.
 
1401
    We need to do this because the KnitPackRevisionStore is less
 
1402
    isolated in its layering - it uses services from the repo and shares them
 
1403
    with all the data written in a single write group.
 
1404
    """
 
1405
 
 
1406
    def __init__(self, repo, transport, weavestore):
 
1407
        """Create a KnitPackTextStore on repo with weavestore.
 
1408
 
 
1409
        This will store its state in the Repository, use the
 
1410
        indices FileNames to provide a KnitGraphIndex,
 
1411
        and at the end of transactions write new indices.
 
1412
        """
 
1413
        # don't call base class constructor - it's not suitable.
 
1414
        # no transient data stored in the transaction
 
1415
        # cache.
 
1416
        self._precious = False
 
1417
        self.repo = repo
 
1418
        self.transport = transport
 
1419
        self.weavestore = weavestore
 
1420
        # XXX for check() which isn't updated yet
 
1421
        self._transport = weavestore._transport
 
1422
 
 
1423
    def get_weave_or_empty(self, file_id, transaction):
 
1424
        """Get a 'Knit' backed by the .tix indices.
 
1425
 
 
1426
        The transaction parameter is ignored.
 
1427
        """
 
1428
        self.repo._pack_collection.ensure_loaded()
 
1429
        add_callback = self.repo._pack_collection.text_index.add_callback
 
1430
        # setup knit specific objects
 
1431
        file_id_index = GraphIndexPrefixAdapter(
 
1432
            self.repo._pack_collection.text_index.combined_index,
 
1433
            (file_id, ), 1, add_nodes_callback=add_callback)
 
1434
        knit_index = KnitGraphIndex(file_id_index,
 
1435
            add_callback=file_id_index.add_nodes,
 
1436
            deltas=True, parents=True)
 
1437
        return knit.KnitVersionedFile('text:' + file_id,
 
1438
            self.transport.clone('..'),
 
1439
            None,
 
1440
            index=knit_index,
 
1441
            access_method=self.repo._pack_collection.text_index.knit_access,
 
1442
            factory=knit.KnitPlainFactory())
 
1443
 
 
1444
    get_weave = get_weave_or_empty
 
1445
 
 
1446
    def __iter__(self):
 
1447
        """Generate a list of the fileids inserted, for use by check."""
 
1448
        self.repo._pack_collection.ensure_loaded()
 
1449
        ids = set()
 
1450
        for index, key, value, refs in \
 
1451
            self.repo._pack_collection.text_index.combined_index.iter_all_entries():
 
1452
            ids.add(key[0])
 
1453
        return iter(ids)
 
1454
 
 
1455
 
 
1456
class InventoryKnitThunk(object):
 
1457
    """An object to manage thunking get_inventory_weave to pack based knits."""
 
1458
 
 
1459
    def __init__(self, repo, transport):
 
1460
        """Create an InventoryKnitThunk for repo at transport.
 
1461
 
 
1462
        This will store its state in the Repository, use the
 
1463
        indices FileNames to provide a KnitGraphIndex,
 
1464
        and at the end of transactions write a new index..
 
1465
        """
 
1466
        self.repo = repo
 
1467
        self.transport = transport
 
1468
 
 
1469
    def get_weave(self):
 
1470
        """Get a 'Knit' that contains inventory data."""
 
1471
        self.repo._pack_collection.ensure_loaded()
 
1472
        add_callback = self.repo._pack_collection.inventory_index.add_callback
 
1473
        # setup knit specific objects
 
1474
        knit_index = KnitGraphIndex(
 
1475
            self.repo._pack_collection.inventory_index.combined_index,
 
1476
            add_callback=add_callback, deltas=True, parents=True)
 
1477
        return knit.KnitVersionedFile(
 
1478
            'inventory', self.transport.clone('..'),
 
1479
            self.repo.control_files._file_mode,
 
1480
            create=False, access_mode=self.repo._access_mode(),
 
1481
            index=knit_index, delta=True, factory=knit.KnitPlainFactory(),
 
1482
            access_method=self.repo._pack_collection.inventory_index.knit_access)
 
1483
 
 
1484
 
 
1485
class KnitPackRepository(KnitRepository):
 
1486
    """Experimental graph-knit using repository."""
 
1487
 
 
1488
    def __init__(self, _format, a_bzrdir, control_files, _revision_store,
 
1489
        control_store, text_store, _commit_builder_class, _serializer):
 
1490
        KnitRepository.__init__(self, _format, a_bzrdir, control_files,
 
1491
            _revision_store, control_store, text_store, _commit_builder_class,
 
1492
            _serializer)
 
1493
        index_transport = control_files._transport.clone('indices')
 
1494
        self._pack_collection = RepositoryPackCollection(self, control_files._transport,
 
1495
            index_transport,
 
1496
            control_files._transport.clone('upload'),
 
1497
            control_files._transport.clone('packs'))
 
1498
        self._revision_store = KnitPackRevisionStore(self, index_transport, self._revision_store)
 
1499
        self.weave_store = KnitPackTextStore(self, index_transport, self.weave_store)
 
1500
        self._inv_thunk = InventoryKnitThunk(self, index_transport)
 
1501
        # True when the repository object is 'write locked' (as opposed to the
 
1502
        # physical lock only taken out around changes to the pack-names list.) 
 
1503
        # Another way to represent this would be a decorator around the control
 
1504
        # files object that presents logical locks as physical ones - if this
 
1505
        # gets ugly consider that alternative design. RBC 20071011
 
1506
        self._write_lock_count = 0
 
1507
        self._transaction = None
 
1508
        # for tests
 
1509
        self._reconcile_does_inventory_gc = True
 
1510
        self._reconcile_fixes_text_parents = False
 
1511
        self._reconcile_backsup_inventory = False
 
1512
 
 
1513
    def _abort_write_group(self):
 
1514
        self._pack_collection._abort_write_group()
 
1515
 
 
1516
    def _access_mode(self):
 
1517
        """Return 'w' or 'r' for depending on whether a write lock is active.
 
1518
        
 
1519
        This method is a helper for the Knit-thunking support objects.
 
1520
        """
 
1521
        if self.is_write_locked():
 
1522
            return 'w'
 
1523
        return 'r'
 
1524
 
 
1525
    def _find_inconsistent_revision_parents(self):
 
1526
        """Find revisions with incorrectly cached parents.
 
1527
 
 
1528
        :returns: an iterator yielding tuples of (revison-id, parents-in-index,
 
1529
            parents-in-revision).
 
1530
        """
 
1531
        assert self.is_locked()
 
1532
        pb = ui.ui_factory.nested_progress_bar()
 
1533
        result = []
 
1534
        try:
 
1535
            revision_nodes = self._pack_collection.revision_index \
 
1536
                .combined_index.iter_all_entries()
 
1537
            index_positions = []
 
1538
            # Get the cached index values for all revisions, and also the location
 
1539
            # in each index of the revision text so we can perform linear IO.
 
1540
            for index, key, value, refs in revision_nodes:
 
1541
                pos, length = value[1:].split(' ')
 
1542
                index_positions.append((index, int(pos), key[0],
 
1543
                    tuple(parent[0] for parent in refs[0])))
 
1544
                pb.update("Reading revision index.", 0, 0)
 
1545
            index_positions.sort()
 
1546
            batch_count = len(index_positions) / 1000 + 1
 
1547
            pb.update("Checking cached revision graph.", 0, batch_count)
 
1548
            for offset in xrange(batch_count):
 
1549
                pb.update("Checking cached revision graph.", offset)
 
1550
                to_query = index_positions[offset * 1000:(offset + 1) * 1000]
 
1551
                if not to_query:
 
1552
                    break
 
1553
                rev_ids = [item[2] for item in to_query]
 
1554
                revs = self.get_revisions(rev_ids)
 
1555
                for revision, item in zip(revs, to_query):
 
1556
                    index_parents = item[3]
 
1557
                    rev_parents = tuple(revision.parent_ids)
 
1558
                    if index_parents != rev_parents:
 
1559
                        result.append((revision.revision_id, index_parents, rev_parents))
 
1560
        finally:
 
1561
            pb.finished()
 
1562
        return result
 
1563
 
 
1564
    def get_parents(self, revision_ids):
 
1565
        """See StackedParentsProvider.get_parents.
 
1566
        
 
1567
        This implementation accesses the combined revision index to provide
 
1568
        answers.
 
1569
        """
 
1570
        self._pack_collection.ensure_loaded()
 
1571
        index = self._pack_collection.revision_index.combined_index
 
1572
        search_keys = set()
 
1573
        for revision_id in revision_ids:
 
1574
            if revision_id != _mod_revision.NULL_REVISION:
 
1575
                search_keys.add((revision_id,))
 
1576
        found_parents = {_mod_revision.NULL_REVISION:[]}
 
1577
        for index, key, value, refs in index.iter_entries(search_keys):
 
1578
            parents = refs[0]
 
1579
            if not parents:
 
1580
                parents = (_mod_revision.NULL_REVISION,)
 
1581
            else:
 
1582
                parents = tuple(parent[0] for parent in parents)
 
1583
            found_parents[key[0]] = parents
 
1584
        result = []
 
1585
        for revision_id in revision_ids:
 
1586
            try:
 
1587
                result.append(found_parents[revision_id])
 
1588
            except KeyError:
 
1589
                result.append(None)
 
1590
        return result
 
1591
 
 
1592
    def _make_parents_provider(self):
 
1593
        return self
 
1594
 
 
1595
    def _refresh_data(self):
 
1596
        if self._write_lock_count == 1 or (
 
1597
            self.control_files._lock_count == 1 and
 
1598
            self.control_files._lock_mode == 'r'):
 
1599
            # forget what names there are
 
1600
            self._pack_collection.reset()
 
1601
            # XXX: Better to do an in-memory merge when acquiring a new lock -
 
1602
            # factor out code from _save_pack_names.
 
1603
            self._pack_collection.ensure_loaded()
 
1604
 
 
1605
    def _start_write_group(self):
 
1606
        self._pack_collection._start_write_group()
 
1607
 
 
1608
    def _commit_write_group(self):
 
1609
        return self._pack_collection._commit_write_group()
 
1610
 
 
1611
    def get_inventory_weave(self):
 
1612
        return self._inv_thunk.get_weave()
 
1613
 
 
1614
    def get_transaction(self):
 
1615
        if self._write_lock_count:
 
1616
            return self._transaction
 
1617
        else:
 
1618
            return self.control_files.get_transaction()
 
1619
 
 
1620
    def is_locked(self):
 
1621
        return self._write_lock_count or self.control_files.is_locked()
 
1622
 
 
1623
    def is_write_locked(self):
 
1624
        return self._write_lock_count
 
1625
 
 
1626
    def lock_write(self, token=None):
 
1627
        if not self._write_lock_count and self.is_locked():
 
1628
            raise errors.ReadOnlyError(self)
 
1629
        self._write_lock_count += 1
 
1630
        if self._write_lock_count == 1:
 
1631
            from bzrlib import transactions
 
1632
            self._transaction = transactions.WriteTransaction()
 
1633
        self._refresh_data()
 
1634
 
 
1635
    def lock_read(self):
 
1636
        if self._write_lock_count:
 
1637
            self._write_lock_count += 1
 
1638
        else:
 
1639
            self.control_files.lock_read()
 
1640
        self._refresh_data()
 
1641
 
 
1642
    def leave_lock_in_place(self):
 
1643
        # not supported - raise an error
 
1644
        raise NotImplementedError(self.leave_lock_in_place)
 
1645
 
 
1646
    def dont_leave_lock_in_place(self):
 
1647
        # not supported - raise an error
 
1648
        raise NotImplementedError(self.dont_leave_lock_in_place)
 
1649
 
 
1650
    @needs_write_lock
 
1651
    def pack(self):
 
1652
        """Compress the data within the repository.
 
1653
 
 
1654
        This will pack all the data to a single pack. In future it may
 
1655
        recompress deltas or do other such expensive operations.
 
1656
        """
 
1657
        self._pack_collection.pack()
 
1658
 
 
1659
    @needs_write_lock
 
1660
    def reconcile(self, other=None, thorough=False):
 
1661
        """Reconcile this repository."""
 
1662
        from bzrlib.reconcile import PackReconciler
 
1663
        reconciler = PackReconciler(self, thorough=thorough)
 
1664
        reconciler.reconcile()
 
1665
        return reconciler
 
1666
 
 
1667
    def unlock(self):
 
1668
        if self._write_lock_count == 1 and self._write_group is not None:
 
1669
            self.abort_write_group()
 
1670
            self._transaction = None
 
1671
            self._write_lock_count = 0
 
1672
            raise errors.BzrError(
 
1673
                'Must end write group before releasing write lock on %s'
 
1674
                % self)
 
1675
        if self._write_lock_count:
 
1676
            self._write_lock_count -= 1
 
1677
            if not self._write_lock_count:
 
1678
                transaction = self._transaction
 
1679
                self._transaction = None
 
1680
                transaction.finish()
 
1681
        else:
 
1682
            self.control_files.unlock()
 
1683
 
 
1684
 
 
1685
class RepositoryFormatPack(MetaDirRepositoryFormat):
 
1686
    """Format logic for pack structured repositories.
 
1687
 
 
1688
    This repository format has:
 
1689
     - a list of packs in pack-names
 
1690
     - packs in packs/NAME.pack
 
1691
     - indices in indices/NAME.{iix,six,tix,rix}
 
1692
     - knit deltas in the packs, knit indices mapped to the indices.
 
1693
     - thunk objects to support the knits programming API.
 
1694
     - a format marker of its own
 
1695
     - an optional 'shared-storage' flag
 
1696
     - an optional 'no-working-trees' flag
 
1697
     - a LockDir lock
 
1698
    """
 
1699
 
 
1700
    # Set this attribute in derived classes to control the repository class
 
1701
    # created by open and initialize.
 
1702
    repository_class = None
 
1703
    # Set this attribute in derived classes to control the
 
1704
    # _commit_builder_class that the repository objects will have passed to
 
1705
    # their constructor.
 
1706
    _commit_builder_class = None
 
1707
    # Set this attribute in derived clases to control the _serializer that the
 
1708
    # repository objects will have passed to their constructor.
 
1709
    _serializer = None
 
1710
 
 
1711
    def _get_control_store(self, repo_transport, control_files):
 
1712
        """Return the control store for this repository."""
 
1713
        return VersionedFileStore(
 
1714
            repo_transport,
 
1715
            prefixed=False,
 
1716
            file_mode=control_files._file_mode,
 
1717
            versionedfile_class=knit.KnitVersionedFile,
 
1718
            versionedfile_kwargs={'factory': knit.KnitPlainFactory()},
 
1719
            )
 
1720
 
 
1721
    def _get_revision_store(self, repo_transport, control_files):
 
1722
        """See RepositoryFormat._get_revision_store()."""
 
1723
        versioned_file_store = VersionedFileStore(
 
1724
            repo_transport,
 
1725
            file_mode=control_files._file_mode,
 
1726
            prefixed=False,
 
1727
            precious=True,
 
1728
            versionedfile_class=knit.KnitVersionedFile,
 
1729
            versionedfile_kwargs={'delta': False,
 
1730
                                  'factory': knit.KnitPlainFactory(),
 
1731
                                 },
 
1732
            escaped=True,
 
1733
            )
 
1734
        return KnitRevisionStore(versioned_file_store)
 
1735
 
 
1736
    def _get_text_store(self, transport, control_files):
 
1737
        """See RepositoryFormat._get_text_store()."""
 
1738
        return self._get_versioned_file_store('knits',
 
1739
                                  transport,
 
1740
                                  control_files,
 
1741
                                  versionedfile_class=knit.KnitVersionedFile,
 
1742
                                  versionedfile_kwargs={
 
1743
                                      'create_parent_dir': True,
 
1744
                                      'delay_create': True,
 
1745
                                      'dir_mode': control_files._dir_mode,
 
1746
                                  },
 
1747
                                  escaped=True)
 
1748
 
 
1749
    def initialize(self, a_bzrdir, shared=False):
 
1750
        """Create a pack based repository.
 
1751
 
 
1752
        :param a_bzrdir: bzrdir to contain the new repository; must already
 
1753
            be initialized.
 
1754
        :param shared: If true the repository will be initialized as a shared
 
1755
                       repository.
 
1756
        """
 
1757
        mutter('creating repository in %s.', a_bzrdir.transport.base)
 
1758
        dirs = ['indices', 'obsolete_packs', 'packs', 'upload']
 
1759
        builder = GraphIndexBuilder()
 
1760
        files = [('pack-names', builder.finish())]
 
1761
        utf8_files = [('format', self.get_format_string())]
 
1762
        
 
1763
        self._upload_blank_content(a_bzrdir, dirs, files, utf8_files, shared)
 
1764
        return self.open(a_bzrdir=a_bzrdir, _found=True)
 
1765
 
 
1766
    def open(self, a_bzrdir, _found=False, _override_transport=None):
 
1767
        """See RepositoryFormat.open().
 
1768
        
 
1769
        :param _override_transport: INTERNAL USE ONLY. Allows opening the
 
1770
                                    repository at a slightly different url
 
1771
                                    than normal. I.e. during 'upgrade'.
 
1772
        """
 
1773
        if not _found:
 
1774
            format = RepositoryFormat.find_format(a_bzrdir)
 
1775
            assert format.__class__ ==  self.__class__
 
1776
        if _override_transport is not None:
 
1777
            repo_transport = _override_transport
 
1778
        else:
 
1779
            repo_transport = a_bzrdir.get_repository_transport(None)
 
1780
        control_files = lockable_files.LockableFiles(repo_transport,
 
1781
                                'lock', lockdir.LockDir)
 
1782
        text_store = self._get_text_store(repo_transport, control_files)
 
1783
        control_store = self._get_control_store(repo_transport, control_files)
 
1784
        _revision_store = self._get_revision_store(repo_transport, control_files)
 
1785
        return self.repository_class(_format=self,
 
1786
                              a_bzrdir=a_bzrdir,
 
1787
                              control_files=control_files,
 
1788
                              _revision_store=_revision_store,
 
1789
                              control_store=control_store,
 
1790
                              text_store=text_store,
 
1791
                              _commit_builder_class=self._commit_builder_class,
 
1792
                              _serializer=self._serializer)
 
1793
 
 
1794
 
 
1795
class RepositoryFormatKnitPack1(RepositoryFormatPack):
 
1796
    """A no-subtrees parameterised Pack repository.
 
1797
 
 
1798
    This format was introduced in 0.92.
 
1799
    """
 
1800
 
 
1801
    repository_class = KnitPackRepository
 
1802
    _commit_builder_class = PackCommitBuilder
 
1803
    _serializer = xml5.serializer_v5
 
1804
 
 
1805
    def _get_matching_bzrdir(self):
 
1806
        return bzrdir.format_registry.make_bzrdir('knitpack-experimental')
 
1807
 
 
1808
    def _ignore_setting_bzrdir(self, format):
 
1809
        pass
 
1810
 
 
1811
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
1812
 
 
1813
    def get_format_string(self):
 
1814
        """See RepositoryFormat.get_format_string()."""
 
1815
        return "Bazaar pack repository format 1 (needs bzr 0.92)\n"
 
1816
 
 
1817
    def get_format_description(self):
 
1818
        """See RepositoryFormat.get_format_description()."""
 
1819
        return "Packs containing knits without subtree support"
 
1820
 
 
1821
    def check_conversion_target(self, target_format):
 
1822
        pass
 
1823
 
 
1824
 
 
1825
class RepositoryFormatKnitPack3(RepositoryFormatPack):
 
1826
    """A subtrees parameterised Pack repository.
 
1827
 
 
1828
    This repository format uses the xml7 serializer to get:
 
1829
     - support for recording full info about the tree root
 
1830
     - support for recording tree-references
 
1831
 
 
1832
    This format was introduced in 0.92.
 
1833
    """
 
1834
 
 
1835
    repository_class = KnitPackRepository
 
1836
    _commit_builder_class = PackRootCommitBuilder
 
1837
    rich_root_data = True
 
1838
    supports_tree_reference = True
 
1839
    _serializer = xml7.serializer_v7
 
1840
 
 
1841
    def _get_matching_bzrdir(self):
 
1842
        return bzrdir.format_registry.make_bzrdir(
 
1843
            'knitpack-subtree-experimental')
 
1844
 
 
1845
    def _ignore_setting_bzrdir(self, format):
 
1846
        pass
 
1847
 
 
1848
    _matchingbzrdir = property(_get_matching_bzrdir, _ignore_setting_bzrdir)
 
1849
 
 
1850
    def check_conversion_target(self, target_format):
 
1851
        if not target_format.rich_root_data:
 
1852
            raise errors.BadConversionTarget(
 
1853
                'Does not support rich root data.', target_format)
 
1854
        if not getattr(target_format, 'supports_tree_reference', False):
 
1855
            raise errors.BadConversionTarget(
 
1856
                'Does not support nested trees', target_format)
 
1857
            
 
1858
    def get_format_string(self):
 
1859
        """See RepositoryFormat.get_format_string()."""
 
1860
        return "Bazaar pack repository format 1 with subtree support (needs bzr 0.92)\n"
 
1861
 
 
1862
    def get_format_description(self):
 
1863
        """See RepositoryFormat.get_format_description()."""
 
1864
        return "Packs containing knits with subtree support\n"