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
|
# Copyright (C) 2005 by Canonical Development Ltd
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
"""
Stores are the main data-storage mechanism for Bazaar-NG.
A store is a simple write-once container indexed by a universally
unique ID.
"""
import os, tempfile, types, osutils, gzip, errno
from stat import ST_SIZE
from StringIO import StringIO
from bzrlib.errors import BzrError
from bzrlib.trace import mutter
import bzrlib.ui
from bzrlib.remotebranch import get_url
######################################################################
# stores
class StoreError(Exception):
pass
class Store(object):
"""An abstract store that holds files indexed by unique names.
Files can be added, but not modified once they are in. Typically
the hash is used as the name, or something else known to be unique,
such as a UUID.
>>> st = ImmutableScratchStore()
>>> st.add(StringIO('hello'), 'aa')
>>> 'aa' in st
True
>>> 'foo' in st
False
You are not allowed to add an id that is already present.
Entries can be retrieved as files, which may then be read.
>>> st.add(StringIO('goodbye'), '123123')
>>> st['123123'].read()
'goodbye'
"""
def total_size(self):
"""Return (count, bytes)
This is the (compressed) size stored on disk, not the size of
the content."""
total = 0
count = 0
for fid in self:
count += 1
total += self._item_size(fid)
return count, total
class ImmutableStore(Store):
"""Store that stores files on disk.
TODO: Atomic add by writing to a temporary file and renaming.
TODO: Guard against the same thing being stored twice, compressed and
uncompressed during copy_multi_immutable - the window is for a
matching store with some crack code that lets it offer a
non gz FOO and then a fz FOO.
In bzr 0.0.5 and earlier, files within the store were marked
readonly on disk. This is no longer done but existing stores need
to be accomodated.
"""
def __init__(self, basedir):
super(ImmutableStore, self).__init__()
self._basedir = basedir
def _path(self, entry_id):
if not isinstance(entry_id, basestring):
raise TypeError(type(entry_id))
if '\\' in entry_id or '/' in entry_id:
raise ValueError("invalid store id %r" % entry_id)
return os.path.join(self._basedir, entry_id)
def __repr__(self):
return "%s(%r)" % (self.__class__.__name__, self._basedir)
def add(self, f, fileid, compressed=True):
"""Add contents of a file into the store.
f -- An open file, or file-like object."""
# FIXME: Only works on files that will fit in memory
from bzrlib.atomicfile import AtomicFile
mutter("add store entry %r" % (fileid))
if isinstance(f, types.StringTypes):
content = f
else:
content = f.read()
p = self._path(fileid)
if os.access(p, os.F_OK) or os.access(p + '.gz', os.F_OK):
raise BzrError("store %r already contains id %r" % (self._basedir, fileid))
fn = p
if compressed:
fn = fn + '.gz'
af = AtomicFile(fn, 'wb')
try:
if compressed:
gf = gzip.GzipFile(mode='wb', fileobj=af)
gf.write(content)
gf.close()
else:
af.write(content)
af.commit()
finally:
af.close()
def copy_multi(self, other, ids, permit_failure=False):
"""Copy texts for ids from other into self.
If an id is present in self, it is skipped.
Returns (count_copied, failed), where failed is a collection of ids
that could not be copied.
"""
pb = bzrlib.ui.ui_factory.progress_bar()
pb.update('preparing to copy')
to_copy = [id for id in ids if id not in self]
if isinstance(other, ImmutableStore):
return self.copy_multi_immutable(other, to_copy, pb)
count = 0
failed = set()
for id in to_copy:
count += 1
pb.update('copy', count, len(to_copy))
if not permit_failure:
self.add(other[id], id)
else:
try:
entry = other[id]
except IndexError:
failed.add(id)
continue
self.add(entry, id)
if not permit_failure:
assert count == len(to_copy)
pb.clear()
return count, failed
def copy_multi_immutable(self, other, to_copy, pb, permit_failure=False):
from shutil import copyfile
count = 0
failed = set()
for id in to_copy:
p = self._path(id)
other_p = other._path(id)
try:
copyfile(other_p, p)
except IOError, e:
if e.errno == errno.ENOENT:
if not permit_failure:
copyfile(other_p+".gz", p+".gz")
else:
try:
copyfile(other_p+".gz", p+".gz")
except IOError, e:
if e.errno == errno.ENOENT:
failed.add(id)
else:
raise
else:
raise
count += 1
pb.update('copy', count, len(to_copy))
assert count == len(to_copy)
pb.clear()
return count, failed
def __contains__(self, fileid):
""""""
p = self._path(fileid)
return (os.access(p, os.R_OK)
or os.access(p + '.gz', os.R_OK))
def _item_size(self, fid):
p = self._path(fid)
try:
return os.stat(p)[ST_SIZE]
except OSError:
return os.stat(p + '.gz')[ST_SIZE]
def __iter__(self):
for f in os.listdir(self._basedir):
if f[-3:] == '.gz':
# TODO: case-insensitive?
yield f[:-3]
else:
yield f
def __len__(self):
return len(os.listdir(self._basedir))
def __getitem__(self, fileid):
"""Returns a file reading from a particular entry."""
p = self._path(fileid)
try:
return gzip.GzipFile(p + '.gz', 'rb')
except IOError, e:
if e.errno != errno.ENOENT:
raise
try:
return file(p, 'rb')
except IOError, e:
if e.errno != errno.ENOENT:
raise
raise IndexError(fileid)
class ImmutableScratchStore(ImmutableStore):
"""Self-destructing test subclass of ImmutableStore.
The Store only exists for the lifetime of the Python object.
Obviously you should not put anything precious in it.
"""
def __init__(self):
super(ImmutableScratchStore, self).__init__(tempfile.mkdtemp())
def __del__(self):
for f in os.listdir(self._basedir):
fpath = os.path.join(self._basedir, f)
# needed on windows, and maybe some other filesystems
os.chmod(fpath, 0600)
os.remove(fpath)
os.rmdir(self._basedir)
mutter("%r destroyed" % self)
class ImmutableMemoryStore(Store):
"""A memory only store."""
def __init__(self):
super(ImmutableMemoryStore, self).__init__()
self._contents = {}
def add(self, stream, fileid, compressed=True):
if self._contents.has_key(fileid):
raise StoreError("fileid %s already in the store" % fileid)
self._contents[fileid] = stream.read()
def __getitem__(self, fileid):
"""Returns a file reading from a particular entry."""
if not self._contents.has_key(fileid):
raise IndexError
return StringIO(self._contents[fileid])
def _item_size(self, fileid):
return len(self._contents[fileid])
def __iter__(self):
return iter(self._contents.keys())
class RemoteStore(object):
def __init__(self, baseurl):
self._baseurl = baseurl
def _path(self, name):
if '/' in name:
raise ValueError('invalid store id', name)
return self._baseurl + '/' + name
def __getitem__(self, fileid):
p = self._path(fileid)
try:
return get_url(p, compressed=True)
except:
raise KeyError(fileid)
class CachedStore:
"""A store that caches data locally, to avoid repeated downloads.
The precacache method should be used to avoid server round-trips for
every piece of data.
"""
def __init__(self, store, cache_dir):
self.source_store = store
self.cache_store = ImmutableStore(cache_dir)
def __getitem__(self, id):
mutter("Cache add %s" % id)
if id not in self.cache_store:
self.cache_store.add(self.source_store[id], id)
return self.cache_store[id]
def prefetch(self, ids):
"""Copy a series of ids into the cache, before they are used.
For remote stores that support pipelining or async downloads, this can
increase speed considerably.
"""
mutter("Prefetch of ids %s" % ",".join(ids))
self.cache_store.copy_multi(self.source_store, ids)
|