root / snf-pithos-backend / pithos / backends / lib / hashfiler / fileblocker.py @ c4399e62
History | View | Annotate | Download (7.3 kB)
1 |
# Copyright 2011-2012 GRNET S.A. All rights reserved.
|
---|---|
2 |
#
|
3 |
# Redistribution and use in source and binary forms, with or
|
4 |
# without modification, are permitted provided that the following
|
5 |
# conditions are met:
|
6 |
#
|
7 |
# 1. Redistributions of source code must retain the above
|
8 |
# copyright notice, this list of conditions and the following
|
9 |
# disclaimer.
|
10 |
#
|
11 |
# 2. Redistributions in binary form must reproduce the above
|
12 |
# copyright notice, this list of conditions and the following
|
13 |
# disclaimer in the documentation and/or other materials
|
14 |
# provided with the distribution.
|
15 |
#
|
16 |
# THIS SOFTWARE IS PROVIDED BY GRNET S.A. ``AS IS'' AND ANY EXPRESS
|
17 |
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
|
18 |
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
19 |
# PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL GRNET S.A OR
|
20 |
# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
21 |
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
22 |
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
|
23 |
# USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
|
24 |
# AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
|
25 |
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
|
26 |
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
27 |
# POSSIBILITY OF SUCH DAMAGE.
|
28 |
#
|
29 |
# The views and conclusions contained in the software and
|
30 |
# documentation are those of the authors and should not be
|
31 |
# interpreted as representing official policies, either expressed
|
32 |
# or implied, of GRNET S.A.
|
33 |
|
34 |
from os import makedirs |
35 |
from os.path import isdir, realpath, exists, join |
36 |
from hashlib import new as newhasher |
37 |
from binascii import hexlify |
38 |
|
39 |
from context_file import ContextFile, file_sync_read_chunks |
40 |
|
41 |
|
42 |
class FileBlocker(object): |
43 |
"""Blocker.
|
44 |
Required constructor parameters: blocksize, blockpath, hashtype.
|
45 |
"""
|
46 |
|
47 |
blocksize = None
|
48 |
blockpath = None
|
49 |
hashtype = None
|
50 |
|
51 |
def __init__(self, **params): |
52 |
blocksize = params['blocksize']
|
53 |
blockpath = params['blockpath']
|
54 |
blockpath = realpath(blockpath) |
55 |
if not isdir(blockpath): |
56 |
if not exists(blockpath): |
57 |
makedirs(blockpath) |
58 |
else:
|
59 |
raise ValueError("Variable blockpath '%s' is not a directory" % (blockpath,)) |
60 |
|
61 |
hashtype = params['hashtype']
|
62 |
try:
|
63 |
hasher = newhasher(hashtype) |
64 |
except ValueError: |
65 |
msg = "Variable hashtype '%s' is not available from hashlib"
|
66 |
raise ValueError(msg % (hashtype,)) |
67 |
|
68 |
hasher.update("")
|
69 |
emptyhash = hasher.digest() |
70 |
|
71 |
self.blocksize = blocksize
|
72 |
self.blockpath = blockpath
|
73 |
self.hashtype = hashtype
|
74 |
self.hashlen = len(emptyhash) |
75 |
self.emptyhash = emptyhash
|
76 |
|
77 |
def _pad(self, block): |
78 |
return block + ('\x00' * (self.blocksize - len(block))) |
79 |
|
80 |
def _get_rear_block(self, blkhash, create=False, write=False): |
81 |
filename = hexlify(blkhash) |
82 |
path = join(self.blockpath,
|
83 |
filename[0:2], filename[2:4], filename[4:6], |
84 |
filename) |
85 |
return ContextFile(path, create=create, write=False) |
86 |
|
87 |
def _check_rear_block(self, blkhash): |
88 |
filename = hexlify(blkhash) |
89 |
path = join(self.blockpath,
|
90 |
filename[0:2], filename[2:4], filename[4:6], |
91 |
filename) |
92 |
return exists(path)
|
93 |
|
94 |
def block_hash(self, data): |
95 |
"""Hash a block of data"""
|
96 |
hasher = newhasher(self.hashtype)
|
97 |
hasher.update(data.rstrip('\x00'))
|
98 |
return hasher.digest()
|
99 |
|
100 |
def block_ping(self, hashes): |
101 |
"""Check hashes for existence and
|
102 |
return those missing from block storage.
|
103 |
"""
|
104 |
notfound = [] |
105 |
append = notfound.append |
106 |
|
107 |
for h in hashes: |
108 |
if h not in notfound and not self._check_rear_block(h): |
109 |
append(h) |
110 |
|
111 |
return notfound
|
112 |
|
113 |
def block_retr(self, hashes): |
114 |
"""Retrieve blocks from storage by their hashes."""
|
115 |
blocksize = self.blocksize
|
116 |
blocks = [] |
117 |
append = blocks.append |
118 |
block = None
|
119 |
|
120 |
for h in hashes: |
121 |
if h == self.emptyhash: |
122 |
append(self._pad('')) |
123 |
continue
|
124 |
with self._get_rear_block(h, create=False, write=False) as rbl: |
125 |
if not rbl: |
126 |
break
|
127 |
for block in rbl.sync_read_chunks(blocksize, 1, 0): |
128 |
break # there should be just one block there |
129 |
if not block: |
130 |
break
|
131 |
append(self._pad(block))
|
132 |
|
133 |
return blocks
|
134 |
|
135 |
def block_stor(self, blocklist): |
136 |
"""Store a bunch of blocks and return (hashes, missing).
|
137 |
Hashes is a list of the hashes of the blocks,
|
138 |
missing is a list of indices in that list indicating
|
139 |
which blocks were missing from the store.
|
140 |
"""
|
141 |
block_hash = self.block_hash
|
142 |
hashlist = [block_hash(b) for b in blocklist] |
143 |
missing = [i for i, h in enumerate(hashlist) |
144 |
if not self._check_rear_block(h)] |
145 |
for i in missing: |
146 |
with self._get_rear_block(hashlist[i], |
147 |
create=True, write=False) as rbl: |
148 |
# ^^^^^^^^^^^
|
149 |
# do not overwrite if exists
|
150 |
rbl.sync_write(blocklist[i]) # XXX: verify?
|
151 |
|
152 |
return hashlist, missing
|
153 |
|
154 |
def block_delta(self, blkhash, offset, data): |
155 |
"""Construct and store a new block from a given block
|
156 |
and a data 'patch' applied at offset. Return:
|
157 |
(the hash of the new block, if the block already existed)
|
158 |
"""
|
159 |
|
160 |
blocksize = self.blocksize
|
161 |
if offset >= blocksize or not data: |
162 |
return None, None |
163 |
|
164 |
block = self.block_retr((blkhash,))
|
165 |
if not block: |
166 |
return None, None |
167 |
|
168 |
block = block[0]
|
169 |
newblock = block[:offset] + data |
170 |
if len(newblock) > blocksize: |
171 |
newblock = newblock[:blocksize] |
172 |
elif len(newblock) < blocksize: |
173 |
newblock += block[len(newblock):]
|
174 |
|
175 |
h, a = self.block_stor((newblock,))
|
176 |
return h[0], 1 if a else 0 |
177 |
|
178 |
def block_hash_file(self, openfile): |
179 |
"""Return the list of hashes (hashes map)
|
180 |
for the blocks in a buffered file.
|
181 |
Helper method, does not affect store.
|
182 |
"""
|
183 |
hashes = [] |
184 |
append = hashes.append |
185 |
block_hash = self.block_hash
|
186 |
|
187 |
for block in file_sync_read_chunks(openfile, self.blocksize, 1, 0): |
188 |
append(block_hash(block)) |
189 |
|
190 |
return hashes
|
191 |
|
192 |
def block_stor_file(self, openfile): |
193 |
"""Read blocks from buffered file object and store them. Return:
|
194 |
(bytes read, list of hashes, list of hashes that were missing)
|
195 |
"""
|
196 |
blocksize = self.blocksize
|
197 |
block_stor = self.block_stor
|
198 |
hashlist = [] |
199 |
hextend = hashlist.extend |
200 |
storedlist = [] |
201 |
sextend = storedlist.extend |
202 |
lastsize = 0
|
203 |
|
204 |
for block in file_sync_read_chunks(openfile, blocksize, 1, 0): |
205 |
hl, sl = block_stor((block,)) |
206 |
hextend(hl) |
207 |
sextend(sl) |
208 |
lastsize = len(block)
|
209 |
|
210 |
size = (len(hashlist) -1) * blocksize + lastsize if hashlist else 0 |
211 |
return size, hashlist, storedlist
|
212 |
|