2 import os, time, weakref, itertools
3 from zope.interface import implements
4 from twisted.python import failure
5 from twisted.internet import defer
6 from twisted.application import service
7 from foolscap import Referenceable, Copyable, RemoteCopy
8 from foolscap import eventual
9 from foolscap.logging import log
11 from allmydata.util.hashutil import file_renewal_secret_hash, \
12 file_cancel_secret_hash, bucket_renewal_secret_hash, \
13 bucket_cancel_secret_hash, plaintext_hasher, \
14 storage_index_hash, plaintext_segment_hasher, content_hash_key_hasher
15 from allmydata import encode, storage, hashtree, uri
16 from allmydata.util import base32, idlib, mathutil
17 from allmydata.util.assertutil import precondition
18 from allmydata.interfaces import IUploadable, IUploader, IUploadResults, \
19 IEncryptedUploadable, RIEncryptedUploadable, IUploadStatus
20 from pycryptopp.cipher.aes import AES
22 from cStringIO import StringIO
31 class HaveAllPeersError(Exception):
32 # we use this to jump out of the loop
35 # this wants to live in storage, not here
36 class TooFullError(Exception):
39 class UploadResults(Copyable, RemoteCopy):
40 implements(IUploadResults)
41 typeToCopy = "allmydata.upload.UploadResults.tahoe.allmydata.com"
45 ciphertext_fetched = None # how much the helper fetched
47 sharemap = None # dict of shnum to placement string
48 servermap = None # dict of peerid to set(shnums)
50 self.timings = {} # dict of name to number of seconds
52 # our current uri_extension is 846 bytes for small files, a few bytes
53 # more for larger ones (since the filesize is encoded in decimal in a
54 # few places). Ask for a little bit more just in case we need it. If
55 # the extension changes size, we can change EXTENSION_SIZE to
56 # allocate a more accurate amount of space.
60 def __init__(self, peerid, storage_server,
61 sharesize, blocksize, num_segments, num_share_hashes,
63 bucket_renewal_secret, bucket_cancel_secret):
64 precondition(isinstance(peerid, str), peerid)
65 precondition(len(peerid) == 20, peerid)
67 self._storageserver = storage_server # to an RIStorageServer
68 self.buckets = {} # k: shareid, v: IRemoteBucketWriter
69 self.sharesize = sharesize
70 as = storage.allocated_size(sharesize,
74 self.allocated_size = as
76 self.blocksize = blocksize
77 self.num_segments = num_segments
78 self.num_share_hashes = num_share_hashes
79 self.storage_index = storage_index
81 self.renew_secret = bucket_renewal_secret
82 self.cancel_secret = bucket_cancel_secret
85 return ("<PeerTracker for peer %s and SI %s>"
86 % (idlib.shortnodeid_b2a(self.peerid),
87 storage.si_b2a(self.storage_index)[:5]))
89 def query(self, sharenums):
90 d = self._storageserver.callRemote("allocate_buckets",
96 canary=Referenceable())
97 d.addCallback(self._got_reply)
100 def _got_reply(self, (alreadygot, buckets)):
101 #log.msg("%s._got_reply(%s)" % (self, (alreadygot, buckets)))
103 for sharenum, rref in buckets.iteritems():
104 bp = storage.WriteBucketProxy(rref, self.sharesize,
107 self.num_share_hashes,
111 self.buckets.update(b)
112 return (alreadygot, set(b.keys()))
114 class Tahoe2PeerSelector:
116 def __init__(self, upload_id, logparent=None, upload_status=None):
117 self.upload_id = upload_id
118 self.query_count, self.good_query_count, self.bad_query_count = 0,0,0
120 self.num_peers_contacted = 0
121 self.last_failure_msg = None
122 self._status = IUploadStatus(upload_status)
123 self._log_parent = log.msg("%s starting" % self, parent=logparent)
126 return "<Tahoe2PeerSelector for upload %s>" % self.upload_id
128 def get_shareholders(self, client,
129 storage_index, share_size, block_size,
130 num_segments, total_shares, shares_of_happiness):
132 @return: a set of PeerTracker instances that have agreed to hold some
137 self._status.set_status("Contacting Peers..")
139 self.total_shares = total_shares
140 self.shares_of_happiness = shares_of_happiness
142 self.homeless_shares = range(total_shares)
143 # self.uncontacted_peers = list() # peers we haven't asked yet
144 self.contacted_peers = [] # peers worth asking again
145 self.contacted_peers2 = [] # peers that we have asked again
146 self._started_second_pass = False
147 self.use_peers = set() # PeerTrackers that have shares assigned to them
148 self.preexisting_shares = {} # sharenum -> PeerTracker holding the share
150 peers = client.get_permuted_peers("storage", storage_index)
152 raise encode.NotEnoughPeersError("client gave us zero peers")
154 # figure out how much space to ask for
156 # this needed_hashes computation should mirror
157 # Encoder.send_all_share_hash_trees. We use an IncompleteHashTree
158 # (instead of a HashTree) because we don't require actual hashing
159 # just to count the levels.
160 ht = hashtree.IncompleteHashTree(total_shares)
161 num_share_hashes = len(ht.needed_hashes(0, include_leaf=True))
163 # decide upon the renewal/cancel secrets, to include them in the
164 # allocat_buckets query.
165 client_renewal_secret = client.get_renewal_secret()
166 client_cancel_secret = client.get_cancel_secret()
168 file_renewal_secret = file_renewal_secret_hash(client_renewal_secret,
170 file_cancel_secret = file_cancel_secret_hash(client_cancel_secret,
173 trackers = [ PeerTracker(peerid, conn,
174 share_size, block_size,
175 num_segments, num_share_hashes,
177 bucket_renewal_secret_hash(file_renewal_secret,
179 bucket_cancel_secret_hash(file_cancel_secret,
182 for (peerid, conn) in peers ]
183 self.uncontacted_peers = trackers
185 d = defer.maybeDeferred(self._loop)
189 if not self.homeless_shares:
191 msg = ("placed all %d shares, "
192 "sent %d queries to %d peers, "
193 "%d queries placed some shares, %d placed none, "
196 self.query_count, self.num_peers_contacted,
197 self.good_query_count, self.bad_query_count,
199 log.msg("peer selection successful for %s: %s" % (self, msg),
200 parent=self._log_parent)
201 return self.use_peers
203 if self.uncontacted_peers:
204 peer = self.uncontacted_peers.pop(0)
205 # TODO: don't pre-convert all peerids to PeerTrackers
206 assert isinstance(peer, PeerTracker)
208 shares_to_ask = set([self.homeless_shares.pop(0)])
209 self.query_count += 1
210 self.num_peers_contacted += 1
212 self._status.set_status("Contacting Peers [%s] (first query),"
214 % (idlib.shortnodeid_b2a(peer.peerid),
215 len(self.homeless_shares)))
216 d = peer.query(shares_to_ask)
217 d.addBoth(self._got_response, peer, shares_to_ask,
218 self.contacted_peers)
220 elif self.contacted_peers:
221 # ask a peer that we've already asked.
222 if not self._started_second_pass:
223 log.msg("starting second pass", parent=self._log_parent,
225 self._started_second_pass = True
226 num_shares = mathutil.div_ceil(len(self.homeless_shares),
227 len(self.contacted_peers))
228 peer = self.contacted_peers.pop(0)
229 shares_to_ask = set(self.homeless_shares[:num_shares])
230 self.homeless_shares[:num_shares] = []
231 self.query_count += 1
233 self._status.set_status("Contacting Peers [%s] (second query),"
235 % (idlib.shortnodeid_b2a(peer.peerid),
236 len(self.homeless_shares)))
237 d = peer.query(shares_to_ask)
238 d.addBoth(self._got_response, peer, shares_to_ask,
239 self.contacted_peers2)
241 elif self.contacted_peers2:
242 # we've finished the second-or-later pass. Move all the remaining
243 # peers back into self.contacted_peers for the next pass.
244 self.contacted_peers.extend(self.contacted_peers2)
245 self.contacted_peers[:] = []
248 # no more peers. If we haven't placed enough shares, we fail.
249 placed_shares = self.total_shares - len(self.homeless_shares)
250 if placed_shares < self.shares_of_happiness:
251 msg = ("placed %d shares out of %d total (%d homeless), "
252 "sent %d queries to %d peers, "
253 "%d queries placed some shares, %d placed none, "
255 (self.total_shares - len(self.homeless_shares),
256 self.total_shares, len(self.homeless_shares),
257 self.query_count, self.num_peers_contacted,
258 self.good_query_count, self.bad_query_count,
260 msg = "peer selection failed for %s: %s" % (self, msg)
261 if self.last_failure_msg:
262 msg += " (%s)" % (self.last_failure_msg,)
263 log.msg(msg, level=log.UNUSUAL, parent=self._log_parent)
264 raise encode.NotEnoughPeersError(msg)
266 # we placed enough to be happy, so we're done
268 self._status.set_status("Placed all shares")
269 return self.use_peers
271 def _got_response(self, res, peer, shares_to_ask, put_peer_here):
272 if isinstance(res, failure.Failure):
273 # This is unusual, and probably indicates a bug or a network
275 log.msg("%s got error during peer selection: %s" % (peer, res),
276 level=log.UNUSUAL, parent=self._log_parent)
277 self.error_count += 1
278 self.homeless_shares = list(shares_to_ask) + self.homeless_shares
279 if (self.uncontacted_peers
280 or self.contacted_peers
281 or self.contacted_peers2):
282 # there is still hope, so just loop
285 # No more peers, so this upload might fail (it depends upon
286 # whether we've hit shares_of_happiness or not). Log the last
287 # failure we got: if a coding error causes all peers to fail
288 # in the same way, this allows the common failure to be seen
289 # by the uploader and should help with debugging
290 msg = ("last failure (from %s) was: %s" % (peer, res))
291 self.last_failure_msg = msg
293 (alreadygot, allocated) = res
294 log.msg("response from peer %s: alreadygot=%s, allocated=%s"
295 % (idlib.shortnodeid_b2a(peer.peerid),
296 tuple(sorted(alreadygot)), tuple(sorted(allocated))),
297 level=log.NOISY, parent=self._log_parent)
300 self.preexisting_shares[s] = peer
301 if s in self.homeless_shares:
302 self.homeless_shares.remove(s)
305 # the PeerTracker will remember which shares were allocated on
306 # that peer. We just have to remember to use them.
308 self.use_peers.add(peer)
311 not_yet_present = set(shares_to_ask) - set(alreadygot)
312 still_homeless = not_yet_present - set(allocated)
315 # they accepted or already had at least one share, so
316 # progress has been made
317 self.good_query_count += 1
319 self.bad_query_count += 1
322 # In networks with lots of space, this is very unusual and
323 # probably indicates an error. In networks with peers that
324 # are full, it is merely unusual. In networks that are very
325 # full, it is common, and many uploads will fail. In most
326 # cases, this is obviously not fatal, and we'll just use some
329 # some shares are still homeless, keep trying to find them a
330 # home. The ones that were rejected get first priority.
331 self.homeless_shares = (list(still_homeless)
332 + self.homeless_shares)
333 # Since they were unable to accept all of our requests, so it
334 # is safe to assume that asking them again won't help.
336 # if they *were* able to accept everything, they might be
337 # willing to accept even more.
338 put_peer_here.append(peer)
344 class EncryptAnUploadable:
345 """This is a wrapper that takes an IUploadable and provides
346 IEncryptedUploadable."""
347 implements(IEncryptedUploadable)
350 def __init__(self, original, log_parent=None):
351 self.original = IUploadable(original)
352 self._log_number = log_parent
353 self._encryptor = None
354 self._plaintext_hasher = plaintext_hasher()
355 self._plaintext_segment_hasher = None
356 self._plaintext_segment_hashes = []
357 self._encoding_parameters = None
358 self._file_size = None
359 self._ciphertext_bytes_read = 0
362 def set_upload_status(self, upload_status):
363 self._status = IUploadStatus(upload_status)
364 self.original.set_upload_status(upload_status)
366 def log(self, *args, **kwargs):
367 if "facility" not in kwargs:
368 kwargs["facility"] = "upload.encryption"
369 if "parent" not in kwargs:
370 kwargs["parent"] = self._log_number
371 return log.msg(*args, **kwargs)
374 if self._file_size is not None:
375 return defer.succeed(self._file_size)
376 d = self.original.get_size()
378 self._file_size = size
380 self._status.set_size(size)
382 d.addCallback(_got_size)
385 def get_all_encoding_parameters(self):
386 if self._encoding_parameters is not None:
387 return defer.succeed(self._encoding_parameters)
388 d = self.original.get_all_encoding_parameters()
389 def _got(encoding_parameters):
390 (k, happy, n, segsize) = encoding_parameters
391 self._segment_size = segsize # used by segment hashers
392 self._encoding_parameters = encoding_parameters
393 self.log("my encoding parameters: %s" % (encoding_parameters,),
395 return encoding_parameters
399 def _get_encryptor(self):
401 return defer.succeed(self._encryptor)
403 d = self.original.get_encryption_key()
408 storage_index = storage_index_hash(key)
409 assert isinstance(storage_index, str)
410 # There's no point to having the SI be longer than the key, so we
411 # specify that it is truncated to the same 128 bits as the AES key.
412 assert len(storage_index) == 16 # SHA-256 truncated to 128b
413 self._storage_index = storage_index
415 self._status.set_storage_index(storage_index)
420 def get_storage_index(self):
421 d = self._get_encryptor()
422 d.addCallback(lambda res: self._storage_index)
425 def _get_segment_hasher(self):
426 p = self._plaintext_segment_hasher
428 left = self._segment_size - self._plaintext_segment_hashed_bytes
430 p = plaintext_segment_hasher()
431 self._plaintext_segment_hasher = p
432 self._plaintext_segment_hashed_bytes = 0
433 return p, self._segment_size
435 def _update_segment_hash(self, chunk):
437 while offset < len(chunk):
438 p, segment_left = self._get_segment_hasher()
439 chunk_left = len(chunk) - offset
440 this_segment = min(chunk_left, segment_left)
441 p.update(chunk[offset:offset+this_segment])
442 self._plaintext_segment_hashed_bytes += this_segment
444 if self._plaintext_segment_hashed_bytes == self._segment_size:
445 # we've filled this segment
446 self._plaintext_segment_hashes.append(p.digest())
447 self._plaintext_segment_hasher = None
448 self.log("closed hash [%d]: %dB" %
449 (len(self._plaintext_segment_hashes)-1,
450 self._plaintext_segment_hashed_bytes),
452 self.log(format="plaintext leaf hash [%(segnum)d] is %(hash)s",
453 segnum=len(self._plaintext_segment_hashes)-1,
454 hash=base32.b2a(p.digest()),
457 offset += this_segment
460 def read_encrypted(self, length, hash_only):
461 # make sure our parameters have been set up first
462 d = self.get_all_encoding_parameters()
464 d.addCallback(lambda ignored: self.get_size())
465 d.addCallback(lambda ignored: self._get_encryptor())
466 # then fetch and encrypt the plaintext. The unusual structure here
467 # (passing a Deferred *into* a function) is needed to avoid
468 # overflowing the stack: Deferreds don't optimize out tail recursion.
469 # We also pass in a list, to which _read_encrypted will append
472 d2 = defer.Deferred()
473 d.addCallback(lambda ignored:
474 self._read_encrypted(length, ciphertext, hash_only, d2))
475 d.addCallback(lambda ignored: d2)
478 def _read_encrypted(self, remaining, ciphertext, hash_only, fire_when_done):
480 fire_when_done.callback(ciphertext)
482 # tolerate large length= values without consuming a lot of RAM by
483 # reading just a chunk (say 50kB) at a time. This only really matters
484 # when hash_only==True (i.e. resuming an interrupted upload), since
485 # that's the case where we will be skipping over a lot of data.
486 size = min(remaining, self.CHUNKSIZE)
487 remaining = remaining - size
488 # read a chunk of plaintext..
489 d = defer.maybeDeferred(self.original.read, size)
490 # N.B.: if read() is synchronous, then since everything else is
491 # actually synchronous too, we'd blow the stack unless we stall for a
492 # tick. Once you accept a Deferred from IUploadable.read(), you must
493 # be prepared to have it fire immediately too.
494 d.addCallback(eventual.fireEventually)
495 def _good(plaintext):
497 # o/' over the fields we go, hashing all the way, sHA! sHA! sHA! o/'
498 ct = self._hash_and_encrypt_plaintext(plaintext, hash_only)
499 ciphertext.extend(ct)
500 self._read_encrypted(remaining, ciphertext, hash_only,
503 fire_when_done.errback(why)
508 def _hash_and_encrypt_plaintext(self, data, hash_only):
509 assert isinstance(data, (tuple, list)), type(data)
512 # we use data.pop(0) instead of 'for chunk in data' to save
513 # memory: each chunk is destroyed as soon as we're done with it.
517 self.log(" read_encrypted handling %dB-sized chunk" % len(chunk),
519 bytes_processed += len(chunk)
520 self._plaintext_hasher.update(chunk)
521 self._update_segment_hash(chunk)
522 # TODO: we have to encrypt the data (even if hash_only==True)
523 # because pycryptopp's AES-CTR implementation doesn't offer a
524 # way to change the counter value. Once pycryptopp acquires
525 # this ability, change this to simply update the counter
526 # before each call to (hash_only==False) _encryptor.process()
527 ciphertext = self._encryptor.process(chunk)
529 self.log(" skipping encryption", level=log.NOISY)
531 cryptdata.append(ciphertext)
534 self._ciphertext_bytes_read += bytes_processed
536 progress = float(self._ciphertext_bytes_read) / self._file_size
537 self._status.set_progress(1, progress)
541 def get_plaintext_hashtree_leaves(self, first, last, num_segments):
542 if len(self._plaintext_segment_hashes) < num_segments:
543 # close out the last one
544 assert len(self._plaintext_segment_hashes) == num_segments-1
545 p, segment_left = self._get_segment_hasher()
546 self._plaintext_segment_hashes.append(p.digest())
547 del self._plaintext_segment_hasher
548 self.log("closing plaintext leaf hasher, hashed %d bytes" %
549 self._plaintext_segment_hashed_bytes,
551 self.log(format="plaintext leaf hash [%(segnum)d] is %(hash)s",
552 segnum=len(self._plaintext_segment_hashes)-1,
553 hash=base32.b2a(p.digest()),
555 assert len(self._plaintext_segment_hashes) == num_segments
556 return defer.succeed(tuple(self._plaintext_segment_hashes[first:last]))
558 def get_plaintext_hash(self):
559 h = self._plaintext_hasher.digest()
560 return defer.succeed(h)
563 return self.original.close()
566 implements(IUploadStatus)
567 statusid_counter = itertools.count(0)
570 self.storage_index = None
573 self.status = "Not started"
574 self.progress = [0.0, 0.0, 0.0]
577 self.counter = self.statusid_counter.next()
578 self.started = time.time()
580 def get_started(self):
582 def get_storage_index(self):
583 return self.storage_index
586 def using_helper(self):
588 def get_status(self):
590 def get_progress(self):
591 return tuple(self.progress)
592 def get_active(self):
594 def get_results(self):
596 def get_counter(self):
599 def set_storage_index(self, si):
600 self.storage_index = si
601 def set_size(self, size):
603 def set_helper(self, helper):
605 def set_status(self, status):
607 def set_progress(self, which, value):
608 # [0]: chk, [1]: ciphertext, [2]: encode+push
609 self.progress[which] = value
610 def set_active(self, value):
612 def set_results(self, value):
616 peer_selector_class = Tahoe2PeerSelector
618 def __init__(self, client):
619 self._client = client
620 self._log_number = self._client.log("CHKUploader starting")
622 self._results = UploadResults()
623 self._storage_index = None
624 self._upload_status = UploadStatus()
625 self._upload_status.set_helper(False)
626 self._upload_status.set_active(True)
627 self._upload_status.set_results(self._results)
629 def log(self, *args, **kwargs):
630 if "parent" not in kwargs:
631 kwargs["parent"] = self._log_number
632 if "facility" not in kwargs:
633 kwargs["facility"] = "tahoe.upload"
634 return self._client.log(*args, **kwargs)
636 def start(self, uploadable):
637 """Start uploading the file.
639 This method returns a Deferred that will fire with the URI (a
642 self._started = time.time()
643 uploadable = IUploadable(uploadable)
644 self.log("starting upload of %s" % uploadable)
646 eu = EncryptAnUploadable(uploadable, self._log_number)
647 eu.set_upload_status(self._upload_status)
648 d = self.start_encrypted(eu)
650 d1 = uploadable.get_encryption_key()
651 d1.addCallback(lambda key: self._compute_uri(res, key))
653 d.addCallback(_uploaded)
655 self._upload_status.set_active(False)
661 """Call this is the upload must be abandoned before it completes.
662 This will tell the shareholders to delete their partial shares. I
663 return a Deferred that fires when these messages have been acked."""
664 if not self._encoder:
665 # how did you call abort() before calling start() ?
666 return defer.succeed(None)
667 return self._encoder.abort()
669 def start_encrypted(self, encrypted):
670 eu = IEncryptedUploadable(encrypted)
672 started = time.time()
673 self._encoder = e = encode.Encoder(self._log_number,
675 d = e.set_encrypted_uploadable(eu)
676 d.addCallback(self.locate_all_shareholders, started)
677 d.addCallback(self.set_shareholders, e)
678 d.addCallback(lambda res: e.start())
679 d.addCallback(self._encrypted_done)
680 # this fires with the uri_extension_hash and other data
683 def locate_all_shareholders(self, encoder, started):
684 peer_selection_started = now = time.time()
685 self._storage_index_elapsed = now - started
686 storage_index = encoder.get_param("storage_index")
687 self._storage_index = storage_index
688 upload_id = storage.si_b2a(storage_index)[:5]
689 self.log("using storage index %s" % upload_id)
690 peer_selector = self.peer_selector_class(upload_id, self._log_number,
693 share_size = encoder.get_param("share_size")
694 block_size = encoder.get_param("block_size")
695 num_segments = encoder.get_param("num_segments")
696 k,desired,n = encoder.get_param("share_counts")
698 self._peer_selection_started = time.time()
699 d = peer_selector.get_shareholders(self._client, storage_index,
700 share_size, block_size,
701 num_segments, n, desired)
703 self._peer_selection_elapsed = time.time() - peer_selection_started
708 def set_shareholders(self, used_peers, encoder):
710 @param used_peers: a sequence of PeerTracker objects
712 self.log("_send_shares, used_peers is %s" % (used_peers,))
714 for peer in used_peers:
715 assert isinstance(peer, PeerTracker)
717 for peer in used_peers:
718 buckets.update(peer.buckets)
719 for shnum in peer.buckets:
720 self._sharemap[shnum] = peer
721 assert len(buckets) == sum([len(peer.buckets) for peer in used_peers])
722 encoder.set_shareholders(buckets)
724 def _encrypted_done(self, res):
728 for shnum in self._encoder.get_shares_placed():
729 peer_tracker = self._sharemap[shnum]
730 peerid = peer_tracker.peerid
731 peerid_s = idlib.shortnodeid_b2a(peerid)
732 r.sharemap[shnum] = "Placed on [%s]" % peerid_s
733 if peerid not in r.servermap:
734 r.servermap[peerid] = set()
735 r.servermap[peerid].add(shnum)
737 r.file_size = self._encoder.file_size
738 r.timings["total"] = now - self._started
739 r.timings["storage_index"] = self._storage_index_elapsed
740 r.timings["peer_selection"] = self._peer_selection_elapsed
741 r.timings.update(self._encoder.get_times())
742 r.uri_extension_data = self._encoder.get_uri_extension_data()
745 def _compute_uri(self, (uri_extension_hash,
746 needed_shares, total_shares, size),
748 u = uri.CHKFileURI(key=key,
749 uri_extension_hash=uri_extension_hash,
750 needed_shares=needed_shares,
751 total_shares=total_shares,
755 r.uri = u.to_string()
758 def get_upload_status(self):
759 return self._upload_status
761 def read_this_many_bytes(uploadable, size, prepend_data=[]):
763 return defer.succeed([])
764 d = uploadable.read(size)
766 assert isinstance(data, list)
767 bytes = sum([len(piece) for piece in data])
770 remaining = size - bytes
772 return read_this_many_bytes(uploadable, remaining,
774 return prepend_data + data
778 class LiteralUploader:
780 def __init__(self, client):
781 self._client = client
782 self._results = UploadResults()
783 self._status = s = UploadStatus()
784 s.set_storage_index(None)
786 s.set_progress(0, 1.0)
788 s.set_results(self._results)
790 def start(self, uploadable):
791 uploadable = IUploadable(uploadable)
792 d = uploadable.get_size()
795 self._status.set_size(size)
796 self._results.file_size = size
797 return read_this_many_bytes(uploadable, size)
798 d.addCallback(_got_size)
799 d.addCallback(lambda data: uri.LiteralFileURI("".join(data)))
800 d.addCallback(lambda u: u.to_string())
801 d.addCallback(self._build_results)
804 def _build_results(self, uri):
805 self._results.uri = uri
806 self._status.set_status("Done")
807 self._status.set_progress(1, 1.0)
808 self._status.set_progress(2, 1.0)
814 def get_upload_status(self):
817 class RemoteEncryptedUploadable(Referenceable):
818 implements(RIEncryptedUploadable)
820 def __init__(self, encrypted_uploadable, upload_status):
821 self._eu = IEncryptedUploadable(encrypted_uploadable)
824 self._status = IUploadStatus(upload_status)
825 # we are responsible for updating the status string while we run, and
826 # for setting the ciphertext-fetch progress.
830 if self._size is not None:
831 return defer.succeed(self._size)
832 d = self._eu.get_size()
836 d.addCallback(_got_size)
839 def remote_get_size(self):
840 return self.get_size()
841 def remote_get_all_encoding_parameters(self):
842 return self._eu.get_all_encoding_parameters()
844 def _read_encrypted(self, length, hash_only):
845 d = self._eu.read_encrypted(length, hash_only)
848 self._offset += length
850 size = sum([len(data) for data in strings])
856 def remote_read_encrypted(self, offset, length):
857 # we don't support seek backwards, but we allow skipping forwards
858 precondition(offset >= 0, offset)
859 precondition(length >= 0, length)
860 lp = log.msg("remote_read_encrypted(%d-%d)" % (offset, offset+length),
862 precondition(offset >= self._offset, offset, self._offset)
863 if offset > self._offset:
864 # read the data from disk anyways, to build up the hash tree
865 skip = offset - self._offset
866 log.msg("remote_read_encrypted skipping ahead from %d to %d, skip=%d" %
867 (self._offset, offset, skip), level=log.UNUSUAL, parent=lp)
868 d = self._read_encrypted(skip, hash_only=True)
870 d = defer.succeed(None)
872 def _at_correct_offset(res):
873 assert offset == self._offset, "%d != %d" % (offset, self._offset)
874 return self._read_encrypted(length, hash_only=False)
875 d.addCallback(_at_correct_offset)
878 size = sum([len(data) for data in strings])
879 self._bytes_sent += size
884 def remote_get_plaintext_hashtree_leaves(self, first, last, num_segments):
885 log.msg("remote_get_plaintext_hashtree_leaves: %d-%d of %d" %
886 (first, last-1, num_segments),
888 d = self._eu.get_plaintext_hashtree_leaves(first, last, num_segments)
891 def remote_get_plaintext_hash(self):
892 return self._eu.get_plaintext_hash()
893 def remote_close(self):
894 return self._eu.close()
897 class AssistedUploader:
899 def __init__(self, helper):
900 self._helper = helper
901 self._log_number = log.msg("AssistedUploader starting")
902 self._storage_index = None
903 self._upload_status = s = UploadStatus()
907 def log(self, *args, **kwargs):
908 if "parent" not in kwargs:
909 kwargs["parent"] = self._log_number
910 return log.msg(*args, **kwargs)
912 def start(self, uploadable):
913 self._started = time.time()
914 u = IUploadable(uploadable)
915 eu = EncryptAnUploadable(u, self._log_number)
916 eu.set_upload_status(self._upload_status)
917 self._encuploadable = eu
919 d.addCallback(self._got_size)
920 d.addCallback(lambda res: eu.get_all_encoding_parameters())
921 d.addCallback(self._got_all_encoding_parameters)
922 # when we get the encryption key, that will also compute the storage
923 # index, so this only takes one pass.
924 # TODO: I'm not sure it's cool to switch back and forth between
925 # the Uploadable and the IEncryptedUploadable that wraps it.
926 d.addCallback(lambda res: u.get_encryption_key())
927 d.addCallback(self._got_encryption_key)
928 d.addCallback(lambda res: eu.get_storage_index())
929 d.addCallback(self._got_storage_index)
930 d.addCallback(self._contact_helper)
931 d.addCallback(self._build_readcap)
933 self._upload_status.set_active(False)
938 def _got_size(self, size):
940 self._upload_status.set_size(size)
942 def _got_all_encoding_parameters(self, params):
943 k, happy, n, segment_size = params
944 # stash these for URI generation later
945 self._needed_shares = k
946 self._total_shares = n
947 self._segment_size = segment_size
949 def _got_encryption_key(self, key):
952 def _got_storage_index(self, storage_index):
953 self._storage_index = storage_index
956 def _contact_helper(self, res):
957 now = self._time_contacting_helper_start = time.time()
958 self._storage_index_elapsed = now - self._started
959 self.log(format="contacting helper for SI %(si)s..",
960 si=storage.si_b2a(self._storage_index))
961 self._upload_status.set_status("Contacting Helper")
962 d = self._helper.callRemote("upload_chk", self._storage_index)
963 d.addCallback(self._contacted_helper)
966 def _contacted_helper(self, (upload_results, upload_helper)):
968 elapsed = now - self._time_contacting_helper_start
969 self._elapsed_time_contacting_helper = elapsed
971 self.log("helper says we need to upload")
972 self._upload_status.set_status("Uploading Ciphertext")
973 # we need to upload the file
974 reu = RemoteEncryptedUploadable(self._encuploadable,
976 # let it pre-compute the size for progress purposes
978 d.addCallback(lambda ignored:
979 upload_helper.callRemote("upload", reu))
980 # this Deferred will fire with the upload results
982 self.log("helper says file is already uploaded")
983 self._upload_status.set_progress(1, 1.0)
984 self._upload_status.set_results(upload_results)
985 return upload_results
987 def _build_readcap(self, upload_results):
988 self.log("upload finished, building readcap")
989 self._upload_status.set_status("Building Readcap")
991 assert r.uri_extension_data["needed_shares"] == self._needed_shares
992 assert r.uri_extension_data["total_shares"] == self._total_shares
993 assert r.uri_extension_data["segment_size"] == self._segment_size
994 assert r.uri_extension_data["size"] == self._size
995 u = uri.CHKFileURI(key=self._key,
996 uri_extension_hash=r.uri_extension_hash,
997 needed_shares=self._needed_shares,
998 total_shares=self._total_shares,
1001 r.uri = u.to_string()
1003 r.file_size = self._size
1004 r.timings["storage_index"] = self._storage_index_elapsed
1005 r.timings["contacting_helper"] = self._elapsed_time_contacting_helper
1006 if "total" in r.timings:
1007 r.timings["helper_total"] = r.timings["total"]
1008 r.timings["total"] = now - self._started
1009 self._upload_status.set_status("Done")
1010 self._upload_status.set_results(r)
1013 def get_upload_status(self):
1014 return self._upload_status
1016 class BaseUploadable:
1017 default_max_segment_size = 1*MiB # overridden by max_segment_size
1018 default_encoding_param_k = 3 # overridden by encoding_parameters
1019 default_encoding_param_happy = 7
1020 default_encoding_param_n = 10
1022 max_segment_size = None
1023 encoding_param_k = None
1024 encoding_param_happy = None
1025 encoding_param_n = None
1027 _all_encoding_parameters = None
1030 def set_upload_status(self, upload_status):
1031 self._status = IUploadStatus(upload_status)
1033 def set_default_encoding_parameters(self, default_params):
1034 assert isinstance(default_params, dict)
1035 for k,v in default_params.items():
1036 precondition(isinstance(k, str), k, v)
1037 precondition(isinstance(v, int), k, v)
1038 if "k" in default_params:
1039 self.default_encoding_param_k = default_params["k"]
1040 if "happy" in default_params:
1041 self.default_encoding_param_happy = default_params["happy"]
1042 if "n" in default_params:
1043 self.default_encoding_param_n = default_params["n"]
1044 if "max_segment_size" in default_params:
1045 self.default_max_segment_size = default_params["max_segment_size"]
1047 def get_all_encoding_parameters(self):
1048 if self._all_encoding_parameters:
1049 return defer.succeed(self._all_encoding_parameters)
1051 max_segsize = self.max_segment_size or self.default_max_segment_size
1052 k = self.encoding_param_k or self.default_encoding_param_k
1053 happy = self.encoding_param_happy or self.default_encoding_param_happy
1054 n = self.encoding_param_n or self.default_encoding_param_n
1057 def _got_size(file_size):
1058 # for small files, shrink the segment size to avoid wasting space
1059 segsize = min(max_segsize, file_size)
1060 # this must be a multiple of 'required_shares'==k
1061 segsize = mathutil.next_multiple(segsize, k)
1062 encoding_parameters = (k, happy, n, segsize)
1063 self._all_encoding_parameters = encoding_parameters
1064 return encoding_parameters
1065 d.addCallback(_got_size)
1068 class FileHandle(BaseUploadable):
1069 implements(IUploadable)
1071 def __init__(self, filehandle, contenthashkey=True):
1072 self._filehandle = filehandle
1074 self._contenthashkey = contenthashkey
1077 def _get_encryption_key_content_hash(self):
1078 if self._key is not None:
1079 return defer.succeed(self._key)
1082 # that sets self._size as a side-effect
1083 d.addCallback(lambda size: self.get_all_encoding_parameters())
1085 k, happy, n, segsize = params
1086 f = self._filehandle
1087 enckey_hasher = content_hash_key_hasher(k, n, segsize)
1092 data = f.read(BLOCKSIZE)
1095 enckey_hasher.update(data)
1096 # TODO: setting progress in a non-yielding loop is kind of
1097 # pointless, but I'm anticipating (perhaps prematurely) the
1098 # day when we use a slowjob or twisted's CooperatorService to
1099 # make this yield time to other jobs.
1100 bytes_read += len(data)
1102 self._status.set_progress(0, float(bytes_read)/self._size)
1104 self._key = enckey_hasher.digest()
1106 self._status.set_progress(0, 1.0)
1107 assert len(self._key) == 16
1112 def _get_encryption_key_random(self):
1113 if self._key is None:
1114 self._key = os.urandom(16)
1115 return defer.succeed(self._key)
1117 def get_encryption_key(self):
1118 if self._contenthashkey:
1119 return self._get_encryption_key_content_hash()
1121 return self._get_encryption_key_random()
1124 if self._size is not None:
1125 return defer.succeed(self._size)
1126 self._filehandle.seek(0,2)
1127 size = self._filehandle.tell()
1129 self._filehandle.seek(0)
1130 return defer.succeed(size)
1132 def read(self, length):
1133 return defer.succeed([self._filehandle.read(length)])
1136 # the originator of the filehandle reserves the right to close it
1139 class FileName(FileHandle):
1140 def __init__(self, filename, contenthashkey=True):
1141 FileHandle.__init__(self, open(filename, "rb"), contenthashkey=contenthashkey)
1143 FileHandle.close(self)
1144 self._filehandle.close()
1146 class Data(FileHandle):
1147 def __init__(self, data, contenthashkey=True):
1148 FileHandle.__init__(self, StringIO(data), contenthashkey=contenthashkey)
1150 class Uploader(service.MultiService):
1151 """I am a service that allows file uploading. I am a service-child of the
1154 implements(IUploader)
1156 uploader_class = CHKUploader
1157 URI_LIT_SIZE_THRESHOLD = 55
1158 MAX_UPLOAD_STATUSES = 10
1160 def __init__(self, helper_furl=None):
1161 self._helper_furl = helper_furl
1163 self._all_uploads = weakref.WeakKeyDictionary()
1164 self._recent_upload_status = []
1165 service.MultiService.__init__(self)
1167 def startService(self):
1168 service.MultiService.startService(self)
1169 if self._helper_furl:
1170 self.parent.tub.connectTo(self._helper_furl,
1173 def _got_helper(self, helper):
1174 self._helper = helper
1175 helper.notifyOnDisconnect(self._lost_helper)
1176 def _lost_helper(self):
1179 def get_helper_info(self):
1180 # return a tuple of (helper_furl_or_None, connected_bool)
1181 return (self._helper_furl, bool(self._helper))
1183 def upload(self, uploadable):
1184 # this returns the URI
1188 uploadable = IUploadable(uploadable)
1189 d = uploadable.get_size()
1190 def _got_size(size):
1191 default_params = self.parent.get_encoding_parameters()
1192 precondition(isinstance(default_params, dict), default_params)
1193 precondition("max_segment_size" in default_params, default_params)
1194 uploadable.set_default_encoding_parameters(default_params)
1195 if size <= self.URI_LIT_SIZE_THRESHOLD:
1196 uploader = LiteralUploader(self.parent)
1198 uploader = AssistedUploader(self._helper)
1200 uploader = self.uploader_class(self.parent)
1201 self._all_uploads[uploader] = None
1202 self._recent_upload_status.append(uploader.get_upload_status())
1203 while len(self._recent_upload_status) > self.MAX_UPLOAD_STATUSES:
1204 self._recent_upload_status.pop(0)
1205 return uploader.start(uploadable)
1206 d.addCallback(_got_size)
1213 def list_all_uploads(self):
1214 return self._all_uploads.keys()
1215 def list_active_uploads(self):
1216 return [u.get_upload_status() for u in self._all_uploads.keys()
1217 if u.get_upload_status().get_active()]
1218 def list_recent_uploads(self):
1219 return self._recent_upload_status