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,
140 log_number, progress=None):
141 upload.CHKUploader.__init__(self, storage_broker, secret_holder, progress=progress)
142 self._storage_index = storage_index
143 self._helper = helper
144 self._incoming_file = incoming_file
145 self._encoding_file = encoding_file
146 self._upload_id = si_b2a(storage_index)[:5]
147 self._log_number = log_number
148 self._upload_status = upload.UploadStatus()
149 self._upload_status.set_helper(False)
150 self._upload_status.set_storage_index(storage_index)
151 self._upload_status.set_status("fetching ciphertext")
152 self._upload_status.set_progress(0, 1.0)
153 self._helper.log("CHKUploadHelper starting for SI %s" % self._upload_id,
156 self._storage_broker = storage_broker
157 self._secret_holder = secret_holder
158 self._fetcher = CHKCiphertextFetcher(self, incoming_file, encoding_file,
160 self._reader = LocalCiphertextReader(self, storage_index, encoding_file)
161 self._finished_observers = observer.OneShotObserverList()
163 self._started = time.time()
164 d = self._fetcher.when_done()
165 d.addCallback(lambda res: self._reader.start())
166 d.addCallback(lambda res: self.start_encrypted(self._reader))
167 d.addCallback(self._finished)
168 d.addErrback(self._failed)
170 def log(self, *args, **kwargs):
171 if 'facility' not in kwargs:
172 kwargs['facility'] = "tahoe.helper.chk"
173 return upload.CHKUploader.log(self, *args, **kwargs)
175 def remote_get_version(self):
178 def remote_upload(self, reader):
179 # reader is an RIEncryptedUploadable. I am specified to return an
180 # UploadResults dictionary.
182 # Log how much ciphertext we need to get.
183 self.log("deciding whether to upload the file or not", level=log.NOISY)
184 if os.path.exists(self._encoding_file):
185 # we have the whole file, and we might be encoding it (or the
186 # encode/upload might have failed, and we need to restart it).
187 self.log("ciphertext already in place", level=log.UNUSUAL)
188 elif os.path.exists(self._incoming_file):
189 # we have some of the file, but not all of it (otherwise we'd be
190 # encoding). The caller might be useful.
191 self.log("partial ciphertext already present", level=log.UNUSUAL)
193 # we don't remember uploading this file
194 self.log("no ciphertext yet", level=log.NOISY)
196 # let our fetcher pull ciphertext from the reader.
197 self._fetcher.add_reader(reader)
199 self._reader.add_reader(reader)
201 # and inform the client when the upload has finished
202 return self._finished_observers.when_fired()
204 def _finished(self, ur):
205 assert interfaces.IUploadResults.providedBy(ur), ur
206 vcapstr = ur.get_verifycapstr()
207 precondition(isinstance(vcapstr, str), vcapstr)
208 v = uri.from_string(vcapstr)
209 f_times = self._fetcher.get_times()
211 hur = upload.HelperUploadResults()
212 hur.timings = {"cumulative_fetch": f_times["cumulative_fetch"],
213 "total_fetch": f_times["total"],
215 for key,val in ur.get_timings().items():
216 hur.timings[key] = val
217 hur.uri_extension_hash = v.uri_extension_hash
218 hur.ciphertext_fetched = self._fetcher.get_ciphertext_fetched()
219 hur.preexisting_shares = ur.get_preexisting_shares()
220 # hur.sharemap needs to be {shnum: set(serverid)}
222 for shnum, servers in ur.get_sharemap().items():
223 hur.sharemap[shnum] = set([s.get_serverid() for s in servers])
224 # and hur.servermap needs to be {serverid: set(shnum)}
226 for server, shnums in ur.get_servermap().items():
227 hur.servermap[server.get_serverid()] = set(shnums)
228 hur.pushed_shares = ur.get_pushed_shares()
229 hur.file_size = ur.get_file_size()
230 hur.uri_extension_data = ur.get_uri_extension_data()
231 hur.verifycapstr = vcapstr
234 os.unlink(self._encoding_file)
235 self._finished_observers.fire(hur)
236 self._helper.upload_finished(self._storage_index, v.size)
239 def _failed(self, f):
240 self.log(format="CHKUploadHelper(%(si)s) failed",
241 si=si_b2a(self._storage_index)[:5],
244 self._finished_observers.fire(f)
245 self._helper.upload_finished(self._storage_index, 0)
248 class AskUntilSuccessMixin:
249 # create me with a _reader array
252 def add_reader(self, reader):
253 self._readers.append(reader)
255 def call(self, *args, **kwargs):
256 if not self._readers:
257 raise NotEnoughWritersError("ran out of assisted uploaders, last failure was %s" % self._last_failure)
258 rr = self._readers[0]
259 d = rr.callRemote(*args, **kwargs)
261 self._last_failure = f
262 if rr in self._readers:
263 self._readers.remove(rr)
264 self._upload_helper.log("call to assisted uploader %s failed" % rr,
265 failure=f, level=log.UNUSUAL)
266 # we can try again with someone else who's left
267 return self.call(*args, **kwargs)
271 class CHKCiphertextFetcher(AskUntilSuccessMixin):
272 """I use one or more remote RIEncryptedUploadable instances to gather
273 ciphertext on disk. When I'm done, the file I create can be used by a
274 LocalCiphertextReader to satisfy the ciphertext needs of a CHK upload
277 I begin pulling ciphertext as soon as a reader is added. I remove readers
278 when they have any sort of error. If the last reader is removed, I fire
279 my when_done() Deferred with a failure.
281 I fire my when_done() Deferred (with None) immediately after I have moved
282 the ciphertext to 'encoded_file'.
285 def __init__(self, helper, incoming_file, encoded_file, logparent):
286 self._upload_helper = helper
287 self._incoming_file = incoming_file
288 self._encoding_file = encoded_file
289 self._upload_id = helper._upload_id
290 self._log_parent = logparent
291 self._done_observers = observer.OneShotObserverList()
293 self._started = False
296 "cumulative_fetch": 0.0,
299 self._ciphertext_fetched = 0
301 def log(self, *args, **kwargs):
302 if "facility" not in kwargs:
303 kwargs["facility"] = "tahoe.helper.chkupload.fetch"
304 if "parent" not in kwargs:
305 kwargs["parent"] = self._log_parent
306 return log.msg(*args, **kwargs)
308 def add_reader(self, reader):
309 AskUntilSuccessMixin.add_reader(self, reader)
310 eventually(self._start)
316 started = time.time()
318 if os.path.exists(self._encoding_file):
319 self.log("ciphertext already present, bypassing fetch",
321 d = defer.succeed(None)
323 # first, find out how large the file is going to be
324 d = self.call("get_size")
325 d.addCallback(self._got_size)
326 d.addCallback(self._start_reading)
327 d.addCallback(self._done)
328 d.addCallback(self._done2, started)
329 d.addErrback(self._failed)
331 def _got_size(self, size):
332 self.log("total size is %d bytes" % size, level=log.NOISY)
333 self._upload_helper._upload_status.set_size(size)
334 self._expected_size = size
336 def _start_reading(self, res):
337 # then find out how much crypttext we have on disk
338 if os.path.exists(self._incoming_file):
339 self._have = os.stat(self._incoming_file)[stat.ST_SIZE]
340 self._upload_helper._helper.count("chk_upload_helper.resumes")
341 self.log("we already have %d bytes" % self._have, level=log.NOISY)
344 self.log("we do not have any ciphertext yet", level=log.NOISY)
345 self.log("starting ciphertext fetch", level=log.NOISY)
346 self._f = open(self._incoming_file, "ab")
348 # now loop to pull the data from the readers
351 # this Deferred will be fired once the last byte has been written to
355 # read data in 50kB chunks. We should choose a more considered number
356 # here, possibly letting the client specify it. The goal should be to
357 # keep the RTT*bandwidth to be less than 10% of the chunk size, to reduce
358 # the upload bandwidth lost because this protocol is non-windowing. Too
359 # large, however, means more memory consumption for both ends. Something
360 # that can be transferred in, say, 10 seconds sounds about right. On my
361 # home DSL line (50kBps upstream), that suggests 500kB. Most lines are
362 # slower, maybe 10kBps, which suggests 100kB, and that's a bit more
363 # memory than I want to hang on to, so I'm going to go with 50kB and see
367 def _loop(self, fire_when_done):
368 # this slightly weird structure is needed because Deferreds don't do
369 # tail-recursion, so it is important to let each one retire promptly.
370 # Simply chaining them will cause a stack overflow at the end of a
371 # transfer that involves more than a few hundred chunks.
372 # 'fire_when_done' lives a long time, but the Deferreds returned by
373 # the inner _fetch() call do not.
375 d = defer.maybeDeferred(self._fetch)
377 elapsed = time.time() - start
378 self._times["cumulative_fetch"] += elapsed
380 self.log("finished reading ciphertext", level=log.NOISY)
381 fire_when_done.callback(None)
383 self._loop(fire_when_done)
385 self.log(format="[%(si)s] ciphertext read failed",
386 si=self._upload_id, failure=f, level=log.UNUSUAL)
387 fire_when_done.errback(f)
388 d.addCallbacks(_done, _err)
392 needed = self._expected_size - self._have
393 fetch_size = min(needed, self.CHUNK_SIZE)
395 self._upload_helper._upload_status.set_progress(1, 1.0)
396 return True # all done
398 if self._expected_size:
399 percent = 1.0 * (self._have+fetch_size) / self._expected_size
400 self.log(format="fetching [%(si)s] %(start)d-%(end)d of %(total)d (%(percent)d%%)",
403 end=self._have+fetch_size,
404 total=self._expected_size,
405 percent=int(100.0*percent),
407 d = self.call("read_encrypted", self._have, fetch_size)
408 def _got_data(ciphertext_v):
409 for data in ciphertext_v:
411 self._have += len(data)
412 self._ciphertext_fetched += len(data)
413 self._upload_helper._helper.count("chk_upload_helper.fetched_bytes", len(data))
414 self._upload_helper._upload_status.set_progress(1, percent)
415 return False # not done
416 d.addCallback(_got_data)
419 def _done(self, res):
422 self.log(format="done fetching ciphertext, size=%(size)d",
423 size=os.stat(self._incoming_file)[stat.ST_SIZE],
425 os.rename(self._incoming_file, self._encoding_file)
427 def _done2(self, _ignored, started):
428 self.log("done2", level=log.NOISY)
429 elapsed = time.time() - started
430 self._times["total"] = elapsed
432 self._done_observers.fire(None)
434 def _failed(self, f):
438 self._done_observers.fire(f)
441 return self._done_observers.when_fired()
446 def get_ciphertext_fetched(self):
447 return self._ciphertext_fetched
450 class LocalCiphertextReader(AskUntilSuccessMixin):
451 implements(interfaces.IEncryptedUploadable)
453 def __init__(self, upload_helper, storage_index, encoding_file):
455 self._upload_helper = upload_helper
456 self._storage_index = storage_index
457 self._encoding_file = encoding_file
461 self._upload_helper._upload_status.set_status("pushing")
462 self._size = os.stat(self._encoding_file)[stat.ST_SIZE]
463 self.f = open(self._encoding_file, "rb")
466 return defer.succeed(self._size)
468 def get_all_encoding_parameters(self):
469 return self.call("get_all_encoding_parameters")
471 def get_storage_index(self):
472 return defer.succeed(self._storage_index)
474 def read_encrypted(self, length, hash_only):
475 assert hash_only is False
476 d = defer.maybeDeferred(self.f.read, length)
477 d.addCallback(lambda data: [data])
482 # ??. I'm not sure if it makes sense to forward the close message.
483 return self.call("close")
487 class Helper(Referenceable):
488 implements(interfaces.RIHelper, interfaces.IStatsProducer)
489 # this is the non-distributed version. When we need to have multiple
490 # helpers, this object will become the HelperCoordinator, and will query
491 # the farm of Helpers to see if anyone has the storage_index of interest,
492 # and send the request off to them. If nobody has it, we'll choose a
496 VERSION = { "http://allmydata.org/tahoe/protocols/helper/v1" :
498 "application-version": str(allmydata.__full_version__),
500 MAX_UPLOAD_STATUSES = 10
502 def __init__(self, basedir, storage_broker, secret_holder,
503 stats_provider, history):
504 self._basedir = basedir
505 self._storage_broker = storage_broker
506 self._secret_holder = secret_holder
507 self._chk_incoming = os.path.join(basedir, "CHK_incoming")
508 self._chk_encoding = os.path.join(basedir, "CHK_encoding")
509 fileutil.make_dirs(self._chk_incoming)
510 fileutil.make_dirs(self._chk_encoding)
511 self._active_uploads = {}
512 self._all_uploads = weakref.WeakKeyDictionary() # for debugging
513 self.stats_provider = stats_provider
515 stats_provider.register_producer(self)
516 self._counters = {"chk_upload_helper.upload_requests": 0,
517 "chk_upload_helper.upload_already_present": 0,
518 "chk_upload_helper.upload_need_upload": 0,
519 "chk_upload_helper.resumes": 0,
520 "chk_upload_helper.fetched_bytes": 0,
521 "chk_upload_helper.encoded_bytes": 0,
523 self._history = history
525 def log(self, *args, **kwargs):
526 if 'facility' not in kwargs:
527 kwargs['facility'] = "tahoe.helper"
528 return log.msg(*args, **kwargs)
530 def count(self, key, value=1):
531 if self.stats_provider:
532 self.stats_provider.count(key, value)
533 self._counters[key] += value
536 OLD = 86400*2 # 48hours
538 inc_count = inc_size = inc_size_old = 0
539 enc_count = enc_size = enc_size_old = 0
540 inc = os.listdir(self._chk_incoming)
541 enc = os.listdir(self._chk_encoding)
543 s = os.stat(os.path.join(self._chk_incoming, f))
544 size = s[stat.ST_SIZE]
545 mtime = s[stat.ST_MTIME]
548 if now - mtime > OLD:
551 s = os.stat(os.path.join(self._chk_encoding, f))
552 size = s[stat.ST_SIZE]
553 mtime = s[stat.ST_MTIME]
556 if now - mtime > OLD:
558 stats = { 'chk_upload_helper.active_uploads': len(self._active_uploads),
559 'chk_upload_helper.incoming_count': inc_count,
560 'chk_upload_helper.incoming_size': inc_size,
561 'chk_upload_helper.incoming_size_old': inc_size_old,
562 'chk_upload_helper.encoding_count': enc_count,
563 'chk_upload_helper.encoding_size': enc_size,
564 'chk_upload_helper.encoding_size_old': enc_size_old,
566 stats.update(self._counters)
569 def remote_get_version(self):
572 def remote_upload_chk(self, storage_index):
573 self.count("chk_upload_helper.upload_requests")
574 lp = self.log(format="helper: upload_chk query for SI %(si)s",
575 si=si_b2a(storage_index))
576 if storage_index in self._active_uploads:
577 self.log("upload is currently active", parent=lp)
578 uh = self._active_uploads[storage_index]
581 d = self._check_chk(storage_index, lp)
582 d.addCallback(self._did_chk_check, storage_index, lp)
584 self.log("error while checking for chk-already-in-grid",
585 failure=f, level=log.WEIRD, parent=lp, umid="jDtxZg")
590 def _check_chk(self, storage_index, lp):
591 # see if this file is already in the grid
592 lp2 = self.log("doing a quick check+UEBfetch",
593 parent=lp, level=log.NOISY)
594 sb = self._storage_broker
595 c = CHKCheckerAndUEBFetcher(sb.get_servers_for_psi, storage_index, lp2)
599 (sharemap, ueb_data, ueb_hash) = res
600 self.log("found file in grid", level=log.NOISY, parent=lp)
601 hur = upload.HelperUploadResults()
602 hur.uri_extension_hash = ueb_hash
603 hur.sharemap = sharemap
604 hur.uri_extension_data = ueb_data
605 hur.preexisting_shares = len(sharemap)
606 hur.pushed_shares = 0
609 d.addCallback(_checked)
612 def _did_chk_check(self, already_present, storage_index, lp):
614 # the necessary results are placed in the UploadResults
615 self.count("chk_upload_helper.upload_already_present")
616 self.log("file already found in grid", parent=lp)
617 return (already_present, None)
619 self.count("chk_upload_helper.upload_need_upload")
620 # the file is not present in the grid, by which we mean there are
621 # less than 'N' shares available.
622 self.log("unable to find file in the grid", parent=lp,
624 # We need an upload helper. Check our active uploads again in
625 # case there was a race.
626 if storage_index in self._active_uploads:
627 self.log("upload is currently active", parent=lp)
628 uh = self._active_uploads[storage_index]
630 self.log("creating new upload helper", parent=lp)
631 uh = self._make_chk_upload_helper(storage_index, lp)
632 self._active_uploads[storage_index] = uh
636 def _make_chk_upload_helper(self, storage_index, lp):
637 si_s = si_b2a(storage_index)
638 incoming_file = os.path.join(self._chk_incoming, si_s)
639 encoding_file = os.path.join(self._chk_encoding, si_s)
640 uh = CHKUploadHelper(storage_index, self,
641 self._storage_broker,
643 incoming_file, encoding_file,
647 def _add_upload(self, uh):
648 self._all_uploads[uh] = None
650 s = uh.get_upload_status()
651 self._history.notify_helper_upload(s)
653 def upload_finished(self, storage_index, size):
654 # this is called with size=0 if the upload failed
655 self.count("chk_upload_helper.encoded_bytes", size)
656 uh = self._active_uploads[storage_index]
657 del self._active_uploads[storage_index]
658 s = uh.get_upload_status()