2 import os, stat, time, weakref
3 from zope.interface import implements
4 from twisted.internet import defer
5 from foolscap.api import Referenceable, DeadReferenceError, eventually
6 import allmydata # for __full_version__
7 from allmydata import interfaces, uri
8 from allmydata.storage.server import si_b2a
9 from allmydata.immutable import upload
10 from allmydata.immutable.layout import ReadBucketProxy
11 from allmydata.util.assertutil import precondition
12 from allmydata.util import log, observer, fileutil, hashutil, dictutil
15 class NotEnoughWritersError(Exception):
19 class CHKCheckerAndUEBFetcher:
20 """I check to see if a file is already present in the grid. I also fetch
21 the URI Extension Block, which is useful for an uploading client who
22 wants to avoid the work of encryption and encoding.
24 I return False if the file is not completely healthy: i.e. if there are
25 less than 'N' shares present.
27 If the file is completely healthy, I return a tuple of (sharemap,
31 def __init__(self, peer_getter, storage_index, logparent=None):
32 self._peer_getter = peer_getter
33 self._found_shares = set()
34 self._storage_index = storage_index
35 self._sharemap = dictutil.DictOfSets()
39 self._logparent = logparent
41 def log(self, *args, **kwargs):
42 if 'facility' not in kwargs:
43 kwargs['facility'] = "tahoe.helper.chk.checkandUEBfetch"
44 if 'parent' not in kwargs:
45 kwargs['parent'] = self._logparent
46 return log.msg(*args, **kwargs)
49 d = self._get_all_shareholders(self._storage_index)
50 d.addCallback(self._get_uri_extension)
51 d.addCallback(self._done)
54 def _get_all_shareholders(self, storage_index):
56 for s in self._peer_getter(storage_index):
57 d = s.get_rref().callRemote("get_buckets", storage_index)
58 d.addCallbacks(self._got_response, self._got_error,
61 return defer.DeferredList(dl)
63 def _got_response(self, buckets, server):
64 # buckets is a dict: maps shum to an rref of the server who holds it
65 shnums_s = ",".join([str(shnum) for shnum in buckets])
66 self.log("got_response: [%s] has %d shares (%s)" %
67 (server.get_name(), len(buckets), shnums_s),
69 self._found_shares.update(buckets.keys())
71 self._sharemap.add(k, server.get_serverid())
72 self._readers.update( [ (bucket, server)
73 for bucket in buckets.values() ] )
75 def _got_error(self, f):
76 if f.check(DeadReferenceError):
78 log.err(f, parent=self._logparent)
81 def _get_uri_extension(self, res):
82 # assume that we can pull the UEB from any share. If we get an error,
83 # declare the whole file unavailable.
85 self.log("no readers, so no UEB", level=log.NOISY)
87 b,server = self._readers.pop()
88 rbp = ReadBucketProxy(b, server, si_b2a(self._storage_index))
89 d = rbp.get_uri_extension()
90 d.addCallback(self._got_uri_extension)
91 d.addErrback(self._ueb_error)
94 def _got_uri_extension(self, ueb):
95 self.log("_got_uri_extension", level=log.NOISY)
96 self._ueb_hash = hashutil.uri_extension_hash(ueb)
97 self._ueb_data = uri.unpack_extension(ueb)
99 def _ueb_error(self, f):
100 # an error means the file is unavailable, but the overall check
102 self.log("UEB fetch failed", failure=f, level=log.WEIRD, umid="sJLKVg")
105 def _done(self, res):
107 found = len(self._found_shares)
108 total = self._ueb_data['total_shares']
109 self.log(format="got %(found)d shares of %(total)d",
110 found=found, total=total, level=log.NOISY)
112 # not all shares are present in the grid
113 self.log("not enough to qualify, file not found in grid",
116 # all shares are present
117 self.log("all shares present, file is found in grid",
119 return (self._sharemap, self._ueb_data, self._ueb_hash)
120 # no shares are present
121 self.log("unable to find UEB data, file not found in grid",
126 class CHKUploadHelper(Referenceable, upload.CHKUploader):
127 """I am the helper-server -side counterpart to AssistedUploader. I handle
128 peer selection, encoding, and share pushing. I read ciphertext from the
129 remote AssistedUploader.
131 implements(interfaces.RICHKUploadHelper)
132 VERSION = { "http://allmydata.org/tahoe/protocols/helper/chk-upload/v1" :
134 "application-version": str(allmydata.__full_version__),
137 def __init__(self, storage_index,
138 helper, storage_broker, secret_holder,
139 incoming_file, encoding_file,
141 self._storage_index = storage_index
142 self._helper = helper
143 self._incoming_file = incoming_file
144 self._encoding_file = encoding_file
145 self._upload_id = si_b2a(storage_index)[:5]
146 self._log_number = log_number
147 self._upload_status = upload.UploadStatus()
148 self._upload_status.set_helper(False)
149 self._upload_status.set_storage_index(storage_index)
150 self._upload_status.set_status("fetching ciphertext")
151 self._upload_status.set_progress(0, 1.0)
152 self._helper.log("CHKUploadHelper starting for SI %s" % self._upload_id,
155 self._storage_broker = storage_broker
156 self._secret_holder = secret_holder
157 self._fetcher = CHKCiphertextFetcher(self, incoming_file, encoding_file,
159 self._reader = LocalCiphertextReader(self, storage_index, encoding_file)
160 self._finished_observers = observer.OneShotObserverList()
162 self._started = time.time()
163 d = self._fetcher.when_done()
164 d.addCallback(lambda res: self._reader.start())
165 d.addCallback(lambda res: self.start_encrypted(self._reader))
166 d.addCallback(self._finished)
167 d.addErrback(self._failed)
169 def log(self, *args, **kwargs):
170 if 'facility' not in kwargs:
171 kwargs['facility'] = "tahoe.helper.chk"
172 return upload.CHKUploader.log(self, *args, **kwargs)
174 def remote_get_version(self):
177 def remote_upload(self, reader):
178 # reader is an RIEncryptedUploadable. I am specified to return an
179 # UploadResults dictionary.
181 # Log how much ciphertext we need to get.
182 self.log("deciding whether to upload the file or not", level=log.NOISY)
183 if os.path.exists(self._encoding_file):
184 # we have the whole file, and we might be encoding it (or the
185 # encode/upload might have failed, and we need to restart it).
186 self.log("ciphertext already in place", level=log.UNUSUAL)
187 elif os.path.exists(self._incoming_file):
188 # we have some of the file, but not all of it (otherwise we'd be
189 # encoding). The caller might be useful.
190 self.log("partial ciphertext already present", level=log.UNUSUAL)
192 # we don't remember uploading this file
193 self.log("no ciphertext yet", level=log.NOISY)
195 # let our fetcher pull ciphertext from the reader.
196 self._fetcher.add_reader(reader)
198 self._reader.add_reader(reader)
200 # and inform the client when the upload has finished
201 return self._finished_observers.when_fired()
203 def _finished(self, ur):
204 assert interfaces.IUploadResults.providedBy(ur), ur
205 vcapstr = ur.get_verifycapstr()
206 precondition(isinstance(vcapstr, str), vcapstr)
207 v = uri.from_string(vcapstr)
208 f_times = self._fetcher.get_times()
210 hur = upload.HelperUploadResults()
211 hur.timings = {"cumulative_fetch": f_times["cumulative_fetch"],
212 "total_fetch": f_times["total"],
214 for key,val in ur.get_timings().items():
215 hur.timings[key] = val
216 hur.uri_extension_hash = v.uri_extension_hash
217 hur.ciphertext_fetched = self._fetcher.get_ciphertext_fetched()
218 hur.preexisting_shares = ur.get_preexisting_shares()
219 hur.sharemap = ur.get_sharemap()
220 hur.servermap = ur.get_servermap()
221 hur.pushed_shares = ur.get_pushed_shares()
222 hur.file_size = ur.get_file_size()
223 hur.uri_extension_data = ur.get_uri_extension_data()
224 hur.verifycapstr = vcapstr
227 os.unlink(self._encoding_file)
228 self._finished_observers.fire(hur)
229 self._helper.upload_finished(self._storage_index, v.size)
232 def _failed(self, f):
233 self.log(format="CHKUploadHelper(%(si)s) failed",
234 si=si_b2a(self._storage_index)[:5],
237 self._finished_observers.fire(f)
238 self._helper.upload_finished(self._storage_index, 0)
241 class AskUntilSuccessMixin:
242 # create me with a _reader array
245 def add_reader(self, reader):
246 self._readers.append(reader)
248 def call(self, *args, **kwargs):
249 if not self._readers:
250 raise NotEnoughWritersError("ran out of assisted uploaders, last failure was %s" % self._last_failure)
251 rr = self._readers[0]
252 d = rr.callRemote(*args, **kwargs)
254 self._last_failure = f
255 if rr in self._readers:
256 self._readers.remove(rr)
257 self._upload_helper.log("call to assisted uploader %s failed" % rr,
258 failure=f, level=log.UNUSUAL)
259 # we can try again with someone else who's left
260 return self.call(*args, **kwargs)
264 class CHKCiphertextFetcher(AskUntilSuccessMixin):
265 """I use one or more remote RIEncryptedUploadable instances to gather
266 ciphertext on disk. When I'm done, the file I create can be used by a
267 LocalCiphertextReader to satisfy the ciphertext needs of a CHK upload
270 I begin pulling ciphertext as soon as a reader is added. I remove readers
271 when they have any sort of error. If the last reader is removed, I fire
272 my when_done() Deferred with a failure.
274 I fire my when_done() Deferred (with None) immediately after I have moved
275 the ciphertext to 'encoded_file'.
278 def __init__(self, helper, incoming_file, encoded_file, logparent):
279 self._upload_helper = helper
280 self._incoming_file = incoming_file
281 self._encoding_file = encoded_file
282 self._upload_id = helper._upload_id
283 self._log_parent = logparent
284 self._done_observers = observer.OneShotObserverList()
286 self._started = False
289 "cumulative_fetch": 0.0,
292 self._ciphertext_fetched = 0
294 def log(self, *args, **kwargs):
295 if "facility" not in kwargs:
296 kwargs["facility"] = "tahoe.helper.chkupload.fetch"
297 if "parent" not in kwargs:
298 kwargs["parent"] = self._log_parent
299 return log.msg(*args, **kwargs)
301 def add_reader(self, reader):
302 AskUntilSuccessMixin.add_reader(self, reader)
303 eventually(self._start)
309 started = time.time()
311 if os.path.exists(self._encoding_file):
312 self.log("ciphertext already present, bypassing fetch",
314 # we'll still need the plaintext hashes (when
315 # LocalCiphertextReader.get_plaintext_hashtree_leaves() is
316 # called), and currently the easiest way to get them is to ask
317 # the sender for the last byte of ciphertext. That will provoke
318 # them into reading and hashing (but not sending) everything
320 have = os.stat(self._encoding_file)[stat.ST_SIZE]
321 d = self.call("read_encrypted", have-1, 1)
322 d.addCallback(self._done2, started)
325 # first, find out how large the file is going to be
326 d = self.call("get_size")
327 d.addCallback(self._got_size)
328 d.addCallback(self._start_reading)
329 d.addCallback(self._done)
330 d.addCallback(self._done2, started)
331 d.addErrback(self._failed)
333 def _got_size(self, size):
334 self.log("total size is %d bytes" % size, level=log.NOISY)
335 self._upload_helper._upload_status.set_size(size)
336 self._expected_size = size
338 def _start_reading(self, res):
339 # then find out how much crypttext we have on disk
340 if os.path.exists(self._incoming_file):
341 self._have = os.stat(self._incoming_file)[stat.ST_SIZE]
342 self._upload_helper._helper.count("chk_upload_helper.resumes")
343 self.log("we already have %d bytes" % self._have, level=log.NOISY)
346 self.log("we do not have any ciphertext yet", level=log.NOISY)
347 self.log("starting ciphertext fetch", level=log.NOISY)
348 self._f = open(self._incoming_file, "ab")
350 # now loop to pull the data from the readers
353 # this Deferred will be fired once the last byte has been written to
357 # read data in 50kB chunks. We should choose a more considered number
358 # here, possibly letting the client specify it. The goal should be to
359 # keep the RTT*bandwidth to be less than 10% of the chunk size, to reduce
360 # the upload bandwidth lost because this protocol is non-windowing. Too
361 # large, however, means more memory consumption for both ends. Something
362 # that can be transferred in, say, 10 seconds sounds about right. On my
363 # home DSL line (50kBps upstream), that suggests 500kB. Most lines are
364 # slower, maybe 10kBps, which suggests 100kB, and that's a bit more
365 # memory than I want to hang on to, so I'm going to go with 50kB and see
369 def _loop(self, fire_when_done):
370 # this slightly weird structure is needed because Deferreds don't do
371 # tail-recursion, so it is important to let each one retire promptly.
372 # Simply chaining them will cause a stack overflow at the end of a
373 # transfer that involves more than a few hundred chunks.
374 # 'fire_when_done' lives a long time, but the Deferreds returned by
375 # the inner _fetch() call do not.
377 d = defer.maybeDeferred(self._fetch)
379 elapsed = time.time() - start
380 self._times["cumulative_fetch"] += elapsed
382 self.log("finished reading ciphertext", level=log.NOISY)
383 fire_when_done.callback(None)
385 self._loop(fire_when_done)
387 self.log(format="[%(si)s] ciphertext read failed",
388 si=self._upload_id, failure=f, level=log.UNUSUAL)
389 fire_when_done.errback(f)
390 d.addCallbacks(_done, _err)
394 needed = self._expected_size - self._have
395 fetch_size = min(needed, self.CHUNK_SIZE)
397 self._upload_helper._upload_status.set_progress(1, 1.0)
398 return True # all done
400 if self._expected_size:
401 percent = 1.0 * (self._have+fetch_size) / self._expected_size
402 self.log(format="fetching [%(si)s] %(start)d-%(end)d of %(total)d (%(percent)d%%)",
405 end=self._have+fetch_size,
406 total=self._expected_size,
407 percent=int(100.0*percent),
409 d = self.call("read_encrypted", self._have, fetch_size)
410 def _got_data(ciphertext_v):
411 for data in ciphertext_v:
413 self._have += len(data)
414 self._ciphertext_fetched += len(data)
415 self._upload_helper._helper.count("chk_upload_helper.fetched_bytes", len(data))
416 self._upload_helper._upload_status.set_progress(1, percent)
417 return False # not done
418 d.addCallback(_got_data)
421 def _done(self, res):
424 self.log(format="done fetching ciphertext, size=%(size)d",
425 size=os.stat(self._incoming_file)[stat.ST_SIZE],
427 os.rename(self._incoming_file, self._encoding_file)
429 def _done2(self, _ignored, started):
430 self.log("done2", level=log.NOISY)
431 elapsed = time.time() - started
432 self._times["total"] = elapsed
434 self._done_observers.fire(None)
436 def _failed(self, f):
440 self._done_observers.fire(f)
443 return self._done_observers.when_fired()
448 def get_ciphertext_fetched(self):
449 return self._ciphertext_fetched
452 class LocalCiphertextReader(AskUntilSuccessMixin):
453 implements(interfaces.IEncryptedUploadable)
455 def __init__(self, upload_helper, storage_index, encoding_file):
457 self._upload_helper = upload_helper
458 self._storage_index = storage_index
459 self._encoding_file = encoding_file
463 self._upload_helper._upload_status.set_status("pushing")
464 self._size = os.stat(self._encoding_file)[stat.ST_SIZE]
465 self.f = open(self._encoding_file, "rb")
468 return defer.succeed(self._size)
470 def get_all_encoding_parameters(self):
471 return self.call("get_all_encoding_parameters")
473 def get_storage_index(self):
474 return defer.succeed(self._storage_index)
476 def read_encrypted(self, length, hash_only):
477 assert hash_only is False
478 d = defer.maybeDeferred(self.f.read, length)
479 d.addCallback(lambda data: [data])
484 # ??. I'm not sure if it makes sense to forward the close message.
485 return self.call("close")
489 class Helper(Referenceable):
490 implements(interfaces.RIHelper, interfaces.IStatsProducer)
491 # this is the non-distributed version. When we need to have multiple
492 # helpers, this object will become the HelperCoordinator, and will query
493 # the farm of Helpers to see if anyone has the storage_index of interest,
494 # and send the request off to them. If nobody has it, we'll choose a
498 VERSION = { "http://allmydata.org/tahoe/protocols/helper/v1" :
500 "application-version": str(allmydata.__full_version__),
502 MAX_UPLOAD_STATUSES = 10
504 def __init__(self, basedir, storage_broker, secret_holder,
505 stats_provider, history):
506 self._basedir = basedir
507 self._storage_broker = storage_broker
508 self._secret_holder = secret_holder
509 self._chk_incoming = os.path.join(basedir, "CHK_incoming")
510 self._chk_encoding = os.path.join(basedir, "CHK_encoding")
511 fileutil.make_dirs(self._chk_incoming)
512 fileutil.make_dirs(self._chk_encoding)
513 self._active_uploads = {}
514 self._all_uploads = weakref.WeakKeyDictionary() # for debugging
515 self.stats_provider = stats_provider
517 stats_provider.register_producer(self)
518 self._counters = {"chk_upload_helper.upload_requests": 0,
519 "chk_upload_helper.upload_already_present": 0,
520 "chk_upload_helper.upload_need_upload": 0,
521 "chk_upload_helper.resumes": 0,
522 "chk_upload_helper.fetched_bytes": 0,
523 "chk_upload_helper.encoded_bytes": 0,
525 self._history = history
527 def log(self, *args, **kwargs):
528 if 'facility' not in kwargs:
529 kwargs['facility'] = "tahoe.helper"
530 return log.msg(*args, **kwargs)
532 def count(self, key, value=1):
533 if self.stats_provider:
534 self.stats_provider.count(key, value)
535 self._counters[key] += value
538 OLD = 86400*2 # 48hours
540 inc_count = inc_size = inc_size_old = 0
541 enc_count = enc_size = enc_size_old = 0
542 inc = os.listdir(self._chk_incoming)
543 enc = os.listdir(self._chk_encoding)
545 s = os.stat(os.path.join(self._chk_incoming, f))
546 size = s[stat.ST_SIZE]
547 mtime = s[stat.ST_MTIME]
550 if now - mtime > OLD:
553 s = os.stat(os.path.join(self._chk_encoding, f))
554 size = s[stat.ST_SIZE]
555 mtime = s[stat.ST_MTIME]
558 if now - mtime > OLD:
560 stats = { 'chk_upload_helper.active_uploads': len(self._active_uploads),
561 'chk_upload_helper.incoming_count': inc_count,
562 'chk_upload_helper.incoming_size': inc_size,
563 'chk_upload_helper.incoming_size_old': inc_size_old,
564 'chk_upload_helper.encoding_count': enc_count,
565 'chk_upload_helper.encoding_size': enc_size,
566 'chk_upload_helper.encoding_size_old': enc_size_old,
568 stats.update(self._counters)
571 def remote_get_version(self):
574 def remote_upload_chk(self, storage_index):
575 self.count("chk_upload_helper.upload_requests")
576 lp = self.log(format="helper: upload_chk query for SI %(si)s",
577 si=si_b2a(storage_index))
578 if storage_index in self._active_uploads:
579 self.log("upload is currently active", parent=lp)
580 uh = self._active_uploads[storage_index]
583 d = self._check_chk(storage_index, lp)
584 d.addCallback(self._did_chk_check, storage_index, lp)
586 self.log("error while checking for chk-already-in-grid",
587 failure=f, level=log.WEIRD, parent=lp, umid="jDtxZg")
592 def _check_chk(self, storage_index, lp):
593 # see if this file is already in the grid
594 lp2 = self.log("doing a quick check+UEBfetch",
595 parent=lp, level=log.NOISY)
596 sb = self._storage_broker
597 c = CHKCheckerAndUEBFetcher(sb.get_servers_for_psi, storage_index, lp2)
601 (sharemap, ueb_data, ueb_hash) = res
602 self.log("found file in grid", level=log.NOISY, parent=lp)
603 hur = upload.HelperUploadResults()
604 hur.uri_extension_hash = ueb_hash
605 hur.sharemap = sharemap
606 hur.uri_extension_data = ueb_data
607 hur.preexisting_shares = len(sharemap)
608 hur.pushed_shares = 0
611 d.addCallback(_checked)
614 def _did_chk_check(self, already_present, storage_index, lp):
616 # the necessary results are placed in the UploadResults
617 self.count("chk_upload_helper.upload_already_present")
618 self.log("file already found in grid", parent=lp)
619 return (already_present, None)
621 self.count("chk_upload_helper.upload_need_upload")
622 # the file is not present in the grid, by which we mean there are
623 # less than 'N' shares available.
624 self.log("unable to find file in the grid", parent=lp,
626 # We need an upload helper. Check our active uploads again in
627 # case there was a race.
628 if storage_index in self._active_uploads:
629 self.log("upload is currently active", parent=lp)
630 uh = self._active_uploads[storage_index]
632 self.log("creating new upload helper", parent=lp)
633 uh = self._make_chk_upload_helper(storage_index, lp)
634 self._active_uploads[storage_index] = uh
638 def _make_chk_upload_helper(self, storage_index, lp):
639 si_s = si_b2a(storage_index)
640 incoming_file = os.path.join(self._chk_incoming, si_s)
641 encoding_file = os.path.join(self._chk_encoding, si_s)
642 uh = CHKUploadHelper(storage_index, self,
643 self._storage_broker,
645 incoming_file, encoding_file,
649 def _add_upload(self, uh):
650 self._all_uploads[uh] = None
652 s = uh.get_upload_status()
653 self._history.notify_helper_upload(s)
655 def upload_finished(self, storage_index, size):
656 # this is called with size=0 if the upload failed
657 self.count("chk_upload_helper.encoded_bytes", size)
658 uh = self._active_uploads[storage_index]
659 del self._active_uploads[storage_index]
660 s = uh.get_upload_status()