]> git.rkrishnan.org Git - tahoe-lafs/tahoe-lafs.git/blob - src/allmydata/storage/server.py
BucketCountingCrawler: store just the count, not cycle+count, since it's too easy...
[tahoe-lafs/tahoe-lafs.git] / src / allmydata / storage / server.py
1 import os, re, weakref, struct, time
2
3 from foolscap import Referenceable
4 from twisted.application import service
5
6 from zope.interface import implements
7 from allmydata.interfaces import RIStorageServer, IStatsProducer
8 from allmydata.util import base32, fileutil, log, time_format
9 import allmydata # for __full_version__
10
11 from allmydata.storage.common import si_b2a, si_a2b, storage_index_to_dir
12 _pyflakes_hush = [si_b2a, si_a2b, storage_index_to_dir] # re-exported
13 from allmydata.storage.lease import LeaseInfo
14 from allmydata.storage.mutable import MutableShareFile, EmptyShare, \
15      create_mutable_sharefile
16 from allmydata.storage.immutable import ShareFile, BucketWriter, BucketReader
17 from allmydata.storage.crawler import BucketCountingCrawler
18
19 # storage/
20 # storage/shares/incoming
21 #   incoming/ holds temp dirs named $START/$STORAGEINDEX/$SHARENUM which will
22 #   be moved to storage/shares/$START/$STORAGEINDEX/$SHARENUM upon success
23 # storage/shares/$START/$STORAGEINDEX
24 # storage/shares/$START/$STORAGEINDEX/$SHARENUM
25
26 # Where "$START" denotes the first 10 bits worth of $STORAGEINDEX (that's 2
27 # base-32 chars).
28
29 # $SHARENUM matches this regex:
30 NUM_RE=re.compile("^[0-9]+$")
31
32
33
34 class StorageServer(service.MultiService, Referenceable):
35     implements(RIStorageServer, IStatsProducer)
36     name = 'storage'
37
38     def __init__(self, storedir, nodeid, reserved_space=0,
39                  discard_storage=False, readonly_storage=False,
40                  stats_provider=None):
41         service.MultiService.__init__(self)
42         assert isinstance(nodeid, str)
43         assert len(nodeid) == 20
44         self.my_nodeid = nodeid
45         self.storedir = storedir
46         sharedir = os.path.join(storedir, "shares")
47         fileutil.make_dirs(sharedir)
48         self.sharedir = sharedir
49         # we don't actually create the corruption-advisory dir until necessary
50         self.corruption_advisory_dir = os.path.join(storedir,
51                                                     "corruption-advisories")
52         self.reserved_space = int(reserved_space)
53         self.no_storage = discard_storage
54         self.readonly_storage = readonly_storage
55         self.stats_provider = stats_provider
56         if self.stats_provider:
57             self.stats_provider.register_producer(self)
58         self.incomingdir = os.path.join(sharedir, 'incoming')
59         self._clean_incomplete()
60         fileutil.make_dirs(self.incomingdir)
61         self._active_writers = weakref.WeakKeyDictionary()
62         lp = log.msg("StorageServer created", facility="tahoe.storage")
63
64         if reserved_space:
65             if self.get_available_space() is None:
66                 log.msg("warning: [storage]reserved_space= is set, but this platform does not support statvfs(2), so this reservation cannot be honored",
67                         umin="0wZ27w", level=log.UNUSUAL)
68
69         self.latencies = {"allocate": [], # immutable
70                           "write": [],
71                           "close": [],
72                           "read": [],
73                           "get": [],
74                           "writev": [], # mutable
75                           "readv": [],
76                           "add-lease": [], # both
77                           "renew": [],
78                           "cancel": [],
79                           }
80
81         statefile = os.path.join(storedir, "bucket_counter.state")
82         self.bucket_counter = BucketCountingCrawler(self, statefile)
83         self.bucket_counter.setServiceParent(self)
84
85     def count(self, name, delta=1):
86         if self.stats_provider:
87             self.stats_provider.count("storage_server." + name, delta)
88
89     def add_latency(self, category, latency):
90         a = self.latencies[category]
91         a.append(latency)
92         if len(a) > 1000:
93             self.latencies[category] = a[-1000:]
94
95     def get_latencies(self):
96         """Return a dict, indexed by category, that contains a dict of
97         latency numbers for each category. Each dict will contain the
98         following keys: mean, 01_0_percentile, 10_0_percentile,
99         50_0_percentile (median), 90_0_percentile, 95_0_percentile,
100         99_0_percentile, 99_9_percentile. If no samples have been collected
101         for the given category, then that category name will not be present
102         in the return value."""
103         # note that Amazon's Dynamo paper says they use 99.9% percentile.
104         output = {}
105         for category in self.latencies:
106             if not self.latencies[category]:
107                 continue
108             stats = {}
109             samples = self.latencies[category][:]
110             samples.sort()
111             count = len(samples)
112             stats["mean"] = sum(samples) / count
113             stats["01_0_percentile"] = samples[int(0.01 * count)]
114             stats["10_0_percentile"] = samples[int(0.1 * count)]
115             stats["50_0_percentile"] = samples[int(0.5 * count)]
116             stats["90_0_percentile"] = samples[int(0.9 * count)]
117             stats["95_0_percentile"] = samples[int(0.95 * count)]
118             stats["99_0_percentile"] = samples[int(0.99 * count)]
119             stats["99_9_percentile"] = samples[int(0.999 * count)]
120             output[category] = stats
121         return output
122
123     def log(self, *args, **kwargs):
124         if "facility" not in kwargs:
125             kwargs["facility"] = "tahoe.storage"
126         return log.msg(*args, **kwargs)
127
128     def _clean_incomplete(self):
129         fileutil.rm_dir(self.incomingdir)
130
131     def do_statvfs(self):
132         return os.statvfs(self.storedir)
133
134     def get_stats(self):
135         # remember: RIStatsProvider requires that our return dict
136         # contains numeric values.
137         stats = { 'storage_server.allocated': self.allocated_size(), }
138         stats["storage_server.reserved_space"] = self.reserved_space
139         for category,ld in self.get_latencies().items():
140             for name,v in ld.items():
141                 stats['storage_server.latencies.%s.%s' % (category, name)] = v
142         writeable = True
143         if self.readonly_storage:
144             writeable = False
145         try:
146             s = self.do_statvfs()
147             disk_total = s.f_bsize * s.f_blocks
148             disk_used = s.f_bsize * (s.f_blocks - s.f_bfree)
149             # spacetime predictors should look at the slope of disk_used.
150             disk_free_for_root = s.f_bsize * s.f_bfree
151             disk_free_for_nonroot = s.f_bsize * s.f_bavail
152
153             # include our local policy here: if we stop accepting shares when
154             # the available space drops below 1GB, then include that fact in
155             # disk_avail.
156             disk_avail = disk_free_for_nonroot - self.reserved_space
157             disk_avail = max(disk_avail, 0)
158             if self.readonly_storage:
159                 disk_avail = 0
160             if disk_avail == 0:
161                 writeable = False
162
163             # spacetime predictors should use disk_avail / (d(disk_used)/dt)
164             stats["storage_server.disk_total"] = disk_total
165             stats["storage_server.disk_used"] = disk_used
166             stats["storage_server.disk_free_for_root"] = disk_free_for_root
167             stats["storage_server.disk_free_for_nonroot"] = disk_free_for_nonroot
168             stats["storage_server.disk_avail"] = disk_avail
169         except AttributeError:
170             # os.statvfs is available only on unix
171             pass
172         stats["storage_server.accepting_immutable_shares"] = int(writeable)
173         s = self.bucket_counter.get_state()
174         bucket_count = s.get("last-complete-bucket-count")
175         if bucket_count:
176             stats["storage_server.total_bucket_count"] = bucket_count
177         return stats
178
179
180     def stat_disk(self, d):
181         s = os.statvfs(d)
182         # s.f_bavail: available to non-root users
183         disk_avail = s.f_bsize * s.f_bavail
184         return disk_avail
185
186     def get_available_space(self):
187         # returns None if it cannot be measured (windows)
188         try:
189             disk_avail = self.stat_disk(self.storedir)
190             disk_avail -= self.reserved_space
191         except AttributeError:
192             disk_avail = None
193         if self.readonly_storage:
194             disk_avail = 0
195         return disk_avail
196
197     def allocated_size(self):
198         space = 0
199         for bw in self._active_writers:
200             space += bw.allocated_size()
201         return space
202
203     def remote_get_version(self):
204         remaining_space = self.get_available_space()
205         if remaining_space is None:
206             # we're on a platform that doesn't have 'df', so make a vague
207             # guess.
208             remaining_space = 2**64
209         version = { "http://allmydata.org/tahoe/protocols/storage/v1" :
210                     { "maximum-immutable-share-size": remaining_space,
211                       "tolerates-immutable-read-overrun": True,
212                       "delete-mutable-shares-with-zero-length-writev": True,
213                       },
214                     "application-version": str(allmydata.__full_version__),
215                     }
216         return version
217
218     def remote_allocate_buckets(self, storage_index,
219                                 renew_secret, cancel_secret,
220                                 sharenums, allocated_size,
221                                 canary, owner_num=0):
222         # owner_num is not for clients to set, but rather it should be
223         # curried into the PersonalStorageServer instance that is dedicated
224         # to a particular owner.
225         start = time.time()
226         self.count("allocate")
227         alreadygot = set()
228         bucketwriters = {} # k: shnum, v: BucketWriter
229         si_dir = storage_index_to_dir(storage_index)
230         si_s = si_b2a(storage_index)
231
232         log.msg("storage: allocate_buckets %s" % si_s)
233
234         # in this implementation, the lease information (including secrets)
235         # goes into the share files themselves. It could also be put into a
236         # separate database. Note that the lease should not be added until
237         # the BucketWriter has been closed.
238         expire_time = time.time() + 31*24*60*60
239         lease_info = LeaseInfo(owner_num,
240                                renew_secret, cancel_secret,
241                                expire_time, self.my_nodeid)
242
243         max_space_per_bucket = allocated_size
244
245         remaining_space = self.get_available_space()
246         limited = remaining_space is not None
247         if limited:
248             # this is a bit conservative, since some of this allocated_size()
249             # has already been written to disk, where it will show up in
250             # get_available_space.
251             remaining_space -= self.allocated_size()
252
253         # fill alreadygot with all shares that we have, not just the ones
254         # they asked about: this will save them a lot of work. Add or update
255         # leases for all of them: if they want us to hold shares for this
256         # file, they'll want us to hold leases for this file.
257         for (shnum, fn) in self._get_bucket_shares(storage_index):
258             alreadygot.add(shnum)
259             sf = ShareFile(fn)
260             sf.add_or_renew_lease(lease_info)
261
262         # self.readonly_storage causes remaining_space=0
263
264         for shnum in sharenums:
265             incominghome = os.path.join(self.incomingdir, si_dir, "%d" % shnum)
266             finalhome = os.path.join(self.sharedir, si_dir, "%d" % shnum)
267             if os.path.exists(finalhome):
268                 # great! we already have it. easy.
269                 pass
270             elif os.path.exists(incominghome):
271                 # Note that we don't create BucketWriters for shnums that
272                 # have a partial share (in incoming/), so if a second upload
273                 # occurs while the first is still in progress, the second
274                 # uploader will use different storage servers.
275                 pass
276             elif (not limited) or (remaining_space >= max_space_per_bucket):
277                 # ok! we need to create the new share file.
278                 bw = BucketWriter(self, incominghome, finalhome,
279                                   max_space_per_bucket, lease_info, canary)
280                 if self.no_storage:
281                     bw.throw_out_all_data = True
282                 bucketwriters[shnum] = bw
283                 self._active_writers[bw] = 1
284                 if limited:
285                     remaining_space -= max_space_per_bucket
286             else:
287                 # bummer! not enough space to accept this bucket
288                 pass
289
290         if bucketwriters:
291             fileutil.make_dirs(os.path.join(self.sharedir, si_dir))
292
293         self.add_latency("allocate", time.time() - start)
294         return alreadygot, bucketwriters
295
296     def _iter_share_files(self, storage_index):
297         for shnum, filename in self._get_bucket_shares(storage_index):
298             f = open(filename, 'rb')
299             header = f.read(32)
300             f.close()
301             if header[:32] == MutableShareFile.MAGIC:
302                 sf = MutableShareFile(filename, self)
303                 # note: if the share has been migrated, the renew_lease()
304                 # call will throw an exception, with information to help the
305                 # client update the lease.
306             elif header[:4] == struct.pack(">L", 1):
307                 sf = ShareFile(filename)
308             else:
309                 continue # non-sharefile
310             yield sf
311
312     def remote_add_lease(self, storage_index, renew_secret, cancel_secret,
313                          owner_num=1):
314         start = time.time()
315         self.count("add-lease")
316         new_expire_time = time.time() + 31*24*60*60
317         lease_info = LeaseInfo(owner_num,
318                                renew_secret, cancel_secret,
319                                new_expire_time, self.my_nodeid)
320         for sf in self._iter_share_files(storage_index):
321             sf.add_or_renew_lease(lease_info)
322         self.add_latency("add-lease", time.time() - start)
323         return None
324
325     def remote_renew_lease(self, storage_index, renew_secret):
326         start = time.time()
327         self.count("renew")
328         new_expire_time = time.time() + 31*24*60*60
329         found_buckets = False
330         for sf in self._iter_share_files(storage_index):
331             found_buckets = True
332             sf.renew_lease(renew_secret, new_expire_time)
333         self.add_latency("renew", time.time() - start)
334         if not found_buckets:
335             raise IndexError("no such lease to renew")
336
337     def remote_cancel_lease(self, storage_index, cancel_secret):
338         start = time.time()
339         self.count("cancel")
340
341         total_space_freed = 0
342         found_buckets = False
343         for sf in self._iter_share_files(storage_index):
344             # note: if we can't find a lease on one share, we won't bother
345             # looking in the others. Unless something broke internally
346             # (perhaps we ran out of disk space while adding a lease), the
347             # leases on all shares will be identical.
348             found_buckets = True
349             # this raises IndexError if the lease wasn't present XXXX
350             total_space_freed += sf.cancel_lease(cancel_secret)
351
352         if found_buckets:
353             storagedir = os.path.join(self.sharedir,
354                                       storage_index_to_dir(storage_index))
355             if not os.listdir(storagedir):
356                 os.rmdir(storagedir)
357
358         if self.stats_provider:
359             self.stats_provider.count('storage_server.bytes_freed',
360                                       total_space_freed)
361         self.add_latency("cancel", time.time() - start)
362         if not found_buckets:
363             raise IndexError("no such storage index")
364
365     def bucket_writer_closed(self, bw, consumed_size):
366         if self.stats_provider:
367             self.stats_provider.count('storage_server.bytes_added', consumed_size)
368         del self._active_writers[bw]
369
370     def _get_bucket_shares(self, storage_index):
371         """Return a list of (shnum, pathname) tuples for files that hold
372         shares for this storage_index. In each tuple, 'shnum' will always be
373         the integer form of the last component of 'pathname'."""
374         storagedir = os.path.join(self.sharedir, storage_index_to_dir(storage_index))
375         try:
376             for f in os.listdir(storagedir):
377                 if NUM_RE.match(f):
378                     filename = os.path.join(storagedir, f)
379                     yield (int(f), filename)
380         except OSError:
381             # Commonly caused by there being no buckets at all.
382             pass
383
384     def remote_get_buckets(self, storage_index):
385         start = time.time()
386         self.count("get")
387         si_s = si_b2a(storage_index)
388         log.msg("storage: get_buckets %s" % si_s)
389         bucketreaders = {} # k: sharenum, v: BucketReader
390         for shnum, filename in self._get_bucket_shares(storage_index):
391             bucketreaders[shnum] = BucketReader(self, filename,
392                                                 storage_index, shnum)
393         self.add_latency("get", time.time() - start)
394         return bucketreaders
395
396     def get_leases(self, storage_index):
397         """Provide an iterator that yields all of the leases attached to this
398         bucket. Each lease is returned as a tuple of (owner_num,
399         renew_secret, cancel_secret, expiration_time).
400
401         This method is not for client use.
402         """
403
404         # since all shares get the same lease data, we just grab the leases
405         # from the first share
406         try:
407             shnum, filename = self._get_bucket_shares(storage_index).next()
408             sf = ShareFile(filename)
409             return sf.iter_leases()
410         except StopIteration:
411             return iter([])
412
413     def remote_slot_testv_and_readv_and_writev(self, storage_index,
414                                                secrets,
415                                                test_and_write_vectors,
416                                                read_vector):
417         start = time.time()
418         self.count("writev")
419         si_s = si_b2a(storage_index)
420         lp = log.msg("storage: slot_writev %s" % si_s)
421         si_dir = storage_index_to_dir(storage_index)
422         (write_enabler, renew_secret, cancel_secret) = secrets
423         # shares exist if there is a file for them
424         bucketdir = os.path.join(self.sharedir, si_dir)
425         shares = {}
426         if os.path.isdir(bucketdir):
427             for sharenum_s in os.listdir(bucketdir):
428                 try:
429                     sharenum = int(sharenum_s)
430                 except ValueError:
431                     continue
432                 filename = os.path.join(bucketdir, sharenum_s)
433                 msf = MutableShareFile(filename, self)
434                 msf.check_write_enabler(write_enabler, si_s)
435                 shares[sharenum] = msf
436         # write_enabler is good for all existing shares.
437
438         # Now evaluate test vectors.
439         testv_is_good = True
440         for sharenum in test_and_write_vectors:
441             (testv, datav, new_length) = test_and_write_vectors[sharenum]
442             if sharenum in shares:
443                 if not shares[sharenum].check_testv(testv):
444                     self.log("testv failed: [%d]: %r" % (sharenum, testv))
445                     testv_is_good = False
446                     break
447             else:
448                 # compare the vectors against an empty share, in which all
449                 # reads return empty strings.
450                 if not EmptyShare().check_testv(testv):
451                     self.log("testv failed (empty): [%d] %r" % (sharenum,
452                                                                 testv))
453                     testv_is_good = False
454                     break
455
456         # now gather the read vectors, before we do any writes
457         read_data = {}
458         for sharenum, share in shares.items():
459             read_data[sharenum] = share.readv(read_vector)
460
461         ownerid = 1 # TODO
462         expire_time = time.time() + 31*24*60*60   # one month
463         lease_info = LeaseInfo(ownerid,
464                                renew_secret, cancel_secret,
465                                expire_time, self.my_nodeid)
466
467         if testv_is_good:
468             # now apply the write vectors
469             for sharenum in test_and_write_vectors:
470                 (testv, datav, new_length) = test_and_write_vectors[sharenum]
471                 if new_length == 0:
472                     if sharenum in shares:
473                         shares[sharenum].unlink()
474                 else:
475                     if sharenum not in shares:
476                         # allocate a new share
477                         allocated_size = 2000 # arbitrary, really
478                         share = self._allocate_slot_share(bucketdir, secrets,
479                                                           sharenum,
480                                                           allocated_size,
481                                                           owner_num=0)
482                         shares[sharenum] = share
483                     shares[sharenum].writev(datav, new_length)
484                     # and update the lease
485                     shares[sharenum].add_or_renew_lease(lease_info)
486
487             if new_length == 0:
488                 # delete empty bucket directories
489                 if not os.listdir(bucketdir):
490                     os.rmdir(bucketdir)
491
492
493         # all done
494         self.add_latency("writev", time.time() - start)
495         return (testv_is_good, read_data)
496
497     def _allocate_slot_share(self, bucketdir, secrets, sharenum,
498                              allocated_size, owner_num=0):
499         (write_enabler, renew_secret, cancel_secret) = secrets
500         my_nodeid = self.my_nodeid
501         fileutil.make_dirs(bucketdir)
502         filename = os.path.join(bucketdir, "%d" % sharenum)
503         share = create_mutable_sharefile(filename, my_nodeid, write_enabler,
504                                          self)
505         return share
506
507     def remote_slot_readv(self, storage_index, shares, readv):
508         start = time.time()
509         self.count("readv")
510         si_s = si_b2a(storage_index)
511         lp = log.msg("storage: slot_readv %s %s" % (si_s, shares),
512                      facility="tahoe.storage", level=log.OPERATIONAL)
513         si_dir = storage_index_to_dir(storage_index)
514         # shares exist if there is a file for them
515         bucketdir = os.path.join(self.sharedir, si_dir)
516         if not os.path.isdir(bucketdir):
517             self.add_latency("readv", time.time() - start)
518             return {}
519         datavs = {}
520         for sharenum_s in os.listdir(bucketdir):
521             try:
522                 sharenum = int(sharenum_s)
523             except ValueError:
524                 continue
525             if sharenum in shares or not shares:
526                 filename = os.path.join(bucketdir, sharenum_s)
527                 msf = MutableShareFile(filename, self)
528                 datavs[sharenum] = msf.readv(readv)
529         log.msg("returning shares %s" % (datavs.keys(),),
530                 facility="tahoe.storage", level=log.NOISY, parent=lp)
531         self.add_latency("readv", time.time() - start)
532         return datavs
533
534     def remote_advise_corrupt_share(self, share_type, storage_index, shnum,
535                                     reason):
536         fileutil.make_dirs(self.corruption_advisory_dir)
537         now = time_format.iso_utc(sep="T")
538         si_s = base32.b2a(storage_index)
539         # windows can't handle colons in the filename
540         fn = os.path.join(self.corruption_advisory_dir,
541                           "%s--%s-%d" % (now, si_s, shnum)).replace(":","")
542         f = open(fn, "w")
543         f.write("report: Share Corruption\n")
544         f.write("type: %s\n" % share_type)
545         f.write("storage_index: %s\n" % si_s)
546         f.write("share_number: %d\n" % shnum)
547         f.write("\n")
548         f.write(reason)
549         f.write("\n")
550         f.close()
551         log.msg(format=("client claims corruption in (%(share_type)s) " +
552                         "%(si)s-%(shnum)d: %(reason)s"),
553                 share_type=share_type, si=si_s, shnum=shnum, reason=reason,
554                 level=log.SCARY, umid="SGx2fA")
555         return None
556