~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/tuned_gzip.py

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

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2005, 2006 Canonical Ltd
 
1
# Copyright (C) 2006-2011 Canonical Ltd
2
2
# Written by Robert Collins <robert.collins@canonical.com>
3
3
#
4
4
# This program is free software; you can redistribute it and/or modify
13
13
#
14
14
# You should have received a copy of the GNU General Public License
15
15
# along with this program; if not, write to the Free Software
16
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 
16
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17
17
 
18
18
"""Bzrlib specific gzip tunings. We plan to feed these to the upstream gzip."""
19
19
 
27
27
import zlib
28
28
 
29
29
# we want a \n preserved, break on \n only splitlines.
30
 
import bzrlib
 
30
from bzrlib import symbol_versioning
31
31
 
32
32
__all__ = ["GzipFile", "bytes_to_gzip"]
33
33
 
52
52
    width=-zlib.MAX_WBITS, mem=zlib.DEF_MEM_LEVEL,
53
53
    crc32=zlib.crc32):
54
54
    """Create a gzip file containing bytes and return its content."""
 
55
    return chunks_to_gzip([bytes])
 
56
 
 
57
 
 
58
def chunks_to_gzip(chunks, factory=zlib.compressobj,
 
59
    level=zlib.Z_DEFAULT_COMPRESSION, method=zlib.DEFLATED,
 
60
    width=-zlib.MAX_WBITS, mem=zlib.DEF_MEM_LEVEL,
 
61
    crc32=zlib.crc32):
 
62
    """Create a gzip file containing chunks and return its content.
 
63
 
 
64
    :param chunks: An iterable of strings. Each string can have arbitrary
 
65
        layout.
 
66
    """
55
67
    result = [
56
68
        '\037\213'  # self.fileobj.write('\037\213')  # magic header
57
69
        '\010'      # self.fileobj.write('\010')      # compression method
69
81
    # using a compressobj avoids a small header and trailer that the compress()
70
82
    # utility function adds.
71
83
    compress = factory(level, method, width, mem, 0)
72
 
    result.append(compress.compress(bytes))
 
84
    crc = 0
 
85
    total_len = 0
 
86
    for chunk in chunks:
 
87
        crc = crc32(chunk, crc)
 
88
        total_len += len(chunk)
 
89
        zbytes = compress.compress(chunk)
 
90
        if zbytes:
 
91
            result.append(zbytes)
73
92
    result.append(compress.flush())
74
 
    result.append(struct.pack("<L", LOWU32(crc32(bytes))))
75
93
    # size may exceed 2GB, or even 4GB
76
 
    result.append(struct.pack("<L", LOWU32(len(bytes))))
 
94
    result.append(struct.pack("<LL", LOWU32(crc), LOWU32(total_len)))
77
95
    return ''.join(result)
78
96
 
79
97
 
100
118
    Yes, its only 1.6 seconds, but they add up.
101
119
    """
102
120
 
 
121
    def __init__(self, *args, **kwargs):
 
122
        symbol_versioning.warn(
 
123
            symbol_versioning.deprecated_in((2, 3, 0))
 
124
            % 'bzrlib.tuned_gzip.GzipFile',
 
125
            DeprecationWarning, stacklevel=2)
 
126
        gzip.GzipFile.__init__(self, *args, **kwargs)
 
127
 
103
128
    def _add_read_data(self, data):
104
129
        # 4169 calls in 183
105
130
        # temp var for len(data) and switch to +='s.
114
139
        """A tuned version of gzip._write_gzip_header
115
140
 
116
141
        We have some extra constrains that plain Gzip does not.
117
 
        1) We want to write the whole blob at once. rather than multiple 
 
142
        1) We want to write the whole blob at once. rather than multiple
118
143
           calls to fileobj.write().
119
144
        2) We never have a filename
120
145
        3) We don't care about the time
136
161
 
137
162
    def _read(self, size=1024):
138
163
        # various optimisations:
139
 
        # reduces lsprof count from 2500 to 
 
164
        # reduces lsprof count from 2500 to
140
165
        # 8337 calls in 1272, 365 internal
141
166
        if self.fileobj is None:
142
167
            raise EOFError, "Reached EOF"
207
232
        """tuned to reduce function calls and eliminate file seeking:
208
233
        pass 1:
209
234
        reduces lsprof count from 800 to 288
210
 
        4168 in 296 
 
235
        4168 in 296
211
236
        avoid U32 call by using struct format L
212
237
        4168 in 200
213
238
        """
214
 
        # We've read to the end of the file, so we should have 8 bytes of 
 
239
        # We've read to the end of the file, so we should have 8 bytes of
215
240
        # unused data in the decompressor. If we don't, there is a corrupt file.
216
241
        # We use these 8 bytes to calculate the CRC and the recorded file size.
217
242
        # We then check the that the computed CRC and size of the
228
253
 
229
254
    def _read_gzip_header(self, bytes=None):
230
255
        """Supply bytes if the minimum header size is already read.
231
 
        
 
256
 
232
257
        :param bytes: 10 bytes of header data.
233
258
        """
234
259
        """starting cost: 300 in 3998
271
296
 
272
297
    def readline(self, size=-1):
273
298
        """Tuned to remove buffer length calls in _unread and...
274
 
        
 
299
 
275
300
        also removes multiple len(c) calls, inlines _unread,
276
301
        total savings - lsprof 5800 to 5300
277
302
        phase 2:
281
306
        leading to a drop to:
282
307
        4168 calls in 1977
283
308
        4168 call to read() in 1646
284
 
        - i.e. just reduced the function call overhead. May be worth 
 
309
        - i.e. just reduced the function call overhead. May be worth
285
310
          keeping.
286
311
        """
287
312
        if size < 0: size = sys.maxint
329
354
        # to :
330
355
        # 4168 calls in 417.
331
356
        # Negative numbers result in reading all the lines
332
 
        
 
357
 
333
358
        # python's gzip routine uses sizehint. This is a more efficient way
334
359
        # than python uses to honor it. But it is even more efficient to
335
360
        # just read the entire thing and use cStringIO to split into lines.
342
367
 
343
368
    def _unread(self, buf, len_buf=None):
344
369
        """tuned to remove unneeded len calls.
345
 
        
 
370
 
346
371
        because this is such an inner routine in readline, and readline is
347
372
        in many inner loops, this has been inlined into readline().
348
373
 
349
374
        The len_buf parameter combined with the reduction in len calls dropped
350
 
        the lsprof ms count for this routine on my test data from 800 to 200 - 
 
375
        the lsprof ms count for this routine on my test data from 800 to 200 -
351
376
        a 75% saving.
352
377
        """
353
378
        if len_buf is None:
371
396
            self.offset += data_len
372
397
 
373
398
    def writelines(self, lines):
374
 
        # profiling indicated a significant overhead 
 
399
        # profiling indicated a significant overhead
375
400
        # calling write for each line.
376
401
        # this batch call is a lot faster :).
377
402
        # (4 seconds to 1 seconds for the sample upgrades I was testing).
378
403
        self.write(''.join(lines))
379
404
 
 
405
    if sys.version_info > (2, 7):
 
406
        # As of Python 2.7 the crc32 must be positive when close is called
 
407
        def close(self):
 
408
            if self.fileobj is None:
 
409
                return
 
410
            if self.mode == gzip.WRITE:
 
411
                self.crc &= 0xFFFFFFFFL
 
412
            gzip.GzipFile.close(self)
380
413