File: hippy.py

package info (click to toggle)
debtorrent 0.1.10
  • links: PTS, VCS
  • area: main
  • in suites: squeeze, wheezy
  • size: 1,464 kB
  • ctags: 1,183
  • sloc: python: 13,703; sh: 282; makefile: 51
file content (373 lines) | stat: -rwxr-xr-x 12,058 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
#!/usr/bin/env python

"""Calculate the sub-piece hashes for large package files.

The command line arguments are the Berkeley database containing the cached
data from previous runs, and the unique name of the Packages file being
processed. Pass the paths of package files to process into the
standard input.

For example::

    find dists -name 'Packages.gz' | sort |
            while read a; do
                    b=$(echo $a | tr / _)
                    d=~/public_html/extrapieces/${b%.gz}-extrapieces.gz
                    zcat $a | sed -n 's/^Filename: //p' |
                            grep -v '^[.]/' |
                            sort | (~/hippy ~/mycache $a || echo >&2 "Failed: $a") |
                            gzip -9 > ${d}.new
                    mv ${d}.new $d
            done

@var MAX_PIECE_SIZE: the maximum piece size to use, pieces may be smaller than this
@var CHUNK_SIZE: the download chunk size used by DebTorrent (used to calculate
    an optimal piece size)
@var MAX_AGE: the maximum iterations of the program to keep subpiece information
    for the Packages file after it's no longer in the file (for slow mirrors)

"""

import bsddb, sha, binascii
import os, sys
import struct
from math import ceil

MAX_PIECE_SIZE = 512*1024
CHUNK_SIZE = 16*1024
MAX_AGE = 14

# The Packages files to read
EXTENSION = ".gz"

def hash(file, piece_size):
    """Read a file and hash it's sub-pieces.

    @type file: C{file}
    @param file: an already opened file-like object to read from
    @type piece_size: C{int}
    @param piece_size: the piece size to divide the file into
    @rtype: C{string}, C{list} of (C{string}, C{int})
    @return: the 40-byte hex representation of the SHA1 hash of the file, and
        the 40-byte hex representation of the SHA1 hash of the piece and the
        length of the piece, for each sub-piece of the file
    
    """
    
    hashes = []
    file_hash = sha.new()

    while 1:
        data = file.read(piece_size)
        if data == "":
            break
        
        hashes.append((sha.new(data).hexdigest(), len(data)))
        file_hash.update(data)

    return file_hash.hexdigest(), hashes


def optimal_piece_size(size):
    """Calculate the optimal piece size to use for a file.
    
    The optimal piece size is the largest possible piece size such that the
    piece size is larger than the extra piece, the piece size is a multiple of
    the chunk size, and the difference between the piece size and the extra
    piece size is a minimum.

    This function currently contains an error, as it returns a non-optimal
    piece size when the size is a multiple of the maximum piece size. This
    error is kept for backwards compatibility with previous versions. To
    correct it::
        
        n = 1 + (size-1) / MAX_PIECE_SIZE
    
    @type size: C{long}
    @param size: the file size
    @rtype: C{int}
    @return: the optimal piece size
    
    """
    
    n = 1 + size / MAX_PIECE_SIZE
    return max(MAX_PIECE_SIZE/2, int(ceil((float(size)/n)/CHUNK_SIZE))*CHUNK_SIZE)

def cache2list(cache_value):
    """Convert a cache value to a list of package names.
    
    The cache is stored as a string. The list is a repeating sequence of one
    byte length followed by a string of that length, followed by one byte
    indicating the number of times the package has been missing from the
    Packages file plus 1. Therefore, the longest string that can be stored is
    256.
    
    @type cache_value: C{string}
    @param cache_value: the cached value for this file
    @rtype: C{dictionary}
    @return: keys are the package names stored in the cache, values are the
        number of times the package has not been found in the Packages file
    
    """

    if cache_value == "":
        return {}

    debs = {}
    while len(cache_value) > 0:
        length = ord(cache_value[0])
        deb = cache_value[1:length+1]
        num = ord(cache_value[length+1]) - 1
        cache_value = cache_value[length+2:]
        debs[deb] = num
        
    return debs

def list2cache(debs):
    """Convert a list of package names to a cacheable value.
    
    @type debs: C{dictionary}
    @param debs: the package names to create a cache value for, keys are the
        names of the packages, values are the integer number of times this
        package has not been found in the Packages file
    @rtype: C{string}
    @return: the cacheable string
    
    """
    
    if not debs:
        return ""
    
    deb_list = debs.keys()
    deb_list.sort()
    cache_value = ""
    for deb in deb_list:
        assert len(deb) < 256
        assert debs[deb] >= 0
        cache_value += chr(len(deb)) + deb + chr(min(255, debs[deb]+1))
    return cache_value

def cache2hash(cache_value):
    """Convert a cache value to a list of sub-piece hashes.
    
    The cache is stored as a string. The first 20 bytes are the SHA1 hash of
    the entire file. Then there are repeating 24 byte sequences, the first 4
    bytes being the length of the piece in network (big-endian) order, the
    next 20 bytes being the SHA1 hash of the piece. If there are no sub-pieces
    for the file, the cached string is empty.
    
    @type cache_value: C{string}
    @param cache_value: the cached value for this file
    @rtype: C{string}, C{list} of (C{string}, C{int})
    @return: the 40-byte hex representation of the SHA1 hash of the file, and
        the 40-byte hex representation of the SHA1 hash of the piece and the
        length of the piece, for each sub-piece of the file
    
    """

    if cache_value == "":
        return None, []

    piece_list = []
    file_hash = binascii.b2a_hex(cache_value[:20])
    cache_value = cache_value[20:]
    
    while len(cache_value) > 0:
        length = struct.unpack(">i", cache_value[:4])[0]
        hash = binascii.b2a_hex(cache_value[4:24])
        cache_value = cache_value[24:]
        piece_list.append((hash, length))
        
    return file_hash, piece_list

def hash2cache(sha1, piece_list):
    """Convert a list of sub-piece hashes to a cacheable value.
    
    @type sha1: C{string}
    @param sha1: the 40-byte hex representation of the SHA1 hash of the file
    @type piece_list: C{list} of (C{string}, C{int})
    @param piece_list: for each sub-piece of the file, the 40-byte hex
        representation of the SHA1 hash and the length of the piece
    @rtype: C{string}
    @return: the cacheable string
    
    """
    
    if not piece_list:
        return ""
    
    cache_value = binascii.a2b_hex(sha1)
    for (hash, length) in piece_list:
        cache_value += struct.pack(">i", length) + binascii.a2b_hex(hash)
    return cache_value

def sub_piece(filename):
    """Calculate and print the sub-pieces for a single file.
    
    @type filename: C{String}
    @param filename: the file to calculate sub pieces for
    
    """
    # Get the size of the file
    size = os.stat(filename).st_size
    
    if size <= MAX_PIECE_SIZE:
        # No sub-pieces are needed for this file
        sha1 = ""
        piece_list = []
    else:
        sys.stderr.write('        Hashing: %s\n' % filename)
    
        # Calculate all the sub-piece hashes
        piece_size = optimal_piece_size(size)
        file = open(filename)
        sha1, piece_list = hash(file, piece_size)
        file.close()
        
    return sha1, piece_list

def run(cache, pkg_file):
    """Process a single Release file.
    
    @type cache: C{bsddb.BTree}
    @param cache: an already opened bDB b-tree
    @type pkg_file: C{string}
    @param pkg_file: the name of the Packages file being processed

    """
    sys.stderr.write('Processing: %s\n' % pkg_file)
    
    # Retrieve the saved list of sub-pieced packages in the Packages file
    pkey = pkg_file + ":pl"
    if cache.has_key(pkey):
        old_debs = cache2list(cache[pkey])
    else:
        old_debs = {}
    new_debs = {}
    
    sys.stderr.write('    Found %d old files\n' % len(old_debs))

    # Print the pice hashes for files in the Packages file
    for filename in sys.stdin:
        filename = filename.rstrip()
        fnkey = filename + ":pc"

        # Check if this file's sub-pieces are already known
        if cache.has_key(fnkey):
            sha1, piece_list = cache2hash(cache[fnkey])
        else:
            # Not known, hash the file
            sha1, piece_list = sub_piece(filename)

            # Save the result for next time
            cache[fnkey] = hash2cache(sha1, piece_list)
        
        # Remove the file from the old list
        old_debs.pop(filename, None)

        if piece_list:
            # Print the resulting sub-piece hashes
            print "Filename: %s" % (filename, )
            print "SHA1: %s" % (sha1, )
            print "SHA1-Pieces:"
            for x in piece_list:
                print " %s %d" % x
            print

            # Save the file to the new list
            new_debs[filename] = 0

    missing_files = old_debs.keys()            
    sys.stderr.write('    Have %d missing old files\n' % len(missing_files))
    missing_files.sort()
        
    # Also print any unexpired old entries
    for missing_file in missing_files:
        # Expire entries after they have been missing for MAX_AGE runs
        if old_debs[missing_file] >= MAX_AGE:
            sys.stderr.write('        Expired: %s\n' % missing_file)
            continue
        
        fnkey = missing_file + ":pc"

        # Check if this file's sub-pieces are already known
        if not cache.has_key(fnkey):
            continue
        
        sha1, piece_list = cache2hash(cache[fnkey])

        if piece_list:
            # Print the resulting sub-piece hashes
            print "Filename: %s" % (missing_file, )
            print "SHA1: %s" % (sha1, )
            print "SHA1-Pieces:"
            for x in piece_list:
                print " %s %d" % x
            print
        
            # Increment the age of the missing file
            new_debs[missing_file] = old_debs[missing_file] + 1
    
    # Write the list back to the cache
    sys.stderr.write('    Saving %d new files\n' % len(new_debs))
    cache[pkey] = list2cache(new_debs)

def clean(cache):
    """Clean unused hash entries from the cache.
    
    @type cache: C{bsddb.BTree}
    @param cache: an already opened bDB b-tree

    """
    sys.stderr.write('Cleaning the cache\n')

    # Get the sets of all files and package lists    
    packages = set()
    files = set()
    unused_hashes = set()
    empty_hashes = 0
    for key in cache.keys():
        if key.endswith(':pl'):
            d = cache2list(cache[key])
            packages.update(set(d.keys()))
        elif key.endswith(':pc'):
            if cache[key]:
                files.add(key[:-3])
            else:
                empty_hashes += 1
                if not os.path.exists(key[:-3]):
                    unused_hashes.add(key[:-3])

    # Find which files are no longer needed
    old_empty_hashes = len(unused_hashes)
    sys.stderr.write('Found %d/%d empty hashes for old files\n' %
                    (old_empty_hashes, empty_hashes))
    unused_hashes.update(files.difference(packages))
    missing_hashes = packages.difference(files)
    sys.stderr.write('Found %d/%d hashes that are no longer needed\n' %
                     (len(unused_hashes) - old_empty_hashes, len(files)))
    sys.stderr.write('Found %d/%d hashes that are missing\n' %
                     (len(missing_hashes), len(packages)))

    # Remove the no longer needed files
    for file in unused_hashes:
        sys.stderr.write('Removing file: %s\n' % (file, ))
        del cache[file + ':pc']

if __name__ == '__main__':
    
    # Open the cache file specified on the command line
    cache_file = sys.argv[1]
    cache = bsddb.btopen(cache_file, "w")

    # Get the Packages file name being processed
    pkg_file = sys.argv[2]
    
    if pkg_file == "CLEAN":
        clean(cache)
    else:
        run(cache, pkg_file)

    # Close the cache file
    cache.sync()
    cache.close()